text stringlengths 54 60.6k |
|---|
<commit_before>// arduino2/sketch.cpp
// servo subsystem
#include <Servo.h>
#include "../gbot.h"
Servo servo_x, servo_y;
int servo_x_direction = SERVO_CENTER;
int servo_y_direction = SERVO_CENTER;
int status = STATUS_OK;
void receive_data(int);
void send_data();
void servo_left();
void servo_right();
void servo_up();
void servo_down();
void servo_center();
void servo_move(Servo, int, int);
void setup()
{
servo_x.attach(SERVO_X_PIN);
servo_y.attach(SERVO_Y_PIN);
servo_x.write(SERVO_CENTER);
servo_y.write(SERVO_CENTER);
Wire.begin(ARDUINO2_ADDR);
Wire.onReceive(receive_data);
Wire.onRequest(send_data);
}
void loop()
{
delay(100);
}
void receive_data(int byteCount)
{
while (Wire.available())
{
switch (Wire.read())
{
case PAN_CENTER:
servo_center();
break;
case PAN_LEFT:
servo_left();
break;
case PAN_RIGHT:
servo_right();
break;
}
}
}
void send_data()
{
Wire.write(status);
}
void servo_left()
{
servo_move(servo_x, servo_x.read() + SERVO_STEP, SERVO_LEFT_MAX);
}
void servo_right()
{
servo_move(servo_x, servo_x.read() - SERVO_STEP, SERVO_RIGHT_MAX);
}
void servo_up()
{
servo_move(servo_y, servo_y.read() + SERVO_STEP, SERVO_UP_MAX);
}
void servo_down()
{
servo_move(servo_y, servo_y.read() - SERVO_STEP, SERVO_DOWN_MAX);
}
void servo_move(Servo servo, int newDirection, int max)
{
newDirection = newDirection > max ? max : newDirection;
servo.write(newDirection);
}
void servo_center()
{
servo_x_direction = SERVO_CENTER;
servo_y_direction = SERVO_CENTER;
servo_x.write(servo_x_direction);
servo_y.write(servo_y_direction);
}
<commit_msg>fixed sketch hopefully<commit_after>// arduino2/sketch.cpp
// servo subsystem
#include <Wire.h>
#include <Servo.h>
#include "../gbot.h"
Servo servo_x, servo_y;
int servo_x_direction = SERVO_CENTER;
int servo_y_direction = SERVO_CENTER;
int status = STATUS_OK;
void receive_data(int);
void send_data();
void servo_left();
void servo_right();
void servo_up();
void servo_down();
void servo_center();
void servo_move(Servo, int, int);
void setup()
{
servo_x.attach(SERVO_X_PIN);
servo_y.attach(SERVO_Y_PIN);
servo_x.write(SERVO_CENTER);
servo_y.write(SERVO_CENTER);
Wire.begin(ARDUINO2_ADDR);
Wire.onReceive(receive_data);
Wire.onRequest(send_data);
}
void loop()
{
delay(100);
}
void receive_data(int byteCount)
{
while (Wire.available())
{
switch (Wire.read())
{
case PAN_CENTER:
servo_center();
break;
case PAN_LEFT:
servo_left();
break;
case PAN_RIGHT:
servo_right();
break;
}
}
}
void send_data()
{
Wire.write(status);
}
void servo_left()
{
servo_move(servo_x, servo_x.read() + SERVO_STEP, SERVO_LEFT_MAX);
}
void servo_right()
{
servo_move(servo_x, servo_x.read() - SERVO_STEP, SERVO_RIGHT_MAX);
}
void servo_up()
{
servo_move(servo_y, servo_y.read() + SERVO_STEP, SERVO_UP_MAX);
}
void servo_down()
{
servo_move(servo_y, servo_y.read() - SERVO_STEP, SERVO_DOWN_MAX);
}
void servo_move(Servo servo, int newDirection, int max)
{
newDirection = newDirection > max ? max : newDirection;
servo.write(newDirection);
}
void servo_center()
{
servo_x_direction = SERVO_CENTER;
servo_y_direction = SERVO_CENTER;
servo_x.write(servo_x_direction);
servo_y.write(servo_y_direction);
}
<|endoftext|> |
<commit_before>/*
icqeditaccountwidget.cpp - ICQ Account Widget
Copyright (c) 2003 by Chris TenHarmsel <tenharmsel@staticmethod.net>
Kopete (c) 2003 by the Kopete developers <kopete-devel@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. *
* *
*************************************************************************
*/
#include "icqeditaccountwidget.h"
#include "ui_icqeditaccountui.h"
#include <qlayout.h>
#include <qcheckbox.h>
#include <qlineedit.h>
#include <qspinbox.h>
#include <qpushbutton.h>
#include <qvalidator.h>
#include <QLatin1String>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kurllabel.h>
#include <kdatewidget.h>
#include <ktoolinvocation.h>
#include <kpassworddialog.h>
#include <kmessagebox.h>
#include "kopetepassword.h"
#include "kopetepasswordwidget.h"
#include "icqprotocol.h"
#include "icqaccount.h"
#include "icqcontact.h"
#include "oscarprivacyengine.h"
#include "oscarsettings.h"
#include "icqchangepassworddialog.h"
ICQEditAccountWidget::ICQEditAccountWidget(ICQProtocol *protocol,
Kopete::Account *account, QWidget *parent)
: QWidget(parent), KopeteEditAccountWidget(account)
{
kDebug(14153) << "Called.";
mAccount=dynamic_cast<ICQAccount*>(account);
mProtocol=protocol;
m_visibleEngine = 0;
m_invisibleEngine = 0;
m_ignoreEngine = 0;
mAccountSettings = new Ui::ICQEditAccountUI();
mAccountSettings->setupUi( this );
mProtocol->fillComboFromTable( mAccountSettings->encodingCombo, mProtocol->encodings() );
//Setup the edtAccountId
QRegExp rx("[0-9]{9}");
QValidator* validator = new QRegExpValidator( rx, this );
mAccountSettings->edtAccountId->setValidator(validator);
// Read in the settings from the account if it exists
if(mAccount)
{
mAccountSettings->edtAccountId->setText(mAccount->accountId());
// TODO: Remove me after we can change Account IDs (Matt)
mAccountSettings->edtAccountId->setReadOnly(true);
mAccountSettings->mPasswordWidget->load(&mAccount->password());
mAccountSettings->chkAutoLogin->setChecked(mAccount->excludeConnect());
QString serverEntry = mAccount->configGroup()->readEntry("Server", "login.oscar.aol.com");
int portEntry = mAccount->configGroup()->readEntry("Port", 5190);
if ( serverEntry != "login.oscar.aol.com" || ( portEntry != 5190) )
mAccountSettings->optionOverrideServer->setChecked( true );
mAccountSettings->edtServerAddress->setText( serverEntry );
mAccountSettings->edtServerPort->setValue( portEntry );
bool configChecked = mAccount->configGroup()->readEntry( "RequireAuth", false );
mAccountSettings->chkRequireAuth->setChecked( configChecked );
configChecked = mAccount->configGroup()->readEntry( "HideIP", true );
mAccountSettings->chkHideIP->setChecked( configChecked );
configChecked = mAccount->configGroup()->readEntry( "WebAware", false );
mAccountSettings->chkWebAware->setChecked( configChecked );
int configValue = mAccount->configGroup()->readEntry( "DefaultEncoding", 4 );
mProtocol->setComboFromTable( mAccountSettings->encodingCombo,
mProtocol->encodings(),
configValue );
//set filetransfer stuff
configChecked = mAccount->configGroup()->readEntry( "FileProxy", false );
mAccountSettings->chkFileProxy->setChecked( configChecked );
configValue = mAccount->configGroup()->readEntry( "FirstPort", 5190 );
mAccountSettings->sbxFirstPort->setValue( configValue );
configValue = mAccount->configGroup()->readEntry( "LastPort", 5199 );
mAccountSettings->sbxLastPort->setValue( configValue );
configValue = mAccount->configGroup()->readEntry( "Timeout", 10 );
mAccountSettings->sbxTimeout->setValue( configValue );
if ( mAccount->engine()->isActive() )
{
m_visibleEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Visible );
m_visibleEngine->setAllContactsView( mAccountSettings->visibleAllContacts );
m_visibleEngine->setContactsView( mAccountSettings->visibleContacts );
QObject::connect( mAccountSettings->visibleAdd, SIGNAL( clicked() ), m_visibleEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->visibleRemove, SIGNAL( clicked() ), m_visibleEngine, SLOT( slotRemove() ) );
m_invisibleEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Invisible );
m_invisibleEngine->setAllContactsView( mAccountSettings->invisibleAllContacts );
m_invisibleEngine->setContactsView( mAccountSettings->invisibleContacts );
QObject::connect( mAccountSettings->invisibleAdd, SIGNAL( clicked() ), m_invisibleEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->invisibleRemove, SIGNAL( clicked() ), m_invisibleEngine, SLOT( slotRemove() ) );
m_ignoreEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Ignore );
m_ignoreEngine->setAllContactsView( mAccountSettings->ignoreAllContacts );
m_ignoreEngine->setContactsView( mAccountSettings->ignoreContacts );
QObject::connect( mAccountSettings->ignoreAdd, SIGNAL( clicked() ), m_ignoreEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->ignoreRemove, SIGNAL( clicked() ), m_ignoreEngine, SLOT( slotRemove() ) );
}
// Hide the registration UI when editing an existing account
mAccountSettings->registrationGroupBox->hide();
}
else
{
int encodingId=4; //see icqprotocol.cpp for mappings
if (KGlobal::locale()->language().startsWith("ru"))
encodingId=2251;
mProtocol->setComboFromTable( mAccountSettings->encodingCombo,
mProtocol->encodings(),
encodingId );
mAccountSettings->changePasswordGroupBox->hide();
}
if ( !mAccount || !mAccount->engine()->isActive() )
{
mAccountSettings->tabVisible->setEnabled( false );
mAccountSettings->tabInvisible->setEnabled( false );
mAccountSettings->tabIgnore->setEnabled( false );
mAccountSettings->buttonChangePassword->setEnabled( false );
}
QObject::connect(mAccountSettings->buttonRegister, SIGNAL(clicked()), this, SLOT(slotOpenRegister()));
QObject::connect(mAccountSettings->buttonChangePassword, SIGNAL(clicked()), this, SLOT(slotChangePassword()));
/* Set tab order to password custom widget correctly */
QWidget::setTabOrder( mAccountSettings->edtAccountId, mAccountSettings->mPasswordWidget->mRemembered );
QWidget::setTabOrder( mAccountSettings->mPasswordWidget->mRemembered, mAccountSettings->mPasswordWidget->mPassword );
QWidget::setTabOrder( mAccountSettings->mPasswordWidget->mPassword, mAccountSettings->chkAutoLogin );
}
ICQEditAccountWidget::~ICQEditAccountWidget()
{
if ( m_visibleEngine )
delete m_visibleEngine;
if ( m_invisibleEngine )
delete m_invisibleEngine;
if ( m_ignoreEngine )
delete m_ignoreEngine;
delete mAccountSettings;
}
Kopete::Account *ICQEditAccountWidget::apply()
{
kDebug(14153) << "Called.";
// If this is a new account, create it
if (!mAccount)
{
kDebug(14153) << "Creating a new account";
mAccount = new ICQAccount(mProtocol, mAccountSettings->edtAccountId->text());
if(!mAccount)
return NULL;
}
mAccountSettings->mPasswordWidget->save(&mAccount->password());
mAccount->setExcludeConnect(mAccountSettings->chkAutoLogin->isChecked());
Oscar::Settings* oscarSettings = mAccount->engine()->clientSettings();
bool configChecked = mAccountSettings->chkRequireAuth->isChecked();
mAccount->configGroup()->writeEntry( "RequireAuth", configChecked );
oscarSettings->setRequireAuth( configChecked );
configChecked = mAccountSettings->chkHideIP->isChecked();
mAccount->configGroup()->writeEntry( "HideIP", configChecked );
oscarSettings->setHideIP( configChecked );
configChecked = mAccountSettings->chkWebAware->isChecked();
mAccount->configGroup()->writeEntry( "WebAware", configChecked );
oscarSettings->setWebAware( configChecked );
int configValue = mProtocol->getCodeForCombo( mAccountSettings->encodingCombo,
mProtocol->encodings() );
mAccount->configGroup()->writeEntry( "DefaultEncoding", configValue );
if ( mAccountSettings->optionOverrideServer->isChecked() )
{
mAccount->setServerAddress(mAccountSettings->edtServerAddress->text().trimmed());
mAccount->setServerPort(mAccountSettings->edtServerPort->value());
}
else
{
mAccount->setServerAddress("login.oscar.aol.com");
mAccount->setServerPort(5190);
}
//set filetransfer stuff
configChecked = mAccountSettings->chkFileProxy->isChecked();
mAccount->configGroup()->writeEntry( "FileProxy", configChecked );
oscarSettings->setFileProxy( configChecked );
configValue = mAccountSettings->sbxFirstPort->value();
mAccount->configGroup()->writeEntry( "FirstPort", configValue );
oscarSettings->setFirstPort( configValue );
configValue = mAccountSettings->sbxLastPort->value();
mAccount->configGroup()->writeEntry( "LastPort", configValue );
oscarSettings->setLastPort( configValue );
configValue = mAccountSettings->sbxTimeout->value();
mAccount->configGroup()->writeEntry( "Timeout", configValue );
oscarSettings->setTimeout( configValue );
if ( mAccount->engine()->isActive() )
{
if ( m_visibleEngine )
m_visibleEngine->storeChanges();
if ( m_invisibleEngine )
m_invisibleEngine->storeChanges();
if ( m_ignoreEngine )
m_ignoreEngine->storeChanges();
//Update Oscar settings
static_cast<ICQMyselfContact*>( mAccount->myself() )->fetchShortInfo();
}
return mAccount;
}
bool ICQEditAccountWidget::validateData()
{
kDebug(14153) << "Called.";
bool bOk;
QString userId = mAccountSettings->edtAccountId->text();
qulonglong uid = userId.toULongLong( &bOk );
if( !bOk || uid == 0 || userId.isEmpty() )
{ KMessageBox::queuedMessageBox(this, KMessageBox::Sorry,
i18n("<qt>You must enter a valid ICQ No.</qt>"), i18n("ICQ"));
return false;
}
// No need to check port, min and max values are properly defined in .ui
if (mAccountSettings->edtServerAddress->text().isEmpty())
return false;
// Seems good to me
kDebug(14153) <<
"Account data validated successfully." << endl;
return true;
}
void ICQEditAccountWidget::slotOpenRegister()
{
KToolInvocation::invokeBrowser( QLatin1String("http://go.icq.com/register/") );
}
void ICQEditAccountWidget::slotChangePassword()
{
ICQChangePasswordDialog *passwordDlg = new ICQChangePasswordDialog( mAccount, this );
passwordDlg->exec();
delete passwordDlg;
}
#include "icqeditaccountwidget.moc"
// vim: set noet ts=4 sts=4 sw=4:
// kate: indent-mode csands; space-indent off; replace-tabs off;
<commit_msg>beautify fallback encoding autosetting for icq protocol SVN_SILENT<commit_after>/*
icqeditaccountwidget.cpp - ICQ Account Widget
Copyright (c) 2003 by Chris TenHarmsel <tenharmsel@staticmethod.net>
Kopete (c) 2003 by the Kopete developers <kopete-devel@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. *
* *
*************************************************************************
*/
#include "icqeditaccountwidget.h"
#include "ui_icqeditaccountui.h"
#include <QLayout>
#include <QCheckbox>
#include <QLineedit>
#include <QSpinBox>
#include <QPushButton>
#include <QValidator>
#include <QLatin1String>
#include <QLocale>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kurllabel.h>
#include <kdatewidget.h>
#include <ktoolinvocation.h>
#include <kpassworddialog.h>
#include <kmessagebox.h>
#include "kopetepassword.h"
#include "kopetepasswordwidget.h"
#include "icqprotocol.h"
#include "icqaccount.h"
#include "icqcontact.h"
#include "oscarprivacyengine.h"
#include "oscarsettings.h"
#include "icqchangepassworddialog.h"
ICQEditAccountWidget::ICQEditAccountWidget(ICQProtocol *protocol,
Kopete::Account *account, QWidget *parent)
: QWidget(parent), KopeteEditAccountWidget(account)
{
kDebug(14153) << "Called.";
mAccount=dynamic_cast<ICQAccount*>(account);
mProtocol=protocol;
m_visibleEngine = 0;
m_invisibleEngine = 0;
m_ignoreEngine = 0;
mAccountSettings = new Ui::ICQEditAccountUI();
mAccountSettings->setupUi( this );
mProtocol->fillComboFromTable( mAccountSettings->encodingCombo, mProtocol->encodings() );
//Setup the edtAccountId
QRegExp rx("[0-9]{9}");
QValidator* validator = new QRegExpValidator( rx, this );
mAccountSettings->edtAccountId->setValidator(validator);
// Read in the settings from the account if it exists
if(mAccount)
{
mAccountSettings->edtAccountId->setText(mAccount->accountId());
// TODO: Remove me after we can change Account IDs (Matt)
mAccountSettings->edtAccountId->setReadOnly(true);
mAccountSettings->mPasswordWidget->load(&mAccount->password());
mAccountSettings->chkAutoLogin->setChecked(mAccount->excludeConnect());
QString serverEntry = mAccount->configGroup()->readEntry("Server", "login.oscar.aol.com");
int portEntry = mAccount->configGroup()->readEntry("Port", 5190);
if ( serverEntry != "login.oscar.aol.com" || ( portEntry != 5190) )
mAccountSettings->optionOverrideServer->setChecked( true );
mAccountSettings->edtServerAddress->setText( serverEntry );
mAccountSettings->edtServerPort->setValue( portEntry );
bool configChecked = mAccount->configGroup()->readEntry( "RequireAuth", false );
mAccountSettings->chkRequireAuth->setChecked( configChecked );
configChecked = mAccount->configGroup()->readEntry( "HideIP", true );
mAccountSettings->chkHideIP->setChecked( configChecked );
configChecked = mAccount->configGroup()->readEntry( "WebAware", false );
mAccountSettings->chkWebAware->setChecked( configChecked );
int configValue = mAccount->configGroup()->readEntry( "DefaultEncoding", 4 );
mProtocol->setComboFromTable( mAccountSettings->encodingCombo,
mProtocol->encodings(),
configValue );
//set filetransfer stuff
configChecked = mAccount->configGroup()->readEntry( "FileProxy", false );
mAccountSettings->chkFileProxy->setChecked( configChecked );
configValue = mAccount->configGroup()->readEntry( "FirstPort", 5190 );
mAccountSettings->sbxFirstPort->setValue( configValue );
configValue = mAccount->configGroup()->readEntry( "LastPort", 5199 );
mAccountSettings->sbxLastPort->setValue( configValue );
configValue = mAccount->configGroup()->readEntry( "Timeout", 10 );
mAccountSettings->sbxTimeout->setValue( configValue );
if ( mAccount->engine()->isActive() )
{
m_visibleEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Visible );
m_visibleEngine->setAllContactsView( mAccountSettings->visibleAllContacts );
m_visibleEngine->setContactsView( mAccountSettings->visibleContacts );
QObject::connect( mAccountSettings->visibleAdd, SIGNAL( clicked() ), m_visibleEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->visibleRemove, SIGNAL( clicked() ), m_visibleEngine, SLOT( slotRemove() ) );
m_invisibleEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Invisible );
m_invisibleEngine->setAllContactsView( mAccountSettings->invisibleAllContacts );
m_invisibleEngine->setContactsView( mAccountSettings->invisibleContacts );
QObject::connect( mAccountSettings->invisibleAdd, SIGNAL( clicked() ), m_invisibleEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->invisibleRemove, SIGNAL( clicked() ), m_invisibleEngine, SLOT( slotRemove() ) );
m_ignoreEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Ignore );
m_ignoreEngine->setAllContactsView( mAccountSettings->ignoreAllContacts );
m_ignoreEngine->setContactsView( mAccountSettings->ignoreContacts );
QObject::connect( mAccountSettings->ignoreAdd, SIGNAL( clicked() ), m_ignoreEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->ignoreRemove, SIGNAL( clicked() ), m_ignoreEngine, SLOT( slotRemove() ) );
}
// Hide the registration UI when editing an existing account
mAccountSettings->registrationGroupBox->hide();
}
else
{
int encodingId=4; //see icqprotocol.cpp for mappings
switch (QLocale::system().language())
{
case QLocale::Russian:
case QLocale::Ukrainian:
case QLocale::Byelorussian:
case QLocale::Bulgarian:
encodingId=2251;
break;
case QLocale::Hebrew:
encodingId=2255;
break;
case QLocale::Turkish:
encodingId=2254;
break;
case QLocale::Greek:
encodingId=2253;
break;
case QLocale::Arabic:
encodingId=2256;
break;
case QLocale::German:
case QLocale::Italian:
case QLocale::Spanish:
case QLocale::Portuguese:
case QLocale::French:
case QLocale::Dutch:
case QLocale::Danish:
case QLocale::Swedish:
case QLocale::Norwegian:
case QLocale::Icelandic:
encodingId=2252;
break;
default:
encodingId=4;
}
mProtocol->setComboFromTable( mAccountSettings->encodingCombo,
mProtocol->encodings(),
encodingId );
mAccountSettings->changePasswordGroupBox->hide();
}
if ( !mAccount || !mAccount->engine()->isActive() )
{
mAccountSettings->tabVisible->setEnabled( false );
mAccountSettings->tabInvisible->setEnabled( false );
mAccountSettings->tabIgnore->setEnabled( false );
mAccountSettings->buttonChangePassword->setEnabled( false );
}
QObject::connect(mAccountSettings->buttonRegister, SIGNAL(clicked()), this, SLOT(slotOpenRegister()));
QObject::connect(mAccountSettings->buttonChangePassword, SIGNAL(clicked()), this, SLOT(slotChangePassword()));
/* Set tab order to password custom widget correctly */
QWidget::setTabOrder( mAccountSettings->edtAccountId, mAccountSettings->mPasswordWidget->mRemembered );
QWidget::setTabOrder( mAccountSettings->mPasswordWidget->mRemembered, mAccountSettings->mPasswordWidget->mPassword );
QWidget::setTabOrder( mAccountSettings->mPasswordWidget->mPassword, mAccountSettings->chkAutoLogin );
}
ICQEditAccountWidget::~ICQEditAccountWidget()
{
if ( m_visibleEngine )
delete m_visibleEngine;
if ( m_invisibleEngine )
delete m_invisibleEngine;
if ( m_ignoreEngine )
delete m_ignoreEngine;
delete mAccountSettings;
}
Kopete::Account *ICQEditAccountWidget::apply()
{
kDebug(14153) << "Called.";
// If this is a new account, create it
if (!mAccount)
{
kDebug(14153) << "Creating a new account";
mAccount = new ICQAccount(mProtocol, mAccountSettings->edtAccountId->text());
if(!mAccount)
return NULL;
}
mAccountSettings->mPasswordWidget->save(&mAccount->password());
mAccount->setExcludeConnect(mAccountSettings->chkAutoLogin->isChecked());
Oscar::Settings* oscarSettings = mAccount->engine()->clientSettings();
bool configChecked = mAccountSettings->chkRequireAuth->isChecked();
mAccount->configGroup()->writeEntry( "RequireAuth", configChecked );
oscarSettings->setRequireAuth( configChecked );
configChecked = mAccountSettings->chkHideIP->isChecked();
mAccount->configGroup()->writeEntry( "HideIP", configChecked );
oscarSettings->setHideIP( configChecked );
configChecked = mAccountSettings->chkWebAware->isChecked();
mAccount->configGroup()->writeEntry( "WebAware", configChecked );
oscarSettings->setWebAware( configChecked );
int configValue = mProtocol->getCodeForCombo( mAccountSettings->encodingCombo,
mProtocol->encodings() );
mAccount->configGroup()->writeEntry( "DefaultEncoding", configValue );
if ( mAccountSettings->optionOverrideServer->isChecked() )
{
mAccount->setServerAddress(mAccountSettings->edtServerAddress->text().trimmed());
mAccount->setServerPort(mAccountSettings->edtServerPort->value());
}
else
{
mAccount->setServerAddress("login.oscar.aol.com");
mAccount->setServerPort(5190);
}
//set filetransfer stuff
configChecked = mAccountSettings->chkFileProxy->isChecked();
mAccount->configGroup()->writeEntry( "FileProxy", configChecked );
oscarSettings->setFileProxy( configChecked );
configValue = mAccountSettings->sbxFirstPort->value();
mAccount->configGroup()->writeEntry( "FirstPort", configValue );
oscarSettings->setFirstPort( configValue );
configValue = mAccountSettings->sbxLastPort->value();
mAccount->configGroup()->writeEntry( "LastPort", configValue );
oscarSettings->setLastPort( configValue );
configValue = mAccountSettings->sbxTimeout->value();
mAccount->configGroup()->writeEntry( "Timeout", configValue );
oscarSettings->setTimeout( configValue );
if ( mAccount->engine()->isActive() )
{
if ( m_visibleEngine )
m_visibleEngine->storeChanges();
if ( m_invisibleEngine )
m_invisibleEngine->storeChanges();
if ( m_ignoreEngine )
m_ignoreEngine->storeChanges();
//Update Oscar settings
static_cast<ICQMyselfContact*>( mAccount->myself() )->fetchShortInfo();
}
return mAccount;
}
bool ICQEditAccountWidget::validateData()
{
kDebug(14153) << "Called.";
bool bOk;
QString userId = mAccountSettings->edtAccountId->text();
qulonglong uid = userId.toULongLong( &bOk );
if( !bOk || uid == 0 || userId.isEmpty() )
{ KMessageBox::queuedMessageBox(this, KMessageBox::Sorry,
i18n("<qt>You must enter a valid ICQ No.</qt>"), i18n("ICQ"));
return false;
}
// No need to check port, min and max values are properly defined in .ui
if (mAccountSettings->edtServerAddress->text().isEmpty())
return false;
// Seems good to me
kDebug(14153) <<
"Account data validated successfully." << endl;
return true;
}
void ICQEditAccountWidget::slotOpenRegister()
{
KToolInvocation::invokeBrowser( QLatin1String("http://go.icq.com/register/") );
}
void ICQEditAccountWidget::slotChangePassword()
{
ICQChangePasswordDialog *passwordDlg = new ICQChangePasswordDialog( mAccount, this );
passwordDlg->exec();
delete passwordDlg;
}
#include "icqeditaccountwidget.moc"
// vim: set noet ts=4 sts=4 sw=4:
// kate: indent-mode csands; space-indent off; replace-tabs off;
<|endoftext|> |
<commit_before>#include"variables.hpp"
#include"executors.hpp"
#include"atoms.hpp"
#include"processes.hpp"
#include"bytecodes.hpp"
#include<iostream>
#include<boost/shared_ptr.hpp>
#include<map>
static boost::shared_ptr<Atom> QUOTEATOM;
static std::map<Atom*,_bytecode_label> bytetb;
template<class T>
static inline T* expect_type(Generic* g, char const* s1 = "executor-error", char const* s2 = "Unspecified error"){
T* tmp = dynamic_cast<T*>(g);
if(tmp == NULL) throw ArcError(s1, s2);
return tmp;
}
static _bytecode_label bytecodelookup(Atom* a){
std::map<Atom*, _bytecode_label>::iterator i = bytetb.find(a);
if(i == bytetb.end()){
return i->second;
} else {
throw ArcError("compile",
"Unknown bytecode form");
}
}
ProcessStatus execute(Process& proc, size_t reductions, bool init=0){
if(init) goto initialize;
DISPATCH_EXECUTORS {
EXECUTOR(arc_executor):
{ DISPATCH_BYTECODES{//provides the Closure* clos
BYTECODE(car):
bytecode_car(proc);
NEXT_BYTECODE;
BYTECODE(cdr):
bytecode_cdr(proc);
NEXT_BYTECODE;
BYTECODE(cons):
bytecode_cons(proc);
NEXT_BYTECODE;
}
} NEXT_EXECUTOR;
/*
(fn (k#|1|# f#|2|#)
(f k (fn (_ r) (k r))))
*/
EXECUTOR(ccc):
{ Closure* c = new(proc)
Closure(THE_EXECUTOR(ccc_helper), 1);
(*c)[0] = proc.stack[1/*k*/];
proc.stack[0] = proc.stack[2/*f*/];
proc.stack[2] = c;
} NEXT_EXECUTOR;
EXECUTOR(ccc_helper):
{ Closure* c = expect_type<Closure>(proc.stack[0]);
proc.stack[0] = (*c)[0/*k*/];
proc.stack[1] = proc.stack[2/*r*/];
proc.stack.pop();
} NEXT_EXECUTOR;
/*(fn (k l)
(compile_helper k (%empty-bytecode-sequence) l))
*/
EXECUTOR(compile):
{ Closure* c = new(proc)
Closure(THE_EXECUTOR(compile_helper), 0);
ArcBytecodeSequence* bseq = new(proc)
ArcBytecodeSequence();
proc.stack[0] = c;
/*just do type checking*/
Cons* cp = expect_type<Cons>(proc.stack[1],
"compile",
"Expected bytecode list");
proc.stack.push(proc.stack[2]);
proc.stack[2] = bseq;
} NEXT_EXECUTOR;
/* (fn (self k b l)
(if (no l)
(k b)
(let (c . l) l
(if (~acons c)
(do
(%bytecode-sequence-append b (%bytecode (%lookup c)))
(self k b l))
(let (c param . params) c
(if
(isa param 'int)
(if params
(self (%closure compile_intseq_bytecode self k b l c param)
(%new-bytecode-sequence) params)
(do
(%bytecode-sequence-append b (%int-bytecode (%lookup c) param))
(self k b l)))
(and (acons param) (caris 'quote))
(do
(%bytecode-sequence-append b (%atom-bytecode (%lookup c) (cadr param)))
(self k b l))
(self (%closure compile_seq_bytecode self k b l c)
(%new-bytecode-sequence) (cons param params))))))))
*/
EXECUTOR(compile_helper):
{ ArcBytecodeSequence* b =
dynamic_cast<ArcBytecodeSequence*>(
proc.stack[2]);
compile_helper_loop:
/*check l (local 3)*/
if(proc.stack[3]->isnil()){
/*(k b)*/
proc.stack.pop();
proc.restack(2);
} else {
/*split l into c and l*/
Cons* l = expect_type<Cons>(proc.stack[3],
"compile",
"Expected bytecode list in "
"compile_helper");
/*c == (local 4)*/
proc.stack.push(l->a);
proc.stack[3] = l->d;
/*determine if c is cons*/
Cons* c = dynamic_cast<Cons*>(proc.stack[4]);
if(c == NULL){/*(~acons c)*/
/*Get the atom*/
Sym* c = expect_type<Sym>(
proc.stack[4],
"compile",
"Expected bytecode symbol");
/*(%bytecode-sequence-append ...)*/
b->append(new Bytecode(
bytetb[c->atom()]));
/*Just pop off c*/
proc.stack.pop();
if(--reductions) goto compile_helper_loop; else return running;
} else {
/*destructure form*/
proc.stack[4] = c->a;
Cons* params = expect_type<Cons>(c->d,
"compile",
"Expected proper list for "
"bytecode with parameter");
/*param = local 5*/
proc.stack.push(params->a);
/*params = local 6*/
proc.stack.push(params->d);
Integer* param =
dynamic_cast<Integer*>(
params->a);
if(param != NULL){/*(isa param 'int)*/
/*check if params is null*/
if(proc.stack[6]->istrue()){
/*IntSeq*/
Closure* clos = new(proc) Closure(THE_EXECUTOR(compile_intseq_bytecode), 6);
for(int i = 0; i < 6; ++i){
(*clos)[i] = proc.stack[i];
}
/*call new closure*/
proc.stack[3] = proc.stack[0];
proc.stack[4] = clos; // have to save this first!
b = proc.stack[5] = new(proc) ArcBytecodeSequence();
proc.restack(4);
if(--reductions) goto compile_helper_loop; else return running;
} else {
/*Int*/
/*Get the atom*/
Sym* c = expect_type<Sym>(
proc.stack[4],
"compile",
"Expected bytecode symbol "
"in int-type bytecode form");
/*(%bytecode-sequence-append ...)*/
b->append(new IntBytecode(bytetb[c->atom()], param->integer()));
/*pop off c, param, and params*/
proc.stack.pop(3);
if(--reductions) goto compile_helper_loop; else return running;
}
} else {
Cons* param = dynamic_cast<Cons*>(params->a);
if(param != NULL){/*(acons param)*/
Sym* carparam = expect_type<Sym>(param->a,
"compile",
"Expected bytecode symbol or quote in parameter to bytecode");
if(carparam.atom() == QUOTEATOM){
param = expect_type<Cons>(param->d,
"compile",
"Expected proper quote-form in symbol-parameter bytecode");
carparam = expect_type<Sym>(param->a,
"compile",
"Expected symbol in symbol-parameter bytecode");
b->append(new AtomBytecode(bytetb[c->atom()], carparam->a));
/*pop off c, param, and params*/
proc.stack.pop(3);
if(--reductions)goto compile_helper_loop; else return running;
} else goto compile_helper_non_quote_param;
}
/*this is effectively our elsemost branch*/
compile_helper_non_quote_param:
/*NOTE! Potential problem. the params variable
here is not the params in the source arc code in
the comments. Instead it is the (cons param params)
from which they were destructured. The problem
here lies in the fact that it isn't in the Arc
stack, which is significant if we have to GC.
From my analysis so far however it seems that
we don't alloc anything along the code path to
this part, so we won't trigger GC.
*/
proc.stack[5] = params;
proc.stack.pop();
Closure* clos = new(proc) Closure(THE_EXECUTOR(compile_seq_bytecode), 5);
for(int i = 0; i < 5; ++i){
(*clos)[i] = proc.stack[i];
}
proc.stack[1] = clos; // Have to save this first!
b = proc.stack[2] = new(proc) ArcBytecodeSequence();
proc.stack[3] = proc.stack.pop();
if(--reductions) goto compile_helper_loop; else return running;
}
}
}
} NEXT_EXECUTOR;
/*
(fn (clos subseq)
(with (b (%closure-ref clos 2)
c (%closure-ref clos 4)
param (%closure-ref clos 5))
(%bytecode-sequence-append b
(%int-seq-bytecode (%lookup c) (%integer param) (%seq subseq)))
; compile_helper k b l
((%closure-ref clos 0) (%closure-ref clos 1) (%closure-ref clos 2) (%closure-ref clos 3))))
*/
EXECUTOR(compile_intseq_bytecode):
{ Closure* clos =
dynamic_cast<Closure*>(proc.stack[0]);
ArcBytecodeSequence* subseq =
dynamic_cast<ArcBytecodeSequence*>(proc.stack[1]);
/*(let ...)*/
ArcBytecodeSequence* b =
dynamic_cast<ArcBytecodeSequence*>(
(*clos)[2]);
/*the type of c wasn't checked in the first place*/
Sym* c = expect_type<Sym>((*clos)[4],
"compile",
"Expected bytecode symbol "
"in int-seq bytecode form");
Integer* param =
dynamic_cast<Integer*>(
(*clos)[5]);
b->append(new IntSeqBytecode(bytetb[c->atom()], param->integer(), subseq->seq));
/*push the closure elements*/
for(int i = 0; i < 4; ++i){
proc.stack.push((*clos)[i]);
}
proc.stack.restack(4);
} NEXT_EXECUTOR;
/*
(fn (clos subseq)
(with (b (%closure-ref clos 2)
c (%closure-ref clos 4))
(%bytecode-sequence-append b
(%seq-bytecode (%lookup c) (%seq subseq)))
((%closure-ref clos 0) (%closure-ref clos 1) (%closure-ref clos 2) (%closure-ref clos 3))))
*/
EXECUTOR():
{ Closure* clos =
dynamic_cast<Closure*>(proc.stack[0]);
ArcBytecodeSequence* subseq =
dynamic_cast<ArcBytecodeSequence*>(proc.stack[1]);
/*(let ...)*/
ArcBytecodeSequence* b =
dynamic_cast<ArcBytecodeSequence*>(
(*clos)[2]);
/*the type of c wasn't checked in the first place*/
Sym* c = expect_type<Sym>((*clos)[4],
"compile",
"Expected bytecode symbol "
"in seq bytecode form");
b->append(new SeqBytecode(bytetb[c->atom()], subseq->seq));
/*push the closure elements*/
for(int i = 0; i < 4; ++i){
proc.stack.push((*clos)[i]);
}
proc.stack.restack(4);
} NEXT_EXECUTOR;
}
return dead;
initialize:
QUOTEATOM = globals->lookup("quote");
bytetb[&*globals->lookup("car")] = THE_BYTECODE_LABEL(car);
bytetb[&*globals->lookup("cdr")] = THE_BYTECODE_LABEL(cdr);
bytetb[&*globals->lookup("cons")] = THE_BYTECODE_LABEL(cons);
return running;
}
<commit_msg>Made proper use of bytecodelookup() helper function<commit_after>#include"variables.hpp"
#include"executors.hpp"
#include"atoms.hpp"
#include"processes.hpp"
#include"bytecodes.hpp"
#include<iostream>
#include<boost/shared_ptr.hpp>
#include<map>
static boost::shared_ptr<Atom> QUOTEATOM;
static std::map<Atom*,_bytecode_label> bytetb;
template<class T>
static inline T* expect_type(Generic* g, char const* s1 = "executor-error", char const* s2 = "Unspecified error"){
T* tmp = dynamic_cast<T*>(g);
if(tmp == NULL) throw ArcError(s1, s2);
return tmp;
}
static _bytecode_label bytecodelookup(boost::shared_ptr<Atom> a){
std::map<Atom*, _bytecode_label>::iterator i = bytetb.find(&*a);
if(i == bytetb.end()){
return i->second;
} else {
throw ArcError("compile",
"Unknown bytecode form");
}
}
ProcessStatus execute(Process& proc, size_t reductions, bool init=0){
if(init) goto initialize;
DISPATCH_EXECUTORS {
EXECUTOR(arc_executor):
{ DISPATCH_BYTECODES{//provides the Closure* clos
BYTECODE(car):
bytecode_car(proc);
NEXT_BYTECODE;
BYTECODE(cdr):
bytecode_cdr(proc);
NEXT_BYTECODE;
BYTECODE(cons):
bytecode_cons(proc);
NEXT_BYTECODE;
}
} NEXT_EXECUTOR;
/*
(fn (k#|1|# f#|2|#)
(f k (fn (_ r) (k r))))
*/
EXECUTOR(ccc):
{ Closure* c = new(proc)
Closure(THE_EXECUTOR(ccc_helper), 1);
(*c)[0] = proc.stack[1/*k*/];
proc.stack[0] = proc.stack[2/*f*/];
proc.stack[2] = c;
} NEXT_EXECUTOR;
EXECUTOR(ccc_helper):
{ Closure* c = expect_type<Closure>(proc.stack[0]);
proc.stack[0] = (*c)[0/*k*/];
proc.stack[1] = proc.stack[2/*r*/];
proc.stack.pop();
} NEXT_EXECUTOR;
/*(fn (k l)
(compile_helper k (%empty-bytecode-sequence) l))
*/
EXECUTOR(compile):
{ Closure* c = new(proc)
Closure(THE_EXECUTOR(compile_helper), 0);
ArcBytecodeSequence* bseq = new(proc)
ArcBytecodeSequence();
proc.stack[0] = c;
/*just do type checking*/
Cons* cp = expect_type<Cons>(proc.stack[1],
"compile",
"Expected bytecode list");
proc.stack.push(proc.stack[2]);
proc.stack[2] = bseq;
} NEXT_EXECUTOR;
/* (fn (self k b l)
(if (no l)
(k b)
(let (c . l) l
(if (~acons c)
(do
(%bytecode-sequence-append b (%bytecode (%lookup c)))
(self k b l))
(let (c param . params) c
(if
(isa param 'int)
(if params
(self (%closure compile_intseq_bytecode self k b l c param)
(%new-bytecode-sequence) params)
(do
(%bytecode-sequence-append b (%int-bytecode (%lookup c) param))
(self k b l)))
(and (acons param) (caris 'quote))
(do
(%bytecode-sequence-append b (%atom-bytecode (%lookup c) (cadr param)))
(self k b l))
(self (%closure compile_seq_bytecode self k b l c)
(%new-bytecode-sequence) (cons param params))))))))
*/
EXECUTOR(compile_helper):
{ ArcBytecodeSequence* b =
dynamic_cast<ArcBytecodeSequence*>(
proc.stack[2]);
compile_helper_loop:
/*check l (local 3)*/
if(proc.stack[3]->isnil()){
/*(k b)*/
proc.stack.pop();
proc.stack.restack(2);
} else {
/*split l into c and l*/
Cons* l = expect_type<Cons>(proc.stack[3],
"compile",
"Expected bytecode list in "
"compile_helper");
/*c == (local 4)*/
proc.stack.push(l->a);
proc.stack[3] = l->d;
/*determine if c is cons*/
Cons* c = dynamic_cast<Cons*>(proc.stack[4]);
if(c == NULL){/*(~acons c)*/
/*Get the atom*/
Sym* c = expect_type<Sym>(
proc.stack[4],
"compile",
"Expected bytecode symbol");
/*(%bytecode-sequence-append ...)*/
b->append(new Bytecode(
bytecodelookup(c->a)));
/*Just pop off c*/
proc.stack.pop();
if(--reductions) goto compile_helper_loop; else return running;
} else {
/*destructure form*/
proc.stack[4] = c->a;
Cons* params = expect_type<Cons>(c->d,
"compile",
"Expected proper list for "
"bytecode with parameter");
/*param = local 5*/
proc.stack.push(params->a);
/*params = local 6*/
proc.stack.push(params->d);
Integer* param =
dynamic_cast<Integer*>(
params->a);
if(param != NULL){/*(isa param 'int)*/
/*check if params is null*/
if(proc.stack[6]->istrue()){
/*IntSeq*/
Closure* clos = new(proc) Closure(THE_EXECUTOR(compile_intseq_bytecode), 6);
for(int i = 0; i < 6; ++i){
(*clos)[i] = proc.stack[i];
}
/*call new closure*/
proc.stack[3] = proc.stack[0];
proc.stack[4] = clos; // have to save this first!
b = proc.stack[5] = new(proc) ArcBytecodeSequence();
proc.restack(4);
if(--reductions) goto compile_helper_loop; else return running;
} else {
/*Int*/
/*Get the atom*/
Sym* c = expect_type<Sym>(
proc.stack[4],
"compile",
"Expected bytecode symbol "
"in int-type bytecode form");
/*(%bytecode-sequence-append ...)*/
b->append(new IntBytecode(bytecodelookup(c->a), param->integer()));
/*pop off c, param, and params*/
proc.stack.pop(3);
if(--reductions) goto compile_helper_loop; else return running;
}
} else {
Cons* param = dynamic_cast<Cons*>(params->a);
if(param != NULL){/*(acons param)*/
Sym* carparam = expect_type<Sym>(param->a,
"compile",
"Expected bytecode symbol or quote in parameter to bytecode");
if(carparam.atom() == QUOTEATOM){
param = expect_type<Cons>(param->d,
"compile",
"Expected proper quote-form in symbol-parameter bytecode");
carparam = expect_type<Sym>(param->a,
"compile",
"Expected symbol in symbol-parameter bytecode");
b->append(new AtomBytecode(bytecodelookup(c->a), carparam->a));
/*pop off c, param, and params*/
proc.stack.pop(3);
if(--reductions)goto compile_helper_loop; else return running;
} else goto compile_helper_non_quote_param;
}
/*this is effectively our elsemost branch*/
compile_helper_non_quote_param:
/*NOTE! Potential problem. the params variable
here is not the params in the source arc code in
the comments. Instead it is the (cons param params)
from which they were destructured. The problem
here lies in the fact that it isn't in the Arc
stack, which is significant if we have to GC.
From my analysis so far however it seems that
we don't alloc anything along the code path to
this part, so we won't trigger GC.
*/
proc.stack[5] = params;
proc.stack.pop();
Closure* clos = new(proc) Closure(THE_EXECUTOR(compile_seq_bytecode), 5);
for(int i = 0; i < 5; ++i){
(*clos)[i] = proc.stack[i];
}
proc.stack[1] = clos; // Have to save this first!
b = proc.stack[2] = new(proc) ArcBytecodeSequence();
proc.stack[3] = proc.stack.pop();
if(--reductions) goto compile_helper_loop; else return running;
}
}
}
} NEXT_EXECUTOR;
/*
(fn (clos subseq)
(with (b (%closure-ref clos 2)
c (%closure-ref clos 4)
param (%closure-ref clos 5))
(%bytecode-sequence-append b
(%int-seq-bytecode (%lookup c) (%integer param) (%seq subseq)))
; compile_helper k b l
((%closure-ref clos 0) (%closure-ref clos 1) (%closure-ref clos 2) (%closure-ref clos 3))))
*/
EXECUTOR(compile_intseq_bytecode):
{ Closure* clos =
dynamic_cast<Closure*>(proc.stack[0]);
ArcBytecodeSequence* subseq =
dynamic_cast<ArcBytecodeSequence*>(proc.stack[1]);
/*(let ...)*/
ArcBytecodeSequence* b =
dynamic_cast<ArcBytecodeSequence*>(
(*clos)[2]);
/*the type of c wasn't checked in the first place*/
Sym* c = expect_type<Sym>((*clos)[4],
"compile",
"Expected bytecode symbol "
"in int-seq bytecode form");
Integer* param =
dynamic_cast<Integer*>(
(*clos)[5]);
b->append(new IntSeqBytecode(bytecodelookup(c->a), param->integer(), subseq->seq));
/*push the closure elements*/
for(int i = 0; i < 4; ++i){
proc.stack.push((*clos)[i]);
}
proc.stack.restack(4);
} NEXT_EXECUTOR;
/*
(fn (clos subseq)
(with (b (%closure-ref clos 2)
c (%closure-ref clos 4))
(%bytecode-sequence-append b
(%seq-bytecode (%lookup c) (%seq subseq)))
((%closure-ref clos 0) (%closure-ref clos 1) (%closure-ref clos 2) (%closure-ref clos 3))))
*/
EXECUTOR():
{ Closure* clos =
dynamic_cast<Closure*>(proc.stack[0]);
ArcBytecodeSequence* subseq =
dynamic_cast<ArcBytecodeSequence*>(proc.stack[1]);
/*(let ...)*/
ArcBytecodeSequence* b =
dynamic_cast<ArcBytecodeSequence*>(
(*clos)[2]);
/*the type of c wasn't checked in the first place*/
Sym* c = expect_type<Sym>((*clos)[4],
"compile",
"Expected bytecode symbol "
"in seq bytecode form");
b->append(new SeqBytecode(bytecodelookup(c->a), subseq->seq));
/*push the closure elements*/
for(int i = 0; i < 4; ++i){
proc.stack.push((*clos)[i]);
}
proc.stack.restack(4);
} NEXT_EXECUTOR;
}
return dead;
initialize:
QUOTEATOM = globals->lookup("quote");
bytetb[&*globals->lookup("car")] = THE_BYTECODE_LABEL(car);
bytetb[&*globals->lookup("cdr")] = THE_BYTECODE_LABEL(cdr);
bytetb[&*globals->lookup("cons")] = THE_BYTECODE_LABEL(cons);
return running;
}
<|endoftext|> |
<commit_before>/**
* \file
* \brief CallOnceOperationsTestCase class implementation
*
* \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2015-12-02
*/
#include "CallOnceOperationsTestCase.hpp"
#include "SequenceAsserter.hpp"
#include "waitForNextTick.hpp"
#include "distortos/callOnce.hpp"
#include "distortos/StaticThread.hpp"
#include "distortos/statistics.hpp"
#include "distortos/ThisThread.hpp"
namespace distortos
{
namespace test
{
#if DISTORTOS_CALLONCE_SUPPORTED == 1 || DOXYGEN == 1
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// sleepFor() duration used in function() passed to callOnce()
constexpr auto sleepForDuration = TickClock::duration{10};
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {512};
/// number of test threads
constexpr size_t totalThreads {10};
/// expected number of context switches in waitForNextTick(): main -> idle -> main
constexpr decltype(statistics::getContextSwitchCount()) waitForNextTickContextSwitchCount {2};
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// pair of sequence points
using SequencePoints = std::pair<unsigned int, unsigned int>;
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Test function passed to callOnce().
*
* This function marks first sequence point, executes ThisThread::sleepFor() and marks second sequence point.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
*/
void function(SequenceAsserter& sequenceAsserter)
{
sequenceAsserter.sequencePoint(1);
ThisThread::sleepFor(sleepForDuration);
sequenceAsserter.sequencePoint(totalThreads + 1);
}
/**
* \brief Test thread function.
*
* This function marks first sequence point, passes function() to callOnce() and marks second sequence point.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] sequencePoints is a pair of sequence points for this instance
* \param [in] onceFlag is a reference to OnceFlag shared object
*/
void thread(SequenceAsserter& sequenceAsserter, const SequencePoints sequencePoints, OnceFlag& onceFlag)
{
sequenceAsserter.sequencePoint(sequencePoints.first);
callOnce(onceFlag, function, sequenceAsserter);
sequenceAsserter.sequencePoint(sequencePoints.second);
}
/**
* \brief Builder of TestThread objects.
*
* \param [in] priority is the thread's priority
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] sequencePoints is a pair of sequence points for this instance
* \param [in] onceFlag is a reference to OnceFlag shared object
*
* \return constructed TestThread object
*/
auto makeTestThread(const uint8_t priority, SequenceAsserter& sequenceAsserter, const SequencePoints sequencePoints,
OnceFlag& onceFlag) ->
decltype(makeStaticThread<testThreadStackSize>(priority, thread, std::ref(sequenceAsserter), sequencePoints,
std::ref(onceFlag)))
{
return makeStaticThread<testThreadStackSize>(priority, thread, std::ref(sequenceAsserter), sequencePoints,
std::ref(onceFlag));
}
} // namespace
#endif // DISTORTOS_CALLONCE_SUPPORTED == 1 || DOXYGEN == 1
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool CallOnceOperationsTestCase::run_() const
{
#if DISTORTOS_CALLONCE_SUPPORTED == 1 || DOXYGEN == 1
const auto contextSwitchCount = statistics::getContextSwitchCount();
SequenceAsserter sequenceAsserter;
OnceFlag onceFlag;
using TestThread = decltype(makeTestThread(uint8_t{}, sequenceAsserter, SequencePoints{}, onceFlag));
std::array<TestThread, totalThreads> threads
{{
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{0, 12}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{2, 13}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{3, 14}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{4, 15}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{5, 16}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{6, 17}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{7, 18}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{8, 19}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{9, 20}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{10, 21}, onceFlag),
}};
waitForNextTick();
const auto start = TickClock::now();
for (auto& thread : threads)
thread.start();
ThisThread::setPriority(testCasePriority_ - 2);
bool invalidState {};
for (size_t i = 1; i < threads.size(); ++i)
if (threads[i].getState() != ThreadState::BlockedOnOnceFlag)
invalidState = true;
for (auto& thread : threads)
thread.join();
if (invalidState != false)
return false;
if (TickClock::now() - start != sleepForDuration + decltype(sleepForDuration){1})
return false;
if (sequenceAsserter.assertSequence(totalThreads * 2 + 2) == false)
return false;
constexpr auto totalContextSwitches = 2 * totalThreads + 3 + waitForNextTickContextSwitchCount;
if (statistics::getContextSwitchCount() - contextSwitchCount != totalContextSwitches)
return false;
#endif // DISTORTOS_CALLONCE_SUPPORTED == 1 || DOXYGEN == 1
return true;
}
} // namespace test
} // namespace distortos
<commit_msg>test: convert CallOnceOperationsTestCase to use dynamic threads<commit_after>/**
* \file
* \brief CallOnceOperationsTestCase class implementation
*
* \author Copyright (C) 2015-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2016-01-04
*/
#include "CallOnceOperationsTestCase.hpp"
#include "SequenceAsserter.hpp"
#include "waitForNextTick.hpp"
#include "distortos/callOnce.hpp"
#include "distortos/DynamicThread.hpp"
#include "distortos/statistics.hpp"
#include "distortos/ThisThread.hpp"
namespace distortos
{
namespace test
{
#if DISTORTOS_CALLONCE_SUPPORTED == 1 || DOXYGEN == 1
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// sleepFor() duration used in function() passed to callOnce()
constexpr auto sleepForDuration = TickClock::duration{10};
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {512};
/// number of test threads
constexpr size_t totalThreads {10};
/// expected number of context switches in waitForNextTick(): main -> idle -> main
constexpr decltype(statistics::getContextSwitchCount()) waitForNextTickContextSwitchCount {2};
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// pair of sequence points
using SequencePoints = std::pair<unsigned int, unsigned int>;
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Test function passed to callOnce().
*
* This function marks first sequence point, executes ThisThread::sleepFor() and marks second sequence point.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
*/
void function(SequenceAsserter& sequenceAsserter)
{
sequenceAsserter.sequencePoint(1);
ThisThread::sleepFor(sleepForDuration);
sequenceAsserter.sequencePoint(totalThreads + 1);
}
/**
* \brief Test thread function
*
* This function marks first sequence point, passes function() to callOnce() and marks second sequence point.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] sequencePoints is a pair of sequence points for this instance
* \param [in] onceFlag is a reference to OnceFlag shared object
*/
void thread(SequenceAsserter& sequenceAsserter, const SequencePoints sequencePoints, OnceFlag& onceFlag)
{
sequenceAsserter.sequencePoint(sequencePoints.first);
callOnce(onceFlag, function, sequenceAsserter);
sequenceAsserter.sequencePoint(sequencePoints.second);
}
/**
* \brief Builder of test threads
*
* \param [in] priority is the thread's priority
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] sequencePoints is a pair of sequence points for this instance
* \param [in] onceFlag is a reference to OnceFlag shared object
*
* \return constructed DynamicThread object
*/
DynamicThread makeTestThread(const uint8_t priority, SequenceAsserter& sequenceAsserter,
const SequencePoints sequencePoints, OnceFlag& onceFlag)
{
return makeDynamicThread({testThreadStackSize, priority}, thread, std::ref(sequenceAsserter), sequencePoints,
std::ref(onceFlag));
}
} // namespace
#endif // DISTORTOS_CALLONCE_SUPPORTED == 1 || DOXYGEN == 1
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool CallOnceOperationsTestCase::run_() const
{
#if DISTORTOS_CALLONCE_SUPPORTED == 1 || DOXYGEN == 1
const auto contextSwitchCount = statistics::getContextSwitchCount();
SequenceAsserter sequenceAsserter;
OnceFlag onceFlag;
std::array<DynamicThread, totalThreads> threads
{{
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{0, 12}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{2, 13}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{3, 14}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{4, 15}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{5, 16}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{6, 17}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{7, 18}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{8, 19}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{9, 20}, onceFlag),
makeTestThread(testCasePriority_ - 1, sequenceAsserter, SequencePoints{10, 21}, onceFlag),
}};
waitForNextTick();
const auto start = TickClock::now();
for (auto& thread : threads)
thread.start();
ThisThread::setPriority(testCasePriority_ - 2);
bool invalidState {};
for (size_t i = 1; i < threads.size(); ++i)
if (threads[i].getState() != ThreadState::BlockedOnOnceFlag)
invalidState = true;
for (auto& thread : threads)
thread.join();
if (invalidState != false)
return false;
if (TickClock::now() - start != sleepForDuration + decltype(sleepForDuration){1})
return false;
if (sequenceAsserter.assertSequence(totalThreads * 2 + 2) == false)
return false;
constexpr auto totalContextSwitches = 2 * totalThreads + 3 + waitForNextTickContextSwitchCount;
if (statistics::getContextSwitchCount() - contextSwitchCount != totalContextSwitches)
return false;
#endif // DISTORTOS_CALLONCE_SUPPORTED == 1 || DOXYGEN == 1
return true;
}
} // namespace test
} // namespace distortos
<|endoftext|> |
<commit_before>/**
* \file
* \brief ThreadPriorityChangeTestCase class implementation
*
* \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2015-05-16
*/
#include "ThreadPriorityChangeTestCase.hpp"
#include "SequenceAsserter.hpp"
#include "distortos/StaticThread.hpp"
#include "distortos/ThisThread.hpp"
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {192};
/// number of test threads
constexpr size_t totalThreads {10};
/*---------------------------------------------------------------------------------------------------------------------+
| local functions' declarations
+---------------------------------------------------------------------------------------------------------------------*/
void thread(SequenceAsserter& sequenceAsserter, unsigned int sequencePoint);
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// type of test thread
using TestThread = decltype(makeStaticThread<testThreadStackSize>({}, thread,
std::ref(std::declval<SequenceAsserter&>()), std::declval<unsigned int>()));
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Test thread.
*
* Just marks the sequence point in SequenceAsserter.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] sequencePoint is the sequence point of this instance
*/
void thread(SequenceAsserter& sequenceAsserter, const unsigned int sequencePoint)
{
sequenceAsserter.sequencePoint(sequencePoint);
}
/**
* \brief Builder of TestThread objects.
*
* \param [in] priority is the thread's priority
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] sequencePoint is the sequence point of this instance
*
* \return constructed TestThread object
*/
TestThread makeTestThread(const uint8_t priority, SequenceAsserter& sequenceAsserter, const unsigned int sequencePoint)
{
return makeStaticThread<testThreadStackSize>(priority, thread, std::ref(sequenceAsserter),
static_cast<unsigned int>(sequencePoint));
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool ThreadPriorityChangeTestCase::run_() const
{
// difference required for this whole test to work
static_assert(testCasePriority_ / 2 > 3, "Invalid test case priority");
const auto thisThreadPriority = ThisThread::getPriority();
const decltype(thisThreadPriority) testThreadPriority = thisThreadPriority / 2;
SequenceAsserter sequenceAsserter;
std::array<TestThread, totalThreads> threads
{{
makeTestThread(testThreadPriority, sequenceAsserter, 4), // change to same priority
makeTestThread(testThreadPriority, sequenceAsserter, 0), // rise
makeTestThread(testThreadPriority, sequenceAsserter, 7), // lower
makeTestThread(testThreadPriority, sequenceAsserter, 8), // lower with "always behind" mode
makeTestThread(testThreadPriority, sequenceAsserter, 1), // rise
makeTestThread(testThreadPriority, sequenceAsserter, 5), // change to same priority
makeTestThread(testThreadPriority, sequenceAsserter, 2), // rise
makeTestThread(testThreadPriority, sequenceAsserter, 6), // lower
makeTestThread(testThreadPriority, sequenceAsserter, 9), // lower with "always behind" mode
makeTestThread(testThreadPriority, sequenceAsserter, 3), // rise
}};
for (auto& thread : threads)
thread.start();
threads[0].setPriority(threads[0].getPriority());
threads[1].setPriority(threads[1].getPriority() + 2);
threads[2].setPriority(threads[2].getPriority() - 2);
threads[3].setPriority(threads[3].getPriority() - 2, true);
threads[4].setPriority(threads[4].getPriority() + 2);
threads[5].setPriority(threads[5].getPriority(), true); // useless "always behind" mode
threads[6].setPriority(threads[6].getPriority() + 2, true); // useless "always behind" mode
threads[7].setPriority(threads[7].getPriority() - 2, false); // explicit "always before" mode
threads[8].setPriority(threads[8].getPriority() - 2, true);
threads[9].setPriority(threads[9].getPriority() + 2, true); // useless "always behind" mode
const auto result1 = sequenceAsserter.assertSequence(0); // no thread finished
ThisThread::setPriority(threads[1].getPriority() - 1);
const auto result2 = sequenceAsserter.assertSequence(4); // high priority threads finished
ThisThread::setPriority(threads[0].getPriority() - 1);
const auto result3 = sequenceAsserter.assertSequence(6); // middle priority threads finished
ThisThread::setPriority(threads[2].getPriority() - 1);
for (auto& thread : threads)
thread.join();
ThisThread::setPriority(thisThreadPriority);
if (result1 == false || result2 == false || result3 == false ||
sequenceAsserter.assertSequence(totalThreads) == false)
return false;
return true;
}
} // namespace test
} // namespace distortos
<commit_msg>test: convert ThreadPriorityChangeTestCase to use dynamic threads<commit_after>/**
* \file
* \brief ThreadPriorityChangeTestCase class implementation
*
* \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*
* \date 2016-01-04
*/
#include "ThreadPriorityChangeTestCase.hpp"
#include "SequenceAsserter.hpp"
#include "distortos/DynamicThread.hpp"
#include "distortos/ThisThread.hpp"
#include <malloc.h>
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {192};
/// number of test threads
constexpr size_t totalThreads {10};
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Test thread
*
* Just marks the sequence point in SequenceAsserter.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] sequencePoint is the sequence point of this instance
*/
void thread(SequenceAsserter& sequenceAsserter, const unsigned int sequencePoint)
{
sequenceAsserter.sequencePoint(sequencePoint);
}
/**
* \brief Builder of test threads
*
* \param [in] priority is the thread's priority
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] sequencePoint is the sequence point of this instance
*
* \return constructed DynamicThread object
*/
DynamicThread makeTestThread(const uint8_t priority, SequenceAsserter& sequenceAsserter,
const unsigned int sequencePoint)
{
return makeDynamicThread({testThreadStackSize, priority}, thread, std::ref(sequenceAsserter), sequencePoint);
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool ThreadPriorityChangeTestCase::run_() const
{
{
// difference required for this whole test to work
static_assert(testCasePriority_ / 2 > 3, "Invalid test case priority");
const auto thisThreadPriority = ThisThread::getPriority();
const decltype(thisThreadPriority) testThreadPriority = thisThreadPriority / 2;
SequenceAsserter sequenceAsserter;
std::array<DynamicThread, totalThreads> threads
{{
makeTestThread(testThreadPriority, sequenceAsserter, 4), // change to same priority
makeTestThread(testThreadPriority, sequenceAsserter, 0), // rise
makeTestThread(testThreadPriority, sequenceAsserter, 7), // lower
makeTestThread(testThreadPriority, sequenceAsserter, 8), // lower with "always behind" mode
makeTestThread(testThreadPriority, sequenceAsserter, 1), // rise
makeTestThread(testThreadPriority, sequenceAsserter, 5), // change to same priority
makeTestThread(testThreadPriority, sequenceAsserter, 2), // rise
makeTestThread(testThreadPriority, sequenceAsserter, 6), // lower
makeTestThread(testThreadPriority, sequenceAsserter, 9), // lower with "always behind" mode
makeTestThread(testThreadPriority, sequenceAsserter, 3), // rise
}};
for (auto& thread : threads)
thread.start();
threads[0].setPriority(threads[0].getPriority());
threads[1].setPriority(threads[1].getPriority() + 2);
threads[2].setPriority(threads[2].getPriority() - 2);
threads[3].setPriority(threads[3].getPriority() - 2, true);
threads[4].setPriority(threads[4].getPriority() + 2);
threads[5].setPriority(threads[5].getPriority(), true); // useless "always behind" mode
threads[6].setPriority(threads[6].getPriority() + 2, true); // useless "always behind" mode
threads[7].setPriority(threads[7].getPriority() - 2, false); // explicit "always before" mode
threads[8].setPriority(threads[8].getPriority() - 2, true);
threads[9].setPriority(threads[9].getPriority() + 2, true); // useless "always behind" mode
const auto result1 = sequenceAsserter.assertSequence(0); // no thread finished
ThisThread::setPriority(threads[1].getPriority() - 1);
const auto result2 = sequenceAsserter.assertSequence(4); // high priority threads finished
ThisThread::setPriority(threads[0].getPriority() - 1);
const auto result3 = sequenceAsserter.assertSequence(6); // middle priority threads finished
ThisThread::setPriority(threads[2].getPriority() - 1);
for (auto& thread : threads)
thread.join();
ThisThread::setPriority(thisThreadPriority);
if (result1 == false || result2 == false || result3 == false ||
sequenceAsserter.assertSequence(totalThreads) == false)
return false;
}
if (mallinfo().uordblks != 0) // all dynamic memory must be deallocated after each test phase
return false;
return true;
}
} // namespace test
} // namespace distortos
<|endoftext|> |
<commit_before>
#include "value.h"
#include "boxed.h"
#include "gobject.h"
#include "debug.cc"
using namespace v8;
namespace GNodeJS {
Handle<Value> GIArgumentToV8(Isolate *isolate, GITypeInfo *type_info, GIArgument *arg) {
GITypeTag type_tag = g_type_info_get_tag (type_info);
switch (type_tag) {
case GI_TYPE_TAG_VOID:
return Undefined (isolate);
case GI_TYPE_TAG_BOOLEAN:
if (arg->v_boolean)
return True (isolate);
else
return False (isolate);
case GI_TYPE_TAG_INT32:
return Integer::New (isolate, arg->v_int);
case GI_TYPE_TAG_UINT32:
return Integer::NewFromUnsigned (isolate, arg->v_uint);
case GI_TYPE_TAG_INT16:
return Integer::New (isolate, arg->v_int16);
case GI_TYPE_TAG_UINT16:
return Integer::NewFromUnsigned (isolate, arg->v_uint16);
case GI_TYPE_TAG_INT8:
return Integer::New (isolate, arg->v_int8);
case GI_TYPE_TAG_UINT8:
return Integer::NewFromUnsigned (isolate, arg->v_uint8);
case GI_TYPE_TAG_FLOAT:
return Number::New (isolate, arg->v_float);
case GI_TYPE_TAG_DOUBLE:
return Number::New (isolate, arg->v_double);
/* For 64-bit integer types, use a float. When JS and V8 adopt
* bigger sized integer types, start using those instead. */
case GI_TYPE_TAG_INT64:
return Number::New (isolate, arg->v_int64);
case GI_TYPE_TAG_UINT64:
return Number::New (isolate, arg->v_uint64);
case GI_TYPE_TAG_UNICHAR:
{
char data[7] = { 0 };
g_unichar_to_utf8 (arg->v_uint32, data);
return String::NewFromUtf8 (isolate, data);
}
case GI_TYPE_TAG_UTF8:
if (arg->v_pointer)
return String::NewFromUtf8 (isolate, (char *) arg->v_pointer);
else
return Null (isolate);
case GI_TYPE_TAG_INTERFACE:
{
GIBaseInfo *interface_info = g_type_info_get_interface (type_info);
GIInfoType interface_type = g_base_info_get_type (interface_info);
switch (interface_type) {
case GI_INFO_TYPE_OBJECT:
return WrapperFromGObject (isolate, (GObject *) arg->v_pointer);
case GI_INFO_TYPE_BOXED:
case GI_INFO_TYPE_STRUCT:
return WrapperFromBoxed (isolate, interface_info, arg->v_pointer);
case GI_INFO_TYPE_FLAGS:
case GI_INFO_TYPE_ENUM:
return Integer::New (isolate, arg->v_int);
default:
g_assert_not_reached ();
}
}
break;
default:
g_assert_not_reached ();
}
}
static GArray * V8ToGArray(Isolate *isolate, GITypeInfo *type_info, Handle<Value> value) {
if (!value->IsArray ()) {
isolate->ThrowException (Exception::TypeError (String::NewFromUtf8 (isolate, "Not an array.")));
return NULL;
}
Local<Array> array = Local<Array>::Cast (value->ToObject ());
GITypeInfo *elem_info = g_type_info_get_param_type (type_info, 0);
int length = array->Length ();
GArray *garray = g_array_sized_new (TRUE, FALSE, sizeof (GIArgument), length);
for (int i = 0; i < length; i++) {
Local<Value> value = array->Get (i);
GIArgument arg;
V8ToGIArgument (isolate, elem_info, &arg, value, false);
g_array_append_val (garray, arg);
}
g_base_info_unref ((GIBaseInfo *) elem_info);
return garray;
}
void V8ToGIArgument(Isolate *isolate, GIBaseInfo *base_info, GIArgument *arg, Handle<Value> value) {
GIInfoType type = g_base_info_get_type (base_info);
switch (type) {
case GI_INFO_TYPE_OBJECT:
arg->v_pointer = GObjectFromWrapper (value);
break;
case GI_INFO_TYPE_BOXED:
case GI_INFO_TYPE_STRUCT:
arg->v_pointer = BoxedFromWrapper (value);
break;
case GI_INFO_TYPE_FLAGS:
case GI_INFO_TYPE_ENUM:
arg->v_int = value->Int32Value ();
break;
default:
print_info_type (base_info, type);
g_assert_not_reached ();
}
}
void V8ToGIArgument(Isolate *isolate, GITypeInfo *type_info, GIArgument *arg, Handle<Value> value, bool may_be_null) {
GITypeTag type_tag = g_type_info_get_tag (type_info);
if (value->IsNull ()) {
arg->v_pointer = NULL;
if (!may_be_null)
isolate->ThrowException (Exception::TypeError (String::NewFromUtf8 (isolate, "Argument may not be null.")));
return;
}
if (value->IsUndefined ()) {
isolate->ThrowException (Exception::TypeError (String::NewFromUtf8 (isolate, "Argument may not be undefined.")));
return;
}
switch (type_tag) {
case GI_TYPE_TAG_VOID:
arg->v_pointer = NULL;
break;
case GI_TYPE_TAG_BOOLEAN:
arg->v_boolean = value->BooleanValue ();
break;
case GI_TYPE_TAG_INT32:
arg->v_int = value->Int32Value ();
break;
case GI_TYPE_TAG_UINT32:
arg->v_uint = value->Uint32Value ();
break;
case GI_TYPE_TAG_INT64:
arg->v_int64 = value->NumberValue ();
break;
case GI_TYPE_TAG_UINT64:
arg->v_uint64 = value->NumberValue ();
break;
case GI_TYPE_TAG_FLOAT:
arg->v_float = value->NumberValue ();
break;
case GI_TYPE_TAG_DOUBLE:
arg->v_double = value->NumberValue ();
break;
case GI_TYPE_TAG_FILENAME:
{
String::Utf8Value str (value);
const char *utf8_data = *str;
arg->v_pointer = g_filename_from_utf8 (utf8_data, -1, NULL, NULL, NULL);
}
break;
case GI_TYPE_TAG_UTF8:
{
String::Utf8Value str (value);
const char *data = *str;
arg->v_pointer = g_strdup (data);
}
break;
case GI_TYPE_TAG_INTERFACE:
{
GIBaseInfo *interface_info = g_type_info_get_interface (type_info);
V8ToGIArgument (isolate, interface_info, arg, value);
g_base_info_unref (interface_info);
}
break;
case GI_TYPE_TAG_ARRAY:
{
GIArrayType array_type = g_type_info_get_array_type (type_info);
GArray *garray = V8ToGArray (isolate, type_info, value);
switch (array_type) {
case GI_ARRAY_TYPE_C:
arg->v_pointer = g_array_free (garray, FALSE);
break;
case GI_ARRAY_TYPE_ARRAY:
arg->v_pointer = garray;
break;
default:
g_assert_not_reached ();
}
}
break;
default:
g_assert_not_reached ();
}
}
void FreeGIArgument(GITypeInfo *type_info, GIArgument *arg) {
GITypeTag type_tag = g_type_info_get_tag (type_info);
switch (type_tag) {
case GI_TYPE_TAG_FILENAME:
case GI_TYPE_TAG_UTF8:
g_free (arg->v_pointer);
break;
case GI_TYPE_TAG_ARRAY:
{
GIArrayType array_type = g_type_info_get_array_type (type_info);
switch (array_type) {
case GI_ARRAY_TYPE_C:
g_free (arg->v_pointer);
break;
case GI_ARRAY_TYPE_ARRAY:
g_array_free ((GArray *) arg->v_pointer, TRUE);
break;
default:
g_assert_not_reached ();
}
}
break;
default:
break;
}
}
void V8ToGValue(GValue *gvalue, Handle<Value> value) {
if (G_VALUE_HOLDS_BOOLEAN (gvalue)) {
g_value_set_boolean (gvalue, value->BooleanValue ());
} else if (G_VALUE_HOLDS_INT (gvalue)) {
g_value_set_int (gvalue, value->Int32Value ());
} else if (G_VALUE_HOLDS_UINT (gvalue)) {
g_value_set_uint (gvalue, value->Uint32Value ());
} else if (G_VALUE_HOLDS_FLOAT (gvalue)) {
g_value_set_float (gvalue, value->NumberValue ());
} else if (G_VALUE_HOLDS_DOUBLE (gvalue)) {
g_value_set_double (gvalue, value->NumberValue ());
} else if (G_VALUE_HOLDS_STRING (gvalue)) {
String::Utf8Value str (value);
const char *data = *str;
g_value_set_string (gvalue, data);
} else if (G_VALUE_HOLDS_ENUM (gvalue)) {
g_value_set_enum (gvalue, value->Int32Value ());
} else if (G_VALUE_HOLDS_OBJECT (gvalue)) {
g_value_set_object (gvalue, GObjectFromWrapper (value));
} else {
g_assert_not_reached ();
}
}
Handle<Value> GValueToV8(Isolate *isolate, const GValue *gvalue) {
if (G_VALUE_HOLDS_BOOLEAN (gvalue)) {
if (g_value_get_boolean (gvalue))
return True (isolate);
else
return False (isolate);
} else if (G_VALUE_HOLDS_INT (gvalue)) {
return Integer::New (isolate, g_value_get_int (gvalue));
} else if (G_VALUE_HOLDS_UINT (gvalue)) {
return Integer::NewFromUnsigned (isolate, g_value_get_uint (gvalue));
} else if (G_VALUE_HOLDS_FLOAT (gvalue)) {
return Number::New (isolate, g_value_get_float (gvalue));
} else if (G_VALUE_HOLDS_DOUBLE (gvalue)) {
return Number::New (isolate, g_value_get_double (gvalue));
} else if (G_VALUE_HOLDS_STRING (gvalue)) {
return String::NewFromUtf8 (isolate, g_value_get_string (gvalue));
} else if (G_VALUE_HOLDS_ENUM (gvalue)) {
return Integer::New (isolate, g_value_get_enum (gvalue));
} else if (G_VALUE_HOLDS_OBJECT (gvalue)) {
return WrapperFromGObject (isolate, G_OBJECT (g_value_get_object (gvalue)));
} else {
g_assert_not_reached ();
}
}
};
<commit_msg>interface as gobject experiment<commit_after>
#include "value.h"
#include "boxed.h"
#include "gobject.h"
#include "debug.cc"
using namespace v8;
namespace GNodeJS {
Handle<Value> GIArgumentToV8(Isolate *isolate, GITypeInfo *type_info, GIArgument *arg) {
GITypeTag type_tag = g_type_info_get_tag (type_info);
switch (type_tag) {
case GI_TYPE_TAG_VOID:
return Undefined (isolate);
case GI_TYPE_TAG_BOOLEAN:
if (arg->v_boolean)
return True (isolate);
else
return False (isolate);
case GI_TYPE_TAG_INT32:
return Integer::New (isolate, arg->v_int);
case GI_TYPE_TAG_UINT32:
return Integer::NewFromUnsigned (isolate, arg->v_uint);
case GI_TYPE_TAG_INT16:
return Integer::New (isolate, arg->v_int16);
case GI_TYPE_TAG_UINT16:
return Integer::NewFromUnsigned (isolate, arg->v_uint16);
case GI_TYPE_TAG_INT8:
return Integer::New (isolate, arg->v_int8);
case GI_TYPE_TAG_UINT8:
return Integer::NewFromUnsigned (isolate, arg->v_uint8);
case GI_TYPE_TAG_FLOAT:
return Number::New (isolate, arg->v_float);
case GI_TYPE_TAG_DOUBLE:
return Number::New (isolate, arg->v_double);
/* For 64-bit integer types, use a float. When JS and V8 adopt
* bigger sized integer types, start using those instead. */
case GI_TYPE_TAG_INT64:
return Number::New (isolate, arg->v_int64);
case GI_TYPE_TAG_UINT64:
return Number::New (isolate, arg->v_uint64);
case GI_TYPE_TAG_UNICHAR:
{
char data[7] = { 0 };
g_unichar_to_utf8 (arg->v_uint32, data);
return String::NewFromUtf8 (isolate, data);
}
case GI_TYPE_TAG_UTF8:
if (arg->v_pointer)
return String::NewFromUtf8 (isolate, (char *) arg->v_pointer);
else
return Null (isolate);
case GI_TYPE_TAG_INTERFACE:
{
GIBaseInfo *interface_info = g_type_info_get_interface (type_info);
GIInfoType interface_type = g_base_info_get_type (interface_info);
switch (interface_type) {
case GI_INFO_TYPE_OBJECT:
return WrapperFromGObject (isolate, (GObject *) arg->v_pointer);
case GI_INFO_TYPE_BOXED:
case GI_INFO_TYPE_STRUCT:
return WrapperFromBoxed (isolate, interface_info, arg->v_pointer);
case GI_INFO_TYPE_FLAGS:
case GI_INFO_TYPE_ENUM:
return Integer::New (isolate, arg->v_int);
default:
g_assert_not_reached ();
}
}
break;
default:
g_assert_not_reached ();
}
}
static GArray * V8ToGArray(Isolate *isolate, GITypeInfo *type_info, Handle<Value> value) {
if (!value->IsArray ()) {
isolate->ThrowException (Exception::TypeError (String::NewFromUtf8 (isolate, "Not an array.")));
return NULL;
}
Local<Array> array = Local<Array>::Cast (value->ToObject ());
GITypeInfo *elem_info = g_type_info_get_param_type (type_info, 0);
int length = array->Length ();
GArray *garray = g_array_sized_new (TRUE, FALSE, sizeof (GIArgument), length);
for (int i = 0; i < length; i++) {
Local<Value> value = array->Get (i);
GIArgument arg;
V8ToGIArgument (isolate, elem_info, &arg, value, false);
g_array_append_val (garray, arg);
}
g_base_info_unref ((GIBaseInfo *) elem_info);
return garray;
}
void V8ToGIArgument(Isolate *isolate, GIBaseInfo *base_info, GIArgument *arg, Handle<Value> value) {
GIInfoType type = g_base_info_get_type (base_info);
switch (type) {
case GI_INFO_TYPE_INTERFACE:
case GI_INFO_TYPE_OBJECT:
arg->v_pointer = GObjectFromWrapper (value);
break;
case GI_INFO_TYPE_BOXED:
case GI_INFO_TYPE_STRUCT:
arg->v_pointer = BoxedFromWrapper (value);
break;
case GI_INFO_TYPE_FLAGS:
case GI_INFO_TYPE_ENUM:
arg->v_int = value->Int32Value ();
break;
default:
print_info_type (base_info, type);
g_assert_not_reached ();
}
}
void V8ToGIArgument(Isolate *isolate, GITypeInfo *type_info, GIArgument *arg, Handle<Value> value, bool may_be_null) {
GITypeTag type_tag = g_type_info_get_tag (type_info);
if (value->IsNull ()) {
arg->v_pointer = NULL;
if (!may_be_null)
isolate->ThrowException (Exception::TypeError (String::NewFromUtf8 (isolate, "Argument may not be null.")));
return;
}
if (value->IsUndefined ()) {
isolate->ThrowException (Exception::TypeError (String::NewFromUtf8 (isolate, "Argument may not be undefined.")));
return;
}
switch (type_tag) {
case GI_TYPE_TAG_VOID:
arg->v_pointer = NULL;
break;
case GI_TYPE_TAG_BOOLEAN:
arg->v_boolean = value->BooleanValue ();
break;
case GI_TYPE_TAG_INT32:
arg->v_int = value->Int32Value ();
break;
case GI_TYPE_TAG_UINT32:
arg->v_uint = value->Uint32Value ();
break;
case GI_TYPE_TAG_INT64:
arg->v_int64 = value->NumberValue ();
break;
case GI_TYPE_TAG_UINT64:
arg->v_uint64 = value->NumberValue ();
break;
case GI_TYPE_TAG_FLOAT:
arg->v_float = value->NumberValue ();
break;
case GI_TYPE_TAG_DOUBLE:
arg->v_double = value->NumberValue ();
break;
case GI_TYPE_TAG_FILENAME:
{
String::Utf8Value str (value);
const char *utf8_data = *str;
arg->v_pointer = g_filename_from_utf8 (utf8_data, -1, NULL, NULL, NULL);
}
break;
case GI_TYPE_TAG_UTF8:
{
String::Utf8Value str (value);
const char *data = *str;
arg->v_pointer = g_strdup (data);
}
break;
case GI_TYPE_TAG_INTERFACE:
{
GIBaseInfo *interface_info = g_type_info_get_interface (type_info);
V8ToGIArgument (isolate, interface_info, arg, value);
g_base_info_unref (interface_info);
}
break;
case GI_TYPE_TAG_ARRAY:
{
GIArrayType array_type = g_type_info_get_array_type (type_info);
GArray *garray = V8ToGArray (isolate, type_info, value);
switch (array_type) {
case GI_ARRAY_TYPE_C:
arg->v_pointer = g_array_free (garray, FALSE);
break;
case GI_ARRAY_TYPE_ARRAY:
arg->v_pointer = garray;
break;
default:
g_assert_not_reached ();
}
}
break;
default:
g_assert_not_reached ();
}
}
void FreeGIArgument(GITypeInfo *type_info, GIArgument *arg) {
GITypeTag type_tag = g_type_info_get_tag (type_info);
switch (type_tag) {
case GI_TYPE_TAG_FILENAME:
case GI_TYPE_TAG_UTF8:
g_free (arg->v_pointer);
break;
case GI_TYPE_TAG_ARRAY:
{
GIArrayType array_type = g_type_info_get_array_type (type_info);
switch (array_type) {
case GI_ARRAY_TYPE_C:
g_free (arg->v_pointer);
break;
case GI_ARRAY_TYPE_ARRAY:
g_array_free ((GArray *) arg->v_pointer, TRUE);
break;
default:
g_assert_not_reached ();
}
}
break;
default:
break;
}
}
void V8ToGValue(GValue *gvalue, Handle<Value> value) {
if (G_VALUE_HOLDS_BOOLEAN (gvalue)) {
g_value_set_boolean (gvalue, value->BooleanValue ());
} else if (G_VALUE_HOLDS_INT (gvalue)) {
g_value_set_int (gvalue, value->Int32Value ());
} else if (G_VALUE_HOLDS_UINT (gvalue)) {
g_value_set_uint (gvalue, value->Uint32Value ());
} else if (G_VALUE_HOLDS_FLOAT (gvalue)) {
g_value_set_float (gvalue, value->NumberValue ());
} else if (G_VALUE_HOLDS_DOUBLE (gvalue)) {
g_value_set_double (gvalue, value->NumberValue ());
} else if (G_VALUE_HOLDS_STRING (gvalue)) {
String::Utf8Value str (value);
const char *data = *str;
g_value_set_string (gvalue, data);
} else if (G_VALUE_HOLDS_ENUM (gvalue)) {
g_value_set_enum (gvalue, value->Int32Value ());
} else if (G_VALUE_HOLDS_OBJECT (gvalue)) {
g_value_set_object (gvalue, GObjectFromWrapper (value));
} else {
g_assert_not_reached ();
}
}
Handle<Value> GValueToV8(Isolate *isolate, const GValue *gvalue) {
if (G_VALUE_HOLDS_BOOLEAN (gvalue)) {
if (g_value_get_boolean (gvalue))
return True (isolate);
else
return False (isolate);
} else if (G_VALUE_HOLDS_INT (gvalue)) {
return Integer::New (isolate, g_value_get_int (gvalue));
} else if (G_VALUE_HOLDS_UINT (gvalue)) {
return Integer::NewFromUnsigned (isolate, g_value_get_uint (gvalue));
} else if (G_VALUE_HOLDS_FLOAT (gvalue)) {
return Number::New (isolate, g_value_get_float (gvalue));
} else if (G_VALUE_HOLDS_DOUBLE (gvalue)) {
return Number::New (isolate, g_value_get_double (gvalue));
} else if (G_VALUE_HOLDS_STRING (gvalue)) {
return String::NewFromUtf8 (isolate, g_value_get_string (gvalue));
} else if (G_VALUE_HOLDS_ENUM (gvalue)) {
return Integer::New (isolate, g_value_get_enum (gvalue));
} else if (G_VALUE_HOLDS_OBJECT (gvalue)) {
return WrapperFromGObject (isolate, G_OBJECT (g_value_get_object (gvalue)));
} else {
g_assert_not_reached ();
}
}
};
<|endoftext|> |
<commit_before>#include "gamescene.h"
void GameScene::append_gameItem(QDeclarativeListProperty<GameItem> *list, GameItem *gameItem)
{
GameScene *scene = qobject_cast<GameScene *>(list->object);
if (scene) {
gameItem->setParentItem(scene);
scene->m_gameItems.append(gameItem);
}
}
GameScene::GameScene(QQuickItem *parent)
: QQuickItem(parent)
{
}
QDeclarativeListProperty<GameItem> GameScene::gameItems()
{
return QDeclarativeListProperty<GameItem>(this, 0, &GameScene::append_gameItem);
}
void GameScene::update(long delta)
{
if (!m_running) // TODO: stop Qt animations as well
return;
GameItem *item;
foreach (item, m_gameItems)
item->update(delta);
}
bool GameScene::running() const
{
return m_running;
}
void GameScene::setRunning(bool running)
{
m_running = running;
emit runningChanged();
}
<commit_msg>Change default running state to true<commit_after>#include "gamescene.h"
void GameScene::append_gameItem(QDeclarativeListProperty<GameItem> *list, GameItem *gameItem)
{
GameScene *scene = qobject_cast<GameScene *>(list->object);
if (scene) {
gameItem->setParentItem(scene);
scene->m_gameItems.append(gameItem);
}
}
GameScene::GameScene(QQuickItem *parent)
: QQuickItem(parent)
, m_running(true)
{
}
QDeclarativeListProperty<GameItem> GameScene::gameItems()
{
return QDeclarativeListProperty<GameItem>(this, 0, &GameScene::append_gameItem);
}
void GameScene::update(long delta)
{
if (!m_running) // TODO: stop Qt animations as well
return;
GameItem *item;
foreach (item, m_gameItems)
item->update(delta);
}
bool GameScene::running() const
{
return m_running;
}
void GameScene::setRunning(bool running)
{
m_running = running;
emit runningChanged();
}
<|endoftext|> |
<commit_before>/* wave.c: Generate a C chord in various wave forms
*
* Copyright 2016 Vincent Damewood
*
* 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 WAVES_H
#define WAVES_H
typedef double (*fpWave)(double);
float phase(float frequency, int sample);
double square(double phase);
double sine(double phase);
double absine(double phase);
double saw(double phase);
double triangle(double phase);
#endif /* WAVES_H */
<commit_msg>Fix a comment<commit_after>/* waves.hh: Various waveforms
*
* Copyright 2016 Vincent Damewood
*
* 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 WAVES_H
#define WAVES_H
typedef double (*fpWave)(double);
float phase(float frequency, int sample);
double square(double phase);
double sine(double phase);
double absine(double phase);
double saw(double phase);
double triangle(double phase);
#endif /* WAVES_H */
<|endoftext|> |
<commit_before>/*******************************************************************************
* alcazar-gen
*
* Copyright (c) 2015 Florian Pigorsch
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
#include <random>
#include "generator.h"
Board generate(int w, int h)
{
const int pathLength = w * h;
Board b(w, h);
std::cout << "Creating initial path..." << std::flush;
Minisat::Solver s;
std::map<std::pair<int, int>, Minisat::Lit> field_pathpos2lit;
std::map<Wall, Minisat::Lit> wall2lit;
b.encode(s, field_pathpos2lit, wall2lit);
std::vector<int> edgeFields;
for (int x = 0; x < w; ++x)
{
edgeFields.push_back(b.index(x, 0));
edgeFields.push_back(b.index(x, h-1));
}
for (int y = 1; y+1 < h; ++y)
{
edgeFields.push_back(b.index(0, y));
edgeFields.push_back(b.index(w-1, y));
}
std::mt19937 rng;
rng.seed(std::random_device()());
std::uniform_int_distribution<std::mt19937::result_type> edgeFieldDist(0, edgeFields.size() - 1);
for (;;)
{
Minisat::vec<Minisat::Lit> initialAssumptions;
// fix entry and exit
for (;;)
{
const int entryField = edgeFields[edgeFieldDist(rng)];
const int exitField = edgeFields[edgeFieldDist(rng)];
if (entryField < exitField)
{
initialAssumptions.push(field_pathpos2lit[{entryField, 0}]);
initialAssumptions.push(field_pathpos2lit[{exitField, pathLength-1}]);
break;
}
}
// no walls
for (auto wall: b.getPossibleWalls())
{
initialAssumptions.push(~wall2lit[wall]);
}
if (s.solve(initialAssumptions)) break;
}
Path path(pathLength);
Minisat::vec<Minisat::Lit> pathClause;
for (int field = 0; field < pathLength; ++field)
{
for (int pos = 0; pos < pathLength; ++pos)
{
const auto lit = field_pathpos2lit[{field, pos}];
const Minisat::lbool value = s.modelValue(lit);
if (value == Minisat::l_True)
{
path.set(pos, b.coord(field));
pathClause.push(~lit);
}
}
}
s.addClause(pathClause);
std::cout << " done" << std::endl;
std::cout << "removing walls... " << std::flush;
std::set<Wall> openWalls;
for (auto w: b.getOpenWalls())
{
openWalls.insert(w);
}
std::vector<Wall> candidateWalls = path.getNonblockingWalls(b.getPossibleWalls());
for (auto w: candidateWalls)
{
openWalls.erase(w);
}
std::vector<Wall> essentialWalls;
while (!candidateWalls.empty())
{
std::cout << "\rRemoving walls... " << candidateWalls.size() << " " << std::flush;
Minisat::vec<Minisat::Lit> assumptions;
std::uniform_int_distribution<std::mt19937::result_type> wallDist(0, candidateWalls.size() - 1);
int wallIndex = wallDist(rng);
const Wall wall = candidateWalls[wallIndex];
if (static_cast<unsigned int>(wallIndex + 1) != candidateWalls.size())
{
std::swap(candidateWalls[wallIndex], candidateWalls.back());
}
candidateWalls.pop_back();
assumptions.push(~wall2lit[wall]);
for (auto w: candidateWalls)
{
assumptions.push(wall2lit[w]);
}
for (auto w: essentialWalls)
{
assumptions.push(wall2lit[w]);
}
for (auto w: openWalls)
{
assumptions.push(~wall2lit[w]);
}
if (s.solve(assumptions))
{
// wall is needed to keep path unique
essentialWalls.push_back(wall);
}
else
{
openWalls.insert(wall);
}
}
std::cout << "\rRemoving walls... done " << std::endl;
// add non-blocking walls
for (auto wall: essentialWalls)
{
b.addWall(wall);
}
return b;
}
<commit_msg>freezing variables of open and essential walls<commit_after>/*******************************************************************************
* alcazar-gen
*
* Copyright (c) 2015 Florian Pigorsch
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
#include <random>
#include "generator.h"
Board generate(int w, int h)
{
const int pathLength = w * h;
Board b(w, h);
std::cout << "Creating initial path..." << std::flush;
Minisat::Solver s;
std::map<std::pair<int, int>, Minisat::Lit> field_pathpos2lit;
std::map<Wall, Minisat::Lit> wall2lit;
b.encode(s, field_pathpos2lit, wall2lit);
std::vector<int> edgeFields;
for (int x = 0; x < w; ++x)
{
edgeFields.push_back(b.index(x, 0));
edgeFields.push_back(b.index(x, h-1));
}
for (int y = 1; y+1 < h; ++y)
{
edgeFields.push_back(b.index(0, y));
edgeFields.push_back(b.index(w-1, y));
}
std::mt19937 rng;
rng.seed(std::random_device()());
std::uniform_int_distribution<std::mt19937::result_type> edgeFieldDist(0, edgeFields.size() - 1);
for (;;)
{
Minisat::vec<Minisat::Lit> initialAssumptions;
// fix entry and exit
for (;;)
{
const int entryField = edgeFields[edgeFieldDist(rng)];
const int exitField = edgeFields[edgeFieldDist(rng)];
if (entryField < exitField)
{
initialAssumptions.push(field_pathpos2lit[{entryField, 0}]);
initialAssumptions.push(field_pathpos2lit[{exitField, pathLength-1}]);
break;
}
}
// no walls
for (auto wall: b.getPossibleWalls())
{
initialAssumptions.push(~wall2lit[wall]);
}
if (s.solve(initialAssumptions)) break;
}
Path path(pathLength);
Minisat::vec<Minisat::Lit> pathClause;
for (int field = 0; field < pathLength; ++field)
{
for (int pos = 0; pos < pathLength; ++pos)
{
const auto lit = field_pathpos2lit[{field, pos}];
const Minisat::lbool value = s.modelValue(lit);
if (value == Minisat::l_True)
{
path.set(pos, b.coord(field));
pathClause.push(~lit);
}
}
}
s.addClause(pathClause);
std::cout << " done" << std::endl;
std::cout << "removing walls... " << std::flush;
std::vector<Wall> candidateWalls = path.getNonblockingWalls(b.getPossibleWalls());
// fixed variables of open walls
std::set<Wall> openWalls;
for (auto w: b.getOpenWalls())
{
openWalls.insert(w);
}
for (auto w: candidateWalls)
{
openWalls.erase(w);
}
for (auto w: openWalls)
{
s.addClause(~wall2lit[w]);
}
std::vector<Wall> essentialWalls;
while (!candidateWalls.empty())
{
std::cout << "\rRemoving walls... " << candidateWalls.size() << " " << std::flush;
Minisat::vec<Minisat::Lit> assumptions;
std::uniform_int_distribution<std::mt19937::result_type> wallDist(0, candidateWalls.size() - 1);
const int wallIndex = wallDist(rng);
const Wall wall = candidateWalls[wallIndex];
if (static_cast<unsigned int>(wallIndex + 1) != candidateWalls.size())
{
std::swap(candidateWalls[wallIndex], candidateWalls.back());
}
candidateWalls.pop_back();
const auto lit = wall2lit[wall];
assumptions.push(~lit);
for (auto w: candidateWalls)
{
assumptions.push(wall2lit[w]);
}
if (s.solve(assumptions))
{
// wall is needed to keep path unique -> fix variable=1
s.addClause(lit);
essentialWalls.push_back(wall);
}
else
{
// wall can be removed -> fix variable=0
s.addClause(~lit);
}
}
std::cout << "\rRemoving walls... done " << std::endl;
// add non-blocking walls
for (auto wall: essentialWalls)
{
b.addWall(wall);
}
return b;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2018 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 "quic/core/http/quic_spdy_stream_body_manager.h"
#include <algorithm>
#include "absl/strings/string_view.h"
#include "quic/platform/api/quic_logging.h"
namespace quic {
QuicSpdyStreamBodyManager::QuicSpdyStreamBodyManager()
: total_body_bytes_received_(0) {}
size_t QuicSpdyStreamBodyManager::OnNonBody(QuicByteCount length) {
QUICHE_DCHECK_NE(0u, length);
if (fragments_.empty()) {
// Non-body bytes can be consumed immediately, because all previously
// received body bytes have been read.
return length;
}
// Non-body bytes will be consumed after last body fragment is read.
fragments_.back().trailing_non_body_byte_count += length;
return 0;
}
void QuicSpdyStreamBodyManager::OnBody(absl::string_view body) {
QUICHE_DCHECK(!body.empty());
fragments_.push_back({body, 0});
total_body_bytes_received_ += body.length();
}
size_t QuicSpdyStreamBodyManager::OnBodyConsumed(size_t num_bytes) {
QuicByteCount bytes_to_consume = 0;
size_t remaining_bytes = num_bytes;
while (remaining_bytes > 0) {
if (fragments_.empty()) {
QUIC_BUG << "Not enough available body to consume.";
return 0;
}
Fragment& fragment = fragments_.front();
const absl::string_view body = fragment.body;
if (body.length() > remaining_bytes) {
// Consume leading |remaining_bytes| bytes of body.
bytes_to_consume += remaining_bytes;
fragment.body = body.substr(remaining_bytes);
return bytes_to_consume;
}
// Consume entire fragment and the following
// |trailing_non_body_byte_count| bytes.
remaining_bytes -= body.length();
bytes_to_consume += body.length() + fragment.trailing_non_body_byte_count;
fragments_.pop_front();
}
return bytes_to_consume;
}
int QuicSpdyStreamBodyManager::PeekBody(iovec* iov, size_t iov_len) const {
QUICHE_DCHECK(iov);
QUICHE_DCHECK_GT(iov_len, 0u);
// TODO(bnc): Is this really necessary?
if (fragments_.empty()) {
iov[0].iov_base = nullptr;
iov[0].iov_len = 0;
return 0;
}
size_t iov_filled = 0;
while (iov_filled < fragments_.size() && iov_filled < iov_len) {
absl::string_view body = fragments_[iov_filled].body;
iov[iov_filled].iov_base = const_cast<char*>(body.data());
iov[iov_filled].iov_len = body.size();
iov_filled++;
}
return iov_filled;
}
size_t QuicSpdyStreamBodyManager::ReadBody(const struct iovec* iov,
size_t iov_len,
size_t* total_bytes_read) {
*total_bytes_read = 0;
QuicByteCount bytes_to_consume = 0;
// The index of iovec to write to.
size_t index = 0;
// Address to write to within current iovec.
char* dest = reinterpret_cast<char*>(iov[index].iov_base);
// Remaining space in current iovec.
size_t dest_remaining = iov[index].iov_len;
while (!fragments_.empty()) {
Fragment& fragment = fragments_.front();
const absl::string_view body = fragment.body;
const size_t bytes_to_copy =
std::min<size_t>(body.length(), dest_remaining);
memcpy(dest, body.data(), bytes_to_copy);
bytes_to_consume += bytes_to_copy;
*total_bytes_read += bytes_to_copy;
if (bytes_to_copy == body.length()) {
// Entire fragment read.
bytes_to_consume += fragment.trailing_non_body_byte_count;
fragments_.pop_front();
} else {
// Consume leading |bytes_to_copy| bytes of body.
fragment.body = body.substr(bytes_to_copy);
}
if (bytes_to_copy == dest_remaining) {
// Current iovec full.
++index;
if (index == iov_len) {
break;
}
dest = reinterpret_cast<char*>(iov[index].iov_base);
dest_remaining = iov[index].iov_len;
} else {
// Advance destination parameters within this iovec.
dest += bytes_to_copy;
dest_remaining -= bytes_to_copy;
}
}
return bytes_to_consume;
}
} // namespace quic
<commit_msg>Migration from QUIC_BUG to QUIC_BUG_V2(bug_id).<commit_after>// Copyright (c) 2018 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 "quic/core/http/quic_spdy_stream_body_manager.h"
#include <algorithm>
#include "absl/strings/string_view.h"
#include "quic/platform/api/quic_logging.h"
namespace quic {
QuicSpdyStreamBodyManager::QuicSpdyStreamBodyManager()
: total_body_bytes_received_(0) {}
size_t QuicSpdyStreamBodyManager::OnNonBody(QuicByteCount length) {
QUICHE_DCHECK_NE(0u, length);
if (fragments_.empty()) {
// Non-body bytes can be consumed immediately, because all previously
// received body bytes have been read.
return length;
}
// Non-body bytes will be consumed after last body fragment is read.
fragments_.back().trailing_non_body_byte_count += length;
return 0;
}
void QuicSpdyStreamBodyManager::OnBody(absl::string_view body) {
QUICHE_DCHECK(!body.empty());
fragments_.push_back({body, 0});
total_body_bytes_received_ += body.length();
}
size_t QuicSpdyStreamBodyManager::OnBodyConsumed(size_t num_bytes) {
QuicByteCount bytes_to_consume = 0;
size_t remaining_bytes = num_bytes;
while (remaining_bytes > 0) {
if (fragments_.empty()) {
QUIC_BUG_V2(quic_bug_10394_1) << "Not enough available body to consume.";
return 0;
}
Fragment& fragment = fragments_.front();
const absl::string_view body = fragment.body;
if (body.length() > remaining_bytes) {
// Consume leading |remaining_bytes| bytes of body.
bytes_to_consume += remaining_bytes;
fragment.body = body.substr(remaining_bytes);
return bytes_to_consume;
}
// Consume entire fragment and the following
// |trailing_non_body_byte_count| bytes.
remaining_bytes -= body.length();
bytes_to_consume += body.length() + fragment.trailing_non_body_byte_count;
fragments_.pop_front();
}
return bytes_to_consume;
}
int QuicSpdyStreamBodyManager::PeekBody(iovec* iov, size_t iov_len) const {
QUICHE_DCHECK(iov);
QUICHE_DCHECK_GT(iov_len, 0u);
// TODO(bnc): Is this really necessary?
if (fragments_.empty()) {
iov[0].iov_base = nullptr;
iov[0].iov_len = 0;
return 0;
}
size_t iov_filled = 0;
while (iov_filled < fragments_.size() && iov_filled < iov_len) {
absl::string_view body = fragments_[iov_filled].body;
iov[iov_filled].iov_base = const_cast<char*>(body.data());
iov[iov_filled].iov_len = body.size();
iov_filled++;
}
return iov_filled;
}
size_t QuicSpdyStreamBodyManager::ReadBody(const struct iovec* iov,
size_t iov_len,
size_t* total_bytes_read) {
*total_bytes_read = 0;
QuicByteCount bytes_to_consume = 0;
// The index of iovec to write to.
size_t index = 0;
// Address to write to within current iovec.
char* dest = reinterpret_cast<char*>(iov[index].iov_base);
// Remaining space in current iovec.
size_t dest_remaining = iov[index].iov_len;
while (!fragments_.empty()) {
Fragment& fragment = fragments_.front();
const absl::string_view body = fragment.body;
const size_t bytes_to_copy =
std::min<size_t>(body.length(), dest_remaining);
memcpy(dest, body.data(), bytes_to_copy);
bytes_to_consume += bytes_to_copy;
*total_bytes_read += bytes_to_copy;
if (bytes_to_copy == body.length()) {
// Entire fragment read.
bytes_to_consume += fragment.trailing_non_body_byte_count;
fragments_.pop_front();
} else {
// Consume leading |bytes_to_copy| bytes of body.
fragment.body = body.substr(bytes_to_copy);
}
if (bytes_to_copy == dest_remaining) {
// Current iovec full.
++index;
if (index == iov_len) {
break;
}
dest = reinterpret_cast<char*>(iov[index].iov_base);
dest_remaining = iov[index].iov_len;
} else {
// Advance destination parameters within this iovec.
dest += bytes_to_copy;
dest_remaining -= bytes_to_copy;
}
}
return bytes_to_consume;
}
} // namespace quic
<|endoftext|> |
<commit_before>#include "Config.h"
#include "ecru.h"
#include <iostream>
#include <fstream>
#include <libgen.h>
#include <sys/stat.h>
#include <libconfig.h++>
using namespace std;
Config::Config()
{
this->configDirectory = std::string(getenv("HOME")) + "/.ecru/";
//string filename = std::string(getenv("HOME")) + "/.ecru/default.conf";
//string filename = this->configDirectory + "default.conf";
string filename = getCurrentConfigFilename();
libconfig::Config *cfg = new libconfig::Config();
try {
cfg->readFile(filename.c_str());
} catch (libconfig::FileIOException& ex) {
cerr << "Configuration wasn't found, run 'ecru-config -g' to generate new configuration." << endl;
exit(1);
} catch (libconfig::ParseException& ex) {
cerr << "Parse exception on line = " << ex.getLine() << ", error: " << ex.getError() << endl;
exit(1);
}
this->config = cfg;
}
string Config::queryConfigProperty(string property)
{
string result = this->config->lookup(property);
return result;
}
string Config::getCurrentConfigFilename()
{
string schemaFilename = this->configDirectory + "current";
ifstream schemaInputStream(schemaFilename.c_str());
if (!schemaInputStream) {
return this->configDirectory + "default.conf";
}
string currentConfigFilename;
schemaInputStream >> currentConfigFilename;
return this->configDirectory + currentConfigFilename;
}
void Config::setCurrentConfigFilename(string filename)
{
string schemaFilename = this->configDirectory + "current";
string configFilename = string(basename((char*)filename.c_str()));
ofstream schemaOutputStream(schemaFilename.c_str());
schemaOutputStream << configFilename << endl;
}
vector<string> Config::listConfigFiles()
{
vector<string> files = ecru::listDirectory(this->configDirectory);
vector<string> configFiles;
for (unsigned int i = 0; i < files.size(); i++) {
string filename = files[i];
if (filename.length() > 5) {
// we're interested only in "*.conf$" files
if (filename.substr(filename.length() - 5) == ".conf") {
configFiles.push_back(this->configDirectory + filename);
}
}
}
return configFiles;
}
string Config::generate(string username, string hpassword)
{
string configDir = "ecru.new";
string templateDir = configDir + "/templates";
string hooksDir = configDir + "/hooks";
string dirs[] = { configDir, templateDir, hooksDir, hooksDir + "/pre", hooksDir + "/post" };
unsigned int dirsCount = sizeof(dirs) / sizeof(dirs[0]);
for (unsigned int i = 0; i < dirsCount; i++) {
/* TODO split into separate function somewhere in ecru:: */
if ((mkdir(dirs[i].c_str(), S_IRWXU)) != 0) {
perror(dirs[i].c_str());
exit(1);
}
}
libconfig::Config *cfg = new libconfig::Config();
libconfig::Setting& setting = cfg->getRoot();
//cout << setting.isGroup() << endl;
setting.add("config", libconfig::Setting::TypeGroup);
libconfig::Setting& configSetting = cfg->lookup("config");
configSetting.add("account", libconfig::Setting::TypeGroup);
libconfig::Setting& accountSetting = cfg->lookup("config.account");
accountSetting.add("login", libconfig::Setting::TypeString);
accountSetting.add("password", libconfig::Setting::TypeString);
accountSetting["login"] = username;
accountSetting["password"] = hpassword;
cfg->writeFile( (configDir + "/default.conf").c_str() );
ofstream outputStream;
outputStream.open( (configDir + "/current").c_str() );
outputStream << "default.conf" << endl;
outputStream.close();
outputStream.open( (templateDir + "/default").c_str() );
outputStream << "subject: " << endl << endl;
outputStream.close();
return configDir;
}
<commit_msg>Support for querying boolean config settings.<commit_after>#include "Config.h"
#include "ecru.h"
#include <iostream>
#include <fstream>
#include <libgen.h>
#include <sys/stat.h>
#include <libconfig.h++>
using namespace std;
Config::Config()
{
this->configDirectory = std::string(getenv("HOME")) + "/.ecru/";
//string filename = std::string(getenv("HOME")) + "/.ecru/default.conf";
//string filename = this->configDirectory + "default.conf";
string filename = getCurrentConfigFilename();
libconfig::Config *cfg = new libconfig::Config();
try {
cfg->readFile(filename.c_str());
} catch (libconfig::FileIOException& ex) {
cerr << "Configuration wasn't found, run 'ecru-config -g' to generate new configuration." << endl;
exit(1);
} catch (libconfig::ParseException& ex) {
cerr << "Parse exception on line = " << ex.getLine() << ", error: " << ex.getError() << endl;
exit(1);
}
this->config = cfg;
}
string Config::queryConfigProperty(string property)
{
string result;
libconfig::Setting& setting = this->config->lookup(property);
switch (setting.getType()) {
case libconfig::Setting::TypeString:
result = (const char*)setting;
break;
case libconfig::Setting::TypeBoolean:
//bool val = (bool)setting;
result = ((bool)setting) ? "true" : "false";
break;
default:
// XXX I guess it should be an exception
result = "unknown type.";
break;
}
return result;
}
string Config::getCurrentConfigFilename()
{
string schemaFilename = this->configDirectory + "current";
ifstream schemaInputStream(schemaFilename.c_str());
if (!schemaInputStream) {
return this->configDirectory + "default.conf";
}
string currentConfigFilename;
schemaInputStream >> currentConfigFilename;
return this->configDirectory + currentConfigFilename;
}
void Config::setCurrentConfigFilename(string filename)
{
string schemaFilename = this->configDirectory + "current";
string configFilename = string(basename((char*)filename.c_str()));
ofstream schemaOutputStream(schemaFilename.c_str());
schemaOutputStream << configFilename << endl;
}
vector<string> Config::listConfigFiles()
{
vector<string> files = ecru::listDirectory(this->configDirectory);
vector<string> configFiles;
for (unsigned int i = 0; i < files.size(); i++) {
string filename = files[i];
if (filename.length() > 5) {
// we're interested only in "*.conf$" files
if (filename.substr(filename.length() - 5) == ".conf") {
configFiles.push_back(this->configDirectory + filename);
}
}
}
return configFiles;
}
string Config::generate(string username, string hpassword)
{
string configDir = "ecru.new";
string templateDir = configDir + "/templates";
string hooksDir = configDir + "/hooks";
string dirs[] = { configDir, templateDir, hooksDir, hooksDir + "/pre", hooksDir + "/post" };
unsigned int dirsCount = sizeof(dirs) / sizeof(dirs[0]);
for (unsigned int i = 0; i < dirsCount; i++) {
/* TODO split into separate function somewhere in ecru:: */
if ((mkdir(dirs[i].c_str(), S_IRWXU)) != 0) {
perror(dirs[i].c_str());
exit(1);
}
}
libconfig::Config *cfg = new libconfig::Config();
libconfig::Setting& setting = cfg->getRoot();
//cout << setting.isGroup() << endl;
setting.add("config", libconfig::Setting::TypeGroup);
libconfig::Setting& configSetting = cfg->lookup("config");
configSetting.add("account", libconfig::Setting::TypeGroup);
libconfig::Setting& accountSetting = cfg->lookup("config.account");
accountSetting.add("login", libconfig::Setting::TypeString);
accountSetting.add("password", libconfig::Setting::TypeString);
accountSetting["login"] = username;
accountSetting["password"] = hpassword;
cfg->writeFile( (configDir + "/default.conf").c_str() );
ofstream outputStream;
outputStream.open( (configDir + "/current").c_str() );
outputStream << "default.conf" << endl;
outputStream.close();
outputStream.open( (templateDir + "/default").c_str() );
outputStream << "subject: " << endl << endl;
outputStream.close();
return configDir;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2018 - present Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <unordered_map>
#include <string>
#include <fstream>
#include "hip/hip_runtime.h"
#include "hip_hcc_internal.h"
#include "trace_helper.h"
constexpr unsigned __hipFatMAGIC2 = 0x48495046; // "HIPF"
#define CLANG_OFFLOAD_BUNDLER_MAGIC "__CLANG_OFFLOAD_BUNDLE__"
#define AMDGCN_AMDHSA_TRIPLE "hip-amdgcn-amd-amdhsa"
struct __ClangOffloadBundleDesc {
uint64_t offset;
uint64_t size;
uint64_t tripleSize;
const char triple[1];
};
struct __ClangOffloadBundleHeader {
const char magic[sizeof(CLANG_OFFLOAD_BUNDLER_MAGIC) - 1];
uint64_t numBundles;
__ClangOffloadBundleDesc desc[1];
};
struct __CudaFatBinaryWrapper {
unsigned int magic;
unsigned int version;
__ClangOffloadBundleHeader* binary;
void* unused;
};
extern "C" std::vector<hipModule_t>*
__hipRegisterFatBinary(const void* data)
{
HIP_INIT();
tprintf(DB_FB, "Enter __hipRegisterFatBinary(%p)\n", data);
const __CudaFatBinaryWrapper* fbwrapper = reinterpret_cast<const __CudaFatBinaryWrapper*>(data);
if (fbwrapper->magic != __hipFatMAGIC2 || fbwrapper->version != 1) {
return nullptr;
}
const __ClangOffloadBundleHeader* header = fbwrapper->binary;
std::string magic(reinterpret_cast<const char*>(header), sizeof(CLANG_OFFLOAD_BUNDLER_MAGIC) - 1);
if (magic.compare(CLANG_OFFLOAD_BUNDLER_MAGIC)) {
return nullptr;
}
auto modules = new std::vector<hipModule_t>{g_deviceCnt};
if (!modules) {
return nullptr;
}
const __ClangOffloadBundleDesc* desc = &header->desc[0];
for (uint64_t i = 0; i < header->numBundles; ++i,
desc = reinterpret_cast<const __ClangOffloadBundleDesc*>(
reinterpret_cast<uintptr_t>(&desc->triple[0]) + desc->tripleSize)) {
std::string triple{&desc->triple[0], sizeof(AMDGCN_AMDHSA_TRIPLE) - 1};
if (triple.compare(AMDGCN_AMDHSA_TRIPLE))
continue;
std::string target{&desc->triple[sizeof(AMDGCN_AMDHSA_TRIPLE)],
desc->tripleSize - sizeof(AMDGCN_AMDHSA_TRIPLE)};
tprintf(DB_FB, "Found bundle for %s\n", target.c_str());
for (int deviceId = 0; deviceId < g_deviceCnt; ++deviceId) {
hsa_agent_t agent = g_allAgents[deviceId + 1];
char name[64] = {};
hsa_agent_get_info(agent, HSA_AGENT_INFO_NAME, name);
if (target.compare(name)) {
continue;
}
ihipModule_t* module = new ihipModule_t;
if (!module) {
continue;
}
hsa_executable_create_alt(HSA_PROFILE_FULL, HSA_DEFAULT_FLOAT_ROUNDING_MODE_DEFAULT, nullptr,
&module->executable);
std::string image{reinterpret_cast<const char*>(
reinterpret_cast<uintptr_t>(header) + desc->offset), desc->size};
module->executable = hip_impl::load_executable(image, module->executable, agent);
if (module->executable.handle) {
modules->at(deviceId) = module;
tprintf(DB_FB, "Loaded code object for %s\n", name);
if (HIP_DUMP_CODE_OBJECT) {
char fname[30];
static std::atomic<int> index;
sprintf(fname, "__hip_dump_code_object%04d.o", index++);
tprintf(DB_FB, "Dump code object %s\n", fname);
std::ofstream ofs;
ofs.open(fname, std::ios::binary);
ofs << image;
ofs.close();
}
} else {
fprintf(stderr, "Failed to load code object for %s\n", name);
abort();
}
}
}
for (int deviceId = 0; deviceId < g_deviceCnt; ++deviceId) {
hsa_agent_t agent = g_allAgents[deviceId + 1];
char name[64] = {};
hsa_agent_get_info(agent, HSA_AGENT_INFO_NAME, name);
if (!(*modules)[deviceId]) {
fprintf(stderr, "No device code bundle for %s\n", name);
abort();
}
}
tprintf(DB_FB, "__hipRegisterFatBinary succeeds and returns %p\n", modules);
return modules;
}
std::map<const void*, std::vector<hipFunction_t>> g_functions;
extern "C" void __hipRegisterFunction(
std::vector<hipModule_t>* modules,
const void* hostFunction,
char* deviceFunction,
const char* deviceName,
unsigned int threadLimit,
uint3* tid,
uint3* bid,
dim3* blockDim,
dim3* gridDim,
int* wSize)
{
HIP_INIT_API(modules, hostFunction, deviceFunction, deviceName);
std::vector<hipFunction_t> functions{g_deviceCnt};
assert(modules && modules->size() >= g_deviceCnt);
for (int deviceId = 0; deviceId < g_deviceCnt; ++deviceId) {
hipFunction_t function;
if (hipSuccess == hipModuleGetFunction(&function, modules->at(deviceId), deviceName)) {
functions[deviceId] = function;
}
else {
tprintf(DB_FB, "missing kernel %s for device %d\n", deviceName, deviceId);
}
}
g_functions.insert(std::make_pair(hostFunction, std::move(functions)));
}
extern "C" void __hipRegisterVar(
std::vector<hipModule_t>* modules,
char* hostVar,
char* deviceVar,
const char* deviceName,
int ext,
int size,
int constant,
int global)
{
}
extern "C" void __hipUnregisterFatBinary(std::vector<hipModule_t>* modules)
{
std::for_each(modules->begin(), modules->end(), [](hipModule_t module){ delete module; });
delete modules;
}
hipError_t hipConfigureCall(
dim3 gridDim,
dim3 blockDim,
size_t sharedMem,
hipStream_t stream)
{
auto ctx = ihipGetTlsDefaultCtx();
LockedAccessor_CtxCrit_t crit(ctx->criticalData());
crit->_execStack.push(ihipExec_t{gridDim, blockDim, sharedMem, stream});
return hipSuccess;
}
hipError_t hipSetupArgument(
const void *arg,
size_t size,
size_t offset)
{
HIP_INIT_API(arg, size, offset);
auto ctx = ihipGetTlsDefaultCtx();
LockedAccessor_CtxCrit_t crit(ctx->criticalData());
auto& arguments = crit->_execStack.top()._arguments;
if (arguments.size() < offset + size) {
arguments.resize(offset + size);
}
::memcpy(&arguments[offset], arg, size);
return hipSuccess;
}
hipError_t hipLaunchByPtr(const void *hostFunction)
{
HIP_INIT_API(hostFunction);
ihipExec_t exec;
{
auto ctx = ihipGetTlsDefaultCtx();
LockedAccessor_CtxCrit_t crit(ctx->criticalData());
exec = std::move(crit->_execStack.top());
crit->_execStack.pop();
}
int deviceId;
if (exec._hStream) {
deviceId = exec._hStream->getDevice()->_deviceId;
}
else if (ihipGetTlsDefaultCtx() && ihipGetTlsDefaultCtx()->getDevice()) {
deviceId = ihipGetTlsDefaultCtx()->getDevice()->_deviceId;
}
else {
deviceId = 0;
}
hipError_t e = hipSuccess;
decltype(g_functions)::iterator it;
if ((it = g_functions.find(hostFunction)) == g_functions.end()) {
e = hipErrorUnknown;
fprintf(stderr, "kernel %p not found!\n", hostFunction);
abort();
} else {
size_t size = exec._arguments.size();
void *extra[] = {
HIP_LAUNCH_PARAM_BUFFER_POINTER, &exec._arguments[0],
HIP_LAUNCH_PARAM_BUFFER_SIZE, &size,
HIP_LAUNCH_PARAM_END
};
e = hipModuleLaunchKernel(it->second[deviceId],
exec._gridDim.x, exec._gridDim.y, exec._gridDim.z,
exec._blockDim.x, exec._blockDim.y, exec._blockDim.z,
exec._sharedMem, exec._hStream, nullptr, extra);
}
return ihipLogStatus(e);
}
<commit_msg>Add more checks for fatbin<commit_after>/*
Copyright (c) 2018 - present Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <unordered_map>
#include <string>
#include <fstream>
#include "hip/hip_runtime.h"
#include "hip_hcc_internal.h"
#include "trace_helper.h"
constexpr unsigned __hipFatMAGIC2 = 0x48495046; // "HIPF"
#define CLANG_OFFLOAD_BUNDLER_MAGIC "__CLANG_OFFLOAD_BUNDLE__"
#define AMDGCN_AMDHSA_TRIPLE "hip-amdgcn-amd-amdhsa"
struct __ClangOffloadBundleDesc {
uint64_t offset;
uint64_t size;
uint64_t tripleSize;
const char triple[1];
};
struct __ClangOffloadBundleHeader {
const char magic[sizeof(CLANG_OFFLOAD_BUNDLER_MAGIC) - 1];
uint64_t numBundles;
__ClangOffloadBundleDesc desc[1];
};
struct __CudaFatBinaryWrapper {
unsigned int magic;
unsigned int version;
__ClangOffloadBundleHeader* binary;
void* unused;
};
extern "C" std::vector<hipModule_t>*
__hipRegisterFatBinary(const void* data)
{
HIP_INIT();
tprintf(DB_FB, "Enter __hipRegisterFatBinary(%p)\n", data);
const __CudaFatBinaryWrapper* fbwrapper = reinterpret_cast<const __CudaFatBinaryWrapper*>(data);
if (fbwrapper->magic != __hipFatMAGIC2 || fbwrapper->version != 1) {
return nullptr;
}
const __ClangOffloadBundleHeader* header = fbwrapper->binary;
std::string magic(reinterpret_cast<const char*>(header), sizeof(CLANG_OFFLOAD_BUNDLER_MAGIC) - 1);
if (magic.compare(CLANG_OFFLOAD_BUNDLER_MAGIC)) {
return nullptr;
}
auto modules = new std::vector<hipModule_t>{g_deviceCnt};
if (!modules) {
return nullptr;
}
const __ClangOffloadBundleDesc* desc = &header->desc[0];
for (uint64_t i = 0; i < header->numBundles; ++i,
desc = reinterpret_cast<const __ClangOffloadBundleDesc*>(
reinterpret_cast<uintptr_t>(&desc->triple[0]) + desc->tripleSize)) {
std::string triple{&desc->triple[0], sizeof(AMDGCN_AMDHSA_TRIPLE) - 1};
if (triple.compare(AMDGCN_AMDHSA_TRIPLE))
continue;
std::string target{&desc->triple[sizeof(AMDGCN_AMDHSA_TRIPLE)],
desc->tripleSize - sizeof(AMDGCN_AMDHSA_TRIPLE)};
tprintf(DB_FB, "Found bundle for %s\n", target.c_str());
for (int deviceId = 0; deviceId < g_deviceCnt; ++deviceId) {
hsa_agent_t agent = g_allAgents[deviceId + 1];
char name[64] = {};
hsa_agent_get_info(agent, HSA_AGENT_INFO_NAME, name);
if (target.compare(name)) {
continue;
}
ihipModule_t* module = new ihipModule_t;
if (!module) {
continue;
}
hsa_executable_create_alt(HSA_PROFILE_FULL, HSA_DEFAULT_FLOAT_ROUNDING_MODE_DEFAULT, nullptr,
&module->executable);
std::string image{reinterpret_cast<const char*>(
reinterpret_cast<uintptr_t>(header) + desc->offset), desc->size};
module->executable = hip_impl::load_executable(image, module->executable, agent);
if (module->executable.handle) {
modules->at(deviceId) = module;
tprintf(DB_FB, "Loaded code object for %s\n", name);
if (HIP_DUMP_CODE_OBJECT) {
char fname[30];
static std::atomic<int> index;
sprintf(fname, "__hip_dump_code_object%04d.o", index++);
tprintf(DB_FB, "Dump code object %s\n", fname);
std::ofstream ofs;
ofs.open(fname, std::ios::binary);
ofs << image;
ofs.close();
}
} else {
fprintf(stderr, "Failed to load code object for %s\n", name);
abort();
}
}
}
for (int deviceId = 0; deviceId < g_deviceCnt; ++deviceId) {
hsa_agent_t agent = g_allAgents[deviceId + 1];
char name[64] = {};
hsa_agent_get_info(agent, HSA_AGENT_INFO_NAME, name);
if (!(*modules)[deviceId]) {
fprintf(stderr, "No device code bundle for %s\n", name);
abort();
}
}
tprintf(DB_FB, "__hipRegisterFatBinary succeeds and returns %p\n", modules);
return modules;
}
std::map<const void*, std::vector<hipFunction_t>> g_functions;
extern "C" void __hipRegisterFunction(
std::vector<hipModule_t>* modules,
const void* hostFunction,
char* deviceFunction,
const char* deviceName,
unsigned int threadLimit,
uint3* tid,
uint3* bid,
dim3* blockDim,
dim3* gridDim,
int* wSize)
{
HIP_INIT_API(modules, hostFunction, deviceFunction, deviceName);
std::vector<hipFunction_t> functions{g_deviceCnt};
assert(modules && modules->size() >= g_deviceCnt);
for (int deviceId = 0; deviceId < g_deviceCnt; ++deviceId) {
hipFunction_t function;
if (hipSuccess == hipModuleGetFunction(&function, modules->at(deviceId), deviceName) &&
function != nullptr) {
functions[deviceId] = function;
}
else {
tprintf(DB_FB, "__hipRegisterFunction cannot find kernel %s for"
" device %d\n", deviceName, deviceId);
}
}
g_functions.insert(std::make_pair(hostFunction, std::move(functions)));
}
extern "C" void __hipRegisterVar(
std::vector<hipModule_t>* modules,
char* hostVar,
char* deviceVar,
const char* deviceName,
int ext,
int size,
int constant,
int global)
{
}
extern "C" void __hipUnregisterFatBinary(std::vector<hipModule_t>* modules)
{
std::for_each(modules->begin(), modules->end(), [](hipModule_t module){ delete module; });
delete modules;
}
hipError_t hipConfigureCall(
dim3 gridDim,
dim3 blockDim,
size_t sharedMem,
hipStream_t stream)
{
auto ctx = ihipGetTlsDefaultCtx();
LockedAccessor_CtxCrit_t crit(ctx->criticalData());
crit->_execStack.push(ihipExec_t{gridDim, blockDim, sharedMem, stream});
return hipSuccess;
}
hipError_t hipSetupArgument(
const void *arg,
size_t size,
size_t offset)
{
HIP_INIT_API(arg, size, offset);
auto ctx = ihipGetTlsDefaultCtx();
LockedAccessor_CtxCrit_t crit(ctx->criticalData());
auto& arguments = crit->_execStack.top()._arguments;
if (arguments.size() < offset + size) {
arguments.resize(offset + size);
}
::memcpy(&arguments[offset], arg, size);
return hipSuccess;
}
hipError_t hipLaunchByPtr(const void *hostFunction)
{
HIP_INIT_API(hostFunction);
ihipExec_t exec;
{
auto ctx = ihipGetTlsDefaultCtx();
LockedAccessor_CtxCrit_t crit(ctx->criticalData());
exec = std::move(crit->_execStack.top());
crit->_execStack.pop();
}
int deviceId;
if (exec._hStream) {
deviceId = exec._hStream->getDevice()->_deviceId;
}
else if (ihipGetTlsDefaultCtx() && ihipGetTlsDefaultCtx()->getDevice()) {
deviceId = ihipGetTlsDefaultCtx()->getDevice()->_deviceId;
}
else {
deviceId = 0;
}
hipError_t e = hipSuccess;
decltype(g_functions)::iterator it;
if ((it = g_functions.find(hostFunction)) == g_functions.end() ||
!it->second[deviceId]) {
e = hipErrorUnknown;
fprintf(stderr, "hipLaunchByPtr cannot find kernel with stub address %p"
" for device %d!\n", hostFunction, deviceId);
abort();
} else {
size_t size = exec._arguments.size();
void *extra[] = {
HIP_LAUNCH_PARAM_BUFFER_POINTER, &exec._arguments[0],
HIP_LAUNCH_PARAM_BUFFER_SIZE, &size,
HIP_LAUNCH_PARAM_END
};
e = hipModuleLaunchKernel(it->second[deviceId],
exec._gridDim.x, exec._gridDim.y, exec._gridDim.z,
exec._blockDim.x, exec._blockDim.y, exec._blockDim.z,
exec._sharedMem, exec._hStream, nullptr, extra);
}
return ihipLogStatus(e);
}
<|endoftext|> |
<commit_before>/*
* HMDCamera.cpp
*
* Created on: Jun 30, 2013
* Author: Jan Ciger
*/
#include <osg/io_utils>
#include <osg/Texture2D>
#include <osg/PolygonMode>
#include <osg/Program>
#include <osg/Shader>
#include <osgDB/ReadFile>
#include <osgViewer/View>
#include "hmdcamera.h"
#include "oculusdevice.h"
HMDCamera::HMDCamera(osgViewer::View* view, OculusDevice* dev) : osg::Group(),
m_configured(false),
m_chromaticAberrationCorrection(false),
m_view(view),
m_dev(dev)
{
}
HMDCamera::~HMDCamera()
{
}
void HMDCamera::traverse(osg::NodeVisitor& nv)
{
if (!m_configured) {
m_configured = true;
configure();
}
// Get orientation from oculus sensor
osg::Quat orient = m_dev->getOrientation();
// Nasty hack to update the view offset for each of the slave cameras
// There doesn't seem to be an accessor for this, fortunately the offsets are public
m_view->findSlaveForCamera(m_l_rtt.get())->_viewOffset.setRotate(orient);
m_view->findSlaveForCamera(m_r_rtt.get())->_viewOffset.setRotate(orient);
osg::Group::traverse(nv);
}
osg::Camera* HMDCamera::createRTTCamera(osg::Camera::BufferComponent buffer, osg::Texture* tex)
{
osg::ref_ptr<osg::Camera> camera = new osg::Camera;
camera->setClearColor(osg::Vec4(0.2f, 0.2f, 0.4f, 1.0f));
camera->setClearMask( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT );
camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
camera->setRenderOrder( osg::Camera::PRE_RENDER );
camera->setGraphicsContext(m_view->getCamera()->getGraphicsContext());
camera->setComputeNearFarMode( osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR );
camera->setReferenceFrame(osg::Camera::RELATIVE_RF);
if ( tex ) {
tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );
tex->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );
camera->setViewport( 0, 0, tex->getTextureWidth(), tex->getTextureHeight() );
camera->attach( buffer, tex, 0, 0, false, 4, 4);
}
return camera.release();
}
osg::Camera* HMDCamera::createHUDCamera(double left, double right, double bottom, double top)
{
osg::ref_ptr<osg::Camera> camera = new osg::Camera;
camera->setGraphicsContext(m_view->getCamera()->getGraphicsContext());
camera->setReferenceFrame( osg::Transform::ABSOLUTE_RF );
camera->setClearColor(osg::Vec4(0.2f, 0.2f, 0.4f, 1.0f));
camera->setClearMask( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
camera->setRenderOrder( osg::Camera::POST_RENDER );
camera->setAllowEventFocus( false );
camera->setProjectionMatrix( osg::Matrix::ortho2D(left, right, bottom, top) );
camera->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
return camera.release();
}
osg::Geode* HMDCamera::createHUDQuad( float width, float height, float scale )
{
osg::Geometry* geom = osg::createTexturedQuadGeometry(osg::Vec3(),
osg::Vec3(width, 0.0f, 0.0f),
osg::Vec3(0.0f, height, 0.0f),
0.0f, 0.0f, width*scale, height*scale );
osg::ref_ptr<osg::Geode> quad = new osg::Geode;
quad->addDrawable( geom );
int values = osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED;
quad->getOrCreateStateSet()->setAttribute(new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::FILL), values );
quad->getOrCreateStateSet()->setMode( GL_LIGHTING, values );
return quad.release();
}
void HMDCamera::configure()
{
const int textureWidth = m_dev->scaleFactor() * m_dev->hScreenResolution()/2;
const int textureHeight = m_dev->scaleFactor() * m_dev->vScreenResolution();
// master projection matrix
m_view->getCamera()->setProjectionMatrix(m_dev->projectionCenterMatrix());
osg::ref_ptr<osg::Texture2D> l_tex = new osg::Texture2D;
l_tex->setTextureSize( textureWidth, textureHeight );
l_tex->setInternalFormat( GL_RGBA );
osg::ref_ptr<osg::Texture2D> r_tex = new osg::Texture2D;
r_tex->setTextureSize( textureWidth, textureHeight );
r_tex->setInternalFormat( GL_RGBA );
osg::ref_ptr<osg::Camera> l_rtt = createRTTCamera(osg::Camera::COLOR_BUFFER, l_tex);
l_rtt->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
l_rtt->setReferenceFrame(osg::Camera::RELATIVE_RF);
m_l_rtt = l_rtt;
osg::ref_ptr<osg::Camera> r_rtt = createRTTCamera(osg::Camera::COLOR_BUFFER, r_tex);
r_rtt->setComputeNearFarMode( osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR );
r_rtt->setReferenceFrame(osg::Camera::RELATIVE_RF);
m_r_rtt = r_rtt;
// Create HUD cameras for each eye
osg::ref_ptr<osg::Camera> l_hud = createHUDCamera(0.0, 1.0, 0.0, 1.0);
l_hud->setViewport(new osg::Viewport(0, 0, m_dev->hScreenResolution() / 2.0f, m_dev->vScreenResolution()));
osg::ref_ptr<osg::Camera> r_hud = createHUDCamera(0.0, 1.0, 0.0, 1.0);
r_hud->setViewport(new osg::Viewport(m_dev->hScreenResolution() / 2.0f, 0,
m_dev->hScreenResolution() / 2.0f, m_dev->vScreenResolution()));
// Create quads on each camera
osg::ref_ptr<osg::Geode> leftQuad = createHUDQuad(1.0f, 1.0f);
l_hud->addChild(leftQuad);
osg::ref_ptr<osg::Geode> rightQuad = createHUDQuad(1.0f, 1.0f);
r_hud->addChild(rightQuad);
// Set up shaders from the Oculus SDK documentation
osg::ref_ptr<osg::Program> program = new osg::Program;
osg::ref_ptr<osg::Shader> vertexShader = new osg::Shader(osg::Shader::VERTEX);
vertexShader->loadShaderSourceFromFile("warp.vert");
osg::ref_ptr<osg::Shader> fragmentShader = new osg::Shader(osg::Shader::FRAGMENT);
// Fragment shader with or without correction for chromatic aberration
if (m_chromaticAberrationCorrection) {
fragmentShader->loadShaderSourceFromFile("warpWithChromeAb.frag");
} else {
fragmentShader->loadShaderSourceFromFile("warpWithoutChromeAb.frag");
}
program->addShader(vertexShader);
program->addShader(fragmentShader);
// Configure state sets for both eyes
osg::StateSet* leftEyeStateSet = leftQuad->getOrCreateStateSet();
leftEyeStateSet->setTextureAttributeAndModes(0, l_tex, osg::StateAttribute::ON);
leftEyeStateSet->setAttributeAndModes( program, osg::StateAttribute::ON );
leftEyeStateSet->addUniform( new osg::Uniform("WarpTexture", 0) );
leftEyeStateSet->addUniform( new osg::Uniform("LensCenter", m_dev->lensCenter(OculusDevice::LEFT_EYE)));
leftEyeStateSet->addUniform( new osg::Uniform("ScreenCenter", m_dev->screenCenter()));
leftEyeStateSet->addUniform( new osg::Uniform("Scale", m_dev->scale()));
leftEyeStateSet->addUniform( new osg::Uniform("ScaleIn", m_dev->scaleIn()));
leftEyeStateSet->addUniform( new osg::Uniform("HmdWarpParam", m_dev->warpParameters()));
leftEyeStateSet->addUniform( new osg::Uniform("ChromAbParam", m_dev->chromAbParameters()));
osg::StateSet* rightEyeStateSet = rightQuad->getOrCreateStateSet();
rightEyeStateSet->setTextureAttributeAndModes(0, r_tex, osg::StateAttribute::ON);
rightEyeStateSet->setAttributeAndModes( program, osg::StateAttribute::ON );
rightEyeStateSet->addUniform( new osg::Uniform("WarpTexture", 0) );
rightEyeStateSet->addUniform( new osg::Uniform("LensCenter", m_dev->lensCenter(OculusDevice::RIGHT_EYE)));
rightEyeStateSet->addUniform( new osg::Uniform("ScreenCenter", m_dev->screenCenter()));
rightEyeStateSet->addUniform( new osg::Uniform("Scale", m_dev->scale()));
rightEyeStateSet->addUniform( new osg::Uniform("ScaleIn", m_dev->scaleIn()));
rightEyeStateSet->addUniform( new osg::Uniform("HmdWarpParam", m_dev->warpParameters()));
rightEyeStateSet->addUniform( new osg::Uniform("ChromAbParam", m_dev->chromAbParameters()));
// Add cameras as slaves, specifying offsets for the projection
// View takes ownership of our cameras, that's why we keep only weak pointers to them
m_view->addSlave(l_rtt, m_dev->projectionOffsetMatrix(OculusDevice::LEFT_EYE), osg::Matrixf::identity(), true);
m_view->addSlave(r_rtt, m_dev->projectionOffsetMatrix(OculusDevice::RIGHT_EYE), osg::Matrixf::identity(), true);
m_view->addSlave(l_hud, false);
m_view->addSlave(r_hud, false);
}
<commit_msg>Change the setup of the slave cameras to get the correct interpupillary distance.<commit_after>/*
* HMDCamera.cpp
*
* Created on: Jun 30, 2013
* Author: Jan Ciger
*/
#include <osg/io_utils>
#include <osg/Texture2D>
#include <osg/PolygonMode>
#include <osg/Program>
#include <osg/Shader>
#include <osgDB/ReadFile>
#include <osgViewer/View>
#include "hmdcamera.h"
#include "oculusdevice.h"
HMDCamera::HMDCamera(osgViewer::View* view, OculusDevice* dev) : osg::Group(),
m_configured(false),
m_chromaticAberrationCorrection(false),
m_view(view),
m_dev(dev)
{
}
HMDCamera::~HMDCamera()
{
}
void HMDCamera::traverse(osg::NodeVisitor& nv)
{
if (!m_configured) {
m_configured = true;
configure();
}
// Get orientation from oculus sensor
osg::Quat orient = m_dev->getOrientation();
// Nasty hack to update the view offset for each of the slave cameras
// There doesn't seem to be an accessor for this, fortunately the offsets are public
m_view->findSlaveForCamera(m_l_rtt.get())->_viewOffset.setRotate(orient);
m_view->findSlaveForCamera(m_r_rtt.get())->_viewOffset.setRotate(orient);
osg::Group::traverse(nv);
}
osg::Camera* HMDCamera::createRTTCamera(osg::Camera::BufferComponent buffer, osg::Texture* tex)
{
osg::ref_ptr<osg::Camera> camera = new osg::Camera;
camera->setClearColor(osg::Vec4(0.2f, 0.2f, 0.4f, 1.0f));
camera->setClearMask( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT );
camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
camera->setRenderOrder( osg::Camera::PRE_RENDER );
camera->setGraphicsContext(m_view->getCamera()->getGraphicsContext());
camera->setComputeNearFarMode( osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR );
camera->setReferenceFrame(osg::Camera::RELATIVE_RF);
if ( tex ) {
tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );
tex->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );
camera->setViewport( 0, 0, tex->getTextureWidth(), tex->getTextureHeight() );
camera->attach( buffer, tex, 0, 0, false, 4, 4);
}
return camera.release();
}
osg::Camera* HMDCamera::createHUDCamera(double left, double right, double bottom, double top)
{
osg::ref_ptr<osg::Camera> camera = new osg::Camera;
camera->setGraphicsContext(m_view->getCamera()->getGraphicsContext());
camera->setReferenceFrame( osg::Transform::ABSOLUTE_RF );
camera->setClearColor(osg::Vec4(0.2f, 0.2f, 0.4f, 1.0f));
camera->setClearMask( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
camera->setRenderOrder( osg::Camera::POST_RENDER );
camera->setAllowEventFocus( false );
camera->setProjectionMatrix( osg::Matrix::ortho2D(left, right, bottom, top) );
camera->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
return camera.release();
}
osg::Geode* HMDCamera::createHUDQuad( float width, float height, float scale )
{
osg::Geometry* geom = osg::createTexturedQuadGeometry(osg::Vec3(),
osg::Vec3(width, 0.0f, 0.0f),
osg::Vec3(0.0f, height, 0.0f),
0.0f, 0.0f, width*scale, height*scale );
osg::ref_ptr<osg::Geode> quad = new osg::Geode;
quad->addDrawable( geom );
int values = osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED;
quad->getOrCreateStateSet()->setAttribute(new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::FILL), values );
quad->getOrCreateStateSet()->setMode( GL_LIGHTING, values );
return quad.release();
}
void HMDCamera::configure()
{
const int textureWidth = m_dev->scaleFactor() * m_dev->hScreenResolution()/2;
const int textureHeight = m_dev->scaleFactor() * m_dev->vScreenResolution();
// master projection matrix
m_view->getCamera()->setProjectionMatrix(m_dev->projectionCenterMatrix());
osg::ref_ptr<osg::Texture2D> l_tex = new osg::Texture2D;
l_tex->setTextureSize( textureWidth, textureHeight );
l_tex->setInternalFormat( GL_RGBA );
osg::ref_ptr<osg::Texture2D> r_tex = new osg::Texture2D;
r_tex->setTextureSize( textureWidth, textureHeight );
r_tex->setInternalFormat( GL_RGBA );
osg::ref_ptr<osg::Camera> l_rtt = createRTTCamera(osg::Camera::COLOR_BUFFER, l_tex);
l_rtt->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
l_rtt->setReferenceFrame(osg::Camera::RELATIVE_RF);
m_l_rtt = l_rtt;
osg::ref_ptr<osg::Camera> r_rtt = createRTTCamera(osg::Camera::COLOR_BUFFER, r_tex);
r_rtt->setComputeNearFarMode( osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR );
r_rtt->setReferenceFrame(osg::Camera::RELATIVE_RF);
m_r_rtt = r_rtt;
// Create HUD cameras for each eye
osg::ref_ptr<osg::Camera> l_hud = createHUDCamera(0.0, 1.0, 0.0, 1.0);
l_hud->setViewport(new osg::Viewport(0, 0, m_dev->hScreenResolution() / 2.0f, m_dev->vScreenResolution()));
osg::ref_ptr<osg::Camera> r_hud = createHUDCamera(0.0, 1.0, 0.0, 1.0);
r_hud->setViewport(new osg::Viewport(m_dev->hScreenResolution() / 2.0f, 0,
m_dev->hScreenResolution() / 2.0f, m_dev->vScreenResolution()));
// Create quads on each camera
osg::ref_ptr<osg::Geode> leftQuad = createHUDQuad(1.0f, 1.0f);
l_hud->addChild(leftQuad);
osg::ref_ptr<osg::Geode> rightQuad = createHUDQuad(1.0f, 1.0f);
r_hud->addChild(rightQuad);
// Set up shaders from the Oculus SDK documentation
osg::ref_ptr<osg::Program> program = new osg::Program;
osg::ref_ptr<osg::Shader> vertexShader = new osg::Shader(osg::Shader::VERTEX);
vertexShader->loadShaderSourceFromFile("warp.vert");
osg::ref_ptr<osg::Shader> fragmentShader = new osg::Shader(osg::Shader::FRAGMENT);
// Fragment shader with or without correction for chromatic aberration
if (m_chromaticAberrationCorrection) {
fragmentShader->loadShaderSourceFromFile("warpWithChromeAb.frag");
} else {
fragmentShader->loadShaderSourceFromFile("warpWithoutChromeAb.frag");
}
program->addShader(vertexShader);
program->addShader(fragmentShader);
// Configure state sets for both eyes
osg::StateSet* leftEyeStateSet = leftQuad->getOrCreateStateSet();
leftEyeStateSet->setTextureAttributeAndModes(0, l_tex, osg::StateAttribute::ON);
leftEyeStateSet->setAttributeAndModes( program, osg::StateAttribute::ON );
leftEyeStateSet->addUniform( new osg::Uniform("WarpTexture", 0) );
leftEyeStateSet->addUniform( new osg::Uniform("LensCenter", m_dev->lensCenter(OculusDevice::LEFT_EYE)));
leftEyeStateSet->addUniform( new osg::Uniform("ScreenCenter", m_dev->screenCenter()));
leftEyeStateSet->addUniform( new osg::Uniform("Scale", m_dev->scale()));
leftEyeStateSet->addUniform( new osg::Uniform("ScaleIn", m_dev->scaleIn()));
leftEyeStateSet->addUniform( new osg::Uniform("HmdWarpParam", m_dev->warpParameters()));
leftEyeStateSet->addUniform( new osg::Uniform("ChromAbParam", m_dev->chromAbParameters()));
osg::StateSet* rightEyeStateSet = rightQuad->getOrCreateStateSet();
rightEyeStateSet->setTextureAttributeAndModes(0, r_tex, osg::StateAttribute::ON);
rightEyeStateSet->setAttributeAndModes( program, osg::StateAttribute::ON );
rightEyeStateSet->addUniform( new osg::Uniform("WarpTexture", 0) );
rightEyeStateSet->addUniform( new osg::Uniform("LensCenter", m_dev->lensCenter(OculusDevice::RIGHT_EYE)));
rightEyeStateSet->addUniform( new osg::Uniform("ScreenCenter", m_dev->screenCenter()));
rightEyeStateSet->addUniform( new osg::Uniform("Scale", m_dev->scale()));
rightEyeStateSet->addUniform( new osg::Uniform("ScaleIn", m_dev->scaleIn()));
rightEyeStateSet->addUniform( new osg::Uniform("HmdWarpParam", m_dev->warpParameters()));
rightEyeStateSet->addUniform( new osg::Uniform("ChromAbParam", m_dev->chromAbParameters()));
// Add cameras as slaves, specifying offsets for the projection
// View takes ownership of our cameras, that's why we keep only weak pointers to them
m_view->addSlave(l_rtt, m_dev->projectionOffsetMatrix(OculusDevice::LEFT_EYE), m_dev->viewMatrix(OculusDevice::LEFT_EYE), true);
m_view->addSlave(r_rtt, m_dev->projectionOffsetMatrix(OculusDevice::RIGHT_EYE), m_dev->viewMatrix(OculusDevice::RIGHT_EYE), true);
m_view->addSlave(l_hud, false);
m_view->addSlave(r_hud, false);
}
<|endoftext|> |
<commit_before>#include "Homie.hpp"
using namespace HomieInternals;
HomieClass::HomieClass()
: _setupCalled(false)
, _firmwareSet(false)
, __HOMIE_SIGNATURE("\x25\x48\x4f\x4d\x49\x45\x5f\x45\x53\x50\x38\x32\x36\x36\x5f\x46\x57\x25") {
strlcpy(Interface::get().brand, DEFAULT_BRAND, MAX_BRAND_LENGTH);
Interface::get().bootMode = HomieBootMode::UNDEFINED;
Interface::get().configurationAp.secured = false;
Interface::get().led.enabled = true;
Interface::get().led.pin = BUILTIN_LED;
Interface::get().led.on = LOW;
Interface::get().reset.idle = true;
Interface::get().reset.enabled = true;
Interface::get().reset.triggerPin = DEFAULT_RESET_PIN;
Interface::get().reset.triggerState = DEFAULT_RESET_STATE;
Interface::get().reset.triggerTime = DEFAULT_RESET_TIME;
Interface::get().reset.flaggedBySketch = false;
Interface::get().flaggedForSleep = false;
Interface::get().globalInputHandler = [](const HomieNode& node, const String& property, const HomieRange& range, const String& value) { return false; };
Interface::get().broadcastHandler = [](const String& level, const String& value) { return false; };
Interface::get().setupFunction = []() {};
Interface::get().loopFunction = []() {};
Interface::get().eventHandler = [](const HomieEvent& event) {};
Interface::get().ready = false;
Interface::get()._mqttClient = &_mqttClient;
Interface::get()._sendingPromise = &_sendingPromise;
Interface::get()._blinker = &_blinker;
Interface::get()._logger = &_logger;
Interface::get()._config = &_config;
DeviceId::generate();
}
HomieClass::~HomieClass() {
}
void HomieClass::_checkBeforeSetup(const __FlashStringHelper* functionName) const {
if (_setupCalled) {
String message;
message.concat(F("✖ "));
message.concat(functionName);
message.concat(F("(): has to be called before setup()"));
Helpers::abort(message);
}
}
void HomieClass::setup() {
_setupCalled = true;
// Check if firmware is set
if (!_firmwareSet) {
Helpers::abort(F("✖ Firmware name must be set before calling setup()"));
return; // never reached, here for clarity
}
// Check if default settings values are valid
bool defaultSettingsValuesValid = true;
for (IHomieSetting* iSetting : IHomieSetting::settings) {
if (iSetting->isBool()) {
HomieSetting<bool>* setting = static_cast<HomieSetting<bool>*>(iSetting);
if (!setting->isRequired() && !setting->validate(setting->get())) {
defaultSettingsValuesValid = false;
break;
}
} else if (iSetting->isLong()) {
HomieSetting<long>* setting = static_cast<HomieSetting<long>*>(iSetting);
if (!setting->isRequired() && !setting->validate(setting->get())) {
defaultSettingsValuesValid = false;
break;
}
} else if (iSetting->isDouble()) {
HomieSetting<double>* setting = static_cast<HomieSetting<double>*>(iSetting);
if (!setting->isRequired() && !setting->validate(setting->get())) {
defaultSettingsValuesValid = false;
break;
}
} else if (iSetting->isConstChar()) {
HomieSetting<const char*>* setting = static_cast<HomieSetting<const char*>*>(iSetting);
if (!setting->isRequired() && !setting->validate(setting->get())) {
defaultSettingsValuesValid = false;
break;
}
}
}
if (!defaultSettingsValuesValid) {
Helpers::abort(F("✖ Default setting value does not pass validator test"));
return; // never reached, here for clarity
}
// boot mode set during this boot by application before Homie.setup()
HomieBootMode _applicationHomieBootMode = Interface::get().bootMode;
// boot mode set before resetting the device. If application has defined a boot mode, this will be ignored
HomieBootMode _nextHomieBootMode = Interface::get().getConfig().getHomieBootModeOnNextBoot();
if (_nextHomieBootMode != HomieBootMode::UNDEFINED) {
Interface::get().getConfig().setHomieBootModeOnNextBoot(HomieBootMode::UNDEFINED);
}
HomieBootMode _selectedHomieBootMode = HomieBootMode::CONFIGURATION;
// select boot mode source
if (_applicationHomieBootMode != HomieBootMode::UNDEFINED) {
_selectedHomieBootMode = _applicationHomieBootMode;
} else if (_nextHomieBootMode != HomieBootMode::UNDEFINED) {
_selectedHomieBootMode = _nextHomieBootMode;
} else {
_selectedHomieBootMode = HomieBootMode::NORMAL;
}
// validate selected mode and fallback as needed
if (_selectedHomieBootMode == HomieBootMode::NORMAL && !Interface::get().getConfig().load()) {
Interface::get().getLogger() << F("Configuration invalid. Using CONFIG MODE") << endl;
_selectedHomieBootMode = HomieBootMode::CONFIGURATION;
}
// run selected mode
if (_selectedHomieBootMode == HomieBootMode::NORMAL) {
_boot = &_bootNormal;
Interface::get().event.type = HomieEventType::NORMAL_MODE;
Interface::get().eventHandler(Interface::get().event);
} else if (_selectedHomieBootMode == HomieBootMode::CONFIGURATION) {
_boot = &_bootConfig;
Interface::get().event.type = HomieEventType::CONFIGURATION_MODE;
Interface::get().eventHandler(Interface::get().event);
} else if (_selectedHomieBootMode == HomieBootMode::STANDALONE) {
_boot = &_bootStandalone;
Interface::get().event.type = HomieEventType::STANDALONE_MODE;
Interface::get().eventHandler(Interface::get().event);
} else {
Helpers::abort(F("✖ Boot mode invalid"));
return; // never reached, here for clarity
}
_boot->setup();
}
void HomieClass::loop() {
_boot->loop();
if (_flaggedForReboot && Interface::get().reset.idle) {
Interface::get().getLogger() << F("Device is idle") << endl;
Interface::get().getLogger() << F("Triggering ABOUT_TO_RESET event...") << endl;
Interface::get().event.type = HomieEventType::ABOUT_TO_RESET;
Interface::get().eventHandler(Interface::get().event);
Interface::get().getLogger() << F("↻ Rebooting device...") << endl;
Serial.flush();
ESP.restart();
}
}
HomieClass& HomieClass::disableLogging() {
_checkBeforeSetup(F("disableLogging"));
Interface::get().getLogger().setLogging(false);
return *this;
}
HomieClass& HomieClass::setLoggingPrinter(Print* printer) {
_checkBeforeSetup(F("setLoggingPrinter"));
Interface::get().getLogger().setPrinter(printer);
return *this;
}
HomieClass& HomieClass::disableLedFeedback() {
_checkBeforeSetup(F("disableLedFeedback"));
Interface::get().led.enabled = false;
return *this;
}
HomieClass& HomieClass::setLedPin(uint8_t pin, uint8_t on) {
_checkBeforeSetup(F("setLedPin"));
Interface::get().led.pin = pin;
Interface::get().led.on = on;
return *this;
}
HomieClass& HomieClass::setConfigurationApPassword(const char* password) {
_checkBeforeSetup(F("setConfigurationApPassword"));
Interface::get().configurationAp.secured = true;
strlcpy(Interface::get().configurationAp.password, password, MAX_WIFI_PASSWORD_LENGTH);
}
void HomieClass::__setFirmware(const char* name, const char* version) {
_checkBeforeSetup(F("setFirmware"));
if (strlen(name) + 1 - 10 > MAX_FIRMWARE_NAME_LENGTH || strlen(version) + 1 - 10 > MAX_FIRMWARE_VERSION_LENGTH) {
Helpers::abort(F("✖ setFirmware(): either the name or version string is too long"));
return; // never reached, here for clarity
}
strncpy(Interface::get().firmware.name, name + 5, strlen(name) - 10);
Interface::get().firmware.name[strlen(name) - 10] = '\0';
strncpy(Interface::get().firmware.version, version + 5, strlen(version) - 10);
Interface::get().firmware.version[strlen(version) - 10] = '\0';
_firmwareSet = true;
}
void HomieClass::__setBrand(const char* brand) const {
_checkBeforeSetup(F("setBrand"));
if (strlen(brand) + 1 - 10 > MAX_BRAND_LENGTH) {
Helpers::abort(F("✖ setBrand(): the brand string is too long"));
return; // never reached, here for clarity
}
strncpy(Interface::get().brand, brand + 5, strlen(brand) - 10);
Interface::get().brand[strlen(brand) - 10] = '\0';
}
void HomieClass::reset() {
Interface::get().reset.flaggedBySketch = true;
}
void HomieClass::reboot() {
_flaggedForReboot = true;
}
void HomieClass::setIdle(bool idle) {
Interface::get().reset.idle = idle;
}
HomieClass& HomieClass::setGlobalInputHandler(const GlobalInputHandler& globalInputHandler) {
_checkBeforeSetup(F("setGlobalInputHandler"));
Interface::get().globalInputHandler = globalInputHandler;
return *this;
}
HomieClass& HomieClass::setBroadcastHandler(const BroadcastHandler& broadcastHandler) {
_checkBeforeSetup(F("setBroadcastHandler"));
Interface::get().broadcastHandler = broadcastHandler;
return *this;
}
HomieClass& HomieClass::setSetupFunction(const OperationFunction& function) {
_checkBeforeSetup(F("setSetupFunction"));
Interface::get().setupFunction = function;
return *this;
}
HomieClass& HomieClass::setLoopFunction(const OperationFunction& function) {
_checkBeforeSetup(F("setLoopFunction"));
Interface::get().loopFunction = function;
return *this;
}
HomieClass& HomieClass::setHomieBootMode(HomieBootMode bootMode) {
_checkBeforeSetup(F("setHomieBootMode"));
Interface::get().bootMode = bootMode;
return *this;
}
HomieClass& HomieClass::setHomieBootModeOnNextBoot(HomieBootMode bootMode) {
Interface::get().getConfig().setHomieBootModeOnNextBoot(bootMode);
return *this;
}
bool HomieClass::isConfigured() {
return Interface::get().getConfig().load();
}
bool HomieClass::isConnected() {
return Interface::get().ready;
}
HomieClass& HomieClass::onEvent(const EventHandler& handler) {
_checkBeforeSetup(F("onEvent"));
Interface::get().eventHandler = handler;
return *this;
}
HomieClass& HomieClass::setResetTrigger(uint8_t pin, uint8_t state, uint16_t time) {
_checkBeforeSetup(F("setResetTrigger"));
Interface::get().reset.enabled = true;
Interface::get().reset.triggerPin = pin;
Interface::get().reset.triggerState = state;
Interface::get().reset.triggerTime = time;
return *this;
}
HomieClass& HomieClass::disableResetTrigger() {
_checkBeforeSetup(F("disableResetTrigger"));
Interface::get().reset.enabled = false;
return *this;
}
const ConfigStruct& HomieClass::getConfiguration() {
return Interface::get().getConfig().get();
}
AsyncMqttClient& HomieClass::getMqttClient() {
return _mqttClient;
}
Logger& HomieClass::getLogger() {
return _logger;
}
void HomieClass::prepareToSleep() {
if (Interface::get().ready) {
Interface::get().flaggedForSleep = true;
} else {
Interface::get().getLogger() << F("Triggering READY_TO_SLEEP event...") << endl;
Interface::get().event.type = HomieEventType::READY_TO_SLEEP;
Interface::get().eventHandler(Interface::get().event);
}
}
HomieClass Homie;
<commit_msg>:bug: Fix not returning a value in setConfigurationApPassword (#378)<commit_after>#include "Homie.hpp"
using namespace HomieInternals;
HomieClass::HomieClass()
: _setupCalled(false)
, _firmwareSet(false)
, __HOMIE_SIGNATURE("\x25\x48\x4f\x4d\x49\x45\x5f\x45\x53\x50\x38\x32\x36\x36\x5f\x46\x57\x25") {
strlcpy(Interface::get().brand, DEFAULT_BRAND, MAX_BRAND_LENGTH);
Interface::get().bootMode = HomieBootMode::UNDEFINED;
Interface::get().configurationAp.secured = false;
Interface::get().led.enabled = true;
Interface::get().led.pin = BUILTIN_LED;
Interface::get().led.on = LOW;
Interface::get().reset.idle = true;
Interface::get().reset.enabled = true;
Interface::get().reset.triggerPin = DEFAULT_RESET_PIN;
Interface::get().reset.triggerState = DEFAULT_RESET_STATE;
Interface::get().reset.triggerTime = DEFAULT_RESET_TIME;
Interface::get().reset.flaggedBySketch = false;
Interface::get().flaggedForSleep = false;
Interface::get().globalInputHandler = [](const HomieNode& node, const String& property, const HomieRange& range, const String& value) { return false; };
Interface::get().broadcastHandler = [](const String& level, const String& value) { return false; };
Interface::get().setupFunction = []() {};
Interface::get().loopFunction = []() {};
Interface::get().eventHandler = [](const HomieEvent& event) {};
Interface::get().ready = false;
Interface::get()._mqttClient = &_mqttClient;
Interface::get()._sendingPromise = &_sendingPromise;
Interface::get()._blinker = &_blinker;
Interface::get()._logger = &_logger;
Interface::get()._config = &_config;
DeviceId::generate();
}
HomieClass::~HomieClass() {
}
void HomieClass::_checkBeforeSetup(const __FlashStringHelper* functionName) const {
if (_setupCalled) {
String message;
message.concat(F("✖ "));
message.concat(functionName);
message.concat(F("(): has to be called before setup()"));
Helpers::abort(message);
}
}
void HomieClass::setup() {
_setupCalled = true;
// Check if firmware is set
if (!_firmwareSet) {
Helpers::abort(F("✖ Firmware name must be set before calling setup()"));
return; // never reached, here for clarity
}
// Check if default settings values are valid
bool defaultSettingsValuesValid = true;
for (IHomieSetting* iSetting : IHomieSetting::settings) {
if (iSetting->isBool()) {
HomieSetting<bool>* setting = static_cast<HomieSetting<bool>*>(iSetting);
if (!setting->isRequired() && !setting->validate(setting->get())) {
defaultSettingsValuesValid = false;
break;
}
} else if (iSetting->isLong()) {
HomieSetting<long>* setting = static_cast<HomieSetting<long>*>(iSetting);
if (!setting->isRequired() && !setting->validate(setting->get())) {
defaultSettingsValuesValid = false;
break;
}
} else if (iSetting->isDouble()) {
HomieSetting<double>* setting = static_cast<HomieSetting<double>*>(iSetting);
if (!setting->isRequired() && !setting->validate(setting->get())) {
defaultSettingsValuesValid = false;
break;
}
} else if (iSetting->isConstChar()) {
HomieSetting<const char*>* setting = static_cast<HomieSetting<const char*>*>(iSetting);
if (!setting->isRequired() && !setting->validate(setting->get())) {
defaultSettingsValuesValid = false;
break;
}
}
}
if (!defaultSettingsValuesValid) {
Helpers::abort(F("✖ Default setting value does not pass validator test"));
return; // never reached, here for clarity
}
// boot mode set during this boot by application before Homie.setup()
HomieBootMode _applicationHomieBootMode = Interface::get().bootMode;
// boot mode set before resetting the device. If application has defined a boot mode, this will be ignored
HomieBootMode _nextHomieBootMode = Interface::get().getConfig().getHomieBootModeOnNextBoot();
if (_nextHomieBootMode != HomieBootMode::UNDEFINED) {
Interface::get().getConfig().setHomieBootModeOnNextBoot(HomieBootMode::UNDEFINED);
}
HomieBootMode _selectedHomieBootMode = HomieBootMode::CONFIGURATION;
// select boot mode source
if (_applicationHomieBootMode != HomieBootMode::UNDEFINED) {
_selectedHomieBootMode = _applicationHomieBootMode;
} else if (_nextHomieBootMode != HomieBootMode::UNDEFINED) {
_selectedHomieBootMode = _nextHomieBootMode;
} else {
_selectedHomieBootMode = HomieBootMode::NORMAL;
}
// validate selected mode and fallback as needed
if (_selectedHomieBootMode == HomieBootMode::NORMAL && !Interface::get().getConfig().load()) {
Interface::get().getLogger() << F("Configuration invalid. Using CONFIG MODE") << endl;
_selectedHomieBootMode = HomieBootMode::CONFIGURATION;
}
// run selected mode
if (_selectedHomieBootMode == HomieBootMode::NORMAL) {
_boot = &_bootNormal;
Interface::get().event.type = HomieEventType::NORMAL_MODE;
Interface::get().eventHandler(Interface::get().event);
} else if (_selectedHomieBootMode == HomieBootMode::CONFIGURATION) {
_boot = &_bootConfig;
Interface::get().event.type = HomieEventType::CONFIGURATION_MODE;
Interface::get().eventHandler(Interface::get().event);
} else if (_selectedHomieBootMode == HomieBootMode::STANDALONE) {
_boot = &_bootStandalone;
Interface::get().event.type = HomieEventType::STANDALONE_MODE;
Interface::get().eventHandler(Interface::get().event);
} else {
Helpers::abort(F("✖ Boot mode invalid"));
return; // never reached, here for clarity
}
_boot->setup();
}
void HomieClass::loop() {
_boot->loop();
if (_flaggedForReboot && Interface::get().reset.idle) {
Interface::get().getLogger() << F("Device is idle") << endl;
Interface::get().getLogger() << F("Triggering ABOUT_TO_RESET event...") << endl;
Interface::get().event.type = HomieEventType::ABOUT_TO_RESET;
Interface::get().eventHandler(Interface::get().event);
Interface::get().getLogger() << F("↻ Rebooting device...") << endl;
Serial.flush();
ESP.restart();
}
}
HomieClass& HomieClass::disableLogging() {
_checkBeforeSetup(F("disableLogging"));
Interface::get().getLogger().setLogging(false);
return *this;
}
HomieClass& HomieClass::setLoggingPrinter(Print* printer) {
_checkBeforeSetup(F("setLoggingPrinter"));
Interface::get().getLogger().setPrinter(printer);
return *this;
}
HomieClass& HomieClass::disableLedFeedback() {
_checkBeforeSetup(F("disableLedFeedback"));
Interface::get().led.enabled = false;
return *this;
}
HomieClass& HomieClass::setLedPin(uint8_t pin, uint8_t on) {
_checkBeforeSetup(F("setLedPin"));
Interface::get().led.pin = pin;
Interface::get().led.on = on;
return *this;
}
HomieClass& HomieClass::setConfigurationApPassword(const char* password) {
_checkBeforeSetup(F("setConfigurationApPassword"));
Interface::get().configurationAp.secured = true;
strlcpy(Interface::get().configurationAp.password, password, MAX_WIFI_PASSWORD_LENGTH);
return *this;
}
void HomieClass::__setFirmware(const char* name, const char* version) {
_checkBeforeSetup(F("setFirmware"));
if (strlen(name) + 1 - 10 > MAX_FIRMWARE_NAME_LENGTH || strlen(version) + 1 - 10 > MAX_FIRMWARE_VERSION_LENGTH) {
Helpers::abort(F("✖ setFirmware(): either the name or version string is too long"));
return; // never reached, here for clarity
}
strncpy(Interface::get().firmware.name, name + 5, strlen(name) - 10);
Interface::get().firmware.name[strlen(name) - 10] = '\0';
strncpy(Interface::get().firmware.version, version + 5, strlen(version) - 10);
Interface::get().firmware.version[strlen(version) - 10] = '\0';
_firmwareSet = true;
}
void HomieClass::__setBrand(const char* brand) const {
_checkBeforeSetup(F("setBrand"));
if (strlen(brand) + 1 - 10 > MAX_BRAND_LENGTH) {
Helpers::abort(F("✖ setBrand(): the brand string is too long"));
return; // never reached, here for clarity
}
strncpy(Interface::get().brand, brand + 5, strlen(brand) - 10);
Interface::get().brand[strlen(brand) - 10] = '\0';
}
void HomieClass::reset() {
Interface::get().reset.flaggedBySketch = true;
}
void HomieClass::reboot() {
_flaggedForReboot = true;
}
void HomieClass::setIdle(bool idle) {
Interface::get().reset.idle = idle;
}
HomieClass& HomieClass::setGlobalInputHandler(const GlobalInputHandler& globalInputHandler) {
_checkBeforeSetup(F("setGlobalInputHandler"));
Interface::get().globalInputHandler = globalInputHandler;
return *this;
}
HomieClass& HomieClass::setBroadcastHandler(const BroadcastHandler& broadcastHandler) {
_checkBeforeSetup(F("setBroadcastHandler"));
Interface::get().broadcastHandler = broadcastHandler;
return *this;
}
HomieClass& HomieClass::setSetupFunction(const OperationFunction& function) {
_checkBeforeSetup(F("setSetupFunction"));
Interface::get().setupFunction = function;
return *this;
}
HomieClass& HomieClass::setLoopFunction(const OperationFunction& function) {
_checkBeforeSetup(F("setLoopFunction"));
Interface::get().loopFunction = function;
return *this;
}
HomieClass& HomieClass::setHomieBootMode(HomieBootMode bootMode) {
_checkBeforeSetup(F("setHomieBootMode"));
Interface::get().bootMode = bootMode;
return *this;
}
HomieClass& HomieClass::setHomieBootModeOnNextBoot(HomieBootMode bootMode) {
Interface::get().getConfig().setHomieBootModeOnNextBoot(bootMode);
return *this;
}
bool HomieClass::isConfigured() {
return Interface::get().getConfig().load();
}
bool HomieClass::isConnected() {
return Interface::get().ready;
}
HomieClass& HomieClass::onEvent(const EventHandler& handler) {
_checkBeforeSetup(F("onEvent"));
Interface::get().eventHandler = handler;
return *this;
}
HomieClass& HomieClass::setResetTrigger(uint8_t pin, uint8_t state, uint16_t time) {
_checkBeforeSetup(F("setResetTrigger"));
Interface::get().reset.enabled = true;
Interface::get().reset.triggerPin = pin;
Interface::get().reset.triggerState = state;
Interface::get().reset.triggerTime = time;
return *this;
}
HomieClass& HomieClass::disableResetTrigger() {
_checkBeforeSetup(F("disableResetTrigger"));
Interface::get().reset.enabled = false;
return *this;
}
const ConfigStruct& HomieClass::getConfiguration() {
return Interface::get().getConfig().get();
}
AsyncMqttClient& HomieClass::getMqttClient() {
return _mqttClient;
}
Logger& HomieClass::getLogger() {
return _logger;
}
void HomieClass::prepareToSleep() {
if (Interface::get().ready) {
Interface::get().flaggedForSleep = true;
} else {
Interface::get().getLogger() << F("Triggering READY_TO_SLEEP event...") << endl;
Interface::get().event.type = HomieEventType::READY_TO_SLEEP;
Interface::get().eventHandler(Interface::get().event);
}
}
HomieClass Homie;
<|endoftext|> |
<commit_before>// Scintilla source code edit control
/** @file LexPS.cxx
** Lexer for PostScript
**
** Written by Nigel Hathaway.
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <fcntl.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static inline bool IsASelfDelimitingChar(const int ch) {
return (ch == '[' || ch == ']' || ch == '{' || ch == '}' ||
ch == '/' || ch == '<' || ch == '>' ||
ch == '(' || ch == ')' || ch == '%');
}
static inline bool IsAWhitespaceChar(const int ch) {
return (ch == ' ' || ch == '\t' || ch == '\r' ||
ch == '\n' || ch == '\f' || ch == '\0');
}
static bool IsABaseNDigit(const int ch, const int base) {
int maxdig = '9';
int letterext = -1;
if (base <= 10)
maxdig = '0' + base - 1;
else
letterext = base - 11;
return ((ch >= '0' && ch <= maxdig) ||
(ch >= 'A' && ch <= ('A' + letterext)) ||
(ch >= 'a' && ch <= ('a' + letterext)));
}
static inline bool IsABase85Char(const int ch) {
return ((ch >= '!' && ch <= 'u') || ch == 'z');
}
static void ColourisePSDoc(
unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords1 = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
StyleContext sc(startPos, length, initStyle, styler);
bool tokenizing = styler.GetPropertyInt("ps.tokenize") != 0;
int pslevel = styler.GetPropertyInt("ps.level", 3);
int lineCurrent = styler.GetLine(startPos);
int nestTextCurrent = 0;
if (lineCurrent > 0 && initStyle == SCE_PS_TEXT)
nestTextCurrent = styler.GetLineState(lineCurrent - 1);
int numRadix = 0;
bool numHasPoint = false;
bool numHasExponent = false;
bool numHasSign = false;
// Clear out existing tokenization
if (tokenizing && length > 0) {
styler.StartAt(startPos, static_cast<char>(INDIC2_MASK));
styler.ColourTo(startPos + length-1, 0);
styler.Flush();
styler.StartAt(startPos);
styler.StartSegment(startPos);
}
for (; sc.More(); sc.Forward()) {
if (sc.atLineStart)
lineCurrent = styler.GetLine(sc.currentPos);
// Determine if the current state should terminate.
if (sc.state == SCE_PS_COMMENT || sc.state == SCE_PS_DSC_VALUE) {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_PS_DSC_COMMENT) {
if (sc.ch == ':') {
sc.Forward();
if (!sc.atLineEnd)
sc.SetState(SCE_PS_DSC_VALUE);
else
sc.SetState(SCE_C_DEFAULT);
} else if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
} else if (IsAWhitespaceChar(sc.ch)) {
sc.ChangeState(SCE_PS_COMMENT);
}
} else if (sc.state == SCE_PS_NUMBER) {
if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) {
if ((sc.chPrev == '+' || sc.chPrev == '-' ||
sc.chPrev == 'E' || sc.chPrev == 'e') && numRadix == 0)
sc.ChangeState(SCE_PS_NAME);
sc.SetState(SCE_C_DEFAULT);
} else if (sc.ch == '#') {
if (numHasPoint || numHasExponent || numHasSign || numRadix != 0) {
sc.ChangeState(SCE_PS_NAME);
} else {
char szradix[5];
sc.GetCurrent(szradix, 4);
numRadix = atoi(szradix);
if (numRadix < 2 || numRadix > 36)
sc.ChangeState(SCE_PS_NAME);
}
} else if ((sc.ch == 'E' || sc.ch == 'e') && numRadix == 0) {
if (numHasExponent) {
sc.ChangeState(SCE_PS_NAME);
} else {
numHasExponent = true;
if (sc.chNext == '+' || sc.chNext == '-')
sc.Forward();
}
} else if (sc.ch == '.') {
if (numHasPoint || numHasExponent || numRadix != 0) {
sc.ChangeState(SCE_PS_NAME);
} else {
numHasPoint = true;
}
} else if (numRadix == 0) {
if (!IsABaseNDigit(sc.ch, 10))
sc.ChangeState(SCE_PS_NAME);
} else {
if (!IsABaseNDigit(sc.ch, numRadix))
sc.ChangeState(SCE_PS_NAME);
}
} else if (sc.state == SCE_PS_NAME || sc.state == SCE_PS_KEYWORD) {
if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if ((pslevel >= 1 && keywords1.InList(s)) ||
(pslevel >= 2 && keywords2.InList(s)) ||
(pslevel >= 3 && keywords3.InList(s)) ||
keywords4.InList(s) || keywords5.InList(s)) {
sc.ChangeState(SCE_PS_KEYWORD);
}
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_PS_LITERAL || sc.state == SCE_PS_IMMEVAL) {
if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch))
sc.SetState(SCE_C_DEFAULT);
} else if (sc.state == SCE_PS_PAREN_ARRAY || sc.state == SCE_PS_PAREN_DICT ||
sc.state == SCE_PS_PAREN_PROC) {
sc.SetState(SCE_C_DEFAULT);
} else if (sc.state == SCE_PS_TEXT) {
if (sc.ch == '(') {
nestTextCurrent++;
} else if (sc.ch == ')') {
if (--nestTextCurrent == 0)
sc.ForwardSetState(SCE_PS_DEFAULT);
} else if (sc.ch == '\\') {
sc.Forward();
}
} else if (sc.state == SCE_PS_HEXSTRING) {
if (sc.ch == '>') {
sc.ForwardSetState(SCE_PS_DEFAULT);
} else if (!IsABaseNDigit(sc.ch, 16) && !IsAWhitespaceChar(sc.ch)) {
sc.SetState(SCE_PS_HEXSTRING);
styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
}
} else if (sc.state == SCE_PS_BASE85STRING) {
if (sc.Match('~', '>')) {
sc.Forward();
sc.ForwardSetState(SCE_PS_DEFAULT);
} else if (!IsABase85Char(sc.ch) && !IsAWhitespaceChar(sc.ch)) {
sc.SetState(SCE_PS_BASE85STRING);
styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_C_DEFAULT) {
unsigned int tokenpos = sc.currentPos;
if (sc.ch == '[' || sc.ch == ']') {
sc.SetState(SCE_PS_PAREN_ARRAY);
} else if (sc.ch == '{' || sc.ch == '}') {
sc.SetState(SCE_PS_PAREN_PROC);
} else if (sc.ch == '/') {
if (sc.chNext == '/') {
sc.SetState(SCE_PS_IMMEVAL);
sc.Forward();
} else {
sc.SetState(SCE_PS_LITERAL);
}
} else if (sc.ch == '<') {
if (sc.chNext == '<') {
sc.SetState(SCE_PS_PAREN_DICT);
sc.Forward();
} else if (sc.chNext == '~') {
sc.SetState(SCE_PS_BASE85STRING);
sc.Forward();
} else {
sc.SetState(SCE_PS_HEXSTRING);
}
} else if (sc.ch == '>' && sc.chNext == '>') {
sc.SetState(SCE_PS_PAREN_DICT);
sc.Forward();
} else if (sc.ch == '>' || sc.ch == ')') {
sc.SetState(SCE_C_DEFAULT);
styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
} else if (sc.ch == '(') {
sc.SetState(SCE_PS_TEXT);
nestTextCurrent = 1;
} else if (sc.ch == '%') {
if (sc.chNext == '%' && sc.atLineStart) {
sc.SetState(SCE_PS_DSC_COMMENT);
sc.Forward();
if (sc.chNext == '+') {
sc.Forward();
sc.ForwardSetState(SCE_PS_DSC_VALUE);
}
} else {
sc.SetState(SCE_PS_COMMENT);
}
} else if ((sc.ch == '+' || sc.ch == '-' || sc.ch == '.') &&
IsABaseNDigit(sc.chNext, 10)) {
sc.SetState(SCE_PS_NUMBER);
numRadix = 0;
numHasPoint = (sc.ch == '.');
numHasExponent = false;
numHasSign = (sc.ch == '+' || sc.ch == '-');
} else if ((sc.ch == '+' || sc.ch == '-') && sc.chNext == '.' &&
IsABaseNDigit(sc.GetRelative(2), 10)) {
sc.SetState(SCE_PS_NUMBER);
numRadix = 0;
numHasPoint = false;
numHasExponent = false;
numHasSign = true;
} else if (IsABaseNDigit(sc.ch, 10)) {
sc.SetState(SCE_PS_NUMBER);
numRadix = 0;
numHasPoint = false;
numHasExponent = false;
numHasSign = false;
} else if (!IsAWhitespaceChar(sc.ch)) {
sc.SetState(SCE_PS_NAME);
}
// Mark the start of tokens
if (tokenizing && sc.state != SCE_C_DEFAULT && sc.state != SCE_PS_COMMENT &&
sc.state != SCE_PS_DSC_COMMENT && sc.state != SCE_PS_DSC_VALUE) {
styler.Flush();
styler.StartAt(tokenpos, static_cast<char>(INDIC2_MASK));
styler.ColourTo(tokenpos, INDIC2_MASK);
styler.Flush();
styler.StartAt(tokenpos);
styler.StartSegment(tokenpos);
}
}
if (sc.atLineEnd)
styler.SetLineState(lineCurrent, nestTextCurrent);
}
sc.Complete();
}
static void FoldPSDoc(unsigned int startPos, int length, int, WordList *[],
Accessor &styler) {
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelCurrent = SC_FOLDLEVELBASE;
if (lineCurrent > 0)
levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
int levelMinCurrent = levelCurrent;
int levelNext = levelCurrent;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style;
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); //mac??
if ((style & 31) == SCE_PS_PAREN_PROC) {
if (ch == '{') {
// Measure the minimum before a '{' to allow
// folding on "} {"
if (levelMinCurrent > levelNext) {
levelMinCurrent = levelNext;
}
levelNext++;
} else if (ch == '}') {
levelNext--;
}
}
if (atEOL) {
int levelUse = levelCurrent;
if (foldAtElse) {
levelUse = levelMinCurrent;
}
int lev = levelUse | levelNext << 16;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if (levelUse < levelNext)
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelCurrent = levelNext;
levelMinCurrent = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
}
static const char * const psWordListDesc[] = {
"PS Level 1 operators",
"PS Level 2 operators",
"PS Level 3 operators",
"RIP-specific operators",
"User-defined operators",
0
};
LexerModule lmPS(SCLEX_PS, ColourisePSDoc, "ps", FoldPSDoc, psWordListDesc);
<commit_msg>Added contact and license reference.<commit_after>// Scintilla source code edit control
/** @file LexPS.cxx
** Lexer for PostScript
**
** Written by Nigel Hathaway <nigel@bprj.co.uk>.
** The License.txt file describes the conditions under which this software may be distributed.
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <fcntl.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static inline bool IsASelfDelimitingChar(const int ch) {
return (ch == '[' || ch == ']' || ch == '{' || ch == '}' ||
ch == '/' || ch == '<' || ch == '>' ||
ch == '(' || ch == ')' || ch == '%');
}
static inline bool IsAWhitespaceChar(const int ch) {
return (ch == ' ' || ch == '\t' || ch == '\r' ||
ch == '\n' || ch == '\f' || ch == '\0');
}
static bool IsABaseNDigit(const int ch, const int base) {
int maxdig = '9';
int letterext = -1;
if (base <= 10)
maxdig = '0' + base - 1;
else
letterext = base - 11;
return ((ch >= '0' && ch <= maxdig) ||
(ch >= 'A' && ch <= ('A' + letterext)) ||
(ch >= 'a' && ch <= ('a' + letterext)));
}
static inline bool IsABase85Char(const int ch) {
return ((ch >= '!' && ch <= 'u') || ch == 'z');
}
static void ColourisePSDoc(
unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords1 = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
StyleContext sc(startPos, length, initStyle, styler);
bool tokenizing = styler.GetPropertyInt("ps.tokenize") != 0;
int pslevel = styler.GetPropertyInt("ps.level", 3);
int lineCurrent = styler.GetLine(startPos);
int nestTextCurrent = 0;
if (lineCurrent > 0 && initStyle == SCE_PS_TEXT)
nestTextCurrent = styler.GetLineState(lineCurrent - 1);
int numRadix = 0;
bool numHasPoint = false;
bool numHasExponent = false;
bool numHasSign = false;
// Clear out existing tokenization
if (tokenizing && length > 0) {
styler.StartAt(startPos, static_cast<char>(INDIC2_MASK));
styler.ColourTo(startPos + length-1, 0);
styler.Flush();
styler.StartAt(startPos);
styler.StartSegment(startPos);
}
for (; sc.More(); sc.Forward()) {
if (sc.atLineStart)
lineCurrent = styler.GetLine(sc.currentPos);
// Determine if the current state should terminate.
if (sc.state == SCE_PS_COMMENT || sc.state == SCE_PS_DSC_VALUE) {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_PS_DSC_COMMENT) {
if (sc.ch == ':') {
sc.Forward();
if (!sc.atLineEnd)
sc.SetState(SCE_PS_DSC_VALUE);
else
sc.SetState(SCE_C_DEFAULT);
} else if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
} else if (IsAWhitespaceChar(sc.ch)) {
sc.ChangeState(SCE_PS_COMMENT);
}
} else if (sc.state == SCE_PS_NUMBER) {
if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) {
if ((sc.chPrev == '+' || sc.chPrev == '-' ||
sc.chPrev == 'E' || sc.chPrev == 'e') && numRadix == 0)
sc.ChangeState(SCE_PS_NAME);
sc.SetState(SCE_C_DEFAULT);
} else if (sc.ch == '#') {
if (numHasPoint || numHasExponent || numHasSign || numRadix != 0) {
sc.ChangeState(SCE_PS_NAME);
} else {
char szradix[5];
sc.GetCurrent(szradix, 4);
numRadix = atoi(szradix);
if (numRadix < 2 || numRadix > 36)
sc.ChangeState(SCE_PS_NAME);
}
} else if ((sc.ch == 'E' || sc.ch == 'e') && numRadix == 0) {
if (numHasExponent) {
sc.ChangeState(SCE_PS_NAME);
} else {
numHasExponent = true;
if (sc.chNext == '+' || sc.chNext == '-')
sc.Forward();
}
} else if (sc.ch == '.') {
if (numHasPoint || numHasExponent || numRadix != 0) {
sc.ChangeState(SCE_PS_NAME);
} else {
numHasPoint = true;
}
} else if (numRadix == 0) {
if (!IsABaseNDigit(sc.ch, 10))
sc.ChangeState(SCE_PS_NAME);
} else {
if (!IsABaseNDigit(sc.ch, numRadix))
sc.ChangeState(SCE_PS_NAME);
}
} else if (sc.state == SCE_PS_NAME || sc.state == SCE_PS_KEYWORD) {
if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if ((pslevel >= 1 && keywords1.InList(s)) ||
(pslevel >= 2 && keywords2.InList(s)) ||
(pslevel >= 3 && keywords3.InList(s)) ||
keywords4.InList(s) || keywords5.InList(s)) {
sc.ChangeState(SCE_PS_KEYWORD);
}
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_PS_LITERAL || sc.state == SCE_PS_IMMEVAL) {
if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch))
sc.SetState(SCE_C_DEFAULT);
} else if (sc.state == SCE_PS_PAREN_ARRAY || sc.state == SCE_PS_PAREN_DICT ||
sc.state == SCE_PS_PAREN_PROC) {
sc.SetState(SCE_C_DEFAULT);
} else if (sc.state == SCE_PS_TEXT) {
if (sc.ch == '(') {
nestTextCurrent++;
} else if (sc.ch == ')') {
if (--nestTextCurrent == 0)
sc.ForwardSetState(SCE_PS_DEFAULT);
} else if (sc.ch == '\\') {
sc.Forward();
}
} else if (sc.state == SCE_PS_HEXSTRING) {
if (sc.ch == '>') {
sc.ForwardSetState(SCE_PS_DEFAULT);
} else if (!IsABaseNDigit(sc.ch, 16) && !IsAWhitespaceChar(sc.ch)) {
sc.SetState(SCE_PS_HEXSTRING);
styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
}
} else if (sc.state == SCE_PS_BASE85STRING) {
if (sc.Match('~', '>')) {
sc.Forward();
sc.ForwardSetState(SCE_PS_DEFAULT);
} else if (!IsABase85Char(sc.ch) && !IsAWhitespaceChar(sc.ch)) {
sc.SetState(SCE_PS_BASE85STRING);
styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_C_DEFAULT) {
unsigned int tokenpos = sc.currentPos;
if (sc.ch == '[' || sc.ch == ']') {
sc.SetState(SCE_PS_PAREN_ARRAY);
} else if (sc.ch == '{' || sc.ch == '}') {
sc.SetState(SCE_PS_PAREN_PROC);
} else if (sc.ch == '/') {
if (sc.chNext == '/') {
sc.SetState(SCE_PS_IMMEVAL);
sc.Forward();
} else {
sc.SetState(SCE_PS_LITERAL);
}
} else if (sc.ch == '<') {
if (sc.chNext == '<') {
sc.SetState(SCE_PS_PAREN_DICT);
sc.Forward();
} else if (sc.chNext == '~') {
sc.SetState(SCE_PS_BASE85STRING);
sc.Forward();
} else {
sc.SetState(SCE_PS_HEXSTRING);
}
} else if (sc.ch == '>' && sc.chNext == '>') {
sc.SetState(SCE_PS_PAREN_DICT);
sc.Forward();
} else if (sc.ch == '>' || sc.ch == ')') {
sc.SetState(SCE_C_DEFAULT);
styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
} else if (sc.ch == '(') {
sc.SetState(SCE_PS_TEXT);
nestTextCurrent = 1;
} else if (sc.ch == '%') {
if (sc.chNext == '%' && sc.atLineStart) {
sc.SetState(SCE_PS_DSC_COMMENT);
sc.Forward();
if (sc.chNext == '+') {
sc.Forward();
sc.ForwardSetState(SCE_PS_DSC_VALUE);
}
} else {
sc.SetState(SCE_PS_COMMENT);
}
} else if ((sc.ch == '+' || sc.ch == '-' || sc.ch == '.') &&
IsABaseNDigit(sc.chNext, 10)) {
sc.SetState(SCE_PS_NUMBER);
numRadix = 0;
numHasPoint = (sc.ch == '.');
numHasExponent = false;
numHasSign = (sc.ch == '+' || sc.ch == '-');
} else if ((sc.ch == '+' || sc.ch == '-') && sc.chNext == '.' &&
IsABaseNDigit(sc.GetRelative(2), 10)) {
sc.SetState(SCE_PS_NUMBER);
numRadix = 0;
numHasPoint = false;
numHasExponent = false;
numHasSign = true;
} else if (IsABaseNDigit(sc.ch, 10)) {
sc.SetState(SCE_PS_NUMBER);
numRadix = 0;
numHasPoint = false;
numHasExponent = false;
numHasSign = false;
} else if (!IsAWhitespaceChar(sc.ch)) {
sc.SetState(SCE_PS_NAME);
}
// Mark the start of tokens
if (tokenizing && sc.state != SCE_C_DEFAULT && sc.state != SCE_PS_COMMENT &&
sc.state != SCE_PS_DSC_COMMENT && sc.state != SCE_PS_DSC_VALUE) {
styler.Flush();
styler.StartAt(tokenpos, static_cast<char>(INDIC2_MASK));
styler.ColourTo(tokenpos, INDIC2_MASK);
styler.Flush();
styler.StartAt(tokenpos);
styler.StartSegment(tokenpos);
}
}
if (sc.atLineEnd)
styler.SetLineState(lineCurrent, nestTextCurrent);
}
sc.Complete();
}
static void FoldPSDoc(unsigned int startPos, int length, int, WordList *[],
Accessor &styler) {
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelCurrent = SC_FOLDLEVELBASE;
if (lineCurrent > 0)
levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
int levelMinCurrent = levelCurrent;
int levelNext = levelCurrent;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style;
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); //mac??
if ((style & 31) == SCE_PS_PAREN_PROC) {
if (ch == '{') {
// Measure the minimum before a '{' to allow
// folding on "} {"
if (levelMinCurrent > levelNext) {
levelMinCurrent = levelNext;
}
levelNext++;
} else if (ch == '}') {
levelNext--;
}
}
if (atEOL) {
int levelUse = levelCurrent;
if (foldAtElse) {
levelUse = levelMinCurrent;
}
int lev = levelUse | levelNext << 16;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if (levelUse < levelNext)
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelCurrent = levelNext;
levelMinCurrent = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
}
static const char * const psWordListDesc[] = {
"PS Level 1 operators",
"PS Level 2 operators",
"PS Level 3 operators",
"RIP-specific operators",
"User-defined operators",
0
};
LexerModule lmPS(SCLEX_PS, ColourisePSDoc, "ps", FoldPSDoc, psWordListDesc);
<|endoftext|> |
<commit_before>#include <iostream>
#include <set>
#include <sstream>
#include <algorithm>
#include "Lower.h"
#include "AddImageChecks.h"
#include "AddParameterChecks.h"
#include "AllocationBoundsInference.h"
#include "Bounds.h"
#include "BoundsInference.h"
#include "CSE.h"
#include "Debug.h"
#include "DebugToFile.h"
#include "DeepCopy.h"
#include "Deinterleave.h"
#include "EarlyFree.h"
#include "FindCalls.h"
#include "Function.h"
#include "FuseGPUThreadLoops.h"
#include "FuzzFloatStores.h"
#include "HexagonOffload.h"
#include "InjectHostDevBufferCopies.h"
#include "InjectImageIntrinsics.h"
#include "InjectOpenGLIntrinsics.h"
#include "Inline.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "IRPrinter.h"
#include "LoopCarry.h"
#include "Memoization.h"
#include "PartitionLoops.h"
#include "Profiling.h"
#include "Qualify.h"
#include "RealizationOrder.h"
#include "RemoveDeadAllocations.h"
#include "RemoveTrivialForLoops.h"
#include "RemoveUndef.h"
#include "Sanitizers.h"
#include "ScheduleFunctions.h"
#include "SelectGPUAPI.h"
#include "SkipStages.h"
#include "SlidingWindow.h"
#include "Simplify.h"
#include "SimplifySpecializations.h"
#include "StorageFlattening.h"
#include "StorageFolding.h"
#include "Substitute.h"
#include "Tracing.h"
#include "TrimNoOps.h"
#include "UnifyDuplicateLets.h"
#include "UniquifyVariableNames.h"
#include "UnrollLoops.h"
#include "VaryingAttributes.h"
#include "VectorizeLoops.h"
#include "WrapCalls.h"
namespace Halide {
namespace Internal {
using std::set;
using std::ostringstream;
using std::string;
using std::vector;
using std::map;
Stmt lower(vector<Function> outputs, const string &pipeline_name, const Target &t, const vector<IRMutator *> &custom_passes) {
// Compute an environment
map<string, Function> env;
for (Function f : outputs) {
map<string, Function> more_funcs = find_transitive_calls(f);
env.insert(more_funcs.begin(), more_funcs.end());
}
// Create a deep-copy of the entire graph of Funcs.
std::tie(outputs, env) = deep_copy(outputs, env);
// Substitute in wrapper Funcs
env = wrap_func_calls(env);
// Compute a realization order
vector<string> order = realization_order(outputs, env);
// Try to simplify the RHS/LHS of a function definition by propagating its
// specializations' conditions
simplify_specializations(env);
bool any_memoized = false;
debug(1) << "Creating initial loop nests...\n";
Stmt s = schedule_functions(outputs, order, env, t, any_memoized);
debug(2) << "Lowering after creating initial loop nests:\n" << s << '\n';
if (any_memoized) {
debug(1) << "Injecting memoization...\n";
s = inject_memoization(s, env, pipeline_name, outputs);
debug(2) << "Lowering after injecting memoization:\n" << s << '\n';
} else {
debug(1) << "Skipping injecting memoization...\n";
}
debug(1) << "Injecting tracing...\n";
s = inject_tracing(s, pipeline_name, env, outputs);
debug(2) << "Lowering after injecting tracing:\n" << s << '\n';
debug(1) << "Adding checks for parameters\n";
s = add_parameter_checks(s, t);
debug(2) << "Lowering after injecting parameter checks:\n" << s << '\n';
// Compute the maximum and minimum possible value of each
// function. Used in later bounds inference passes.
debug(1) << "Computing bounds of each function's value\n";
FuncValueBounds func_bounds = compute_function_value_bounds(order, env);
// The checks will be in terms of the symbols defined by bounds
// inference.
debug(1) << "Adding checks for images\n";
s = add_image_checks(s, outputs, t, order, env, func_bounds);
debug(2) << "Lowering after injecting image checks:\n" << s << '\n';
// This pass injects nested definitions of variable names, so we
// can't simplify statements from here until we fix them up. (We
// can still simplify Exprs).
debug(1) << "Performing computation bounds inference...\n";
s = bounds_inference(s, outputs, order, env, func_bounds);
debug(2) << "Lowering after computation bounds inference:\n" << s << '\n';
debug(1) << "Performing sliding window optimization...\n";
s = sliding_window(s, env);
debug(2) << "Lowering after sliding window:\n" << s << '\n';
debug(1) << "Performing allocation bounds inference...\n";
s = allocation_bounds_inference(s, env, func_bounds);
debug(2) << "Lowering after allocation bounds inference:\n" << s << '\n';
debug(1) << "Removing code that depends on undef values...\n";
s = remove_undef(s);
debug(2) << "Lowering after removing code that depends on undef values:\n" << s << "\n\n";
// This uniquifies the variable names, so we're good to simplify
// after this point. This lets later passes assume syntactic
// equivalence means semantic equivalence.
debug(1) << "Uniquifying variable names...\n";
s = uniquify_variable_names(s);
debug(2) << "Lowering after uniquifying variable names:\n" << s << "\n\n";
debug(1) << "Performing storage folding optimization...\n";
s = storage_folding(s, env);
debug(2) << "Lowering after storage folding:\n" << s << '\n';
debug(1) << "Injecting debug_to_file calls...\n";
s = debug_to_file(s, outputs, env);
debug(2) << "Lowering after injecting debug_to_file calls:\n" << s << '\n';
debug(1) << "Simplifying...\n"; // without removing dead lets, because storage flattening needs the strides
s = simplify(s, false);
debug(2) << "Lowering after first simplification:\n" << s << "\n\n";
debug(1) << "Dynamically skipping stages...\n";
s = skip_stages(s, order);
debug(2) << "Lowering after dynamically skipping stages:\n" << s << "\n\n";
if (t.has_feature(Target::OpenGL) || t.has_feature(Target::Renderscript)) {
debug(1) << "Injecting image intrinsics...\n";
s = inject_image_intrinsics(s, env);
debug(2) << "Lowering after image intrinsics:\n" << s << "\n\n";
}
debug(1) << "Performing storage flattening...\n";
s = storage_flattening(s, outputs, env, t);
debug(2) << "Lowering after storage flattening:\n" << s << "\n\n";
if (any_memoized) {
debug(1) << "Rewriting memoized allocations...\n";
s = rewrite_memoized_allocations(s, env);
debug(2) << "Lowering after rewriting memoized allocations:\n" << s << "\n\n";
} else {
debug(1) << "Skipping rewriting memoized allocations...\n";
}
if (t.has_gpu_feature() ||
t.has_feature(Target::OpenGLCompute) ||
t.has_feature(Target::OpenGL) ||
t.has_feature(Target::Renderscript) ||
(t.arch != Target::Hexagon && (t.features_any_of({Target::HVX_64, Target::HVX_128})))) {
debug(1) << "Selecting a GPU API for GPU loops...\n";
s = select_gpu_api(s, t);
debug(2) << "Lowering after selecting a GPU API:\n" << s << "\n\n";
debug(1) << "Injecting host <-> dev buffer copies...\n";
s = inject_host_dev_buffer_copies(s, t);
debug(2) << "Lowering after injecting host <-> dev buffer copies:\n" << s << "\n\n";
}
if (t.has_feature(Target::OpenGL)) {
debug(1) << "Injecting OpenGL texture intrinsics...\n";
s = inject_opengl_intrinsics(s);
debug(2) << "Lowering after OpenGL intrinsics:\n" << s << "\n\n";
}
if (t.has_gpu_feature() ||
t.has_feature(Target::OpenGLCompute) ||
t.has_feature(Target::Renderscript)) {
debug(1) << "Injecting per-block gpu synchronization...\n";
s = fuse_gpu_thread_loops(s);
debug(2) << "Lowering after injecting per-block gpu synchronization:\n" << s << "\n\n";
}
debug(1) << "Simplifying...\n";
s = simplify(s);
s = unify_duplicate_lets(s);
s = remove_trivial_for_loops(s);
debug(2) << "Lowering after second simplifcation:\n" << s << "\n\n";
debug(1) << "Unrolling...\n";
s = unroll_loops(s);
s = simplify(s);
debug(2) << "Lowering after unrolling:\n" << s << "\n\n";
debug(1) << "Vectorizing...\n";
s = vectorize_loops(s);
s = simplify(s);
debug(2) << "Lowering after vectorizing:\n" << s << "\n\n";
debug(1) << "Detecting vector interleavings...\n";
s = rewrite_interleavings(s);
s = simplify(s);
debug(2) << "Lowering after rewriting vector interleavings:\n" << s << "\n\n";
debug(1) << "Partitioning loops to simplify boundary conditions...\n";
s = partition_loops(s);
s = simplify(s);
debug(2) << "Lowering after partitioning loops:\n" << s << "\n\n";
debug(1) << "Trimming loops to the region over which they do something...\n";
s = trim_no_ops(s);
debug(2) << "Lowering after loop trimming:\n" << s << "\n\n";
debug(1) << "Injecting early frees...\n";
s = inject_early_frees(s);
debug(2) << "Lowering after injecting early frees:\n" << s << "\n\n";
if (t.has_feature(Target::Profile)) {
debug(1) << "Injecting profiling...\n";
s = inject_profiling(s, pipeline_name);
debug(2) << "Lowering after injecting profiling:\n" << s << "\n\n";
}
if (t.has_feature(Target::FuzzFloatStores)) {
debug(1) << "Fuzzing floating point stores...\n";
s = fuzz_float_stores(s);
debug(2) << "Lowering after fuzzing floating point stores:\n" << s << "\n\n";
}
debug(1) << "Simplifying...\n";
s = common_subexpression_elimination(s);
if (t.has_feature(Target::OpenGL)) {
debug(1) << "Detecting varying attributes...\n";
s = find_linear_expressions(s);
debug(2) << "Lowering after detecting varying attributes:\n" << s << "\n\n";
debug(1) << "Moving varying attribute expressions out of the shader...\n";
s = setup_gpu_vertex_buffer(s);
debug(2) << "Lowering after removing varying attributes:\n" << s << "\n\n";
}
s = remove_dead_allocations(s);
s = remove_trivial_for_loops(s);
s = simplify(s);
debug(1) << "Lowering after final simplification:\n" << s << "\n\n";
if (t.has_feature(Target::MSAN)) {
debug(1) << "Injecting MSAN helpers...\n";
s = inject_msan_helpers(s);
debug(2) << "Lowering after injecting MSAN helpers:\n" << s << "\n\n";
}
debug(1) << "Splitting off Hexagon offload...\n";
s = inject_hexagon_rpc(s, t);
debug(2) << "Lowering after splitting off Hexagon offload:\n" << s << '\n';
if (!custom_passes.empty()) {
for (size_t i = 0; i < custom_passes.size(); i++) {
debug(1) << "Running custom lowering pass " << i << "...\n";
s = custom_passes[i]->mutate(s);
debug(1) << "Lowering after custom pass " << i << ":\n" << s << "\n\n";
}
}
return s;
}
}
}
<commit_msg>Move MSAN injections to just after storage flattening<commit_after>#include <iostream>
#include <set>
#include <sstream>
#include <algorithm>
#include "Lower.h"
#include "AddImageChecks.h"
#include "AddParameterChecks.h"
#include "AllocationBoundsInference.h"
#include "Bounds.h"
#include "BoundsInference.h"
#include "CSE.h"
#include "Debug.h"
#include "DebugToFile.h"
#include "DeepCopy.h"
#include "Deinterleave.h"
#include "EarlyFree.h"
#include "FindCalls.h"
#include "Function.h"
#include "FuseGPUThreadLoops.h"
#include "FuzzFloatStores.h"
#include "HexagonOffload.h"
#include "InjectHostDevBufferCopies.h"
#include "InjectImageIntrinsics.h"
#include "InjectOpenGLIntrinsics.h"
#include "Inline.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "IRPrinter.h"
#include "LoopCarry.h"
#include "Memoization.h"
#include "PartitionLoops.h"
#include "Profiling.h"
#include "Qualify.h"
#include "RealizationOrder.h"
#include "RemoveDeadAllocations.h"
#include "RemoveTrivialForLoops.h"
#include "RemoveUndef.h"
#include "Sanitizers.h"
#include "ScheduleFunctions.h"
#include "SelectGPUAPI.h"
#include "SkipStages.h"
#include "SlidingWindow.h"
#include "Simplify.h"
#include "SimplifySpecializations.h"
#include "StorageFlattening.h"
#include "StorageFolding.h"
#include "Substitute.h"
#include "Tracing.h"
#include "TrimNoOps.h"
#include "UnifyDuplicateLets.h"
#include "UniquifyVariableNames.h"
#include "UnrollLoops.h"
#include "VaryingAttributes.h"
#include "VectorizeLoops.h"
#include "WrapCalls.h"
namespace Halide {
namespace Internal {
using std::set;
using std::ostringstream;
using std::string;
using std::vector;
using std::map;
Stmt lower(vector<Function> outputs, const string &pipeline_name, const Target &t, const vector<IRMutator *> &custom_passes) {
// Compute an environment
map<string, Function> env;
for (Function f : outputs) {
map<string, Function> more_funcs = find_transitive_calls(f);
env.insert(more_funcs.begin(), more_funcs.end());
}
// Create a deep-copy of the entire graph of Funcs.
std::tie(outputs, env) = deep_copy(outputs, env);
// Substitute in wrapper Funcs
env = wrap_func_calls(env);
// Compute a realization order
vector<string> order = realization_order(outputs, env);
// Try to simplify the RHS/LHS of a function definition by propagating its
// specializations' conditions
simplify_specializations(env);
bool any_memoized = false;
debug(1) << "Creating initial loop nests...\n";
Stmt s = schedule_functions(outputs, order, env, t, any_memoized);
debug(2) << "Lowering after creating initial loop nests:\n" << s << '\n';
if (any_memoized) {
debug(1) << "Injecting memoization...\n";
s = inject_memoization(s, env, pipeline_name, outputs);
debug(2) << "Lowering after injecting memoization:\n" << s << '\n';
} else {
debug(1) << "Skipping injecting memoization...\n";
}
debug(1) << "Injecting tracing...\n";
s = inject_tracing(s, pipeline_name, env, outputs);
debug(2) << "Lowering after injecting tracing:\n" << s << '\n';
debug(1) << "Adding checks for parameters\n";
s = add_parameter_checks(s, t);
debug(2) << "Lowering after injecting parameter checks:\n" << s << '\n';
// Compute the maximum and minimum possible value of each
// function. Used in later bounds inference passes.
debug(1) << "Computing bounds of each function's value\n";
FuncValueBounds func_bounds = compute_function_value_bounds(order, env);
// The checks will be in terms of the symbols defined by bounds
// inference.
debug(1) << "Adding checks for images\n";
s = add_image_checks(s, outputs, t, order, env, func_bounds);
debug(2) << "Lowering after injecting image checks:\n" << s << '\n';
// This pass injects nested definitions of variable names, so we
// can't simplify statements from here until we fix them up. (We
// can still simplify Exprs).
debug(1) << "Performing computation bounds inference...\n";
s = bounds_inference(s, outputs, order, env, func_bounds);
debug(2) << "Lowering after computation bounds inference:\n" << s << '\n';
debug(1) << "Performing sliding window optimization...\n";
s = sliding_window(s, env);
debug(2) << "Lowering after sliding window:\n" << s << '\n';
debug(1) << "Performing allocation bounds inference...\n";
s = allocation_bounds_inference(s, env, func_bounds);
debug(2) << "Lowering after allocation bounds inference:\n" << s << '\n';
debug(1) << "Removing code that depends on undef values...\n";
s = remove_undef(s);
debug(2) << "Lowering after removing code that depends on undef values:\n" << s << "\n\n";
// This uniquifies the variable names, so we're good to simplify
// after this point. This lets later passes assume syntactic
// equivalence means semantic equivalence.
debug(1) << "Uniquifying variable names...\n";
s = uniquify_variable_names(s);
debug(2) << "Lowering after uniquifying variable names:\n" << s << "\n\n";
debug(1) << "Performing storage folding optimization...\n";
s = storage_folding(s, env);
debug(2) << "Lowering after storage folding:\n" << s << '\n';
debug(1) << "Injecting debug_to_file calls...\n";
s = debug_to_file(s, outputs, env);
debug(2) << "Lowering after injecting debug_to_file calls:\n" << s << '\n';
debug(1) << "Simplifying...\n"; // without removing dead lets, because storage flattening needs the strides
s = simplify(s, false);
debug(2) << "Lowering after first simplification:\n" << s << "\n\n";
debug(1) << "Dynamically skipping stages...\n";
s = skip_stages(s, order);
debug(2) << "Lowering after dynamically skipping stages:\n" << s << "\n\n";
if (t.has_feature(Target::OpenGL) || t.has_feature(Target::Renderscript)) {
debug(1) << "Injecting image intrinsics...\n";
s = inject_image_intrinsics(s, env);
debug(2) << "Lowering after image intrinsics:\n" << s << "\n\n";
}
debug(1) << "Performing storage flattening...\n";
s = storage_flattening(s, outputs, env, t);
debug(2) << "Lowering after storage flattening:\n" << s << "\n\n";
if (t.has_feature(Target::MSAN)) {
debug(1) << "Injecting MSAN helpers...\n";
s = inject_msan_helpers(s);
debug(2) << "Lowering after injecting MSAN helpers:\n" << s << "\n\n";
}
if (any_memoized) {
debug(1) << "Rewriting memoized allocations...\n";
s = rewrite_memoized_allocations(s, env);
debug(2) << "Lowering after rewriting memoized allocations:\n" << s << "\n\n";
} else {
debug(1) << "Skipping rewriting memoized allocations...\n";
}
if (t.has_gpu_feature() ||
t.has_feature(Target::OpenGLCompute) ||
t.has_feature(Target::OpenGL) ||
t.has_feature(Target::Renderscript) ||
(t.arch != Target::Hexagon && (t.features_any_of({Target::HVX_64, Target::HVX_128})))) {
debug(1) << "Selecting a GPU API for GPU loops...\n";
s = select_gpu_api(s, t);
debug(2) << "Lowering after selecting a GPU API:\n" << s << "\n\n";
debug(1) << "Injecting host <-> dev buffer copies...\n";
s = inject_host_dev_buffer_copies(s, t);
debug(2) << "Lowering after injecting host <-> dev buffer copies:\n" << s << "\n\n";
}
if (t.has_feature(Target::OpenGL)) {
debug(1) << "Injecting OpenGL texture intrinsics...\n";
s = inject_opengl_intrinsics(s);
debug(2) << "Lowering after OpenGL intrinsics:\n" << s << "\n\n";
}
if (t.has_gpu_feature() ||
t.has_feature(Target::OpenGLCompute) ||
t.has_feature(Target::Renderscript)) {
debug(1) << "Injecting per-block gpu synchronization...\n";
s = fuse_gpu_thread_loops(s);
debug(2) << "Lowering after injecting per-block gpu synchronization:\n" << s << "\n\n";
}
debug(1) << "Simplifying...\n";
s = simplify(s);
s = unify_duplicate_lets(s);
s = remove_trivial_for_loops(s);
debug(2) << "Lowering after second simplifcation:\n" << s << "\n\n";
debug(1) << "Unrolling...\n";
s = unroll_loops(s);
s = simplify(s);
debug(2) << "Lowering after unrolling:\n" << s << "\n\n";
debug(1) << "Vectorizing...\n";
s = vectorize_loops(s);
s = simplify(s);
debug(2) << "Lowering after vectorizing:\n" << s << "\n\n";
debug(1) << "Detecting vector interleavings...\n";
s = rewrite_interleavings(s);
s = simplify(s);
debug(2) << "Lowering after rewriting vector interleavings:\n" << s << "\n\n";
debug(1) << "Partitioning loops to simplify boundary conditions...\n";
s = partition_loops(s);
s = simplify(s);
debug(2) << "Lowering after partitioning loops:\n" << s << "\n\n";
debug(1) << "Trimming loops to the region over which they do something...\n";
s = trim_no_ops(s);
debug(2) << "Lowering after loop trimming:\n" << s << "\n\n";
debug(1) << "Injecting early frees...\n";
s = inject_early_frees(s);
debug(2) << "Lowering after injecting early frees:\n" << s << "\n\n";
if (t.has_feature(Target::Profile)) {
debug(1) << "Injecting profiling...\n";
s = inject_profiling(s, pipeline_name);
debug(2) << "Lowering after injecting profiling:\n" << s << "\n\n";
}
if (t.has_feature(Target::FuzzFloatStores)) {
debug(1) << "Fuzzing floating point stores...\n";
s = fuzz_float_stores(s);
debug(2) << "Lowering after fuzzing floating point stores:\n" << s << "\n\n";
}
debug(1) << "Simplifying...\n";
s = common_subexpression_elimination(s);
if (t.has_feature(Target::OpenGL)) {
debug(1) << "Detecting varying attributes...\n";
s = find_linear_expressions(s);
debug(2) << "Lowering after detecting varying attributes:\n" << s << "\n\n";
debug(1) << "Moving varying attribute expressions out of the shader...\n";
s = setup_gpu_vertex_buffer(s);
debug(2) << "Lowering after removing varying attributes:\n" << s << "\n\n";
}
s = remove_dead_allocations(s);
s = remove_trivial_for_loops(s);
s = simplify(s);
debug(1) << "Lowering after final simplification:\n" << s << "\n\n";
debug(1) << "Splitting off Hexagon offload...\n";
s = inject_hexagon_rpc(s, t);
debug(2) << "Lowering after splitting off Hexagon offload:\n" << s << '\n';
if (!custom_passes.empty()) {
for (size_t i = 0; i < custom_passes.size(); i++) {
debug(1) << "Running custom lowering pass " << i << "...\n";
s = custom_passes[i]->mutate(s);
debug(1) << "Lowering after custom pass " << i << ":\n" << s << "\n\n";
}
}
return s;
}
}
}
<|endoftext|> |
<commit_before>#include <info/info.hpp>
#include <op/op.hpp>
#include <singleton.hpp>
#include <utility>
#include <algorithm>
using namespace MCPP;
namespace MCPP {
static const String name("Information Provider");
static const String identifier("info");
static const String summary("Provides information about various server internals.");
static const Word priority=1;
static const String info_banner="====INFORMATION====";
static const String log_prepend("Information Provider: ");
static const String mods_dir("info_mods");
static String help;
static const Regex split("\\s+");
Word Information::Priority () const noexcept {
return priority;
}
const String & Information::Name () const noexcept {
return name;
}
const String & Information::Identifier () const noexcept {
return identifier;
}
const String & Information::Help () const noexcept {
return help;
}
const String & Information::Summary () const noexcept {
return summary;
}
bool Information::Check (SmartPointer<Client> client) const {
return Ops::Get().IsOp(client->GetUsername());
}
Vector<InformationProvider *> Information::retrieve (const Regex & regex) {
Vector<InformationProvider *> retr;
for (auto * ip : providers)
if (regex.IsMatch(ip->Identifier()))
retr.Add(ip);
return retr;
}
InformationProvider * Information::retrieve (const String & name) {
for (auto * ip : providers)
if (name==ip->Identifier())
return ip;
return nullptr;
}
Vector<String> Information::AutoComplete (const String & args_str) const {
Vector<String> retr;
auto args=split.Split(args_str);
if (args.Count()<=1)
for (auto * ip : (
(args.Count()==0)
? providers
: const_cast<Information *>(this)->retrieve(
Regex(
String::Format(
"^{0}",
Regex::Escape(
args[0]
)
)
)
)
)) retr.Add(ip->Identifier());
return retr;
}
bool Information::Execute (SmartPointer<Client> client, const String & args_str, ChatMessage & message) {
// If there's no client, do nothing
if (client.IsNull()) return true;
auto args=split.Split(args_str);
// If there's no argument, or more
// than one, that's a syntax error
if (args.Count()!=1) return false;
// Attempt to retrieve the appropriate
// information provider. If there
// isn't one, that's a syntax error
auto * ip=retrieve(args[0]);
if (ip==nullptr) return false;
// Prepare a chat message
message << ChatStyle::Bold
<< ChatStyle::Yellow
<< info_banner
<< ChatFormat::Pop
<< ChatFormat::Pop
<< Newline;
// Get rest of chat message from
// provider
ip->Execute(message);
return true;
}
void Information::Install () {
// Install ourselves into the command
// module
Commands::Get().Add(this);
}
void Information::Add (InformationProvider * provider) {
if (provider!=nullptr) {
// Insert sorted
// Find insertion point
Word i=0;
for (
;
(i<providers.Count()) &&
(providers[i]->Identifier()<provider->Identifier());
++i
);
// Insert
providers.Insert(
provider,
i
);
// Rebuild help
//
// CONSIDER OPTIMIZING
help=String();
for (const auto * ip : providers) {
if (help.Size()!=0) help << Newline;
help << "/info " << ip->Identifier() << " - " << ip->Help();
}
}
}
static Singleton<Information> singleton;
Information & Information::Get () noexcept {
return singleton.Get();
}
}
extern "C" {
Module * Load () {
return &(singleton.Get());
}
void Unload () {
singleton.Destroy();
}
}
<commit_msg>/info Fix<commit_after>#include <info/info.hpp>
#include <op/op.hpp>
#include <singleton.hpp>
#include <utility>
#include <algorithm>
using namespace MCPP;
namespace MCPP {
static const String name("Information Provider");
static const String identifier("info");
static const String summary("Provides information about various server internals.");
static const Word priority=1;
static const String info_banner="====INFORMATION====";
static const String log_prepend("Information Provider: ");
static const String mods_dir("info_mods");
static String help;
static const Regex split("\\s+");
Word Information::Priority () const noexcept {
return priority;
}
const String & Information::Name () const noexcept {
return name;
}
const String & Information::Identifier () const noexcept {
return identifier;
}
const String & Information::Help () const noexcept {
return help;
}
const String & Information::Summary () const noexcept {
return summary;
}
bool Information::Check (SmartPointer<Client> client) const {
return Ops::Get().IsOp(client->GetUsername());
}
Vector<InformationProvider *> Information::retrieve (const Regex & regex) {
Vector<InformationProvider *> retr;
for (auto * ip : providers)
if (regex.IsMatch(ip->Identifier()))
retr.Add(ip);
return retr;
}
InformationProvider * Information::retrieve (const String & name) {
for (auto * ip : providers)
if (name==ip->Identifier())
return ip;
return nullptr;
}
Vector<String> Information::AutoComplete (const String & args_str) const {
Vector<String> retr;
auto args=split.Split(args_str);
if (args.Count()<=1)
for (auto * ip : (
(args.Count()==0)
? providers
: const_cast<Information *>(this)->retrieve(
Regex(
String::Format(
"^{0}",
Regex::Escape(
args[0]
)
)
)
)
)) retr.Add(ip->Identifier());
return retr;
}
bool Information::Execute (SmartPointer<Client>, const String & args_str, ChatMessage & message) {
auto args=split.Split(args_str);
// If there's no argument, or more
// than one, that's a syntax error
if (args.Count()!=1) return false;
// Attempt to retrieve the appropriate
// information provider. If there
// isn't one, that's a syntax error
auto * ip=retrieve(args[0]);
if (ip==nullptr) return false;
// Prepare a chat message
message << ChatStyle::Bold
<< ChatStyle::Yellow
<< info_banner
<< ChatFormat::Pop
<< ChatFormat::Pop
<< Newline;
// Get rest of chat message from
// provider
ip->Execute(message);
return true;
}
void Information::Install () {
// Install ourselves into the command
// module
Commands::Get().Add(this);
}
void Information::Add (InformationProvider * provider) {
if (provider!=nullptr) {
// Insert sorted
// Find insertion point
Word i=0;
for (
;
(i<providers.Count()) &&
(providers[i]->Identifier()<provider->Identifier());
++i
);
// Insert
providers.Insert(
provider,
i
);
// Rebuild help
//
// CONSIDER OPTIMIZING
help=String();
for (const auto * ip : providers) {
if (help.Size()!=0) help << Newline;
help << "/info " << ip->Identifier() << " - " << ip->Help();
}
}
}
static Singleton<Information> singleton;
Information & Information::Get () noexcept {
return singleton.Get();
}
}
extern "C" {
Module * Load () {
return &(singleton.Get());
}
void Unload () {
singleton.Destroy();
}
}
<|endoftext|> |
<commit_before>//
// (C) Jan de Vaan 2007-2010, all rights reserved. See the accompanying "License.txt" for licensed use.
//
#include "charls.h"
#include "util.h"
#include "jpegstreamreader.h"
#include "jpegstreamwriter.h"
#include "jpegmarkersegment.h"
using namespace std;
using namespace charls;
static void VerifyInput(const ByteStreamInfo& uncompressedStream, const JlsParameters& parameters)
{
if (!uncompressedStream.rawStream && !uncompressedStream.rawData)
throw CreateSystemError(ApiResult::InvalidJlsParameters, "rawStream or rawData needs to reference to something");
if (parameters.width < 1 || parameters.width > 65535)
throw CreateSystemError(ApiResult::InvalidJlsParameters, "width needs to be in the range [1, 65535]");
if (parameters.height < 1 || parameters.height > 65535)
throw CreateSystemError(ApiResult::InvalidJlsParameters, "height needs to be in the range [1, 65535]");
if (parameters.bitspersample < 2 || parameters.bitspersample > 16)
throw CreateSystemError(ApiResult::InvalidJlsParameters, "bitspersample needs to be in the range [2, 16]");
if (!(parameters.ilv == InterleaveMode::None || parameters.ilv == InterleaveMode::Sample || parameters.ilv == InterleaveMode::Line))
throw CreateSystemError(ApiResult::InvalidJlsParameters, "ilv needs to be set to a value of {None, Sample, Line}");
if (parameters.components < 1 || parameters.components > 255)
throw CreateSystemError(ApiResult::InvalidJlsParameters, "components needs to be in the range [1, 255]");
if (uncompressedStream.rawData)
{
if (uncompressedStream.count < size_t(parameters.height * parameters.width * parameters.components * (parameters.bitspersample > 8 ? 2 : 1)))
throw CreateSystemError(ApiResult::InvalidJlsParameters, "uncompressed size does not match with the other parameters");
}
switch (parameters.components)
{
case 3:
break;
case 4:
if (parameters.ilv == InterleaveMode::Sample)
throw CreateSystemError(ApiResult::InvalidJlsParameters, "ilv cannot be set to Sample in combination with components = 4");
break;
default:
if (parameters.ilv != InterleaveMode::None)
throw CreateSystemError(ApiResult::InvalidJlsParameters, "ilv can only be set to None in combination with components = 1");
break;
}
}
static ApiResult SystemErrorToCharLSError(const std::system_error& e)
{
return e.code().category() == CharLSCategoryInstance() ? static_cast<ApiResult>(e.code().value()) : ApiResult::UnspecifiedFailure;
}
static void ClearErrorMessage(char* errorMessage)
{
if (errorMessage)
{
errorMessage[0] = 0;
}
}
static void CopyWhatTextToErrorMessage(const std::system_error& e, char* errorMessage)
{
if (!errorMessage)
return;
if (e.code().category() == CharLSCategoryInstance())
{
ASSERT(strlen(e.what()) < 255);
strcpy(errorMessage, e.what());
}
else
{
errorMessage[0] = 0;
}
}
CHARLS_IMEXPORT(ApiResult) JpegLsEncodeStream(ByteStreamInfo compressedStreamInfo, size_t& pcbyteWritten,
ByteStreamInfo rawStreamInfo, const struct JlsParameters& parameters, char* errorMessage)
{
try
{
VerifyInput(rawStreamInfo, parameters);
JlsParameters info = parameters;
if (info.bytesperline == 0)
{
info.bytesperline = info.width * ((info.bitspersample + 7)/8);
if (info.ilv != InterleaveMode::None)
{
info.bytesperline *= info.components;
}
}
JpegStreamWriter writer;
if (info.jfif.version)
{
writer.AddSegment(JpegMarkerSegment::CreateJpegFileInterchangeFormatSegment(info.jfif));
}
writer.AddSegment(JpegMarkerSegment::CreateStartOfFrameSegment(info.width, info.height, info.bitspersample, info.components));
if (info.colorTransform != ColorTransformation::None)
{
writer.AddColorTransform(info.colorTransform);
}
if (info.ilv == InterleaveMode::None)
{
int32_t cbyteComp = info.width * info.height * ((info.bitspersample + 7) / 8);
for (int32_t component = 0; component < info.components; ++component)
{
writer.AddScan(rawStreamInfo, info);
SkipBytes(&rawStreamInfo, cbyteComp);
}
}
else
{
writer.AddScan(rawStreamInfo, info);
}
writer.Write(compressedStreamInfo);
pcbyteWritten = writer.GetBytesWritten();
ClearErrorMessage(errorMessage);
return ApiResult::OK;
}
catch (const std::system_error& e)
{
CopyWhatTextToErrorMessage(e, errorMessage);
return SystemErrorToCharLSError(e);
}
catch (...)
{
ClearErrorMessage(errorMessage);
return ApiResult::UnexpectedFailure;
}
}
CHARLS_IMEXPORT(ApiResult) JpegLsDecodeStream(ByteStreamInfo rawStream, ByteStreamInfo compressedStream, const JlsParameters* info, char* errorMessage)
{
try
{
JpegStreamReader reader(compressedStream);
if (info)
{
reader.SetInfo(*info);
}
reader.Read(rawStream);
ClearErrorMessage(errorMessage);
return ApiResult::OK;
}
catch (const std::system_error& e)
{
CopyWhatTextToErrorMessage(e, errorMessage);
return SystemErrorToCharLSError(e);
}
catch (...)
{
ClearErrorMessage(errorMessage);
return ApiResult::UnexpectedFailure;
}
}
CHARLS_IMEXPORT(ApiResult) JpegLsReadHeaderStream(ByteStreamInfo rawStreamInfo, JlsParameters* pparams, char* errorMessage)
{
try
{
JpegStreamReader reader(rawStreamInfo);
reader.ReadHeader();
reader.ReadStartOfScan(true);
*pparams = reader.GetMetadata();
ClearErrorMessage(errorMessage);
return ApiResult::OK;
}
catch (const std::system_error& e)
{
CopyWhatTextToErrorMessage(e, errorMessage);
return SystemErrorToCharLSError(e);
}
catch (...)
{
ClearErrorMessage(errorMessage);
return ApiResult::UnexpectedFailure;
}
}
extern "C"
{
CHARLS_IMEXPORT(ApiResult) JpegLsEncode(void* destination, size_t destinationLength, size_t* bytesWritten, const void* source, size_t sourceLength, const struct JlsParameters* parameters, char* errorMessage)
{
if (!destination || !bytesWritten || !source || !parameters)
return ApiResult::InvalidJlsParameters;
ByteStreamInfo rawStreamInfo = FromByteArray(source, sourceLength);
ByteStreamInfo compressedStreamInfo = FromByteArray(destination, destinationLength);
return JpegLsEncodeStream(compressedStreamInfo, *bytesWritten, rawStreamInfo, *parameters, errorMessage);
}
CHARLS_IMEXPORT(ApiResult) JpegLsReadHeader(const void* compressedData, size_t compressedLength, JlsParameters* pparams, char* errorMessage)
{
return JpegLsReadHeaderStream(FromByteArray(compressedData, compressedLength), pparams, errorMessage);
}
CHARLS_IMEXPORT(ApiResult) JpegLsDecode(void* destination, size_t destinationLength, const void* source, size_t sourceLength, const struct JlsParameters* info, char* errorMessage)
{
ByteStreamInfo compressedStream = FromByteArray(source, sourceLength);
ByteStreamInfo rawStreamInfo = FromByteArray(destination, destinationLength);
return JpegLsDecodeStream(rawStreamInfo, compressedStream, info, errorMessage);
}
CHARLS_IMEXPORT(ApiResult) JpegLsVerifyEncode(const void* uncompressedData, size_t uncompressedLength, const void* compressedData, size_t compressedLength, char* errorMessage)
{
try
{
JlsParameters info = JlsParameters();
auto error = JpegLsReadHeader(compressedData, compressedLength, &info, errorMessage);
if (error != ApiResult::OK)
return error;
ByteStreamInfo rawStreamInfo = FromByteArray(uncompressedData, uncompressedLength);
VerifyInput(rawStreamInfo, info);
JpegStreamWriter writer;
if (info.jfif.version)
{
writer.AddSegment(JpegMarkerSegment::CreateJpegFileInterchangeFormatSegment(info.jfif));
}
writer.AddSegment(JpegMarkerSegment::CreateStartOfFrameSegment(info.width, info.height, info.bitspersample, info.components));
if (info.ilv == InterleaveMode::None)
{
int32_t fieldLength = info.width * info.height * ((info.bitspersample + 7) / 8);
for (int32_t component = 0; component < info.components; ++component)
{
writer.AddScan(rawStreamInfo, info);
SkipBytes(&rawStreamInfo, fieldLength);
}
}
else
{
writer.AddScan(rawStreamInfo, info);
}
std::vector<uint8_t> rgbyteCompressed(compressedLength + 16);
memcpy(&rgbyteCompressed[0], compressedData, compressedLength);
writer.EnableCompare(true);
writer.Write(FromByteArray(&rgbyteCompressed[0], rgbyteCompressed.size()));
ClearErrorMessage(errorMessage);
return ApiResult::OK;
}
catch (const std::system_error& e)
{
CopyWhatTextToErrorMessage(e, errorMessage);
return SystemErrorToCharLSError(e);
}
catch (...)
{
ClearErrorMessage(errorMessage);
return ApiResult::UnexpectedFailure;
}
}
CHARLS_IMEXPORT(ApiResult) JpegLsDecodeRect(void* uncompressedData, size_t uncompressedLength, const void* compressedData, size_t compressedLength,
JlsRect roi, JlsParameters* info, char* errorMessage)
{
try
{
ByteStreamInfo compressedStream = FromByteArray(compressedData, compressedLength);
JpegStreamReader reader(compressedStream);
ByteStreamInfo rawStreamInfo = FromByteArray(uncompressedData, uncompressedLength);
if (info)
{
reader.SetInfo(*info);
}
reader.SetRect(roi);
reader.Read(rawStreamInfo);
ClearErrorMessage(errorMessage);
return ApiResult::OK;
}
catch (const std::system_error& e)
{
CopyWhatTextToErrorMessage(e, errorMessage);
return SystemErrorToCharLSError(e);
}
catch (...)
{
ClearErrorMessage(errorMessage);
return ApiResult::UnexpectedFailure;
}
}
}
<commit_msg>Removed not needed std:: namespace references.<commit_after>//
// (C) Jan de Vaan 2007-2010, all rights reserved. See the accompanying "License.txt" for licensed use.
//
#include "charls.h"
#include "util.h"
#include "jpegstreamreader.h"
#include "jpegstreamwriter.h"
#include "jpegmarkersegment.h"
using namespace std;
using namespace charls;
static void VerifyInput(const ByteStreamInfo& uncompressedStream, const JlsParameters& parameters)
{
if (!uncompressedStream.rawStream && !uncompressedStream.rawData)
throw CreateSystemError(ApiResult::InvalidJlsParameters, "rawStream or rawData needs to reference to something");
if (parameters.width < 1 || parameters.width > 65535)
throw CreateSystemError(ApiResult::InvalidJlsParameters, "width needs to be in the range [1, 65535]");
if (parameters.height < 1 || parameters.height > 65535)
throw CreateSystemError(ApiResult::InvalidJlsParameters, "height needs to be in the range [1, 65535]");
if (parameters.bitspersample < 2 || parameters.bitspersample > 16)
throw CreateSystemError(ApiResult::InvalidJlsParameters, "bitspersample needs to be in the range [2, 16]");
if (!(parameters.ilv == InterleaveMode::None || parameters.ilv == InterleaveMode::Sample || parameters.ilv == InterleaveMode::Line))
throw CreateSystemError(ApiResult::InvalidJlsParameters, "ilv needs to be set to a value of {None, Sample, Line}");
if (parameters.components < 1 || parameters.components > 255)
throw CreateSystemError(ApiResult::InvalidJlsParameters, "components needs to be in the range [1, 255]");
if (uncompressedStream.rawData)
{
if (uncompressedStream.count < size_t(parameters.height * parameters.width * parameters.components * (parameters.bitspersample > 8 ? 2 : 1)))
throw CreateSystemError(ApiResult::InvalidJlsParameters, "uncompressed size does not match with the other parameters");
}
switch (parameters.components)
{
case 3:
break;
case 4:
if (parameters.ilv == InterleaveMode::Sample)
throw CreateSystemError(ApiResult::InvalidJlsParameters, "ilv cannot be set to Sample in combination with components = 4");
break;
default:
if (parameters.ilv != InterleaveMode::None)
throw CreateSystemError(ApiResult::InvalidJlsParameters, "ilv can only be set to None in combination with components = 1");
break;
}
}
static ApiResult SystemErrorToCharLSError(const system_error& e)
{
return e.code().category() == CharLSCategoryInstance() ? static_cast<ApiResult>(e.code().value()) : ApiResult::UnspecifiedFailure;
}
static void ClearErrorMessage(char* errorMessage)
{
if (errorMessage)
{
errorMessage[0] = 0;
}
}
static void CopyWhatTextToErrorMessage(const system_error& e, char* errorMessage)
{
if (!errorMessage)
return;
if (e.code().category() == CharLSCategoryInstance())
{
ASSERT(strlen(e.what()) < 255);
strcpy(errorMessage, e.what());
}
else
{
errorMessage[0] = 0;
}
}
CHARLS_IMEXPORT(ApiResult) JpegLsEncodeStream(ByteStreamInfo compressedStreamInfo, size_t& pcbyteWritten,
ByteStreamInfo rawStreamInfo, const struct JlsParameters& parameters, char* errorMessage)
{
try
{
VerifyInput(rawStreamInfo, parameters);
JlsParameters info = parameters;
if (info.bytesperline == 0)
{
info.bytesperline = info.width * ((info.bitspersample + 7)/8);
if (info.ilv != InterleaveMode::None)
{
info.bytesperline *= info.components;
}
}
JpegStreamWriter writer;
if (info.jfif.version)
{
writer.AddSegment(JpegMarkerSegment::CreateJpegFileInterchangeFormatSegment(info.jfif));
}
writer.AddSegment(JpegMarkerSegment::CreateStartOfFrameSegment(info.width, info.height, info.bitspersample, info.components));
if (info.colorTransform != ColorTransformation::None)
{
writer.AddColorTransform(info.colorTransform);
}
if (info.ilv == InterleaveMode::None)
{
int32_t cbyteComp = info.width * info.height * ((info.bitspersample + 7) / 8);
for (int32_t component = 0; component < info.components; ++component)
{
writer.AddScan(rawStreamInfo, info);
SkipBytes(&rawStreamInfo, cbyteComp);
}
}
else
{
writer.AddScan(rawStreamInfo, info);
}
writer.Write(compressedStreamInfo);
pcbyteWritten = writer.GetBytesWritten();
ClearErrorMessage(errorMessage);
return ApiResult::OK;
}
catch (const system_error& e)
{
CopyWhatTextToErrorMessage(e, errorMessage);
return SystemErrorToCharLSError(e);
}
catch (...)
{
ClearErrorMessage(errorMessage);
return ApiResult::UnexpectedFailure;
}
}
CHARLS_IMEXPORT(ApiResult) JpegLsDecodeStream(ByteStreamInfo rawStream, ByteStreamInfo compressedStream, const JlsParameters* info, char* errorMessage)
{
try
{
JpegStreamReader reader(compressedStream);
if (info)
{
reader.SetInfo(*info);
}
reader.Read(rawStream);
ClearErrorMessage(errorMessage);
return ApiResult::OK;
}
catch (const system_error& e)
{
CopyWhatTextToErrorMessage(e, errorMessage);
return SystemErrorToCharLSError(e);
}
catch (...)
{
ClearErrorMessage(errorMessage);
return ApiResult::UnexpectedFailure;
}
}
CHARLS_IMEXPORT(ApiResult) JpegLsReadHeaderStream(ByteStreamInfo rawStreamInfo, JlsParameters* pparams, char* errorMessage)
{
try
{
JpegStreamReader reader(rawStreamInfo);
reader.ReadHeader();
reader.ReadStartOfScan(true);
*pparams = reader.GetMetadata();
ClearErrorMessage(errorMessage);
return ApiResult::OK;
}
catch (const std::system_error& e)
{
CopyWhatTextToErrorMessage(e, errorMessage);
return SystemErrorToCharLSError(e);
}
catch (...)
{
ClearErrorMessage(errorMessage);
return ApiResult::UnexpectedFailure;
}
}
extern "C"
{
CHARLS_IMEXPORT(ApiResult) JpegLsEncode(void* destination, size_t destinationLength, size_t* bytesWritten, const void* source, size_t sourceLength, const struct JlsParameters* parameters, char* errorMessage)
{
if (!destination || !bytesWritten || !source || !parameters)
return ApiResult::InvalidJlsParameters;
ByteStreamInfo rawStreamInfo = FromByteArray(source, sourceLength);
ByteStreamInfo compressedStreamInfo = FromByteArray(destination, destinationLength);
return JpegLsEncodeStream(compressedStreamInfo, *bytesWritten, rawStreamInfo, *parameters, errorMessage);
}
CHARLS_IMEXPORT(ApiResult) JpegLsReadHeader(const void* compressedData, size_t compressedLength, JlsParameters* pparams, char* errorMessage)
{
return JpegLsReadHeaderStream(FromByteArray(compressedData, compressedLength), pparams, errorMessage);
}
CHARLS_IMEXPORT(ApiResult) JpegLsDecode(void* destination, size_t destinationLength, const void* source, size_t sourceLength, const struct JlsParameters* info, char* errorMessage)
{
ByteStreamInfo compressedStream = FromByteArray(source, sourceLength);
ByteStreamInfo rawStreamInfo = FromByteArray(destination, destinationLength);
return JpegLsDecodeStream(rawStreamInfo, compressedStream, info, errorMessage);
}
CHARLS_IMEXPORT(ApiResult) JpegLsVerifyEncode(const void* uncompressedData, size_t uncompressedLength, const void* compressedData, size_t compressedLength, char* errorMessage)
{
try
{
JlsParameters info = JlsParameters();
auto error = JpegLsReadHeader(compressedData, compressedLength, &info, errorMessage);
if (error != ApiResult::OK)
return error;
ByteStreamInfo rawStreamInfo = FromByteArray(uncompressedData, uncompressedLength);
VerifyInput(rawStreamInfo, info);
JpegStreamWriter writer;
if (info.jfif.version)
{
writer.AddSegment(JpegMarkerSegment::CreateJpegFileInterchangeFormatSegment(info.jfif));
}
writer.AddSegment(JpegMarkerSegment::CreateStartOfFrameSegment(info.width, info.height, info.bitspersample, info.components));
if (info.ilv == InterleaveMode::None)
{
int32_t fieldLength = info.width * info.height * ((info.bitspersample + 7) / 8);
for (int32_t component = 0; component < info.components; ++component)
{
writer.AddScan(rawStreamInfo, info);
SkipBytes(&rawStreamInfo, fieldLength);
}
}
else
{
writer.AddScan(rawStreamInfo, info);
}
vector<uint8_t> rgbyteCompressed(compressedLength + 16);
memcpy(&rgbyteCompressed[0], compressedData, compressedLength);
writer.EnableCompare(true);
writer.Write(FromByteArray(&rgbyteCompressed[0], rgbyteCompressed.size()));
ClearErrorMessage(errorMessage);
return ApiResult::OK;
}
catch (const system_error& e)
{
CopyWhatTextToErrorMessage(e, errorMessage);
return SystemErrorToCharLSError(e);
}
catch (...)
{
ClearErrorMessage(errorMessage);
return ApiResult::UnexpectedFailure;
}
}
CHARLS_IMEXPORT(ApiResult) JpegLsDecodeRect(void* uncompressedData, size_t uncompressedLength, const void* compressedData, size_t compressedLength,
JlsRect roi, JlsParameters* info, char* errorMessage)
{
try
{
ByteStreamInfo compressedStream = FromByteArray(compressedData, compressedLength);
JpegStreamReader reader(compressedStream);
ByteStreamInfo rawStreamInfo = FromByteArray(uncompressedData, uncompressedLength);
if (info)
{
reader.SetInfo(*info);
}
reader.SetRect(roi);
reader.Read(rawStreamInfo);
ClearErrorMessage(errorMessage);
return ApiResult::OK;
}
catch (const system_error& e)
{
CopyWhatTextToErrorMessage(e, errorMessage);
return SystemErrorToCharLSError(e);
}
catch (...)
{
ClearErrorMessage(errorMessage);
return ApiResult::UnexpectedFailure;
}
}
}
<|endoftext|> |
<commit_before>/*
* fileio.hpp
*
* Created on: Oct 21, 2009
* Author: rasmussn
*/
#ifndef FILEIO_HPP_
#define FILEIO_HPP_
#include "io.h"
#include "../include/PVLayerLoc.h"
#include "../columns/Communicator.hpp"
namespace PV {
FILE * pvp_open_write_file(const char * filename, Communicator * comm, bool append);
int pvp_close_file(FILE * fp, Communicator * comm);
int pvp_read_header(const char * filename, Communicator * comm, double * time,
int * filetype, int * datatype, int params[], int * numParams);
int pvp_write_header(FILE * fp, Communicator * comm, double time, const PVLayerLoc * loc,
int filetype, int datatype, int subRecordSize,
bool extended, bool contiguous, unsigned int numParams);
int read(const char * filename, Communicator * comm, double * time, pvdata_t * data,
const PVLayerLoc * loc, int datatype, bool extended, bool contiguous);
int write(const char * filename, Communicator * comm, double time, pvdata_t * data,
const PVLayerLoc * loc, int datatype, bool extended, bool contiguous);
int writeActivitySparse(FILE * fp, Communicator * comm, double time, PVLayer * l);
int readWeights(PVPatch ** patches, int numPatches, const char * filename,
Communicator * comm, double * time, const PVLayerLoc * loc, bool extended);
int writeWeights(const char * filename, Communicator * comm, double time, bool append,
const PVLayerLoc * loc, int nxp, int nyp, int nfp, float minVal, float maxVal,
PVPatch ** patches, int numPatches);
int pvp_check_file_header(const PVLayerLoc * loc, int params[], int numParams);
} // namespace PV
#endif /* FILEIO_HPP_ */
<commit_msg>Made pvdata_t * data array const int write.<commit_after>/*
* fileio.hpp
*
* Created on: Oct 21, 2009
* Author: rasmussn
*/
#ifndef FILEIO_HPP_
#define FILEIO_HPP_
#include "io.h"
#include "../include/PVLayerLoc.h"
#include "../columns/Communicator.hpp"
namespace PV {
FILE * pvp_open_write_file(const char * filename, Communicator * comm, bool append);
int pvp_close_file(FILE * fp, Communicator * comm);
int pvp_read_header(const char * filename, Communicator * comm, double * time,
int * filetype, int * datatype, int params[], int * numParams);
int pvp_write_header(FILE * fp, Communicator * comm, double time, const PVLayerLoc * loc,
int filetype, int datatype, int subRecordSize,
bool extended, bool contiguous, unsigned int numParams);
int read(const char * filename, Communicator * comm, double * time, pvdata_t * data,
const PVLayerLoc * loc, int datatype, bool extended, bool contiguous);
int write(const char * filename, Communicator * comm, double time, const pvdata_t * data,
const PVLayerLoc * loc, int datatype, bool extended, bool contiguous);
int writeActivitySparse(FILE * fp, Communicator * comm, double time, PVLayer * l);
int readWeights(PVPatch ** patches, int numPatches, const char * filename,
Communicator * comm, double * time, const PVLayerLoc * loc, bool extended);
int writeWeights(const char * filename, Communicator * comm, double time, bool append,
const PVLayerLoc * loc, int nxp, int nyp, int nfp, float minVal, float maxVal,
PVPatch ** patches, int numPatches);
int pvp_check_file_header(const PVLayerLoc * loc, int params[], int numParams);
} // namespace PV
#endif /* FILEIO_HPP_ */
<|endoftext|> |
<commit_before>#include <microscopes/irm/model.hpp>
#include <microscopes/common/util.hpp>
#include <distributions/special.hpp>
#include <algorithm>
using namespace std;
using namespace distributions;
using namespace microscopes::common;
using namespace microscopes::common::sparse_ndarray;
using namespace microscopes::irm;
using namespace microscopes::irm::detail;
using namespace microscopes::models;
state::state(const vector<size_t> &domains,
const vector<relation_t> &relations)
: domains_(), relations_()
{
MICROSCOPES_DCHECK(domains.size(), "no domains given");
domains_.reserve(domains.size());
for (auto n : domains)
domains_.emplace_back(n);
for (auto s : domains)
MICROSCOPES_DCHECK(s, "empty domain given");
for (const auto &r : relations) {
for (auto d : r.domains_)
MICROSCOPES_DCHECK(d < domains.size(), "invalid domain given");
relations_.emplace_back(r);
}
domain_relations_.reserve(domains_.size());
for (size_t i = 0; i < domains_.size(); i++)
domain_relations_.emplace_back(domain_relations(i));
}
static inline void
AssertAllEntitiesAccounted(const vector<set<size_t>> &c, size_t n)
{
vector<bool> ents(n, false);
for (const auto &s : c)
for (auto eid : s) {
MICROSCOPES_DCHECK(eid < ents.size(), "bad eid given");
MICROSCOPES_DCHECK(!ents[eid], "eid given twice");
ents[eid] = true;
}
for (auto b : ents)
MICROSCOPES_DCHECK(b, "ent unaccounted for");
}
void
state::eids_to_gids_under_relation(
vector<size_t> &gids,
const vector<size_t> &eids,
const relation_t &desc) const
{
gids.clear();
gids.reserve(desc.domains_.size());
for (size_t i = 0; i < desc.domains_.size(); i++) {
MICROSCOPES_ASSERT(domains_[desc.domains_[i]].assignments()[eids[i]] != -1);
gids.push_back(domains_[desc.domains_[i]].assignments()[eids[i]]);
}
}
void
state::add_value_to_feature_group(
const vector<size_t> &gids,
const value_accessor &value,
relation_container_t &relation,
rng_t &rng,
float *acc_score)
{
MICROSCOPES_ASSERT(!value.anymasked());
shared_ptr<feature_group> group;
auto it = relation.suffstats_table_.find(gids);
if (it == relation.suffstats_table_.end()) {
group = relation.desc_.model_->create_feature_group(rng);
auto &ss = relation.suffstats_table_[gids];
ss.ident_ = relation.ident_gen_++;
ss.count_ = 1;
MICROSCOPES_ASSERT(!ss.ss_);
ss.ss_ = group;
MICROSCOPES_ASSERT(relation.ident_table_.find(ss.ident_) == relation.ident_table_.end());
relation.ident_table_[ss.ident_] = gids;
} else {
it->second.count_++;
group = it->second.ss_;
}
MICROSCOPES_ASSERT(group);
if (acc_score)
*acc_score += group->score_value(*relation.desc_.model_, value, rng);
group->add_value(*relation.desc_.model_, value, rng);
}
void
state::remove_value_from_feature_group(
const vector<size_t> &gids,
const value_accessor &value,
relation_container_t &relation,
rng_t &rng)
{
auto it = relation.suffstats_table_.find(gids);
MICROSCOPES_ASSERT(!value.anymasked());
MICROSCOPES_ASSERT(it != relation.suffstats_table_.end());
MICROSCOPES_ASSERT(it->second.count_);
MICROSCOPES_ASSERT(it->second.ss_);
MICROSCOPES_ASSERT(
relation.ident_table_.find(it->second.ident_) != relation.ident_table_.end() &&
relation.ident_table_[it->second.ident_] == gids);
it->second.ss_->remove_value(*relation.desc_.model_, value, rng);
it->second.count_--;
// XXX: unfortunately, we cannot clean this up now!! this is because for
// non-conjugate models, score_value() depends on the randomness we sampled
// in add_value_to_feature_group() for correctness. yes, this is quite hacky
// (for conjugate models, it is safe to delete here)
//
// note that, the point at which the suffstat can be GC-ed for non-conj
// models is when >= of the gids associated with it is no longer a valid gid
// (which should imply the count is zero also)
//if (!--it->second.count_) {
// relation.ident_table_.erase(it->second.ident_);
// relation.suffstats_table_.erase(it);
//}
}
void
state::iterate_over_entity_data(
size_t domain,
size_t eid,
const dataset_t &d,
function<void(size_t, const vector<size_t> &, const value_accessor &)> callback) const
{
for (const auto &dr : domain_relations_[domain]) {
auto &relation = relations_[dr.rel_];
auto &data = d[dr.rel_];
vector<size_t> ignore_idxs;
for (size_t i = 0; i < dr.pos_; i++)
if (relation.desc_.domains_[i] == domain)
ignore_idxs.push_back(i);
for (const auto &p : data->slice(dr.pos_, eid)) {
// don't double count
bool skip = false;
for (auto idx : ignore_idxs) {
if (p.first[idx] == eid) {
skip = true;
break;
}
}
if (skip)
continue;
callback(dr.rel_, p.first, p.second);
}
}
}
vector< vector<size_t> >
state::entity_data_positions(size_t domain, size_t eid, const dataset_t &d) const
{
vector< vector<size_t> > ret;
iterate_over_entity_data(
domain, eid, d,
[&ret](size_t, const vector<size_t> &eids, const value_accessor &) {
ret.emplace_back(eids);
});
return ret;
}
void
state::initialize(const vector<vector<set<size_t>>> &clusters, const dataset_t &d, rng_t &rng)
{
MICROSCOPES_DCHECK(clusters.size() == domains_.size(), "invalid number of clusterings");
assert_correct_shape(d);
for (size_t i = 0; i < domains_.size(); i++) {
MICROSCOPES_DCHECK(!domains_[i].ngroups(), "domain not empty");
const auto &c = clusters[i];
MICROSCOPES_DCHECK(c.size() > 0, "no clusters given!");
for (size_t j = 0; j < c.size(); j++)
domains_[i].create_group();
AssertAllEntitiesAccounted(c, domains_[i].nentities());
for (size_t j = 0; j < c.size(); j++)
for (auto eid : c[j])
domains_[i].add_value(j, eid);
}
#ifdef DEBUG_MODE
for (auto &d : domains_)
for (auto s : d.assignments())
MICROSCOPES_DCHECK(s != -1, "assignments should all be filled");
#endif
vector<size_t> gids;
for (size_t i = 0; i < relations_.size(); i++) {
auto &relation = relations_[i];
for (const auto &p : *d[i]) {
eids_to_gids_under_relation(gids, p.first, relation.desc_);
add_value_to_feature_group(gids, p.second, relation, rng, nullptr);
}
}
}
void
state::random_initialize(const dataset_t &d, rng_t &rng)
{
assert_correct_shape(d);
vector<vector<set<size_t>>> clusters;
clusters.reserve(domains_.size());
for (auto &d : domains_) {
vector<set<size_t>> cluster;
// create min(100, n/2) + 1 groups
const size_t ngroups = min(size_t(100), d.nentities()) + 1;
cluster.resize(ngroups);
const auto groups = util::range(ngroups);
for (size_t i = 0; i < d.nentities(); i++) {
const auto choice = util::sample_choice(groups, rng);
cluster[choice].insert(i);
}
clusters.emplace_back(cluster);
}
initialize(clusters, d, rng);
}
void
state::add_value0(size_t domain, size_t gid, size_t eid, const dataset_t &d, rng_t &rng, float *acc_score)
{
domains_[domain].add_value(gid, eid);
vector<size_t> gids;
iterate_over_entity_data(
domain, eid, d,
[this, &gids, &rng, acc_score](
size_t rid,
const vector<size_t> &eids,
const value_accessor &value) {
auto &relation = this->relations_[rid];
this->eids_to_gids_under_relation(gids, eids, relation.desc_);
this->add_value_to_feature_group(gids, value, relation, rng, acc_score);
});
}
size_t
state::remove_value0(size_t domain, size_t eid, const dataset_t &d, rng_t &rng)
{
vector<size_t> gids;
iterate_over_entity_data(
domain, eid, d,
[this, &gids, &rng](
size_t rid,
const vector<size_t> &eids,
const value_accessor &value) {
auto &relation = this->relations_[rid];
this->eids_to_gids_under_relation(gids, eids, relation.desc_);
this->remove_value_from_feature_group(gids, value, relation, rng);
});
return domains_[domain].remove_value(eid).first;
}
pair<vector<size_t>, vector<float>>
state::score_value0(size_t did, size_t eid, const dataset_t &d, rng_t &rng) const
{
const auto &domain = domains_[did];
MICROSCOPES_DCHECK(!domain.empty_groups().empty(), "no empty groups");
pair<vector<size_t>, vector<float>> ret;
ret.first.reserve(domain.ngroups());
ret.second.reserve(domain.ngroups());
float pseudocounts = 0;
for (const auto &g : domain) {
const float pseudocount = domain.pseudocount(g.first, g.second);
float sum = fast_log(pseudocount);
const_cast<state *>(this)->add_value0(did, g.first, eid, d, rng, &sum);
const size_t gid = const_cast<state *>(this)->remove_value0(did, eid, d, rng);
if (unlikely(gid != g.first))
MICROSCOPES_ASSERT(false);
ret.first.push_back(g.first);
ret.second.push_back(sum);
pseudocounts += pseudocount;
}
const float lgnorm = fast_log(pseudocounts);
for (auto &s : ret.second)
s -= lgnorm;
return ret;
}
float
state::score_likelihood(size_t relation, ident_t id, rng_t &rng) const
{
auto &ss = get_suffstats_t(relation, id);
return ss.ss_->score_data(*relations_[relation].desc_.model_, rng);
}
float
state::score_likelihood(size_t relation, rng_t &rng) const
{
MICROSCOPES_DCHECK(relation < relations_.size(), "invalid relation id");
float score = 0.;
auto &m = relations_[relation].desc_.model_;
for (auto &p : relations_[relation].suffstats_table_)
score += p.second.ss_->score_data(*m, rng);
return score;
}
<commit_msg>assertion -> dcheck<commit_after>#include <microscopes/irm/model.hpp>
#include <microscopes/common/util.hpp>
#include <distributions/special.hpp>
#include <algorithm>
using namespace std;
using namespace distributions;
using namespace microscopes::common;
using namespace microscopes::common::sparse_ndarray;
using namespace microscopes::irm;
using namespace microscopes::irm::detail;
using namespace microscopes::models;
state::state(const vector<size_t> &domains,
const vector<relation_t> &relations)
: domains_(), relations_()
{
MICROSCOPES_DCHECK(domains.size(), "no domains given");
domains_.reserve(domains.size());
for (auto n : domains)
domains_.emplace_back(n);
for (auto s : domains)
MICROSCOPES_DCHECK(s, "empty domain given");
for (const auto &r : relations) {
for (auto d : r.domains_)
MICROSCOPES_DCHECK(d < domains.size(), "invalid domain given");
relations_.emplace_back(r);
}
domain_relations_.reserve(domains_.size());
for (size_t i = 0; i < domains_.size(); i++)
domain_relations_.emplace_back(domain_relations(i));
}
static inline void
AssertAllEntitiesAccounted(const vector<set<size_t>> &c, size_t n)
{
vector<bool> ents(n, false);
for (const auto &s : c)
for (auto eid : s) {
MICROSCOPES_DCHECK(eid < ents.size(), "bad eid given");
MICROSCOPES_DCHECK(!ents[eid], "eid given twice");
ents[eid] = true;
}
for (auto b : ents)
MICROSCOPES_DCHECK(b, "ent unaccounted for");
}
void
state::eids_to_gids_under_relation(
vector<size_t> &gids,
const vector<size_t> &eids,
const relation_t &desc) const
{
gids.clear();
gids.reserve(desc.domains_.size());
for (size_t i = 0; i < desc.domains_.size(); i++) {
MICROSCOPES_DCHECK(
domains_[desc.domains_[i]].assignments()[eids[i]] != -1,
"eid is not assigned to a valid group");
gids.push_back(domains_[desc.domains_[i]].assignments()[eids[i]]);
}
}
void
state::add_value_to_feature_group(
const vector<size_t> &gids,
const value_accessor &value,
relation_container_t &relation,
rng_t &rng,
float *acc_score)
{
MICROSCOPES_ASSERT(!value.anymasked());
shared_ptr<feature_group> group;
auto it = relation.suffstats_table_.find(gids);
if (it == relation.suffstats_table_.end()) {
group = relation.desc_.model_->create_feature_group(rng);
auto &ss = relation.suffstats_table_[gids];
ss.ident_ = relation.ident_gen_++;
ss.count_ = 1;
MICROSCOPES_ASSERT(!ss.ss_);
ss.ss_ = group;
MICROSCOPES_ASSERT(relation.ident_table_.find(ss.ident_) == relation.ident_table_.end());
relation.ident_table_[ss.ident_] = gids;
} else {
it->second.count_++;
group = it->second.ss_;
}
MICROSCOPES_ASSERT(group);
if (acc_score)
*acc_score += group->score_value(*relation.desc_.model_, value, rng);
group->add_value(*relation.desc_.model_, value, rng);
}
void
state::remove_value_from_feature_group(
const vector<size_t> &gids,
const value_accessor &value,
relation_container_t &relation,
rng_t &rng)
{
auto it = relation.suffstats_table_.find(gids);
MICROSCOPES_ASSERT(!value.anymasked());
MICROSCOPES_ASSERT(it != relation.suffstats_table_.end());
MICROSCOPES_ASSERT(it->second.count_);
MICROSCOPES_ASSERT(it->second.ss_);
MICROSCOPES_ASSERT(
relation.ident_table_.find(it->second.ident_) != relation.ident_table_.end() &&
relation.ident_table_[it->second.ident_] == gids);
it->second.ss_->remove_value(*relation.desc_.model_, value, rng);
it->second.count_--;
// XXX: unfortunately, we cannot clean this up now!! this is because for
// non-conjugate models, score_value() depends on the randomness we sampled
// in add_value_to_feature_group() for correctness. yes, this is quite hacky
// (for conjugate models, it is safe to delete here)
//
// note that, the point at which the suffstat can be GC-ed for non-conj
// models is when >= of the gids associated with it is no longer a valid gid
// (which should imply the count is zero also)
//if (!--it->second.count_) {
// relation.ident_table_.erase(it->second.ident_);
// relation.suffstats_table_.erase(it);
//}
}
void
state::iterate_over_entity_data(
size_t domain,
size_t eid,
const dataset_t &d,
function<void(size_t, const vector<size_t> &, const value_accessor &)> callback) const
{
for (const auto &dr : domain_relations_[domain]) {
auto &relation = relations_[dr.rel_];
auto &data = d[dr.rel_];
vector<size_t> ignore_idxs;
for (size_t i = 0; i < dr.pos_; i++)
if (relation.desc_.domains_[i] == domain)
ignore_idxs.push_back(i);
for (const auto &p : data->slice(dr.pos_, eid)) {
// don't double count
bool skip = false;
for (auto idx : ignore_idxs) {
if (p.first[idx] == eid) {
skip = true;
break;
}
}
if (skip)
continue;
callback(dr.rel_, p.first, p.second);
}
}
}
vector< vector<size_t> >
state::entity_data_positions(size_t domain, size_t eid, const dataset_t &d) const
{
vector< vector<size_t> > ret;
iterate_over_entity_data(
domain, eid, d,
[&ret](size_t, const vector<size_t> &eids, const value_accessor &) {
ret.emplace_back(eids);
});
return ret;
}
void
state::initialize(const vector<vector<set<size_t>>> &clusters, const dataset_t &d, rng_t &rng)
{
MICROSCOPES_DCHECK(clusters.size() == domains_.size(), "invalid number of clusterings");
assert_correct_shape(d);
for (size_t i = 0; i < domains_.size(); i++) {
MICROSCOPES_DCHECK(!domains_[i].ngroups(), "domain not empty");
const auto &c = clusters[i];
MICROSCOPES_DCHECK(c.size() > 0, "no clusters given!");
for (size_t j = 0; j < c.size(); j++)
domains_[i].create_group();
AssertAllEntitiesAccounted(c, domains_[i].nentities());
for (size_t j = 0; j < c.size(); j++)
for (auto eid : c[j])
domains_[i].add_value(j, eid);
}
#ifdef DEBUG_MODE
for (auto &d : domains_)
for (auto s : d.assignments())
MICROSCOPES_DCHECK(s != -1, "assignments should all be filled");
#endif
vector<size_t> gids;
for (size_t i = 0; i < relations_.size(); i++) {
auto &relation = relations_[i];
for (const auto &p : *d[i]) {
eids_to_gids_under_relation(gids, p.first, relation.desc_);
add_value_to_feature_group(gids, p.second, relation, rng, nullptr);
}
}
}
void
state::random_initialize(const dataset_t &d, rng_t &rng)
{
assert_correct_shape(d);
vector<vector<set<size_t>>> clusters;
clusters.reserve(domains_.size());
for (auto &d : domains_) {
vector<set<size_t>> cluster;
// create min(100, n/2) + 1 groups
const size_t ngroups = min(size_t(100), d.nentities()) + 1;
cluster.resize(ngroups);
const auto groups = util::range(ngroups);
for (size_t i = 0; i < d.nentities(); i++) {
const auto choice = util::sample_choice(groups, rng);
cluster[choice].insert(i);
}
clusters.emplace_back(cluster);
}
initialize(clusters, d, rng);
}
void
state::add_value0(size_t domain, size_t gid, size_t eid, const dataset_t &d, rng_t &rng, float *acc_score)
{
domains_[domain].add_value(gid, eid);
vector<size_t> gids;
iterate_over_entity_data(
domain, eid, d,
[this, &gids, &rng, acc_score](
size_t rid,
const vector<size_t> &eids,
const value_accessor &value) {
auto &relation = this->relations_[rid];
this->eids_to_gids_under_relation(gids, eids, relation.desc_);
this->add_value_to_feature_group(gids, value, relation, rng, acc_score);
});
}
size_t
state::remove_value0(size_t domain, size_t eid, const dataset_t &d, rng_t &rng)
{
vector<size_t> gids;
iterate_over_entity_data(
domain, eid, d,
[this, &gids, &rng](
size_t rid,
const vector<size_t> &eids,
const value_accessor &value) {
auto &relation = this->relations_[rid];
this->eids_to_gids_under_relation(gids, eids, relation.desc_);
this->remove_value_from_feature_group(gids, value, relation, rng);
});
return domains_[domain].remove_value(eid).first;
}
pair<vector<size_t>, vector<float>>
state::score_value0(size_t did, size_t eid, const dataset_t &d, rng_t &rng) const
{
const auto &domain = domains_[did];
MICROSCOPES_DCHECK(!domain.empty_groups().empty(), "no empty groups");
pair<vector<size_t>, vector<float>> ret;
ret.first.reserve(domain.ngroups());
ret.second.reserve(domain.ngroups());
float pseudocounts = 0;
for (const auto &g : domain) {
const float pseudocount = domain.pseudocount(g.first, g.second);
float sum = fast_log(pseudocount);
const_cast<state *>(this)->add_value0(did, g.first, eid, d, rng, &sum);
const size_t gid = const_cast<state *>(this)->remove_value0(did, eid, d, rng);
if (unlikely(gid != g.first))
MICROSCOPES_ASSERT(false);
ret.first.push_back(g.first);
ret.second.push_back(sum);
pseudocounts += pseudocount;
}
const float lgnorm = fast_log(pseudocounts);
for (auto &s : ret.second)
s -= lgnorm;
return ret;
}
float
state::score_likelihood(size_t relation, ident_t id, rng_t &rng) const
{
auto &ss = get_suffstats_t(relation, id);
return ss.ss_->score_data(*relations_[relation].desc_.model_, rng);
}
float
state::score_likelihood(size_t relation, rng_t &rng) const
{
MICROSCOPES_DCHECK(relation < relations_.size(), "invalid relation id");
float score = 0.;
auto &m = relations_[relation].desc_.model_;
for (auto &p : relations_[relation].suffstats_table_)
score += p.second.ss_->score_data(*m, rng);
return score;
}
<|endoftext|> |
<commit_before>// =============================================================================
// File Name: Robot.cpp
// Description: Implements the main robot class
// Author: FRC Team 3512, Spartatroniks
// =============================================================================
#include "Robot.hpp"
#include <cmath>
#include <iostream>
Robot::Robot() : settings("/home/lvuser/RobotSettings.txt"),
drive1Buttons(0),
drive2Buttons(1),
evButtons(2),
dsDisplay(DSDisplay::getInstance(settings.getInt("DS_Port"))),
pidGraph(3513) {
robotDrive = std::make_unique<DriveTrain>();
ev = std::make_unique<Elevator>();
driveStick1 = std::make_unique<Joystick>(0);
driveStick2 = std::make_unique<Joystick>(1);
evStick = std::make_unique<Joystick>(2);
autoTimer = std::make_unique<Timer>();
displayTimer = std::make_unique<Timer>();
accumTimer = std::make_unique<Timer>();
dsDisplay.addAutoMethod("Noop Auton", &Robot::AutoNoop, this);
dsDisplay.addAutoMethod("DriveForward", &Robot::AutoDriveForward, this);
dsDisplay.addAutoMethod("OneTote", &Robot::AutoOneTote, this);
pidGraph.setSendInterval(5);
displayTimer->Start();
}
void Robot::OperatorControl() {
while (IsEnabled() && IsOperatorControl()) {
if (driveStick2->GetRawButton(2)) {
robotDrive->drive(driveStick1->GetY(), driveStick2->GetX(), true);
}
else {
robotDrive->drive(driveStick1->GetY(), driveStick2->GetX());
}
// Open/close tines
if (evButtons.releasedButton(1)) {
ev->elevatorGrab(!ev->isElevatorGrabbed());
}
// Open/close intake
if (evButtons.releasedButton(2)) {
ev->intakeGrab(!ev->isIntakeGrabbed());
}
// Start auto-stacking mode
if (evButtons.releasedButton(3)) {
ev->stackTotes();
}
// Manual height control
if (evButtons.releasedButton(4)) {
ev->setManualMode(!ev->isManualMode());
}
// Stow intake
if (evButtons.releasedButton(5)) {
ev->stowIntake(!ev->isIntakeStowed());
}
// Automatic preset buttons (7-12)
// TODO: Special case for level 0
if (evButtons.releasedButton(8)) {
ev->raiseElevator("EV_GROUND");
}
if (evButtons.releasedButton(7)) {
ev->raiseElevator("EV_TOTE_1");
}
if (evButtons.releasedButton(10)) {
ev->raiseElevator("EV_TOTE_2");
}
if (evButtons.releasedButton(9)) {
ev->raiseElevator("EV_TOTE_3");
}
if (evButtons.releasedButton(12)) {
ev->raiseElevator("EV_TOTE_4");
}
if (evButtons.releasedButton(11)) {
ev->raiseElevator("EV_TOTE_5");
}
// Set manual value
ev->setManualLiftSpeed(evStick->GetY());
if (evStick->GetPOV() == 0) {
ev->setIntakeDirectionLeft(Elevator::S_FORWARD);
ev->setIntakeDirectionRight(Elevator::S_FORWARD);
}
else if (evStick->GetPOV() == 90) {
ev->setIntakeDirectionLeft(Elevator::S_ROTATE_CCW);
ev->setIntakeDirectionRight(Elevator::S_ROTATE_CCW);
}
else if (evStick->GetPOV() == 180) {
ev->setIntakeDirectionLeft(Elevator::S_REVERSE);
ev->setIntakeDirectionRight(Elevator::S_REVERSE);
}
else if (evStick->GetPOV() == 270) {
ev->setIntakeDirectionLeft(Elevator::S_ROTATE_CW);
ev->setIntakeDirectionRight(Elevator::S_ROTATE_CW);
}
else {
if (driveStick1->GetPOV() == 0) {
ev->setIntakeDirectionLeft(Elevator::S_FORWARD);
}
else if (driveStick1->GetPOV() == 90) {
ev->setIntakeDirectionLeft(Elevator::S_ROTATE_CCW);
}
else if (driveStick1->GetPOV() == 180 ||
driveStick1->GetRawButton(1)) {
ev->setIntakeDirectionLeft(Elevator::S_REVERSE);
}
else if (driveStick1->GetPOV() == 270) {
ev->setIntakeDirectionLeft(Elevator::S_ROTATE_CW);
}
else {
ev->setIntakeDirectionLeft(Elevator::S_STOPPED);
}
if (driveStick2->GetPOV() == 0) {
ev->setIntakeDirectionRight(Elevator::S_FORWARD);
}
else if (driveStick2->GetPOV() == 90) {
ev->setIntakeDirectionRight(Elevator::S_ROTATE_CCW);
}
else if (driveStick2->GetPOV() == 180 ||
driveStick2->GetRawButton(1)) {
ev->setIntakeDirectionRight(Elevator::S_REVERSE);
}
else if (driveStick2->GetPOV() == 270) {
ev->setIntakeDirectionRight(Elevator::S_ROTATE_CW);
}
else {
ev->setIntakeDirectionRight(Elevator::S_STOPPED);
}
}
if (drive2Buttons.releasedButton(12)) {
ev->resetEncoders();
}
// Accumulate assisted automatic mode
double deltaT = accumTimer->Get();
accumTimer->Reset();
accumTimer->Start();
double evStickY = evStick->GetY();
evStickY = 0;
manualAverage.addValue(evStickY * ev->getMaxVelocity() * deltaT);
// Deadband
if (applyDeadband(manualAverage.get(), 0.05) &&
applyDeadband(evStickY, 0.05)) {
if (ev->getSetpoint() + manualAverage.get() > 0
&& ev->getSetpoint() + manualAverage.get() <
settings.getDouble("EV_MAX_HEIGHT")) {
std::cout << "manualChangeSetpoint("
<< manualAverage.get()
<< ")"
<< std::endl;
ev->manualChangeSetpoint(manualAverage.get());
}
}
/* Opens intake if the elevator is at the same level as it or if the
* tines are open
*/
if (ev->isIntakeGrabbed()) {
if ((ev->getSetpoint() < 11 && !ev->isManualMode()) ||
!ev->isElevatorGrabbed() ||
ev->isIntakeStowed()) {
ev->intakeGrab(false);
}
}
// Poll the limit reset limit switch
ev->pollLiftLimitSwitches();
// Update the elevator automatic stacking state
ev->updateState();
drive1Buttons.updateButtons();
drive2Buttons.updateButtons();
evButtons.updateButtons();
DS_PrintOut();
Wait(0.01);
}
}
void Robot::Autonomous() {
autoTimer->Reset();
autoTimer->Start();
robotDrive->resetEncoders();
AutoNoop();
//dsDisplay.execAutonomous();
}
void Robot::Disabled() {
while (IsDisabled()) {
DS_PrintOut();
Wait(0.1);
}
robotDrive->reloadPID();
ev->reloadPID();
}
void Robot::DS_PrintOut() {
if (pidGraph.hasIntervalPassed()) {
pidGraph.graphData(ev->getHeight(), "Distance (EV)");
pidGraph.graphData(ev->getSetpoint(), "Setpoint (EV)");
pidGraph.graphData(robotDrive->getLeftDist(), "Left PV (DR)");
pidGraph.graphData(robotDrive->getLeftSetpoint(), "Left SP (DR)");
pidGraph.graphData(robotDrive->getRightDist(), "Right PV (DR)");
pidGraph.graphData(robotDrive->getRightSetpoint(), "Right SP (DR)");
pidGraph.resetInterval();
}
if (displayTimer->HasPeriodPassed(0.5)) {
// Send things to DS display
dsDisplay.clear();
dsDisplay.addData("ENCODER_LEFT", robotDrive->getLeftDist());
dsDisplay.addData("ENCODER_RIGHT", robotDrive->getRightDist());
dsDisplay.addData("EV_POS_DISP", ev->getHeight());
dsDisplay.addData("EV_POS", 100 * ev->getHeight() / 60);
dsDisplay.addData("EV_TOTE_INSIDE", ev->pollFrontLimitSwitches());
dsDisplay.addData("INTAKE_ARMS_CLOSED", ev->isIntakeGrabbed());
dsDisplay.addData("ARMS_CLOSED", ev->isElevatorGrabbed());
dsDisplay.sendToDS();
}
dsDisplay.receiveFromDS();
}
float Robot::applyDeadband(float value, float deadband) {
if (fabs(value) > deadband) {
if (value > 0) {
return (value - deadband) / (1 - deadband);
}
else {
return (value + deadband) / (1 - deadband);
}
}
else {
return 0.f;
}
}
START_ROBOT_CLASS(Robot);
<commit_msg>Simplified intake direction control logic<commit_after>// =============================================================================
// File Name: Robot.cpp
// Description: Implements the main robot class
// Author: FRC Team 3512, Spartatroniks
// =============================================================================
#include "Robot.hpp"
#include <cmath>
#include <iostream>
Robot::Robot() : settings("/home/lvuser/RobotSettings.txt"),
drive1Buttons(0),
drive2Buttons(1),
evButtons(2),
dsDisplay(DSDisplay::getInstance(settings.getInt("DS_Port"))),
pidGraph(3513) {
robotDrive = std::make_unique<DriveTrain>();
ev = std::make_unique<Elevator>();
driveStick1 = std::make_unique<Joystick>(0);
driveStick2 = std::make_unique<Joystick>(1);
evStick = std::make_unique<Joystick>(2);
autoTimer = std::make_unique<Timer>();
displayTimer = std::make_unique<Timer>();
accumTimer = std::make_unique<Timer>();
dsDisplay.addAutoMethod("Noop Auton", &Robot::AutoNoop, this);
dsDisplay.addAutoMethod("DriveForward", &Robot::AutoDriveForward, this);
dsDisplay.addAutoMethod("OneTote", &Robot::AutoOneTote, this);
pidGraph.setSendInterval(5);
displayTimer->Start();
}
void Robot::OperatorControl() {
while (IsEnabled() && IsOperatorControl()) {
if (driveStick2->GetRawButton(2)) {
robotDrive->drive(driveStick1->GetY(), driveStick2->GetX(), true);
}
else {
robotDrive->drive(driveStick1->GetY(), driveStick2->GetX());
}
// Open/close tines
if (evButtons.releasedButton(1)) {
ev->elevatorGrab(!ev->isElevatorGrabbed());
}
// Open/close intake
if (evButtons.releasedButton(2)) {
ev->intakeGrab(!ev->isIntakeGrabbed());
}
// Start auto-stacking mode
if (evButtons.releasedButton(3)) {
ev->stackTotes();
}
// Manual height control
if (evButtons.releasedButton(4)) {
ev->setManualMode(!ev->isManualMode());
}
// Stow intake
if (evButtons.releasedButton(5)) {
ev->stowIntake(!ev->isIntakeStowed());
}
// Automatic preset buttons (7-12)
// TODO: Special case for level 0
if (evButtons.releasedButton(8)) {
ev->raiseElevator("EV_GROUND");
}
if (evButtons.releasedButton(7)) {
ev->raiseElevator("EV_TOTE_1");
}
if (evButtons.releasedButton(10)) {
ev->raiseElevator("EV_TOTE_2");
}
if (evButtons.releasedButton(9)) {
ev->raiseElevator("EV_TOTE_3");
}
if (evButtons.releasedButton(12)) {
ev->raiseElevator("EV_TOTE_4");
}
if (evButtons.releasedButton(11)) {
ev->raiseElevator("EV_TOTE_5");
}
// Set manual value
ev->setManualLiftSpeed(evStick->GetY());
if (driveStick1->GetPOV() == 0 || evStick->GetPOV() == 0) {
ev->setIntakeDirectionLeft(Elevator::S_FORWARD);
}
else if (driveStick1->GetPOV() == 90 || evStick->GetPOV() == 90) {
ev->setIntakeDirectionLeft(Elevator::S_ROTATE_CCW);
}
else if (driveStick1->GetPOV() == 180 || evStick->GetPOV() == 180 ||
driveStick1->GetRawButton(1)) {
ev->setIntakeDirectionLeft(Elevator::S_REVERSE);
}
else if (driveStick1->GetPOV() == 270 || evStick->GetPOV() == 270) {
ev->setIntakeDirectionLeft(Elevator::S_ROTATE_CW);
}
else {
ev->setIntakeDirectionLeft(Elevator::S_STOPPED);
}
if (driveStick2->GetPOV() == 0 || evStick->GetPOV() == 0) {
ev->setIntakeDirectionRight(Elevator::S_FORWARD);
}
else if (driveStick2->GetPOV() == 90 || evStick->GetPOV() == 90) {
ev->setIntakeDirectionRight(Elevator::S_ROTATE_CCW);
}
else if (driveStick2->GetPOV() == 180 || evStick->GetPOV() == 180 ||
driveStick2->GetRawButton(1)) {
ev->setIntakeDirectionRight(Elevator::S_REVERSE);
}
else if (driveStick2->GetPOV() == 270 || evStick->GetPOV() == 270) {
ev->setIntakeDirectionRight(Elevator::S_ROTATE_CW);
}
else {
ev->setIntakeDirectionRight(Elevator::S_STOPPED);
}
if (drive2Buttons.releasedButton(12)) {
ev->resetEncoders();
}
// Accumulate assisted automatic mode
double deltaT = accumTimer->Get();
accumTimer->Reset();
accumTimer->Start();
double evStickY = evStick->GetY();
evStickY = 0;
manualAverage.addValue(evStickY * ev->getMaxVelocity() * deltaT);
// Deadband
if (applyDeadband(manualAverage.get(), 0.05) &&
applyDeadband(evStickY, 0.05)) {
if (ev->getSetpoint() + manualAverage.get() > 0
&& ev->getSetpoint() + manualAverage.get() <
settings.getDouble("EV_MAX_HEIGHT")) {
std::cout << "manualChangeSetpoint("
<< manualAverage.get()
<< ")"
<< std::endl;
ev->manualChangeSetpoint(manualAverage.get());
}
}
/* Opens intake if the elevator is at the same level as it or if the
* tines are open
*/
if (ev->isIntakeGrabbed()) {
if ((ev->getSetpoint() < 11 && !ev->isManualMode()) ||
!ev->isElevatorGrabbed() ||
ev->isIntakeStowed()) {
ev->intakeGrab(false);
}
}
// Poll the limit reset limit switch
ev->pollLiftLimitSwitches();
// Update the elevator automatic stacking state
ev->updateState();
drive1Buttons.updateButtons();
drive2Buttons.updateButtons();
evButtons.updateButtons();
DS_PrintOut();
Wait(0.01);
}
}
void Robot::Autonomous() {
autoTimer->Reset();
autoTimer->Start();
robotDrive->resetEncoders();
AutoNoop();
// dsDisplay.execAutonomous();
}
void Robot::Disabled() {
while (IsDisabled()) {
DS_PrintOut();
Wait(0.1);
}
robotDrive->reloadPID();
ev->reloadPID();
}
void Robot::DS_PrintOut() {
if (pidGraph.hasIntervalPassed()) {
pidGraph.graphData(ev->getHeight(), "Distance (EV)");
pidGraph.graphData(ev->getSetpoint(), "Setpoint (EV)");
pidGraph.graphData(robotDrive->getLeftDist(), "Left PV (DR)");
pidGraph.graphData(robotDrive->getLeftSetpoint(), "Left SP (DR)");
pidGraph.graphData(robotDrive->getRightDist(), "Right PV (DR)");
pidGraph.graphData(robotDrive->getRightSetpoint(), "Right SP (DR)");
pidGraph.resetInterval();
}
if (displayTimer->HasPeriodPassed(0.5)) {
// Send things to DS display
dsDisplay.clear();
dsDisplay.addData("ENCODER_LEFT", robotDrive->getLeftDist());
dsDisplay.addData("ENCODER_RIGHT", robotDrive->getRightDist());
dsDisplay.addData("EV_POS_DISP", ev->getHeight());
dsDisplay.addData("EV_POS", 100 * ev->getHeight() / 60);
dsDisplay.addData("EV_TOTE_INSIDE", ev->pollFrontLimitSwitches());
dsDisplay.addData("INTAKE_ARMS_CLOSED", ev->isIntakeGrabbed());
dsDisplay.addData("ARMS_CLOSED", ev->isElevatorGrabbed());
dsDisplay.sendToDS();
}
dsDisplay.receiveFromDS();
}
float Robot::applyDeadband(float value, float deadband) {
if (fabs(value) > deadband) {
if (value > 0) {
return (value - deadband) / (1 - deadband);
}
else {
return (value + deadband) / (1 - deadband);
}
}
else {
return 0.f;
}
}
START_ROBOT_CLASS(Robot);
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Library
Module: SbrLgt.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include <math.h>
#include "SbrRen.hh"
#include "SbrLgt.hh"
// Description:
// Implement base class method.
void vlSbrLight::Render(vlRenderer *ren,int light_index)
{
this->Render((vlSbrRenderer *)ren,light_index);
}
// Description:
// Actual light render method.
void vlSbrLight::Render(vlSbrRenderer *ren,int light_index)
{
float dx, dy, dz;
float color[3];
int light_flag;
int fd;
light_flag = ren->GetLightSwitch();
fd = ren->GetFd();
// get required info from light
color[0] = this->Intensity * this->Color[0];
color[1] = this->Intensity * this->Color[1];
color[2] = this->Intensity * this->Color[2];
dx = this->Position[0] - this->FocalPoint[0];
dy = this->Position[1] - this->FocalPoint[1];
dz = this->Position[2] - this->FocalPoint[2];
dz = -dz;
// define the light source
light_source(fd, light_index, DIRECTIONAL,
color[0], color[1], color[2],
dx, dy, dz);
light_flag |= (0x0001 << light_index);
vlDebugMacro(<< "Defining front light\n");
// define another mirror light if backlit is on
if (ren->GetBackLight())
{
light_index++;
light_source(fd, light_index, DIRECTIONAL,
color[0], color[1], color[2],
-dx, -dy, -dz);
vlDebugMacro(<< "Defining back light\n");
light_flag |= (0x0001 << light_index);
}
// update the light switch
light_switch(fd, light_flag);
vlDebugMacro(<< "SB_light_switch: " << light_flag << "\n");
}
<commit_msg>bug fix in z coord<commit_after>/*=========================================================================
Program: Visualization Library
Module: SbrLgt.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include <math.h>
#include "SbrRen.hh"
#include "SbrLgt.hh"
// Description:
// Implement base class method.
void vlSbrLight::Render(vlRenderer *ren,int light_index)
{
this->Render((vlSbrRenderer *)ren,light_index);
}
// Description:
// Actual light render method.
void vlSbrLight::Render(vlSbrRenderer *ren,int light_index)
{
float dx, dy, dz;
float color[3];
int light_flag;
int fd;
light_flag = ren->GetLightSwitch();
fd = ren->GetFd();
// get required info from light
color[0] = this->Intensity * this->Color[0];
color[1] = this->Intensity * this->Color[1];
color[2] = this->Intensity * this->Color[2];
dx = this->Position[0] - this->FocalPoint[0];
dy = this->Position[1] - this->FocalPoint[1];
dz = this->Position[2] - this->FocalPoint[2];
// define the light source
light_source(fd, light_index, DIRECTIONAL,
color[0], color[1], color[2],
dx, dy, dz);
light_flag |= (0x0001 << light_index);
vlDebugMacro(<< "Defining front light\n");
// define another mirror light if backlit is on
if (ren->GetBackLight())
{
light_index++;
light_source(fd, light_index, DIRECTIONAL,
color[0], color[1], color[2],
-dx, -dy, -dz);
vlDebugMacro(<< "Defining back light\n");
light_flag |= (0x0001 << light_index);
}
// update the light switch
light_switch(fd, light_flag);
vlDebugMacro(<< "SB_light_switch: " << light_flag << "\n");
}
<|endoftext|> |
<commit_before>/*
* Scene.cpp
*
* Created on: 24.01.2015
* Author: sartz
*/
#include "Scene.hpp"
#include "Tile.hpp"
Scene::Scene() {
// TODO Auto-generated constructor stub
for (int x=0;x<sizeX * largeTileSizeX;x++)
{
for (int y=0;y<sizeY * largeTileSizeY;y++)
{
gameBoard.push_back(new Tile());
}
}
}
Scene::~Scene() {
// TODO Auto-generated destructor stub
}
GameObject* Scene::getTile(int x, int y)
{
if (x + y*sizeX < (int)gameBoard.size())
{
return gameBoard[x + y*sizeX];
}
return 0;
}
void Scene::setTile(GameObject* obj, int x, int y)
{
gameBoard[x + y*sizeX] = obj;
}
void Scene::switchLargeTile(int x1, int y1, int x2, int y2)
{
GameObject* tmpObj;
int startX1 = x1*largeTileSizeX;
int startY1 = y1*largeTileSizeY;
int startX2 = x2*largeTileSizeX;
int startY2 = y2*largeTileSizeY;
for (int x=0;x<largeTileSizeX;x++)
{
for (int y=0;largeTileSizeY;y++)
{
tmpObj = getTile(startX1+x, startY1+y);
setTile(getTile(startX2+x, startY2+y), startX1+x, startY1+y);
setTile(tmpObj, startX2+x, startY2+y);
}
}
}
void Scene::update(sf::Time deltaT)
{
for (std::vector<GameObject*>::iterator it = gameBoard.begin();it != gameBoard.end(); it++)
{
(*it)->update(deltaT);
}
}
<commit_msg>fix gameBoard<commit_after>/*
* Scene.cpp
*
* Created on: 24.01.2015
* Author: sartz
*/
#include "Scene.hpp"
#include "Tile.hpp"
Scene::Scene() {
// TODO Auto-generated constructor stub
for (int x=0;x<sizeX * largeTileSizeX;x++)
{
for (int y=0;y<sizeY * largeTileSizeY;y++)
{
gameBoard.push_back(new Tile());
}
}
}
Scene::~Scene() {
// TODO Auto-generated destructor stub
}
GameObject* Scene::getTile(int x, int y)
{
if (x + y*sizeX < (int)gameBoard.size())
{
return gameBoard[x + y * sizeX * largeTileSizeX];
}
return 0;
}
void Scene::setTile(GameObject* obj, int x, int y)
{
gameBoard[x + y * sizeX * largeTileSizeX] = obj;
}
void Scene::switchLargeTile(int x1, int y1, int x2, int y2)
{
GameObject* tmpObj;
int startX1 = x1*largeTileSizeX;
int startY1 = y1*largeTileSizeY;
int startX2 = x2*largeTileSizeX;
int startY2 = y2*largeTileSizeY;
for (int x=0;x<largeTileSizeX;x++)
{
for (int y=0;largeTileSizeY;y++)
{
tmpObj = getTile(startX1+x, startY1+y);
setTile(getTile(startX2+x, startY2+y), startX1+x, startY1+y);
setTile(tmpObj, startX2+x, startY2+y);
}
}
}
void Scene::update(sf::Time deltaT)
{
for (std::vector<GameObject*>::iterator it = gameBoard.begin();it != gameBoard.end(); it++)
{
(*it)->update(deltaT);
}
}
<|endoftext|> |
<commit_before>
#include "keyboard.h"
#include <X11/XKBlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include "../deps/chromium/macros.h"
#include "../deps/chromium/x/keysym_to_unicode.h"
#include "../deps/chromium/x/keycode_and_xkeycode.h"
typedef struct _XDisplay XDisplay;
namespace {
class KeyModifierMaskToXModifierMask {
public:
static KeyModifierMaskToXModifierMask& GetInstance() {
static KeyModifierMaskToXModifierMask instance;
return instance;
}
void Initialize(Display* display) {
alt_modifier = 0;
meta_modifier = 0;
num_lock_modifier = 0;
mode_switch_modifier = 0;
if (!display) {
return;
}
XModifierKeymap* mod_map = XGetModifierMapping(display);
int max_mod_keys = mod_map->max_keypermod;
for (int mod_index = 0; mod_index <= 8; ++mod_index) {
for (int key_index = 0; key_index < max_mod_keys; ++key_index) {
int key = mod_map->modifiermap[mod_index * max_mod_keys + key_index];
if (!key) {
continue;
}
int keysym = XkbKeycodeToKeysym(display, key, 0, 0);
if (!keysym) {
continue;
}
// TODO: Also check for XK_ISO_Level3_Shift 0xFE03
if (keysym == XK_Alt_L || keysym == XK_Alt_R) {
alt_modifier = 1 << mod_index;
}
if (keysym == XK_Mode_switch) {
mode_switch_modifier = 1 << mod_index;
}
if (keysym == XK_Meta_L || keysym == XK_Super_L || keysym == XK_Meta_R || keysym == XK_Super_R) {
meta_modifier = 1 << mod_index;
}
if (keysym == XK_Num_Lock) {
num_lock_modifier = 1 << mod_index;
}
}
}
XFreeModifiermap(mod_map);
}
int XModFromKeyMod(int keyMod) {
int x_modifier = 0;
// Ctrl + Alt => AltGr
if (keyMod & kControlKeyModifierMask && keyMod & kAltKeyModifierMask) {
x_modifier |= mode_switch_modifier;//alt_r_modifier;
} else if (keyMod & kControlKeyModifierMask) {
x_modifier |= ControlMask;
} else if (keyMod & kAltKeyModifierMask) {
x_modifier |= alt_modifier;
}
if (keyMod & kShiftKeyModifierMask) {
x_modifier |= ShiftMask;
}
if (keyMod & kMetaKeyModifierMask) {
x_modifier |= meta_modifier;
}
if (keyMod & kNumLockKeyModifierMask) {
x_modifier |= num_lock_modifier;
}
return x_modifier;
}
private:
KeyModifierMaskToXModifierMask() {
Initialize(NULL);
}
int alt_modifier;
int meta_modifier;
int num_lock_modifier;
int mode_switch_modifier;
DISALLOW_COPY_AND_ASSIGN(KeyModifierMaskToXModifierMask);
};
std::string GetStrFromXEvent(const XEvent* xev) {
const XKeyEvent* xkey = &xev->xkey;
KeySym keysym = XK_VoidSymbol;
XLookupString(const_cast<XKeyEvent*>(xkey), NULL, 0, &keysym, NULL);
uint16_t character = ui::GetUnicodeCharacterFromXKeySym(keysym);
if (!character)
return std::string();
wchar_t *t = new wchar_t[2];
t[0] = character;
t[1] = 0;
std::string result = UTF16to8(t);
delete []t;
return result;
}
} // namespace
namespace vscode_keyboard {
std::vector<KeyMapping> GetKeyMapping() {
std::vector<KeyMapping> result;
Display *display;
if (!(display = XOpenDisplay(""))) {
return result;
}
XEvent event;
memset(&event, 0, sizeof(XEvent));
XKeyEvent* key_event = &event.xkey;
key_event->display = display;
key_event->type = KeyPress;
KeyModifierMaskToXModifierMask *mask_provider = &KeyModifierMaskToXModifierMask::GetInstance();
mask_provider->Initialize(display);
for (size_t i = 0; i < arraysize(ui::gKeyCodeToXKeyCode); ++i) {
ui::KeyboardCode key_code = ui::gKeyCodeToXKeyCode[i].key_code;
int x_key_code = ui::gKeyCodeToXKeyCode[i].x_key_code;
key_event->keycode = x_key_code;
key_event->state = 0;
std::string value = GetStrFromXEvent(&event);
key_event->state = mask_provider->XModFromKeyMod(kShiftKeyModifierMask);
std::string withShift = GetStrFromXEvent(&event);
key_event->state = mask_provider->XModFromKeyMod(kControlKeyModifierMask | kAltKeyModifierMask);
std::string withAltGr = GetStrFromXEvent(&event);
key_event->state = mask_provider->XModFromKeyMod(kShiftKeyModifierMask | kControlKeyModifierMask | kAltKeyModifierMask);
std::string withShiftAltGr = GetStrFromXEvent(&event);
KeyMapping keyMapping = KeyMapping();
keyMapping.key_code = key_code;
keyMapping.value = value;
keyMapping.withShift = withShift;
keyMapping.withAltGr = withAltGr;
keyMapping.withShiftAltGr = withShiftAltGr;
result.push_back(keyMapping);
}
XFlush(display);
XCloseDisplay(display);
return result;
}
} // namespace vscode_keyboard
<commit_msg>Get linux compiling again<commit_after>
#include "keyboard.h"
#include "string_conversion.h"
#include <X11/XKBlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include "../deps/chromium/macros.h"
#include "../deps/chromium/x/keysym_to_unicode.h"
#include "../deps/chromium/x/keycode_and_xkeycode.h"
typedef struct _XDisplay XDisplay;
namespace {
class KeyModifierMaskToXModifierMask {
public:
static KeyModifierMaskToXModifierMask& GetInstance() {
static KeyModifierMaskToXModifierMask instance;
return instance;
}
void Initialize(Display* display) {
alt_modifier = 0;
meta_modifier = 0;
num_lock_modifier = 0;
mode_switch_modifier = 0;
if (!display) {
return;
}
XModifierKeymap* mod_map = XGetModifierMapping(display);
int max_mod_keys = mod_map->max_keypermod;
for (int mod_index = 0; mod_index <= 8; ++mod_index) {
for (int key_index = 0; key_index < max_mod_keys; ++key_index) {
int key = mod_map->modifiermap[mod_index * max_mod_keys + key_index];
if (!key) {
continue;
}
int keysym = XkbKeycodeToKeysym(display, key, 0, 0);
if (!keysym) {
continue;
}
// TODO: Also check for XK_ISO_Level3_Shift 0xFE03
if (keysym == XK_Alt_L || keysym == XK_Alt_R) {
alt_modifier = 1 << mod_index;
}
if (keysym == XK_Mode_switch) {
mode_switch_modifier = 1 << mod_index;
}
if (keysym == XK_Meta_L || keysym == XK_Super_L || keysym == XK_Meta_R || keysym == XK_Super_R) {
meta_modifier = 1 << mod_index;
}
if (keysym == XK_Num_Lock) {
num_lock_modifier = 1 << mod_index;
}
}
}
XFreeModifiermap(mod_map);
}
int XModFromKeyMod(int keyMod) {
int x_modifier = 0;
// Ctrl + Alt => AltGr
if (keyMod & kControlKeyModifierMask && keyMod & kAltKeyModifierMask) {
x_modifier |= mode_switch_modifier;//alt_r_modifier;
} else if (keyMod & kControlKeyModifierMask) {
x_modifier |= ControlMask;
} else if (keyMod & kAltKeyModifierMask) {
x_modifier |= alt_modifier;
}
if (keyMod & kShiftKeyModifierMask) {
x_modifier |= ShiftMask;
}
if (keyMod & kMetaKeyModifierMask) {
x_modifier |= meta_modifier;
}
if (keyMod & kNumLockKeyModifierMask) {
x_modifier |= num_lock_modifier;
}
return x_modifier;
}
private:
KeyModifierMaskToXModifierMask() {
Initialize(NULL);
}
int alt_modifier;
int meta_modifier;
int num_lock_modifier;
int mode_switch_modifier;
DISALLOW_COPY_AND_ASSIGN(KeyModifierMaskToXModifierMask);
};
std::string GetStrFromXEvent(const XEvent* xev) {
const XKeyEvent* xkey = &xev->xkey;
KeySym keysym = XK_VoidSymbol;
XLookupString(const_cast<XKeyEvent*>(xkey), NULL, 0, &keysym, NULL);
uint16_t character = ui::GetUnicodeCharacterFromXKeySym(keysym);
if (!character)
return std::string();
wchar_t value = character;
return vscode_keyboard::UTF16toUTF8(&value, 1);
}
} // namespace
namespace vscode_keyboard {
std::vector<KeyMapping> GetKeyMapping() {
std::vector<KeyMapping> result;
Display *display;
if (!(display = XOpenDisplay(""))) {
return result;
}
XEvent event;
memset(&event, 0, sizeof(XEvent));
XKeyEvent* key_event = &event.xkey;
key_event->display = display;
key_event->type = KeyPress;
KeyModifierMaskToXModifierMask *mask_provider = &KeyModifierMaskToXModifierMask::GetInstance();
mask_provider->Initialize(display);
for (size_t i = 0; i < arraysize(ui::gKeyCodeToXKeyCode); ++i) {
ui::KeyboardCode key_code = ui::gKeyCodeToXKeyCode[i].key_code;
int x_key_code = ui::gKeyCodeToXKeyCode[i].x_key_code;
key_event->keycode = x_key_code;
key_event->state = 0;
std::string value = GetStrFromXEvent(&event);
key_event->state = mask_provider->XModFromKeyMod(kShiftKeyModifierMask);
std::string withShift = GetStrFromXEvent(&event);
key_event->state = mask_provider->XModFromKeyMod(kControlKeyModifierMask | kAltKeyModifierMask);
std::string withAltGr = GetStrFromXEvent(&event);
key_event->state = mask_provider->XModFromKeyMod(kShiftKeyModifierMask | kControlKeyModifierMask | kAltKeyModifierMask);
std::string withShiftAltGr = GetStrFromXEvent(&event);
KeyMapping keyMapping = KeyMapping();
keyMapping.key_code = key_code;
keyMapping.value = value;
keyMapping.withShift = withShift;
keyMapping.withAltGr = withAltGr;
keyMapping.withShiftAltGr = withShiftAltGr;
result.push_back(keyMapping);
}
XFlush(display);
XCloseDisplay(display);
return result;
}
} // namespace vscode_keyboard
<|endoftext|> |
<commit_before>/*
* V1.h
*
* Created on: Jul 30, 2008
*
*/
#ifndef V1_HPP_
#define V1_HPP_
#include "HyPerLayer.hpp"
#include "../arch/opencl/CLKernel.hpp"
#include "LIF2.h"
namespace PV
{
// by default uses LIF2 parameters
typedef LIF2_params LIFParams;
class V1: public PV::HyPerLayer
{
public:
V1(const char* name, HyPerCol * hc);
V1(const char* name, HyPerCol * hc, PVLayerType type);
virtual int updateState(float time, float dt);
virtual int updateStateOpenCL(float time, float dt);
virtual int writeState(const char * path, float time);
int setParams(PVParams * params, LIFParams * p);
protected:
// OpenCL variables
//
CLKernel * updatestate_kernel; // CL kernel for update state call
int nxl; // local grid size in x
int nyl; // local grid size in y
virtual int updateV();
virtual int setActivity();
virtual int resetPhiBuffers();
int resetBuffer(pvdata_t * buf, int numItems);
private:
virtual int initialize(PVLayerType type);
int findPostSynaptic(int dim, int maxSize, int col,
// input: which layer, which neuron
HyPerLayer *lSource, float pos[],
// output: how many of our neurons are connected.
// an array with their indices.
// an array with their feature vectors.
int* nNeurons, int nConnectedNeurons[], float *vPos);
};
} // namespace PV
#ifdef __cplusplus
extern "C"
{
#endif
#ifdef __cplusplus
}
#endif
#endif /* V1_HPP_ */
<commit_msg>Deleted some OBSOLETE code. Added some OpenCL implementation in preparation for real stuff. Actually mostly consistent use of #ifdef PV_USE_OPENCL to remove implementation.<commit_after>/*
* V1.h
*
* Created on: Jul 30, 2008
*
*/
#ifndef V1_HPP_
#define V1_HPP_
#include "HyPerLayer.hpp"
#include "../arch/opencl/CLKernel.hpp"
#include "LIF2.h"
namespace PV
{
// by default uses LIF2 parameters
typedef LIF2_params LIFParams;
class V1: public PV::HyPerLayer
{
public:
V1(const char* name, HyPerCol * hc);
V1(const char* name, HyPerCol * hc, PVLayerType type);
virtual int updateState(float time, float dt);
#ifdef PV_USE_OPENCL
virtual int updateStateOpenCL(float time, float dt);
#endif
virtual int writeState(const char * path, float time);
int setParams(PVParams * params, LIFParams * p);
protected:
virtual int updateV();
virtual int setActivity();
virtual int resetPhiBuffers();
int resetBuffer(pvdata_t * buf, int numItems);
private:
virtual int initialize(PVLayerType type);
int findPostSynaptic(int dim, int maxSize, int col,
// input: which layer, which neuron
HyPerLayer *lSource, float pos[],
// output: how many of our neurons are connected.
// an array with their indices.
// an array with their feature vectors.
int* nNeurons, int nConnectedNeurons[], float *vPos);
};
} // namespace PV
#ifdef __cplusplus
extern "C"
{
#endif
#ifdef __cplusplus
}
#endif
#endif /* V1_HPP_ */
<|endoftext|> |
<commit_before>#include <microscopes/lda/model.hpp>
microscopes::lda::model_definition::model_definition(size_t n, size_t v)
: n_(n), v_(v)
{
MICROSCOPES_DCHECK(n > 0, "no docs");
MICROSCOPES_DCHECK(v > 0, "no terms");
}
microscopes::lda::state::state(const model_definition &defn,
float alpha,
float beta,
float gamma,
const std::vector<std::vector<size_t>> &docs,
common::rng_t &rng)
: V(defn.v()),
alpha_(alpha),
beta_(beta),
gamma_(gamma),
x_ji(docs),
n_k(lda_util::defaultdict<size_t, float>(beta * defn.v()))
{
// This page intentionally left blank
}
microscopes::lda::state::state(const model_definition &defn,
float alpha,
float beta,
float gamma,
size_t initial_dishes,
const std::vector<std::vector<size_t>> &docs,
common::rng_t &rng)
: state(defn, alpha, beta, gamma, docs, rng) {
auto dish_pool = microscopes::common::util::range(initial_dishes);
create_dish(); // Dummy dish
for (size_t eid = 0; eid < nentities(); ++eid) {
create_entity();
auto did = common::util::sample_choice(dish_pool, rng);
if (did > dishes_.back()){
did = create_dish();
}
create_table(eid, did);
table_doc_word.push_back(std::vector<size_t>(nterms(eid), 0));
}
}
microscopes::lda::state::state(const model_definition &defn,
float alpha,
float beta,
float gamma,
const std::vector<std::vector<size_t>> &dish_assignments,
const std::vector<std::vector<size_t>> &table_assignments,
const std::vector<std::vector<size_t>> &docs,
common::rng_t &rng)
: state(defn, alpha, beta, gamma, docs, rng) {
}
void
microscopes::lda::state::create_entity(){
using_t.push_back(std::vector<size_t>());
n_jt.push_back(std::vector<size_t>());
restaurants_.push_back(std::vector<size_t>());
n_jtv.push_back(std::vector< std::map<size_t, size_t>>());
}
std::vector<std::vector<size_t>>
microscopes::lda::state::assignments() {
std::vector<std::vector<size_t>> ret;
ret.resize(nentities());
for (size_t eid = 0; eid < nentities(); eid++) {
ret[eid].resize(table_doc_word[eid].size());
for (size_t did = 0; did < table_doc_word[eid].size(); did++) {
auto table = table_doc_word[eid][did];
ret[eid][did] = restaurants_[eid][table];
}
}
return ret;
}
/**
* Returns, for each entity, a map from
* table IDs -> (global) dish assignments
*
*/
std::vector<std::vector<size_t>>
microscopes::lda::state::dish_assignments() {
return restaurants_;
}
/**
* Returns, for each entity, an assignment vector
* from each word to the (local) table it is assigned to.
*
*/
std::vector<std::vector<size_t>>
microscopes::lda::state::table_assignments() {
return table_doc_word;
}
float
microscopes::lda::state::score_assignment() const
{
return 0;
}
float
microscopes::lda::state::score_data(common::rng_t &rng) const
{
return 0;
}
std::vector<std::map<size_t, float>>
microscopes::lda::state::word_distribution() {
// Distribution over words for each topic
std::vector<std::map<size_t, float>> vec;
vec.reserve(dishes_.size());
for (auto k : dishes_) {
if (k == 0) continue;
vec.push_back(std::map<size_t, float>());
for (size_t v = 0; v < V; ++v) {
if (n_kv[k].contains(v)) {
vec.back()[v] = n_kv[k].get(v) / n_k.get(k);
}
else {
vec.back()[v] = beta_ / n_k.get(k);
}
}
}
return vec;
}
std::vector<std::vector<float>>
microscopes::lda::state::document_distribution () {
// Distribution over topics for each document
std::vector<std::vector<float>> theta;
theta.reserve(restaurants_.size());
std::vector<float> am_k(m_k.begin(), m_k.end());
am_k[0] = gamma_;
double sum_am_dishes_ = 0;
for (auto k : dishes_) {
sum_am_dishes_ += am_k[k];
}
for (size_t i = 0; i < am_k.size(); ++i) {
am_k[i] *= alpha_ / sum_am_dishes_;
}
for (size_t j = 0; j < restaurants_.size(); j++) {
std::vector<size_t> &n_jt_ = n_jt[j];
std::vector<float> p_jk = am_k;
for (auto t : using_t[j]) {
if (t == 0) continue;
size_t k = restaurants_[j][t];
p_jk[k] += n_jt_[t];
}
p_jk = lda_util::selectByIndex(p_jk, dishes_);
lda_util::normalize<float>(p_jk);
theta.push_back(p_jk);
}
return theta;
}
double
microscopes::lda::state::perplexity() {
std::vector<std::map<size_t, float>> phi = word_distribution();
std::vector<std::vector<float>> theta = document_distribution();
phi.insert(phi.begin(), std::map<size_t, float>());
double log_likelihood = 0;
size_t N = 0;
for (size_t j = 0; j < x_ji.size(); j++) {
auto &py_x_ji = x_ji[j];
auto &p_jk = theta[j];
for (auto &v : py_x_ji) {
double word_prob = 0;
for (size_t i = 0; i < p_jk.size(); i++) {
auto p = p_jk[i];
auto &p_kv = phi[i];
word_prob += p * p_kv[v];
}
log_likelihood -= distributions::fast_log(word_prob);
}
N += x_ji[j].size();
}
return exp(log_likelihood / N);
}
// private:
void
microscopes::lda::state::leave_from_dish(size_t j, size_t t) {
size_t k = restaurants_[j][t];
MICROSCOPES_DCHECK(k > 0, "k < = 0");
MICROSCOPES_DCHECK(m_k[k] > 0, "m_k[k] <= 0");
m_k[k] -= 1; // one less table for topic k
if (m_k[k] == 0) // destroy table
{
delete_dish(k);
restaurants_[j][t] = 0;
}
}
void
microscopes::lda::state::validate_n_k_values() {
return;
std::map<size_t, std::tuple<float, float>> values;
for (auto k : dishes_) {
float n_kv_sum = 0;
for (size_t v = 0; v < V; v++) {
n_kv_sum += n_kv[k].get(v);
}
values[k] = std::tuple<float, float>(n_kv_sum, n_k.get(k));
}
for (auto kv : values) {
if (kv.first == 0) continue;
MICROSCOPES_CHECK(std::abs((std::get<0>(kv.second) - std::get<1>(kv.second))) < 0.01,
"n_kv doesn't match n_k");
}
}
void
microscopes::lda::state::seat_at_dish(size_t j, size_t t, size_t k_new) {
m_k[k_new] += 1;
size_t k_old = restaurants_[j][t];
if (k_new != k_old)
{
MICROSCOPES_DCHECK(k_new != 0, "k_new is 0");
restaurants_[j][t] = k_new;
float n_jt_val = n_jt[j][t];
if (k_old != 0)
{
n_k.decr(k_old, n_jt_val);
}
n_k.incr(k_new, n_jt_val);
for (auto kv : n_jtv[j][t]) {
auto v = kv.first;
auto n = kv.second;
MICROSCOPES_DCHECK(v < nwords(), "Word out of bounds");
if (k_old != 0)
{
n_kv[k_old].decr(v, n);
}
n_kv[k_new].incr(v, n);
}
}
}
void
microscopes::lda::state::add_table(size_t ein, size_t t_new, size_t did) {
table_doc_word[ein][did] = t_new;
n_jt[ein][t_new] += 1;
size_t k_new = restaurants_[ein][t_new];
n_k.incr(k_new, 1);
size_t v = x_ji[ein][did];
MICROSCOPES_DCHECK(v < nwords(), "Word out of bounds");
n_kv[k_new].incr(v, 1);
n_jtv[ein][t_new][v] += 1;
}
size_t
microscopes::lda::state::create_dish() {
size_t k_new = dishes_.size();
for (size_t i = 0; i < dishes_.size(); ++i)
{
if (i != dishes_[i])
{
k_new = i;
break;
}
}
if (k_new == dishes_.size())
{
m_k.push_back(0);
n_kv.push_back(lda_util::defaultdict<size_t, float>(beta_));
MICROSCOPES_DCHECK(dishes_.size() == 0 || k_new == dishes_.back() + 1, "bad k_new (1)");
MICROSCOPES_DCHECK(k_new < n_kv.size(), "bad k_new (2)");
}
dishes_.insert(dishes_.begin() + k_new, k_new);
n_k.set(k_new, beta_ * V);
n_kv[k_new] = lda_util::defaultdict<size_t, float>(beta_);
m_k[k_new] = 0;
return k_new;
}
size_t
microscopes::lda::state::create_table(size_t ein, size_t k_new)
{
size_t t_new = using_t[ein].size();
for (size_t i = 0; i < using_t[ein].size(); ++i)
{
if (i != using_t[ein][i])
{
t_new = i;
break;
}
}
if (t_new == using_t[ein].size())
{
n_jt[ein].push_back(0);
restaurants_[ein].push_back(0);
n_jtv[ein].push_back(std::map<size_t, size_t>());
}
using_t[ein].insert(using_t[ein].begin() + t_new, t_new);
n_jt[ein][t_new] = 0;
// MICROSCOPES_DCHECK(k_new != 0, "k_new ");
restaurants_[ein][t_new] = k_new;
if (k_new != 0){
m_k[k_new] += 1;
}
return t_new;
}
void
microscopes::lda::state::remove_table(size_t eid, size_t tid) {
size_t t = table_doc_word[eid][tid];
if (t > 0)
{
size_t k = restaurants_[eid][t];
MICROSCOPES_DCHECK(k > 0, "k <= 0");
// decrease counters
size_t v = x_ji[eid][tid];
MICROSCOPES_DCHECK(v < nwords(), "Word out of bounds");
n_kv[k].decr(v, 1);
n_k.decr(k, 1);
n_jt[eid][t] -= 1;
n_jtv[eid][t][v] -= 1;
if (n_jt[eid][t] == 0)
{
delete_table(eid, t);
}
}
}
void
microscopes::lda::state::delete_table(size_t eid, size_t tid) {
size_t k = restaurants_[eid][tid];
lda_util::removeFirst(using_t[eid], tid);
m_k[k] -= 1;
MICROSCOPES_DCHECK(m_k[k] >= 0, "m_k[k] < 0");
if (m_k[k] == 0)
{
delete_dish(k);
}
}
<commit_msg>Create dishes based on assignment<commit_after>#include <microscopes/lda/model.hpp>
microscopes::lda::model_definition::model_definition(size_t n, size_t v)
: n_(n), v_(v)
{
MICROSCOPES_DCHECK(n > 0, "no docs");
MICROSCOPES_DCHECK(v > 0, "no terms");
}
microscopes::lda::state::state(const model_definition &defn,
float alpha,
float beta,
float gamma,
const std::vector<std::vector<size_t>> &docs,
common::rng_t &rng)
: V(defn.v()),
alpha_(alpha),
beta_(beta),
gamma_(gamma),
x_ji(docs),
n_k(lda_util::defaultdict<size_t, float>(beta * defn.v()))
{
// This page intentionally left blank
}
microscopes::lda::state::state(const model_definition &defn,
float alpha,
float beta,
float gamma,
size_t initial_dishes,
const std::vector<std::vector<size_t>> &docs,
common::rng_t &rng)
: state(defn, alpha, beta, gamma, docs, rng) {
auto dish_pool = microscopes::common::util::range(initial_dishes);
create_dish(); // Dummy dish
for (size_t eid = 0; eid < nentities(); ++eid) {
create_entity();
auto did = common::util::sample_choice(dish_pool, rng);
if (did > dishes_.back()){
did = create_dish();
}
create_table(eid, did);
table_doc_word.push_back(std::vector<size_t>(nterms(eid), 0));
}
}
microscopes::lda::state::state(const model_definition &defn,
float alpha,
float beta,
float gamma,
const std::vector<std::vector<size_t>> &dish_assignments,
const std::vector<std::vector<size_t>> &table_assignments,
const std::vector<std::vector<size_t>> &docs,
common::rng_t &rng)
: state(defn, alpha, beta, gamma, docs, rng) {
auto assigned_dishes = lda_util::unique_members(dish_assignments);
auto assigned_tables = lda_util::unique_members(table_assignments);
size_t num_dishes = *std::max_element(assigned_dishes.begin(), assigned_dishes.end());
num_dishes++;
for(size_t dish = 0; dish < num_dishes; dish++) {
create_dish();
}
}
void
microscopes::lda::state::create_entity(){
using_t.push_back(std::vector<size_t>());
n_jt.push_back(std::vector<size_t>());
restaurants_.push_back(std::vector<size_t>());
n_jtv.push_back(std::vector< std::map<size_t, size_t>>());
}
std::vector<std::vector<size_t>>
microscopes::lda::state::assignments() {
std::vector<std::vector<size_t>> ret;
ret.resize(nentities());
for (size_t eid = 0; eid < nentities(); eid++) {
ret[eid].resize(table_doc_word[eid].size());
for (size_t did = 0; did < table_doc_word[eid].size(); did++) {
auto table = table_doc_word[eid][did];
ret[eid][did] = restaurants_[eid][table];
}
}
return ret;
}
/**
* Returns, for each entity, a map from
* table IDs -> (global) dish assignments
*
*/
std::vector<std::vector<size_t>>
microscopes::lda::state::dish_assignments() {
return restaurants_;
}
/**
* Returns, for each entity, an assignment vector
* from each word to the (local) table it is assigned to.
*
*/
std::vector<std::vector<size_t>>
microscopes::lda::state::table_assignments() {
return table_doc_word;
}
float
microscopes::lda::state::score_assignment() const
{
return 0;
}
float
microscopes::lda::state::score_data(common::rng_t &rng) const
{
return 0;
}
std::vector<std::map<size_t, float>>
microscopes::lda::state::word_distribution() {
// Distribution over words for each topic
std::vector<std::map<size_t, float>> vec;
vec.reserve(dishes_.size());
for (auto k : dishes_) {
if (k == 0) continue;
vec.push_back(std::map<size_t, float>());
for (size_t v = 0; v < V; ++v) {
if (n_kv[k].contains(v)) {
vec.back()[v] = n_kv[k].get(v) / n_k.get(k);
}
else {
vec.back()[v] = beta_ / n_k.get(k);
}
}
}
return vec;
}
std::vector<std::vector<float>>
microscopes::lda::state::document_distribution () {
// Distribution over topics for each document
std::vector<std::vector<float>> theta;
theta.reserve(restaurants_.size());
std::vector<float> am_k(m_k.begin(), m_k.end());
am_k[0] = gamma_;
double sum_am_dishes_ = 0;
for (auto k : dishes_) {
sum_am_dishes_ += am_k[k];
}
for (size_t i = 0; i < am_k.size(); ++i) {
am_k[i] *= alpha_ / sum_am_dishes_;
}
for (size_t j = 0; j < restaurants_.size(); j++) {
std::vector<size_t> &n_jt_ = n_jt[j];
std::vector<float> p_jk = am_k;
for (auto t : using_t[j]) {
if (t == 0) continue;
size_t k = restaurants_[j][t];
p_jk[k] += n_jt_[t];
}
p_jk = lda_util::selectByIndex(p_jk, dishes_);
lda_util::normalize<float>(p_jk);
theta.push_back(p_jk);
}
return theta;
}
double
microscopes::lda::state::perplexity() {
std::vector<std::map<size_t, float>> phi = word_distribution();
std::vector<std::vector<float>> theta = document_distribution();
phi.insert(phi.begin(), std::map<size_t, float>());
double log_likelihood = 0;
size_t N = 0;
for (size_t j = 0; j < x_ji.size(); j++) {
auto &py_x_ji = x_ji[j];
auto &p_jk = theta[j];
for (auto &v : py_x_ji) {
double word_prob = 0;
for (size_t i = 0; i < p_jk.size(); i++) {
auto p = p_jk[i];
auto &p_kv = phi[i];
word_prob += p * p_kv[v];
}
log_likelihood -= distributions::fast_log(word_prob);
}
N += x_ji[j].size();
}
return exp(log_likelihood / N);
}
// private:
void
microscopes::lda::state::leave_from_dish(size_t j, size_t t) {
size_t k = restaurants_[j][t];
MICROSCOPES_DCHECK(k > 0, "k < = 0");
MICROSCOPES_DCHECK(m_k[k] > 0, "m_k[k] <= 0");
m_k[k] -= 1; // one less table for topic k
if (m_k[k] == 0) // destroy table
{
delete_dish(k);
restaurants_[j][t] = 0;
}
}
void
microscopes::lda::state::validate_n_k_values() {
return;
std::map<size_t, std::tuple<float, float>> values;
for (auto k : dishes_) {
float n_kv_sum = 0;
for (size_t v = 0; v < V; v++) {
n_kv_sum += n_kv[k].get(v);
}
values[k] = std::tuple<float, float>(n_kv_sum, n_k.get(k));
}
for (auto kv : values) {
if (kv.first == 0) continue;
MICROSCOPES_CHECK(std::abs((std::get<0>(kv.second) - std::get<1>(kv.second))) < 0.01,
"n_kv doesn't match n_k");
}
}
void
microscopes::lda::state::seat_at_dish(size_t j, size_t t, size_t k_new) {
m_k[k_new] += 1;
size_t k_old = restaurants_[j][t];
if (k_new != k_old)
{
MICROSCOPES_DCHECK(k_new != 0, "k_new is 0");
restaurants_[j][t] = k_new;
float n_jt_val = n_jt[j][t];
if (k_old != 0)
{
n_k.decr(k_old, n_jt_val);
}
n_k.incr(k_new, n_jt_val);
for (auto kv : n_jtv[j][t]) {
auto v = kv.first;
auto n = kv.second;
MICROSCOPES_DCHECK(v < nwords(), "Word out of bounds");
if (k_old != 0)
{
n_kv[k_old].decr(v, n);
}
n_kv[k_new].incr(v, n);
}
}
}
void
microscopes::lda::state::add_table(size_t ein, size_t t_new, size_t did) {
table_doc_word[ein][did] = t_new;
n_jt[ein][t_new] += 1;
size_t k_new = restaurants_[ein][t_new];
n_k.incr(k_new, 1);
size_t v = x_ji[ein][did];
MICROSCOPES_DCHECK(v < nwords(), "Word out of bounds");
n_kv[k_new].incr(v, 1);
n_jtv[ein][t_new][v] += 1;
}
size_t
microscopes::lda::state::create_dish() {
size_t k_new = dishes_.size();
for (size_t i = 0; i < dishes_.size(); ++i)
{
if (i != dishes_[i])
{
k_new = i;
break;
}
}
if (k_new == dishes_.size())
{
m_k.push_back(0);
n_kv.push_back(lda_util::defaultdict<size_t, float>(beta_));
MICROSCOPES_DCHECK(dishes_.size() == 0 || k_new == dishes_.back() + 1, "bad k_new (1)");
MICROSCOPES_DCHECK(k_new < n_kv.size(), "bad k_new (2)");
}
dishes_.insert(dishes_.begin() + k_new, k_new);
n_k.set(k_new, beta_ * V);
n_kv[k_new] = lda_util::defaultdict<size_t, float>(beta_);
m_k[k_new] = 0;
return k_new;
}
size_t
microscopes::lda::state::create_table(size_t ein, size_t k_new)
{
size_t t_new = using_t[ein].size();
for (size_t i = 0; i < using_t[ein].size(); ++i)
{
if (i != using_t[ein][i])
{
t_new = i;
break;
}
}
if (t_new == using_t[ein].size())
{
n_jt[ein].push_back(0);
restaurants_[ein].push_back(0);
n_jtv[ein].push_back(std::map<size_t, size_t>());
}
using_t[ein].insert(using_t[ein].begin() + t_new, t_new);
n_jt[ein][t_new] = 0;
// MICROSCOPES_DCHECK(k_new != 0, "k_new ");
restaurants_[ein][t_new] = k_new;
if (k_new != 0){
m_k[k_new] += 1;
}
return t_new;
}
void
microscopes::lda::state::remove_table(size_t eid, size_t tid) {
size_t t = table_doc_word[eid][tid];
if (t > 0)
{
size_t k = restaurants_[eid][t];
MICROSCOPES_DCHECK(k > 0, "k <= 0");
// decrease counters
size_t v = x_ji[eid][tid];
MICROSCOPES_DCHECK(v < nwords(), "Word out of bounds");
n_kv[k].decr(v, 1);
n_k.decr(k, 1);
n_jt[eid][t] -= 1;
n_jtv[eid][t][v] -= 1;
if (n_jt[eid][t] == 0)
{
delete_table(eid, t);
}
}
}
void
microscopes::lda::state::delete_table(size_t eid, size_t tid) {
size_t k = restaurants_[eid][tid];
lda_util::removeFirst(using_t[eid], tid);
m_k[k] -= 1;
MICROSCOPES_DCHECK(m_k[k] >= 0, "m_k[k] < 0");
if (m_k[k] == 0)
{
delete_dish(k);
}
}
<|endoftext|> |
<commit_before>// config.cc
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright 2013-2014 Yandex LLC
// \file
// Configuration and version utilties
#include <unistd.h>
#include <iostream>
#include <dcd/config.h>
using namespace std;
namespace dcd {
void PrintVersionInfo() {
#ifndef OS_WIN
cerr << "Version information : " << endl;
cerr << "\tgit revision\t\t: " << g_dcd_gitrevision << endl;
cerr << "\tCompiled on\t\t: " << __DATE__ << " " << __TIME__ << endl;
cerr << "\tCompiler flags\t\t: " << g_dcd_cflags << endl;
cerr << "\tLinker flags\t\t: " << g_dcd_lflags << endl;
cerr << "\tCompiler version\t: " << g_dcd_compiler_version << endl << endl;
#endif
}
//Functions to queury to the total system memory
//Answer from http://stackoverflow.com/questions/2513505/how-to-get-available-memory-c-g
#ifdef MSVCVER
size_t GetTotalSystemMemory() {
MEMORYSTATUSEX status;
status.dwLength = sizeof(status);
GlobalMemoryStatusEx(&status);
return status.ullTotalPhys;
}
#else
size_t GetTotalSystemMemory() {
/*
long pages = sysconf(_SC_PHYS_PAGES);
long page_size = sysconf(_SC_PAGE_SIZE);
return pages * page_size; */
return 0;
}
#endif
void PrintMachineInfo() {
cerr << "Machine information : " << endl;
cerr << "\tNumber of cores\t\t: " << endl;
cerr << "\tNumber of threads\t: " << endl;
cerr << "\tMachine load\t\t: " << endl;
cerr << "\tMachine is virtual\t: " << endl;
cerr << "\tAmount of memory\t: " << GetTotalSystemMemory() << endl;
cerr << "\tOS version\t\t: " << endl;
cerr << "\tHostname\t\t: " << endl;
}
///Code take from https://www.hackerzvoice.net/ouah/Red_%20Pill.html
int SwallowRedpill () {
unsigned char m[2+4], rpill[] = "\x0f\x01\x0d\x00\x00\x00\x00\xc3";
*((unsigned long*)&rpill[3]) = (unsigned long)m;
((void(*)())&rpill)();
return (m[5]>0xd0) ? 1 : 0;
}
} //namespace dcd
<commit_msg>Get hostname functions<commit_after>// config.cc
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright 2013-2014 Yandex LLC
// \file
// Configuration and version utilties
#include <unistd.h>
#include <iostream>
#include <dcd/config.h>
using namespace std;
namespace dcd {
void PrintVersionInfo() {
#ifndef OS_WIN
cerr << "Version information : " << endl;
cerr << "\tgit revision\t\t: " << g_dcd_gitrevision << endl;
cerr << "\tCompiled on\t\t: " << __DATE__ << " " << __TIME__ << endl;
cerr << "\tCompiler flags\t\t: " << g_dcd_cflags << endl;
cerr << "\tLinker flags\t\t: " << g_dcd_lflags << endl;
cerr << "\tCompiler version\t: " << g_dcd_compiler_version << endl << endl;
#endif
}
//Functions to queury to the total system memory
//Answer from http://stackoverflow.com/questions/2513505/how-to-get-available-memory-c-g
#ifdef MSVCVER
size_t GetTotalSystemMemory() {
MEMORYSTATUSEX status;
status.dwLength = sizeof(status);
GlobalMemoryStatusEx(&status);
return status.ullTotalPhys;
}
#else
size_t GetTotalSystemMemory() {
/*
long pages = sysconf(_SC_PHYS_PAGES);
long page_size = sysconf(_SC_PAGE_SIZE);
return pages * page_size; */
return 0;
}
#endif
#ifdef _MSCVER
string GetHostname() {
return "";
}
#else
string GetHostname() {
char str[1024];
memset(str, 0, 1024);
gethostname(str, 1024);
return string(str);
#endif
void PrintMachineInfo() {
cerr << "Machine information : " << endl;
cerr << "\tNumber of cores\t\t: " << endl;
cerr << "\tNumber of threads\t: " << endl;
cerr << "\tMachine load\t\t: " << endl;
cerr << "\tMachine is virtual\t: " << endl;
cerr << "\tAmount of memory\t: " << GetTotalSystemMemory() << endl;
cerr << "\tOS version\t\t: " << endl;
cerr << "\tHostname\t\t: " << GetHostname() << endl;
}
///Code take from https://www.hackerzvoice.net/ouah/Red_%20Pill.html
int SwallowRedpill () {
unsigned char m[2+4], rpill[] = "\x0f\x01\x0d\x00\x00\x00\x00\xc3";
*((unsigned long*)&rpill[3]) = (unsigned long)m;
((void(*)())&rpill)();
return (m[5]>0xd0) ? 1 : 0;
}
} //namespace dcd
<|endoftext|> |
<commit_before>#include <nan.h>
#include <boost/coroutine/all.hpp>
#include <sstream>
using v8::FunctionTemplate;
using v8::Handle;
using v8::Object;
using v8::String;
NAN_METHOD(Fibo) {
NanScope();
boost::coroutines::asymmetric_coroutine<int>::pull_type source(
[&](boost::coroutines::asymmetric_coroutine<int>::push_type& sink) {
int first = 1, second = 1;
sink(first);
sink(second);
for (int i = 0; i < 8; ++i)
{
int third = first + second;
first = second;
second = third;
sink( third);
}
});
std::stringstream ss;
bool first = true;
for (auto i : source) {
if (!first) {
ss << " ";
}
else {
first = false;
}
ss << i;
}
NanReturnValue(NanNew<String>(ss.str().c_str()));
}
void InitAll(Handle<Object> exports) {
exports->Set(NanNew<String>("fibo"),
NanNew<FunctionTemplate>(Fibo)->GetFunction());
}
NODE_MODULE(addon, InitAll)<commit_msg>comments<commit_after>#include <nan.h>
#include <boost/coroutine/all.hpp>
#include <sstream>
using v8::FunctionTemplate;
using v8::Handle;
using v8::Object;
using v8::String;
NAN_METHOD(Fibo) {
NanScope();
// Lambda from the Fibonacci example:
boost::coroutines::asymmetric_coroutine<int>::pull_type source(
[&](boost::coroutines::asymmetric_coroutine<int>::push_type& sink) {
int first = 1, second = 1;
sink(first);
sink(second);
for (int i = 0; i < 8; ++i)
{
int third = first + second;
first = second;
second = third;
sink( third);
}
});
// Write the results to a string stream:
std::stringstream ss;
bool first = true;
for (auto i : source) {
if (!first) {
ss << " ";
}
else {
first = false;
}
ss << i;
}
// Return it to node engine
NanReturnValue(NanNew<String>(ss.str().c_str()));
}
void InitAll(Handle<Object> exports) {
// Method that returns the generated Fibonacci sequence as a string:
exports->Set(NanNew<String>("fibo"),
NanNew<FunctionTemplate>(Fibo)->GetFunction());
}
NODE_MODULE(addon, InitAll)<|endoftext|> |
<commit_before>#include "config.h"
#include "main.h"
#include <string.h>
#include <errno.h>
#include <time.h>
#ifdef HAVE_WINDOWS_H
#include <windows.h>
#endif
#include <vector>
const ALchar *last_error = "No error";
#define MAKE_FUNC(x) typeof(x) * p##x
#ifdef HAS_SNDFILE
void *sndfile_handle;
MAKE_FUNC(sf_open);
MAKE_FUNC(sf_open_virtual);
MAKE_FUNC(sf_close);
MAKE_FUNC(sf_readf_short);
MAKE_FUNC(sf_seek);
#endif
#ifdef HAS_VORBISFILE
void *vorbisfile_handle;
MAKE_FUNC(ov_open_callbacks);
MAKE_FUNC(ov_clear);
MAKE_FUNC(ov_info);
MAKE_FUNC(ov_read);
MAKE_FUNC(ov_pcm_seek);
#endif
#ifdef HAS_MPG123
void *mpg123_hdl;
MAKE_FUNC(mpg123_init);
MAKE_FUNC(mpg123_new);
MAKE_FUNC(mpg123_open_64);
MAKE_FUNC(mpg123_open_feed);
MAKE_FUNC(mpg123_delete);
MAKE_FUNC(mpg123_decode);
MAKE_FUNC(mpg123_read);
MAKE_FUNC(mpg123_format_none);
MAKE_FUNC(mpg123_getformat);
MAKE_FUNC(mpg123_format);
MAKE_FUNC(mpg123_seek_64);
#endif
#undef MAKE_FUNC
static void init_libs()
{
#if defined(HAVE_WINDOWS_H) && defined(HAS_LOADLIBRARY)
# define LOAD_FUNC(x, f) do { \
p##f = reinterpret_cast<typeof(f)*>(GetProcAddress((HMODULE)x, #f)); \
if(!(p##f)) \
fprintf(stderr, "Could not load "#f"\n"); \
} while(0)
#ifdef HAS_SNDFILE
sndfile_handle = LoadLibrary("sndfile.dll");
#endif
#ifdef HAS_VORBISFILE
vorbisfile_handle = LoadLibrary("vorbisfile.dll");
#endif
#ifdef HAS_MPG123
mpg123_hdl = LoadLibrary("mpg123.dll");
#endif
#elif defined(HAS_DLOPEN)
# define LOAD_FUNC(x, f) do { \
p##f = reinterpret_cast<typeof(f)*>(dlsym(x, #f)); \
if((err=dlerror()) != NULL) { \
fprintf(stderr, "Could not load "#f": %s\n", err); \
p##f = NULL; \
} \
} while(0)
const char *err;
#ifdef HAS_SNDFILE
sndfile_handle = dlopen("libsndfile.so.1", RTLD_NOW);
#endif
#ifdef HAS_VORBISFILE
vorbisfile_handle = dlopen("libvorbisfile.so.3", RTLD_NOW);
#endif
#ifdef HAS_MPG123
mpg123_hdl = dlopen("libmpg123.so.0", RTLD_NOW);
#endif
#else
# define LOAD_FUNC(m, x) (p##x = x)
#ifdef HAS_SNDFILE
sndfile_handle = (void*)0xDECAFBAD;
#endif
#ifdef HAS_VORBISFILE
vorbisfile_handle = (void*)0xDEADBEEF;
#endif
#ifdef HAS_MPG123
mpg123_hdl = (void*)0xD00FBA11;
#endif
#endif
#ifdef HAS_SNDFILE
if(sndfile_handle)
{
LOAD_FUNC(sndfile_handle, sf_open);
LOAD_FUNC(sndfile_handle, sf_open_virtual);
LOAD_FUNC(sndfile_handle, sf_close);
LOAD_FUNC(sndfile_handle, sf_readf_short);
LOAD_FUNC(sndfile_handle, sf_seek);
if(!psf_open || !psf_open_virtual || !psf_close || !psf_readf_short ||
!psf_seek)
sndfile_handle = NULL;
}
#endif
#ifdef HAS_VORBISFILE
if(vorbisfile_handle)
{
LOAD_FUNC(vorbisfile_handle, ov_open_callbacks);
LOAD_FUNC(vorbisfile_handle, ov_clear);
LOAD_FUNC(vorbisfile_handle, ov_info);
LOAD_FUNC(vorbisfile_handle, ov_read);
LOAD_FUNC(vorbisfile_handle, ov_pcm_seek);
if(!pov_open_callbacks || !pov_clear || !pov_info || !pov_read ||
!pov_pcm_seek)
vorbisfile_handle = NULL;
}
#endif
#ifdef HAS_MPG123
if(mpg123_hdl)
{
LOAD_FUNC(mpg123_hdl, mpg123_init);
LOAD_FUNC(mpg123_hdl, mpg123_new);
LOAD_FUNC(mpg123_hdl, mpg123_open_64);
LOAD_FUNC(mpg123_hdl, mpg123_open_feed);
LOAD_FUNC(mpg123_hdl, mpg123_decode);
LOAD_FUNC(mpg123_hdl, mpg123_read);
LOAD_FUNC(mpg123_hdl, mpg123_getformat);
LOAD_FUNC(mpg123_hdl, mpg123_format_none);
LOAD_FUNC(mpg123_hdl, mpg123_format);
LOAD_FUNC(mpg123_hdl, mpg123_delete);
LOAD_FUNC(mpg123_hdl, mpg123_seek_64);
if(!pmpg123_init || !pmpg123_new || !pmpg123_open_64 ||
!pmpg123_open_feed || !pmpg123_decode || !pmpg123_read ||
!pmpg123_getformat || !pmpg123_format_none || !pmpg123_format ||
!pmpg123_delete || !pmpg123_seek_64 || pmpg123_init() != MPG123_OK)
mpg123_hdl = NULL;
}
#endif
#undef LOAD_FUNC
}
void init_alure()
{
static bool done = false;
if(done) return;
done = true;
init_libs();
}
extern "C" {
/* Function: alureGetErrorString
*
* Returns a string describing the last error encountered.
*/
ALURE_API const ALchar* ALURE_APIENTRY alureGetErrorString(void)
{
const ALchar *ret = last_error;
last_error = "No error";
return ret;
}
/* Function: alureGetDeviceNames
*
* Gets an array of device name strings from OpenAL. This encapsulates
* AL_ENUMERATE_ALL_EXT (if supported and 'all' is true) and standard
* enumeration, with 'count' being set to the number of returned device
* names. Returns NULL on error.
*
* See Also: <alureFreeDeviceNames>
*/
ALURE_API const ALCchar** ALURE_APIENTRY alureGetDeviceNames(ALCboolean all, ALCsizei *count)
{
init_alure();
const ALCchar *list = NULL;
if(all && alcIsExtensionPresent(NULL, "ALC_ENUMERATE_ALL_EXT"))
list = alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
else
list = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
if(!list)
{
alcGetError(NULL);
last_error = "No device names found";
return NULL;
}
const ALCchar *cur = list;
ALuint retlistLen = 0;
while(*cur)
{
cur += strlen(cur)+1;
retlistLen++;
}
const ALCchar **retlist = new const ALCchar*[retlistLen];
retlistLen = 0;
cur = list;
while(*cur)
{
retlist[retlistLen] = cur;
cur += strlen(cur)+1;
retlistLen++;
}
*count = retlistLen;
return retlist;
}
/* Function: alureFreeDeviceNames
*
* Frees the device name array returned from alureGetDeviceNames.
*
* See Also: <alureGetDeviceNames>
*/
ALURE_API ALvoid ALURE_APIENTRY alureFreeDeviceNames(const ALCchar **names)
{
init_alure();
delete[] names;
}
/* Function: alureInitDevice
*
* Opens the named device, creates a context with the given attributes, and
* sets that context as current. The name and attribute list would be the same
* as what's passed to alcOpenDevice and alcCreateContext respectively. Returns
* AL_FALSE on error.
*
* See Also: <alureShutdownDevice>
*/
ALURE_API ALboolean ALURE_APIENTRY alureInitDevice(const ALCchar *name, const ALCint *attribs)
{
init_alure();
ALCdevice *device = alcOpenDevice(name);
if(!device)
{
alcGetError(NULL);
last_error = "Device open failed";
return AL_FALSE;
}
ALCcontext *context = alcCreateContext(device, attribs);
if(alcGetError(device) != ALC_NO_ERROR || !context)
{
alcCloseDevice(device);
last_error = "Context creation failed";
return AL_FALSE;
}
alcMakeContextCurrent(context);
if(alcGetError(device) != AL_NO_ERROR)
{
alcDestroyContext(context);
alcCloseDevice(device);
last_error = "Context setup failed";
return AL_FALSE;
}
return AL_TRUE;
}
/* Function: alureShutdownDevice
*
* Destroys the current context and closes its associated device. Returns
* AL_FALSE on error.
*
* See Also: <alureInitDevice>
*/
ALURE_API ALboolean ALURE_APIENTRY alureShutdownDevice(void)
{
init_alure();
ALCcontext *context = alcGetCurrentContext();
ALCdevice *device = alcGetContextsDevice(context);
if(alcGetError(device) || !device)
{
last_error = "Failed to get current device";
return AL_FALSE;
}
alcMakeContextCurrent(NULL);
alcDestroyContext(context);
alcCloseDevice(device);
alcGetError(NULL);
return AL_TRUE;
}
/* Function: alureSleep
*
* Rests the calling thread for the given number of seconds. Returns AL_FALSE
* on error.
*/
ALURE_API ALboolean ALURE_APIENTRY alureSleep(ALfloat duration)
{
init_alure();
if(duration < 0.0f)
{
last_error = "Invalid duration";
return AL_FALSE;
}
ALuint seconds = (ALuint)duration;
ALfloat rest = duration - (ALfloat)seconds;
#ifdef HAVE_NANOSLEEP
struct timespec t, remainingTime;
t.tv_sec = (time_t)seconds;
t.tv_nsec = (long)(rest*1000000000);
while(nanosleep(&t, &remainingTime) < 0 && errno == EINTR)
t = remainingTime;
#elif defined(HAVE_WINDOWS_H)
while(seconds > 0)
{
Sleep(1000);
seconds--;
}
Sleep((DWORD)(rest * 1000));
#endif
return AL_TRUE;
}
} // extern "C"
<commit_msg>Load the right dynamic libs in OSX<commit_after>#include "config.h"
#include "main.h"
#include <string.h>
#include <errno.h>
#include <time.h>
#ifdef HAVE_WINDOWS_H
#include <windows.h>
#endif
#include <vector>
const ALchar *last_error = "No error";
#define MAKE_FUNC(x) typeof(x) * p##x
#ifdef HAS_SNDFILE
void *sndfile_handle;
MAKE_FUNC(sf_open);
MAKE_FUNC(sf_open_virtual);
MAKE_FUNC(sf_close);
MAKE_FUNC(sf_readf_short);
MAKE_FUNC(sf_seek);
#endif
#ifdef HAS_VORBISFILE
void *vorbisfile_handle;
MAKE_FUNC(ov_open_callbacks);
MAKE_FUNC(ov_clear);
MAKE_FUNC(ov_info);
MAKE_FUNC(ov_read);
MAKE_FUNC(ov_pcm_seek);
#endif
#ifdef HAS_MPG123
void *mpg123_hdl;
MAKE_FUNC(mpg123_init);
MAKE_FUNC(mpg123_new);
MAKE_FUNC(mpg123_open_64);
MAKE_FUNC(mpg123_open_feed);
MAKE_FUNC(mpg123_delete);
MAKE_FUNC(mpg123_decode);
MAKE_FUNC(mpg123_read);
MAKE_FUNC(mpg123_format_none);
MAKE_FUNC(mpg123_getformat);
MAKE_FUNC(mpg123_format);
MAKE_FUNC(mpg123_seek_64);
#endif
#undef MAKE_FUNC
static void init_libs()
{
#if defined(HAVE_WINDOWS_H) && defined(HAS_LOADLIBRARY)
# define LOAD_FUNC(x, f) do { \
p##f = reinterpret_cast<typeof(f)*>(GetProcAddress((HMODULE)x, #f)); \
if(!(p##f)) \
fprintf(stderr, "Could not load "#f"\n"); \
} while(0)
#ifdef HAS_SNDFILE
sndfile_handle = LoadLibrary("sndfile.dll");
#endif
#ifdef HAS_VORBISFILE
vorbisfile_handle = LoadLibrary("vorbisfile.dll");
#endif
#ifdef HAS_MPG123
mpg123_hdl = LoadLibrary("mpg123.dll");
#endif
#elif defined(HAS_DLOPEN)
# define LOAD_FUNC(x, f) do { \
p##f = reinterpret_cast<typeof(f)*>(dlsym(x, #f)); \
if((err=dlerror()) != NULL) { \
fprintf(stderr, "Could not load "#f": %s\n", err); \
p##f = NULL; \
} \
} while(0)
#ifdef __APPLE__
# define VER_PREFIX
# define VER_POSTFIX ".dylib"
#else
# define VER_PREFIX ".so"
# define VER_POSTFIX
#endif
const char *err;
#ifdef HAS_SNDFILE
sndfile_handle = dlopen("libsndfile"VER_PREFIX".1"VER_POSTFIX, RTLD_NOW);
#endif
#ifdef HAS_VORBISFILE
vorbisfile_handle = dlopen("libvorbisfile"VER_PREFIX".3"VER_POSTFIX, RTLD_NOW);
#endif
#ifdef HAS_MPG123
mpg123_hdl = dlopen("libmpg123"VER_PREFIX".0"VER_POSTFIX, RTLD_NOW);
#endif
#undef VER_PREFIX
#undef VER_POSTFIX
#else
# define LOAD_FUNC(m, x) (p##x = x)
#ifdef HAS_SNDFILE
sndfile_handle = (void*)0xDECAFBAD;
#endif
#ifdef HAS_VORBISFILE
vorbisfile_handle = (void*)0xDEADBEEF;
#endif
#ifdef HAS_MPG123
mpg123_hdl = (void*)0xD00FBA11;
#endif
#endif
#ifdef HAS_SNDFILE
if(sndfile_handle)
{
LOAD_FUNC(sndfile_handle, sf_open);
LOAD_FUNC(sndfile_handle, sf_open_virtual);
LOAD_FUNC(sndfile_handle, sf_close);
LOAD_FUNC(sndfile_handle, sf_readf_short);
LOAD_FUNC(sndfile_handle, sf_seek);
if(!psf_open || !psf_open_virtual || !psf_close || !psf_readf_short ||
!psf_seek)
sndfile_handle = NULL;
}
#endif
#ifdef HAS_VORBISFILE
if(vorbisfile_handle)
{
LOAD_FUNC(vorbisfile_handle, ov_open_callbacks);
LOAD_FUNC(vorbisfile_handle, ov_clear);
LOAD_FUNC(vorbisfile_handle, ov_info);
LOAD_FUNC(vorbisfile_handle, ov_read);
LOAD_FUNC(vorbisfile_handle, ov_pcm_seek);
if(!pov_open_callbacks || !pov_clear || !pov_info || !pov_read ||
!pov_pcm_seek)
vorbisfile_handle = NULL;
}
#endif
#ifdef HAS_MPG123
if(mpg123_hdl)
{
LOAD_FUNC(mpg123_hdl, mpg123_init);
LOAD_FUNC(mpg123_hdl, mpg123_new);
LOAD_FUNC(mpg123_hdl, mpg123_open_64);
LOAD_FUNC(mpg123_hdl, mpg123_open_feed);
LOAD_FUNC(mpg123_hdl, mpg123_decode);
LOAD_FUNC(mpg123_hdl, mpg123_read);
LOAD_FUNC(mpg123_hdl, mpg123_getformat);
LOAD_FUNC(mpg123_hdl, mpg123_format_none);
LOAD_FUNC(mpg123_hdl, mpg123_format);
LOAD_FUNC(mpg123_hdl, mpg123_delete);
LOAD_FUNC(mpg123_hdl, mpg123_seek_64);
if(!pmpg123_init || !pmpg123_new || !pmpg123_open_64 ||
!pmpg123_open_feed || !pmpg123_decode || !pmpg123_read ||
!pmpg123_getformat || !pmpg123_format_none || !pmpg123_format ||
!pmpg123_delete || !pmpg123_seek_64 || pmpg123_init() != MPG123_OK)
mpg123_hdl = NULL;
}
#endif
#undef LOAD_FUNC
}
void init_alure()
{
static bool done = false;
if(done) return;
done = true;
init_libs();
}
extern "C" {
/* Function: alureGetErrorString
*
* Returns a string describing the last error encountered.
*/
ALURE_API const ALchar* ALURE_APIENTRY alureGetErrorString(void)
{
const ALchar *ret = last_error;
last_error = "No error";
return ret;
}
/* Function: alureGetDeviceNames
*
* Gets an array of device name strings from OpenAL. This encapsulates
* AL_ENUMERATE_ALL_EXT (if supported and 'all' is true) and standard
* enumeration, with 'count' being set to the number of returned device
* names. Returns NULL on error.
*
* See Also: <alureFreeDeviceNames>
*/
ALURE_API const ALCchar** ALURE_APIENTRY alureGetDeviceNames(ALCboolean all, ALCsizei *count)
{
init_alure();
const ALCchar *list = NULL;
if(all && alcIsExtensionPresent(NULL, "ALC_ENUMERATE_ALL_EXT"))
list = alcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
else
list = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
if(!list)
{
alcGetError(NULL);
last_error = "No device names found";
return NULL;
}
const ALCchar *cur = list;
ALuint retlistLen = 0;
while(*cur)
{
cur += strlen(cur)+1;
retlistLen++;
}
const ALCchar **retlist = new const ALCchar*[retlistLen];
retlistLen = 0;
cur = list;
while(*cur)
{
retlist[retlistLen] = cur;
cur += strlen(cur)+1;
retlistLen++;
}
*count = retlistLen;
return retlist;
}
/* Function: alureFreeDeviceNames
*
* Frees the device name array returned from alureGetDeviceNames.
*
* See Also: <alureGetDeviceNames>
*/
ALURE_API ALvoid ALURE_APIENTRY alureFreeDeviceNames(const ALCchar **names)
{
init_alure();
delete[] names;
}
/* Function: alureInitDevice
*
* Opens the named device, creates a context with the given attributes, and
* sets that context as current. The name and attribute list would be the same
* as what's passed to alcOpenDevice and alcCreateContext respectively. Returns
* AL_FALSE on error.
*
* See Also: <alureShutdownDevice>
*/
ALURE_API ALboolean ALURE_APIENTRY alureInitDevice(const ALCchar *name, const ALCint *attribs)
{
init_alure();
ALCdevice *device = alcOpenDevice(name);
if(!device)
{
alcGetError(NULL);
last_error = "Device open failed";
return AL_FALSE;
}
ALCcontext *context = alcCreateContext(device, attribs);
if(alcGetError(device) != ALC_NO_ERROR || !context)
{
alcCloseDevice(device);
last_error = "Context creation failed";
return AL_FALSE;
}
alcMakeContextCurrent(context);
if(alcGetError(device) != AL_NO_ERROR)
{
alcDestroyContext(context);
alcCloseDevice(device);
last_error = "Context setup failed";
return AL_FALSE;
}
return AL_TRUE;
}
/* Function: alureShutdownDevice
*
* Destroys the current context and closes its associated device. Returns
* AL_FALSE on error.
*
* See Also: <alureInitDevice>
*/
ALURE_API ALboolean ALURE_APIENTRY alureShutdownDevice(void)
{
init_alure();
ALCcontext *context = alcGetCurrentContext();
ALCdevice *device = alcGetContextsDevice(context);
if(alcGetError(device) || !device)
{
last_error = "Failed to get current device";
return AL_FALSE;
}
alcMakeContextCurrent(NULL);
alcDestroyContext(context);
alcCloseDevice(device);
alcGetError(NULL);
return AL_TRUE;
}
/* Function: alureSleep
*
* Rests the calling thread for the given number of seconds. Returns AL_FALSE
* on error.
*/
ALURE_API ALboolean ALURE_APIENTRY alureSleep(ALfloat duration)
{
init_alure();
if(duration < 0.0f)
{
last_error = "Invalid duration";
return AL_FALSE;
}
ALuint seconds = (ALuint)duration;
ALfloat rest = duration - (ALfloat)seconds;
#ifdef HAVE_NANOSLEEP
struct timespec t, remainingTime;
t.tv_sec = (time_t)seconds;
t.tv_nsec = (long)(rest*1000000000);
while(nanosleep(&t, &remainingTime) < 0 && errno == EINTR)
t = remainingTime;
#elif defined(HAVE_WINDOWS_H)
while(seconds > 0)
{
Sleep(1000);
seconds--;
}
Sleep((DWORD)(rest * 1000));
#endif
return AL_TRUE;
}
} // extern "C"
<|endoftext|> |
<commit_before>#include <nanosoft/mysql.h>
#include <mysql/mysql.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
namespace nanosoft
{
MYSQL *mysql_init_struct = MySQL::init();
MYSQL * MySQL::init()
{
MYSQL *m = mysql_init(0);
if ( m ) return m;
fprintf(stderr, "MySQL initialization fault\n");
return 0;
}
/**
* Конструктор
*/
MySQL::MySQL(): conn(0)
{
}
/**
* Деструктор
*/
MySQL::~MySQL()
{
close();
}
/**
* Инициализация потока
*/
void MySQL::threadInit()
{
mysql_thread_init();
}
/**
* Финализация потока
*/
void MySQL::threadEnd()
{
mysql_thread_end();
}
/**
* Соединение сервером
*
* В случае неудачи выводит в stderr сообщение об ошибке и возращает FALSE
*
* @param host хост
* @param database имя БД к которой подключаемся
* @param user пользователь
* @param password пароль
* @param port порт
* @return TRUE - соединение установлено, FALSE ошибка соединения
*/
bool MySQL::connect(const std::string &host, const std::string &database, const std::string &user, const std::string &password, int port)
{
conn = mysql_real_connect(mysql_init_struct, host.c_str(), user.c_str(), password.c_str(), database.c_str(), port, 0, 0);
if ( conn ) return true;
fprintf(stderr, "[MySQL] connection fault\n");
return false;
}
/**
* Соединение сервером
*
* В случае неудачи выводит в stderr сообщение об ошибке и возращает FALSE
*
* @param sock путь к Unix-сокету
* @param database имя БД к которой подключаемся
* @param user пользователь
* @param password пароль
* @return TRUE - соединение установлено, FALSE ошибка соединения
*/
bool MySQL::connectUnix(const std::string &sock, const std::string &database, const std::string &user, const std::string &password)
{
conn = mysql_real_connect(mysql_init_struct, 0, user.c_str(), password.c_str(), database.c_str(), 0, sock.c_str(), 0);
if ( conn ) return true;
fprintf(stderr, "[MySQL] connection fault\n");
return false;
}
/**
* Экранировать строку
*/
std::string MySQL::escape(const std::string &text)
{
char *buf = new char[text.length() * 2 + 1];
size_t len = mysql_real_escape_string(conn, buf, text.c_str(), text.length());
return std::string(buf, len);
}
/**
* Экранировать строку и заключить её в кавычки
*/
std::string MySQL::quote(const std::string &text)
{
return '"' + text + '"';
}
/**
* Выполнить произвольный SQL-запрос
*/
MySQL::result MySQL::query(const char *sql, ...)
{
char *buf;
va_list args;
va_start(args, sql);
int len = vasprintf(&buf, sql, args);
va_end(args);
int status = mysql_real_query(conn, buf, len);
free(buf);
if ( status ) {
fprintf(stderr, "[MySQL] %s\n", mysql_error(conn));
return 0;
}
MYSQL_RES *res = mysql_store_result(conn);
if ( res || mysql_field_count(conn) > 0 ) {
ResultSet *r = new ResultSet;
r->res = res;
r->field_count = mysql_field_count(conn);
r->fields = mysql_fetch_fields(res);
r->values = mysql_fetch_row(res);
if ( r->values ) r->lengths = mysql_fetch_lengths(res);
return r;
}
if ( mysql_errno(conn) ) {
fprintf(stderr, "[MySQL] %s\n", mysql_error(conn));
}
return 0;
}
/**
* Закрыть соединение с сервером
*/
void MySQL::close()
{
if ( conn )
{
mysql_close(conn);
conn = 0;
}
}
void MySQL::result::next()
{
if ( res && res->res ) {
res->values = mysql_fetch_row(res->res);
if ( res->values ) res->lengths = mysql_fetch_lengths(res->res);
}
}
int MySQL::result::indexOf(const char *name)
{
MYSQL_FIELD *p = res->fields;
for(size_t i = 0; i < res->field_count; i++, p++)
{
if ( strcmp(name, p->name) == 0 ) return i;
}
fprintf(stderr, "[MySQL] field not found: %s\n", name);
return 0;
}
std::string MySQL::result::operator [] (size_t num)
{
return std::string(res->values[num], res->lengths[num]);
}
std::string MySQL::result::operator [] (const char *name)
{
int num = indexOf(name);
return std::string(res->values[num], res->lengths[num]);
}
bool MySQL::result::isNull(size_t num)
{
return res->values[num] != 0;
}
bool MySQL::result::isNull(const char *name)
{
int num = indexOf(name);
return res->values[num] != 0;
}
/**
* Удалить набор данных
*/
void MySQL::result::free()
{
mysql_free_result(res->res);
}
}
<commit_msg>fix MySQL::quote<commit_after>#include <nanosoft/mysql.h>
#include <mysql/mysql.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
namespace nanosoft
{
MYSQL *mysql_init_struct = MySQL::init();
MYSQL * MySQL::init()
{
MYSQL *m = mysql_init(0);
if ( m ) return m;
fprintf(stderr, "MySQL initialization fault\n");
return 0;
}
/**
* Конструктор
*/
MySQL::MySQL(): conn(0)
{
}
/**
* Деструктор
*/
MySQL::~MySQL()
{
close();
}
/**
* Инициализация потока
*/
void MySQL::threadInit()
{
mysql_thread_init();
}
/**
* Финализация потока
*/
void MySQL::threadEnd()
{
mysql_thread_end();
}
/**
* Соединение сервером
*
* В случае неудачи выводит в stderr сообщение об ошибке и возращает FALSE
*
* @param host хост
* @param database имя БД к которой подключаемся
* @param user пользователь
* @param password пароль
* @param port порт
* @return TRUE - соединение установлено, FALSE ошибка соединения
*/
bool MySQL::connect(const std::string &host, const std::string &database, const std::string &user, const std::string &password, int port)
{
conn = mysql_real_connect(mysql_init_struct, host.c_str(), user.c_str(), password.c_str(), database.c_str(), port, 0, 0);
if ( conn ) return true;
fprintf(stderr, "[MySQL] connection fault\n");
return false;
}
/**
* Соединение сервером
*
* В случае неудачи выводит в stderr сообщение об ошибке и возращает FALSE
*
* @param sock путь к Unix-сокету
* @param database имя БД к которой подключаемся
* @param user пользователь
* @param password пароль
* @return TRUE - соединение установлено, FALSE ошибка соединения
*/
bool MySQL::connectUnix(const std::string &sock, const std::string &database, const std::string &user, const std::string &password)
{
conn = mysql_real_connect(mysql_init_struct, 0, user.c_str(), password.c_str(), database.c_str(), 0, sock.c_str(), 0);
if ( conn ) return true;
fprintf(stderr, "[MySQL] connection fault\n");
return false;
}
/**
* Экранировать строку
*/
std::string MySQL::escape(const std::string &text)
{
char *buf = new char[text.length() * 2 + 1];
size_t len = mysql_real_escape_string(conn, buf, text.c_str(), text.length());
return std::string(buf, len);
}
/**
* Экранировать строку и заключить её в кавычки
*/
std::string MySQL::quote(const std::string &text)
{
return '"' + escape(text) + '"';
}
/**
* Выполнить произвольный SQL-запрос
*/
MySQL::result MySQL::query(const char *sql, ...)
{
char *buf;
va_list args;
va_start(args, sql);
int len = vasprintf(&buf, sql, args);
va_end(args);
int status = mysql_real_query(conn, buf, len);
free(buf);
if ( status ) {
fprintf(stderr, "[MySQL] %s\n", mysql_error(conn));
return 0;
}
MYSQL_RES *res = mysql_store_result(conn);
if ( res || mysql_field_count(conn) > 0 ) {
ResultSet *r = new ResultSet;
r->res = res;
r->field_count = mysql_field_count(conn);
r->fields = mysql_fetch_fields(res);
r->values = mysql_fetch_row(res);
if ( r->values ) r->lengths = mysql_fetch_lengths(res);
return r;
}
if ( mysql_errno(conn) ) {
fprintf(stderr, "[MySQL] %s\n", mysql_error(conn));
}
return 0;
}
/**
* Закрыть соединение с сервером
*/
void MySQL::close()
{
if ( conn )
{
mysql_close(conn);
conn = 0;
}
}
void MySQL::result::next()
{
if ( res && res->res ) {
res->values = mysql_fetch_row(res->res);
if ( res->values ) res->lengths = mysql_fetch_lengths(res->res);
}
}
int MySQL::result::indexOf(const char *name)
{
MYSQL_FIELD *p = res->fields;
for(size_t i = 0; i < res->field_count; i++, p++)
{
if ( strcmp(name, p->name) == 0 ) return i;
}
fprintf(stderr, "[MySQL] field not found: %s\n", name);
return 0;
}
std::string MySQL::result::operator [] (size_t num)
{
return std::string(res->values[num], res->lengths[num]);
}
std::string MySQL::result::operator [] (const char *name)
{
int num = indexOf(name);
return std::string(res->values[num], res->lengths[num]);
}
bool MySQL::result::isNull(size_t num)
{
return res->values[num] != 0;
}
bool MySQL::result::isNull(const char *name)
{
int num = indexOf(name);
return res->values[num] != 0;
}
/**
* Удалить набор данных
*/
void MySQL::result::free()
{
mysql_free_result(res->res);
}
}
<|endoftext|> |
<commit_before>
#ifdef _DEBUG
//#include <vld.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <string.h>
#include "StrStr.h"
#include "Kmp.h"
#include "BoyerMoore.h"
#include "support/StopWatch.h"
using namespace StringMatch;
#ifndef _DEBUG
const size_t Iterations = 5000000;
#else
const size_t Iterations = 10000;
#endif
//
// See: http://volnitsky.com/project/str_search/index.html
//
static const char * s_SearchTexts[] = {
"Here is a sample example.",
"8'E . It consists of a number of low-lying, largely mangrove covered islands covering an area of around 665 km^2. "
"The population of Bakassi is the subject of some dispute, but is generally put at between 150,000 and 300,000 people."
};
static const char * s_Patterns[] = {
"sample",
"example",
"islands",
"around",
"subject",
"between",
"people",
"between 150,000"
};
void StringMatch_examples()
{
// Usage 1
{
AnsiString::Kmp::Pattern pattern("example");
if (pattern.has_compiled()) {
int pos = pattern.match("Here is a sample example.");
}
}
// Usage 2
{
AnsiString::Kmp::Pattern pattern;
bool compiled = pattern.preprocessing("example");
if (compiled) {
int pos = pattern.match("Here is a sample example.");
}
}
// Usage 3
{
AnsiString::Kmp::Pattern pattern("example");
AnsiString::Kmp::Matcher matcher("Here is a sample example.");
if (pattern.has_compiled()) {
int pos = matcher.find(pattern);
}
}
// Usage 4
{
AnsiString::Kmp::Pattern pattern("example");
AnsiString::Kmp::Matcher matcher;
matcher.set_text("Here is a sample example.");
if (pattern.has_compiled()) {
int pos = matcher.find(pattern);
}
}
// Usage 5
{
AnsiString::Kmp::Pattern pattern("example");
AnsiString::Kmp::Matcher matcher;
if (pattern.has_compiled()) {
int pos = matcher.find("Here is a sample example.", pattern);
}
}
// Usage 6
{
AnsiString::Kmp::Pattern pattern("example");
AnsiString::Kmp::Matcher matcher("Here is a sample example.");
if (pattern.has_compiled()) {
int pos = AnsiString::Kmp::find(matcher, pattern);
}
}
}
template <typename algorithm_type>
void StringMatch_test()
{
typedef typename algorithm_type::Pattern pattern_type;
const char pattern_text_1[] = "sample";
char pattern_text_2[] = "a sample";
printf("---------------------------------------------------------------------------------------\n");
printf(" Test: %s\n", typeid(algorithm_type).name());
printf("---------------------------------------------------------------------------------------\n\n");
test::StopWatch sw;
int sum, index_of;
// pattern: "example"
pattern_type pattern;
pattern.preprocessing("example");
sum = 0;
sw.start();
for (size_t i = 0; i < Iterations; ++i) {
index_of = pattern.match("Here is a sample example.");
sum += index_of;
}
sw.stop();
pattern.print_result("Here is a sample example.", index_of, sum, sw.getElapsedMillisec());
// pattern1: "sample"
pattern_type pattern1(pattern_text_1);
sum = 0;
sw.start();
for (size_t i = 0; i < Iterations; ++i) {
index_of = pattern1.match("Here is a sample example.");
sum += index_of;
}
sw.stop();
pattern1.print_result("Here is a sample example.", index_of, sum, sw.getElapsedMillisec());
// pattern2: "a sample"
pattern_type pattern2(pattern_text_2);
sum = 0;
sw.start();
for (size_t i = 0; i < Iterations; ++i) {
index_of = pattern2.match("Here is a sample example.");
sum += index_of;
}
sw.stop();
pattern2.print_result("Here is a sample example.", index_of, sum, sw.getElapsedMillisec());
}
void StringMatch_strstr_benchmark()
{
test::StopWatch sw;
int sum;
static const size_t iters = Iterations / (sm_countof(s_SearchTexts) * sm_countof(s_Patterns));
printf("-----------------------------------------------------------\n");
printf(" Benchmark: %s\n", "strstr()");
printf("-----------------------------------------------------------\n\n");
static const int kSearchTexts = sm_countof_i(s_SearchTexts);
static const int kPatterns = sm_countof_i(s_Patterns);
StringRef texts[kSearchTexts];
for (int i = 0; i < kSearchTexts; ++i) {
texts[i].set_data(s_SearchTexts[i], strlen(s_SearchTexts[i]));
}
StringRef patterns[kPatterns];
for (int i = 0; i < kPatterns; ++i) {
patterns[i].set_data(s_Patterns[i], strlen(s_Patterns[i]));
}
sum = 0;
sw.start();
for (size_t loop = 0; loop < iters; ++loop) {
for (int i = 0; i < kSearchTexts; ++i) {
for (int j = 0; j < kPatterns; ++j) {
const char * substr = strstr(texts[i].c_str(), patterns[j].c_str());
if (substr != nullptr) {
int index_of = (int)(substr - texts[i].c_str());
sum += index_of;
}
else {
sum += (int)Status::NotFound;
}
}
}
}
sw.stop();
printf("sum: %-11d, time spent: %0.3f ms\n\n", sum, sw.getElapsedMillisec());
}
template <typename algorithm_type>
void StringMatch_benchmark()
{
typedef typename algorithm_type::Pattern pattern_type;
test::StopWatch sw;
int sum;
static const size_t iters = Iterations / (sm_countof(s_SearchTexts) * sm_countof(s_Patterns));
printf("---------------------------------------------------------------------------------------\n");
printf(" Benchmark: %s\n", typeid(algorithm_type).name());
printf("---------------------------------------------------------------------------------------\n\n");
static const int kSearchTexts = sm_countof_i(s_SearchTexts);
static const int kPatterns = sm_countof_i(s_Patterns);
StringRef texts[kSearchTexts];
for (int i = 0; i < kSearchTexts; ++i) {
texts[i].set_data(s_SearchTexts[i], strlen(s_SearchTexts[i]));
}
pattern_type pattern[kPatterns];
for (int i = 0; i < kPatterns; ++i) {
pattern[i].preprocessing(s_Patterns[i]);
}
sum = 0;
sw.start();
for (size_t loop = 0; loop < iters; ++loop) {
for (int i = 0; i < kSearchTexts; ++i) {
for (int j = 0; j < kPatterns; ++j) {
int index_of = pattern[j].match(texts[i].c_str());
sum += index_of;
}
}
}
sw.stop();
printf("sum: %-11d, time spent: %0.3f ms\n\n", sum, sw.getElapsedMillisec());
}
int main(int argc, char * argv[])
{
StringMatch_examples();
StringMatch_test<AnsiString::Kmp>();
StringMatch_test<AnsiString::BoyerMoore>();
StringMatch_strstr_benchmark();
StringMatch_benchmark<AnsiString::StrStr>();
StringMatch_benchmark<AnsiString::Kmp>();
StringMatch_benchmark<AnsiString::BoyerMoore>();
#if defined(_WIN32) || defined(WIN32) || defined(OS_WINDOWS) || defined(__WINDOWS__)
::system("pause");
#endif
return 0;
}
<commit_msg>小改动;<commit_after>
#ifdef _DEBUG
//#include <vld.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <string.h>
#include "StrStr.h"
#include "Kmp.h"
#include "BoyerMoore.h"
#include "support/StopWatch.h"
using namespace StringMatch;
#ifndef _DEBUG
static const size_t kIterations = 5000000;
#else
static const size_t kIterations = 10000;
#endif
//
// See: http://volnitsky.com/project/str_search/index.html
//
static const char * s_SearchTexts[] = {
"Here is a sample example.",
"8'E . It consists of a number of low-lying, largely mangrove covered islands covering an area of around 665 km^2. "
"The population of Bakassi is the subject of some dispute, but is generally put at between 150,000 and 300,000 people."
};
static const char * s_Patterns[] = {
"sample",
"example",
"islands",
"around",
"subject",
"between",
"people",
"between 150,000"
};
void StringMatch_examples()
{
// Usage 1
{
AnsiString::Kmp::Pattern pattern("example");
if (pattern.has_compiled()) {
int pos = pattern.match("Here is a sample example.");
}
}
// Usage 2
{
AnsiString::Kmp::Pattern pattern;
bool compiled = pattern.preprocessing("example");
if (compiled) {
int pos = pattern.match("Here is a sample example.");
}
}
// Usage 3
{
AnsiString::Kmp::Pattern pattern("example");
AnsiString::Kmp::Matcher matcher("Here is a sample example.");
if (pattern.has_compiled()) {
int pos = matcher.find(pattern);
}
}
// Usage 4
{
AnsiString::Kmp::Pattern pattern("example");
AnsiString::Kmp::Matcher matcher;
matcher.set_text("Here is a sample example.");
if (pattern.has_compiled()) {
int pos = matcher.find(pattern);
}
}
// Usage 5
{
AnsiString::Kmp::Pattern pattern("example");
AnsiString::Kmp::Matcher matcher;
if (pattern.has_compiled()) {
int pos = matcher.find("Here is a sample example.", pattern);
}
}
// Usage 6
{
AnsiString::Kmp::Pattern pattern("example");
AnsiString::Kmp::Matcher matcher("Here is a sample example.");
if (pattern.has_compiled()) {
int pos = AnsiString::Kmp::find(matcher, pattern);
}
}
}
template <typename algorithm_type>
void StringMatch_test()
{
typedef typename algorithm_type::Pattern pattern_type;
const char pattern_text_1[] = "sample";
const char pattern_text_2[] = "a sample";
printf("---------------------------------------------------------------------------------------\n");
printf(" Test: %s\n", typeid(algorithm_type).name());
printf("---------------------------------------------------------------------------------------\n\n");
test::StopWatch sw;
int sum, index_of;
// pattern: "example"
pattern_type pattern;
pattern.preprocessing("example");
sum = 0;
sw.start();
for (size_t i = 0; i < kIterations; ++i) {
index_of = pattern.match("Here is a sample example.");
sum += index_of;
}
sw.stop();
pattern.print_result("Here is a sample example.", index_of, sum, sw.getElapsedMillisec());
// pattern1: "sample"
pattern_type pattern1(pattern_text_1);
sum = 0;
sw.start();
for (size_t i = 0; i < kIterations; ++i) {
index_of = pattern1.match("Here is a sample example.");
sum += index_of;
}
sw.stop();
pattern1.print_result("Here is a sample example.", index_of, sum, sw.getElapsedMillisec());
// pattern2: "a sample"
pattern_type pattern2(pattern_text_2);
sum = 0;
sw.start();
for (size_t i = 0; i < kIterations; ++i) {
index_of = pattern2.match("Here is a sample example.");
sum += index_of;
}
sw.stop();
pattern2.print_result("Here is a sample example.", index_of, sum, sw.getElapsedMillisec());
}
void StringMatch_strstr_benchmark()
{
test::StopWatch sw;
int sum;
static const size_t iters = kIterations / (sm_countof(s_SearchTexts) * sm_countof(s_Patterns));
printf("-----------------------------------------------------------\n");
printf(" Benchmark: %s\n", "strstr()");
printf("-----------------------------------------------------------\n\n");
static const int kSearchTexts = sm_countof_i(s_SearchTexts);
static const int kPatterns = sm_countof_i(s_Patterns);
StringRef texts[kSearchTexts];
for (int i = 0; i < kSearchTexts; ++i) {
texts[i].set_data(s_SearchTexts[i], strlen(s_SearchTexts[i]));
}
StringRef patterns[kPatterns];
for (int i = 0; i < kPatterns; ++i) {
patterns[i].set_data(s_Patterns[i], strlen(s_Patterns[i]));
}
sum = 0;
sw.start();
for (size_t loop = 0; loop < iters; ++loop) {
for (int i = 0; i < kSearchTexts; ++i) {
for (int j = 0; j < kPatterns; ++j) {
const char * substr = strstr(texts[i].c_str(), patterns[j].c_str());
if (substr != nullptr) {
int index_of = (int)(substr - texts[i].c_str());
sum += index_of;
}
else {
sum += (int)Status::NotFound;
}
}
}
}
sw.stop();
printf("sum: %-11d, time spent: %0.3f ms\n\n", sum, sw.getElapsedMillisec());
}
template <typename algorithm_type>
void StringMatch_benchmark()
{
typedef typename algorithm_type::Pattern pattern_type;
test::StopWatch sw;
int sum;
static const size_t iters = kIterations / (sm_countof(s_SearchTexts) * sm_countof(s_Patterns));
printf("---------------------------------------------------------------------------------------\n");
printf(" Benchmark: %s\n", typeid(algorithm_type).name());
printf("---------------------------------------------------------------------------------------\n\n");
static const int kSearchTexts = sm_countof_i(s_SearchTexts);
static const int kPatterns = sm_countof_i(s_Patterns);
StringRef texts[kSearchTexts];
for (int i = 0; i < kSearchTexts; ++i) {
texts[i].set_data(s_SearchTexts[i], strlen(s_SearchTexts[i]));
}
pattern_type pattern[kPatterns];
for (int i = 0; i < kPatterns; ++i) {
pattern[i].preprocessing(s_Patterns[i]);
}
sum = 0;
sw.start();
for (size_t loop = 0; loop < iters; ++loop) {
for (int i = 0; i < kSearchTexts; ++i) {
for (int j = 0; j < kPatterns; ++j) {
int index_of = pattern[j].match(texts[i].c_str());
sum += index_of;
}
}
}
sw.stop();
printf("sum: %-11d, time spent: %0.3f ms\n\n", sum, sw.getElapsedMillisec());
}
int main(int argc, char * argv[])
{
StringMatch_examples();
StringMatch_test<AnsiString::Kmp>();
StringMatch_test<AnsiString::BoyerMoore>();
StringMatch_strstr_benchmark();
StringMatch_benchmark<AnsiString::StrStr>();
StringMatch_benchmark<AnsiString::Kmp>();
StringMatch_benchmark<AnsiString::BoyerMoore>();
#if defined(_WIN32) || defined(WIN32) || defined(OS_WINDOWS) || defined(__WINDOWS__)
::system("pause");
#endif
return 0;
}
<|endoftext|> |
<commit_before>#include "flatgltf/2.0/glTF_generated.h"
#include "flatgltf/2.0/glTFapi.hpp"
#include "flatgltf/common/glTFutils.hpp"
#include "glTFinternal.hpp"
#define KHUTILS_ASSERTION_INLINE
#include "khutils/assertion.hpp"
#include "khutils/runtime_exceptions.hpp"
namespace glTF_2_0
{
using namespace glTF_common;
//-------------------------------------------------------------------------
BufferT* const createBuffer(Document* const doc, const char* name)
{
auto instance = Buffer_t{new BufferT};
if (name)
{
instance->name = name;
}
doc->root->buffers.push_back(std::move(instance));
return doc->root->buffers.back().get();
}
//---
//! create buffer
// if name is null, data will be internal
BufferT* const createBuffer(Document* const doc, const char* uri, const char* name)
{
auto buffer = createBuffer(doc, name);
if (uri)
{
createBindata(doc, uri);
}
else
{
}
return buffer;
}
//---
std::vector<uint8_t>& createBindata(Document* const doc, const char* name)
{
return getBindata(doc, name);
}
//---
size_t addBufferData(const uint8_t* const data, size_t length, Document* const doc, BufferT* const buf)
{
KHUTILS_ASSERT_PTR(data);
KHUTILS_ASSERT_PTR(doc);
KHUTILS_ASSERT_PTR(buf);
if (isDataUri(buf->uri))
{
auto bufData = convertUriToData(buf->uri);
std::copy_n(data, length, std::back_inserter(bufData));
buf->uri = convertDataToUri(bufData);
buf->byteLength = bufData.size();
}
else
{
auto& bufData = getBindata(doc, buf->uri.c_str());
std::copy_n(data, length, std::back_inserter(bufData));
buf->byteLength = bufData.size();
}
return buf->byteLength;
}
///-----------------------------------------------------------------------
/// bindata
///-----------------------------------------------------------------------
std::vector<uint8_t>& getBindata(Document* const doc, const char* name)
{
return doc->bindata[name];
}
size_t setBindata(const std::vector<uint8_t>& data, Document* const doc, const char* name)
{
doc->bindata[name].clear();
doc->bindata[name].reserve(data.size());
std::copy(data.begin(), data.end(), std::back_inserter(doc->bindata[name]));
return doc->bindata[name].size();
}
size_t addBindata(const std::vector<uint8_t>& data, Document* const doc, const char* name)
{
doc->bindata[name].reserve(doc->bindata[name].size() + data.size());
std::copy(data.begin(), data.end(), std::back_inserter(doc->bindata[name]));
return doc->bindata[name].size();
}
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
} // namespace glTF_2_0
<commit_msg>fixed buffer creation<commit_after>#include "flatgltf/2.0/glTF_generated.h"
#include "flatgltf/2.0/glTFapi.hpp"
#include "flatgltf/common/glTFutils.hpp"
#include "glTFinternal.hpp"
#define KHUTILS_ASSERTION_INLINE
#include "khutils/assertion.hpp"
#include "khutils/runtime_exceptions.hpp"
namespace glTF_2_0
{
using namespace glTF_common;
//-------------------------------------------------------------------------
BufferT* const createBuffer(Document* const doc, const char* name)
{
KHUTILS_ASSERT_PTR(doc);
auto instance = Buffer_t{new BufferT};
if (name)
{
instance->name = name;
}
doc->root->buffers.push_back(std::move(instance));
return doc->root->buffers.back().get();
}
//---
//! create buffer
// if name is null, data will be internal
BufferT* const createBuffer(Document* const doc, const char* uri, const char* name)
{
KHUTILS_ASSERT_PTR(doc);
KHUTILS_ASSERT_PTR(uri);
auto buffer = createBuffer(doc, name);
buffer->uri = uri;
if (!isDataUri(uri))
{
createBindata(doc, uri);
}
return buffer;
}
//---
std::vector<uint8_t>& createBindata(Document* const doc, const char* name)
{
KHUTILS_ASSERT_PTR(doc);
return getBindata(doc, name);
}
//---
size_t addBufferData(const uint8_t* const data, size_t length, Document* const doc, BufferT* const buf)
{
KHUTILS_ASSERT_PTR(data);
KHUTILS_ASSERT_PTR(doc);
KHUTILS_ASSERT_PTR(buf);
if (isDataUri(buf->uri))
{
auto bufData = convertUriToData(buf->uri);
std::copy_n(data, length, std::back_inserter(bufData));
buf->uri = convertDataToUri(bufData);
buf->byteLength = bufData.size();
}
else
{
auto& bufData = getBindata(doc, buf->uri.c_str());
std::copy_n(data, length, std::back_inserter(bufData));
buf->byteLength = bufData.size();
}
return buf->byteLength;
}
///-----------------------------------------------------------------------
/// bindata
///-----------------------------------------------------------------------
std::vector<uint8_t>& getBindata(Document* const doc, const char* name)
{
return doc->bindata[name];
}
size_t setBindata(const std::vector<uint8_t>& data, Document* const doc, const char* name)
{
doc->bindata[name].clear();
doc->bindata[name].reserve(data.size());
std::copy(data.begin(), data.end(), std::back_inserter(doc->bindata[name]));
return doc->bindata[name].size();
}
size_t addBindata(const std::vector<uint8_t>& data, Document* const doc, const char* name)
{
doc->bindata[name].reserve(doc->bindata[name].size() + data.size());
std::copy(data.begin(), data.end(), std::back_inserter(doc->bindata[name]));
return doc->bindata[name].size();
}
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
} // namespace glTF_2_0
<|endoftext|> |
<commit_before>#include "Action/AAction.hh"
AAction::AAction()
: _data(*Action::data), _state(Action::NOT_STARTED)
{
addListener("onInit", &AAction::_init);
addListener("onUpdate", &AAction::_update);
}
Action::State AAction::update()
{
if (_state == Action::NOT_STARTED)
{
while (_actions.size())
{
delete _actions.front();
_actions.pop();
}
emit("onInit");
if (_state == Action::NOT_STARTED)
_state = Action::RUNNING;
}
if (_state == Action::RUNNING && !_actions.size())
emit("onUpdate");
if (_state == Action::RUNNING && _actions.size())
{
_actions.front()->update();
if (_actions.front()->getState() > Action::RUNNING)
{
delete _actions.front();
_actions.pop();
if (!_actions.size())
emit("onEmptyQueue");
}
}
return (_state);
}
void AAction::emit(const std::string &signal)
{
std::map<std::string, std::vector<std::function<void(AAction *)> > >::iterator it;
if ((it = _listeners.find(signal)) == _listeners.end())
return;
for (uint16_t i = 0; i < it->second.size(); i++)
(it->second[i])(this);
}
void AAction::addListener(const std::string &signal, void (*listener)(AAction *))
{
_listeners[signal].push_back(listener);
}
void AAction::addListener(const std::string &signal, void (AAction::*listener)())
{
std::function<void (AAction *)> l = [listener](AAction *that){(that->*listener)();};
_listeners[signal].push_back(l);
}
<commit_msg>add: onFrame event<commit_after>#include "Action/AAction.hh"
AAction::AAction()
: _data(*Action::data), _state(Action::NOT_STARTED)
{
addListener("onInit", &AAction::_init);
addListener("onUpdate", &AAction::_update);
}
Action::State AAction::update()
{
if (_state == Action::NOT_STARTED)
{
while (_actions.size())
{
delete _actions.front();
_actions.pop();
}
emit("onInit");
if (_state == Action::NOT_STARTED)
_state = Action::RUNNING;
}
emit("onFrame");
if (_state == Action::RUNNING && !_actions.size())
emit("onUpdate");
if (_state == Action::RUNNING && _actions.size())
{
_actions.front()->update();
if (_actions.front()->getState() > Action::RUNNING)
{
delete _actions.front();
_actions.pop();
if (!_actions.size())
emit("onEmptyQueue");
}
}
return (_state);
}
void AAction::emit(const std::string &signal)
{
std::map<std::string, std::vector<std::function<void(AAction *)> > >::iterator it;
if ((it = _listeners.find(signal)) == _listeners.end())
return;
for (uint16_t i = 0; i < it->second.size(); i++)
(it->second[i])(this);
}
void AAction::addListener(const std::string &signal, void (*listener)(AAction *))
{
_listeners[signal].push_back(listener);
}
void AAction::addListener(const std::string &signal, void (AAction::*listener)())
{
std::function<void (AAction *)> l = [listener](AAction *that){(that->*listener)();};
_listeners[signal].push_back(l);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAOCPP_PEGTL_INCLUDE_INTERNAL_FILE_OPENER_HPP
#define TAOCPP_PEGTL_INCLUDE_INTERNAL_FILE_OPENER_HPP
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <utility>
#include "../config.hpp"
#include "../input_error.hpp"
namespace tao
{
namespace TAOCPP_PEGTL_NAMESPACE
{
namespace internal
{
struct file_opener
{
explicit file_opener( const char* filename )
: m_source( filename ),
m_fd( open() )
{
}
file_opener( const file_opener& ) = delete;
file_opener( file_opener&& ) = delete;
~file_opener() noexcept
{
::close( m_fd );
}
void operator=( const file_opener& ) = delete;
void operator=( file_opener&& ) = delete;
std::size_t size() const
{
struct stat st; // NOLINT
errno = 0;
if(::fstat( m_fd, &st ) < 0 ) {
TAOCPP_PEGTL_THROW_INPUT_ERROR( "unable to fstat() file " << m_source << " descriptor " << m_fd );
}
return std::size_t( st.st_size );
}
const char* const m_source;
const int m_fd;
private:
int open() const
{
errno = 0;
const int fd = ::open( m_source, O_RDONLY /*| O_CLOEXEC*/ ); // NOLINT
if( fd >= 0 ) {
return fd;
}
TAOCPP_PEGTL_THROW_INPUT_ERROR( "unable to open() file " << m_source << " for reading" );
}
};
} // namespace internal
} // namespace TAOCPP_PEGTL_NAMESPACE
} // namespace tao
#endif
<commit_msg>sync third_party/tao/pegtl/internal/file_opener.hpp<commit_after>// Copyright (c) 2014-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAOCPP_PEGTL_INCLUDE_INTERNAL_FILE_OPENER_HPP
#define TAOCPP_PEGTL_INCLUDE_INTERNAL_FILE_OPENER_HPP
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <utility>
#include "../config.hpp"
#include "../input_error.hpp"
namespace tao
{
namespace TAOCPP_PEGTL_NAMESPACE
{
namespace internal
{
struct file_opener
{
explicit file_opener( const char* filename )
: m_source( filename ),
m_fd( open() )
{
}
file_opener( const file_opener& ) = delete;
file_opener( file_opener&& ) = delete;
~file_opener() noexcept
{
::close( m_fd );
}
void operator=( const file_opener& ) = delete;
void operator=( file_opener&& ) = delete;
std::size_t size() const
{
struct stat st; // NOLINT
errno = 0;
if(::fstat( m_fd, &st ) < 0 ) {
TAOCPP_PEGTL_THROW_INPUT_ERROR( "unable to fstat() file " << m_source << " descriptor " << m_fd );
}
return std::size_t( st.st_size );
}
const char* const m_source;
const int m_fd;
private:
int open() const
{
errno = 0;
const int fd = ::open( m_source,
O_RDONLY
#ifdef O_CLOEXEC
| O_CLOEXEC
#endif
);
if( fd >= 0 ) {
return fd;
}
TAOCPP_PEGTL_THROW_INPUT_ERROR( "unable to open() file " << m_source << " for reading" );
}
};
} // namespace internal
} // namespace TAOCPP_PEGTL_NAMESPACE
} // namespace tao
#endif
<|endoftext|> |
<commit_before>#include "smssendprovider.h"
#include "smsglobal.h"
#include "smscontact.h"
#include <kdeversion.h>
#if KDE_VERSION > 305
#include <kprocio.h>
#else
#include <kprocess.h>
#endif
#include <qregexp.h>
#include <qlabel.h>
#include <qfile.h>
#include <klineedit.h>
#include <kmessagebox.h>
#include <klocale.h>
SMSSendProvider::SMSSendProvider(QString providerName, QString prefixValue, SMSContact* contact, QObject* parent, const char *name)
: QObject( parent, name )
{
provider = providerName;
prefix = prefixValue;
m_contact = contact;
messagePos = -1;
telPos = -1;
QString file = prefix + "/share/smssend/" + provider + ".sms";
QFile f(file);
if (f.open(IO_ReadOnly))
{
QTextStream t(&f);
QString group = QString("SMSSend-%1").arg(provider);
while( !t.eof())
{
QString s = t.readLine();
if( s[0] == '%')
{
QStringList args = QStringList::split(':',s);
QStringList options = QStringList::split(' ', args[0]);
names.append(options[0].replace(0,1,""));
descriptions.append(args[1]);
values.append(SMSGlobal::readConfig(group, names[names.count()-1], m_contact));
if( args[0].contains("Message") || args[0].contains("message")
|| args[0].contains("message") || args[0].contains("nachricht")
|| args[0].contains("Msg") || args[0].contains("Mensagem") )
{
for( int i = 0; i < options.count(); i++)
{
if (options[i].contains("Size="))
{
QString option = options[i];
option.replace(0,5,"");
m_maxSize = option.toInt();
}
}
messagePos = names.count()-1;
}
else if ( args[0].contains("Tel") || args[0].contains("Number")
|| args[0].contains("number") || args[0].contains("TelNum")
|| args[0].contains("Recipient") || args[0].contains("Tel1")
|| args[0].contains("To") || args[0].contains("nummer")
|| args[0].contains("telefone") || args[0].contains("ToPhone") )
{
telPos = names.count() - 1;
}
}
}
}
f.close();
if ( messagePos == -1 )
{
canSend = false;
KMessageBox::error(0L, i18n("Could not determine which argument which should contain the message"),
i18n("Could not send message"));
return;
}
if ( telPos == -1 )
{
canSend = false;
KMessageBox::error(0L, i18n("Could not determine which argument which should contain the number"),
i18n("Could not send message"));
return;
}
canSend = true;
}
SMSSendProvider::~SMSSendProvider()
{
}
QString SMSSendProvider::name(int i)
{
if ( telPos == i || messagePos == i)
return QString::null;
else
return names[i];
}
QString SMSSendProvider::value(int i)
{
return values[i];
}
QString SMSSendProvider::description(int i)
{
return descriptions[i];
}
void SMSSendProvider::save(QPtrList<SMSSendArg> args)
{
QString group = QString("SMSSend-%1").arg(provider);
for (unsigned i=0; i < args.count(); i++)
{
if (args.at(i)->value->text() == "")
SMSGlobal::deleteConfig(group, args.at(i)->argName->text(), m_contact);
else
SMSGlobal::writeConfig(group, args.at(i)->argName->text(), m_contact, args.at(i)->value->text());
}
}
int SMSSendProvider::count()
{
return names.count();
}
void SMSSendProvider::send(const KopeteMessage& msg)
{
m_msg = msg;
QString message = msg.plainBody();
QString nr = msg.to().first()->id();
if (canSend = false)
return;
values[messagePos] = message;
values[telPos] = nr;
#if KDE_VERSION > 305
KProcIO* p = new KProcIO;
#else
KProcess* p = new KProcess;
#endif
*p << QString("%1/bin/smssend").arg(prefix) << provider;
for( unsigned int i = 0; i < values.count(); ++i)
*p << values[i];
output.clear();
connect( p, SIGNAL(processExited(KProcess *)), this, SLOT(slotSendFinished(KProcess*)));
connect( p, SIGNAL(receivedStdout(KProcess*, char*, int)),
this, SLOT(slotReceivedOutput(KProcess*, char*, int)));
connect( p, SIGNAL(receivedStderr(KProcess*, char*, int)),
this, SLOT(slotReceivedOutput(KProcess*, char*, int)));
p->start(KProcess::Block);
}
void SMSSendProvider::slotSendFinished(KProcess* p)
{
if (p->exitStatus() == 0)
{
KMessageBox::information(0L, i18n("Message sent"), output.join("\n"), i18n("Message sent"));
emit messageSent(m_msg);
}
else
{
KMessageBox::detailedError(0L, i18n("Something went wrong when sending message"), output.join("\n"),
i18n("Could not send message"));
}
}
void SMSSendProvider::slotReceivedOutput(KProcess*, char *buffer, int buflen)
{
QStringList lines = QStringList::split("\n", QString::fromLocal8Bit(buffer, buflen));
for (QStringList::Iterator it = lines.begin(); it != lines.end(); ++it)
output.append(*it);
}
int SMSSendProvider::maxSize()
{
return m_maxSize;
}
#include "smssendprovider.moc"
/*
* Local variables:
* c-indentation-style: k&r
* c-basic-offset: 8
* indent-tabs-mode: t
* End:
*/
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>CVS_SILENT: no comment<commit_after>#include "smssendprovider.h"
#include "smsglobal.h"
#include "smscontact.h"
#include <kdeversion.h>
#if KDE_VERSION > 305
#include <kprocio.h>
#else
#include <kprocess.h>
#endif
#include <qregexp.h>
#include <qlabel.h>
#include <qfile.h>
#include <klineedit.h>
#include <kmessagebox.h>
#include <klocale.h>
SMSSendProvider::SMSSendProvider(QString providerName, QString prefixValue, SMSContact* contact, QObject* parent, const char *name)
: QObject( parent, name )
{
provider = providerName;
prefix = prefixValue;
m_contact = contact;
messagePos = -1;
telPos = -1;
QString file = prefix + "/share/smssend/" + provider + ".sms";
QFile f(file);
if (f.open(IO_ReadOnly))
{
QTextStream t(&f);
QString group = QString("SMSSend-%1").arg(provider);
while( !t.eof())
{
QString s = t.readLine();
if( s[0] == '%')
{
QStringList args = QStringList::split(':',s);
QStringList options = QStringList::split(' ', args[0]);
names.append(options[0].replace(0,1,""));
descriptions.append(args[1]);
values.append(SMSGlobal::readConfig(group, names[names.count()-1], m_contact));
if( args[0].contains("Message") || args[0].contains("message")
|| args[0].contains("message") || args[0].contains("nachricht")
|| args[0].contains("Msg") || args[0].contains("Mensagem") )
{
for( int i = 0; i < options.count(); i++)
{
if (options[i].contains("Size="))
{
QString option = options[i];
option.replace(0,5,"");
m_maxSize = option.toInt();
}
}
messagePos = names.count()-1;
}
else if ( args[0].contains("Tel") || args[0].contains("Number")
|| args[0].contains("number") || args[0].contains("TelNum")
|| args[0].contains("Recipient") || args[0].contains("Tel1")
|| args[0].contains("To") || args[0].contains("nummer")
|| args[0].contains("telefone") || args[0].contains("ToPhone") )
{
telPos = names.count() - 1;
}
}
}
}
f.close();
if ( messagePos == -1 )
{
canSend = false;
KMessageBox::error(0L, i18n("Could not determine which argument which should contain the message"),
i18n("Could not send message"));
return;
}
if ( telPos == -1 )
{
canSend = false;
KMessageBox::error(0L, i18n("Could not determine which argument which should contain the number"),
i18n("Could not send message"));
return;
}
canSend = true;
}
SMSSendProvider::~SMSSendProvider()
{
}
QString SMSSendProvider::name(int i)
{
if ( telPos == i || messagePos == i)
return QString::null;
else
return names[i];
}
QString SMSSendProvider::value(int i)
{
return values[i];
}
QString SMSSendProvider::description(int i)
{
return descriptions[i];
}
void SMSSendProvider::save(QPtrList<SMSSendArg> args)
{
QString group = QString("SMSSend-%1").arg(provider);
for (unsigned i=0; i < args.count(); i++)
{
if (args.at(i)->value->text() == "")
SMSGlobal::deleteConfig(group, args.at(i)->argName->text(), m_contact);
else
SMSGlobal::writeConfig(group, args.at(i)->argName->text(), m_contact, args.at(i)->value->text());
}
}
int SMSSendProvider::count()
{
return names.count();
}
void SMSSendProvider::send(const KopeteMessage& msg)
{
m_msg = msg;
QString message = msg.plainBody();
QString nr = msg.to().first()->id();
if (canSend = false)
return;
values[messagePos] = message;
values[telPos] = nr;
#if KDE_VERSION > 305
KProcIO* p = new KProcIO;
#else
KProcess* p = new KProcess;
#endif
*p << QString("%1/bin/smssend").arg(prefix) << provider << values;
output.clear();
connect( p, SIGNAL(processExited(KProcess *)), this, SLOT(slotSendFinished(KProcess*)));
connect( p, SIGNAL(receivedStdout(KProcess*, char*, int)),
this, SLOT(slotReceivedOutput(KProcess*, char*, int)));
connect( p, SIGNAL(receivedStderr(KProcess*, char*, int)),
this, SLOT(slotReceivedOutput(KProcess*, char*, int)));
p->start(KProcess::Block);
}
void SMSSendProvider::slotSendFinished(KProcess* p)
{
if (p->exitStatus() == 0)
{
KMessageBox::information(0L, i18n("Message sent"), output.join("\n"), i18n("Message sent"));
emit messageSent(m_msg);
}
else
{
KMessageBox::detailedError(0L, i18n("Something went wrong when sending message"), output.join("\n"),
i18n("Could not send message"));
}
}
void SMSSendProvider::slotReceivedOutput(KProcess*, char *buffer, int buflen)
{
QStringList lines = QStringList::split("\n", QString::fromLocal8Bit(buffer, buflen));
for (QStringList::Iterator it = lines.begin(); it != lines.end(); ++it)
output.append(*it);
}
int SMSSendProvider::maxSize()
{
return m_maxSize;
}
#include "smssendprovider.moc"
/*
* Local variables:
* c-indentation-style: k&r
* c-basic-offset: 8
* indent-tabs-mode: t
* End:
*/
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>/**********************************************************************************
* Project: ROOT - a Root-integrated toolkit for multivariate data analysis *
* Package: TMVA *
* Web : http://tmva.sourceforge.net *
* *
* Description: *
* *
* Authors: *
* Stefan Wunsch (stefan.wunsch@cern.ch) *
* Luca Zampieri (luca.zampieri@alumni.epfl.ch) *
* *
* Copyright (c) 2019: *
* CERN, Switzerland *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted according to the terms listed in LICENSE *
* (http://tmva.sourceforge.net/LICENSE) *
**********************************************************************************/
#ifndef TMVA_TREEINFERENCE_FOREST
#define TMVA_TREEINFERENCE_FOREST
#include <functional>
#include <string>
#include <vector>
#include <stdexcept>
#include <cmath>
#include <algorithm>
#include "TFile.h"
#include "TDirectory.h"
#include "TInterpreter.h"
#include "TUUID.h"
#include "TGenericClassInfo.h" // ROOT::Internal::GetDemangledTypeName
#include "BranchlessTree.hxx"
#include "Objectives.hxx"
namespace TMVA {
namespace Experimental {
namespace Internal {
template <typename T>
T *GetObjectSafe(TFile *f, const std::string &n, const std::string &m)
{
auto v = reinterpret_cast<T *>(f->Get(m.c_str()));
if (v == nullptr)
throw std::runtime_error("Failed to read " + m + " from file " + n + ".");
return v;
}
template <typename T>
bool CompareTree(const BranchlessTree<T> &a, const BranchlessTree<T> &b)
{
if (a.fInputs[0] == b.fInputs[0])
return a.fThresholds[0] < b.fThresholds[0];
else
return a.fInputs[0] < b.fInputs[0];
}
} // namespace Internal
/// Forest base class
///
/// \tparam T Value type for the computation (usually floating point type)
/// \tparam ForestType Type of the collection of trees
template <typename T, typename ForestType>
struct ForestBase {
using Value_t = T;
std::function<T(T)> fObjectiveFunc; ///< Objective function
ForestType fTrees; ///< Store the forest, either as vector or jitted function
int fNumInputs; ///< Number of input variables
void Inference(const T *inputs, const int rows, bool layout, T *predictions);
};
/// Perform inference of the forest on a batch of inputs
///
/// \param[in] inputs Pointer to data containing the inputs
/// \param[in] rows Number of events in inputs vector
/// \param[in] layout Row major (true) or column major (false) memory layout
/// \param[in] predictions Pointer to the buffer to be filled with the predictions
template <typename T, typename ForestType>
inline void ForestBase<T, ForestType>::Inference(const T *inputs, const int rows, bool layout, T *predictions)
{
const auto strideTree = layout ? 1 : rows;
const auto strideBatch = layout ? fNumInputs : 1;
for (int i = 0; i < rows; i++) {
predictions[i] = 0.0;
for (auto &tree : fTrees) {
predictions[i] += tree.Inference(inputs + i * strideBatch, strideTree);
}
predictions[i] = fObjectiveFunc(predictions[i]);
}
}
/// Forest using branchless trees
///
/// \tparam T Value type for the computation (usually floating point type)
template <typename T>
struct BranchlessForest : public ForestBase<T, std::vector<BranchlessTree<T>>> {
void Load(const std::string &key, const std::string &filename, const int output = 0, const bool sortTrees = true);
};
/// Load parameters from a ROOT file to the branchless trees
///
/// \param[in] key Name of folder in the ROOT file containing the model parameters
/// \param[in] filename Filename of the ROOT file
/// \param[in] output Load trees corresponding to the given output node of the forest
/// \param[in] sortTrees Flag to indicate sorting the input trees by the cut value of the first node of each tree
template <typename T>
inline void
BranchlessForest<T>::Load(const std::string &key, const std::string &filename, const int output, const bool sortTrees)
{
// Open input file and get folder from key
auto file = TFile::Open(filename.c_str(), "READ");
// Load parameters from file
auto maxDepth = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/max_depth");
auto numTrees = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/num_trees");
auto numInputs = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/num_inputs");
auto numOutputs = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/num_outputs");
auto objective = Internal::GetObjectSafe<std::string>(file, filename, key + "/objective");
auto inputs = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/inputs");
auto outputs = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/outputs");
auto thresholds = Internal::GetObjectSafe<std::vector<T>>(file, filename, key + "/thresholds");
this->fNumInputs = numInputs->at(0);
this->fObjectiveFunc = Objectives::GetFunction<T>(*objective);
const auto lenInputs = std::pow(2, maxDepth->at(0)) - 1;
const auto lenThresholds = std::pow(2, maxDepth->at(0) + 1) - 1;
// Find number of trees corresponding to given output node
if (output > numOutputs->at(0))
throw std::runtime_error("Given output node of the forest is larger or equal to number of output nodes.");
int c = 0;
for (int i = 0; i < numTrees->at(0); i++)
if (outputs->at(i) == output)
c++;
if (c == 0)
std::runtime_error("No trees found for given output node of the forest.");
this->fTrees.resize(c);
// Load parameters in trees
c = 0;
for (int i = 0; i < numTrees->at(0); i++) {
// Select only trees for the given output node of the forest
if (outputs->at(i) != output)
continue;
// Set tree depth
this->fTrees[c].fTreeDepth = maxDepth->at(0);
// Set feature indices
this->fTrees[c].fInputs.resize(lenInputs);
for (int j = 0; j < lenInputs; j++)
this->fTrees[c].fInputs[j] = inputs->at(i * lenInputs + j);
// Set threshold values
this->fTrees[c].fThresholds.resize(lenThresholds);
for (int j = 0; j < lenThresholds; j++)
this->fTrees[c].fThresholds[j] = thresholds->at(i * lenThresholds + j);
// Fill sparse trees fully
this->fTrees[c].FillSparse();
c++;
}
// Sort trees by first cut variable and threshold value
if (sortTrees)
std::sort(this->fTrees.begin(), this->fTrees.end(), Internal::CompareTree<T>);
// Clean-up
delete maxDepth;
delete numTrees;
delete numInputs;
delete objective;
delete inputs;
delete thresholds;
file->Close();
}
/// Forest using branchless jitted trees
///
/// \tparam T Value type for the computation (usually floating point type)
template <typename T>
struct BranchlessJittedForest : public ForestBase<T, std::function<void (const T *, const int, bool, T*)>> {
std::string Load(const std::string &key, const std::string &filename, const int output = 0, const bool sortTrees = true);
void Inference(const T *inputs, const int rows, bool layout, T *predictions);
};
/// Load parameters from a ROOT file to the branchless trees
///
/// \param[in] key Name of folder in the ROOT file containing the model parameters
/// \param[in] filename Filename of the ROOT file
/// \param[in] output Load trees corresponding to the given output node of the forest
/// \param[in] sortTrees Flag to indicate sorting the input trees by the cut value of the first node of each tree
/// \return Return jitted code as string
template <typename T>
inline std::string
BranchlessJittedForest<T>::Load(const std::string &key, const std::string &filename, const int output, const bool sortTrees)
{
// Open input file and get folder from key
auto file = TFile::Open(filename.c_str(), "READ");
// Load parameters from file
auto maxDepth = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/max_depth");
auto numTrees = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/num_trees");
auto numInputs = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/num_inputs");
auto numOutputs = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/num_outputs");
auto objective = Internal::GetObjectSafe<std::string>(file, filename, key + "/objective");
auto inputs = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/inputs");
auto outputs = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/outputs");
auto thresholds = Internal::GetObjectSafe<std::vector<T>>(file, filename, key + "/thresholds");
this->fNumInputs = numInputs->at(0);
this->fObjectiveFunc = Objectives::GetFunction<T>(*objective);
const auto lenInputs = std::pow(2, maxDepth->at(0)) - 1;
const auto lenThresholds = std::pow(2, maxDepth->at(0) + 1) - 1;
// Find number of trees corresponding to given output node
if (output > numOutputs->at(0))
throw std::runtime_error("Given output node of the forest is larger or equal to number of output nodes.");
int c = 0;
for (int i = 0; i < numTrees->at(0); i++)
if (outputs->at(i) == output)
c++;
if (c == 0)
std::runtime_error("No trees found for given output node of the forest.");
// Get typename of template argument as string
std::string typeName = ROOT::Internal::GetDemangledTypeName(typeid(T));
if (typeName.compare("") == 0) {
throw std::runtime_error("Failed to just-in-time compile inference code for branchless forest (typename as string)");
}
// Load parameters in trees
std::vector<T> firstThreshold(c);
std::vector<int> firstInput(c, -1);
std::vector<std::string> codes(c);
c = 0;
for (int i = 0; i < numTrees->at(0); i++) {
// Select only trees for the given output node of the forest
if (outputs->at(i) != output)
continue;
// Set tree depth
BranchlessTree<T> tree;
tree.fTreeDepth = maxDepth->at(0);
// Set feature indices
tree.fInputs.resize(lenInputs);
for (int j = 0; j < lenInputs; j++)
tree.fInputs[j] = inputs->at(i * lenInputs + j);
// Set threshold values
tree.fThresholds.resize(lenThresholds);
for (int j = 0; j < lenThresholds; j++)
tree.fThresholds[j] = thresholds->at(i * lenThresholds + j);
// Fill sparse trees fully
tree.FillSparse();
// Save first threshold and input index for ordering the trees later
firstThreshold[c] = tree.fThresholds[0];
if (lenInputs != 0)
firstInput[c] = tree.fInputs[0];
// Save code for jitting
std::stringstream ss;
ss << "tree" << c;
codes[c] = tree.GetInferenceCode(ss.str(), typeName);
c++;
}
// Sort trees by first cut variable and threshold value
std::vector<int> treeIndices(codes.size());
for(int i = 0; i < c; i++) treeIndices[i] = i;
if (sortTrees) {
auto compareIndices = [&firstInput, &firstThreshold](int i, int j)
{
if (firstInput[i] == firstInput[j])
return firstThreshold[i] < firstThreshold[j];
else
return firstInput[i] < firstInput[j];
};
std::sort(treeIndices.begin(), treeIndices.end(), compareIndices);
}
// Get unique ID for a private namespace
TUUID uuid;
std::string nameSpace = uuid.AsString();
for (auto& v : nameSpace) {
if (v == '-') v = '_';
}
nameSpace = "ns_" + nameSpace;
// JIT the forest
std::stringstream jitForest;
jitForest << "#pragma cling optimize(3)\n"
<< "namespace " << nameSpace << " {\n";
for (int i = 0; i < static_cast<int>(codes.size()); i++) {
jitForest << codes[treeIndices[i]] << "\n\n";
}
jitForest << "void Inference(const "
<< typeName << "* inputs, const int rows, bool layout, "
<< typeName << "* predictions)"
<< "\n{\n"
<< " const auto strideTree = layout ? 1 : rows;\n"
<< " const auto strideBatch = layout ? " << this->fNumInputs << " : 1;\n"
<< " for (int i = 0; i < rows; i++) {\n"
<< " predictions[i] = 0.0;\n";
for (int i = 0; i < static_cast<int>(codes.size()); i++) {
std::stringstream ss;
ss << "tree" << i;
const std::string funcName = ss.str();
jitForest << " predictions[i] += " << funcName << "(inputs + i * strideBatch, strideTree);\n";
}
jitForest << " }\n"
<< "}\n"
<< "} // end namespace " << nameSpace;
const std::string jitForestStr = jitForest.str();
const auto err = gInterpreter->Declare(jitForestStr.c_str());
if (err == 0) {
throw std::runtime_error("Failed to just-in-time compile inference code for branchless forest (declare function)");
}
// Get function pointer and attach pointer to the forest
std::stringstream treesFunc;
treesFunc << "#pragma cling optimize(3)\n" << nameSpace << "::Inference";
const std::string treesFuncStr = treesFunc.str();
auto ptr = gInterpreter->Calc(treesFuncStr.c_str());
if (ptr == 0) {
throw std::runtime_error("Failed to just-in-time compile inference code for branchless forest (compile function)");
}
this->fTrees = reinterpret_cast<void (*)(const T *, int, bool, float*)>(ptr);
// Clean-up
delete maxDepth;
delete numTrees;
delete numInputs;
delete objective;
delete inputs;
delete thresholds;
file->Close();
return jitForestStr;
}
/// Perform inference of the forest with the jitted branchless implementation on a batch of inputs
///
/// \param[in] inputs Pointer to data containing the inputs
/// \param[in] rows Number of events in inputs vector
/// \param[in] layout Row major (true) or column major (false) memory layout
/// \param[in] predictions Pointer to the buffer to be filled with the predictions
template <typename T>
void BranchlessJittedForest<T>::Inference(const T *inputs, const int rows, bool layout, T *predictions)
{
this->fTrees(inputs, rows, layout, predictions);
for (int i = 0; i < rows; i++)
predictions[i] = this->fObjectiveFunc(predictions[i]);
}
} // namespace Experimental
} // namespace TMVA
#endif // TMVA_TREEINFERENCE_FOREST
<commit_msg>[TMVA] Make GetObjectSafe type-safe<commit_after>/**********************************************************************************
* Project: ROOT - a Root-integrated toolkit for multivariate data analysis *
* Package: TMVA *
* Web : http://tmva.sourceforge.net *
* *
* Description: *
* *
* Authors: *
* Stefan Wunsch (stefan.wunsch@cern.ch) *
* Luca Zampieri (luca.zampieri@alumni.epfl.ch) *
* *
* Copyright (c) 2019: *
* CERN, Switzerland *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted according to the terms listed in LICENSE *
* (http://tmva.sourceforge.net/LICENSE) *
**********************************************************************************/
#ifndef TMVA_TREEINFERENCE_FOREST
#define TMVA_TREEINFERENCE_FOREST
#include <functional>
#include <string>
#include <vector>
#include <stdexcept>
#include <cmath>
#include <algorithm>
#include "TFile.h"
#include "TDirectory.h"
#include "TInterpreter.h"
#include "TUUID.h"
#include "TGenericClassInfo.h" // ROOT::Internal::GetDemangledTypeName
#include "BranchlessTree.hxx"
#include "Objectives.hxx"
namespace TMVA {
namespace Experimental {
namespace Internal {
template <typename T>
T *GetObjectSafe(TFile *f, const std::string &n, const std::string &m)
{
auto *v = f->Get<T>(m.c_str());
if (v == nullptr)
throw std::runtime_error("Failed to read " + m + " from file " + n + ".");
return v;
}
template <typename T>
bool CompareTree(const BranchlessTree<T> &a, const BranchlessTree<T> &b)
{
if (a.fInputs[0] == b.fInputs[0])
return a.fThresholds[0] < b.fThresholds[0];
else
return a.fInputs[0] < b.fInputs[0];
}
} // namespace Internal
/// Forest base class
///
/// \tparam T Value type for the computation (usually floating point type)
/// \tparam ForestType Type of the collection of trees
template <typename T, typename ForestType>
struct ForestBase {
using Value_t = T;
std::function<T(T)> fObjectiveFunc; ///< Objective function
ForestType fTrees; ///< Store the forest, either as vector or jitted function
int fNumInputs; ///< Number of input variables
void Inference(const T *inputs, const int rows, bool layout, T *predictions);
};
/// Perform inference of the forest on a batch of inputs
///
/// \param[in] inputs Pointer to data containing the inputs
/// \param[in] rows Number of events in inputs vector
/// \param[in] layout Row major (true) or column major (false) memory layout
/// \param[in] predictions Pointer to the buffer to be filled with the predictions
template <typename T, typename ForestType>
inline void ForestBase<T, ForestType>::Inference(const T *inputs, const int rows, bool layout, T *predictions)
{
const auto strideTree = layout ? 1 : rows;
const auto strideBatch = layout ? fNumInputs : 1;
for (int i = 0; i < rows; i++) {
predictions[i] = 0.0;
for (auto &tree : fTrees) {
predictions[i] += tree.Inference(inputs + i * strideBatch, strideTree);
}
predictions[i] = fObjectiveFunc(predictions[i]);
}
}
/// Forest using branchless trees
///
/// \tparam T Value type for the computation (usually floating point type)
template <typename T>
struct BranchlessForest : public ForestBase<T, std::vector<BranchlessTree<T>>> {
void Load(const std::string &key, const std::string &filename, const int output = 0, const bool sortTrees = true);
};
/// Load parameters from a ROOT file to the branchless trees
///
/// \param[in] key Name of folder in the ROOT file containing the model parameters
/// \param[in] filename Filename of the ROOT file
/// \param[in] output Load trees corresponding to the given output node of the forest
/// \param[in] sortTrees Flag to indicate sorting the input trees by the cut value of the first node of each tree
template <typename T>
inline void
BranchlessForest<T>::Load(const std::string &key, const std::string &filename, const int output, const bool sortTrees)
{
// Open input file and get folder from key
auto file = TFile::Open(filename.c_str(), "READ");
// Load parameters from file
auto maxDepth = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/max_depth");
auto numTrees = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/num_trees");
auto numInputs = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/num_inputs");
auto numOutputs = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/num_outputs");
auto objective = Internal::GetObjectSafe<std::string>(file, filename, key + "/objective");
auto inputs = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/inputs");
auto outputs = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/outputs");
auto thresholds = Internal::GetObjectSafe<std::vector<T>>(file, filename, key + "/thresholds");
this->fNumInputs = numInputs->at(0);
this->fObjectiveFunc = Objectives::GetFunction<T>(*objective);
const auto lenInputs = std::pow(2, maxDepth->at(0)) - 1;
const auto lenThresholds = std::pow(2, maxDepth->at(0) + 1) - 1;
// Find number of trees corresponding to given output node
if (output > numOutputs->at(0))
throw std::runtime_error("Given output node of the forest is larger or equal to number of output nodes.");
int c = 0;
for (int i = 0; i < numTrees->at(0); i++)
if (outputs->at(i) == output)
c++;
if (c == 0)
std::runtime_error("No trees found for given output node of the forest.");
this->fTrees.resize(c);
// Load parameters in trees
c = 0;
for (int i = 0; i < numTrees->at(0); i++) {
// Select only trees for the given output node of the forest
if (outputs->at(i) != output)
continue;
// Set tree depth
this->fTrees[c].fTreeDepth = maxDepth->at(0);
// Set feature indices
this->fTrees[c].fInputs.resize(lenInputs);
for (int j = 0; j < lenInputs; j++)
this->fTrees[c].fInputs[j] = inputs->at(i * lenInputs + j);
// Set threshold values
this->fTrees[c].fThresholds.resize(lenThresholds);
for (int j = 0; j < lenThresholds; j++)
this->fTrees[c].fThresholds[j] = thresholds->at(i * lenThresholds + j);
// Fill sparse trees fully
this->fTrees[c].FillSparse();
c++;
}
// Sort trees by first cut variable and threshold value
if (sortTrees)
std::sort(this->fTrees.begin(), this->fTrees.end(), Internal::CompareTree<T>);
// Clean-up
delete maxDepth;
delete numTrees;
delete numInputs;
delete objective;
delete inputs;
delete thresholds;
file->Close();
}
/// Forest using branchless jitted trees
///
/// \tparam T Value type for the computation (usually floating point type)
template <typename T>
struct BranchlessJittedForest : public ForestBase<T, std::function<void (const T *, const int, bool, T*)>> {
std::string Load(const std::string &key, const std::string &filename, const int output = 0, const bool sortTrees = true);
void Inference(const T *inputs, const int rows, bool layout, T *predictions);
};
/// Load parameters from a ROOT file to the branchless trees
///
/// \param[in] key Name of folder in the ROOT file containing the model parameters
/// \param[in] filename Filename of the ROOT file
/// \param[in] output Load trees corresponding to the given output node of the forest
/// \param[in] sortTrees Flag to indicate sorting the input trees by the cut value of the first node of each tree
/// \return Return jitted code as string
template <typename T>
inline std::string
BranchlessJittedForest<T>::Load(const std::string &key, const std::string &filename, const int output, const bool sortTrees)
{
// Open input file and get folder from key
auto file = TFile::Open(filename.c_str(), "READ");
// Load parameters from file
auto maxDepth = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/max_depth");
auto numTrees = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/num_trees");
auto numInputs = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/num_inputs");
auto numOutputs = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/num_outputs");
auto objective = Internal::GetObjectSafe<std::string>(file, filename, key + "/objective");
auto inputs = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/inputs");
auto outputs = Internal::GetObjectSafe<std::vector<int>>(file, filename, key + "/outputs");
auto thresholds = Internal::GetObjectSafe<std::vector<T>>(file, filename, key + "/thresholds");
this->fNumInputs = numInputs->at(0);
this->fObjectiveFunc = Objectives::GetFunction<T>(*objective);
const auto lenInputs = std::pow(2, maxDepth->at(0)) - 1;
const auto lenThresholds = std::pow(2, maxDepth->at(0) + 1) - 1;
// Find number of trees corresponding to given output node
if (output > numOutputs->at(0))
throw std::runtime_error("Given output node of the forest is larger or equal to number of output nodes.");
int c = 0;
for (int i = 0; i < numTrees->at(0); i++)
if (outputs->at(i) == output)
c++;
if (c == 0)
std::runtime_error("No trees found for given output node of the forest.");
// Get typename of template argument as string
std::string typeName = ROOT::Internal::GetDemangledTypeName(typeid(T));
if (typeName.compare("") == 0) {
throw std::runtime_error("Failed to just-in-time compile inference code for branchless forest (typename as string)");
}
// Load parameters in trees
std::vector<T> firstThreshold(c);
std::vector<int> firstInput(c, -1);
std::vector<std::string> codes(c);
c = 0;
for (int i = 0; i < numTrees->at(0); i++) {
// Select only trees for the given output node of the forest
if (outputs->at(i) != output)
continue;
// Set tree depth
BranchlessTree<T> tree;
tree.fTreeDepth = maxDepth->at(0);
// Set feature indices
tree.fInputs.resize(lenInputs);
for (int j = 0; j < lenInputs; j++)
tree.fInputs[j] = inputs->at(i * lenInputs + j);
// Set threshold values
tree.fThresholds.resize(lenThresholds);
for (int j = 0; j < lenThresholds; j++)
tree.fThresholds[j] = thresholds->at(i * lenThresholds + j);
// Fill sparse trees fully
tree.FillSparse();
// Save first threshold and input index for ordering the trees later
firstThreshold[c] = tree.fThresholds[0];
if (lenInputs != 0)
firstInput[c] = tree.fInputs[0];
// Save code for jitting
std::stringstream ss;
ss << "tree" << c;
codes[c] = tree.GetInferenceCode(ss.str(), typeName);
c++;
}
// Sort trees by first cut variable and threshold value
std::vector<int> treeIndices(codes.size());
for(int i = 0; i < c; i++) treeIndices[i] = i;
if (sortTrees) {
auto compareIndices = [&firstInput, &firstThreshold](int i, int j)
{
if (firstInput[i] == firstInput[j])
return firstThreshold[i] < firstThreshold[j];
else
return firstInput[i] < firstInput[j];
};
std::sort(treeIndices.begin(), treeIndices.end(), compareIndices);
}
// Get unique ID for a private namespace
TUUID uuid;
std::string nameSpace = uuid.AsString();
for (auto& v : nameSpace) {
if (v == '-') v = '_';
}
nameSpace = "ns_" + nameSpace;
// JIT the forest
std::stringstream jitForest;
jitForest << "#pragma cling optimize(3)\n"
<< "namespace " << nameSpace << " {\n";
for (int i = 0; i < static_cast<int>(codes.size()); i++) {
jitForest << codes[treeIndices[i]] << "\n\n";
}
jitForest << "void Inference(const "
<< typeName << "* inputs, const int rows, bool layout, "
<< typeName << "* predictions)"
<< "\n{\n"
<< " const auto strideTree = layout ? 1 : rows;\n"
<< " const auto strideBatch = layout ? " << this->fNumInputs << " : 1;\n"
<< " for (int i = 0; i < rows; i++) {\n"
<< " predictions[i] = 0.0;\n";
for (int i = 0; i < static_cast<int>(codes.size()); i++) {
std::stringstream ss;
ss << "tree" << i;
const std::string funcName = ss.str();
jitForest << " predictions[i] += " << funcName << "(inputs + i * strideBatch, strideTree);\n";
}
jitForest << " }\n"
<< "}\n"
<< "} // end namespace " << nameSpace;
const std::string jitForestStr = jitForest.str();
const auto err = gInterpreter->Declare(jitForestStr.c_str());
if (err == 0) {
throw std::runtime_error("Failed to just-in-time compile inference code for branchless forest (declare function)");
}
// Get function pointer and attach pointer to the forest
std::stringstream treesFunc;
treesFunc << "#pragma cling optimize(3)\n" << nameSpace << "::Inference";
const std::string treesFuncStr = treesFunc.str();
auto ptr = gInterpreter->Calc(treesFuncStr.c_str());
if (ptr == 0) {
throw std::runtime_error("Failed to just-in-time compile inference code for branchless forest (compile function)");
}
this->fTrees = reinterpret_cast<void (*)(const T *, int, bool, float*)>(ptr);
// Clean-up
delete maxDepth;
delete numTrees;
delete numInputs;
delete objective;
delete inputs;
delete thresholds;
file->Close();
return jitForestStr;
}
/// Perform inference of the forest with the jitted branchless implementation on a batch of inputs
///
/// \param[in] inputs Pointer to data containing the inputs
/// \param[in] rows Number of events in inputs vector
/// \param[in] layout Row major (true) or column major (false) memory layout
/// \param[in] predictions Pointer to the buffer to be filled with the predictions
template <typename T>
void BranchlessJittedForest<T>::Inference(const T *inputs, const int rows, bool layout, T *predictions)
{
this->fTrees(inputs, rows, layout, predictions);
for (int i = 0; i < rows; i++)
predictions[i] = this->fObjectiveFunc(predictions[i]);
}
} // namespace Experimental
} // namespace TMVA
#endif // TMVA_TREEINFERENCE_FOREST
<|endoftext|> |
<commit_before>// ----------------------------------------------------------------------------
// ------------- AI Battleground, Copyright(C) Maciej Pryc, 2016 --------------
// ----------------------------------------------------------------------------
#include "CapturePoint.h"
#include "TextureManager.h"
#include "LevelInfo.h"
#include <iostream>
CapturePoint::CapturePoint(class LevelInfo* argLevelInfo, class TextureManager* TexManager, sf::Vector2f argPosition, ETeam argTeam) :
MyLevelInfo(argLevelInfo), ActorsArray(MyLevelInfo->GetActorsArray()), ActorsNumber(MyLevelInfo->GetActorsNumber()),
Position(argPosition), HealStepInterval(sf::seconds(0.2f)), Team(argTeam), MaxHP(10000.0f), HP(MaxHP), HPPerHealStep(MaxHP / CAPTURE_POINT_SPRITES_NUMBER),
LowHPThreshold(MaxHP * 0.6f), VeryLowHPThreshold(MaxHP * 0.33f), Size(0.0f), bHasLowHP(false)
{
sf::Vector2u FirstTextureSize;
for (int i = 0; i < CAPTURE_POINT_SPRITES_NUMBER; ++i)
{
std::string TexName(std::string("CapturePoint") + (Team == ETeam::TEAM_A ? "A" : "B") + std::to_string(i + 1));
sf::Vector2u TexSize = TexManager->InitTexture(&CapturePointSprite[i], TexName);
if (i == 0)
FirstTextureSize = TexSize;
else if (TexSize != FirstTextureSize)
std::cout << "CapturePoint construction: sprite textures in different sizes! " << TexName << std::endl;
CapturePointSprite[i].setPosition(Position);
CapturePointSprite[i].setOrigin(TexSize.x / 2.0f, TexSize.y / 2.0f);
}
Size = (float)FirstTextureSize.x;
bHasLowHP = HP < LowHPThreshold;
}
CapturePoint::~CapturePoint()
{
}
void CapturePoint::Update(const float DeltaTime)
{
HealStepTimeCounter += sf::seconds(DeltaTime);
if (HealStepTimeCounter >= HealStepInterval)
{
ChangeHP(HPPerHealStep);
HealStepTimeCounter -= HealStepInterval;
}
}
void CapturePoint::TakeDamage(float DamageAmount)
{
ChangeHP(-DamageAmount);
}
void CapturePoint::ChangeHP(float HPDelta)
{
bool bHadLowHP = bHasLowHP;
HP = Clamp(HP + HPDelta, 0.0f, MaxHP);
bHasLowHP = HP < LowHPThreshold;
if (bHadLowHP != bHasLowHP)
{
for (int i = 0; i < ActorsNumber; ++i)
{
if (ActorsArray[i] != nullptr && ActorsArray[i]->GetTeam() != Team && ActorsArray[i]->GetNearestEnemyCapturePoint() == this)
ActorsArray[i]->SetBEnemyCapturePointAtLowHP(bHasLowHP);
}
}
}
void CapturePoint::Draw(sf::RenderWindow* Window) const
{
Window->draw(GetCurrentSprite());
}
const sf::Sprite& CapturePoint::GetCurrentSprite() const
{
const float HPRatio = HP / MaxHP;
return CapturePointSprite[(int)((1.0f - HPRatio) * (CAPTURE_POINT_SPRITES_NUMBER - 1))];
}
sf::Vector2f CapturePoint::GetPosition() const
{
return Position;
}
float CapturePoint::GetSize() const
{
return Size;
}
bool CapturePoint::HasLowHP() const
{
return bHasLowHP;
}
bool CapturePoint::HasVeryLowHP() const
{
return HP < VeryLowHPThreshold;
}
float CapturePoint::GetHP() const
{
return HP;
}
<commit_msg>Capture point heal step frequency increased.<commit_after>// ----------------------------------------------------------------------------
// ------------- AI Battleground, Copyright(C) Maciej Pryc, 2016 --------------
// ----------------------------------------------------------------------------
#include "CapturePoint.h"
#include "TextureManager.h"
#include "LevelInfo.h"
#include <iostream>
CapturePoint::CapturePoint(class LevelInfo* argLevelInfo, class TextureManager* TexManager, sf::Vector2f argPosition, ETeam argTeam) :
MyLevelInfo(argLevelInfo), ActorsArray(MyLevelInfo->GetActorsArray()), ActorsNumber(MyLevelInfo->GetActorsNumber()),
Position(argPosition), HealStepInterval(sf::seconds(0.1f)), Team(argTeam), MaxHP(10000.0f), HP(MaxHP), HPPerHealStep(MaxHP / CAPTURE_POINT_SPRITES_NUMBER),
LowHPThreshold(MaxHP * 0.6f), VeryLowHPThreshold(MaxHP * 0.33f), Size(0.0f), bHasLowHP(false)
{
sf::Vector2u FirstTextureSize;
for (int i = 0; i < CAPTURE_POINT_SPRITES_NUMBER; ++i)
{
std::string TexName(std::string("CapturePoint") + (Team == ETeam::TEAM_A ? "A" : "B") + std::to_string(i + 1));
sf::Vector2u TexSize = TexManager->InitTexture(&CapturePointSprite[i], TexName);
if (i == 0)
FirstTextureSize = TexSize;
else if (TexSize != FirstTextureSize)
std::cout << "CapturePoint construction: sprite textures in different sizes! " << TexName << std::endl;
CapturePointSprite[i].setPosition(Position);
CapturePointSprite[i].setOrigin(TexSize.x / 2.0f, TexSize.y / 2.0f);
}
Size = (float)FirstTextureSize.x;
bHasLowHP = HP < LowHPThreshold;
}
CapturePoint::~CapturePoint()
{
}
void CapturePoint::Update(const float DeltaTime)
{
HealStepTimeCounter += sf::seconds(DeltaTime);
if (HealStepTimeCounter >= HealStepInterval)
{
ChangeHP(HPPerHealStep);
HealStepTimeCounter -= HealStepInterval;
}
}
void CapturePoint::TakeDamage(float DamageAmount)
{
ChangeHP(-DamageAmount);
}
void CapturePoint::ChangeHP(float HPDelta)
{
bool bHadLowHP = bHasLowHP;
HP = Clamp(HP + HPDelta, 0.0f, MaxHP);
bHasLowHP = HP < LowHPThreshold;
if (bHadLowHP != bHasLowHP)
{
for (int i = 0; i < ActorsNumber; ++i)
{
if (ActorsArray[i] != nullptr && ActorsArray[i]->GetTeam() != Team && ActorsArray[i]->GetNearestEnemyCapturePoint() == this)
ActorsArray[i]->SetBEnemyCapturePointAtLowHP(bHasLowHP);
}
}
}
void CapturePoint::Draw(sf::RenderWindow* Window) const
{
Window->draw(GetCurrentSprite());
}
const sf::Sprite& CapturePoint::GetCurrentSprite() const
{
const float HPRatio = HP / MaxHP;
return CapturePointSprite[(int)((1.0f - HPRatio) * (CAPTURE_POINT_SPRITES_NUMBER - 1))];
}
sf::Vector2f CapturePoint::GetPosition() const
{
return Position;
}
float CapturePoint::GetSize() const
{
return Size;
}
bool CapturePoint::HasLowHP() const
{
return bHasLowHP;
}
bool CapturePoint::HasVeryLowHP() const
{
return HP < VeryLowHPThreshold;
}
float CapturePoint::GetHP() const
{
return HP;
}
<|endoftext|> |
<commit_before>/*********************************************************************
*
* Copyright (C) 2008, Simon Kagstrom
*
* Filename: jfmt.cc
* Author: Simon Kagstrom <simon.kagstrom@gmail.com>
* Description: Jfmt instructions (jumps and calls)
*
* $Id:$
*
********************************************************************/
class BranchInstruction : public Instruction
{
public:
BranchInstruction(uint32_t address, int opcode,
MIPS_register_t rs, MIPS_register_t rt, MIPS_register_t rd,
int32_t extra) : Instruction(address, opcode, rs, rt, rd, extra)
{
}
bool pass1()
{
if (this->delayed)
this->delayed->pass1();
return true;
}
bool isBranch()
{
return true;
}
int getMaxStackHeight() { return 0; }
};
class Jump : public BranchInstruction
{
public:
Jump(uint32_t address, int opcode, int32_t extra) : BranchInstruction(address, opcode, R_ZERO, R_ZERO, R_ZERO, extra)
{
}
bool pass1()
{
Instruction *dstInsn = controller->getBranchTarget(this->extra << 2);
if (this->delayed)
this->delayed->pass1();
dstInsn->setBranchTarget();
return true;
}
bool pass2()
{
Instruction *dst = controller->getBranchTarget(this->extra << 2);
if (this->delayed)
this->delayed->pass2();
if (!dst)
{
emit->error("Jump from 0x%x to 0x%x: target not found\n",
this->address, this->extra << 2);
return false;
}
emit->bc_goto(dst->getAddress());
return true;
}
};
class Jalr : public BranchInstruction
{
public:
Jalr(uint32_t address, int opcode, MIPS_register_t rs) : BranchInstruction(address, opcode, rs, R_ZERO, R_ZERO, 0)
{
this->dstMethod = NULL;
}
bool pass1()
{
this->dstMethod = controller->getCallTableMethod();
assert(this->dstMethod);
if (this->delayed)
this->delayed->pass1();
return true;
}
bool pass2()
{
void *it;
emit->bc_pushregister(this->rs);
if (this->delayed)
this->delayed->pass2();
for (MIPS_register_t reg = this->dstMethod->getFirstRegisterToPass(&it);
reg != 0;
reg = this->dstMethod->getNextRegisterToPass(&it))
{
emit->bc_pushregister( reg );
}
emit->bc_invokestatic( "%s", this->dstMethod->getJavaMethodName() );
if (this->dstMethod->clobbersReg(R_V1))
{
emit->bc_getstatic("CRunTime/saved_v1 I");
emit->bc_popregister( R_V1 );
}
if (this->dstMethod->clobbersReg(R_V0))
emit->bc_popregister( R_V0 );
return true;
}
int fillDestinations(int *p)
{
return this->addToRegisterUsage(R_V0, p) + this->addToRegisterUsage(R_V1, p);
}
int fillSources(int *p)
{
return this->addToRegisterUsage(this->rs, p) + this->addToRegisterUsage(R_A0, p) + this->addToRegisterUsage(R_A1, p) + this->addToRegisterUsage(R_A2, p) + this->addToRegisterUsage(R_A3, p) + this->addToRegisterUsage(R_SP, p);
};
private:
JavaMethod *dstMethod;
};
class Jal : public BranchInstruction
{
public:
Jal(uint32_t address, int opcode, int32_t extra) : BranchInstruction(address, opcode, R_ZERO, R_ZERO, R_ZERO, extra)
{
this->dstMethod = NULL;
this->builtin = NULL;
}
bool pass1()
{
this->dstMethod = controller->getMethodByAddress(this->extra << 2);
if (this->delayed)
this->delayed->pass1();
if (!this->dstMethod)
{
emit->error("Jal from 0x%x to 0x%x: Target address not found\n",
this->address, this->extra << 2);
return false;
}
this->builtin = controller->matchBuiltin(this->dstMethod->getName());
if (this->builtin)
return this->builtin->pass1(this);
return true;
}
virtual bool pass2()
{
void *it;
if (this->delayed)
this->delayed->pass2();
if (this->builtin)
return this->builtin->pass2(this);
/* Pass registers */
for (MIPS_register_t reg = this->dstMethod->getFirstRegisterToPass(&it);
reg != 0;
reg = this->dstMethod->getNextRegisterToPass(&it))
{
emit->bc_pushregister( reg );
}
emit->bc_invokestatic("%s/%s", "Cibyl", this->dstMethod->getJavaMethodName());
if (this->dstMethod->clobbersReg(R_V1))
{
emit->bc_getstatic("CRunTime/saved_v1 I");
emit->bc_popregister( R_V1 );
}
if (this->dstMethod->clobbersReg(R_V0))
emit->bc_popregister( R_V0 );
return true;
}
int fillDestinations(int *p)
{
int out = 0;
out += this->addToRegisterUsage(R_V0, p) + this->addToRegisterUsage(R_V1, p);
if (this->builtin)
out += this->builtin->fillDestinations(p);
return out;
}
int fillSources(int *p)
{
int out = 0;
out += this->addToRegisterUsage(this->rs, p) + this->addToRegisterUsage(R_A0, p) + this->addToRegisterUsage(R_A1, p) + this->addToRegisterUsage(R_A2, p) + this->addToRegisterUsage(R_A3, p) + this->addToRegisterUsage(R_SP, p);
if (this->builtin)
out += this->builtin->fillSources(p);
return out;
};
int getMaxStackHeight()
{
assert(this->dstMethod);
return max(this->dstMethod->getRegistersToPass(), 2);
}
protected:
JavaMethod *dstMethod;
Builtin *builtin;
};
class JalReturn : public Jal
{
public:
JalReturn(uint32_t address, int opcode, int32_t extra) : Jal(address, opcode, extra)
{
}
bool pass2()
{
bool out = Jal::pass2();
/* Return from this function (undo the tail call optimization) */
emit->bc_goto("__CIBYL_function_return");
return out;
}
};
class Jr : public BranchInstruction
{
public:
Jr(uint32_t address, int opcode, MIPS_register_t rs) : BranchInstruction(address, opcode, rs, R_ZERO, R_ZERO, 0)
{
}
virtual bool isRegisterIndirectJump()
{
if ( this->rs != R_RA )
return true;
return false;
}
virtual bool isReturnJump()
{
if ( this->rs == R_RA )
return true;
return false;
}
int fillSources(int *p)
{
return this->addToRegisterUsage(this->rs, p);
};
bool pass2()
{
if (this->rs == R_RA)
{
if (this->delayed)
this->delayed->pass2();
emit->bc_goto("__CIBYL_function_return");
}
else
{
emit->bc_pushregister( this->rs );
if (this->delayed)
this->delayed->pass2();
emit->bc_goto("__CIBYL_local_jumptab");
}
return true;
}
};
class TwoRegisterConditionalJump : public BranchInstruction
{
public:
TwoRegisterConditionalJump(const char *what, uint32_t address, int opcode, MIPS_register_t rs,
MIPS_register_t rt, int32_t extra) : BranchInstruction(address, opcode, rs, rt, R_ZERO, extra)
{
this->bc = what;
this->dst = (this->address + 4) + (this->extra << 2);
}
int fillSources(int *p)
{
return this->addToRegisterUsage(this->rs, p) + this->addToRegisterUsage(this->rt, p);
};
bool pass1()
{
Instruction *dstInsn = controller->getBranchTarget(this->dst);
JavaMethod *srcMethod = controller->getMethodByAddress( this->getAddress() );
JavaMethod *dstMethod = controller->getMethodByAddress( dstInsn->getAddress() );
if ( !dstInsn )
{
emit->error("The branch at 0x%x in does not have a target (address 0x%x)\n",
this->getAddress(), this->dst);
}
if ( srcMethod != dstMethod)
{
emit->error("The branch at 0x%x in method %s ends in method %s\n",
this->getAddress(), srcMethod->getName(), dstMethod->getName());
return false;
}
dstInsn->setBranchTarget();
return true;
}
bool pass2()
{
emit->bc_pushregister( this->rs );
emit->bc_pushregister( this->rt );
if (this->delayed)
this->delayed->pass2();
emit->bc_condbranch("%s L_%x", this->bc, this->dst);
return true;
}
private:
const char *bc;
uint32_t dst;
};
class OneRegisterConditionalJump : public BranchInstruction
{
public:
OneRegisterConditionalJump(const char *what, uint32_t address, int opcode, MIPS_register_t rs,
int32_t extra) : BranchInstruction(address, opcode, rs, R_ZERO, R_ZERO, extra)
{
this->bc = what;
this->dst = (this->address + 4) + (this->extra << 2);
}
int fillSources(int *p)
{
return this->addToRegisterUsage(this->rs, p);
};
bool pass1()
{
Instruction *dstInsn = controller->getBranchTarget(this->dst);
JavaMethod *srcMethod = controller->getMethodByAddress( this->getAddress() );
JavaMethod *dstMethod = controller->getMethodByAddress( dstInsn->getAddress() );
if ( !dstInsn )
{
emit->error("The branch at 0x%x in does not have a target (address 0x%x)\n",
this->getAddress(), this->dst);
}
if ( srcMethod != dstMethod)
{
emit->error("The branch at 0x%x in method %s ends in method %s\n",
this->getAddress(), srcMethod->getName(), dstMethod->getName());
return false;
}
dstInsn->setBranchTarget();
return true;
}
bool pass2()
{
emit->bc_pushregister( this->rs );
if (this->delayed)
this->delayed->pass2();
emit->bc_condbranch("%s L_%x", this->bc, this->dst);
return true;
}
private:
const char *bc;
uint32_t dst;
};
<commit_msg>Don't hardcode class name<commit_after>/*********************************************************************
*
* Copyright (C) 2008, Simon Kagstrom
*
* Filename: jfmt.cc
* Author: Simon Kagstrom <simon.kagstrom@gmail.com>
* Description: Jfmt instructions (jumps and calls)
*
* $Id:$
*
********************************************************************/
class BranchInstruction : public Instruction
{
public:
BranchInstruction(uint32_t address, int opcode,
MIPS_register_t rs, MIPS_register_t rt, MIPS_register_t rd,
int32_t extra) : Instruction(address, opcode, rs, rt, rd, extra)
{
}
bool pass1()
{
if (this->delayed)
this->delayed->pass1();
return true;
}
bool isBranch()
{
return true;
}
int getMaxStackHeight() { return 0; }
};
class Jump : public BranchInstruction
{
public:
Jump(uint32_t address, int opcode, int32_t extra) : BranchInstruction(address, opcode, R_ZERO, R_ZERO, R_ZERO, extra)
{
}
bool pass1()
{
Instruction *dstInsn = controller->getBranchTarget(this->extra << 2);
if (this->delayed)
this->delayed->pass1();
dstInsn->setBranchTarget();
return true;
}
bool pass2()
{
Instruction *dst = controller->getBranchTarget(this->extra << 2);
if (this->delayed)
this->delayed->pass2();
if (!dst)
{
emit->error("Jump from 0x%x to 0x%x: target not found\n",
this->address, this->extra << 2);
return false;
}
emit->bc_goto(dst->getAddress());
return true;
}
};
class Jalr : public BranchInstruction
{
public:
Jalr(uint32_t address, int opcode, MIPS_register_t rs) : BranchInstruction(address, opcode, rs, R_ZERO, R_ZERO, 0)
{
this->dstMethod = NULL;
}
bool pass1()
{
this->dstMethod = controller->getCallTableMethod();
assert(this->dstMethod);
if (this->delayed)
this->delayed->pass1();
return true;
}
bool pass2()
{
void *it;
emit->bc_pushregister(this->rs);
if (this->delayed)
this->delayed->pass2();
for (MIPS_register_t reg = this->dstMethod->getFirstRegisterToPass(&it);
reg != 0;
reg = this->dstMethod->getNextRegisterToPass(&it))
{
emit->bc_pushregister( reg );
}
emit->bc_invokestatic( "%s", this->dstMethod->getJavaMethodName() );
if (this->dstMethod->clobbersReg(R_V1))
{
emit->bc_getstatic("CRunTime/saved_v1 I");
emit->bc_popregister( R_V1 );
}
if (this->dstMethod->clobbersReg(R_V0))
emit->bc_popregister( R_V0 );
return true;
}
int fillDestinations(int *p)
{
return this->addToRegisterUsage(R_V0, p) + this->addToRegisterUsage(R_V1, p);
}
int fillSources(int *p)
{
return this->addToRegisterUsage(this->rs, p) + this->addToRegisterUsage(R_A0, p) + this->addToRegisterUsage(R_A1, p) + this->addToRegisterUsage(R_A2, p) + this->addToRegisterUsage(R_A3, p) + this->addToRegisterUsage(R_SP, p);
};
private:
JavaMethod *dstMethod;
};
class Jal : public BranchInstruction
{
public:
Jal(uint32_t address, int opcode, int32_t extra) : BranchInstruction(address, opcode, R_ZERO, R_ZERO, R_ZERO, extra)
{
this->dstMethod = NULL;
this->dstClass = NULL;
this->builtin = NULL;
}
bool pass1()
{
this->dstMethod = controller->getMethodByAddress(this->extra << 2);
panic_if(!this->dstMethod, "No method found for jal to 0x%x\n", this->extra << 2);
this->dstClass = controller->getClassByMethodName(this->dstMethod->getName());
if (this->delayed)
this->delayed->pass1();
if (!this->dstMethod)
{
emit->error("Jal from 0x%x to 0x%x: Target address not found\n",
this->address, this->extra << 2);
return false;
}
this->builtin = controller->matchBuiltin(this->dstMethod->getName());
if (this->builtin)
return this->builtin->pass1(this);
return true;
}
virtual bool pass2()
{
void *it;
if (this->delayed)
this->delayed->pass2();
if (this->builtin)
return this->builtin->pass2(this);
/* Pass registers */
for (MIPS_register_t reg = this->dstMethod->getFirstRegisterToPass(&it);
reg != 0;
reg = this->dstMethod->getNextRegisterToPass(&it))
{
emit->bc_pushregister( reg );
}
emit->bc_invokestatic("%s/%s", dstClass->getName(), this->dstMethod->getJavaMethodName());
if (this->dstMethod->clobbersReg(R_V1))
{
emit->bc_getstatic("CRunTime/saved_v1 I");
emit->bc_popregister( R_V1 );
}
if (this->dstMethod->clobbersReg(R_V0))
emit->bc_popregister( R_V0 );
return true;
}
int fillDestinations(int *p)
{
int out = 0;
out += this->addToRegisterUsage(R_V0, p) + this->addToRegisterUsage(R_V1, p);
if (this->builtin)
out += this->builtin->fillDestinations(p);
return out;
}
int fillSources(int *p)
{
int out = 0;
out += this->addToRegisterUsage(this->rs, p) + this->addToRegisterUsage(R_A0, p) + this->addToRegisterUsage(R_A1, p) + this->addToRegisterUsage(R_A2, p) + this->addToRegisterUsage(R_A3, p) + this->addToRegisterUsage(R_SP, p);
if (this->builtin)
out += this->builtin->fillSources(p);
return out;
};
int getMaxStackHeight()
{
assert(this->dstMethod);
return max(this->dstMethod->getRegistersToPass(), 2);
}
protected:
JavaMethod *dstMethod;
JavaClass *dstClass;
Builtin *builtin;
};
class JalReturn : public Jal
{
public:
JalReturn(uint32_t address, int opcode, int32_t extra) : Jal(address, opcode, extra)
{
}
bool pass2()
{
bool out = Jal::pass2();
/* Return from this function (undo the tail call optimization) */
emit->bc_goto("__CIBYL_function_return");
return out;
}
};
class Jr : public BranchInstruction
{
public:
Jr(uint32_t address, int opcode, MIPS_register_t rs) : BranchInstruction(address, opcode, rs, R_ZERO, R_ZERO, 0)
{
}
virtual bool isRegisterIndirectJump()
{
if ( this->rs != R_RA )
return true;
return false;
}
virtual bool isReturnJump()
{
if ( this->rs == R_RA )
return true;
return false;
}
int fillSources(int *p)
{
return this->addToRegisterUsage(this->rs, p);
};
bool pass2()
{
if (this->rs == R_RA)
{
if (this->delayed)
this->delayed->pass2();
emit->bc_goto("__CIBYL_function_return");
}
else
{
emit->bc_pushregister( this->rs );
if (this->delayed)
this->delayed->pass2();
emit->bc_goto("__CIBYL_local_jumptab");
}
return true;
}
};
class TwoRegisterConditionalJump : public BranchInstruction
{
public:
TwoRegisterConditionalJump(const char *what, uint32_t address, int opcode, MIPS_register_t rs,
MIPS_register_t rt, int32_t extra) : BranchInstruction(address, opcode, rs, rt, R_ZERO, extra)
{
this->bc = what;
this->dst = (this->address + 4) + (this->extra << 2);
}
int fillSources(int *p)
{
return this->addToRegisterUsage(this->rs, p) + this->addToRegisterUsage(this->rt, p);
};
bool pass1()
{
Instruction *dstInsn = controller->getBranchTarget(this->dst);
JavaMethod *srcMethod = controller->getMethodByAddress( this->getAddress() );
JavaMethod *dstMethod = controller->getMethodByAddress( dstInsn->getAddress() );
if ( !dstInsn )
{
emit->error("The branch at 0x%x in does not have a target (address 0x%x)\n",
this->getAddress(), this->dst);
}
if ( srcMethod != dstMethod)
{
emit->error("The branch at 0x%x in method %s ends in method %s\n",
this->getAddress(), srcMethod->getName(), dstMethod->getName());
return false;
}
dstInsn->setBranchTarget();
return true;
}
bool pass2()
{
emit->bc_pushregister( this->rs );
emit->bc_pushregister( this->rt );
if (this->delayed)
this->delayed->pass2();
emit->bc_condbranch("%s L_%x", this->bc, this->dst);
return true;
}
private:
const char *bc;
uint32_t dst;
};
class OneRegisterConditionalJump : public BranchInstruction
{
public:
OneRegisterConditionalJump(const char *what, uint32_t address, int opcode, MIPS_register_t rs,
int32_t extra) : BranchInstruction(address, opcode, rs, R_ZERO, R_ZERO, extra)
{
this->bc = what;
this->dst = (this->address + 4) + (this->extra << 2);
}
int fillSources(int *p)
{
return this->addToRegisterUsage(this->rs, p);
};
bool pass1()
{
Instruction *dstInsn = controller->getBranchTarget(this->dst);
JavaMethod *srcMethod = controller->getMethodByAddress( this->getAddress() );
JavaMethod *dstMethod = controller->getMethodByAddress( dstInsn->getAddress() );
if ( !dstInsn )
{
emit->error("The branch at 0x%x in does not have a target (address 0x%x)\n",
this->getAddress(), this->dst);
}
if ( srcMethod != dstMethod)
{
emit->error("The branch at 0x%x in method %s ends in method %s\n",
this->getAddress(), srcMethod->getName(), dstMethod->getName());
return false;
}
dstInsn->setBranchTarget();
return true;
}
bool pass2()
{
emit->bc_pushregister( this->rs );
if (this->delayed)
this->delayed->pass2();
emit->bc_condbranch("%s L_%x", this->bc, this->dst);
return true;
}
private:
const char *bc;
uint32_t dst;
};
<|endoftext|> |
<commit_before>///
/// @file S2_hard.cpp
/// @brief Calculate the contribution of the hard special leaves which
/// require use of a sieve (Deleglise-Rivat algorithm).
/// This is a parallel implementation which uses compression
/// (PiTable & FactorTable) to reduce the memory usage by
/// about 10x.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <FactorTable.hpp>
#include <primecount-internal.hpp>
#include <int128.hpp>
#include <min_max.hpp>
#include <pmath.hpp>
#include <BitSieve.hpp>
#include <S2LoadBalancer.hpp>
#include <S2Status.hpp>
#include <stdint.h>
#include <algorithm>
#include <iostream>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primecount;
namespace {
namespace S2_hard {
/// For each prime calculate its first multiple >= low.
template <typename T>
vector<int64_t> generate_next_multiples(int64_t low, int64_t size, vector<T>& primes)
{
vector<int64_t> next;
next.reserve(size);
next.push_back(0);
for (int64_t b = 1; b < size; b++)
{
int64_t prime = primes[b];
int64_t next_multiple = ceil_div(low, prime) * prime;
next_multiple += prime * (~next_multiple & 1);
next.push_back(next_multiple);
}
return next;
}
/// phi(y, i) nodes with i <= c do not contribute to S2, so we
/// simply sieve out the multiples of the first c primes.
///
template <typename T>
void pre_sieve(BitSieve& sieve,
vector<T>& primes,
vector<int64_t>& next,
int64_t low,
int64_t high,
int64_t c)
{
sieve.fill(low, high);
for (int64_t i = 2; i <= c; i++)
{
int64_t k = next[i];
for (int64_t prime = primes[i]; k < high; k += prime * 2)
sieve.unset(k - low);
next[i] = k;
}
}
/// Cross-off the multiples of prime in the sieve array.
/// @return Count of crossed-off multiples.
///
int64_t cross_off(int64_t prime,
int64_t low,
int64_t high,
int64_t& next_multiple,
BitSieve& sieve)
{
int64_t unset = 0;
int64_t k = next_multiple;
for (; k < high; k += prime * 2)
{
if (sieve[k - low])
{
sieve.unset(k - low);
unset++;
}
}
next_multiple = k;
return unset;
}
/// Compute the S2 contribution of the special leaves that require
/// a sieve. Each thread processes the interval
/// [low_thread, low_thread + segments * segment_size[
/// and the missing special leaf contributions for the interval
/// [1, low_process[ are later reconstructed and added in
/// the parent S2_hard() function.
///
template <typename T, typename P, typename F>
T S2_hard_thread(T x,
int64_t y,
int64_t z,
int64_t c,
int64_t segment_size,
int64_t segments_per_thread,
int64_t thread_num,
int64_t low,
int64_t limit,
FactorTable<F>& factors,
PiTable& pi,
vector<P>& primes,
vector<int64_t>& mu_sum,
vector<int64_t>& phi)
{
low += segment_size * segments_per_thread * thread_num;
limit = min(low + segment_size * segments_per_thread, limit);
int64_t pi_sqrty = pi[isqrt(y)];
int64_t max_prime = min3(isqrt(x / low), isqrt(z), y);
int64_t pi_max = pi[max_prime];
if (c > pi_max)
return 0;
T S2_thread = 0;
BitSieve sieve(segment_size);
vector<int64_t> next = generate_next_multiples(low, pi_max + 1, primes);
phi.resize(pi_max + 1, 0);
mu_sum.resize(pi_max + 1, 0);
// Segmeted sieve of Eratosthenes
for (; low < limit; low += segment_size)
{
// Current segment = interval [low, high[
int64_t high = min(low + segment_size, limit);
int64_t b = c + 1;
// Cross-off the multiples of the first c primes
pre_sieve(sieve, primes, next, low, high, c);
int64_t count_low_high = sieve.count((high - 1) - low);
// For c + 1 <= b <= pi_sqrty
// Find all special leaves: n = primes[b] * m
// which satisfy: mu[m] != 0 && primes[b] < lpf[m] && low <= (x / n) < high
for (int64_t end = min(pi_sqrty, pi_max); b <= end; b++)
{
int64_t prime = primes[b];
T x2 = x / prime;
int64_t min_m = max(min(x2 / high, y), y / prime);
int64_t max_m = min(x2 / low, y);
int64_t count = 0;
int64_t i = 0;
if (prime >= max_m)
goto next_segment;
factors.to_index(&min_m);
factors.to_index(&max_m);
for (int64_t m = max_m; m > min_m; m--)
{
if (prime < factors.lpf(m))
{
int64_t xn = (int64_t) (x2 / factors.get_number(m));
count += sieve.count(i, xn - low);
i = xn - low + 1;
int64_t phi_xn = phi[b] + count;
int64_t mu_m = factors.mu(m);
S2_thread -= mu_m * phi_xn;
mu_sum[b] -= mu_m;
}
}
phi[b] += count_low_high;
count_low_high -= cross_off(prime, low, high, next[b], sieve);
}
// For pi_sqrty <= b <= pi_sqrtz
// Find all hard special leaves: n = primes[b] * primes[l]
// which satisfy: low <= (x / n) < high
for (; b <= pi_max; b++)
{
int64_t prime = primes[b];
T x2 = x / prime;
int64_t l = pi[min3(x2 / low, z / prime, y)];
int64_t min_hard_leaf = max3(min(x2 / high, y), y / prime, prime);
int64_t count = 0;
int64_t i = 0;
if (prime >= primes[l])
goto next_segment;
for (; primes[l] > min_hard_leaf; l--)
{
int64_t xn = (int64_t) (x2 / primes[l]);
count += sieve.count(i, xn - low);
i = xn - low + 1;
int64_t phi_xn = phi[b] + count;
S2_thread += phi_xn;
mu_sum[b]++;
}
phi[b] += count_low_high;
count_low_high -= cross_off(prime, low, high, next[b], sieve);
}
next_segment:;
}
return S2_thread;
}
/// Calculate the contribution of the hard special leaves which
/// require use of a sieve (to reduce the memory usage).
/// This is a parallel implementation with advanced load balancing.
/// As most special leaves tend to be in the first segments we
/// start off with a small segment size and few segments
/// per thread, after each iteration we dynamically increase
/// the segment size and the segments per thread.
///
template <typename T, typename P, typename F>
T S2_hard(T x,
int64_t y,
int64_t z,
int64_t c,
T s2_hard_approx,
PiTable& pi,
vector<P>& primes,
FactorTable<F>& factors,
int threads)
{
if (print_status())
{
cout << endl;
cout << "=== S2_hard(x, y) ===" << endl;
cout << "Computation of the hard special leaves" << endl;
}
double time = get_wtime();
T s2_hard = 0;
int64_t low = 1;
int64_t limit = z + 1;
S2Status status;
S2LoadBalancer loadBalancer(x, limit, threads);
int64_t segment_size = loadBalancer.get_min_segment_size();
int64_t segments_per_thread = 1;
vector<int64_t> phi_total(pi[min(isqrt(z), y)] + 1, 0);
while (low < limit)
{
int64_t segments = ceil_div(limit - low, segment_size);
threads = in_between(1, threads, segments);
segments_per_thread = in_between(1, segments_per_thread, ceil_div(segments, threads));
aligned_vector<vector<int64_t> > phi(threads);
aligned_vector<vector<int64_t> > mu_sum(threads);
aligned_vector<double> timings(threads);
#pragma omp parallel for num_threads(threads) reduction(+: s2_hard)
for (int i = 0; i < threads; i++)
{
timings[i] = get_wtime();
s2_hard += S2_hard_thread(x, y, z, c, segment_size, segments_per_thread,
i, low, limit, factors, pi, primes, mu_sum[i], phi[i]);
timings[i] = get_wtime() - timings[i];
}
// Once all threads have finished reconstruct and add the
// missing contribution of all special leaves. This must
// be done in order as each thread (i) requires the sum of
// the phi values from the previous threads.
//
for (int i = 0; i < threads; i++)
{
for (size_t j = 1; j < phi[i].size(); j++)
{
s2_hard += phi_total[j] * (T) mu_sum[i][j];
phi_total[j] += phi[i][j];
}
}
low += segments_per_thread * threads * segment_size;
loadBalancer.update(low, threads, &segment_size, &segments_per_thread, timings);
if (print_status())
status.print(s2_hard, s2_hard_approx, loadBalancer.get_rsd());
}
if (print_status())
print_result("S2_hard", s2_hard, time);
return s2_hard;
}
} // namespace S2_hard
} // namespace
namespace primecount {
int64_t S2_hard(int64_t x,
int64_t y,
int64_t z,
int64_t c,
int64_t s2_hard_approx,
PiTable& pi,
vector<int32_t>& primes,
FactorTable<uint16_t>& factors,
int threads)
{
return S2_hard::S2_hard((intfast64_t) x, y, z, c, (intfast64_t) s2_hard_approx, pi, primes, factors, threads);
}
#ifdef HAVE_INT128_T
int128_t S2_hard(int128_t x,
int64_t y,
int64_t z,
int64_t c,
int128_t s2_hard_approx,
PiTable& pi,
vector<uint32_t>& primes,
FactorTable<uint16_t>& factors,
int threads)
{
return S2_hard::S2_hard((intfast128_t) x, y, z, c, (intfast128_t) s2_hard_approx, pi, primes, factors, threads);
}
int128_t S2_hard(int128_t x,
int64_t y,
int64_t z,
int64_t c,
int128_t s2_hard_approx,
PiTable& pi,
vector<int64_t>& primes,
FactorTable<uint32_t>& factors,
int threads)
{
return S2_hard::S2_hard((intfast128_t) x, y, z, c, (intfast128_t) s2_hard_approx, pi, primes, factors, threads);
}
#endif
} // namespace primecount
<commit_msg>Refactoring<commit_after>///
/// @file S2_hard.cpp
/// @brief Calculate the contribution of the hard special leaves which
/// require use of a sieve (Deleglise-Rivat algorithm).
/// This is a parallel implementation which uses compression
/// (PiTable & FactorTable) to reduce the memory usage by
/// about 10x.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <FactorTable.hpp>
#include <primecount-internal.hpp>
#include <int128.hpp>
#include <min_max.hpp>
#include <pmath.hpp>
#include <BitSieve.hpp>
#include <S2LoadBalancer.hpp>
#include <S2Status.hpp>
#include <stdint.h>
#include <algorithm>
#include <iostream>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primecount;
namespace {
namespace S2_hard {
/// For each prime calculate its first multiple >= low.
template <typename T>
vector<int64_t> generate_next_multiples(int64_t low, int64_t size, vector<T>& primes)
{
vector<int64_t> next;
next.reserve(size);
next.push_back(0);
for (int64_t b = 1; b < size; b++)
{
int64_t prime = primes[b];
int64_t next_multiple = ceil_div(low, prime) * prime;
next_multiple += prime * (~next_multiple & 1);
next.push_back(next_multiple);
}
return next;
}
/// phi(y, i) nodes with i <= c do not contribute to S2, so we
/// simply sieve out the multiples of the first c primes.
///
template <typename T>
void pre_sieve(BitSieve& sieve,
vector<T>& primes,
vector<int64_t>& next,
int64_t low,
int64_t high,
int64_t c)
{
sieve.fill(low, high);
for (int64_t i = 2; i <= c; i++)
{
int64_t k = next[i];
for (int64_t prime = primes[i]; k < high; k += prime * 2)
sieve.unset(k - low);
next[i] = k;
}
}
/// Cross-off the multiples of prime in the sieve array.
/// @return Count of crossed-off multiples.
///
int64_t cross_off(int64_t prime,
int64_t low,
int64_t high,
int64_t& next_multiple,
BitSieve& sieve)
{
int64_t unset = 0;
int64_t k = next_multiple;
for (; k < high; k += prime * 2)
{
if (sieve[k - low])
{
sieve.unset(k - low);
unset++;
}
}
next_multiple = k;
return unset;
}
/// Compute the S2 contribution of the special leaves that require
/// a sieve. Each thread processes the interval
/// [low_thread, low_thread + segments * segment_size[
/// and the missing special leaf contributions for the interval
/// [1, low_process[ are later reconstructed and added in
/// the parent S2_hard() function.
///
template <typename T, typename P, typename F>
T S2_hard_thread(T x,
int64_t y,
int64_t z,
int64_t c,
int64_t segment_size,
int64_t segments_per_thread,
int64_t thread_num,
int64_t low,
int64_t limit,
FactorTable<F>& factors,
PiTable& pi,
vector<P>& primes,
vector<int64_t>& mu_sum,
vector<int64_t>& phi)
{
low += segment_size * segments_per_thread * thread_num;
limit = min(low + segment_size * segments_per_thread, limit);
int64_t pi_sqrty = pi[isqrt(y)];
int64_t max_prime = min3(isqrt(x / low), isqrt(z), y);
int64_t pi_max = pi[max_prime];
if (c > pi_max)
return 0;
T S2_thread = 0;
BitSieve sieve(segment_size);
vector<int64_t> next = generate_next_multiples(low, pi_max + 1, primes);
phi.resize(pi_max + 1, 0);
mu_sum.resize(pi_max + 1, 0);
// Segmeted sieve of Eratosthenes
for (; low < limit; low += segment_size)
{
// Current segment = interval [low, high[
int64_t high = min(low + segment_size, limit);
int64_t b = c + 1;
// Cross-off the multiples of the first c primes
pre_sieve(sieve, primes, next, low, high, c);
int64_t count_low_high = sieve.count((high - 1) - low);
// For c + 1 <= b <= pi_sqrty
// Find all special leaves: n = primes[b] * m
// which satisfy: mu[m] != 0 && primes[b] < lpf[m] && low <= (x / n) < high
for (int64_t end = min(pi_sqrty, pi_max); b <= end; b++)
{
int64_t prime = primes[b];
T x2 = x / prime;
int64_t min_m = max(min(x2 / high, y), y / prime);
int64_t max_m = min(x2 / low, y);
int64_t count = 0;
int64_t i = 0;
if (prime >= max_m)
goto next_segment;
factors.to_index(&min_m);
factors.to_index(&max_m);
for (int64_t m = max_m; m > min_m; m--)
{
if (prime < factors.lpf(m))
{
int64_t xn = (int64_t) (x2 / factors.get_number(m));
int64_t stop = xn - low;
count += sieve.count(i, stop);
i = stop + 1;
int64_t phi_xn = phi[b] + count;
int64_t mu_m = factors.mu(m);
S2_thread -= mu_m * phi_xn;
mu_sum[b] -= mu_m;
}
}
phi[b] += count_low_high;
count_low_high -= cross_off(prime, low, high, next[b], sieve);
}
// For pi_sqrty <= b <= pi_sqrtz
// Find all hard special leaves: n = primes[b] * primes[l]
// which satisfy: low <= (x / n) < high
for (; b <= pi_max; b++)
{
int64_t prime = primes[b];
T x2 = x / prime;
int64_t l = pi[min3(x2 / low, z / prime, y)];
int64_t min_hard_leaf = max3(min(x2 / high, y), y / prime, prime);
int64_t count = 0;
int64_t i = 0;
if (prime >= primes[l])
goto next_segment;
for (; primes[l] > min_hard_leaf; l--)
{
int64_t xn = (int64_t) (x2 / primes[l]);
int64_t stop = xn - low;
count += sieve.count(i, stop);
i = stop + 1;
int64_t phi_xn = phi[b] + count;
S2_thread += phi_xn;
mu_sum[b]++;
}
phi[b] += count_low_high;
count_low_high -= cross_off(prime, low, high, next[b], sieve);
}
next_segment:;
}
return S2_thread;
}
/// Calculate the contribution of the hard special leaves which
/// require use of a sieve (to reduce the memory usage).
/// This is a parallel implementation with advanced load balancing.
/// As most special leaves tend to be in the first segments we
/// start off with a small segment size and few segments
/// per thread, after each iteration we dynamically increase
/// the segment size and the segments per thread.
///
template <typename T, typename P, typename F>
T S2_hard(T x,
int64_t y,
int64_t z,
int64_t c,
T s2_hard_approx,
PiTable& pi,
vector<P>& primes,
FactorTable<F>& factors,
int threads)
{
if (print_status())
{
cout << endl;
cout << "=== S2_hard(x, y) ===" << endl;
cout << "Computation of the hard special leaves" << endl;
}
double time = get_wtime();
T s2_hard = 0;
int64_t low = 1;
int64_t limit = z + 1;
S2Status status;
S2LoadBalancer loadBalancer(x, limit, threads);
int64_t segment_size = loadBalancer.get_min_segment_size();
int64_t segments_per_thread = 1;
vector<int64_t> phi_total(pi[min(isqrt(z), y)] + 1, 0);
while (low < limit)
{
int64_t segments = ceil_div(limit - low, segment_size);
threads = in_between(1, threads, segments);
segments_per_thread = in_between(1, segments_per_thread, ceil_div(segments, threads));
aligned_vector<vector<int64_t> > phi(threads);
aligned_vector<vector<int64_t> > mu_sum(threads);
aligned_vector<double> timings(threads);
#pragma omp parallel for num_threads(threads) reduction(+: s2_hard)
for (int i = 0; i < threads; i++)
{
timings[i] = get_wtime();
s2_hard += S2_hard_thread(x, y, z, c, segment_size, segments_per_thread,
i, low, limit, factors, pi, primes, mu_sum[i], phi[i]);
timings[i] = get_wtime() - timings[i];
}
// Once all threads have finished reconstruct and add the
// missing contribution of all special leaves. This must
// be done in order as each thread (i) requires the sum of
// the phi values from the previous threads.
//
for (int i = 0; i < threads; i++)
{
for (size_t j = 1; j < phi[i].size(); j++)
{
s2_hard += phi_total[j] * (T) mu_sum[i][j];
phi_total[j] += phi[i][j];
}
}
low += segments_per_thread * threads * segment_size;
loadBalancer.update(low, threads, &segment_size, &segments_per_thread, timings);
if (print_status())
status.print(s2_hard, s2_hard_approx, loadBalancer.get_rsd());
}
if (print_status())
print_result("S2_hard", s2_hard, time);
return s2_hard;
}
} // namespace S2_hard
} // namespace
namespace primecount {
int64_t S2_hard(int64_t x,
int64_t y,
int64_t z,
int64_t c,
int64_t s2_hard_approx,
PiTable& pi,
vector<int32_t>& primes,
FactorTable<uint16_t>& factors,
int threads)
{
return S2_hard::S2_hard((intfast64_t) x, y, z, c, (intfast64_t) s2_hard_approx, pi, primes, factors, threads);
}
#ifdef HAVE_INT128_T
int128_t S2_hard(int128_t x,
int64_t y,
int64_t z,
int64_t c,
int128_t s2_hard_approx,
PiTable& pi,
vector<uint32_t>& primes,
FactorTable<uint16_t>& factors,
int threads)
{
return S2_hard::S2_hard((intfast128_t) x, y, z, c, (intfast128_t) s2_hard_approx, pi, primes, factors, threads);
}
int128_t S2_hard(int128_t x,
int64_t y,
int64_t z,
int64_t c,
int128_t s2_hard_approx,
PiTable& pi,
vector<int64_t>& primes,
FactorTable<uint32_t>& factors,
int threads)
{
return S2_hard::S2_hard((intfast128_t) x, y, z, c, (intfast128_t) s2_hard_approx, pi, primes, factors, threads);
}
#endif
} // namespace primecount
<|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Hammad Mazhar
// =============================================================================
//
// ChronoParallel test program using penalty method for frictional contact.
//
// The model simulated here consists of a number of spherical objects falling
// onto a mixer blade attached through a revolute joint to the ground.
//
// The global reference frame has Z up.
//
// If available, OpenGL is used for run-time rendering. Otherwise, the
// simulation is carried out for a pre-defined duration and output files are
// generated for post-processing with POV-Ray.
// =============================================================================
#include <stdio.h>
#include <vector>
#include <cmath>
#include "chrono_parallel/physics/ChSystemParallel.h"
#include "chrono/ChConfig.h"
#include "chrono/utils/ChUtilsCreators.h"
#include "chrono/utils/ChUtilsInputOutput.h"
#include "chrono/utils/ChUtilsGeometry.h"
#include "chrono/utils/ChUtilsGenerators.h"
#ifdef CHRONO_OPENGL
#include "chrono_opengl/ChOpenGLWindow.h"
#endif
using namespace chrono;
using namespace chrono::collision;
// -----------------------------------------------------------------------------
// Create a bin consisting of five boxes attached to the ground and a mixer
// blade attached through a revolute joint to ground. The mixer is constrained
// to rotate at constant angular velocity.
// -----------------------------------------------------------------------------
void AddContainer(ChSystemParallelDVI* sys) {
// IDs for the two bodies
int binId = -200;
int mixerId = -201;
// Create a common material
ChSharedPtr<ChMaterialSurface> mat(new ChMaterialSurface);
mat->SetFriction(0.4f);
// Create the containing bin (2 x 2 x 1)
ChSharedBodyPtr bin(new ChBody(new ChCollisionModelParallel));
bin->SetMaterialSurface(mat);
bin->SetIdentifier(binId);
bin->SetMass(1);
bin->SetPos(ChVector<>(0, 0, 0));
bin->SetRot(ChQuaternion<>(1, 0, 0, 0));
bin->SetCollide(true);
bin->SetBodyFixed(true);
ChVector<> hdim(.5, .5, 0.05);
bin->GetCollisionModel()->ClearModel();
utils::AddBoxGeometry(bin.get_ptr(), ChVector<>(hdim.x, hdim.y, hdim.z), ChVector<>(0, 0, -hdim.z));
// utils::AddBoxGeometry(bin.get_ptr(), ChVector<>(hdim.x, hdim.y, hdim.z), ChVector<>(0, 0, hdim.z*10));
bin->GetCollisionModel()->SetFamily(1);
bin->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(2);
bin->GetCollisionModel()->BuildModel();
sys->AddBody(bin);
}
// -----------------------------------------------------------------------------
// Create the fluid in the shape of a sphere.
// -----------------------------------------------------------------------------
void AddFluid(ChSystemParallelDVI* sys) {
ChFluidContainer* fluid_container = new ChFluidContainer(sys);
real radius = sys->GetSettings()->fluid.kernel_radius * 5; //*5
real dens = 30;
real3 num_fluid = real3(10, 10, 10);
real3 origin(0, 0, .2);
real vol;
std::vector<real3> pos_fluid;
std::vector<real3> vel_fluid;
double dist = sys->GetSettings()->fluid.kernel_radius * .75;
utils::HCPSampler<> sampler(dist);
utils::Generator::PointVector points = sampler.SampleSphere(ChVector<>(0, 0, 0), radius);
pos_fluid.resize(points.size());
vel_fluid.resize(points.size());
for (int i = 0; i < points.size(); i++) {
pos_fluid[i] = real3(points[i].x, points[i].y, points[i].z) + origin;
vel_fluid[i] = real3(0, 0, 0);
}
vol = 4.0 / 3.0 * CH_C_PI * pow(radius + sys->GetSettings()->fluid.kernel_radius, 3) / (points.size());
sys->GetSettings()->fluid.mass = sys->GetSettings()->fluid.density * vol * .5; //* .48; //*0.695;//* 0.6388;
std::cout << "fluid_mass: " << sys->GetSettings()->fluid.mass << std::endl;
fluid_container->UpdatePosition(0);
fluid_container->AddFluid(pos_fluid, vel_fluid);
}
// -----------------------------------------------------------------------------
// Create the system, specify simulation parameters, and run simulation loop.
// -----------------------------------------------------------------------------
int main(int argc, char* argv[]) {
int threads = 8;
// Simulation parameters
// ---------------------
double gravity = 9.81;
double time_step = 1e-3;
double time_end = 1;
double out_fps = 50;
uint max_iteration = 30;
real tolerance = 1e-3;
// Create system
// -------------
ChSystemParallelDVI msystem;
// omp_set_num_threads(4);
// Set number of threads.
// int max_threads = 2;//CHOMPfunctions::GetNumProcs();
// if (threads > max_threads)
// threads = max_threads;
// msystem.SetParallelThreadNumber(threads);
// CHOMPfunctions::SetNumThreads(threads);
// Set gravitational acceleration
msystem.Set_G_acc(ChVector<>(0, 0, -gravity));
// Set solver parameters
msystem.GetSettings()->solver.solver_mode = SLIDING;
msystem.GetSettings()->solver.max_iteration_normal = 0;
msystem.GetSettings()->solver.max_iteration_sliding = 40;
msystem.GetSettings()->solver.max_iteration_spinning = 0;
msystem.GetSettings()->solver.max_iteration_bilateral = 0;
msystem.GetSettings()->solver.tolerance = tolerance;
msystem.GetSettings()->solver.alpha = 0;
msystem.GetSettings()->solver.use_full_inertia_tensor = false;
msystem.GetSettings()->collision.use_two_level = false;
msystem.GetSettings()->solver.contact_recovery_speed = 100;
msystem.GetSettings()->solver.cache_step_length = true;
msystem.ChangeSolverType(BB);
msystem.GetSettings()->collision.narrowphase_algorithm = NARROWPHASE_HYBRID_MPR;
msystem.GetSettings()->fluid.tau = time_step * 4;
msystem.GetSettings()->fluid.cohesion = 0;
msystem.GetSettings()->fluid.epsilon = 0; // 1e-3;
msystem.GetSettings()->fluid.kernel_radius = .02;
msystem.GetSettings()->fluid.mass = .007 * 5.5;
msystem.GetSettings()->fluid.viscosity = 20;
msystem.GetSettings()->fluid.enable_viscosity = true;
msystem.GetSettings()->fluid.mu = .1;
msystem.GetSettings()->fluid.density = 1000;
msystem.GetSettings()->fluid.fluid_is_rigid = false;
//msystem.GetSettings()->fluid.max_interactions = 30;
msystem.GetSettings()->fluid.artificial_pressure = true;
msystem.GetSettings()->fluid.artificial_pressure_k = .001;
msystem.GetSettings()->fluid.artificial_pressure_dq = 0; //.2 * system->GetSettings()->fluid.kernel_radius;
msystem.GetSettings()->fluid.artificial_pressure_n = 4;
msystem.GetSettings()->fluid.collision_envelope = msystem.GetSettings()->fluid.kernel_radius * .05;
msystem.GetSettings()->fluid.vorticity_confinement = 40;
msystem.GetSettings()->collision.collision_envelope = (msystem.GetSettings()->fluid.kernel_radius * .05);
msystem.GetSettings()->collision.bins_per_axis = int3(2, 2, 2);
// msystem.SetLoggingLevel(LOG_TRACE, true);
// msystem.SetLoggingLevel(LOG_INFO, true);
// Create the fixed and moving bodies
// ----------------------------------
AddContainer(&msystem);
AddFluid(&msystem);
// Perform the simulation
// ----------------------
#ifdef CHRONO_OPENGL
opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
gl_window.Initialize(1280, 720, "fluidDVI", &msystem);
gl_window.SetCamera(ChVector<>(0, -10, 0), ChVector<>(0, 0, 0), ChVector<>(0, 0, 1));
// Uncomment the following two lines for the OpenGL manager to automatically
// run the simulation in an infinite loop.
// gl_window.StartDrawLoop(time_step);
// return 0;
while (true) {
if (gl_window.Active()) {
gl_window.DoStepDynamics(time_step);
gl_window.Render();
} else {
break;
}
}
#else
// Run simulation for specified time
int num_steps = std::ceil(time_end / time_step);
double time = 0;
for (int i = 0; i < num_steps; i++) {
msystem.DoStepDynamics(time_step);
time += time_step;
}
#endif
return 0;
}
<commit_msg>Update fluid demo<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Hammad Mazhar
// =============================================================================
//
// ChronoParallel test program using penalty method for frictional contact.
//
// The model simulated here consists of a number of spherical objects falling
// onto a mixer blade attached through a revolute joint to the ground.
//
// The global reference frame has Z up.
//
// If available, OpenGL is used for run-time rendering. Otherwise, the
// simulation is carried out for a pre-defined duration and output files are
// generated for post-processing with POV-Ray.
// =============================================================================
#include <stdio.h>
#include <vector>
#include <cmath>
#include "chrono_parallel/physics/ChSystemParallel.h"
#include "chrono/ChConfig.h"
#include "chrono/utils/ChUtilsCreators.h"
#include "chrono/utils/ChUtilsInputOutput.h"
#include "chrono/utils/ChUtilsGeometry.h"
#include "chrono/utils/ChUtilsGenerators.h"
#ifdef CHRONO_OPENGL
#include "chrono_opengl/ChOpenGLWindow.h"
#endif
using namespace chrono;
using namespace chrono::collision;
// -----------------------------------------------------------------------------
// Create a bin consisting of five boxes attached to the ground and a mixer
// blade attached through a revolute joint to ground. The mixer is constrained
// to rotate at constant angular velocity.
// -----------------------------------------------------------------------------
void AddContainer(ChSystemParallelDVI* sys) {
// IDs for the two bodies
int binId = -200;
int mixerId = -201;
// Create a common material
ChSharedPtr<ChMaterialSurface> mat(new ChMaterialSurface);
mat->SetFriction(0.4f);
ChVector<> hdim(.55, .6, .55);
utils::CreateBoxContainer(sys, 0, mat, hdim, 0.05, Vector(0, 0, 0), QUNIT, true, false, true, true);
}
// -----------------------------------------------------------------------------
// Create the fluid in the shape of a sphere.
// -----------------------------------------------------------------------------
void AddFluid(ChSystemParallelDVI* sys) {
ChFluidContainer* fluid_container = new ChFluidContainer(sys);
real radius = .1; //*5
real dens = 30;
real3 num_fluid = real3(10, 10, 10);
real3 origin(0, 0, .2);
real vol;
std::vector<real3> pos_fluid;
std::vector<real3> vel_fluid;
double dist = sys->GetSettings()->fluid.kernel_radius * .9;
utils::HCPSampler<> sampler(dist);
vol = dist * dist * dist * .8;
#if 1
utils::Generator::PointVector points = sampler.SampleSphere(ChVector<>(0, 0, 0), radius);
// vol = 4.0 / 3.0 * CH_C_PI * pow(radius, 3) / real(points.size());
#else
ChVector<> hdim(.5, .5, .5);
utils::Generator::PointVector points = sampler.SampleBox(ChVector<>(0, 0, -hdim.z), hdim);
// vol = hdim.x * hdim.y * hdim.z / real(points.size());
#endif
pos_fluid.resize(points.size());
vel_fluid.resize(points.size());
for (int i = 0; i < points.size(); i++) {
pos_fluid[i] = real3(points[i].x, points[i].y, points[i].z) + origin;
vel_fluid[i] = real3(0, 0, 0);
}
sys->GetSettings()->fluid.mass = sys->GetSettings()->fluid.density * vol;
std::cout << "fluid_mass: " << sys->GetSettings()->fluid.mass << std::endl;
fluid_container->UpdatePosition(0);
fluid_container->AddFluid(pos_fluid, vel_fluid);
}
// -----------------------------------------------------------------------------
// Create the system, specify simulation parameters, and run simulation loop.
// -----------------------------------------------------------------------------
int main(int argc, char* argv[]) {
int threads = 8;
// Simulation parameters
// ---------------------
double gravity = 9.81;
double time_step = 1e-3;
double time_end = 1;
double out_fps = 50;
uint max_iteration = 30;
real tolerance = 1e-3;
// Create system
// -------------
ChSystemParallelDVI msystem;
// omp_set_num_threads(4);
// Set number of threads.
// int max_threads = 2;//CHOMPfunctions::GetNumProcs();
// if (threads > max_threads)
// threads = max_threads;
// msystem.SetParallelThreadNumber(threads);
// CHOMPfunctions::SetNumThreads(threads);
// Set gravitational acceleration
msystem.Set_G_acc(ChVector<>(0, 0, -gravity));
// Set solver parameters
msystem.GetSettings()->solver.solver_mode = SLIDING;
msystem.GetSettings()->solver.max_iteration_normal = 0;
msystem.GetSettings()->solver.max_iteration_sliding = 40;
msystem.GetSettings()->solver.max_iteration_spinning = 0;
msystem.GetSettings()->solver.max_iteration_bilateral = 0;
msystem.GetSettings()->solver.tolerance = tolerance;
msystem.GetSettings()->solver.alpha = 0;
msystem.GetSettings()->solver.use_full_inertia_tensor = false;
msystem.GetSettings()->collision.use_two_level = false;
msystem.GetSettings()->solver.contact_recovery_speed = 100000;
msystem.GetSettings()->solver.cache_step_length = true;
msystem.ChangeSolverType(BB);
msystem.GetSettings()->collision.narrowphase_algorithm = NARROWPHASE_HYBRID_MPR;
msystem.GetSettings()->fluid.tau = time_step * 4;
msystem.GetSettings()->fluid.cohesion = 0;
msystem.GetSettings()->fluid.epsilon = 0; // 1e-3;
msystem.GetSettings()->fluid.kernel_radius = .016;
msystem.GetSettings()->fluid.mass = .007 * 5.5;
msystem.GetSettings()->fluid.viscosity = 20;
msystem.GetSettings()->fluid.enable_viscosity = false;
msystem.GetSettings()->fluid.mu = .1;
msystem.GetSettings()->fluid.density = 1000;
msystem.GetSettings()->fluid.fluid_is_rigid = false;
msystem.GetSettings()->fluid.initialize_mass = false;
// msystem.GetSettings()->fluid.max_interactions = 30;
msystem.GetSettings()->fluid.artificial_pressure = true;
msystem.GetSettings()->fluid.artificial_pressure_k = .001;
msystem.GetSettings()->fluid.artificial_pressure_dq = 0; //.2 * system->GetSettings()->fluid.kernel_radius;
msystem.GetSettings()->fluid.artificial_pressure_n = 4;
msystem.GetSettings()->fluid.collision_envelope = msystem.GetSettings()->fluid.kernel_radius * .05;
msystem.GetSettings()->fluid.vorticity_confinement = 40;
msystem.GetSettings()->collision.collision_envelope = (msystem.GetSettings()->fluid.kernel_radius * .05);
msystem.GetSettings()->collision.bins_per_axis = int3(2, 2, 2);
msystem.SetLoggingLevel(LOG_TRACE, true);
msystem.SetLoggingLevel(LOG_INFO, true);
// Create the fixed and moving bodies
// ----------------------------------
AddContainer(&msystem);
AddFluid(&msystem);
// Perform the simulation
// ----------------------
#ifdef CHRONO_OPENGL
opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
gl_window.Initialize(1280, 720, "fluidDVI", &msystem);
gl_window.SetCamera(ChVector<>(0, -2, 0), ChVector<>(0, 0, 0), ChVector<>(0, 0, 1), .2);
gl_window.Pause();
// Uncomment the following two lines for the OpenGL manager to automatically
// run the simulation in an infinite loop.
// gl_window.StartDrawLoop(time_step);
// return 0;
while (true) {
if (gl_window.Active()) {
gl_window.DoStepDynamics(time_step);
gl_window.Render();
} else {
break;
}
}
#else
// Run simulation for specified time
int num_steps = std::ceil(time_end / time_step);
double time = 0;
for (int i = 0; i < num_steps; i++) {
msystem.DoStepDynamics(time_step);
time += time_step;
}
#endif
return 0;
}
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#ifdef HAVE_WEBP
#include "precomp.hpp"
#include <webp/decode.h>
#include <webp/encode.h>
#include <stdio.h>
#include <limits.h>
#include "grfmt_webp.hpp"
#include "opencv2/imgproc.hpp"
const size_t WEBP_HEADER_SIZE = 32;
namespace cv
{
WebPDecoder::WebPDecoder()
{
m_buf_supported = true;
}
WebPDecoder::~WebPDecoder() {}
size_t WebPDecoder::signatureLength() const
{
return WEBP_HEADER_SIZE;
}
bool WebPDecoder::checkSignature(const String & signature) const
{
bool ret = false;
if(signature.size() >= WEBP_HEADER_SIZE)
{
WebPBitstreamFeatures features;
if(VP8_STATUS_OK == WebPGetFeatures((uint8_t *)signature.c_str(),
WEBP_HEADER_SIZE, &features))
{
ret = true;
}
}
return ret;
}
ImageDecoder WebPDecoder::newDecoder() const
{
return makePtr<WebPDecoder>();
}
bool WebPDecoder::readHeader()
{
if (m_buf.empty())
{
FILE * wfile = NULL;
wfile = fopen(m_filename.c_str(), "rb");
if(wfile == NULL)
{
return false;
}
fseek(wfile, 0, SEEK_END);
long int wfile_size = ftell(wfile);
fseek(wfile, 0, SEEK_SET);
if(wfile_size > static_cast<long int>(INT_MAX))
{
fclose(wfile);
return false;
}
data.create(1, (int)wfile_size, CV_8U);
size_t data_size = fread(data.ptr(), 1, wfile_size, wfile);
if(wfile)
{
fclose(wfile);
}
if(static_cast<long int>(data_size) != wfile_size)
{
return false;
}
}
else
{
data = m_buf;
}
WebPBitstreamFeatures features;
if(VP8_STATUS_OK == WebPGetFeatures(data.ptr(), WEBP_HEADER_SIZE, &features))
{
m_width = features.width;
m_height = features.height;
if (features.has_alpha)
{
m_type = CV_8UC4;
channels = 4;
}
else
{
m_type = CV_8UC3;
channels = 3;
}
return true;
}
return false;
}
bool WebPDecoder::readData(Mat &img)
{
if( m_width > 0 && m_height > 0 )
{
if (img.cols != m_width || img.rows != m_height || img.type() != m_type)
{
img.create(m_height, m_width, m_type);
}
uchar* out_data = img.ptr();
size_t out_data_size = img.cols * img.rows * img.elemSize();
uchar *res_ptr = 0;
if (channels == 3)
{
res_ptr = WebPDecodeBGRInto(data.ptr(), data.total(), out_data,
(int)out_data_size, (int)img.step);
}
else if (channels == 4)
{
res_ptr = WebPDecodeBGRAInto(data.ptr(), data.total(), out_data,
(int)out_data_size, (int)img.step);
}
if(res_ptr == out_data)
{
return true;
}
}
return false;
}
WebPEncoder::WebPEncoder()
{
m_description = "WebP files (*.webp)";
m_buf_supported = true;
}
WebPEncoder::~WebPEncoder() { }
ImageEncoder WebPEncoder::newEncoder() const
{
return makePtr<WebPEncoder>();
}
bool WebPEncoder::write(const Mat& img, const std::vector<int>& params)
{
int channels = img.channels(), depth = img.depth();
int width = img.cols, height = img.rows;
const Mat *image = &img;
Mat temp;
size_t size = 0;
bool comp_lossless = true;
float quality = 100.0f;
if (params.size() > 1)
{
if (params[0] == CV_IMWRITE_WEBP_QUALITY)
{
comp_lossless = false;
quality = static_cast<float>(params[1]);
if (quality < 1.0f)
{
quality = 1.0f;
}
if (quality > 100.0f)
{
comp_lossless = true;
}
}
}
uint8_t *out = NULL;
if(depth != CV_8U)
{
return false;
}
if(channels == 1)
{
cvtColor(*image, temp, CV_GRAY2BGR);
image = &temp;
channels = 3;
}
else if (channels == 2)
{
return false;
}
if (comp_lossless)
{
if(channels == 3)
{
size = WebPEncodeLosslessBGR(image->ptr(), width, height, (int)image->step, &out);
}
else if(channels == 4)
{
size = WebPEncodeLosslessBGRA(image->ptr(), width, height, (int)image->step, &out);
}
}
else
{
if(channels == 3)
{
size = WebPEncodeBGR(image->ptr(), width, height, (int)image->step, quality, &out);
}
else if(channels == 4)
{
size = WebPEncodeBGRA(image->ptr(), width, height, (int)image->step, quality, &out);
}
}
if(size > 0)
{
if(m_buf)
{
m_buf->resize(size);
memcpy(&(*m_buf)[0], out, size);
}
else
{
FILE *fd = fopen(m_filename.c_str(), "wb");
if(fd != NULL)
{
fwrite(out, size, sizeof(uint8_t), fd);
fclose(fd); fd = NULL;
}
}
}
if (out != NULL)
{
free(out);
out = NULL;
}
return size > 0;
}
}
#endif
<commit_msg>imgcodecs: fix webp IMREAD_GRAYSCALE loading<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#ifdef HAVE_WEBP
#include "precomp.hpp"
#include <webp/decode.h>
#include <webp/encode.h>
#include <stdio.h>
#include <limits.h>
#include "grfmt_webp.hpp"
#include "opencv2/imgproc.hpp"
const size_t WEBP_HEADER_SIZE = 32;
namespace cv
{
WebPDecoder::WebPDecoder()
{
m_buf_supported = true;
}
WebPDecoder::~WebPDecoder() {}
size_t WebPDecoder::signatureLength() const
{
return WEBP_HEADER_SIZE;
}
bool WebPDecoder::checkSignature(const String & signature) const
{
bool ret = false;
if(signature.size() >= WEBP_HEADER_SIZE)
{
WebPBitstreamFeatures features;
if(VP8_STATUS_OK == WebPGetFeatures((uint8_t *)signature.c_str(),
WEBP_HEADER_SIZE, &features))
{
ret = true;
}
}
return ret;
}
ImageDecoder WebPDecoder::newDecoder() const
{
return makePtr<WebPDecoder>();
}
bool WebPDecoder::readHeader()
{
if (m_buf.empty())
{
FILE * wfile = NULL;
wfile = fopen(m_filename.c_str(), "rb");
if(wfile == NULL)
{
return false;
}
fseek(wfile, 0, SEEK_END);
long int wfile_size = ftell(wfile);
fseek(wfile, 0, SEEK_SET);
if(wfile_size > static_cast<long int>(INT_MAX))
{
fclose(wfile);
return false;
}
data.create(1, (int)wfile_size, CV_8U);
size_t data_size = fread(data.ptr(), 1, wfile_size, wfile);
if(wfile)
{
fclose(wfile);
}
if(static_cast<long int>(data_size) != wfile_size)
{
return false;
}
}
else
{
data = m_buf;
}
WebPBitstreamFeatures features;
if(VP8_STATUS_OK == WebPGetFeatures(data.ptr(), WEBP_HEADER_SIZE, &features))
{
m_width = features.width;
m_height = features.height;
if (features.has_alpha)
{
m_type = CV_8UC4;
channels = 4;
}
else
{
m_type = CV_8UC3;
channels = 3;
}
return true;
}
return false;
}
bool WebPDecoder::readData(Mat &img)
{
if( m_width > 0 && m_height > 0 )
{
bool convert_grayscale = (img.type() == CV_8UC1); // IMREAD_GRAYSCALE requested
if (img.cols != m_width || img.rows != m_height || img.type() != m_type)
{
img.create(m_height, m_width, m_type);
}
uchar* out_data = img.ptr();
size_t out_data_size = img.cols * img.rows * img.elemSize();
uchar *res_ptr = 0;
if (channels == 3)
{
res_ptr = WebPDecodeBGRInto(data.ptr(), data.total(), out_data,
(int)out_data_size, (int)img.step);
}
else if (channels == 4)
{
res_ptr = WebPDecodeBGRAInto(data.ptr(), data.total(), out_data,
(int)out_data_size, (int)img.step);
}
if(res_ptr == out_data)
{
if (convert_grayscale)
{
cvtColor(img, img, COLOR_BGR2GRAY);
}
return true;
}
}
return false;
}
WebPEncoder::WebPEncoder()
{
m_description = "WebP files (*.webp)";
m_buf_supported = true;
}
WebPEncoder::~WebPEncoder() { }
ImageEncoder WebPEncoder::newEncoder() const
{
return makePtr<WebPEncoder>();
}
bool WebPEncoder::write(const Mat& img, const std::vector<int>& params)
{
int channels = img.channels(), depth = img.depth();
int width = img.cols, height = img.rows;
const Mat *image = &img;
Mat temp;
size_t size = 0;
bool comp_lossless = true;
float quality = 100.0f;
if (params.size() > 1)
{
if (params[0] == CV_IMWRITE_WEBP_QUALITY)
{
comp_lossless = false;
quality = static_cast<float>(params[1]);
if (quality < 1.0f)
{
quality = 1.0f;
}
if (quality > 100.0f)
{
comp_lossless = true;
}
}
}
uint8_t *out = NULL;
if(depth != CV_8U)
{
return false;
}
if(channels == 1)
{
cvtColor(*image, temp, CV_GRAY2BGR);
image = &temp;
channels = 3;
}
else if (channels == 2)
{
return false;
}
if (comp_lossless)
{
if(channels == 3)
{
size = WebPEncodeLosslessBGR(image->ptr(), width, height, (int)image->step, &out);
}
else if(channels == 4)
{
size = WebPEncodeLosslessBGRA(image->ptr(), width, height, (int)image->step, &out);
}
}
else
{
if(channels == 3)
{
size = WebPEncodeBGR(image->ptr(), width, height, (int)image->step, quality, &out);
}
else if(channels == 4)
{
size = WebPEncodeBGRA(image->ptr(), width, height, (int)image->step, quality, &out);
}
}
if(size > 0)
{
if(m_buf)
{
m_buf->resize(size);
memcpy(&(*m_buf)[0], out, size);
}
else
{
FILE *fd = fopen(m_filename.c_str(), "wb");
if(fd != NULL)
{
fwrite(out, size, sizeof(uint8_t), fd);
fclose(fd); fd = NULL;
}
}
}
if (out != NULL)
{
free(out);
out = NULL;
}
return size > 0;
}
}
#endif
<|endoftext|> |
<commit_before>#include"../header/CTsaiAlgorithm.h"
#include<algorithm> //min_element, rotate, sort
#include<chrono> //for random
#include<cstddef> //size_t
#include<functional> //equal_to, hash
#include<iterator> //make_move_iterator
#include<random> //mt19937, uniform_int_distribution
#include<stdexcept> //logic_error
#include<vector>
#include"../../lib/header/algorithm/algorithm.h" //unique_without_sort
#include"../../lib/header/math/math.h" //Cantor_pairing_function
#include"../../lib/header/thread/CThread_unordered_map.h"
#include"../../lib/header/tool/Boolean.h"
#include"../header/TsaiAlgorithmFwd.h"
#include"../header/CData.h" //step4_algorithm
#include"../header/CPath.h"
#include"../header/path_algorithm.h" //path_algorithm
using namespace nQCircuit;
using namespace nTsaiAlgorithm;
using namespace std;
namespace
{
typedef vector<vector<Func_t::value_type>> Cycle_t;
typedef pair<Func_t::value_type,Func_t::value_type> PoolKey_t;
Split_t find_path(const Cycle_t &,size_t);
Split_t find_path_random(mt19937 &,const Cycle_t &,size_t);
void find_path_impl(const Cycle_t::value_type &,vec_const_vec_CQCircuit_ptr &,size_t);
void find_path_impl_random(mt19937 &,const Cycle_t::value_type &,vec_const_vec_CQCircuit_ptr &,size_t);
bool next_permutation(Cycle_t &);
size_t next_permutation_count(const Cycle_t &);
inline size_t next_permutation_count(const Split_t &split)
{
return nMath::factorial(split.size());
}
size_t route(size_t size); //when your bit is higher than 4, you have to modify this
Cycle_t step1_create_cycle(const Func_t &);
vec_CQCircuit step2_rotate_cycle(Cycle_t &,size_t);
vec_CQCircuit step2_rotate_cycle_random(mt19937 &,Cycle_t &,size_t);
vec_CQCircuit step3_permutate_cycle(Split_t &);
vec_CQCircuit step3_permutate_cycle_random(mt19937 &,Split_t &);
}
namespace std
{
template<>
struct equal_to<PoolKey_t>
{
inline bool operator()(const PoolKey_t &lhs,const PoolKey_t &rhs) const
{
return (lhs.first==rhs.first&&lhs.second==rhs.second)
||(lhs.first==rhs.second&&lhs.second==rhs.first);
}
};
template<>
struct hash<PoolKey_t>
{
inline size_t operator()(const PoolKey_t &val) const
{
return val.first<val.second?
nMath::Cantor_pairing_function(val.first,val.second):
nMath::Cantor_pairing_function(val.second,val.first);
}
};
}
namespace
{
Split_t find_path(const Cycle_t &cycle,const size_t bit)
{
Split_t gate(cycle.size()); //not {}
for(size_t i{0};i!=gate.size();++i)
{
gate[i].first=i; //for next_permutation in step3_permutate_cycle
find_path_impl(cycle[i],gate[i].second,bit);
}
return gate;
}
Split_t find_path_random(mt19937 &mt,const Cycle_t &cycle,const size_t bit)
{
Split_t gate(cycle.size()); //not {}
for(size_t i{0};i!=gate.size();++i)
{
gate[i].first=i; //for next_permutation in step3_permutate_cycle
find_path_impl_random(mt,cycle[i],gate[i].second,bit);
}
return gate;
}
void find_path_impl(const Cycle_t::value_type &cycle,vec_const_vec_CQCircuit_ptr &vec,const size_t bit)
{
static nThread::CThread_unordered_map<PoolKey_t,vec_CQCircuit> pool;
for(size_t i{cycle.size()-1};i;--i)
{
const PoolKey_t key{cycle[i],cycle[i-1]};
pool.try_emplace_func(key,[=,&cycle]{
const CPath<Func_t::value_type> path{cycle[i],cycle[i-1]};
const auto routeCount{route(path.size())};
vec_CQCircuit temp{path.size()*routeCount,vec_CQCircuit::value_type{bit}};
for(size_t j{0};j!=path.size();++j)
for(size_t k{0};k!=routeCount;++k)
temp[j*routeCount+k]=path_algorithm(path[j].begin(),path[j].end(),bit,k);
return temp;
});
vec.emplace_back(&pool.at(key));
}
}
void find_path_impl_random(mt19937 &mt,const Cycle_t::value_type &cycle,vec_const_vec_CQCircuit_ptr &vec,const size_t bit)
{
for(size_t i{cycle.size()-1};i;--i)
{
const CPath<Func_t::value_type> path{cycle[i],cycle[i-1]};
uniform_int_distribution<size_t> dist{0,path.size()*route(path.size())-1};
const size_t choice{dist(mt)};
vec.emplace_back(new vec_CQCircuit{1,path_algorithm(path[choice/path.size()].begin(),path[choice/path.size()].end(),bit,choice%path.size())});
}
}
bool next_permutation(Cycle_t &cycle)
{
for(auto &val:cycle)
if(2<val.size())
{
rotate(val.begin(),next(val.begin()),val.end());
if(min_element(val.begin(),val.end())!=val.begin())
return true;
}
return false;
}
size_t next_permutation_count(const Cycle_t &cycle)
{
size_t count{1};
for(auto &val:cycle)
if(2<val.size())
count*=val.size();
return count;
}
size_t route(const size_t size)
{
switch(size)
{
case 1: return 1;
case 2: return 2;
case 6: return 6;
case 24: return 20;
default: throw logic_error{"Cannot find route"};
}
}
Cycle_t step1_create_cycle(const Func_t &func)
{
Cycle_t cycle;
vector<nTool::Boolean> ready(func.size()); //not {}
for(size_t i{0};i!=ready.size();++i)
if(i!=func[i]&&!ready[i]) //i!=func[i], implicit conversion
{
cycle.emplace_back(); //push a empty object
for(auto j{i};!ready[j];ready[j]=true,j=func[j])
cycle.back().emplace_back(static_cast<Cycle_t::value_type::value_type>(j));
}
return cycle;
}
vec_CQCircuit step2_rotate_cycle(Cycle_t &cycle,const size_t bit)
{
vec_CQCircuit result;
do
{
auto temp{find_path(cycle,bit)};
move_insert(result,step3_permutate_cycle(temp));
}while(next_permutation(cycle));
erase_equal(result);
sort_by_size(result);
if(result.size())
erase_size_bigger_than_smallest_size_plus_1(result);
return result;
}
vec_CQCircuit step2_rotate_cycle_random(mt19937 &mt,Cycle_t &cycle,const size_t bit)
{
uniform_int_distribution<size_t> dist{0,next_permutation_count(cycle)-1};
for(size_t choice{dist(mt)};choice--;)
next_permutation(cycle);
Split_t split{find_path_random(mt,cycle,bit)};
const auto temp{step3_permutate_cycle(split)};
for(pair<size_t,vec_const_vec_CQCircuit_ptr> &val:split)
for(const vec_CQCircuit *val2:val.second)
delete val2;
return temp;
}
vec_CQCircuit step3_permutate_cycle(Split_t &split)
{
vec_CQCircuit result;
do
move_insert(result,step4_algorithm(split));
while(next_permutation(split.begin(),split.end(),[](const pair<size_t,vec_const_vec_CQCircuit_ptr> &lhs,const pair<size_t,vec_const_vec_CQCircuit_ptr> &rhs){return lhs.first<rhs.first;}));
erase_equal(result);
sort_by_size(result);
if(result.size())
erase_size_bigger_than_smallest_size_plus_1(result);
return result;
}
vec_CQCircuit step3_permutate_cycle_random(mt19937 &mt,Split_t &split)
{
uniform_int_distribution<size_t> dist{0,next_permutation_count(split)-1};
for(size_t choice{dist(mt)};choice--;)
next_permutation(split.begin(),split.end(),[](const pair<size_t,vec_const_vec_CQCircuit_ptr> &lhs,const pair<size_t,vec_const_vec_CQCircuit_ptr> &rhs){return lhs.first<rhs.first;});
return step4_algorithm(split);
}
}
namespace nTsaiAlgorithm
{
void sort_by_size(vec_CQCircuit &val)
{
sort(val.begin(),val.end(),[](const CQCircuit &lhs,const CQCircuit &rhs){return lhs.size()<rhs.size();});
}
void erase_equal(vec_CQCircuit &val)
{
val.erase(nAlgorithm::unique_without_sort(val.begin(),val.end()),val.end());
}
void erase_size_bigger_than_smallest_size_plus_1(vec_CQCircuit &val)
{
const auto size{val.front().size()+1};
val.erase(find_if(val.begin(),val.end(),[=](const CQCircuit &circuit){return size<circuit.size();}),val.end());
}
void move_insert(vec_CQCircuit &result,vec_CQCircuit &&rVal)
{
result.insert(result.end(),make_move_iterator(rVal.begin()),make_move_iterator(rVal.end()));
}
void CTsaiAlgorithm::create()
{
Cycle_t cycle{step1_create_cycle(getFunc())};
if(cycle.size())
result_=step2_rotate_cycle(cycle,nMath::log_2(getFunc().size())); //find_path_impl will use the second argument
}
void CRandom_TsaiAlgorithm::create()
{
Cycle_t cycle{step1_create_cycle(getFunc())};
mt19937 mt{static_cast<mt19937::result_type>(chrono::high_resolution_clock::now().time_since_epoch().count())};
if(cycle.size())
{
result_=step2_rotate_cycle_random(mt,cycle,nMath::log_2(getFunc().size())); //find_path_impl will use the second argument
erase_equal(result_);
sort_by_size(result_);
if(result_.size())
erase_size_bigger_than_smallest_size_plus_1(result_);
}
}
}<commit_msg>use nAlgorithm::for_each<commit_after>#include"../header/CTsaiAlgorithm.h"
#include<algorithm> //min_element, rotate, sort
#include<chrono> //for random
#include<cstddef> //size_t
#include<functional> //equal_to, hash
#include<iterator> //make_move_iterator
#include<random> //mt19937, uniform_int_distribution
#include<stdexcept> //logic_error
#include<vector>
#include"../../lib/header/algorithm/algorithm.h" //unique_without_sort
#include"../../lib/header/math/math.h" //Cantor_pairing_function
#include"../../lib/header/thread/CThread_unordered_map.h"
#include"../../lib/header/tool/Boolean.h"
#include"../header/TsaiAlgorithmFwd.h"
#include"../header/CData.h" //step4_algorithm
#include"../header/CPath.h"
#include"../header/path_algorithm.h" //path_algorithm
using namespace nQCircuit;
using namespace nTsaiAlgorithm;
using namespace std;
namespace
{
typedef vector<vector<Func_t::value_type>> Cycle_t;
typedef pair<Func_t::value_type,Func_t::value_type> PoolKey_t;
Split_t find_path(const Cycle_t &,size_t);
Split_t find_path_random(mt19937 &,const Cycle_t &,size_t);
void find_path_impl(const Cycle_t::value_type &,vec_const_vec_CQCircuit_ptr &,size_t);
void find_path_impl_random(mt19937 &,const Cycle_t::value_type &,vec_const_vec_CQCircuit_ptr &,size_t);
bool next_permutation(Cycle_t &);
size_t next_permutation_count(const Cycle_t &);
inline size_t next_permutation_count(const Split_t &split)
{
return nMath::factorial(split.size());
}
size_t route(size_t size); //when your bit is higher than 4, you have to modify this
Cycle_t step1_create_cycle(const Func_t &);
vec_CQCircuit step2_rotate_cycle(Cycle_t &,size_t);
vec_CQCircuit step2_rotate_cycle_random(mt19937 &,Cycle_t &,size_t);
vec_CQCircuit step3_permutate_cycle(Split_t &);
vec_CQCircuit step3_permutate_cycle_random(mt19937 &,Split_t &);
}
namespace std
{
template<>
struct equal_to<PoolKey_t>
{
inline bool operator()(const PoolKey_t &lhs,const PoolKey_t &rhs) const
{
return (lhs.first==rhs.first&&lhs.second==rhs.second)
||(lhs.first==rhs.second&&lhs.second==rhs.first);
}
};
template<>
struct hash<PoolKey_t>
{
inline size_t operator()(const PoolKey_t &val) const
{
return val.first<val.second?
nMath::Cantor_pairing_function(val.first,val.second):
nMath::Cantor_pairing_function(val.second,val.first);
}
};
}
namespace
{
Split_t find_path(const Cycle_t &cycle,const size_t bit)
{
Split_t gate(cycle.size()); //not {}
nAlgorithm::for_each<size_t>(0,gate.size(),[&](const auto i){
gate[i].first=i; //for next_permutation in step3_permutate_cycle
});
nAlgorithm::for_each<size_t>(0,gate.size(),[&,bit](const auto i){
find_path_impl(cycle[i],gate[i].second,bit);
});
return gate;
}
Split_t find_path_random(mt19937 &mt,const Cycle_t &cycle,const size_t bit)
{
Split_t gate(cycle.size()); //not {}
nAlgorithm::for_each<size_t>(0,gate.size(),[&](const auto i){
gate[i].first=i; //for next_permutation in step3_permutate_cycle
});
nAlgorithm::for_each<size_t>(0,gate.size(),[&,bit](const auto i){
find_path_impl_random(mt,cycle[i],gate[i].second,bit);
});
return gate;
}
void find_path_impl(const Cycle_t::value_type &cycle,vec_const_vec_CQCircuit_ptr &vec,const size_t bit)
{
static nThread::CThread_unordered_map<PoolKey_t,vec_CQCircuit> pool;
for(size_t i{cycle.size()-1};i;--i)
{
const PoolKey_t key{cycle[i],cycle[i-1]};
pool.try_emplace_func(key,[=,&cycle]{
const CPath<Func_t::value_type> path{cycle[i],cycle[i-1]};
const auto routeCount{route(path.size())};
vec_CQCircuit temp{path.size()*routeCount,vec_CQCircuit::value_type{bit}};
nAlgorithm::for_each<size_t>(0,path.size(),[=,&temp,&path](const auto j){
nAlgorithm::for_each<size_t>(0,routeCount,[=,&temp,&path](const auto k){
temp[j*routeCount+k]=path_algorithm(path[j].begin(),path[j].end(),bit,k);
});
});
return temp;
});
vec.emplace_back(&pool.at(key));
}
}
void find_path_impl_random(mt19937 &mt,const Cycle_t::value_type &cycle,vec_const_vec_CQCircuit_ptr &vec,const size_t bit)
{
for(size_t i{cycle.size()-1};i;--i)
{
const CPath<Func_t::value_type> path{cycle[i],cycle[i-1]};
uniform_int_distribution<size_t> dist{0,path.size()*route(path.size())-1};
const size_t choice{dist(mt)};
vec.emplace_back(new vec_CQCircuit{1,path_algorithm(path[choice/path.size()].begin(),path[choice/path.size()].end(),bit,choice%path.size())});
}
}
bool next_permutation(Cycle_t &cycle)
{
for(auto &val:cycle)
if(2<val.size())
{
rotate(val.begin(),next(val.begin()),val.end());
if(min_element(val.begin(),val.end())!=val.begin())
return true;
}
return false;
}
size_t next_permutation_count(const Cycle_t &cycle)
{
size_t count{1};
for(auto &val:cycle)
if(2<val.size())
count*=val.size();
return count;
}
size_t route(const size_t size)
{
switch(size)
{
case 1: return 1;
case 2: return 2;
case 6: return 6;
case 24: return 20;
default: throw logic_error{"Cannot find route"};
}
}
Cycle_t step1_create_cycle(const Func_t &func)
{
Cycle_t cycle;
vector<nTool::Boolean> ready(func.size()); //not {}
nAlgorithm::for_each<size_t>(0,ready.size(),[&](const auto i){
if(i!=func[i]&&!ready[i]) //i!=func[i], implicit conversion
{
cycle.emplace_back(); //push a empty object
for(auto j{i};!ready[j];ready[j]=true,j=func[j])
cycle.back().emplace_back(static_cast<Cycle_t::value_type::value_type>(j));
}
});
return cycle;
}
vec_CQCircuit step2_rotate_cycle(Cycle_t &cycle,const size_t bit)
{
vec_CQCircuit result;
do
{
auto temp{find_path(cycle,bit)};
move_insert(result,step3_permutate_cycle(temp));
}while(next_permutation(cycle));
erase_equal(result);
sort_by_size(result);
if(result.size())
erase_size_bigger_than_smallest_size_plus_1(result);
return result;
}
vec_CQCircuit step2_rotate_cycle_random(mt19937 &mt,Cycle_t &cycle,const size_t bit)
{
uniform_int_distribution<size_t> dist{0,next_permutation_count(cycle)-1};
for(size_t choice{dist(mt)};choice--;)
next_permutation(cycle);
Split_t split{find_path_random(mt,cycle,bit)};
const auto temp{step3_permutate_cycle(split)};
for(const pair<size_t,vec_const_vec_CQCircuit_ptr> &val:split)
for(const vec_CQCircuit *val2:val.second)
delete val2;
return temp;
}
vec_CQCircuit step3_permutate_cycle(Split_t &split)
{
vec_CQCircuit result;
do
move_insert(result,step4_algorithm(split));
while(next_permutation(split.begin(),split.end(),[](const pair<size_t,vec_const_vec_CQCircuit_ptr> &lhs,const pair<size_t,vec_const_vec_CQCircuit_ptr> &rhs){return lhs.first<rhs.first;}));
erase_equal(result);
sort_by_size(result);
if(result.size())
erase_size_bigger_than_smallest_size_plus_1(result);
return result;
}
vec_CQCircuit step3_permutate_cycle_random(mt19937 &mt,Split_t &split)
{
uniform_int_distribution<size_t> dist{0,next_permutation_count(split)-1};
for(size_t choice{dist(mt)};choice--;)
next_permutation(split.begin(),split.end(),[](const pair<size_t,vec_const_vec_CQCircuit_ptr> &lhs,const pair<size_t,vec_const_vec_CQCircuit_ptr> &rhs){return lhs.first<rhs.first;});
return step4_algorithm(split);
}
}
namespace nTsaiAlgorithm
{
void sort_by_size(vec_CQCircuit &val)
{
sort(val.begin(),val.end(),[](const CQCircuit &lhs,const CQCircuit &rhs){return lhs.size()<rhs.size();});
}
void erase_equal(vec_CQCircuit &val)
{
val.erase(nAlgorithm::unique_without_sort(val.begin(),val.end()),val.end());
}
void erase_size_bigger_than_smallest_size_plus_1(vec_CQCircuit &val)
{
const auto size{val.front().size()+1};
val.erase(find_if(val.begin(),val.end(),[=](const CQCircuit &circuit){return size<circuit.size();}),val.end());
}
void move_insert(vec_CQCircuit &result,vec_CQCircuit &&rVal)
{
result.insert(result.end(),make_move_iterator(rVal.begin()),make_move_iterator(rVal.end()));
}
void CTsaiAlgorithm::create()
{
Cycle_t cycle{step1_create_cycle(getFunc())};
if(cycle.size())
result_=step2_rotate_cycle(cycle,nMath::log_2(getFunc().size())); //find_path_impl will use the second argument
}
void CRandom_TsaiAlgorithm::create()
{
Cycle_t cycle{step1_create_cycle(getFunc())};
mt19937 mt{static_cast<mt19937::result_type>(chrono::high_resolution_clock::now().time_since_epoch().count())};
if(cycle.size())
{
result_=step2_rotate_cycle_random(mt,cycle,nMath::log_2(getFunc().size())); //find_path_impl will use the second argument
erase_equal(result_);
sort_by_size(result_);
if(result_.size())
erase_size_bigger_than_smallest_size_plus_1(result_);
}
}
}<|endoftext|> |
<commit_before><commit_msg>Planning: code cleaning<commit_after><|endoftext|> |
<commit_before>/**
* @file ClusterRefiner.cpp
* @brief cluster refiner interface implementation
*/
//external headers
// uncomment if the prints are needed #include <iostream>
//local headers
#include "../include/ClusterRefiner.hpp"
namespace clusterer
{
namespace backend
{
void ClusterRefiner::printSol(const ClusterEncoding& clusterSol){
/*
for(unsigned int i = 0; i < clusterSol.size(); i++){
std::cout<<clusterSol.getClusterOfVertex(i)<<" ";
}
std::cout<<"\n";
*/
}
ClusterRefiner::ClusterRefiner(std::mt19937 *rand_gen, double prob)
: gen(rand_gen), bd(prob)
{
this->after_density = 0.0;
this->original_density = 0.0;
}
void ClusterRefiner::refine(ClusterEncoding& clusterSol, const AbstractGraph& graph)
{
// initialize clusters_density vector and populate with the
// computed values in computeClustersDensity function
uint32_t cluster_number = clusterSol.size();
clusters_density = std::vector<double>(cluster_number,0.0);
computeClustersDensity(clusterSol,graph);
std::vector<int> cluster_list_freq(clusterSol.size(),0);
// build frequency list of cluster ids needed for a check down below
for(unsigned int i = 0; i < clusterSol.size(); i++){
cluster_list_freq[clusterSol.getClusterOfVertex(i)]++;
}
double max_cluster_den = clusters_density[0];
ClusterId max_cluster_id = 0;
double min_cluster_den = RAND_MAX;
ClusterId min_cluster_id = 0;
for(unsigned int i = 0; i < clusters_density.size(); i++){
if(cluster_list_freq[i] != 0){
// check if needed the computed density values for the clusters
// std::cout<<i<<": "<<"--> "<<clusters_density[i]<<"\n";
if(clusters_density[i] >= max_cluster_den){
max_cluster_den = clusters_density[i];
max_cluster_id = i;
}
if(clusters_density[i] <= min_cluster_den){
min_cluster_den = clusters_density[i];
min_cluster_id = i;
}
}
}
// pick which cluster to refine using bernoulli distribution
// p -- probability to refine max_cluster_id
// (1-p) -- probability to refine min_cluster_id
ClusterId cluster_to_refine;
if(bd((*gen))) cluster_to_refine = max_cluster_id;
else cluster_to_refine = min_cluster_id;
// create the 2 new possible encodings
// option1: if an edge is in between clusters the node from the
// cluster to be refined is placed in the other cluster
// option2: if an edge is in between clusters the node from the
// the other cluster is placed in the to be refined cluster
IntegerVectorEncoding option1(&graph);
IntegerVectorEncoding option2(&graph);
// make option1, option2 copies of the original solution
for(unsigned int i = 0; i < clusterSol.size(); i++){
ClusterId temp = clusterSol.getClusterOfVertex(i);
option1.addToCluster(i,temp);
option2.addToCluster(i,temp);
}
printSol(option1);
for(auto& e: graph.getEdgesAndWeights()){
ClusterId startNodeCluster = clusterSol.getClusterOfVertex(e.first.first);
ClusterId endNodeCluster = clusterSol.getClusterOfVertex(e.first.second);
if(startNodeCluster == cluster_to_refine
&& endNodeCluster != cluster_to_refine){
option1.addToCluster(e.first.first,endNodeCluster);
option2.addToCluster(e.first.second,startNodeCluster);
}
}
// finding the intra-cluster density corresponding to the new cluster
// for the 2 new options and store the original's density
double option1_den = getClusterDensity(cluster_to_refine,option1,graph);
double option2_den = getClusterDensity(cluster_to_refine,option2,graph);
this->original_density = clusters_density[cluster_to_refine];
this->after_density = this->original_density;
/* in case future debugging is needed this would be helpful
std::cout<<"original: "; printSol(clusterSol);
std::cout<<cluster_to_refine<<": density -- "<<original<<"\n";
std::cout<<"option1: "; printSol(option1);
std::cout<<cluster_to_refine<<": density -- "<<option1_den<<"\n";
std::cout<<"option2: "; printSol(option2);
std::cout<<cluster_to_refine<<": density -- "<<option2_den<<"\n";
*/
// update the original version considering the bigger intra-cluster
// density for the refined chosen cluster
// or it can stay the same if better improvements are not made
if(std::max(std::max(option1_den,option2_den),this->original_density) == option1_den)
{
this->after_density = option1_den;
for(unsigned int i = 0; i < clusterSol.size();i++){
ClusterId c = option1.getClusterOfVertex(i);
if(c != clusterSol.getClusterOfVertex(i))
clusterSol.addToCluster(i,c);
}
} else if (std::max(std::max(option1_den,option2_den),this->original_density) == option2_den)
{
this->after_density = option2_den;
for(unsigned int i = 0; i < clusterSol.size();i++){
ClusterId c = option2.getClusterOfVertex(i);
if(c != clusterSol.getClusterOfVertex(i))
clusterSol.addToCluster(i,c);
}
}
}
void ClusterRefiner::computeClustersDensity(ClusterEncoding& clusterSol,
const AbstractGraph& graph)
{
// compute the total intra weight of each cluster and store it
// properly into clusters_density[respective_cluster]
for (auto& e : graph.getEdgesAndWeights()){
ClusterId startNodeCluster = clusterSol.getClusterOfVertex(e.first.first);
ClusterId endNodeCluster = clusterSol.getClusterOfVertex(e.first.second);
// the if basically checks if edge e is in a cluster
if(startNodeCluster == endNodeCluster){
clusters_density[startNodeCluster] += e.second;
}
}
// for each cluster Id find out the number of vertices in the cluster
// if cluster Id has no vertices it's density will stay 0.0
for (unsigned int i = 0; i < clusters_density.size(); i++){
double no_of_vertices = clusterSol.getVerticesInCluster(i).size();
if(no_of_vertices != 0)
clusters_density[i] = clusters_density[i]/(no_of_vertices*no_of_vertices);
}
}
double ClusterRefiner::getClusterDensity(ClusterId cid, ClusterEncoding& clusterSol,
const AbstractGraph& graph)
{
double no_vertices = clusterSol.getVerticesInCluster(cid).size();
// the cluster cid was basically replaced by another clusterId
// this can happen
// no point in carrying on and compute its density
if(no_vertices == 0) return 0;
double weight = 0.0;
for (auto& e : graph.getEdgesAndWeights()){
ClusterId startNodeCluster = clusterSol.getClusterOfVertex(e.first.first);
ClusterId endNodeCluster = clusterSol.getClusterOfVertex(e.first.second);
// the if basically checks if edge e is in cluster cid
if(startNodeCluster == endNodeCluster && startNodeCluster == cid){
weight += e.second;
}
}
return weight/(no_vertices*no_vertices);
}
// again these are useful for the testing units, not part of the algorithm itself
double ClusterRefiner::getOriginalClusterRefineDensity(){
return this->original_density;
}
double ClusterRefiner::getAfterClusterRefineDensity(){
return this->after_density;
}
ClusterRefiner::~ClusterRefiner()
{
//dtor
}
}
}<commit_msg>Added missing normalize call.<commit_after>/**
* @file ClusterRefiner.cpp
* @brief cluster refiner interface implementation
*/
//external headers
// uncomment if the prints are needed #include <iostream>
//local headers
#include "../include/ClusterRefiner.hpp"
namespace clusterer
{
namespace backend
{
void ClusterRefiner::printSol(const ClusterEncoding& clusterSol)
{
/*
for(unsigned int i = 0; i < clusterSol.size(); i++){
std::cout<<clusterSol.getClusterOfVertex(i)<<" ";
}
std::cout<<"\n";
*/
}
ClusterRefiner::ClusterRefiner(std::mt19937* rand_gen, double prob)
: gen(rand_gen), bd(prob)
{
this->after_density = 0.0;
this->original_density = 0.0;
}
void ClusterRefiner::refine(ClusterEncoding& clusterSol, const AbstractGraph& graph)
{
// initialize clusters_density vector and populate with the
// computed values in computeClustersDensity function
uint32_t cluster_number = clusterSol.size();
clusters_density = std::vector<double>(cluster_number,0.0);
computeClustersDensity(clusterSol,graph);
std::vector<int> cluster_list_freq(clusterSol.size(),0);
// build frequency list of cluster ids needed for a check down below
for (unsigned int i = 0; i < clusterSol.size(); i++)
{
cluster_list_freq[clusterSol.getClusterOfVertex(i)]++;
}
double max_cluster_den = clusters_density[0];
ClusterId max_cluster_id = 0;
double min_cluster_den = RAND_MAX;
ClusterId min_cluster_id = 0;
for (unsigned int i = 0; i < clusters_density.size(); i++)
{
if (cluster_list_freq[i] != 0)
{
// check if needed the computed density values for the clusters
// std::cout<<i<<": "<<"--> "<<clusters_density[i]<<"\n";
if (clusters_density[i] >= max_cluster_den)
{
max_cluster_den = clusters_density[i];
max_cluster_id = i;
}
if (clusters_density[i] <= min_cluster_den)
{
min_cluster_den = clusters_density[i];
min_cluster_id = i;
}
}
}
// pick which cluster to refine using bernoulli distribution
// p -- probability to refine max_cluster_id
// (1-p) -- probability to refine min_cluster_id
ClusterId cluster_to_refine;
if (bd((*gen))) { cluster_to_refine = max_cluster_id; }
else { cluster_to_refine = min_cluster_id; }
// create the 2 new possible encodings
// option1: if an edge is in between clusters the node from the
// cluster to be refined is placed in the other cluster
// option2: if an edge is in between clusters the node from the
// the other cluster is placed in the to be refined cluster
IntegerVectorEncoding option1(&graph);
IntegerVectorEncoding option2(&graph);
// make option1, option2 copies of the original solution
for (unsigned int i = 0; i < clusterSol.size(); i++)
{
ClusterId temp = clusterSol.getClusterOfVertex(i);
option1.addToCluster(i,temp);
option2.addToCluster(i,temp);
}
printSol(option1);
for (auto& e: graph.getEdgesAndWeights())
{
ClusterId startNodeCluster = clusterSol.getClusterOfVertex(e.first.first);
ClusterId endNodeCluster = clusterSol.getClusterOfVertex(e.first.second);
if (startNodeCluster == cluster_to_refine
&& endNodeCluster != cluster_to_refine)
{
option1.addToCluster(e.first.first,endNodeCluster);
option2.addToCluster(e.first.second,startNodeCluster);
}
}
// finding the intra-cluster density corresponding to the new cluster
// for the 2 new options and store the original's density
double option1_den = getClusterDensity(cluster_to_refine,option1,graph);
double option2_den = getClusterDensity(cluster_to_refine,option2,graph);
this->original_density = clusters_density[cluster_to_refine];
this->after_density = this->original_density;
/* in case future debugging is needed this would be helpful
std::cout<<"original: "; printSol(clusterSol);
std::cout<<cluster_to_refine<<": density -- "<<original<<"\n";
std::cout<<"option1: "; printSol(option1);
std::cout<<cluster_to_refine<<": density -- "<<option1_den<<"\n";
std::cout<<"option2: "; printSol(option2);
std::cout<<cluster_to_refine<<": density -- "<<option2_den<<"\n";
*/
// update the original version considering the bigger intra-cluster
// density for the refined chosen cluster
// or it can stay the same if better improvements are not made
if (std::max(std::max(option1_den,option2_den),this->original_density) == option1_den)
{
this->after_density = option1_den;
for (unsigned int i = 0; i < clusterSol.size(); i++)
{
ClusterId c = option1.getClusterOfVertex(i);
if (c != clusterSol.getClusterOfVertex(i))
{ clusterSol.addToCluster(i,c); }
}
}
else if (std::max(std::max(option1_den,option2_den),this->original_density) == option2_den)
{
this->after_density = option2_den;
for (unsigned int i = 0; i < clusterSol.size(); i++)
{
ClusterId c = option2.getClusterOfVertex(i);
if (c != clusterSol.getClusterOfVertex(i))
{ clusterSol.addToCluster(i,c); }
}
}
clusterSol.normalize();
}
void ClusterRefiner::computeClustersDensity(ClusterEncoding& clusterSol,
const AbstractGraph& graph)
{
// compute the total intra weight of each cluster and store it
// properly into clusters_density[respective_cluster]
for (auto& e : graph.getEdgesAndWeights())
{
ClusterId startNodeCluster = clusterSol.getClusterOfVertex(e.first.first);
ClusterId endNodeCluster = clusterSol.getClusterOfVertex(e.first.second);
// the if basically checks if edge e is in a cluster
if (startNodeCluster == endNodeCluster)
{
clusters_density[startNodeCluster] += e.second;
}
}
// for each cluster Id find out the number of vertices in the cluster
// if cluster Id has no vertices it's density will stay 0.0
for (unsigned int i = 0; i < clusters_density.size(); i++)
{
double no_of_vertices = clusterSol.getVerticesInCluster(i).size();
if (no_of_vertices != 0)
{ clusters_density[i] = clusters_density[i]/(no_of_vertices*no_of_vertices); }
}
}
double ClusterRefiner::getClusterDensity(ClusterId cid, ClusterEncoding& clusterSol,
const AbstractGraph& graph)
{
double no_vertices = clusterSol.getVerticesInCluster(cid).size();
// the cluster cid was basically replaced by another clusterId
// this can happen
// no point in carrying on and compute its density
if (no_vertices == 0) { return 0; }
double weight = 0.0;
for (auto& e : graph.getEdgesAndWeights())
{
ClusterId startNodeCluster = clusterSol.getClusterOfVertex(e.first.first);
ClusterId endNodeCluster = clusterSol.getClusterOfVertex(e.first.second);
// the if basically checks if edge e is in cluster cid
if (startNodeCluster == endNodeCluster && startNodeCluster == cid)
{
weight += e.second;
}
}
return weight/(no_vertices*no_vertices);
}
// again these are useful for the testing units, not part of the algorithm itself
double ClusterRefiner::getOriginalClusterRefineDensity()
{
return this->original_density;
}
double ClusterRefiner::getAfterClusterRefineDensity()
{
return this->after_density;
}
ClusterRefiner::~ClusterRefiner()
{
//dtor
}
}
}<|endoftext|> |
<commit_before>/***********************************************************************
filename: SamplesBrowserManager.cpp
created: 11/6/2012
author: Lukas E Meindl
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "SamplesBrowserManager.h"
#include "SamplesFramework.h"
#include "CEGUI/Window.h"
#include "CEGUI/SchemeManager.h"
#include "CEGUI/WindowManager.h"
#include "CEGUI/EventArgs.h"
#include "CEGUI/widgets/VerticalLayoutContainer.h"
#include "CEGUI/widgets/FrameWindow.h"
#include "CEGUI/Image.h"
using namespace CEGUI;
const CEGUI::uint32 SamplesBrowserManager::d_sampleWindowFrameNormal(0xFFFFFFFF);
const CEGUI::uint32 SamplesBrowserManager::d_sampleWindowFrameSelected(0xFF77FFB6);
SamplesBrowserManager::SamplesBrowserManager(SamplesFramework* owner, CEGUI::Window* samplesWindow)
: d_owner(owner),
d_root(samplesWindow),
d_childCount(0),
d_aspectRatio(1.f),
d_selectedWindow(0)
{
init();
}
CEGUI::Window* SamplesBrowserManager::getWindow()
{
return d_root;
}
CEGUI::FrameWindow* SamplesBrowserManager::createAndAddSampleWindow(const CEGUI::String& name, const CEGUI::Image& image)
{
WindowManager& winMgr = WindowManager::getSingleton();
CEGUI::VerticalLayoutContainer* root = static_cast<VerticalLayoutContainer*>(winMgr.createWindow("VerticalLayoutContainer"));
root->setMaxSize(CEGUI::USize(cegui_absdim(9999999999.f), cegui_absdim(9999999999.f)));
CEGUI::Window* windowName = winMgr.createWindow("SampleBrowserSkin/StaticText");
windowName->setSize(CEGUI::USize(cegui_absdim(260.f), cegui_absdim(40.f)));
windowName->setText(name);
windowName->setHorizontalAlignment(HorizontalAlignment::HA_CENTRE);
root->addChild(windowName);
FrameWindow* sampleWindow;
sampleWindow = static_cast<FrameWindow*>(winMgr.createWindow("SampleBrowserSkin/SampleWindow", name));
CEGUI::String imageName = image.getName();
sampleWindow->setProperty("Image", imageName);
sampleWindow->setSize(USize(UDim(1.f, -10.f), cegui_absdim(1.f)));
sampleWindow->setMouseInputPropagationEnabled(true);
sampleWindow->subscribeEvent(Window::EventMouseClick, Event::Subscriber(&SamplesBrowserManager::handleMouseClickSampleWindow, this));
sampleWindow->subscribeEvent(Window::EventMouseDoubleClick, Event::Subscriber(&SamplesBrowserManager::handleMouseDoubleClickSampleWindow, this));
CEGUI::ColourRect colRect((CEGUI::Colour(d_sampleWindowFrameNormal)));
sampleWindow->setProperty("FrameColours", CEGUI::PropertyHelper<ColourRect>::toString(colRect));
sampleWindow->setAspectMode(AM_EXPAND);
root->addChild(sampleWindow);
d_sampleWindows.push_back(sampleWindow);
d_verticalLayoutContainerSamples->addChild(root);
++d_childCount;
return sampleWindow;
}
void SamplesBrowserManager::setWindowRatio(float aspectRatio)
{
d_aspectRatio = aspectRatio;
updateWindows();
}
void SamplesBrowserManager::updateWindows()
{
float vertOffset = 0.f;
int max = d_sampleWindows.size();
for(int i = 0; i < max; ++i)
{
CEGUI::Window* window(d_sampleWindows[i]);
window->setAspectRatio(d_aspectRatio);
window->setSize(USize(UDim(1.f, -10.f), cegui_absdim(1.f)));
}
d_root->setSize(USize(cegui_reldim(1.f), cegui_reldim(1.f)));
}
bool SamplesBrowserManager::handleMouseClickSampleWindow(const CEGUI::EventArgs& args)
{
const WindowEventArgs& winArgs(static_cast<const WindowEventArgs&>(args));
CEGUI::Window* wnd(winArgs.window);
selectSampleWindow(wnd);
d_owner->handleSampleSelection(wnd);
return true;
}
bool SamplesBrowserManager::handleMouseDoubleClickSampleWindow(const CEGUI::EventArgs& args)
{
const WindowEventArgs& winArgs(static_cast<const WindowEventArgs&>(args));
CEGUI::Window* wnd(winArgs.window);
d_owner->handleStartDisplaySample(wnd);
return true;
}
void SamplesBrowserManager::selectSampleWindow(CEGUI::Window* wnd)
{
if(d_selectedWindow)
{
CEGUI::ColourRect colRectNormal = CEGUI::ColourRect(CEGUI::Colour(d_sampleWindowFrameNormal));
d_selectedWindow->setProperty("FrameColours", CEGUI::PropertyHelper<ColourRect>::toString(colRectNormal));
}
d_selectedWindow = wnd;
CEGUI::ColourRect colRectSelected = CEGUI::ColourRect(CEGUI::Colour(d_sampleWindowFrameSelected));
d_selectedWindow->setProperty("FrameColours", CEGUI::PropertyHelper<ColourRect>::toString(colRectSelected));
}
void SamplesBrowserManager::init()
{
WindowManager& winMgr = WindowManager::getSingleton();
d_verticalLayoutContainerSamples = static_cast<VerticalLayoutContainer*>(winMgr.createWindow("VerticalLayoutContainer"));
d_verticalLayoutContainerSamples->setSize(CEGUI::USize(cegui_reldim(1.f), cegui_reldim(1.f)));
d_verticalLayoutContainerSamples->setMaxSize(CEGUI::USize(cegui_absdim(9999999999.f), cegui_absdim(9999999999.f)));
d_verticalLayoutContainerSamples->setMouseInputPropagationEnabled(true);
d_root->addChild(d_verticalLayoutContainerSamples);
}<commit_msg>MOD: Fix for window alignment<commit_after>/***********************************************************************
filename: SamplesBrowserManager.cpp
created: 11/6/2012
author: Lukas E Meindl
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "SamplesBrowserManager.h"
#include "SamplesFramework.h"
#include "CEGUI/Window.h"
#include "CEGUI/SchemeManager.h"
#include "CEGUI/WindowManager.h"
#include "CEGUI/EventArgs.h"
#include "CEGUI/widgets/VerticalLayoutContainer.h"
#include "CEGUI/widgets/FrameWindow.h"
#include "CEGUI/Image.h"
using namespace CEGUI;
const CEGUI::uint32 SamplesBrowserManager::d_sampleWindowFrameNormal(0xFFFFFFFF);
const CEGUI::uint32 SamplesBrowserManager::d_sampleWindowFrameSelected(0xFF77FFB6);
SamplesBrowserManager::SamplesBrowserManager(SamplesFramework* owner, CEGUI::Window* samplesWindow)
: d_owner(owner),
d_root(samplesWindow),
d_childCount(0),
d_aspectRatio(1.f),
d_selectedWindow(0)
{
init();
}
CEGUI::Window* SamplesBrowserManager::getWindow()
{
return d_root;
}
CEGUI::FrameWindow* SamplesBrowserManager::createAndAddSampleWindow(const CEGUI::String& name, const CEGUI::Image& image)
{
WindowManager& winMgr = WindowManager::getSingleton();
CEGUI::VerticalLayoutContainer* root = static_cast<VerticalLayoutContainer*>(winMgr.createWindow("VerticalLayoutContainer"));
root->setMaxSize(CEGUI::USize(cegui_absdim(9999999999.f), cegui_absdim(9999999999.f)));
CEGUI::Window* windowName = winMgr.createWindow("SampleBrowserSkin/StaticText");
windowName->setSize(CEGUI::USize(cegui_absdim(260.f), cegui_absdim(40.f)));
windowName->setText(name);
windowName->setHorizontalAlignment(HA_CENTRE);
root->addChild(windowName);
FrameWindow* sampleWindow;
sampleWindow = static_cast<FrameWindow*>(winMgr.createWindow("SampleBrowserSkin/SampleWindow", name));
CEGUI::String imageName = image.getName();
sampleWindow->setProperty("Image", imageName);
sampleWindow->setSize(USize(UDim(1.f, -10.f), cegui_absdim(1.f)));
sampleWindow->setMouseInputPropagationEnabled(true);
sampleWindow->subscribeEvent(Window::EventMouseClick, Event::Subscriber(&SamplesBrowserManager::handleMouseClickSampleWindow, this));
sampleWindow->subscribeEvent(Window::EventMouseDoubleClick, Event::Subscriber(&SamplesBrowserManager::handleMouseDoubleClickSampleWindow, this));
CEGUI::ColourRect colRect((CEGUI::Colour(d_sampleWindowFrameNormal)));
sampleWindow->setProperty("FrameColours", CEGUI::PropertyHelper<ColourRect>::toString(colRect));
sampleWindow->setAspectMode(AM_EXPAND);
root->addChild(sampleWindow);
d_sampleWindows.push_back(sampleWindow);
d_verticalLayoutContainerSamples->addChild(root);
++d_childCount;
return sampleWindow;
}
void SamplesBrowserManager::setWindowRatio(float aspectRatio)
{
d_aspectRatio = aspectRatio;
updateWindows();
}
void SamplesBrowserManager::updateWindows()
{
float vertOffset = 0.f;
int max = d_sampleWindows.size();
for(int i = 0; i < max; ++i)
{
CEGUI::Window* window(d_sampleWindows[i]);
window->setAspectRatio(d_aspectRatio);
window->setSize(USize(UDim(1.f, -10.f), cegui_absdim(1.f)));
}
d_root->setSize(USize(cegui_reldim(1.f), cegui_reldim(1.f)));
}
bool SamplesBrowserManager::handleMouseClickSampleWindow(const CEGUI::EventArgs& args)
{
const WindowEventArgs& winArgs(static_cast<const WindowEventArgs&>(args));
CEGUI::Window* wnd(winArgs.window);
selectSampleWindow(wnd);
d_owner->handleSampleSelection(wnd);
return true;
}
bool SamplesBrowserManager::handleMouseDoubleClickSampleWindow(const CEGUI::EventArgs& args)
{
const WindowEventArgs& winArgs(static_cast<const WindowEventArgs&>(args));
CEGUI::Window* wnd(winArgs.window);
d_owner->handleStartDisplaySample(wnd);
return true;
}
void SamplesBrowserManager::selectSampleWindow(CEGUI::Window* wnd)
{
if(d_selectedWindow)
{
CEGUI::ColourRect colRectNormal = CEGUI::ColourRect(CEGUI::Colour(d_sampleWindowFrameNormal));
d_selectedWindow->setProperty("FrameColours", CEGUI::PropertyHelper<ColourRect>::toString(colRectNormal));
}
d_selectedWindow = wnd;
CEGUI::ColourRect colRectSelected = CEGUI::ColourRect(CEGUI::Colour(d_sampleWindowFrameSelected));
d_selectedWindow->setProperty("FrameColours", CEGUI::PropertyHelper<ColourRect>::toString(colRectSelected));
}
void SamplesBrowserManager::init()
{
WindowManager& winMgr = WindowManager::getSingleton();
d_verticalLayoutContainerSamples = static_cast<VerticalLayoutContainer*>(winMgr.createWindow("VerticalLayoutContainer"));
d_verticalLayoutContainerSamples->setSize(CEGUI::USize(cegui_reldim(1.f), cegui_reldim(1.f)));
d_verticalLayoutContainerSamples->setMaxSize(CEGUI::USize(cegui_absdim(9999999999.f), cegui_absdim(9999999999.f)));
d_verticalLayoutContainerSamples->setMouseInputPropagationEnabled(true);
d_root->addChild(d_verticalLayoutContainerSamples);
}<|endoftext|> |
<commit_before>#include "shaderlab/WxPreviewCanvas.h"
#include "shaderlab/MessageID.h"
#include "shaderlab/WxGraphPage.h"
#include "shaderlab/ImageViewer.h"
#include "shaderlab/HeightViewer.h"
#include "shaderlab/ModelViewer.h"
#include "shaderlab/Node.h"
#include <ee0/WxStagePage.h>
#include <ee0/SubjectMgr.h>
#include <blueprint/Node.h>
#include <unirender/Device.h>
#include <unirender/ShaderProgram.h>
#include <shadertrans/ShaderTrans.h>
#include <painting0/ModelMatUpdater.h>
#include <painting3/ViewMatUpdater.h>
#include <painting3/ProjectMatUpdater.h>
#include <shadergraph/block/FragmentShader.h>
namespace shaderlab
{
WxPreviewCanvas::WxPreviewCanvas(const ur::Device& dev, ee0::WxStagePage* stage,
ECS_WORLD_PARAM const ee0::RenderContext& rc)
: ee3::WxStageCanvas(dev, stage, ECS_WORLD_VAR &rc, nullptr, true)
{
m_viewers[VIEWER_IMAGE] = std::make_shared<ImageViewer>(dev);
m_viewers[VIEWER_HEIGHT] = std::make_shared<HeightViewer>(dev);
m_viewers[VIEWER_MODEL] = std::make_shared<ModelViewer>(dev);
auto sub_mgr = stage->GetSubjectMgr();
sub_mgr->RegisterObserver(MSG_SHADER_CHANGED, this);
}
WxPreviewCanvas::~WxPreviewCanvas()
{
if (m_graph_page)
{
auto sub_mgr = m_graph_page->GetSubjectMgr();
sub_mgr->UnregisterObserver(ee0::MSG_NODE_SELECTION_INSERT, this);
}
auto sub_mgr = m_stage->GetSubjectMgr();
sub_mgr->UnregisterObserver(MSG_SHADER_CHANGED, this);
}
void WxPreviewCanvas::OnNotify(uint32_t msg, const ee0::VariantSet& variants)
{
ee3::WxStageCanvas::OnNotify(msg, variants);
switch (msg)
{
case MSG_SHADER_CHANGED:
RebuildShader();
SetDirty();
break;
}
}
void WxPreviewCanvas::DrawBackground3D() const
{
// ee3::WxStageCanvas::DrawBackgroundGrids(10.0f, 0.2f);
// ee3::WxStageCanvas::DrawBackgroundCross();
}
void WxPreviewCanvas::DrawForeground3D() const
{
if (!m_graph_page) {
return;
}
}
void WxPreviewCanvas::DrawForeground2D() const
{
auto shader = m_viewers[m_viewer_type]->GetShader();
if (shader)
{
auto model_updater = shader->QueryUniformUpdater(ur::GetUpdaterTypeID<pt0::ModelMatUpdater>());
if (model_updater) {
std::static_pointer_cast<pt0::ModelMatUpdater>(model_updater)->Update(sm::mat4());
}
}
m_viewers[m_viewer_type]->Draw(*GetRenderContext().ur_ctx, GetWidnowContext().wc3.get());
}
void WxPreviewCanvas::OnTimer()
{
m_eval.UpdateUniforms();
SetDirty();
}
void WxPreviewCanvas::RebuildShader()
{
std::vector<bp::NodePtr> nodes;
auto root = m_graph_page->GetSceneTree()->GetRootNode();
assert(root->HasSharedComp<n0::CompComplex>());
auto& ccomplex = root->GetSharedComp<n0::CompComplex>();
nodes.reserve(ccomplex.GetAllChildren().size());
for (auto& c : ccomplex.GetAllChildren()) {
if (c->HasUniqueComp<bp::CompNode>()) {
nodes.push_back(c->GetUniqueComp<bp::CompNode>().GetNode());
}
}
auto textures = m_eval.QueryTextures(nodes);
for (auto& viewer : m_viewers)
{
auto shader = m_eval.BuildShader(m_dev, viewer->GetVertShaderCode(), nodes);
if (shader) {
viewer->Update(*GetRenderContext().ur_ctx, shader, textures);
}
}
for (auto& bp_node : nodes) {
BuildNodePreviewShader(bp_node);
}
}
void WxPreviewCanvas::BuildNodePreviewShader(const bp::NodePtr& bp_node) const
{
if (!bp_node->get_type().is_derived_from<shaderlab::Node>()) {
return;
}
auto node = std::static_pointer_cast<Node>(bp_node);
if (!node->GetPreview()) {
return;
}
auto back_node = m_front_eval->QueryBackNode(*node);
if (!back_node) {
return;
}
auto& src_outputs = back_node->GetExports();
if (src_outputs.empty()) {
return;
}
int conn_fs_idx = -1;
switch (src_outputs[0].var.type.type)
{
case shadergraph::VarType::Float4:
conn_fs_idx = static_cast<int>(shadergraph::block::FragmentShader::Input::RGBA);
break;
case shadergraph::VarType::Float3:
conn_fs_idx = static_cast<int>(shadergraph::block::FragmentShader::Input::RGB);
break;
case shadergraph::VarType::Float2:
conn_fs_idx = static_cast<int>(shadergraph::block::FragmentShader::Input::RG);
break;
case shadergraph::VarType::Float:
conn_fs_idx = static_cast<int>(shadergraph::block::FragmentShader::Input::Grey);
break;
}
if (conn_fs_idx < 0) {
return;
}
auto fs_out = std::make_shared<shadergraph::block::FragmentShader>();
dag::make_connecting<shadergraph::Variant>({ back_node, 0 }, { fs_out, conn_fs_idx });
shadergraph::Evaluator back_eval;
back_eval.Rebuild(fs_out);
back_eval.Rebuild(fs_out);
auto fs = back_eval.GenShaderCode();
if (fs.empty()) {
return;
}
std::vector<unsigned int> _vs, _fs;
auto vs = m_viewers[m_viewer_type]->GetVertShaderCode();
shadertrans::ShaderTrans::GLSL2SpirV(shadertrans::ShaderStage::VertexShader, vs, _vs);
shadertrans::ShaderTrans::GLSL2SpirV(shadertrans::ShaderStage::PixelShader, fs, _fs);
auto shader = m_dev.CreateShaderProgram(_vs, _fs);
if (!shader->CheckStatus()) {
return;
}
dag::disconnect<shadergraph::Variant>({ back_node, 0 }, { fs_out, conn_fs_idx });
node->SetPreviewShader(shader);
}
}<commit_msg>clean up<commit_after>#include "shaderlab/WxPreviewCanvas.h"
#include "shaderlab/MessageID.h"
#include "shaderlab/WxGraphPage.h"
#include "shaderlab/ImageViewer.h"
#include "shaderlab/HeightViewer.h"
#include "shaderlab/ModelViewer.h"
#include "shaderlab/Node.h"
#include <ee0/WxStagePage.h>
#include <ee0/SubjectMgr.h>
#include <blueprint/Node.h>
#include <unirender/Device.h>
#include <unirender/ShaderProgram.h>
#include <shadertrans/ShaderTrans.h>
#include <painting0/ModelMatUpdater.h>
#include <painting3/ViewMatUpdater.h>
#include <painting3/ProjectMatUpdater.h>
#include <shadergraph/block/FragmentShader.h>
namespace shaderlab
{
WxPreviewCanvas::WxPreviewCanvas(const ur::Device& dev, ee0::WxStagePage* stage,
ECS_WORLD_PARAM const ee0::RenderContext& rc)
: ee3::WxStageCanvas(dev, stage, ECS_WORLD_VAR &rc, nullptr, true)
{
m_viewers[VIEWER_IMAGE] = std::make_shared<ImageViewer>(dev);
m_viewers[VIEWER_HEIGHT] = std::make_shared<HeightViewer>(dev);
m_viewers[VIEWER_MODEL] = std::make_shared<ModelViewer>(dev);
auto sub_mgr = stage->GetSubjectMgr();
sub_mgr->RegisterObserver(MSG_SHADER_CHANGED, this);
}
WxPreviewCanvas::~WxPreviewCanvas()
{
if (m_graph_page)
{
auto sub_mgr = m_graph_page->GetSubjectMgr();
sub_mgr->UnregisterObserver(ee0::MSG_NODE_SELECTION_INSERT, this);
}
auto sub_mgr = m_stage->GetSubjectMgr();
sub_mgr->UnregisterObserver(MSG_SHADER_CHANGED, this);
}
void WxPreviewCanvas::OnNotify(uint32_t msg, const ee0::VariantSet& variants)
{
ee3::WxStageCanvas::OnNotify(msg, variants);
switch (msg)
{
case MSG_SHADER_CHANGED:
RebuildShader();
SetDirty();
break;
}
}
void WxPreviewCanvas::DrawBackground3D() const
{
// ee3::WxStageCanvas::DrawBackgroundGrids(10.0f, 0.2f);
// ee3::WxStageCanvas::DrawBackgroundCross();
}
void WxPreviewCanvas::DrawForeground3D() const
{
if (!m_graph_page) {
return;
}
}
void WxPreviewCanvas::DrawForeground2D() const
{
auto shader = m_viewers[m_viewer_type]->GetShader();
if (shader)
{
auto model_updater = shader->QueryUniformUpdater(ur::GetUpdaterTypeID<pt0::ModelMatUpdater>());
if (model_updater) {
std::static_pointer_cast<pt0::ModelMatUpdater>(model_updater)->Update(sm::mat4());
}
}
m_viewers[m_viewer_type]->Draw(*GetRenderContext().ur_ctx, GetWidnowContext().wc3.get());
}
void WxPreviewCanvas::OnTimer()
{
m_eval.UpdateUniforms();
SetDirty();
}
void WxPreviewCanvas::RebuildShader()
{
std::vector<bp::NodePtr> nodes;
auto root = m_graph_page->GetSceneTree()->GetRootNode();
assert(root->HasSharedComp<n0::CompComplex>());
auto& ccomplex = root->GetSharedComp<n0::CompComplex>();
nodes.reserve(ccomplex.GetAllChildren().size());
for (auto& c : ccomplex.GetAllChildren()) {
if (c->HasUniqueComp<bp::CompNode>()) {
nodes.push_back(c->GetUniqueComp<bp::CompNode>().GetNode());
}
}
auto textures = m_eval.QueryTextures(nodes);
for (auto& viewer : m_viewers)
{
auto shader = m_eval.BuildShader(m_dev, viewer->GetVertShaderCode(), nodes);
if (shader) {
viewer->Update(*GetRenderContext().ur_ctx, shader, textures);
}
}
for (auto& bp_node : nodes) {
BuildNodePreviewShader(bp_node);
}
}
void WxPreviewCanvas::BuildNodePreviewShader(const bp::NodePtr& bp_node) const
{
if (!bp_node->get_type().is_derived_from<shaderlab::Node>()) {
return;
}
auto node = std::static_pointer_cast<Node>(bp_node);
if (!node->GetPreview()) {
return;
}
auto back_node = m_front_eval->QueryBackNode(*node);
if (!back_node) {
return;
}
auto& src_outputs = back_node->GetExports();
if (src_outputs.empty()) {
return;
}
int conn_fs_idx = -1;
switch (src_outputs[0].var.type.type)
{
case shadergraph::VarType::Float4:
conn_fs_idx = static_cast<int>(shadergraph::block::FragmentShader::Input::RGBA);
break;
case shadergraph::VarType::Float3:
conn_fs_idx = static_cast<int>(shadergraph::block::FragmentShader::Input::RGB);
break;
case shadergraph::VarType::Float2:
conn_fs_idx = static_cast<int>(shadergraph::block::FragmentShader::Input::RG);
break;
case shadergraph::VarType::Float:
conn_fs_idx = static_cast<int>(shadergraph::block::FragmentShader::Input::Grey);
break;
}
if (conn_fs_idx < 0) {
return;
}
auto fs_out = std::make_shared<shadergraph::block::FragmentShader>();
dag::make_connecting<shadergraph::Variant>({ back_node, 0 }, { fs_out, conn_fs_idx });
shadergraph::Evaluator back_eval;
back_eval.Rebuild(fs_out);
auto fs = back_eval.GenShaderCode();
if (fs.empty()) {
return;
}
std::vector<unsigned int> _vs, _fs;
auto vs = m_viewers[m_viewer_type]->GetVertShaderCode();
shadertrans::ShaderTrans::GLSL2SpirV(shadertrans::ShaderStage::VertexShader, vs, _vs);
shadertrans::ShaderTrans::GLSL2SpirV(shadertrans::ShaderStage::PixelShader, fs, _fs);
auto shader = m_dev.CreateShaderProgram(_vs, _fs);
if (!shader->CheckStatus()) {
return;
}
dag::disconnect<shadergraph::Variant>({ back_node, 0 }, { fs_out, conn_fs_idx });
node->SetPreviewShader(shader);
}
}<|endoftext|> |
<commit_before><commit_msg>Fix double (post)initialization of scenes on startup<commit_after><|endoftext|> |
<commit_before><commit_msg>Format frame time plot line in ms<commit_after><|endoftext|> |
<commit_before>#include <stan/math/prim/scal.hpp>
#include <gtest/gtest.h>
#include <limits>
TEST(MathFunctions, is_nan) {
using stan::math::is_nan;
double infinity = std::numeric_limits<double>::infinity();
double nan = std::numeric_limits<double>::quiet_NaN();
double min = std::numeric_limits<double>::min();
double max = std::numeric_limits<double>::max();
EXPECT_TRUE(stan::math::is_nan(nan));
EXPECT_FALSE(stan::math::is_nan(infinity));
EXPECT_FALSE(stan::math::is_nan(0));
EXPECT_FALSE(stan::math::is_nan(1));
EXPECT_FALSE(stan::math::is_nan(min));
EXPECT_FALSE(stan::math::is_nan(max));
}
<commit_msg>Add tests for variadic calls<commit_after>#include <stan/math/prim/scal.hpp>
#include <gtest/gtest.h>
#include <limits>
TEST(MathFunctions, is_nan) {
using stan::math::is_nan;
double infinity = std::numeric_limits<double>::infinity();
double nan = std::numeric_limits<double>::quiet_NaN();
double min = std::numeric_limits<double>::min();
double max = std::numeric_limits<double>::max();
EXPECT_TRUE(is_nan(nan));
EXPECT_FALSE(is_nan(infinity));
EXPECT_FALSE(is_nan(0));
EXPECT_FALSE(is_nan(1));
EXPECT_FALSE(is_nan(min));
EXPECT_FALSE(is_nan(max));
}
TEST(MathFunctions, is_nan_variadic) {
using stan::math::is_nan;
double infinity = std::numeric_limits<double>::infinity();
double nan = std::numeric_limits<double>::quiet_NaN();
double min = std::numeric_limits<double>::min();
double max = std::numeric_limits<double>::max();
EXPECT_TRUE(is_nan(nan, infinity, 1.0));
EXPECT_TRUE(is_nan(max, infinity, nan, 2.0, 5.0));
EXPECT_TRUE(is_nan(max, min, nan));
EXPECT_FALSE(is_nan(1.0, 2.0, 20.0, 1, 2));
}
<|endoftext|> |
<commit_before>/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2010 Hieu Hoang
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 <algorithm>
#include <iostream>
#include <vector>
#include "StaticData.h"
#include "ChartTranslationOptionList.h"
#include "ChartTranslationOptions.h"
#include "ChartCellCollection.h"
#include "WordsRange.h"
#include "InputType.h"
#include "InputPath.h"
using namespace std;
namespace Moses
{
ChartTranslationOptionList::ChartTranslationOptionList(size_t ruleLimit, const InputType &input)
: m_size(0)
, m_ruleLimit(ruleLimit)
{
m_scoreThreshold = std::numeric_limits<float>::infinity();
}
ChartTranslationOptionList::~ChartTranslationOptionList()
{
RemoveAllInColl(m_collection);
}
void ChartTranslationOptionList::Clear()
{
m_size = 0;
m_scoreThreshold = std::numeric_limits<float>::infinity();
}
class ChartTranslationOptionOrderer
{
public:
bool operator()(const ChartTranslationOptions* itemA, const ChartTranslationOptions* itemB) const {
return itemA->GetEstimateOfBestScore() > itemB->GetEstimateOfBestScore();
}
};
void ChartTranslationOptionList::Add(const TargetPhraseCollection &tpc,
const StackVec &stackVec,
const WordsRange &range)
{
if (tpc.IsEmpty()) {
return;
}
for (size_t i = 0; i < stackVec.size(); ++i) {
const ChartCellLabel &chartCellLabel = *stackVec[i];
size_t numHypos = chartCellLabel.GetStack().cube->size();
if (numHypos == 0) {
return; // empty stack. These rules can't be used
}
}
const TargetPhrase &targetPhrase = **(tpc.begin());
float score = targetPhrase.GetFutureScore();
for (StackVec::const_iterator p = stackVec.begin(); p != stackVec.end(); ++p) {
score += (*p)->GetBestScore(this);
}
// If the rule limit has already been reached then don't add the option
// unless it is better than at least one existing option.
if (m_size > m_ruleLimit && score < m_scoreThreshold) {
return;
}
// Add the option to the list.
if (m_size == m_collection.size()) {
// m_collection has reached capacity: create a new object.
m_collection.push_back(new ChartTranslationOptions(tpc, stackVec,
range, score));
} else {
// Overwrite an unused object.
*(m_collection[m_size]) = ChartTranslationOptions(tpc, stackVec,
range, score);
}
++m_size;
// If the rule limit hasn't been exceeded then update the threshold.
if (m_size <= m_ruleLimit) {
m_scoreThreshold = (score < m_scoreThreshold) ? score : m_scoreThreshold;
}
// Prune if bursting
if (m_size == m_ruleLimit * 2) {
NTH_ELEMENT4(m_collection.begin(),
m_collection.begin() + m_ruleLimit - 1,
m_collection.begin() + m_size,
ChartTranslationOptionOrderer());
m_scoreThreshold = m_collection[m_ruleLimit-1]->GetEstimateOfBestScore();
m_size = m_ruleLimit;
}
}
void ChartTranslationOptionList::AddPhraseOOV(TargetPhrase &phrase, std::list<TargetPhraseCollection*> &waste_memory, const WordsRange &range)
{
TargetPhraseCollection *tpc = new TargetPhraseCollection();
tpc->Add(&phrase);
waste_memory.push_back(tpc);
StackVec empty;
Add(*tpc, empty, range);
}
void ChartTranslationOptionList::ApplyThreshold()
{
if (m_size > m_ruleLimit) {
// Something's gone wrong if the list has grown to m_ruleLimit * 2
// without being pruned.
assert(m_size < m_ruleLimit * 2);
// Reduce the list to the best m_ruleLimit options. The remaining
// options can be overwritten on subsequent calls to Add().
NTH_ELEMENT4(m_collection.begin(),
m_collection.begin()+m_ruleLimit,
m_collection.begin()+m_size,
ChartTranslationOptionOrderer());
m_size = m_ruleLimit;
}
// keep only those over best + threshold
float scoreThreshold = -std::numeric_limits<float>::infinity();
CollType::const_iterator iter;
for (iter = m_collection.begin(); iter != m_collection.begin()+m_size; ++iter) {
const ChartTranslationOptions *transOpt = *iter;
float score = transOpt->GetEstimateOfBestScore();
scoreThreshold = (score > scoreThreshold) ? score : scoreThreshold;
}
scoreThreshold += StaticData::Instance().GetTranslationOptionThreshold();
CollType::iterator bound = std::partition(m_collection.begin(),
m_collection.begin()+m_size,
ScoreThresholdPred(scoreThreshold));
m_size = std::distance(m_collection.begin(), bound);
}
float ChartTranslationOptionList::GetBestScore(const ChartCellLabel *chartCell) const
{
const HypoList *stack = chartCell->GetStack().cube;
assert(stack);
assert(!stack->empty());
const ChartHypothesis &bestHypo = **(stack->begin());
return bestHypo.GetTotalScore();
}
void ChartTranslationOptionList::Evaluate(const InputType &input, const InputPath &inputPath)
{
// NEVER iterate over ALL of the collection. Just over the first m_size
CollType::iterator iter;
for (iter = m_collection.begin(); iter != m_collection.begin() + m_size; ++iter) {
ChartTranslationOptions &transOpts = **iter;
transOpts.Evaluate(input, inputPath);
}
}
std::ostream& operator<<(std::ostream &out, const ChartTranslationOptionList &obj)
{
for (size_t i = 0; i < obj.m_collection.size(); ++i) {
const ChartTranslationOptions &transOpts = *obj.m_collection[i];
out << transOpts << endl;
}
return out;
}
}
<commit_msg>strange assert failure when stack is empty<commit_after>/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2010 Hieu Hoang
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 <algorithm>
#include <iostream>
#include <vector>
#include "StaticData.h"
#include "ChartTranslationOptionList.h"
#include "ChartTranslationOptions.h"
#include "ChartCellCollection.h"
#include "WordsRange.h"
#include "InputType.h"
#include "InputPath.h"
using namespace std;
namespace Moses
{
ChartTranslationOptionList::ChartTranslationOptionList(size_t ruleLimit, const InputType &input)
: m_size(0)
, m_ruleLimit(ruleLimit)
{
m_scoreThreshold = std::numeric_limits<float>::infinity();
}
ChartTranslationOptionList::~ChartTranslationOptionList()
{
RemoveAllInColl(m_collection);
}
void ChartTranslationOptionList::Clear()
{
m_size = 0;
m_scoreThreshold = std::numeric_limits<float>::infinity();
}
class ChartTranslationOptionOrderer
{
public:
bool operator()(const ChartTranslationOptions* itemA, const ChartTranslationOptions* itemB) const {
return itemA->GetEstimateOfBestScore() > itemB->GetEstimateOfBestScore();
}
};
void ChartTranslationOptionList::Add(const TargetPhraseCollection &tpc,
const StackVec &stackVec,
const WordsRange &range)
{
if (tpc.IsEmpty()) {
return;
}
for (size_t i = 0; i < stackVec.size(); ++i) {
const ChartCellLabel &chartCellLabel = *stackVec[i];
size_t numHypos = chartCellLabel.GetStack().cube->size();
if (numHypos == 0) {
return; // empty stack. These rules can't be used
}
}
const TargetPhrase &targetPhrase = **(tpc.begin());
float score = targetPhrase.GetFutureScore();
for (StackVec::const_iterator p = stackVec.begin(); p != stackVec.end(); ++p) {
score += (*p)->GetBestScore(this);
}
// If the rule limit has already been reached then don't add the option
// unless it is better than at least one existing option.
if (m_size > m_ruleLimit && score < m_scoreThreshold) {
return;
}
// Add the option to the list.
if (m_size == m_collection.size()) {
// m_collection has reached capacity: create a new object.
m_collection.push_back(new ChartTranslationOptions(tpc, stackVec,
range, score));
} else {
// Overwrite an unused object.
*(m_collection[m_size]) = ChartTranslationOptions(tpc, stackVec,
range, score);
}
++m_size;
// If the rule limit hasn't been exceeded then update the threshold.
if (m_size <= m_ruleLimit) {
m_scoreThreshold = (score < m_scoreThreshold) ? score : m_scoreThreshold;
}
// Prune if bursting
if (m_size == m_ruleLimit * 2) {
NTH_ELEMENT4(m_collection.begin(),
m_collection.begin() + m_ruleLimit - 1,
m_collection.begin() + m_size,
ChartTranslationOptionOrderer());
m_scoreThreshold = m_collection[m_ruleLimit-1]->GetEstimateOfBestScore();
m_size = m_ruleLimit;
}
}
void ChartTranslationOptionList::AddPhraseOOV(TargetPhrase &phrase, std::list<TargetPhraseCollection*> &waste_memory, const WordsRange &range)
{
TargetPhraseCollection *tpc = new TargetPhraseCollection();
tpc->Add(&phrase);
waste_memory.push_back(tpc);
StackVec empty;
Add(*tpc, empty, range);
}
void ChartTranslationOptionList::ApplyThreshold()
{
if (m_size > m_ruleLimit) {
// Something's gone wrong if the list has grown to m_ruleLimit * 2
// without being pruned.
assert(m_size < m_ruleLimit * 2);
// Reduce the list to the best m_ruleLimit options. The remaining
// options can be overwritten on subsequent calls to Add().
NTH_ELEMENT4(m_collection.begin(),
m_collection.begin()+m_ruleLimit,
m_collection.begin()+m_size,
ChartTranslationOptionOrderer());
m_size = m_ruleLimit;
}
// keep only those over best + threshold
float scoreThreshold = -std::numeric_limits<float>::infinity();
CollType::const_iterator iter;
for (iter = m_collection.begin(); iter != m_collection.begin()+m_size; ++iter) {
const ChartTranslationOptions *transOpt = *iter;
float score = transOpt->GetEstimateOfBestScore();
scoreThreshold = (score > scoreThreshold) ? score : scoreThreshold;
}
scoreThreshold += StaticData::Instance().GetTranslationOptionThreshold();
CollType::iterator bound = std::partition(m_collection.begin(),
m_collection.begin()+m_size,
ScoreThresholdPred(scoreThreshold));
m_size = std::distance(m_collection.begin(), bound);
}
float ChartTranslationOptionList::GetBestScore(const ChartCellLabel *chartCell) const
{
const HypoList *stack = chartCell->GetStack().cube;
assert(stack);
//assert(!stack->empty());
if (stack->empty()) {
return 0;
}
else {
const ChartHypothesis &bestHypo = **(stack->begin());
return bestHypo.GetTotalScore();
}
}
void ChartTranslationOptionList::Evaluate(const InputType &input, const InputPath &inputPath)
{
// NEVER iterate over ALL of the collection. Just over the first m_size
CollType::iterator iter;
for (iter = m_collection.begin(); iter != m_collection.begin() + m_size; ++iter) {
ChartTranslationOptions &transOpts = **iter;
transOpts.Evaluate(input, inputPath);
}
}
std::ostream& operator<<(std::ostream &out, const ChartTranslationOptionList &obj)
{
for (size_t i = 0; i < obj.m_collection.size(); ++i) {
const ChartTranslationOptions &transOpts = *obj.m_collection[i];
out << transOpts << endl;
}
return out;
}
}
<|endoftext|> |
<commit_before>//
// MainPage.xaml.cpp
// Implementation of the MainPage class.
//
#include "pch.h"
#include "MainPage.xaml.h"
using namespace GpioOneWire;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::UI::Core;
using namespace Windows::System::Threading;
using namespace Windows::Devices::Gpio;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
void GpioOneWire::Dht11::Init (GpioPin^ Pin)
{
// Use InputPullUp if supported, otherwise fall back to Input (floating)
this->inputDriveMode =
Pin->IsDriveModeSupported(GpioPinDriveMode::InputPullUp) ?
GpioPinDriveMode::InputPullUp : GpioPinDriveMode::Input;
Pin->SetDriveMode(this->inputDriveMode);
this->pin = Pin;
}
_Use_decl_annotations_
HRESULT GpioOneWire::Dht11::Sample (GpioOneWire::Dht11Reading& Reading)
{
Reading = Dht11Reading();
LARGE_INTEGER qpf;
QueryPerformanceFrequency(&qpf);
// convert microseconds to QPF units
const unsigned int oneThreshold = static_cast<unsigned int>(
110LL * qpf.QuadPart / 1000000LL);
// Set pin as input pull up
this->pin->SetDriveMode(this->inputDriveMode);
// Latch low value onto pin
this->pin->Write(GpioPinValue::Low);
// Set pin as output
this->pin->SetDriveMode(GpioPinDriveMode::Output);
// Wait for at least 18 ms
Sleep(18);
// Set pin back to input
this->pin->SetDriveMode(this->inputDriveMode);
GpioPinValue previousValue = this->pin->Read();
// catch the first rising edge
ULONGLONG endTickCount = GetTickCount64() + 1;
for (;;) {
if (GetTickCount64() > endTickCount) {
return HRESULT_FROM_WIN32(ERROR_TIMEOUT);
}
GpioPinValue value = this->pin->Read();
if (value != previousValue) {
// rising edgue?
if (value == GpioPinValue::High) {
break;
}
previousValue = value;
}
}
LARGE_INTEGER prevTime = { 0 };
unsigned int i = 0;
endTickCount = GetTickCount64() + 10;
// capture every falling edge until all bits are received or
// timeout occurs
for (;;) {
if (GetTickCount64() > endTickCount) {
return HRESULT_FROM_WIN32(ERROR_TIMEOUT);
}
GpioPinValue value = this->pin->Read();
if ((previousValue == GpioPinValue::High) && (value == GpioPinValue::Low)) {
// A falling edge was detected
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
if (i != 0) {
unsigned int difference = static_cast<unsigned int>(
now.QuadPart - prevTime.QuadPart);
Reading.bits[Reading.bits.size() - i] =
difference > oneThreshold;
}
prevTime = now;
++i;
if (i == (Reading.bits.size() + 1))
break;
}
previousValue = value;
}
if (i != (Reading.bits.size() + 1)) {
// did not receive all bits
return HRESULT_FROM_WIN32(ERROR_IO_DEVICE);
}
if (!Reading.IsValid()) {
// checksum mismatch
return HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
}
return S_OK;
}
MainPage::MainPage()
{
InitializeComponent();
}
void GpioOneWire::MainPage::Page_Loaded(
Platform::Object^ sender,
Windows::UI::Xaml::RoutedEventArgs^ e
)
{
GpioController^ controller = GpioController::GetDefault();
if (!controller) {
this->statusText->Text = L"GPIO is not available on this system";
return;
}
GpioPin^ pin;
try {
pin = controller->OpenPin(18);
} catch (Exception^ ex) {
this->statusText->Text = L"Failed to open GPIO pin: " + ex->Message;
return;
}
this->dht11.Init(pin);
this->pullResistorText->Text = this->dht11.PullResistorRequired() ?
L"10k pull-up resistor required." : L"Pull-up resistor not required.";
TimeSpan period = { 2 * 10000000LL };
this->timer = ThreadPoolTimer::CreatePeriodicTimer(
ref new TimerElapsedHandler(this, &MainPage::timerElapsed),
period);
this->statusText->Text = L"Status: Initialized Successfully";
}
void GpioOneWire::MainPage::timerElapsed (
Windows::System::Threading::ThreadPoolTimer^ Timer
)
{
HRESULT sensorHr;
Dht11Reading reading;
int retryCount = 0;
do {
sensorHr = this->dht11.Sample(reading);
} while (FAILED(sensorHr) && (++retryCount < 20));
this->Dispatcher->RunAsync(
CoreDispatcherPriority::Normal,
ref new DispatchedHandler([this, reading, sensorHr, retryCount] ()
{
if (FAILED(sensorHr)) {
this->humidityText->Text = L"Humidity: (failed)";
this->temperatureText->Text = L"Temperature: (failed)";
switch (sensorHr) {
case __HRESULT_FROM_WIN32(ERROR_IO_DEVICE):
this->statusText->Text = L"Did not catch all falling edges";
break;
case __HRESULT_FROM_WIN32(ERROR_TIMEOUT):
this->statusText->Text = L"Timed out waiting for sample";
break;
case __HRESULT_FROM_WIN32(ERROR_INVALID_DATA):
this->statusText->Text = L"Checksum validation failed";
break;
default:
this->statusText->Text = L"Failed to get reading";
}
return;
}
HRESULT hr;
wchar_t buf[128];
hr = StringCchPrintfW(
buf,
ARRAYSIZE(buf),
L"Humidity: %.1f%% RH",,
reading.Humidity());
if (FAILED(hr)) {
throw ref new Exception(hr, L"Failed to print string");
}
this->humidityText->Text = ref new String(buf);
hr = StringCchPrintfW(
buf,
ARRAYSIZE(buf),
L"Temperature: %.1f \u00B0C",
reading.Temperature());
if (FAILED(hr)) {
throw ref new Exception(hr, L"Failed to print string");
}
this->temperatureText->Text = ref new String(buf);
hr = StringCchPrintfW(
buf,
ARRAYSIZE(buf),
L"Succeeded (%d %s)",
retryCount,
(retryCount == 1) ? L"retry" : L"retries");
if (FAILED(hr)) {
throw ref new Exception(hr, L"Failed to print string");
}
this->statusText->Text = ref new String(buf);
}));
}
<commit_msg>Removed misplaced comma.<commit_after>//
// MainPage.xaml.cpp
// Implementation of the MainPage class.
//
#include "pch.h"
#include "MainPage.xaml.h"
using namespace GpioOneWire;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::UI::Core;
using namespace Windows::System::Threading;
using namespace Windows::Devices::Gpio;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
void GpioOneWire::Dht11::Init (GpioPin^ Pin)
{
// Use InputPullUp if supported, otherwise fall back to Input (floating)
this->inputDriveMode =
Pin->IsDriveModeSupported(GpioPinDriveMode::InputPullUp) ?
GpioPinDriveMode::InputPullUp : GpioPinDriveMode::Input;
Pin->SetDriveMode(this->inputDriveMode);
this->pin = Pin;
}
_Use_decl_annotations_
HRESULT GpioOneWire::Dht11::Sample (GpioOneWire::Dht11Reading& Reading)
{
Reading = Dht11Reading();
LARGE_INTEGER qpf;
QueryPerformanceFrequency(&qpf);
// convert microseconds to QPF units
const unsigned int oneThreshold = static_cast<unsigned int>(
110LL * qpf.QuadPart / 1000000LL);
// Set pin as input pull up
this->pin->SetDriveMode(this->inputDriveMode);
// Latch low value onto pin
this->pin->Write(GpioPinValue::Low);
// Set pin as output
this->pin->SetDriveMode(GpioPinDriveMode::Output);
// Wait for at least 18 ms
Sleep(18);
// Set pin back to input
this->pin->SetDriveMode(this->inputDriveMode);
GpioPinValue previousValue = this->pin->Read();
// catch the first rising edge
ULONGLONG endTickCount = GetTickCount64() + 1;
for (;;) {
if (GetTickCount64() > endTickCount) {
return HRESULT_FROM_WIN32(ERROR_TIMEOUT);
}
GpioPinValue value = this->pin->Read();
if (value != previousValue) {
// rising edgue?
if (value == GpioPinValue::High) {
break;
}
previousValue = value;
}
}
LARGE_INTEGER prevTime = { 0 };
unsigned int i = 0;
endTickCount = GetTickCount64() + 10;
// capture every falling edge until all bits are received or
// timeout occurs
for (;;) {
if (GetTickCount64() > endTickCount) {
return HRESULT_FROM_WIN32(ERROR_TIMEOUT);
}
GpioPinValue value = this->pin->Read();
if ((previousValue == GpioPinValue::High) && (value == GpioPinValue::Low)) {
// A falling edge was detected
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
if (i != 0) {
unsigned int difference = static_cast<unsigned int>(
now.QuadPart - prevTime.QuadPart);
Reading.bits[Reading.bits.size() - i] =
difference > oneThreshold;
}
prevTime = now;
++i;
if (i == (Reading.bits.size() + 1))
break;
}
previousValue = value;
}
if (i != (Reading.bits.size() + 1)) {
// did not receive all bits
return HRESULT_FROM_WIN32(ERROR_IO_DEVICE);
}
if (!Reading.IsValid()) {
// checksum mismatch
return HRESULT_FROM_WIN32(ERROR_INVALID_DATA);
}
return S_OK;
}
MainPage::MainPage()
{
InitializeComponent();
}
void GpioOneWire::MainPage::Page_Loaded(
Platform::Object^ sender,
Windows::UI::Xaml::RoutedEventArgs^ e
)
{
GpioController^ controller = GpioController::GetDefault();
if (!controller) {
this->statusText->Text = L"GPIO is not available on this system";
return;
}
GpioPin^ pin;
try {
pin = controller->OpenPin(18);
} catch (Exception^ ex) {
this->statusText->Text = L"Failed to open GPIO pin: " + ex->Message;
return;
}
this->dht11.Init(pin);
this->pullResistorText->Text = this->dht11.PullResistorRequired() ?
L"10k pull-up resistor required." : L"Pull-up resistor not required.";
TimeSpan period = { 2 * 10000000LL };
this->timer = ThreadPoolTimer::CreatePeriodicTimer(
ref new TimerElapsedHandler(this, &MainPage::timerElapsed),
period);
this->statusText->Text = L"Status: Initialized Successfully";
}
void GpioOneWire::MainPage::timerElapsed (
Windows::System::Threading::ThreadPoolTimer^ Timer
)
{
HRESULT sensorHr;
Dht11Reading reading;
int retryCount = 0;
do {
sensorHr = this->dht11.Sample(reading);
} while (FAILED(sensorHr) && (++retryCount < 20));
this->Dispatcher->RunAsync(
CoreDispatcherPriority::Normal,
ref new DispatchedHandler([this, reading, sensorHr, retryCount] ()
{
if (FAILED(sensorHr)) {
this->humidityText->Text = L"Humidity: (failed)";
this->temperatureText->Text = L"Temperature: (failed)";
switch (sensorHr) {
case __HRESULT_FROM_WIN32(ERROR_IO_DEVICE):
this->statusText->Text = L"Did not catch all falling edges";
break;
case __HRESULT_FROM_WIN32(ERROR_TIMEOUT):
this->statusText->Text = L"Timed out waiting for sample";
break;
case __HRESULT_FROM_WIN32(ERROR_INVALID_DATA):
this->statusText->Text = L"Checksum validation failed";
break;
default:
this->statusText->Text = L"Failed to get reading";
}
return;
}
HRESULT hr;
wchar_t buf[128];
hr = StringCchPrintfW(
buf,
ARRAYSIZE(buf),
L"Humidity: %.1f%% RH",
reading.Humidity());
if (FAILED(hr)) {
throw ref new Exception(hr, L"Failed to print string");
}
this->humidityText->Text = ref new String(buf);
hr = StringCchPrintfW(
buf,
ARRAYSIZE(buf),
L"Temperature: %.1f \u00B0C",
reading.Temperature());
if (FAILED(hr)) {
throw ref new Exception(hr, L"Failed to print string");
}
this->temperatureText->Text = ref new String(buf);
hr = StringCchPrintfW(
buf,
ARRAYSIZE(buf),
L"Succeeded (%d %s)",
retryCount,
(retryCount == 1) ? L"retry" : L"retries");
if (FAILED(hr)) {
throw ref new Exception(hr, L"Failed to print string");
}
this->statusText->Text = ref new String(buf);
}));
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "FsDiscoverer.h"
#include <algorithm>
#include <queue>
#include "factory/FileSystemFactory.h"
#include "filesystem/IDevice.h"
#include "Media.h"
#include "File.h"
#include "Device.h"
#include "Folder.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "utils/Filename.h"
namespace
{
class DeviceRemovedException : public std::runtime_error
{
public:
DeviceRemovedException() noexcept
: std::runtime_error( "A device was removed during the discovery" )
{
}
};
}
namespace medialibrary
{
FsDiscoverer::FsDiscoverer( std::shared_ptr<factory::IFileSystem> fsFactory, MediaLibrary* ml, IMediaLibraryCb* cb )
: m_ml( ml )
, m_fsFactory( fsFactory )
, m_cb( cb )
{
}
bool FsDiscoverer::discover( const std::string &entryPoint )
{
LOG_INFO( "Adding to discovery list: ", entryPoint );
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
std::shared_ptr<fs::IDirectory> fsDir = m_fsFactory->createDirectory( entryPoint );
// Otherwise, create a directory and check it for modifications
if ( fsDir == nullptr )
{
LOG_ERROR("Failed to create an IDirectory for ", entryPoint );
return false;
}
auto f = Folder::fromMrl( m_ml, fsDir->mrl() );
// If the folder exists, we assume it will be handled by reload()
if ( f != nullptr )
return true;
try
{
if ( hasDotNoMediaFile( *fsDir ) )
return true;
return addFolder( std::move( fsDir ), nullptr );
}
catch ( std::system_error& ex )
{
LOG_WARN( entryPoint, " discovery aborted because of a filesystem error: ", ex.what() );
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
LOG_WARN( entryPoint, " discovery aborted (assuming blacklisted folder): ", ex.what() );
}
catch ( DeviceRemovedException& )
{
// Simply ignore, the device has already been marked as removed and the DB updated accordingly
LOG_INFO( "Discovery of ", fsDir->mrl(), " was stopped after the device was removed" );
}
return true;
}
void FsDiscoverer::reloadFolder( std::shared_ptr<Folder> f )
{
auto folder = m_fsFactory->createDirectory( f->mrl() );
try
{
checkFolder( std::move( folder ), std::move( f ), false );
}
catch ( DeviceRemovedException& )
{
LOG_INFO( "Reloading of ", f->mrl(), " was stopped after the device was removed" );
}
}
bool FsDiscoverer::reload()
{
LOG_INFO( "Reloading all folders" );
auto rootFolders = Folder::fetchRootFolders( m_ml );
for ( const auto f : rootFolders )
reloadFolder( std::move( f ) );
return true;
}
bool FsDiscoverer::reload( const std::string& entryPoint )
{
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
LOG_INFO( "Reloading folder ", entryPoint );
auto folder = Folder::fromMrl( m_ml, entryPoint );
if ( folder == nullptr )
{
LOG_ERROR( "Can't reload ", entryPoint, ": folder wasn't found in database" );
return false;
}
reloadFolder( std::move( folder ) );
return true;
}
void FsDiscoverer::checkFolder( std::shared_ptr<fs::IDirectory> currentFolderFs,
std::shared_ptr<Folder> currentFolder,
bool newFolder ) const
{
try
{
// We already know of this folder, though it may now contain a .nomedia file.
// In this case, simply delete the folder.
if ( hasDotNoMediaFile( *currentFolderFs ) )
{
if ( newFolder == false )
{
LOG_INFO( "Deleting folder ", currentFolderFs->mrl(), " due to a .nomedia file" );
m_ml->deleteFolder( *currentFolder );
}
else
LOG_INFO( "Ignoring folder ", currentFolderFs->mrl(), " due to a .nomedia file" );
return;
}
}
// Only check once for a system_error. They are bound to happen when we list the files/folders
// within, and hasDotMediaFile is the first place when this is done
catch ( std::system_error& ex )
{
LOG_WARN( "Failed to browse ", currentFolderFs->mrl(), ": ", ex.what() );
// Even when we're discovering a new folder, we want to rule out device removal as the cause of
// an IO error. If this is the cause, simply abort the discovery. All the folder we have
// discovered so far will be marked as non-present through sqlite hooks, and we'll resume the
// discovery when the device gets plugged back in
if ( currentFolderFs->device()->isRemovable() )
{
// If the device is removable, check if it was indeed removed.
LOG_INFO( "The device containing ", currentFolderFs->mrl(), " is removable. Checking for device removal..." );
m_ml->refreshDevices( *m_fsFactory );
// The device presence flag will be changed in place, so simply retest it
if ( currentFolderFs->device()->isPresent() == false )
throw DeviceRemovedException();
LOG_INFO( "Device was not removed" );
}
// However if the device isn't removable, we want to:
// - ignore it when we're discovering a new folder.
// - delete it when it was discovered in the past. This is likely to be due to a permission change
// as we would not check the folder if it wasn't present during the parent folder browsing
// but it might also be that we're checking an entry point.
// The error won't arise earlier, as we only perform IO when reading the folder from this function.
if ( newFolder == false )
{
// If we ever came across this folder, its content is now unaccessible: let's remove it.
m_ml->deleteFolder( *currentFolder );
}
return;
}
m_cb->onDiscoveryProgress( currentFolderFs->mrl() );
// Load the folders we already know of:
LOG_INFO( "Checking for modifications in ", currentFolderFs->mrl() );
// Don't try to fetch any potential sub folders if the folder was freshly added
std::vector<std::shared_ptr<Folder>> subFoldersInDB;
if ( newFolder == false )
subFoldersInDB = currentFolder->folders();
for ( const auto& subFolder : currentFolderFs->dirs() )
{
auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [&subFolder](const std::shared_ptr<Folder>& f) {
return f->mrl() == subFolder->mrl();
});
// We don't know this folder, it's a new one
if ( it == end( subFoldersInDB ) )
{
if ( hasDotNoMediaFile( *subFolder ) )
{
LOG_INFO( "Ignoring folder with a .nomedia file" );
continue;
}
LOG_INFO( "New folder detected: ", subFolder->mrl() );
try
{
addFolder( subFolder, currentFolder.get() );
continue;
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
// Best attempt to detect a foreign key violation, indicating the parent folders have been
// deleted due to blacklisting
if ( strstr( ex.what(), "foreign key" ) != NULL )
{
LOG_WARN( "Creation of a folder failed because the parent is non existing: ", ex.what(),
". Assuming it was deleted due to blacklisting" );
return;
}
LOG_WARN( "Creation of a duplicated folder failed: ", ex.what(), ". Assuming it was blacklisted" );
continue;
}
}
auto folderInDb = *it;
// In any case, check for modifications, as a change related to a mountpoint might
// not update the folder modification date.
// Also, relying on the modification date probably isn't portable
checkFolder( subFolder, folderInDb, false );
subFoldersInDB.erase( it );
}
// Now all folders we had in DB but haven't seen from the FS must have been deleted.
for ( auto f : subFoldersInDB )
{
LOG_INFO( "Folder ", f->mrl(), " not found in FS, deleting it" );
m_ml->deleteFolder( *f );
}
checkFiles( currentFolderFs, currentFolder );
LOG_INFO( "Done checking subfolders in ", currentFolderFs->mrl() );
}
void FsDiscoverer::checkFiles( std::shared_ptr<fs::IDirectory> parentFolderFs,
std::shared_ptr<Folder> parentFolder ) const
{
LOG_INFO( "Checking file in ", parentFolderFs->mrl() );
static const std::string req = "SELECT * FROM " + policy::FileTable::Name
+ " WHERE folder_id = ?";
auto files = File::fetchAll<File>( m_ml, req, parentFolder->id() );
std::vector<std::shared_ptr<fs::IFile>> filesToAdd;
std::vector<std::shared_ptr<File>> filesToRemove;
for ( const auto& fileFs: parentFolderFs->files() )
{
auto it = std::find_if( begin( files ), end( files ), [fileFs](const std::shared_ptr<File>& f) {
return f->mrl() == fileFs->mrl();
});
if ( it == end( files ) )
{
if ( MediaLibrary::isExtensionSupported( fileFs->extension().c_str() ) == true )
filesToAdd.push_back( fileFs );
continue;
}
if ( fileFs->lastModificationDate() == (*it)->lastModificationDate() )
{
// Unchanged file
files.erase( it );
continue;
}
auto& file = (*it);
LOG_INFO( "Forcing file refresh ", fileFs->mrl() );
// Pre-cache the file's media, since we need it to remove. However, better doing it
// out of a write context, since that way, other threads can also read the database.
file->media();
filesToRemove.push_back( std::move( file ) );
filesToAdd.push_back( fileFs );
files.erase( it );
}
using FilesT = decltype( files );
using FilesToRemoveT = decltype( filesToRemove );
using FilesToAddT = decltype( filesToAdd );
sqlite::Tools::withRetries( 3, [this, &parentFolder, &parentFolderFs]
( FilesT files, FilesToAddT filesToAdd, FilesToRemoveT filesToRemove ) {
auto t = m_ml->getConn()->newTransaction();
for ( auto file : files )
{
LOG_INFO( "File ", file->mrl(), " not found on filesystem, deleting it" );
auto media = file->media();
if ( media != nullptr && media->isDeleted() == false )
media->removeFile( *file );
else if ( file->isDeleted() == false )
{
// This is unexpected, as the file should have been deleted when the media was
// removed.
LOG_WARN( "Deleting a file without an associated media." );
file->destroy();
}
}
for ( auto& f : filesToRemove )
{
auto media = f->media();
if ( media != nullptr )
media->removeFile( *f );
else
{
// If there is no media associated with this file, the file had to be removed through
// a trigger
assert( f->isDeleted() );
}
}
// Insert all files at once to avoid SQL write contention
for ( auto& p : filesToAdd )
m_ml->addFile( p, parentFolder, parentFolderFs );
t->commit();
LOG_INFO( "Done checking files in ", parentFolderFs->mrl() );
}, std::move( files ), std::move( filesToAdd ), std::move( filesToRemove ) );
}
bool FsDiscoverer::hasDotNoMediaFile( const fs::IDirectory& directory )
{
const auto& files = directory.files();
return std::find_if( begin( files ), end( files ), []( const std::shared_ptr<fs::IFile>& file ){
return strcasecmp( file->name().c_str(), ".nomedia" ) == 0;
}) != end( files );
}
bool FsDiscoverer::addFolder( std::shared_ptr<fs::IDirectory> folder,
Folder* parentFolder ) const
{
auto deviceFs = folder->device();
// We are creating a folder, there has to be a device containing it.
assert( deviceFs != nullptr );
auto device = Device::fromUuid( m_ml, deviceFs->uuid() );
if ( device == nullptr )
{
LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
device = Device::create( m_ml, deviceFs->uuid(),
utils::file::scheme( folder->mrl() ),
deviceFs->isRemovable() );
}
auto f = Folder::create( m_ml, folder->mrl(),
parentFolder != nullptr ? parentFolder->id() : 0,
*device, *deviceFs );
if ( f == nullptr )
return false;
checkFolder( std::move( folder ), std::move( f ), true );
return true;
}
}
<commit_msg>FsDiscoverer: remove std::move() on const object<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "FsDiscoverer.h"
#include <algorithm>
#include <queue>
#include "factory/FileSystemFactory.h"
#include "filesystem/IDevice.h"
#include "Media.h"
#include "File.h"
#include "Device.h"
#include "Folder.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "utils/Filename.h"
namespace
{
class DeviceRemovedException : public std::runtime_error
{
public:
DeviceRemovedException() noexcept
: std::runtime_error( "A device was removed during the discovery" )
{
}
};
}
namespace medialibrary
{
FsDiscoverer::FsDiscoverer( std::shared_ptr<factory::IFileSystem> fsFactory, MediaLibrary* ml, IMediaLibraryCb* cb )
: m_ml( ml )
, m_fsFactory( fsFactory )
, m_cb( cb )
{
}
bool FsDiscoverer::discover( const std::string &entryPoint )
{
LOG_INFO( "Adding to discovery list: ", entryPoint );
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
std::shared_ptr<fs::IDirectory> fsDir = m_fsFactory->createDirectory( entryPoint );
// Otherwise, create a directory and check it for modifications
if ( fsDir == nullptr )
{
LOG_ERROR("Failed to create an IDirectory for ", entryPoint );
return false;
}
auto f = Folder::fromMrl( m_ml, fsDir->mrl() );
// If the folder exists, we assume it will be handled by reload()
if ( f != nullptr )
return true;
try
{
if ( hasDotNoMediaFile( *fsDir ) )
return true;
return addFolder( std::move( fsDir ), nullptr );
}
catch ( std::system_error& ex )
{
LOG_WARN( entryPoint, " discovery aborted because of a filesystem error: ", ex.what() );
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
LOG_WARN( entryPoint, " discovery aborted (assuming blacklisted folder): ", ex.what() );
}
catch ( DeviceRemovedException& )
{
// Simply ignore, the device has already been marked as removed and the DB updated accordingly
LOG_INFO( "Discovery of ", fsDir->mrl(), " was stopped after the device was removed" );
}
return true;
}
void FsDiscoverer::reloadFolder( std::shared_ptr<Folder> f )
{
auto folder = m_fsFactory->createDirectory( f->mrl() );
try
{
checkFolder( std::move( folder ), std::move( f ), false );
}
catch ( DeviceRemovedException& )
{
LOG_INFO( "Reloading of ", f->mrl(), " was stopped after the device was removed" );
}
}
bool FsDiscoverer::reload()
{
LOG_INFO( "Reloading all folders" );
auto rootFolders = Folder::fetchRootFolders( m_ml );
for ( const auto& f : rootFolders )
reloadFolder( f );
return true;
}
bool FsDiscoverer::reload( const std::string& entryPoint )
{
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
LOG_INFO( "Reloading folder ", entryPoint );
auto folder = Folder::fromMrl( m_ml, entryPoint );
if ( folder == nullptr )
{
LOG_ERROR( "Can't reload ", entryPoint, ": folder wasn't found in database" );
return false;
}
reloadFolder( std::move( folder ) );
return true;
}
void FsDiscoverer::checkFolder( std::shared_ptr<fs::IDirectory> currentFolderFs,
std::shared_ptr<Folder> currentFolder,
bool newFolder ) const
{
try
{
// We already know of this folder, though it may now contain a .nomedia file.
// In this case, simply delete the folder.
if ( hasDotNoMediaFile( *currentFolderFs ) )
{
if ( newFolder == false )
{
LOG_INFO( "Deleting folder ", currentFolderFs->mrl(), " due to a .nomedia file" );
m_ml->deleteFolder( *currentFolder );
}
else
LOG_INFO( "Ignoring folder ", currentFolderFs->mrl(), " due to a .nomedia file" );
return;
}
}
// Only check once for a system_error. They are bound to happen when we list the files/folders
// within, and hasDotMediaFile is the first place when this is done
catch ( std::system_error& ex )
{
LOG_WARN( "Failed to browse ", currentFolderFs->mrl(), ": ", ex.what() );
// Even when we're discovering a new folder, we want to rule out device removal as the cause of
// an IO error. If this is the cause, simply abort the discovery. All the folder we have
// discovered so far will be marked as non-present through sqlite hooks, and we'll resume the
// discovery when the device gets plugged back in
if ( currentFolderFs->device()->isRemovable() )
{
// If the device is removable, check if it was indeed removed.
LOG_INFO( "The device containing ", currentFolderFs->mrl(), " is removable. Checking for device removal..." );
m_ml->refreshDevices( *m_fsFactory );
// The device presence flag will be changed in place, so simply retest it
if ( currentFolderFs->device()->isPresent() == false )
throw DeviceRemovedException();
LOG_INFO( "Device was not removed" );
}
// However if the device isn't removable, we want to:
// - ignore it when we're discovering a new folder.
// - delete it when it was discovered in the past. This is likely to be due to a permission change
// as we would not check the folder if it wasn't present during the parent folder browsing
// but it might also be that we're checking an entry point.
// The error won't arise earlier, as we only perform IO when reading the folder from this function.
if ( newFolder == false )
{
// If we ever came across this folder, its content is now unaccessible: let's remove it.
m_ml->deleteFolder( *currentFolder );
}
return;
}
m_cb->onDiscoveryProgress( currentFolderFs->mrl() );
// Load the folders we already know of:
LOG_INFO( "Checking for modifications in ", currentFolderFs->mrl() );
// Don't try to fetch any potential sub folders if the folder was freshly added
std::vector<std::shared_ptr<Folder>> subFoldersInDB;
if ( newFolder == false )
subFoldersInDB = currentFolder->folders();
for ( const auto& subFolder : currentFolderFs->dirs() )
{
auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [&subFolder](const std::shared_ptr<Folder>& f) {
return f->mrl() == subFolder->mrl();
});
// We don't know this folder, it's a new one
if ( it == end( subFoldersInDB ) )
{
if ( hasDotNoMediaFile( *subFolder ) )
{
LOG_INFO( "Ignoring folder with a .nomedia file" );
continue;
}
LOG_INFO( "New folder detected: ", subFolder->mrl() );
try
{
addFolder( subFolder, currentFolder.get() );
continue;
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
// Best attempt to detect a foreign key violation, indicating the parent folders have been
// deleted due to blacklisting
if ( strstr( ex.what(), "foreign key" ) != NULL )
{
LOG_WARN( "Creation of a folder failed because the parent is non existing: ", ex.what(),
". Assuming it was deleted due to blacklisting" );
return;
}
LOG_WARN( "Creation of a duplicated folder failed: ", ex.what(), ". Assuming it was blacklisted" );
continue;
}
}
auto folderInDb = *it;
// In any case, check for modifications, as a change related to a mountpoint might
// not update the folder modification date.
// Also, relying on the modification date probably isn't portable
checkFolder( subFolder, folderInDb, false );
subFoldersInDB.erase( it );
}
// Now all folders we had in DB but haven't seen from the FS must have been deleted.
for ( auto f : subFoldersInDB )
{
LOG_INFO( "Folder ", f->mrl(), " not found in FS, deleting it" );
m_ml->deleteFolder( *f );
}
checkFiles( currentFolderFs, currentFolder );
LOG_INFO( "Done checking subfolders in ", currentFolderFs->mrl() );
}
void FsDiscoverer::checkFiles( std::shared_ptr<fs::IDirectory> parentFolderFs,
std::shared_ptr<Folder> parentFolder ) const
{
LOG_INFO( "Checking file in ", parentFolderFs->mrl() );
static const std::string req = "SELECT * FROM " + policy::FileTable::Name
+ " WHERE folder_id = ?";
auto files = File::fetchAll<File>( m_ml, req, parentFolder->id() );
std::vector<std::shared_ptr<fs::IFile>> filesToAdd;
std::vector<std::shared_ptr<File>> filesToRemove;
for ( const auto& fileFs: parentFolderFs->files() )
{
auto it = std::find_if( begin( files ), end( files ), [fileFs](const std::shared_ptr<File>& f) {
return f->mrl() == fileFs->mrl();
});
if ( it == end( files ) )
{
if ( MediaLibrary::isExtensionSupported( fileFs->extension().c_str() ) == true )
filesToAdd.push_back( fileFs );
continue;
}
if ( fileFs->lastModificationDate() == (*it)->lastModificationDate() )
{
// Unchanged file
files.erase( it );
continue;
}
auto& file = (*it);
LOG_INFO( "Forcing file refresh ", fileFs->mrl() );
// Pre-cache the file's media, since we need it to remove. However, better doing it
// out of a write context, since that way, other threads can also read the database.
file->media();
filesToRemove.push_back( std::move( file ) );
filesToAdd.push_back( fileFs );
files.erase( it );
}
using FilesT = decltype( files );
using FilesToRemoveT = decltype( filesToRemove );
using FilesToAddT = decltype( filesToAdd );
sqlite::Tools::withRetries( 3, [this, &parentFolder, &parentFolderFs]
( FilesT files, FilesToAddT filesToAdd, FilesToRemoveT filesToRemove ) {
auto t = m_ml->getConn()->newTransaction();
for ( auto file : files )
{
LOG_INFO( "File ", file->mrl(), " not found on filesystem, deleting it" );
auto media = file->media();
if ( media != nullptr && media->isDeleted() == false )
media->removeFile( *file );
else if ( file->isDeleted() == false )
{
// This is unexpected, as the file should have been deleted when the media was
// removed.
LOG_WARN( "Deleting a file without an associated media." );
file->destroy();
}
}
for ( auto& f : filesToRemove )
{
auto media = f->media();
if ( media != nullptr )
media->removeFile( *f );
else
{
// If there is no media associated with this file, the file had to be removed through
// a trigger
assert( f->isDeleted() );
}
}
// Insert all files at once to avoid SQL write contention
for ( auto& p : filesToAdd )
m_ml->addFile( p, parentFolder, parentFolderFs );
t->commit();
LOG_INFO( "Done checking files in ", parentFolderFs->mrl() );
}, std::move( files ), std::move( filesToAdd ), std::move( filesToRemove ) );
}
bool FsDiscoverer::hasDotNoMediaFile( const fs::IDirectory& directory )
{
const auto& files = directory.files();
return std::find_if( begin( files ), end( files ), []( const std::shared_ptr<fs::IFile>& file ){
return strcasecmp( file->name().c_str(), ".nomedia" ) == 0;
}) != end( files );
}
bool FsDiscoverer::addFolder( std::shared_ptr<fs::IDirectory> folder,
Folder* parentFolder ) const
{
auto deviceFs = folder->device();
// We are creating a folder, there has to be a device containing it.
assert( deviceFs != nullptr );
auto device = Device::fromUuid( m_ml, deviceFs->uuid() );
if ( device == nullptr )
{
LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
device = Device::create( m_ml, deviceFs->uuid(),
utils::file::scheme( folder->mrl() ),
deviceFs->isRemovable() );
}
auto f = Folder::create( m_ml, folder->mrl(),
parentFolder != nullptr ? parentFolder->id() : 0,
*device, *deviceFs );
if ( f == nullptr )
return false;
checkFolder( std::move( folder ), std::move( f ), true );
return true;
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "FsDiscoverer.h"
#include <algorithm>
#include <queue>
#include "factory/FileSystemFactory.h"
#include "filesystem/IDevice.h"
#include "Media.h"
#include "File.h"
#include "Device.h"
#include "Folder.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "utils/Filename.h"
namespace medialibrary
{
FsDiscoverer::FsDiscoverer( std::shared_ptr<factory::IFileSystem> fsFactory, MediaLibrary* ml, IMediaLibraryCb* cb )
: m_ml( ml )
, m_fsFactory( fsFactory )
, m_cb( cb )
{
}
bool FsDiscoverer::discover( const std::string &entryPoint )
{
LOG_INFO( "Adding to discovery list: ", entryPoint );
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
std::shared_ptr<fs::IDirectory> fsDir = m_fsFactory->createDirectory( entryPoint );
// Otherwise, create a directory and check it for modifications
if ( fsDir == nullptr )
{
LOG_ERROR("Failed to create an IDirectory for ", entryPoint );
return false;
}
auto f = Folder::fromMrl( m_ml, fsDir->mrl() );
// If the folder exists, we assume it will be handled by reload()
if ( f != nullptr )
return true;
try
{
if ( hasDotNoMediaFile( *fsDir ) )
return true;
return addFolder( *fsDir, nullptr );
}
catch ( std::system_error& ex )
{
LOG_WARN( entryPoint, " discovery aborted because of a filesystem error: ", ex.what() );
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
LOG_WARN( entryPoint, " discovery aborted (assuming blacklisted folder): ", ex.what() );
}
return true;
}
bool FsDiscoverer::reload()
{
LOG_INFO( "Reloading all folders" );
// Start by checking if previously known devices have been plugged/unplugged
if ( checkDevices() == false )
{
LOG_ERROR( "Refusing to reloading files with no storage device" );
return false;
}
auto rootFolders = Folder::fetchRootFolders( m_ml );
for ( const auto& f : rootFolders )
{
auto folder = m_fsFactory->createDirectory( f->mrl() );
if ( folder == nullptr )
{
LOG_INFO( "Removing folder ", f->mrl() );
m_ml->deleteFolder( *f );
continue;
}
checkFolder( *folder, *f, false );
}
return true;
}
bool FsDiscoverer::reload( const std::string& entryPoint )
{
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
LOG_INFO( "Reloading folder ", entryPoint );
// Start by checking if previously known devices have been plugged/unplugged
if ( checkDevices() == false )
{
LOG_ERROR( "Refusing to reloading files with no storage device" );
return false;
}
auto folder = Folder::fromMrl( m_ml, entryPoint );
if ( folder == nullptr )
{
LOG_ERROR( "Can't reload ", entryPoint, ": folder wasn't found in database" );
return false;
}
auto folderFs = m_fsFactory->createDirectory( folder->mrl() );
if ( folderFs == nullptr )
{
LOG_ERROR(" Failed to create a fs::IDirectory representing ", folder->mrl() );
return false;
}
checkFolder( *folderFs, *folder, false );
return true;
}
bool FsDiscoverer::checkDevices()
{
if ( m_fsFactory->refreshDevices() == false )
return false;
auto devices = Device::fetchAll( m_ml );
for ( auto& d : devices )
{
auto deviceFs = m_fsFactory->createDevice( d->uuid() );
auto fsDevicePresent = deviceFs != nullptr && deviceFs->isPresent();
if ( d->isPresent() != fsDevicePresent )
{
LOG_INFO( "Device ", d->uuid(), " changed presence state: ", d->isPresent(), " -> ", fsDevicePresent );
d->setPresent( fsDevicePresent );
}
else
{
LOG_INFO( "Device ", d->uuid(), " unchanged" );
}
}
return true;
}
void FsDiscoverer::checkFolder( fs::IDirectory& currentFolderFs, Folder& currentFolder, bool newFolder ) const
{
try
{
// We already know of this folder, though it may now contain a .nomedia file.
// In this case, simply delete the folder.
if ( hasDotNoMediaFile( currentFolderFs ) )
{
if ( newFolder == false )
{
LOG_INFO( "Deleting folder ", currentFolderFs.mrl(), " due to a .nomedia file" );
m_ml->deleteFolder( currentFolder );
}
return;
}
}
// Only check once for a system_error. They are bound to happen when we list the files/folders
// within, and hasDotMediaFile is the first place when this is done (except in case the root
// entry point fails to be browsed, in which case the failure would happen before)
catch ( std::system_error& ex )
{
LOG_WARN( "Failed to browse ", currentFolderFs.mrl(), ": ", ex.what() );
if ( newFolder == false )
{
// If we ever came across this folder, its content is now unaccessible: let's remove it.
m_ml->deleteFolder( currentFolder );
}
return;
}
m_cb->onDiscoveryProgress( currentFolderFs.mrl() );
// Load the folders we already know of:
LOG_INFO( "Checking for modifications in ", currentFolderFs.mrl() );
// Don't try to fetch any potential sub folders if the folder was freshly added
std::vector<std::shared_ptr<Folder>> subFoldersInDB;
if ( newFolder == false )
subFoldersInDB = currentFolder.folders();
for ( const auto& subFolder : currentFolderFs.dirs() )
{
auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [&subFolder](const std::shared_ptr<Folder>& f) {
return f->mrl() == subFolder->mrl();
});
// We don't know this folder, it's a new one
if ( it == end( subFoldersInDB ) )
{
if ( hasDotNoMediaFile( *subFolder ) )
{
LOG_INFO( "Ignoring folder with a .nomedia file" );
continue;
}
LOG_INFO( "New folder detected: ", subFolder->mrl() );
try
{
addFolder( *subFolder, ¤tFolder );
continue;
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
// Best attempt to detect a foreign key violation, indicating the parent folders have been
// deleted due to blacklisting
if ( strstr( ex.what(), "foreign key" ) != NULL )
{
LOG_WARN( "Creation of a folder failed because the parent is non existing: ", ex.what(),
". Assuming it was deleted due to blacklisting" );
return;
}
LOG_WARN( "Creation of a duplicated folder failed: ", ex.what(), ". Assuming it was blacklisted" );
continue;
}
}
auto folderInDb = *it;
// In any case, check for modifications, as a change related to a mountpoint might
// not update the folder modification date.
// Also, relying on the modification date probably isn't portable
checkFolder( *subFolder, *folderInDb, false );
subFoldersInDB.erase( it );
}
// Now all folders we had in DB but haven't seen from the FS must have been deleted.
for ( auto f : subFoldersInDB )
{
LOG_INFO( "Folder ", f->mrl(), " not found in FS, deleting it" );
m_ml->deleteFolder( *f );
}
checkFiles( currentFolderFs, currentFolder );
LOG_INFO( "Done checking subfolders in ", currentFolderFs.mrl() );
}
void FsDiscoverer::checkFiles( fs::IDirectory& parentFolderFs, Folder& parentFolder ) const
{
LOG_INFO( "Checking file in ", parentFolderFs.mrl() );
static const std::string req = "SELECT * FROM " + policy::FileTable::Name
+ " WHERE folder_id = ?";
auto files = File::fetchAll<File>( m_ml, req, parentFolder.id() );
std::vector<std::shared_ptr<fs::IFile>> filesToAdd;
std::vector<std::shared_ptr<File>> filesToRemove;
for ( const auto& fileFs: parentFolderFs.files() )
{
auto it = std::find_if( begin( files ), end( files ), [fileFs](const std::shared_ptr<File>& f) {
return f->mrl() == fileFs->mrl();
});
if ( it == end( files ) )
{
filesToAdd.push_back( std::move( fileFs ) );
continue;
}
if ( fileFs->lastModificationDate() == (*it)->lastModificationDate() )
{
// Unchanged file
files.erase( it );
continue;
}
auto& file = (*it);
LOG_INFO( "Forcing file refresh ", fileFs->mrl() );
// Pre-cache the file's media, since we need it to remove. However, better doing it
// out of a write context, since that way, other threads can also read the database.
file->media();
filesToRemove.push_back( std::move( file ) );
filesToAdd.push_back( std::move( fileFs ) );
files.erase( it );
}
auto t = m_ml->getConn()->newTransaction();
for ( auto file : files )
{
LOG_INFO( "File ", file->mrl(), " not found on filesystem, deleting it" );
file->media()->removeFile( *file );
}
for ( auto& f : filesToRemove )
f->media()->removeFile( *f );
// Insert all files at once to avoid SQL write contention
for ( auto& p : filesToAdd )
m_ml->addFile( *p, parentFolder, parentFolderFs );
t->commit();
LOG_INFO( "Done checking files in ", parentFolderFs.mrl() );
}
bool FsDiscoverer::hasDotNoMediaFile( const fs::IDirectory& directory )
{
const auto& files = directory.files();
return std::find_if( begin( files ), end( files ), []( const std::shared_ptr<fs::IFile>& file ){
return file->name() == ".nomedia";
}) != end( files );
}
bool FsDiscoverer::addFolder( fs::IDirectory& folder, Folder* parentFolder ) const
{
auto deviceFs = folder.device();
// We are creating a folder, there has to be a device containing it.
assert( deviceFs != nullptr );
auto device = Device::fromUuid( m_ml, deviceFs->uuid() );
if ( device == nullptr )
{
LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
device = Device::create( m_ml, deviceFs->uuid(), utils::file::scheme( folder.mrl() ),
deviceFs->isRemovable() );
}
auto f = Folder::create( m_ml, folder.mrl(),
parentFolder != nullptr ? parentFolder->id() : 0,
*device, *deviceFs );
if ( f == nullptr )
return false;
checkFolder( folder, *f, true );
return true;
}
}
<commit_msg>FsDiscoverer: Avoid a potential corner case crash<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "FsDiscoverer.h"
#include <algorithm>
#include <queue>
#include "factory/FileSystemFactory.h"
#include "filesystem/IDevice.h"
#include "Media.h"
#include "File.h"
#include "Device.h"
#include "Folder.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "utils/Filename.h"
namespace medialibrary
{
FsDiscoverer::FsDiscoverer( std::shared_ptr<factory::IFileSystem> fsFactory, MediaLibrary* ml, IMediaLibraryCb* cb )
: m_ml( ml )
, m_fsFactory( fsFactory )
, m_cb( cb )
{
}
bool FsDiscoverer::discover( const std::string &entryPoint )
{
LOG_INFO( "Adding to discovery list: ", entryPoint );
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
std::shared_ptr<fs::IDirectory> fsDir = m_fsFactory->createDirectory( entryPoint );
// Otherwise, create a directory and check it for modifications
if ( fsDir == nullptr )
{
LOG_ERROR("Failed to create an IDirectory for ", entryPoint );
return false;
}
auto f = Folder::fromMrl( m_ml, fsDir->mrl() );
// If the folder exists, we assume it will be handled by reload()
if ( f != nullptr )
return true;
try
{
if ( hasDotNoMediaFile( *fsDir ) )
return true;
return addFolder( *fsDir, nullptr );
}
catch ( std::system_error& ex )
{
LOG_WARN( entryPoint, " discovery aborted because of a filesystem error: ", ex.what() );
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
LOG_WARN( entryPoint, " discovery aborted (assuming blacklisted folder): ", ex.what() );
}
return true;
}
bool FsDiscoverer::reload()
{
LOG_INFO( "Reloading all folders" );
// Start by checking if previously known devices have been plugged/unplugged
if ( checkDevices() == false )
{
LOG_ERROR( "Refusing to reloading files with no storage device" );
return false;
}
auto rootFolders = Folder::fetchRootFolders( m_ml );
for ( const auto& f : rootFolders )
{
auto folder = m_fsFactory->createDirectory( f->mrl() );
if ( folder == nullptr )
{
LOG_INFO( "Removing folder ", f->mrl() );
m_ml->deleteFolder( *f );
continue;
}
checkFolder( *folder, *f, false );
}
return true;
}
bool FsDiscoverer::reload( const std::string& entryPoint )
{
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
LOG_INFO( "Reloading folder ", entryPoint );
// Start by checking if previously known devices have been plugged/unplugged
if ( checkDevices() == false )
{
LOG_ERROR( "Refusing to reloading files with no storage device" );
return false;
}
auto folder = Folder::fromMrl( m_ml, entryPoint );
if ( folder == nullptr )
{
LOG_ERROR( "Can't reload ", entryPoint, ": folder wasn't found in database" );
return false;
}
auto folderFs = m_fsFactory->createDirectory( folder->mrl() );
if ( folderFs == nullptr )
{
LOG_ERROR(" Failed to create a fs::IDirectory representing ", folder->mrl() );
return false;
}
checkFolder( *folderFs, *folder, false );
return true;
}
bool FsDiscoverer::checkDevices()
{
if ( m_fsFactory->refreshDevices() == false )
return false;
auto devices = Device::fetchAll( m_ml );
for ( auto& d : devices )
{
auto deviceFs = m_fsFactory->createDevice( d->uuid() );
auto fsDevicePresent = deviceFs != nullptr && deviceFs->isPresent();
if ( d->isPresent() != fsDevicePresent )
{
LOG_INFO( "Device ", d->uuid(), " changed presence state: ", d->isPresent(), " -> ", fsDevicePresent );
d->setPresent( fsDevicePresent );
}
else
{
LOG_INFO( "Device ", d->uuid(), " unchanged" );
}
}
return true;
}
void FsDiscoverer::checkFolder( fs::IDirectory& currentFolderFs, Folder& currentFolder, bool newFolder ) const
{
try
{
// We already know of this folder, though it may now contain a .nomedia file.
// In this case, simply delete the folder.
if ( hasDotNoMediaFile( currentFolderFs ) )
{
if ( newFolder == false )
{
LOG_INFO( "Deleting folder ", currentFolderFs.mrl(), " due to a .nomedia file" );
m_ml->deleteFolder( currentFolder );
}
return;
}
}
// Only check once for a system_error. They are bound to happen when we list the files/folders
// within, and hasDotMediaFile is the first place when this is done (except in case the root
// entry point fails to be browsed, in which case the failure would happen before)
catch ( std::system_error& ex )
{
LOG_WARN( "Failed to browse ", currentFolderFs.mrl(), ": ", ex.what() );
if ( newFolder == false )
{
// If we ever came across this folder, its content is now unaccessible: let's remove it.
m_ml->deleteFolder( currentFolder );
}
return;
}
m_cb->onDiscoveryProgress( currentFolderFs.mrl() );
// Load the folders we already know of:
LOG_INFO( "Checking for modifications in ", currentFolderFs.mrl() );
// Don't try to fetch any potential sub folders if the folder was freshly added
std::vector<std::shared_ptr<Folder>> subFoldersInDB;
if ( newFolder == false )
subFoldersInDB = currentFolder.folders();
for ( const auto& subFolder : currentFolderFs.dirs() )
{
auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [&subFolder](const std::shared_ptr<Folder>& f) {
return f->mrl() == subFolder->mrl();
});
// We don't know this folder, it's a new one
if ( it == end( subFoldersInDB ) )
{
if ( hasDotNoMediaFile( *subFolder ) )
{
LOG_INFO( "Ignoring folder with a .nomedia file" );
continue;
}
LOG_INFO( "New folder detected: ", subFolder->mrl() );
try
{
addFolder( *subFolder, ¤tFolder );
continue;
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
// Best attempt to detect a foreign key violation, indicating the parent folders have been
// deleted due to blacklisting
if ( strstr( ex.what(), "foreign key" ) != NULL )
{
LOG_WARN( "Creation of a folder failed because the parent is non existing: ", ex.what(),
". Assuming it was deleted due to blacklisting" );
return;
}
LOG_WARN( "Creation of a duplicated folder failed: ", ex.what(), ". Assuming it was blacklisted" );
continue;
}
}
auto folderInDb = *it;
// In any case, check for modifications, as a change related to a mountpoint might
// not update the folder modification date.
// Also, relying on the modification date probably isn't portable
checkFolder( *subFolder, *folderInDb, false );
subFoldersInDB.erase( it );
}
// Now all folders we had in DB but haven't seen from the FS must have been deleted.
for ( auto f : subFoldersInDB )
{
LOG_INFO( "Folder ", f->mrl(), " not found in FS, deleting it" );
m_ml->deleteFolder( *f );
}
checkFiles( currentFolderFs, currentFolder );
LOG_INFO( "Done checking subfolders in ", currentFolderFs.mrl() );
}
void FsDiscoverer::checkFiles( fs::IDirectory& parentFolderFs, Folder& parentFolder ) const
{
LOG_INFO( "Checking file in ", parentFolderFs.mrl() );
static const std::string req = "SELECT * FROM " + policy::FileTable::Name
+ " WHERE folder_id = ?";
auto files = File::fetchAll<File>( m_ml, req, parentFolder.id() );
std::vector<std::shared_ptr<fs::IFile>> filesToAdd;
std::vector<std::shared_ptr<File>> filesToRemove;
for ( const auto& fileFs: parentFolderFs.files() )
{
auto it = std::find_if( begin( files ), end( files ), [fileFs](const std::shared_ptr<File>& f) {
return f->mrl() == fileFs->mrl();
});
if ( it == end( files ) )
{
filesToAdd.push_back( std::move( fileFs ) );
continue;
}
if ( fileFs->lastModificationDate() == (*it)->lastModificationDate() )
{
// Unchanged file
files.erase( it );
continue;
}
auto& file = (*it);
LOG_INFO( "Forcing file refresh ", fileFs->mrl() );
// Pre-cache the file's media, since we need it to remove. However, better doing it
// out of a write context, since that way, other threads can also read the database.
file->media();
filesToRemove.push_back( std::move( file ) );
filesToAdd.push_back( std::move( fileFs ) );
files.erase( it );
}
auto t = m_ml->getConn()->newTransaction();
for ( auto file : files )
{
LOG_INFO( "File ", file->mrl(), " not found on filesystem, deleting it" );
auto media = file->media();
if ( media != nullptr && media->isDeleted() == false )
media->removeFile( *file );
else if ( file->isDeleted() == false )
{
// This is unexpected, as the file should have been deleted when the media was
// removed.
LOG_WARN( "Deleting a file without an associated media." );
file->destroy();
}
}
for ( auto& f : filesToRemove )
f->media()->removeFile( *f );
// Insert all files at once to avoid SQL write contention
for ( auto& p : filesToAdd )
m_ml->addFile( *p, parentFolder, parentFolderFs );
t->commit();
LOG_INFO( "Done checking files in ", parentFolderFs.mrl() );
}
bool FsDiscoverer::hasDotNoMediaFile( const fs::IDirectory& directory )
{
const auto& files = directory.files();
return std::find_if( begin( files ), end( files ), []( const std::shared_ptr<fs::IFile>& file ){
return file->name() == ".nomedia";
}) != end( files );
}
bool FsDiscoverer::addFolder( fs::IDirectory& folder, Folder* parentFolder ) const
{
auto deviceFs = folder.device();
// We are creating a folder, there has to be a device containing it.
assert( deviceFs != nullptr );
auto device = Device::fromUuid( m_ml, deviceFs->uuid() );
if ( device == nullptr )
{
LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
device = Device::create( m_ml, deviceFs->uuid(), utils::file::scheme( folder.mrl() ),
deviceFs->isRemovable() );
}
auto f = Folder::create( m_ml, folder.mrl(),
parentFolder != nullptr ? parentFolder->id() : 0,
*device, *deviceFs );
if ( f == nullptr )
return false;
checkFolder( folder, *f, true );
return true;
}
}
<|endoftext|> |
<commit_before>#include "gl_core_4_4.h"
#include "Font.h"
#include <stdio.h>
#define STB_TRUETYPE_IMPLEMENTATION
#include <stb_truetype.h>
namespace aie {
Font::Font(const char* trueTypeFontFile, unsigned short fontHeight)
: m_glyphData(nullptr),
m_glHandle(0),
m_pixelBufferHandle(0),
m_textureWidth(0),
m_textureHeight(0) {
FILE* file = nullptr;
fopen_s(&file, trueTypeFontFile, "rb");
if (file != nullptr) {
unsigned char* ttf_buffer = new unsigned char[4096 * 1024];
fread(ttf_buffer, 1, 4096 * 1024, file);
fclose(file);
// determine size of texture image
m_textureWidth = fontHeight / 16 * 256;
m_textureHeight = fontHeight / 16 * 256;
if (fontHeight <= 16) {
m_textureWidth = 256;
m_textureHeight = 256;
}
if (m_textureWidth > 2048)
m_textureWidth = 2048;
if (m_textureHeight > 2048)
m_textureHeight = 2048;
glGenBuffers(1, &m_pixelBufferHandle);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, m_pixelBufferHandle);
glBufferData(GL_PIXEL_UNPACK_BUFFER, m_textureWidth * m_textureHeight, nullptr, GL_STREAM_COPY);
unsigned char* tempBitmapData = (GLubyte*)glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0,
m_textureWidth * m_textureHeight,
GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);
m_glyphData = new stbtt_bakedchar[256];
memset(m_glyphData, 0, sizeof(stbtt_bakedchar) * 256);
stbtt_BakeFontBitmap(ttf_buffer, 0, fontHeight, tempBitmapData, m_textureWidth, m_textureHeight, 0, 256, (stbtt_bakedchar*)m_glyphData);
glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
glGenTextures(1, &m_glHandle);
glBindTexture(GL_TEXTURE_2D, m_glHandle);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_R8, m_textureWidth, m_textureHeight);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_textureWidth, m_textureHeight, GL_RED, GL_UNSIGNED_BYTE, nullptr);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
delete[] ttf_buffer;
}
}
Font::~Font() {
delete[] (stbtt_bakedchar*)m_glyphData;
glDeleteTextures(1, &m_glHandle);
glDeleteBuffers(1, &m_pixelBufferHandle);
}
float Font::getStringWidth(const char* str) {
stbtt_aligned_quad Q = {};
float xPos = 0.0f;
float yPos = 0.0f;
while (*str != 0) {
stbtt_GetBakedQuad(
(stbtt_bakedchar*)m_glyphData,
m_textureWidth,
m_textureHeight,
(unsigned char)*str, &xPos, &yPos, &Q, 1);
str++;
}
// get the position of the last vert for the last character rendered
return Q.x1;
}
float Font::getStringHeight(const char* str) {
stbtt_aligned_quad Q = {};
float low = 9999999, high = -9999999;
float xPos = 0.0f;
float yPos = 0.0f;
while (*str != 0) {
stbtt_GetBakedQuad(
(stbtt_bakedchar*)m_glyphData,
m_textureWidth,
m_textureHeight,
(unsigned char)*str, &xPos, &yPos, &Q, 1);
low = low > Q.y0 ? Q.y0 : low;
high = high < Q.y1 ? Q.y1 : high;
str++;
}
return high - low;
}
void Font::getStringSize(const char* str, float& width, float& height) {
stbtt_aligned_quad Q = {};
float low = 9999999, high = -9999999;
float xPos = 0.0f;
float yPos = 0.0f;
while (*str != 0) {
stbtt_GetBakedQuad(
(stbtt_bakedchar*)m_glyphData,
m_textureWidth,
m_textureHeight,
(unsigned char)*str, &xPos, &yPos, &Q, 1);
low = low > Q.y0 ? Q.y0 : low;
high = high < Q.y1 ? Q.y1 : high;
str++;
}
height = high - low;
width = Q.x1;
}
void Font::getStringRectangle(const char* str, float& x0, float& y0, float& x1, float& y1) {
stbtt_aligned_quad Q = {};
y1 = 9999999, y0 = -9999999;
x0 = 9999999, x1 = -9999999;
float xPos = 0.0f;
float yPos = 0.0f;
while (*str != 0) {
stbtt_GetBakedQuad(
(stbtt_bakedchar*)m_glyphData,
m_textureWidth,
m_textureHeight,
(unsigned char)*str, &xPos, &yPos, &Q, 1);
y1 = y1 > Q.y0 ? Q.y0 : y1;
y0 = y0 < Q.y1 ? Q.y1 : y0;
x1 = x1 < Q.x1 ? Q.x1 : x1;
x0 = x0 > Q.x0 ? Q.x0 : x0;
str++;
}
y0 *= -1;
y1 *= -1;
}
} // namepace aie<commit_msg>swapped out glTexStorage2D for glTexImage2D to allow for backwards compatibility<commit_after>#include "gl_core_4_4.h"
#include "Font.h"
#include <stdio.h>
#define STB_TRUETYPE_IMPLEMENTATION
#include <stb_truetype.h>
namespace aie {
Font::Font(const char* trueTypeFontFile, unsigned short fontHeight)
: m_glyphData(nullptr),
m_glHandle(0),
m_pixelBufferHandle(0),
m_textureWidth(0),
m_textureHeight(0) {
FILE* file = nullptr;
fopen_s(&file, trueTypeFontFile, "rb");
if (file != nullptr) {
unsigned char* ttf_buffer = new unsigned char[4096 * 1024];
fread(ttf_buffer, 1, 4096 * 1024, file);
fclose(file);
// determine size of texture image
m_textureWidth = fontHeight / 16 * 256;
m_textureHeight = fontHeight / 16 * 256;
if (fontHeight <= 16) {
m_textureWidth = 256;
m_textureHeight = 256;
}
if (m_textureWidth > 2048)
m_textureWidth = 2048;
if (m_textureHeight > 2048)
m_textureHeight = 2048;
glGenBuffers(1, &m_pixelBufferHandle);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, m_pixelBufferHandle);
glBufferData(GL_PIXEL_UNPACK_BUFFER, m_textureWidth * m_textureHeight, nullptr, GL_STREAM_COPY);
unsigned char* tempBitmapData = (GLubyte*)glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0,
m_textureWidth * m_textureHeight,
GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);
m_glyphData = new stbtt_bakedchar[256];
memset(m_glyphData, 0, sizeof(stbtt_bakedchar) * 256);
stbtt_BakeFontBitmap(ttf_buffer, 0, fontHeight, tempBitmapData, m_textureWidth, m_textureHeight, 0, 256, (stbtt_bakedchar*)m_glyphData);
glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
glGenTextures(1, &m_glHandle);
glBindTexture(GL_TEXTURE_2D, m_glHandle);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, m_textureWidth, m_textureHeight, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
delete[] ttf_buffer;
}
}
Font::~Font() {
delete[] (stbtt_bakedchar*)m_glyphData;
glDeleteTextures(1, &m_glHandle);
glDeleteBuffers(1, &m_pixelBufferHandle);
}
float Font::getStringWidth(const char* str) {
stbtt_aligned_quad Q = {};
float xPos = 0.0f;
float yPos = 0.0f;
while (*str != 0) {
stbtt_GetBakedQuad(
(stbtt_bakedchar*)m_glyphData,
m_textureWidth,
m_textureHeight,
(unsigned char)*str, &xPos, &yPos, &Q, 1);
str++;
}
// get the position of the last vert for the last character rendered
return Q.x1;
}
float Font::getStringHeight(const char* str) {
stbtt_aligned_quad Q = {};
float low = 9999999, high = -9999999;
float xPos = 0.0f;
float yPos = 0.0f;
while (*str != 0) {
stbtt_GetBakedQuad(
(stbtt_bakedchar*)m_glyphData,
m_textureWidth,
m_textureHeight,
(unsigned char)*str, &xPos, &yPos, &Q, 1);
low = low > Q.y0 ? Q.y0 : low;
high = high < Q.y1 ? Q.y1 : high;
str++;
}
return high - low;
}
void Font::getStringSize(const char* str, float& width, float& height) {
stbtt_aligned_quad Q = {};
float low = 9999999, high = -9999999;
float xPos = 0.0f;
float yPos = 0.0f;
while (*str != 0) {
stbtt_GetBakedQuad(
(stbtt_bakedchar*)m_glyphData,
m_textureWidth,
m_textureHeight,
(unsigned char)*str, &xPos, &yPos, &Q, 1);
low = low > Q.y0 ? Q.y0 : low;
high = high < Q.y1 ? Q.y1 : high;
str++;
}
height = high - low;
width = Q.x1;
}
void Font::getStringRectangle(const char* str, float& x0, float& y0, float& x1, float& y1) {
stbtt_aligned_quad Q = {};
y1 = 9999999, y0 = -9999999;
x0 = 9999999, x1 = -9999999;
float xPos = 0.0f;
float yPos = 0.0f;
while (*str != 0) {
stbtt_GetBakedQuad(
(stbtt_bakedchar*)m_glyphData,
m_textureWidth,
m_textureHeight,
(unsigned char)*str, &xPos, &yPos, &Q, 1);
y1 = y1 > Q.y0 ? Q.y0 : y1;
y0 = y0 < Q.y1 ? Q.y1 : y0;
x1 = x1 < Q.x1 ? Q.x1 : x1;
x0 = x0 > Q.x0 ? Q.x0 : x0;
str++;
}
y0 *= -1;
y1 *= -1;
}
} // namepace aie<|endoftext|> |
<commit_before>#include "qt/editor_dialog.hpp"
#include "map/framework.hpp"
#include "search/result.hpp"
#include "indexer/classificator.hpp"
#include "indexer/feature.hpp"
#include "indexer/feature_algo.hpp"
#include "indexer/osm_editor.hpp"
#include "base/collection_cast.hpp"
#include "std/set.hpp"
#include "std/vector.hpp"
#include <QtWidgets/QComboBox>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QVBoxLayout>
#include <QtCore/QSignalMapper>
using feature::Metadata;
constexpr char const * kStreetObjectName = "addr:street";
constexpr char const * kHouseNumberObjectName = "addr:housenumber";
EditorDialog::EditorDialog(QWidget * parent, FeatureType const & feature, Framework & frm) : QDialog(parent)
{
osm::Editor & editor = osm::Editor::Instance();
QVBoxLayout * vLayout = new QVBoxLayout();
// Zero uneditable row: coordinates.
ms::LatLon const ll = MercatorBounds::ToLatLon(feature::GetCenter(feature));
QHBoxLayout * coordinatesRow = new QHBoxLayout();
coordinatesRow->addWidget(new QLabel("Latitude, Longitude:"));
QLabel * coords = new QLabel(QString::fromStdString(strings::to_string_dac(ll.lat, 6) +
"," + strings::to_string_dac(ll.lon, 6)));
coords->setTextInteractionFlags(Qt::TextSelectableByMouse);
coordinatesRow->addWidget(coords);
vLayout->addLayout(coordinatesRow);
// First uneditable row: feature types.
string strTypes;
feature.ForEachType([&strTypes](uint32_t type)
{
strTypes += classif().GetReadableObjectName(type) + " ";
});
QHBoxLayout * typesRow = new QHBoxLayout();
typesRow->addWidget(new QLabel("Types:"));
typesRow->addWidget(new QLabel(QString::fromStdString(strTypes)));
vLayout->addLayout(typesRow);
bool const readOnlyName = !editor.IsNameEditable(feature);
// Rows block: Name(s) label(s) and text input.
char const * defaultLangStr = StringUtf8Multilang::GetLangByCode(StringUtf8Multilang::DEFAULT_CODE);
// Default name editor is always displayed, even if feature name is empty.
QHBoxLayout * defaultNameRow = new QHBoxLayout();
defaultNameRow->addWidget(new QLabel(QString("name")));
QLineEdit * defaultNamelineEdit = new QLineEdit();
defaultNamelineEdit->setReadOnly(readOnlyName);
defaultNamelineEdit->setObjectName(defaultLangStr);
defaultNameRow->addWidget(defaultNamelineEdit);
vLayout->addLayout(defaultNameRow);
feature.ForEachNameRef([&](int8_t langCode, string const & name) -> bool
{
if (langCode == StringUtf8Multilang::DEFAULT_CODE)
defaultNamelineEdit->setText(QString::fromStdString(name));
else
{
QHBoxLayout * nameRow = new QHBoxLayout();
char const * langStr = StringUtf8Multilang::GetLangByCode(langCode);
nameRow->addWidget(new QLabel(QString("name:") + langStr));
QLineEdit * lineEditName = new QLineEdit(QString::fromStdString(name));
lineEditName->setReadOnly(readOnlyName);
lineEditName->setObjectName(langStr);
nameRow->addWidget(lineEditName);
vLayout->addLayout(nameRow);
}
return true; // true is needed to enumerate all languages.
});
// Address rows.
bool const readOnlyAddress = !editor.IsAddressEditable(feature);
vector<string> nearbyStreets = frm.GetNearbyFeatureStreets(feature);
// If feature does not have a specified street, display empty combo box.
search::AddressInfo const info = frm.GetFeatureAddressInfo(feature);
if (info.m_street.empty())
nearbyStreets.insert(nearbyStreets.begin(), "");
QHBoxLayout * streetRow = new QHBoxLayout();
streetRow->addWidget(new QLabel(QString(kStreetObjectName)));
QComboBox * cmb = new QComboBox();
for (auto const & street : nearbyStreets)
cmb->addItem(street.c_str());
cmb->setEditable(!readOnlyAddress);
cmb->setEnabled(!readOnlyAddress);
cmb->setObjectName(kStreetObjectName);
streetRow->addWidget(cmb) ;
vLayout->addLayout(streetRow);
QHBoxLayout * houseRow = new QHBoxLayout();
houseRow->addWidget(new QLabel(QString(kHouseNumberObjectName)));
QLineEdit * houseLineEdit = new QLineEdit();
houseLineEdit->setText(info.m_house.c_str());
houseLineEdit->setReadOnly(readOnlyAddress);
houseLineEdit->setObjectName(kHouseNumberObjectName);
houseRow->addWidget(houseLineEdit);
vLayout->addLayout(houseRow);
// All metadata rows.
QVBoxLayout * metaRows = new QVBoxLayout();
vector<Metadata::EType> const editableMetadataFields = editor.EditableMetadataForType(feature);
for (Metadata::EType const field : editableMetadataFields)
{
QString const fieldName = QString::fromStdString(DebugPrint(field));
QHBoxLayout * fieldRow = new QHBoxLayout();
fieldRow->addWidget(new QLabel(fieldName));
QLineEdit * lineEdit = new QLineEdit(QString::fromStdString(feature.GetMetadata().Get(field)));
// Mark line editor to query it's text value when editing is finished.
lineEdit->setObjectName(fieldName);
fieldRow->addWidget(lineEdit);
metaRows->addLayout(fieldRow);
}
vLayout->addLayout(metaRows);
// Dialog buttons.
QDialogButtonBox * buttonBox = new QDialogButtonBox(
QDialogButtonBox::Cancel | QDialogButtonBox::Save);
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
// Delete button should send custom int return value from dialog.
QPushButton * deletePOIButton = new QPushButton("Delete POI");
QSignalMapper * signalMapper = new QSignalMapper();
connect(deletePOIButton, SIGNAL(clicked()), signalMapper, SLOT(map()));
signalMapper->setMapping(deletePOIButton, QDialogButtonBox::DestructiveRole);
connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(done(int)));
buttonBox->addButton(deletePOIButton, QDialogButtonBox::DestructiveRole);
QHBoxLayout * buttonsRowLayout = new QHBoxLayout();
buttonsRowLayout->addWidget(buttonBox);
vLayout->addLayout(buttonsRowLayout);
setLayout(vLayout);
setWindowTitle("POI Editor");
}
StringUtf8Multilang EditorDialog::GetEditedNames() const
{
StringUtf8Multilang names;
for (int8_t langCode = StringUtf8Multilang::DEFAULT_CODE; langCode < StringUtf8Multilang::MAX_SUPPORTED_LANGUAGES; ++langCode)
{
QLineEdit * le = findChild<QLineEdit *>(StringUtf8Multilang::GetLangByCode(langCode));
if (!le)
continue;
string const name = le->text().toStdString();
if (!name.empty())
names.AddString(langCode, name);
}
return names;
}
Metadata EditorDialog::GetEditedMetadata() const
{
Metadata metadata;
for (int type = Metadata::FMD_CUISINE; type < Metadata::FMD_COUNT; ++type)
{
QLineEdit * editor = findChild<QLineEdit *>(QString::fromStdString(DebugPrint(static_cast<Metadata::EType>(type))));
if (editor)
metadata.Set(static_cast<Metadata::EType>(type), editor->text().toStdString());
}
return metadata;
}
string EditorDialog::GetEditedStreet() const
{
QComboBox const * cmb = findChild<QComboBox *>();
if (cmb->count())
return cmb->itemText(0).toStdString();
return string();
}
string EditorDialog::GetEditedHouseNumber() const
{
return findChild<QLineEdit *>(kHouseNumberObjectName)->text().toStdString();
}
<commit_msg>[qt][editor] Correctly return edited street name from combo box.<commit_after>#include "qt/editor_dialog.hpp"
#include "map/framework.hpp"
#include "search/result.hpp"
#include "indexer/classificator.hpp"
#include "indexer/feature.hpp"
#include "indexer/feature_algo.hpp"
#include "indexer/osm_editor.hpp"
#include "base/collection_cast.hpp"
#include "std/set.hpp"
#include "std/vector.hpp"
#include <QtWidgets/QComboBox>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QVBoxLayout>
#include <QtCore/QSignalMapper>
using feature::Metadata;
constexpr char const * kStreetObjectName = "addr:street";
constexpr char const * kHouseNumberObjectName = "addr:housenumber";
EditorDialog::EditorDialog(QWidget * parent, FeatureType const & feature, Framework & frm) : QDialog(parent)
{
osm::Editor & editor = osm::Editor::Instance();
QVBoxLayout * vLayout = new QVBoxLayout();
// Zero uneditable row: coordinates.
ms::LatLon const ll = MercatorBounds::ToLatLon(feature::GetCenter(feature));
QHBoxLayout * coordinatesRow = new QHBoxLayout();
coordinatesRow->addWidget(new QLabel("Latitude, Longitude:"));
QLabel * coords = new QLabel(QString::fromStdString(strings::to_string_dac(ll.lat, 6) +
"," + strings::to_string_dac(ll.lon, 6)));
coords->setTextInteractionFlags(Qt::TextSelectableByMouse);
coordinatesRow->addWidget(coords);
vLayout->addLayout(coordinatesRow);
// First uneditable row: feature types.
string strTypes;
feature.ForEachType([&strTypes](uint32_t type)
{
strTypes += classif().GetReadableObjectName(type) + " ";
});
QHBoxLayout * typesRow = new QHBoxLayout();
typesRow->addWidget(new QLabel("Types:"));
typesRow->addWidget(new QLabel(QString::fromStdString(strTypes)));
vLayout->addLayout(typesRow);
bool const readOnlyName = !editor.IsNameEditable(feature);
// Rows block: Name(s) label(s) and text input.
char const * defaultLangStr = StringUtf8Multilang::GetLangByCode(StringUtf8Multilang::DEFAULT_CODE);
// Default name editor is always displayed, even if feature name is empty.
QHBoxLayout * defaultNameRow = new QHBoxLayout();
defaultNameRow->addWidget(new QLabel(QString("name")));
QLineEdit * defaultNamelineEdit = new QLineEdit();
defaultNamelineEdit->setReadOnly(readOnlyName);
defaultNamelineEdit->setObjectName(defaultLangStr);
defaultNameRow->addWidget(defaultNamelineEdit);
vLayout->addLayout(defaultNameRow);
feature.ForEachNameRef([&](int8_t langCode, string const & name) -> bool
{
if (langCode == StringUtf8Multilang::DEFAULT_CODE)
defaultNamelineEdit->setText(QString::fromStdString(name));
else
{
QHBoxLayout * nameRow = new QHBoxLayout();
char const * langStr = StringUtf8Multilang::GetLangByCode(langCode);
nameRow->addWidget(new QLabel(QString("name:") + langStr));
QLineEdit * lineEditName = new QLineEdit(QString::fromStdString(name));
lineEditName->setReadOnly(readOnlyName);
lineEditName->setObjectName(langStr);
nameRow->addWidget(lineEditName);
vLayout->addLayout(nameRow);
}
return true; // true is needed to enumerate all languages.
});
// Address rows.
bool const readOnlyAddress = !editor.IsAddressEditable(feature);
vector<string> nearbyStreets = frm.GetNearbyFeatureStreets(feature);
// If feature does not have a specified street, display empty combo box.
search::AddressInfo const info = frm.GetFeatureAddressInfo(feature);
if (info.m_street.empty())
nearbyStreets.insert(nearbyStreets.begin(), "");
QHBoxLayout * streetRow = new QHBoxLayout();
streetRow->addWidget(new QLabel(QString(kStreetObjectName)));
QComboBox * cmb = new QComboBox();
for (auto const & street : nearbyStreets)
cmb->addItem(street.c_str());
cmb->setEditable(!readOnlyAddress);
cmb->setEnabled(!readOnlyAddress);
cmb->setObjectName(kStreetObjectName);
streetRow->addWidget(cmb) ;
vLayout->addLayout(streetRow);
QHBoxLayout * houseRow = new QHBoxLayout();
houseRow->addWidget(new QLabel(QString(kHouseNumberObjectName)));
QLineEdit * houseLineEdit = new QLineEdit();
houseLineEdit->setText(info.m_house.c_str());
houseLineEdit->setReadOnly(readOnlyAddress);
houseLineEdit->setObjectName(kHouseNumberObjectName);
houseRow->addWidget(houseLineEdit);
vLayout->addLayout(houseRow);
// All metadata rows.
QVBoxLayout * metaRows = new QVBoxLayout();
vector<Metadata::EType> const editableMetadataFields = editor.EditableMetadataForType(feature);
for (Metadata::EType const field : editableMetadataFields)
{
QString const fieldName = QString::fromStdString(DebugPrint(field));
QHBoxLayout * fieldRow = new QHBoxLayout();
fieldRow->addWidget(new QLabel(fieldName));
QLineEdit * lineEdit = new QLineEdit(QString::fromStdString(feature.GetMetadata().Get(field)));
// Mark line editor to query it's text value when editing is finished.
lineEdit->setObjectName(fieldName);
fieldRow->addWidget(lineEdit);
metaRows->addLayout(fieldRow);
}
vLayout->addLayout(metaRows);
// Dialog buttons.
QDialogButtonBox * buttonBox = new QDialogButtonBox(
QDialogButtonBox::Cancel | QDialogButtonBox::Save);
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
// Delete button should send custom int return value from dialog.
QPushButton * deletePOIButton = new QPushButton("Delete POI");
QSignalMapper * signalMapper = new QSignalMapper();
connect(deletePOIButton, SIGNAL(clicked()), signalMapper, SLOT(map()));
signalMapper->setMapping(deletePOIButton, QDialogButtonBox::DestructiveRole);
connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(done(int)));
buttonBox->addButton(deletePOIButton, QDialogButtonBox::DestructiveRole);
QHBoxLayout * buttonsRowLayout = new QHBoxLayout();
buttonsRowLayout->addWidget(buttonBox);
vLayout->addLayout(buttonsRowLayout);
setLayout(vLayout);
setWindowTitle("POI Editor");
}
StringUtf8Multilang EditorDialog::GetEditedNames() const
{
StringUtf8Multilang names;
for (int8_t langCode = StringUtf8Multilang::DEFAULT_CODE; langCode < StringUtf8Multilang::MAX_SUPPORTED_LANGUAGES; ++langCode)
{
QLineEdit * le = findChild<QLineEdit *>(StringUtf8Multilang::GetLangByCode(langCode));
if (!le)
continue;
string const name = le->text().toStdString();
if (!name.empty())
names.AddString(langCode, name);
}
return names;
}
Metadata EditorDialog::GetEditedMetadata() const
{
Metadata metadata;
for (int type = Metadata::FMD_CUISINE; type < Metadata::FMD_COUNT; ++type)
{
QLineEdit * editor = findChild<QLineEdit *>(QString::fromStdString(DebugPrint(static_cast<Metadata::EType>(type))));
if (editor)
metadata.Set(static_cast<Metadata::EType>(type), editor->text().toStdString());
}
return metadata;
}
string EditorDialog::GetEditedStreet() const
{
QComboBox const * cmb = findChild<QComboBox *>();
return cmb->currentText().toStdString();
}
string EditorDialog::GetEditedHouseNumber() const
{
return findChild<QLineEdit *>(kHouseNumberObjectName)->text().toStdString();
}
<|endoftext|> |
<commit_before>#include "QCodeEditor.h"
#include "xo/system/system_tools.h"
#include "xo/system/assert.h"
#include "xo/string/string_tools.h"
#include <QTextStream>
#include <QMessageBox>
#include <QFileDialog>
QCodeEditor::QCodeEditor( QWidget* parent ) :
QWidget( parent ),
textChangedFlag( false )
{
QVBoxLayout* verticalLayout = new QVBoxLayout( this );
verticalLayout->setContentsMargins( 0, 0, 0, 0 );
setLayout( verticalLayout );
textEdit = new QCodeTextEdit( this );
QFont font;
font.setFamily( QStringLiteral( "Consolas" ) );
font.setPointSize( 9 );
textEdit->setFont( font );
textEdit->setLineWrapMode( QPlainTextEdit::NoWrap );
textEdit->setTabStopWidth( 16 );
textEdit->setWordWrapMode( QTextOption::NoWrap );
verticalLayout->addWidget( textEdit );
connect( textEdit, SIGNAL( textChanged() ), this, SLOT( textEditChanged() ) );
}
QCodeEditor::~QCodeEditor()
{}
QString QCodeEditor::getPlainText() const
{
return textEdit->toPlainText();
}
void QCodeEditor::open( const QString& filename )
{
QCodeSyntaxHighlighter* xmlSyntaxHighlighter = new QCodeSyntaxHighlighter( textEdit->document(), QCodeSyntaxHighlighter::detectLanguage( filename ) );
QFile f( filename );
if ( f.open( QFile::ReadOnly | QFile::Text ) )
{
QTextStream str( &f );
QString data = str.readAll();
textEdit->setPlainText( data );
fileName = filename;
textChangedFlag = false;
}
else xo_error( "Could not open " + filename.toStdString() );
}
void QCodeEditor::openDialog( const QString& folder, const QString& fileTypes )
{
auto fn = QFileDialog::getOpenFileName( this, "Open File", folder, fileTypes );
if ( !fn.isEmpty() )
open( fn );
}
void QCodeEditor::save()
{
QFile file( fileName );
if ( !file.open( QIODevice::WriteOnly ) )
{
QMessageBox::critical( this, "Error writing file", "Could not open file " + fileName );
return;
}
else
{
QTextStream stream( &file );
stream << textEdit->toPlainText();
stream.flush();
file.close();
textChangedFlag = false;
}
}
void QCodeEditor::saveAs( const QString& fn )
{
if ( getFileFormat( fn ) != getFileFormat( fileName ) )
{
std::stringstream stri( textEdit->toPlainText().toStdString() );
xo::prop_node pn;
stri >> xo::prop_node_deserializer( getFileFormat( fileName ), pn );
std::stringstream stro;
stro << xo::prop_node_serializer( getFileFormat( fn ), pn );
QCodeSyntaxHighlighter* xmlSyntaxHighlighter = new QCodeSyntaxHighlighter( textEdit->document(), QCodeSyntaxHighlighter::detectLanguage( fn ) );
textEdit->setPlainText( QString( stro.str().c_str() ) );
}
fileName = fn;
save();
}
QString QCodeEditor::getTitle()
{
return QFileInfo( fileName ).fileName() + ( hasTextChanged() ? "*" : "" );
}
void QCodeEditor::textEditChanged()
{
if ( !textChangedFlag )
{
textChangedFlag = true;
emit textChanged();
}
}
xo::file_format QCodeEditor::getFileFormat( const QString& filename ) const
{
auto ext = xo::path( filename.toStdString() ).extension();
if ( ext == "xml" )
return xo::file_format::xml;
else if ( ext == "zml" )
return xo::file_format::zml;
else return xo::file_format::unknown;
}
//
// BasicXMLSyntaxHighlighter
//
QCodeSyntaxHighlighter::QCodeSyntaxHighlighter( QObject* parent, Language l ) : QSyntaxHighlighter( parent )
{
setLanguage( l );
}
QCodeSyntaxHighlighter::QCodeSyntaxHighlighter( QTextDocument* parent, Language l ) : QSyntaxHighlighter( parent )
{
setLanguage( l );
}
void QCodeSyntaxHighlighter::highlightBlock( const QString &text )
{
if ( language == XML )
{
// Special treatment for xml element regex as we use captured text to emulate lookbehind
int xmlElementIndex = m_xmlElementRegex.indexIn( text );
while ( xmlElementIndex >= 0 )
{
int matchedPos = m_xmlElementRegex.pos( 1 );
int matchedLength = m_xmlElementRegex.cap( 1 ).length();
setFormat( matchedPos, matchedLength, m_ElementFormat );
xmlElementIndex = m_xmlElementRegex.indexIn( text, matchedPos + matchedLength );
}
highlightByRegex( m_NumberFormat, m_NumberRegex, text );
highlightByRegex( m_AttributeFormat, m_xmlAttributeRegex, text );
}
else
{
highlightByRegex( m_NumberFormat, m_NumberRegex, text );
highlightByRegex( m_AttributeFormat, m_xmlAttributeRegex, text );
highlightByRegex( m_ElementFormat, m_xmlElementRegex, text );
}
// Highlight xml keywords *after* xml elements to fix any occasional / captured into the enclosing element
for ( auto& regex : m_xmlKeywordRegexes )
highlightByRegex( m_KeywordFormat, regex, text );
highlightByRegex( m_ValueFormat, m_xmlValueRegex, text );
highlightByRegex( m_SpecialFormat, m_SpecialRegex, text );
if ( language == ZML )
{
int i = m_xmlCommentRegex.indexIn( text );
while ( i >= 0 )
{
int quotes_before = 0;
for ( int x = 0; x <= i; ++x )
quotes_before += int( text[ x ] == '\"' );
if ( quotes_before % 2 == 0 )
{
setFormat( i, m_xmlCommentRegex.matchedLength(), m_CommentFormat );
break;
}
else i = m_xmlCommentRegex.indexIn( text, i + 1 );
}
}
else
{
highlightByRegex( m_CommentFormat, m_xmlCommentRegex, text );
}
}
void QCodeSyntaxHighlighter::highlightByRegex( const QTextCharFormat & format, const QRegExp & regex, const QString & text )
{
int index = regex.indexIn( text );
while ( index >= 0 )
{
int matchedLength = regex.matchedLength();
setFormat( index, matchedLength, format );
index = regex.indexIn( text, index + matchedLength );
}
}
void QCodeSyntaxHighlighter::setRegexes()
{
switch ( language )
{
case XML:
m_xmlElementRegex.setPattern( "<[\\s]*[/]?[\\s]*([^\\n]\\w*)(?=[\\s/>])" );
m_xmlAttributeRegex.setPattern( "\\w+(?=\\=)" );
m_xmlValueRegex.setPattern( "\"[^\\n\"]+\"(?=[\\s/>])" );
m_xmlCommentRegex.setPattern( "<!--[^\\n]*-->" );
m_SpecialRegex.setPattern( "/.^/" );
m_xmlKeywordRegexes = QList<QRegExp>() << QRegExp( "<\\?" ) << QRegExp( "/>" ) << QRegExp( ">" ) << QRegExp( "<" ) << QRegExp( "</" ) << QRegExp( "\\?>" );
break;
case ZML:
m_xmlElementRegex.setPattern( "\\w+\\s*\\=\\s*\\{" );
m_xmlAttributeRegex.setPattern( "\\w+\\s*(\\=)" );
m_xmlValueRegex.setPattern( "\"[^\\n\"]+\"" );
m_xmlCommentRegex.setPattern( ";[^\\n]*" );
m_SpecialRegex.setPattern( "#\\w+" );
m_xmlKeywordRegexes = QList<QRegExp>() << QRegExp( "\\{" ) << QRegExp( "\\}" ) << QRegExp( "\\[" ) << QRegExp( "\\]" ) << QRegExp( "\\=" );
break;
default:
xo_error( "Unsupported language" );
}
m_NumberRegex.setPattern( "\\b([-+]?[\\.\\d]+)" );
}
void QCodeSyntaxHighlighter::setFormats()
{
m_KeywordFormat.setForeground( Qt::darkGray );
m_ElementFormat.setForeground( Qt::darkBlue );
m_ElementFormat.setFontWeight( QFont::Bold );
m_AttributeFormat.setForeground( Qt::darkBlue );
//m_AttributeFormat.setFontWeight( QFont::Bold );
m_ValueFormat.setForeground( Qt::darkRed );
m_CommentFormat.setForeground( Qt::darkGreen );
m_CommentFormat.setFontItalic( true );
m_NumberFormat.setForeground( Qt::darkMagenta );
m_SpecialFormat.setForeground( Qt::blue );
m_SpecialFormat.setFontItalic( true );
m_SpecialFormat.setFontWeight( QFont::Bold );
}
void QCodeSyntaxHighlighter::setLanguage( Language l )
{
language = l;
setRegexes();
setFormats();
}
QCodeSyntaxHighlighter::Language QCodeSyntaxHighlighter::detectLanguage( const QString& filename )
{
auto ext = xo::path( filename.toStdString() ).extension();
if ( ext == "xml" )
return XML;
else if ( ext == "zml" )
return ZML;
else return ZML;
}
//
// QCodeTextEdit
//
QCodeTextEdit::QCodeTextEdit( QWidget* parent ) : QPlainTextEdit( parent )
{
lineNumberArea = new LineNumberArea( this );
connect( this, SIGNAL( blockCountChanged( int ) ), this, SLOT( updateLineNumberAreaWidth( int ) ) );
connect( this, SIGNAL( updateRequest( QRect, int ) ), this, SLOT( updateLineNumberArea( QRect, int ) ) );
updateLineNumberAreaWidth( 0 );
}
void QCodeTextEdit::lineNumberAreaPaintEvent( QPaintEvent *event )
{
QPainter painter( lineNumberArea );
painter.fillRect( event->rect(), Qt::lightGray );
QTextBlock block = firstVisibleBlock();
int blockNumber = block.blockNumber();
int top = (int)blockBoundingGeometry( block ).translated( contentOffset() ).top();
int bottom = top + (int)blockBoundingRect( block ).height();
while ( block.isValid() && top <= event->rect().bottom() ) {
if ( block.isVisible() && bottom >= event->rect().top() ) {
QString number = QString::number( blockNumber + 1 );
painter.setPen( Qt::black );
painter.drawText( 0, top, lineNumberArea->width() - 2, fontMetrics().height(),
Qt::AlignRight, number );
}
block = block.next();
top = bottom;
bottom = top + (int)blockBoundingRect( block ).height();
++blockNumber;
}
}
int QCodeTextEdit::lineNumberAreaWidth()
{
int digits = 1;
int max = qMax( 1, blockCount() );
while ( max >= 10 ) {
max /= 10;
++digits;
}
int space = 4 + fontMetrics().width( QLatin1Char( '9' ) ) * digits;
return space;
}
void QCodeTextEdit::updateLineNumberAreaWidth( int newBlockCount )
{
setViewportMargins( lineNumberAreaWidth(), 0, 0, 0 );
}
void QCodeTextEdit::updateLineNumberArea( const QRect& rect, int dy )
{
if ( dy )
lineNumberArea->scroll( 0, dy );
else
lineNumberArea->update( 0, rect.y(), lineNumberArea->width(), rect.height() );
if ( rect.contains( viewport()->rect() ) )
updateLineNumberAreaWidth( 0 );
}
void QCodeTextEdit::resizeEvent( QResizeEvent *event )
{
QPlainTextEdit::resizeEvent( event );
QRect cr = contentsRect();
lineNumberArea->setGeometry( QRect( cr.left(), cr.top(), lineNumberAreaWidth(), cr.height() ) );
}
void QCodeTextEdit::keyPressEvent( QKeyEvent *e )
{
if ( e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter )
{
auto line = textCursor().block().text().toStdString();
int tabs = 0;
while ( tabs < line.size() && line[ tabs ] == '\t' )
++tabs;
QPlainTextEdit::keyPressEvent( e );
QPlainTextEdit::insertPlainText( QString( tabs, '\t' ) );
}
else QPlainTextEdit::keyPressEvent( e );
}
<commit_msg>getFileFormat fix<commit_after>#include "QCodeEditor.h"
#include "xo/system/system_tools.h"
#include "xo/system/assert.h"
#include "xo/string/string_tools.h"
#include <QTextStream>
#include <QMessageBox>
#include <QFileDialog>
QCodeEditor::QCodeEditor( QWidget* parent ) :
QWidget( parent ),
textChangedFlag( false )
{
QVBoxLayout* verticalLayout = new QVBoxLayout( this );
verticalLayout->setContentsMargins( 0, 0, 0, 0 );
setLayout( verticalLayout );
textEdit = new QCodeTextEdit( this );
QFont font;
font.setFamily( QStringLiteral( "Consolas" ) );
font.setPointSize( 9 );
textEdit->setFont( font );
textEdit->setLineWrapMode( QPlainTextEdit::NoWrap );
textEdit->setTabStopWidth( 16 );
textEdit->setWordWrapMode( QTextOption::NoWrap );
verticalLayout->addWidget( textEdit );
connect( textEdit, SIGNAL( textChanged() ), this, SLOT( textEditChanged() ) );
}
QCodeEditor::~QCodeEditor()
{}
QString QCodeEditor::getPlainText() const
{
return textEdit->toPlainText();
}
void QCodeEditor::open( const QString& filename )
{
QCodeSyntaxHighlighter* xmlSyntaxHighlighter = new QCodeSyntaxHighlighter( textEdit->document(), QCodeSyntaxHighlighter::detectLanguage( filename ) );
QFile f( filename );
if ( f.open( QFile::ReadOnly | QFile::Text ) )
{
QTextStream str( &f );
QString data = str.readAll();
textEdit->setPlainText( data );
fileName = filename;
textChangedFlag = false;
}
else xo_error( "Could not open " + filename.toStdString() );
}
void QCodeEditor::openDialog( const QString& folder, const QString& fileTypes )
{
auto fn = QFileDialog::getOpenFileName( this, "Open File", folder, fileTypes );
if ( !fn.isEmpty() )
open( fn );
}
void QCodeEditor::save()
{
QFile file( fileName );
if ( !file.open( QIODevice::WriteOnly ) )
{
QMessageBox::critical( this, "Error writing file", "Could not open file " + fileName );
return;
}
else
{
QTextStream stream( &file );
stream << textEdit->toPlainText();
stream.flush();
file.close();
textChangedFlag = false;
}
}
void QCodeEditor::saveAs( const QString& fn )
{
if ( getFileFormat( fn ) != getFileFormat( fileName ) )
{
std::stringstream stri( textEdit->toPlainText().toStdString() );
xo::prop_node pn;
stri >> xo::prop_node_deserializer( getFileFormat( fileName ), pn );
std::stringstream stro;
stro << xo::prop_node_serializer( getFileFormat( fn ), pn );
QCodeSyntaxHighlighter* xmlSyntaxHighlighter = new QCodeSyntaxHighlighter( textEdit->document(), QCodeSyntaxHighlighter::detectLanguage( fn ) );
textEdit->setPlainText( QString( stro.str().c_str() ) );
}
fileName = fn;
save();
}
QString QCodeEditor::getTitle()
{
return QFileInfo( fileName ).fileName() + ( hasTextChanged() ? "*" : "" );
}
void QCodeEditor::textEditChanged()
{
if ( !textChangedFlag )
{
textChangedFlag = true;
emit textChanged();
}
}
xo::file_format QCodeEditor::getFileFormat( const QString& filename ) const
{
return xo::detect_file_format( xo::path( filename.toStdString() ) );
}
//
// BasicXMLSyntaxHighlighter
//
QCodeSyntaxHighlighter::QCodeSyntaxHighlighter( QObject* parent, Language l ) : QSyntaxHighlighter( parent )
{
setLanguage( l );
}
QCodeSyntaxHighlighter::QCodeSyntaxHighlighter( QTextDocument* parent, Language l ) : QSyntaxHighlighter( parent )
{
setLanguage( l );
}
void QCodeSyntaxHighlighter::highlightBlock( const QString &text )
{
if ( language == XML )
{
// Special treatment for xml element regex as we use captured text to emulate lookbehind
int xmlElementIndex = m_xmlElementRegex.indexIn( text );
while ( xmlElementIndex >= 0 )
{
int matchedPos = m_xmlElementRegex.pos( 1 );
int matchedLength = m_xmlElementRegex.cap( 1 ).length();
setFormat( matchedPos, matchedLength, m_ElementFormat );
xmlElementIndex = m_xmlElementRegex.indexIn( text, matchedPos + matchedLength );
}
highlightByRegex( m_NumberFormat, m_NumberRegex, text );
highlightByRegex( m_AttributeFormat, m_xmlAttributeRegex, text );
}
else
{
highlightByRegex( m_NumberFormat, m_NumberRegex, text );
highlightByRegex( m_AttributeFormat, m_xmlAttributeRegex, text );
highlightByRegex( m_ElementFormat, m_xmlElementRegex, text );
}
// Highlight xml keywords *after* xml elements to fix any occasional / captured into the enclosing element
for ( auto& regex : m_xmlKeywordRegexes )
highlightByRegex( m_KeywordFormat, regex, text );
highlightByRegex( m_ValueFormat, m_xmlValueRegex, text );
highlightByRegex( m_SpecialFormat, m_SpecialRegex, text );
if ( language == ZML )
{
int i = m_xmlCommentRegex.indexIn( text );
while ( i >= 0 )
{
int quotes_before = 0;
for ( int x = 0; x <= i; ++x )
quotes_before += int( text[ x ] == '\"' );
if ( quotes_before % 2 == 0 )
{
setFormat( i, m_xmlCommentRegex.matchedLength(), m_CommentFormat );
break;
}
else i = m_xmlCommentRegex.indexIn( text, i + 1 );
}
}
else
{
highlightByRegex( m_CommentFormat, m_xmlCommentRegex, text );
}
}
void QCodeSyntaxHighlighter::highlightByRegex( const QTextCharFormat & format, const QRegExp & regex, const QString & text )
{
int index = regex.indexIn( text );
while ( index >= 0 )
{
int matchedLength = regex.matchedLength();
setFormat( index, matchedLength, format );
index = regex.indexIn( text, index + matchedLength );
}
}
void QCodeSyntaxHighlighter::setRegexes()
{
switch ( language )
{
case XML:
m_xmlElementRegex.setPattern( "<[\\s]*[/]?[\\s]*([^\\n]\\w*)(?=[\\s/>])" );
m_xmlAttributeRegex.setPattern( "\\w+(?=\\=)" );
m_xmlValueRegex.setPattern( "\"[^\\n\"]+\"(?=[\\s/>])" );
m_xmlCommentRegex.setPattern( "<!--[^\\n]*-->" );
m_SpecialRegex.setPattern( "/.^/" );
m_xmlKeywordRegexes = QList<QRegExp>() << QRegExp( "<\\?" ) << QRegExp( "/>" ) << QRegExp( ">" ) << QRegExp( "<" ) << QRegExp( "</" ) << QRegExp( "\\?>" );
break;
case ZML:
m_xmlElementRegex.setPattern( "\\w+\\s*\\=\\s*\\{" );
m_xmlAttributeRegex.setPattern( "\\w+\\s*(\\=)" );
m_xmlValueRegex.setPattern( "\"[^\\n\"]+\"" );
m_xmlCommentRegex.setPattern( ";[^\\n]*" );
m_SpecialRegex.setPattern( "#\\w+" );
m_xmlKeywordRegexes = QList<QRegExp>() << QRegExp( "\\{" ) << QRegExp( "\\}" ) << QRegExp( "\\[" ) << QRegExp( "\\]" ) << QRegExp( "\\=" );
break;
default:
xo_error( "Unsupported language" );
}
m_NumberRegex.setPattern( "\\b([-+]?[\\.\\d]+)" );
}
void QCodeSyntaxHighlighter::setFormats()
{
m_KeywordFormat.setForeground( Qt::darkGray );
m_ElementFormat.setForeground( Qt::darkBlue );
m_ElementFormat.setFontWeight( QFont::Bold );
m_AttributeFormat.setForeground( Qt::darkBlue );
//m_AttributeFormat.setFontWeight( QFont::Bold );
m_ValueFormat.setForeground( Qt::darkRed );
m_CommentFormat.setForeground( Qt::darkGreen );
m_CommentFormat.setFontItalic( true );
m_NumberFormat.setForeground( Qt::darkMagenta );
m_SpecialFormat.setForeground( Qt::blue );
m_SpecialFormat.setFontItalic( true );
m_SpecialFormat.setFontWeight( QFont::Bold );
}
void QCodeSyntaxHighlighter::setLanguage( Language l )
{
language = l;
setRegexes();
setFormats();
}
QCodeSyntaxHighlighter::Language QCodeSyntaxHighlighter::detectLanguage( const QString& filename )
{
auto ext = xo::path( filename.toStdString() ).extension();
if ( ext == "xml" )
return XML;
else if ( ext == "zml" )
return ZML;
else return ZML;
}
//
// QCodeTextEdit
//
QCodeTextEdit::QCodeTextEdit( QWidget* parent ) : QPlainTextEdit( parent )
{
lineNumberArea = new LineNumberArea( this );
connect( this, SIGNAL( blockCountChanged( int ) ), this, SLOT( updateLineNumberAreaWidth( int ) ) );
connect( this, SIGNAL( updateRequest( QRect, int ) ), this, SLOT( updateLineNumberArea( QRect, int ) ) );
updateLineNumberAreaWidth( 0 );
}
void QCodeTextEdit::lineNumberAreaPaintEvent( QPaintEvent *event )
{
QPainter painter( lineNumberArea );
painter.fillRect( event->rect(), Qt::lightGray );
QTextBlock block = firstVisibleBlock();
int blockNumber = block.blockNumber();
int top = (int)blockBoundingGeometry( block ).translated( contentOffset() ).top();
int bottom = top + (int)blockBoundingRect( block ).height();
while ( block.isValid() && top <= event->rect().bottom() ) {
if ( block.isVisible() && bottom >= event->rect().top() ) {
QString number = QString::number( blockNumber + 1 );
painter.setPen( Qt::black );
painter.drawText( 0, top, lineNumberArea->width() - 2, fontMetrics().height(),
Qt::AlignRight, number );
}
block = block.next();
top = bottom;
bottom = top + (int)blockBoundingRect( block ).height();
++blockNumber;
}
}
int QCodeTextEdit::lineNumberAreaWidth()
{
int digits = 1;
int max = qMax( 1, blockCount() );
while ( max >= 10 ) {
max /= 10;
++digits;
}
int space = 4 + fontMetrics().width( QLatin1Char( '9' ) ) * digits;
return space;
}
void QCodeTextEdit::updateLineNumberAreaWidth( int newBlockCount )
{
setViewportMargins( lineNumberAreaWidth(), 0, 0, 0 );
}
void QCodeTextEdit::updateLineNumberArea( const QRect& rect, int dy )
{
if ( dy )
lineNumberArea->scroll( 0, dy );
else
lineNumberArea->update( 0, rect.y(), lineNumberArea->width(), rect.height() );
if ( rect.contains( viewport()->rect() ) )
updateLineNumberAreaWidth( 0 );
}
void QCodeTextEdit::resizeEvent( QResizeEvent *event )
{
QPlainTextEdit::resizeEvent( event );
QRect cr = contentsRect();
lineNumberArea->setGeometry( QRect( cr.left(), cr.top(), lineNumberAreaWidth(), cr.height() ) );
}
void QCodeTextEdit::keyPressEvent( QKeyEvent *e )
{
if ( e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter )
{
auto line = textCursor().block().text().toStdString();
int tabs = 0;
while ( tabs < line.size() && line[ tabs ] == '\t' )
++tabs;
QPlainTextEdit::keyPressEvent( e );
QPlainTextEdit::insertPlainText( QString( tabs, '\t' ) );
}
else QPlainTextEdit::keyPressEvent( e );
}
<|endoftext|> |
<commit_before>// Copyright 2012-2013 Samplecount S.L.
//
// 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 "Methcla/Exception.hpp"
#include "Methcla/Audio/SynthDef.hpp"
#include <boost/optional.hpp>
#include <iostream>
#include <limits>
#include <memory>
#include <utility>
using namespace boost;
using namespace Methcla::Audio;
using namespace std;
Methcla::Audio::FloatPort::FloatPort( Type type, uint32_t index, const char* symbol
, float minValue, float maxValue, float defaultValue )
: Port(type, index, symbol)
, m_minValue(isnan(minValue) ? -numeric_limits<float>::max() : minValue)
, m_maxValue(isnan(maxValue) ? numeric_limits<float>::max() : maxValue)
, m_defaultValue(isnan(defaultValue) ? 0 : defaultValue)
{ }
PluginLibrary::PluginLibrary(const Methcla_Library* lib, std::shared_ptr<Methcla::Plugin::Library> plugin)
: m_lib(lib)
, m_plugin(plugin)
{
}
PluginLibrary::~PluginLibrary()
{
if ((m_lib != nullptr) && (m_lib->destroy != nullptr)) {
m_lib->destroy(m_lib->handle);
}
}
SynthDef::SynthDef(const Methcla_SynthDef* synthDef)
: m_descriptor(synthDef)
, m_numAudioInputs(0)
, m_numAudioOutputs(0)
, m_numControlInputs(0)
, m_numControlOutputs(0)
{
Methcla_Port port;
std::memset(&port, 0, sizeof(port));
for (size_t i=0; m_descriptor->port(m_descriptor, i, &port); i++) {
switch (port.type) {
case kMethcla_AudioPort:
switch (port.direction) {
case kMethcla_Input:
m_ports.push_back(Port( Port::Type(Port::kAudio|Port::kInput)
, m_numAudioInputs
, "<unknown>" ));
m_numAudioInputs++;
break;
case kMethcla_Output:
m_ports.push_back(Port( Port::Type(Port::kAudio|Port::kOutput)
, m_numAudioOutputs
, "<unknown>" ));
m_numAudioOutputs++;
break;
}
break;
case kMethcla_ControlPort:
switch (port.direction) {
case kMethcla_Input:
m_ports.push_back(Port( Port::Type(Port::kControl|Port::kInput)
, m_numControlInputs
, "<unknown>" ));
m_numControlInputs++;
break;
case kMethcla_Output:
m_ports.push_back(Port( Port::Type(Port::kControl|Port::kOutput)
, m_numControlOutputs
, "<unknown>" ));
m_numControlOutputs++;
break;
}
}
}
std::cerr << "SynthDef " << uri() << " loaded (" << m_descriptor << "):" << std::endl
<< " instance size: " << instanceSize() << std::endl
<< " control inputs: " << numControlInputs() << std::endl
<< " control outputs: " << numControlOutputs() << std::endl
<< " audio inputs: " << numAudioInputs() << std::endl
<< " audio outputs: " << numAudioOutputs() << std::endl;
}
void PluginManager::loadPlugins(const Methcla_Host* host, const std::list<Methcla_LibraryFunction>& funcs)
{
for (auto f : funcs) {
const Methcla_Library* lib = f(host, ".");
if (lib != nullptr) {
m_libs.push_back(std::make_shared<PluginLibrary>(lib));
}
}
}
void PluginManager::loadPlugins(const Methcla_Host* host, const std::string& directory)
{
std::cout << "PluginManager::loadPlugins not yet implemented" << std::endl;
}
<commit_msg>Code reorganisation<commit_after>// Copyright 2012-2013 Samplecount S.L.
//
// 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 "Methcla/Exception.hpp"
#include "Methcla/Audio/SynthDef.hpp"
#include <boost/optional.hpp>
#include <iostream>
#include <limits>
#include <memory>
#include <utility>
using namespace boost;
using namespace Methcla::Audio;
using namespace std;
Methcla::Audio::FloatPort::FloatPort( Type type, uint32_t index, const char* symbol
, float minValue, float maxValue, float defaultValue )
: Port(type, index, symbol)
, m_minValue(isnan(minValue) ? -numeric_limits<float>::max() : minValue)
, m_maxValue(isnan(maxValue) ? numeric_limits<float>::max() : maxValue)
, m_defaultValue(isnan(defaultValue) ? 0 : defaultValue)
{ }
SynthDef::SynthDef(const Methcla_SynthDef* synthDef)
: m_descriptor(synthDef)
, m_numAudioInputs(0)
, m_numAudioOutputs(0)
, m_numControlInputs(0)
, m_numControlOutputs(0)
{
Methcla_Port port;
std::memset(&port, 0, sizeof(port));
for (size_t i=0; m_descriptor->port(m_descriptor, i, &port); i++) {
switch (port.type) {
case kMethcla_AudioPort:
switch (port.direction) {
case kMethcla_Input:
m_ports.push_back(Port( Port::Type(Port::kAudio|Port::kInput)
, m_numAudioInputs
, "<unknown>" ));
m_numAudioInputs++;
break;
case kMethcla_Output:
m_ports.push_back(Port( Port::Type(Port::kAudio|Port::kOutput)
, m_numAudioOutputs
, "<unknown>" ));
m_numAudioOutputs++;
break;
}
break;
case kMethcla_ControlPort:
switch (port.direction) {
case kMethcla_Input:
m_ports.push_back(Port( Port::Type(Port::kControl|Port::kInput)
, m_numControlInputs
, "<unknown>" ));
m_numControlInputs++;
break;
case kMethcla_Output:
m_ports.push_back(Port( Port::Type(Port::kControl|Port::kOutput)
, m_numControlOutputs
, "<unknown>" ));
m_numControlOutputs++;
break;
}
}
}
std::cerr << "SynthDef " << uri() << " loaded (" << m_descriptor << "):" << std::endl
<< " instance size: " << instanceSize() << std::endl
<< " control inputs: " << numControlInputs() << std::endl
<< " control outputs: " << numControlOutputs() << std::endl
<< " audio inputs: " << numAudioInputs() << std::endl
<< " audio outputs: " << numAudioOutputs() << std::endl;
}
PluginLibrary::PluginLibrary(const Methcla_Library* lib, std::shared_ptr<Methcla::Plugin::Library> plugin)
: m_lib(lib)
, m_plugin(plugin)
{
}
PluginLibrary::~PluginLibrary()
{
if ((m_lib != nullptr) && (m_lib->destroy != nullptr)) {
m_lib->destroy(m_lib);
}
}
void PluginManager::loadPlugins(const Methcla_Host* host, const std::list<Methcla_LibraryFunction>& funcs)
{
for (auto f : funcs) {
const Methcla_Library* lib = f(host, ".");
if (lib != nullptr) {
m_libs.push_back(std::make_shared<PluginLibrary>(lib));
}
}
}
void PluginManager::loadPlugins(const Methcla_Host* host, const std::string& directory)
{
std::cout << "PluginManager::loadPlugins not yet implemented" << std::endl;
}
<|endoftext|> |
<commit_before>#include <memory>
#include <SFCGAL/all.h>
#include <SFCGAL/algorithm/triangulate.h>
#include <SFCGAL/io/wkt.h>
#include <SFCGAL/io/WaveFrontObj.h>
using namespace SFCGAL ;
int main() {
std::string wkt( "MULTIPOLYGON(((17.6999999999534 21.2000000001863,0 5.70000000018626,4.19999999995343 0,10.4000000000233 4.79999999981374,22.4000000000233 13.2999999998137,17.6999999999534 21.2000000001863)))" );
std::auto_ptr< Geometry > g( io::readWkt( wkt ) ) ;
io::WaveFrontObj obj;
obj.addGeometry( g->as< MultiPolygon >() ) ;
obj.save( "triangulation3d_in_plane.obj" );
return 0;
}
<commit_msg>remove io::WaveFrontObj<commit_after><|endoftext|> |
<commit_before>//
// main.cpp
// GLEngineExample1
//
// Created by Asger Nyman Christiansen on 18/12/2016.
// Copyright © 2016 Asger Nyman Christiansen. All rights reserved.
//
#include "GLCamera.h"
#include "MeshCreator.h"
#include "materials/GLColorMaterial.h"
#include "gtx/rotate_vector.hpp"
#include "GLAmbientOcclusionEffect.h"
#define GLFW_INCLUDE_NONE
#include "glfw3.h"
using namespace std;
using namespace glm;
using namespace gle;
using namespace mesh;
GLFWwindow* gWindow = NULL;
shared_ptr<float> cube_rotation_angle = make_shared<float>(0.f);
void on_error(int errorCode, const char* msg)
{
throw std::runtime_error(msg);
}
void print_fps(double elapsedTime)
{
static int draws = 0;
draws++;
static float seconds = 0.;
seconds += elapsedTime;
if(seconds > 5)
{
std::cout << "FPS: " << ((float)draws)/seconds << std::endl;
seconds = 0.;
draws = 0;
}
}
void update(GLCamera& camera)
{
static float last_time = glfwGetTime();
float time = glfwGetTime();
float elapsed_time = time - last_time;
print_fps(elapsed_time);
*cube_rotation_angle = time;
static vec3 view_position = vec3(0., 0., 5.);
static vec3 view_direction = vec3(0., 0., -1.);
const float speed = 3.;
if(glfwGetKey(gWindow, 'S'))
{
view_position -= speed * elapsed_time * view_direction;
}
else if(glfwGetKey(gWindow, 'W'))
{
view_position += speed * elapsed_time * view_direction;
}
auto side = normalize(cross(view_direction, vec3(0.,1.,0.)));
auto up = normalize(cross(side, view_direction));
if(glfwGetKey(gWindow, 'A'))
{
view_direction = vec3(glm::rotate(mat4(), elapsed_time, up) * vec4(view_direction, 1.));
}
else if(glfwGetKey(gWindow, 'D'))
{
view_direction = vec3(glm::rotate(mat4(), -elapsed_time, up) * vec4(view_direction, 1.));
}
else if(glfwGetKey(gWindow, 'E'))
{
view_direction = vec3(glm::rotate(mat4(), -elapsed_time, side) * vec4(view_direction, 1.));
}
else if(glfwGetKey(gWindow, 'Q'))
{
view_direction = vec3(glm::rotate(mat4(), elapsed_time, side) * vec4(view_direction, 1.));
}
camera.set_view(view_position, view_direction);
last_time = time;
}
void create_cube(GLScene& root)
{
auto material = make_shared<GLColorMaterial>(vec3(0.5, 0.1, 0.7));
auto geometry = MeshCreator::create_box(false);
auto rotation_node = std::make_shared<GLRotationNode>(vec3(1., 1., 0.), cube_rotation_angle);
root.add_child(rotation_node)->add_leaf(geometry, material);
}
void create_room(GLScene& root)
{
auto color_material = make_shared<GLColorMaterial>(vec3(0.5, 0.5, 0.5));
auto box = MeshCreator::create_box(true);
auto scale_node = std::make_shared<GLTransformationNode>(scale(vec3(10., 10., 10.)));
root.add_child(scale_node)->add_leaf(box, color_material);
}
int main(int argc, const char * argv[])
{
int WIN_SIZE_X = 1200;
int WIN_SIZE_Y = 700;
// initialise GLFW
glfwSetErrorCallback(on_error);
if(!glfwInit())
throw std::runtime_error("glfwInit failed");
// Open a window with GLFW
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
gWindow = glfwCreateWindow(WIN_SIZE_X, WIN_SIZE_Y, "GLEngine example 1", NULL, NULL);
if(!gWindow)
throw std::runtime_error("glfwCreateWindow failed. Can your hardware handle OpenGL 3.3?");
// GLFW settings
glfwSetInputMode(gWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetCursorPos(gWindow, 0, 0);
glfwMakeContextCurrent(gWindow);
glfwGetFramebufferSize(gWindow, &WIN_SIZE_X, &WIN_SIZE_Y);
// Create camera
auto camera = GLCamera(WIN_SIZE_X, WIN_SIZE_Y);
camera.add_post_effect(make_shared<GLAmbientOcclusionEffect>());
// Create scene
auto scene = GLScene();
create_room(scene);
create_cube(scene);
scene.add_light(std::make_shared<GLPointLight>(glm::vec3(-1., 5., 1.)));
scene.add_light(std::make_shared<GLDirectionalLight>(glm::vec3(1., -1., 0.)));
// run while the window is open
while(!glfwWindowShouldClose(gWindow))
{
// process pending events
glfwPollEvents();
// update the scene based on the time elapsed since last update
update(camera);
// draw one frame
camera.draw(scene);
glfwSwapBuffers(gWindow);
//exit program if escape key is pressed
if(glfwGetKey(gWindow, GLFW_KEY_ESCAPE))
glfwSetWindowShouldClose(gWindow, GL_TRUE);
}
// clean up and exit
glfwTerminate();
return 0;
}
<commit_msg>Using SDL instead of GLFW in shadows example.<commit_after>//
// main.cpp
// GLEngineExample1
//
// Created by Asger Nyman Christiansen on 18/12/2016.
// Copyright © 2016 Asger Nyman Christiansen. All rights reserved.
//
#include "GLCamera.h"
#include "MeshCreator.h"
#include "materials/GLColorMaterial.h"
#include "gtx/rotate_vector.hpp"
#include "GLAmbientOcclusionEffect.h"
#define SDL_MAIN_HANDLED
#include "SDL.h"
using namespace std;
using namespace glm;
using namespace gle;
using namespace mesh;
shared_ptr<float> cube_rotation_angle = make_shared<float>(0.f);
void on_error(int errorCode, const char* msg)
{
throw std::runtime_error(msg);
}
void print_fps(double elapsedTime)
{
static int draws = 0;
draws++;
static float seconds = 0.;
seconds += elapsedTime;
if(seconds > 5)
{
std::cout << "FPS: " << ((float)draws)/seconds << std::endl;
seconds = 0.;
draws = 0;
}
}
void update(GLCamera& camera)
{
static float last_time = time();
float current_time = time();
float elapsed_time = current_time - last_time;
last_time = current_time;
print_fps(elapsed_time);
*cube_rotation_angle = current_time;
static vec3 view_position = vec3(0., 0., 5.);
static vec3 view_direction = vec3(0., 0., -1.);
const float speed = 3.;
const Uint8* currentKeyStates = SDL_GetKeyboardState( NULL );
if(currentKeyStates[ SDL_SCANCODE_S ])
{
view_position -= speed * elapsed_time * view_direction;
}
else if(currentKeyStates[ SDL_SCANCODE_W ])
{
view_position += speed * elapsed_time * view_direction;
}
auto side = normalize(cross(view_direction, vec3(0.,1.,0.)));
auto up = normalize(cross(side, view_direction));
if(currentKeyStates[ SDL_SCANCODE_A ])
{
view_direction = vec3(glm::rotate(mat4(), elapsed_time, up) * vec4(view_direction, 1.));
}
else if(currentKeyStates[ SDL_SCANCODE_D ])
{
view_direction = vec3(glm::rotate(mat4(), -elapsed_time, up) * vec4(view_direction, 1.));
}
else if(currentKeyStates[ SDL_SCANCODE_E ])
{
view_direction = vec3(glm::rotate(mat4(), -elapsed_time, side) * vec4(view_direction, 1.));
}
else if(currentKeyStates[ SDL_SCANCODE_Q ])
{
view_direction = vec3(glm::rotate(mat4(), elapsed_time, side) * vec4(view_direction, 1.));
}
camera.set_view(view_position, view_direction);
}
void create_cube(GLScene& root)
{
auto material = make_shared<GLColorMaterial>(vec3(0.5, 0.1, 0.7));
auto geometry = MeshCreator::create_box(false);
auto rotation_node = std::make_shared<GLRotationNode>(vec3(1., 1., 0.), cube_rotation_angle);
root.add_child(rotation_node)->add_leaf(geometry, material);
}
void create_room(GLScene& root)
{
auto color_material = make_shared<GLColorMaterial>(vec3(0.5, 0.5, 0.5));
auto box = MeshCreator::create_box(true);
auto scale_node = std::make_shared<GLTransformationNode>(scale(vec3(10., 10., 10.)));
root.add_child(scale_node)->add_leaf(box, color_material);
}
int main(int argc, const char * argv[])
{
// Initialize SDL
if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 )
{
printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
throw std::runtime_error("SDL init failed");
}
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
// Create window
int window_width = 1200;
int window_height = 700;
auto window = SDL_CreateWindow( "Shadows", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, window_width, window_height, SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE );
if( window == NULL )
{
printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
throw std::runtime_error("SDL init failed");
}
// Create context
auto glcontext = SDL_GL_CreateContext(window);
// Create camera
auto camera = GLCamera(window_width, window_height);
camera.add_post_effect(make_shared<GLAmbientOcclusionEffect>());
// Create scene
auto scene = GLScene();
create_room(scene);
create_cube(scene);
scene.add_light(std::make_shared<GLPointLight>(glm::vec3(-1., 5., 1.)));
scene.add_light(std::make_shared<GLDirectionalLight>(glm::vec3(1., -1., 0.)));
// run while the window is open
bool quit = false;
while(!quit)
{
// process pending events
SDL_Event e;
while( SDL_PollEvent( &e ) != 0 )
{
if( e.type == SDL_QUIT || e.key.keysym.sym == SDLK_ESCAPE)
{
quit = true;
}
}
// update the scene based on the time elapsed since last update
update(camera);
// draw one frame
camera.draw(scene);
SDL_GL_SwapWindow(window);
}
// Delete context
SDL_GL_DeleteContext(glcontext);
// Destroy window
SDL_DestroyWindow( window );
window = NULL;
// Quit SDL subsystems
SDL_Quit();
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "type/connection.h"
#include "type/pt_data.h"
#include "type/stop_point.h"
#include "type/indexes.h"
#include "type/serialization.h"
namespace navitia {
namespace type {
template <class Archive>
void StopPointConnection::save(Archive& ar, const unsigned int) const {
ar& idx& uri& departure& destination& display_duration& duration& max_duration& connection_type& _properties;
}
template <class Archive>
void StopPointConnection::load(Archive& ar, const unsigned int) {
ar& idx& uri& departure& destination& display_duration& duration& max_duration& connection_type& _properties;
// loading manage StopPoint::stop_point_connection_list
departure->stop_point_connection_list.push_back(this);
destination->stop_point_connection_list.push_back(this);
}
SPLIT_SERIALIZABLE(StopPointConnection)
Indexes StopPointConnection::get(Type_e type, const PT_Data&) const {
Indexes result;
switch (type) {
case Type_e::StopPoint:
result.insert(this->departure->idx);
result.insert(this->destination->idx);
break;
default:
break;
}
return result;
}
bool StopPointConnection::operator<(const StopPointConnection& other) const {
if (this->departure != other.departure) {
return *this->departure < *other.departure;
}
return *this->destination < *other.destination;
}
} // namespace type
} // namespace navitia
<commit_msg>Revert "cleanup connection"<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "type/connection.h"
#include "type/type.h"
#include "type/indexes.h"
#include "type/serialization.h"
namespace navitia {
namespace type {
template <class Archive>
void StopPointConnection::save(Archive& ar, const unsigned int) const {
ar& idx& uri& departure& destination& display_duration& duration& max_duration& connection_type& _properties;
}
template <class Archive>
void StopPointConnection::load(Archive& ar, const unsigned int) {
ar& idx& uri& departure& destination& display_duration& duration& max_duration& connection_type& _properties;
// loading manage StopPoint::stop_point_connection_list
departure->stop_point_connection_list.push_back(this);
destination->stop_point_connection_list.push_back(this);
}
SPLIT_SERIALIZABLE(StopPointConnection)
Indexes StopPointConnection::get(Type_e type, const PT_Data&) const {
Indexes result;
switch (type) {
case Type_e::StopPoint:
result.insert(this->departure->idx);
result.insert(this->destination->idx);
break;
default:
break;
}
return result;
}
bool StopPointConnection::operator<(const StopPointConnection& other) const {
if (this->departure != other.departure) {
return *this->departure < *other.departure;
}
return *this->destination < *other.destination;
}
} // namespace type
} // namespace navitia
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved.
*
* This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
*
* Use of this source code is governed by MIT license that can be found in the
* LICENSE file in the root of the source tree. All contributing project authors
* may be found in the AUTHORS file in the root of the source tree.
*/
#include "H264.h"
#include "SPSParser.h"
#include "Util/logger.h"
using namespace toolkit;
namespace mediakit{
bool getAVCInfo(const char * sps,int sps_len,int &iVideoWidth, int &iVideoHeight, float &iVideoFps){
T_GetBitContext tGetBitBuf;
T_SPS tH264SpsInfo;
memset(&tGetBitBuf,0,sizeof(tGetBitBuf));
memset(&tH264SpsInfo,0,sizeof(tH264SpsInfo));
tGetBitBuf.pu8Buf = (uint8_t*)sps + 1;
tGetBitBuf.iBufSize = sps_len - 1;
if(0 != h264DecSeqParameterSet((void *) &tGetBitBuf, &tH264SpsInfo)){
return false;
}
h264GetWidthHeight(&tH264SpsInfo, &iVideoWidth, &iVideoHeight);
h264GeFramerate(&tH264SpsInfo, &iVideoFps);
//ErrorL << iVideoWidth << " " << iVideoHeight << " " << iVideoFps;
return true;
}
bool getAVCInfo(const string& strSps,int &iVideoWidth, int &iVideoHeight, float &iVideoFps) {
return getAVCInfo(strSps.data(),strSps.size(),iVideoWidth,iVideoHeight,iVideoFps);
}
const char *memfind(const char *buf, int len, const char *subbuf, int sublen) {
for (auto i = 0; i < len - sublen; ++i) {
if (memcmp(buf + i, subbuf, sublen) == 0) {
return buf + i;
}
}
return NULL;
}
void splitH264(const char *ptr, int len, const std::function<void(const char *, int)> &cb) {
auto nal = ptr;
auto end = ptr + len;
while(true) {
auto next_nal = memfind(nal + 3,end - nal - 3,"\x0\x0\x1",3);
if(next_nal){
cb(nal,next_nal - nal);
nal = next_nal;
continue;
}
cb(nal,end - nal);
break;
}
}
Sdp::Ptr H264Track::getSdp() {
if(!ready()){
WarnL << getCodecName() << " Track未准备好";
return nullptr;
}
return std::make_shared<H264Sdp>(getSps(),getPps());
}
}//namespace mediakit
<commit_msg>修复h264 split后可能多个字节的bug<commit_after>/*
* Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved.
*
* This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
*
* Use of this source code is governed by MIT license that can be found in the
* LICENSE file in the root of the source tree. All contributing project authors
* may be found in the AUTHORS file in the root of the source tree.
*/
#include "H264.h"
#include "SPSParser.h"
#include "Util/logger.h"
using namespace toolkit;
namespace mediakit{
bool getAVCInfo(const char * sps,int sps_len,int &iVideoWidth, int &iVideoHeight, float &iVideoFps){
T_GetBitContext tGetBitBuf;
T_SPS tH264SpsInfo;
memset(&tGetBitBuf,0,sizeof(tGetBitBuf));
memset(&tH264SpsInfo,0,sizeof(tH264SpsInfo));
tGetBitBuf.pu8Buf = (uint8_t*)sps + 1;
tGetBitBuf.iBufSize = sps_len - 1;
if(0 != h264DecSeqParameterSet((void *) &tGetBitBuf, &tH264SpsInfo)){
return false;
}
h264GetWidthHeight(&tH264SpsInfo, &iVideoWidth, &iVideoHeight);
h264GeFramerate(&tH264SpsInfo, &iVideoFps);
//ErrorL << iVideoWidth << " " << iVideoHeight << " " << iVideoFps;
return true;
}
bool getAVCInfo(const string& strSps,int &iVideoWidth, int &iVideoHeight, float &iVideoFps) {
return getAVCInfo(strSps.data(),strSps.size(),iVideoWidth,iVideoHeight,iVideoFps);
}
const char *memfind(const char *buf, int len, const char *subbuf, int sublen) {
for (auto i = 0; i < len - sublen; ++i) {
if (memcmp(buf + i, subbuf, sublen) == 0) {
return buf + i;
}
}
return NULL;
}
void splitH264(const char *ptr, int len, const std::function<void(const char *, int)> &cb) {
auto nal = ptr;
auto end = ptr + len;
while(true) {
auto next_nal = memfind(nal + 3,end - nal - 3,"\x0\x0\x1",3);
if(next_nal){
if(*(next_nal - 1) == 0x00){
next_nal -= 1;
}
cb(nal,next_nal - nal);
nal = next_nal;
continue;
}
cb(nal,end - nal);
break;
}
}
#if 0
//splitH264函数测试程序
static onceToken s_token([](){
char buf[] = "\x00\x00\x00\x01\x12\x23\x34\x45\x56"
"\x00\x00\x00\x01\x12\x23\x34\x45\x56"
"\x00\x00\x00\x01\x12\x23\x34\x45\x56"
"\x00\x00\x01\x12\x23\x34\x45\x56";
splitH264(buf, sizeof(buf) - 1, [](const char *ptr, int len){
cout << hexdump(ptr, len) << endl;
});
});
#endif //0
Sdp::Ptr H264Track::getSdp() {
if(!ready()){
WarnL << getCodecName() << " Track未准备好";
return nullptr;
}
return std::make_shared<H264Sdp>(getSps(),getPps());
}
}//namespace mediakit
<|endoftext|> |
<commit_before>#include "Fl_Tree_PrefsC.h"
#ifdef __cplusplus
EXPORT {
#endif
FL_EXPORT_C(fl_Tree_Prefs, Fl_Tree_Prefs_New)(){
//
}
FL_EXPORT_C(Fl_Font,Fl_Tree_Prefs_item_labelfont)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelfont();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_item_labelfont)(fl_Tree_Prefs tree_prefs,Fl_Font val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelfont(val);
}
FL_EXPORT_C(Fl_Fontsize,Fl_Tree_Prefs_item_labelsize)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelsize();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_item_labelsize)(fl_Tree_Prefs tree_prefs,Fl_Fontsize val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelsize(val);
}
FL_EXPORT_C(Fl_Color,Fl_Tree_Prefs_item_labelfgcolor)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelfgcolor();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_item_labelfgcolor)(fl_Tree_Prefs tree_prefs,Fl_Color val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelfgcolor(val);
}
FL_EXPORT_C(Fl_Color,Fl_Tree_Prefs_item_labelbgcolor)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelbgcolor();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_item_labelbgcolor)(fl_Tree_Prefs tree_prefs,Fl_Color val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelbgcolor(val);
}
FL_EXPORT_C(Fl_Color,Fl_Tree_Prefs_item_labelbgcolor)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelbgcolor();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_item_labelbgcolor)(fl_Tree_Prefs tree_prefs,Fl_Color val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelbgcolor(val);
}
FL_EXPORT_C(Fl_Font,Fl_Tree_Prefs_labelfont)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelfont();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_labelfont)(fl_Tree_Prefs tree_prefs,Fl_Font val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelfont(val);
}
FL_EXPORT_C(Fl_Fontsize,Fl_Tree_Prefs_labelsize)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelsize();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_labelsize)(fl_Tree_Prefs tree_prefs,Fl_Fontsize val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelsize(val);
}
FL_EXPORT_C(Fl_Color,Fl_Tree_Prefs_labelfgcolor)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelfgcolor();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_labelfgcolor)(fl_Tree_Prefs tree_prefs,Fl_Color val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelfgcolor(val);
}
FL_EXPORT_C(Fl_Color,Fl_Tree_Prefs_labelbgcolor)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelbgcolor();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_labelbgcolor)(fl_Tree_Prefs tree_prefs,Fl_Color val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelbgcolor(val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_marginleft)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->marginleft();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_marginleft)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->marginleft(val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_margintop)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->margintop();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_Fl_Tree_Prefs_margintop)(fl_Tree_Prefs tree_prefs,fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->Fl_Tree_Prefs_margintop(tree_prefs,val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_marginbottom)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->marginbottom();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_marginbottom)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->marginbottom(val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_openchild_marginbottom)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->openchild_marginbottom();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_openchild_marginbottom)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->openchild_marginbottom(val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_usericonmarginleft)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->usericonmarginleft();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_usericonmarginleft)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->usericonmarginleft(val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_labelmarginleft)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelmarginleft();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_labelmarginleft)(fl_Tree_Prefs tree_prefs,fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->set_labelmarginleft(tree_prefs,val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_widgetmarginleft)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->widgetmarginleft();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_widgetmarginleft)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->widgetmarginleft(val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_linespacing)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->linespacing();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_linespacing)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->linespacing(val);
}
FL_EXPORT_C(Fl_Color,Fl_Tree_Prefs_connectorcolor)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->connectorcolor();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_connectorcolor)(fl_Tree_Prefs tree_prefs,Fl_Color val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->connectorcolor(val);
}
FL_EXPORT_C(Fl_Tree_Connector,Fl_Tree_Prefs_connectorstyle)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->connectorstyle();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_connectorstyle_with_tree_connector)(fl_Tree_Prefs tree_prefs,Fl_Tree_Connector val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->connectorstyle(val);
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_connectorstyle_with_val)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->connectorstyle(val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_connectorwidth)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->connectorwidth();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_connectorwidth)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->connectorwidth(val);
}
FL_EXPORT_C(Fl_Image*,Fl_Tree_Prefs_openicon)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->openicon();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_openicon)(fl_Tree_Prefs tree_prefs,Fl_Image *val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->openicon(*val);
}
FL_EXPORT_C(Fl_Image*,Fl_Tree_Prefs_closeicon)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->closeicon();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_closeicon)(fl_Tree_Prefs tree_prefs,Fl_Image *val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->closeicon(*val);
}
FL_EXPORT_C(Fl_Image*,Fl_Tree_Prefs_usericon)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->usericon();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_usericon)(fl_Tree_Prefs tree_prefs,Fl_Image *val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->usericon(*val);
}
FL_EXPORT_C(char,Fl_Tree_Prefs_showcollapse)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->showcollapse();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_showcollapse)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->showcollapse(val);
}
FL_EXPORT_C(Fl_Tree_Sort,Fl_Tree_Prefs_sortorder)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->sortorder();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_sortorder)(fl_Tree_Prefs tree_prefs,Fl_Tree_Sort val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->sortorder(val);
}
FL_EXPORT_C(Fl_Boxtype,Fl_Tree_Prefs_selectbox)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->selectbox();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_selectbox)(fl_Tree_Prefs tree_prefs,Fl_Boxtype val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->selectbox(val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_showroot)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->showroot();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_showroot)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->showroot(val);
}
FL_EXPORT_C(Fl_Tree_Select,Fl_Tree_Prefs_selectmode)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->selectmode();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_selectmode)(fl_Tree_Prefs tree_prefs,fl_Tree_Prefs tree_prefs,Fl_Tree_Select val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->selectmode(tree_prefs,val);
}
FL_EXPORT_C(Fl_Tree_Item_Reselect_Mode,Fl_Tree_Prefs_item_reselect_mode)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_reselect_mode();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_item_reselect_mode)(fl_Tree_Prefs tree_prefs,Fl_Tree_Item_Reselect_Mode mode){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_reselect_mode(mode);
}
FL_EXPORT_C(Fl_Tree_Item_Draw_Mode,Fl_Tree_Prefs_item_draw_mode)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_draw_mode();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_item_draw_mode)(fl_Tree_Prefs tree_prefs,Fl_Tree_Item_Draw_Mode val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_draw_mode(val);
}
#ifdef __cplusplus
}
#endif
<commit_msg>Forgot the constructor<commit_after>#include "Fl_Tree_PrefsC.h"
#ifdef __cplusplus
EXPORT {
#endif
FL_EXPORT_C(fl_Tree_Prefs, Fl_Tree_Prefs_New)(){
Fl_Tree_Prefs* prefs = new Fl_Tree_Prefs();
return (fl_Tree_Prefs)prefs;
}
FL_EXPORT_C(Fl_Font,Fl_Tree_Prefs_item_labelfont)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelfont();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_item_labelfont)(fl_Tree_Prefs tree_prefs,Fl_Font val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelfont(val);
}
FL_EXPORT_C(Fl_Fontsize,Fl_Tree_Prefs_item_labelsize)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelsize();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_item_labelsize)(fl_Tree_Prefs tree_prefs,Fl_Fontsize val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelsize(val);
}
FL_EXPORT_C(Fl_Color,Fl_Tree_Prefs_item_labelfgcolor)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelfgcolor();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_item_labelfgcolor)(fl_Tree_Prefs tree_prefs,Fl_Color val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelfgcolor(val);
}
FL_EXPORT_C(Fl_Color,Fl_Tree_Prefs_item_labelbgcolor)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelbgcolor();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_item_labelbgcolor)(fl_Tree_Prefs tree_prefs,Fl_Color val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelbgcolor(val);
}
FL_EXPORT_C(Fl_Color,Fl_Tree_Prefs_item_labelbgcolor)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelbgcolor();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_item_labelbgcolor)(fl_Tree_Prefs tree_prefs,Fl_Color val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_labelbgcolor(val);
}
FL_EXPORT_C(Fl_Font,Fl_Tree_Prefs_labelfont)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelfont();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_labelfont)(fl_Tree_Prefs tree_prefs,Fl_Font val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelfont(val);
}
FL_EXPORT_C(Fl_Fontsize,Fl_Tree_Prefs_labelsize)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelsize();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_labelsize)(fl_Tree_Prefs tree_prefs,Fl_Fontsize val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelsize(val);
}
FL_EXPORT_C(Fl_Color,Fl_Tree_Prefs_labelfgcolor)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelfgcolor();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_labelfgcolor)(fl_Tree_Prefs tree_prefs,Fl_Color val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelfgcolor(val);
}
FL_EXPORT_C(Fl_Color,Fl_Tree_Prefs_labelbgcolor)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelbgcolor();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_labelbgcolor)(fl_Tree_Prefs tree_prefs,Fl_Color val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelbgcolor(val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_marginleft)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->marginleft();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_marginleft)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->marginleft(val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_margintop)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->margintop();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_Fl_Tree_Prefs_margintop)(fl_Tree_Prefs tree_prefs,fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->Fl_Tree_Prefs_margintop(tree_prefs,val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_marginbottom)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->marginbottom();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_marginbottom)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->marginbottom(val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_openchild_marginbottom)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->openchild_marginbottom();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_openchild_marginbottom)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->openchild_marginbottom(val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_usericonmarginleft)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->usericonmarginleft();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_usericonmarginleft)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->usericonmarginleft(val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_labelmarginleft)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->labelmarginleft();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_labelmarginleft)(fl_Tree_Prefs tree_prefs,fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->set_labelmarginleft(tree_prefs,val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_widgetmarginleft)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->widgetmarginleft();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_widgetmarginleft)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->widgetmarginleft(val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_linespacing)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->linespacing();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_linespacing)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->linespacing(val);
}
FL_EXPORT_C(Fl_Color,Fl_Tree_Prefs_connectorcolor)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->connectorcolor();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_connectorcolor)(fl_Tree_Prefs tree_prefs,Fl_Color val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->connectorcolor(val);
}
FL_EXPORT_C(Fl_Tree_Connector,Fl_Tree_Prefs_connectorstyle)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->connectorstyle();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_connectorstyle_with_tree_connector)(fl_Tree_Prefs tree_prefs,Fl_Tree_Connector val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->connectorstyle(val);
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_connectorstyle_with_val)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->connectorstyle(val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_connectorwidth)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->connectorwidth();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_connectorwidth)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->connectorwidth(val);
}
FL_EXPORT_C(Fl_Image*,Fl_Tree_Prefs_openicon)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->openicon();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_openicon)(fl_Tree_Prefs tree_prefs,Fl_Image *val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->openicon(*val);
}
FL_EXPORT_C(Fl_Image*,Fl_Tree_Prefs_closeicon)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->closeicon();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_closeicon)(fl_Tree_Prefs tree_prefs,Fl_Image *val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->closeicon(*val);
}
FL_EXPORT_C(Fl_Image*,Fl_Tree_Prefs_usericon)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->usericon();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_usericon)(fl_Tree_Prefs tree_prefs,Fl_Image *val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->usericon(*val);
}
FL_EXPORT_C(char,Fl_Tree_Prefs_showcollapse)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->showcollapse();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_showcollapse)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->showcollapse(val);
}
FL_EXPORT_C(Fl_Tree_Sort,Fl_Tree_Prefs_sortorder)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->sortorder();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_sortorder)(fl_Tree_Prefs tree_prefs,Fl_Tree_Sort val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->sortorder(val);
}
FL_EXPORT_C(Fl_Boxtype,Fl_Tree_Prefs_selectbox)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->selectbox();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_selectbox)(fl_Tree_Prefs tree_prefs,Fl_Boxtype val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->selectbox(val);
}
FL_EXPORT_C(int,Fl_Tree_Prefs_showroot)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->showroot();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_showroot)(fl_Tree_Prefs tree_prefs,int val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->showroot(val);
}
FL_EXPORT_C(Fl_Tree_Select,Fl_Tree_Prefs_selectmode)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->selectmode();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_selectmode)(fl_Tree_Prefs tree_prefs,fl_Tree_Prefs tree_prefs,Fl_Tree_Select val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->selectmode(tree_prefs,val);
}
FL_EXPORT_C(Fl_Tree_Item_Reselect_Mode,Fl_Tree_Prefs_item_reselect_mode)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_reselect_mode();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_item_reselect_mode)(fl_Tree_Prefs tree_prefs,Fl_Tree_Item_Reselect_Mode mode){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_reselect_mode(mode);
}
FL_EXPORT_C(Fl_Tree_Item_Draw_Mode,Fl_Tree_Prefs_item_draw_mode)(fl_Tree_Prefs tree_prefs){
return (static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_draw_mode();
}
FL_EXPORT_C(void,Fl_Tree_Prefs_set_item_draw_mode)(fl_Tree_Prefs tree_prefs,Fl_Tree_Item_Draw_Mode val){
(static_cast<Fl_Tree_Prefs*>(tree_prefs))->item_draw_mode(val);
}
#ifdef __cplusplus
}
#endif
<|endoftext|> |
<commit_before>#include "gru.h"
#include <sstream>
#include <gflags/gflags.h>
#include <boost/algorithm/string.hpp>
#include <vector>
#include <cmath>
#include "logging.h"
#include "util.h"
DECLARE_int32(galaxy_deploy_step);
DECLARE_string(minion_path);
DECLARE_string(nexus_server_list);
DECLARE_string(nexus_root_path);
DECLARE_string(master_path);
DECLARE_bool(enable_cpu_soft_limit);
DECLARE_bool(enable_memory_soft_limit);
DECLARE_string(galaxy_node_label);
DECLARE_string(galaxy_user);
DECLARE_string(galaxy_token);
DECLARE_string(galaxy_pool);
DECLARE_int32(max_minions_per_host);
namespace baidu {
namespace shuttle {
static const int64_t default_additional_map_memory = 1024l * 1024 * 1024;
static const int64_t default_additional_reduce_memory = 2048l * 1024 * 1024;
static const int default_map_additional_millicores = 0;
static const int default_reduce_additional_millicores = 500;
int Gru::additional_map_millicores = default_map_additional_millicores;
int Gru::additional_reduce_millicores = default_reduce_additional_millicores;
int64_t Gru::additional_map_memory = default_additional_map_memory;
int64_t Gru::additional_reduce_memory = default_additional_reduce_memory;
Gru::Gru(::baidu::galaxy::sdk::AppMaster* galaxy, JobDescriptor* job,
const std::string& job_id, WorkMode mode) :
galaxy_(galaxy), job_(job), job_id_(job_id), mode_(mode) {
mode_str_ = ((mode == kReduce) ? "reduce" : "map");
minion_name_ = job->name() + "_" + mode_str_;
}
Status Gru::Start() {
::baidu::galaxy::sdk::SubmitJobRequest galaxy_job;
galaxy_job.user.user = FLAGS_galaxy_user;
galaxy_job.user.token = FLAGS_galaxy_token;
galaxy_job.hostname = ::baidu::common::util::GetLocalHostName();
std::vector<std::string> pools;
boost::split(pools, FLAGS_galaxy_pool, boost::is_any_of(","));
galaxy_job.job.deploy.pools = pools;
galaxy_job.job.name = minion_name_ + "@minion";
galaxy_job.job.type = ::baidu::galaxy::sdk::kJobBatch;
if (mode_ == kReduce) {
galaxy_job.job.deploy.replica = std::min(job_->reduce_capacity(),
std::min(job_->reduce_total() * 6 / 5, 20));
} else {
galaxy_job.job.deploy.replica = std::min(job_->map_capacity(),
std::min(job_->map_total() * 6 / 5, 20));
}
galaxy_job.job.deploy.step = std::min((int)FLAGS_galaxy_deploy_step, (int)galaxy_job.job.deploy.replica);
galaxy_job.job.deploy.interval = 1;
galaxy_job.job.deploy.max_per_host = FLAGS_max_minions_per_host;
galaxy_job.job.deploy.update_break_count = 0;
galaxy_job.job.version = "1.0.0";
galaxy_job.job.run_user = "galaxy";
if (!FLAGS_galaxy_node_label.empty()) {
galaxy_job.job.deploy.tag = FLAGS_galaxy_node_label;
}
::baidu::galaxy::sdk::PodDescription & pod_desc = galaxy_job.job.pod;
pod_desc.workspace_volum.size = (3L << 30);
pod_desc.workspace_volum.medium = ::baidu::galaxy::sdk::kDisk;
pod_desc.workspace_volum.exclusive = false;
pod_desc.workspace_volum.readonly = false;
pod_desc.workspace_volum.use_symlink = false;
pod_desc.workspace_volum.dest_path = "/home/shuttle";
pod_desc.workspace_volum.type = ::baidu::galaxy::sdk::kEmptyDir;
::baidu::galaxy::sdk::TaskDescription task_desc;
if (mode_str_ == "map") {
task_desc.cpu.milli_core = job_->millicores() + additional_map_millicores;
} else {
task_desc.cpu.milli_core = job_->millicores() + additional_reduce_millicores;
}
task_desc.memory.size = job_->memory() +
((mode_ == kReduce) ? additional_reduce_memory : additional_map_memory);
std::string app_package;
std::vector<std::string> cache_archive_list;
int file_size = job_->files().size();
for (int i = 0; i < file_size; ++i) {
const std::string& file = job_->files(i);
if (boost::starts_with(file, "hdfs://")) {
cache_archive_list.push_back(file);
} else {
app_package = file;
}
}
std::stringstream ss;
if (!job_->input_dfs().user().empty()) {
ss << "hadoop_job_ugi=" << job_->input_dfs().user()
<< "," << job_->input_dfs().password()
<< " fs_default_name=hdfs://" << job_->input_dfs().host()
<< ":" << job_->input_dfs().port() << " ";
}
for (size_t i = 0; i < cache_archive_list.size(); i++) {
ss << "cache_archive_" << i << "=" << cache_archive_list[i] << " ";
}
ss << "app_package=" << app_package
<< " ./minion_boot.sh -jobid=" << job_id_ << " -nexus_addr=" << FLAGS_nexus_server_list
<< " -master_nexus_path=" << FLAGS_nexus_root_path + FLAGS_master_path
<< " -work_mode=" << ((mode_ == kMapOnly) ? "map-only" : mode_str_);
std::stringstream ss_stop;
ss_stop << "source ./hdfs_env.sh; ./minion -jobid=" << job_id_ << " -nexus_addr=" << FLAGS_nexus_server_list
<< " -master_nexus_path=" << FLAGS_nexus_root_path + FLAGS_master_path
<< " -work_mode=" << ((mode_ == kMapOnly) ? "map-only" : mode_str_)
<< " -kill_task";
task_desc.exe_package.package.source_path = FLAGS_minion_path;
task_desc.exe_package.package.dest_path = ".";
task_desc.exe_package.package.version = "1.0";
task_desc.exe_package.start_cmd = ss.str();
task_desc.exe_package.stop_cmd = ss_stop.str().c_str();
task_desc.data_package.reload_cmd = ss.str();
task_desc.tcp_throt.recv_bps_quota = (80L << 20);
task_desc.tcp_throt.send_bps_quota = (80L << 20);
task_desc.blkio.weight = 50;
::baidu::galaxy::sdk::PortRequired port_req;
port_req.port = "dynamic";
port_req.port_name = "NFS_CLIENT_PORT";
task_desc.ports.push_back(port_req);
port_req.port = "dynamic";
port_req.port_name = "MINION_PORT";
task_desc.ports.push_back(port_req);
if (FLAGS_enable_cpu_soft_limit) {
task_desc.cpu.excess = true;
} else {
task_desc.cpu.excess = false;
}
if (FLAGS_enable_memory_soft_limit) {
task_desc.memory.excess = true;
} else {
task_desc.memory.excess = false;
}
pod_desc.tasks.push_back(task_desc);
std::string minion_id;
::baidu::galaxy::sdk::SubmitJobResponse rsps;
if (galaxy_->SubmitJob(galaxy_job, &rsps)) {
minion_id = rsps.jobid;
LOG(INFO, "galaxy job id: %s", minion_id.c_str());
minion_id_ = minion_id;
galaxy_job_ = galaxy_job;
if (minion_id_.empty()) {
LOG(INFO, "can not get galaxy job id");
return kGalaxyError;
}
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
Status Gru::Kill() {
LOG(INFO, "kill galaxy job: %s", minion_id_.c_str());
if (minion_id_.empty()) {
return kOk;
}
::baidu::galaxy::sdk::RemoveJobRequest rqst;
::baidu::galaxy::sdk::RemoveJobResponse rsps;
rqst.jobid = minion_id_;
rqst.user = galaxy_job_.user;
rqst.hostname = ::baidu::common::util::GetLocalHostName();
if (galaxy_->RemoveJob(rqst, &rsps)) {
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
Status Gru::Update(const std::string& priority,
int capacity) {
::baidu::galaxy::sdk::JobDescription job_desc = galaxy_job_.job;
if (!priority.empty()) {
//job_desc.priority = priority;
}
if (capacity != -1) {
job_desc.deploy.replica = capacity;
}
::baidu::galaxy::sdk::UpdateJobRequest rqst;
::baidu::galaxy::sdk::UpdateJobResponse rsps;
rqst.user = galaxy_job_.user;
rqst.job = job_desc;
rqst.jobid = minion_id_;
rqst.hostname = ::baidu::common::util::GetLocalHostName();
rqst.operate = ::baidu::galaxy::sdk::kUpdateJobStart;
if (galaxy_->UpdateJob(rqst, &rsps)) {
if (!priority.empty()) {
//galaxy_job_.priority = priority;
}
if (capacity != -1) {
galaxy_job_.job.deploy.replica = capacity;
}
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
}
}
<commit_msg>Fix replica problem<commit_after>#include "gru.h"
#include <sstream>
#include <gflags/gflags.h>
#include <boost/algorithm/string.hpp>
#include <vector>
#include <cmath>
#include "logging.h"
#include "util.h"
DECLARE_int32(galaxy_deploy_step);
DECLARE_string(minion_path);
DECLARE_string(nexus_server_list);
DECLARE_string(nexus_root_path);
DECLARE_string(master_path);
DECLARE_bool(enable_cpu_soft_limit);
DECLARE_bool(enable_memory_soft_limit);
DECLARE_string(galaxy_node_label);
DECLARE_string(galaxy_user);
DECLARE_string(galaxy_token);
DECLARE_string(galaxy_pool);
DECLARE_int32(max_minions_per_host);
namespace baidu {
namespace shuttle {
static const int64_t default_additional_map_memory = 1024l * 1024 * 1024;
static const int64_t default_additional_reduce_memory = 2048l * 1024 * 1024;
static const int default_map_additional_millicores = 0;
static const int default_reduce_additional_millicores = 500;
int Gru::additional_map_millicores = default_map_additional_millicores;
int Gru::additional_reduce_millicores = default_reduce_additional_millicores;
int64_t Gru::additional_map_memory = default_additional_map_memory;
int64_t Gru::additional_reduce_memory = default_additional_reduce_memory;
Gru::Gru(::baidu::galaxy::sdk::AppMaster* galaxy, JobDescriptor* job,
const std::string& job_id, WorkMode mode) :
galaxy_(galaxy), job_(job), job_id_(job_id), mode_(mode) {
mode_str_ = ((mode == kReduce) ? "reduce" : "map");
minion_name_ = job->name() + "_" + mode_str_;
}
Status Gru::Start() {
::baidu::galaxy::sdk::SubmitJobRequest galaxy_job;
galaxy_job.user.user = FLAGS_galaxy_user;
galaxy_job.user.token = FLAGS_galaxy_token;
galaxy_job.hostname = ::baidu::common::util::GetLocalHostName();
std::vector<std::string> pools;
boost::split(pools, FLAGS_galaxy_pool, boost::is_any_of(","));
galaxy_job.job.deploy.pools = pools;
galaxy_job.job.name = minion_name_ + "@minion";
galaxy_job.job.type = ::baidu::galaxy::sdk::kJobBatch;
if (mode_ == kReduce) {
galaxy_job.job.deploy.replica = std::min(job_->reduce_capacity(),
std::max(job_->reduce_total() * 6 / 5, 20));
} else {
galaxy_job.job.deploy.replica = std::min(job_->map_capacity(),
std::max(job_->map_total() * 6 / 5, 20));
}
galaxy_job.job.deploy.step = std::min((int)FLAGS_galaxy_deploy_step, (int)galaxy_job.job.deploy.replica);
galaxy_job.job.deploy.interval = 1;
galaxy_job.job.deploy.max_per_host = FLAGS_max_minions_per_host;
galaxy_job.job.deploy.update_break_count = 0;
galaxy_job.job.version = "1.0.0";
galaxy_job.job.run_user = "galaxy";
if (!FLAGS_galaxy_node_label.empty()) {
galaxy_job.job.deploy.tag = FLAGS_galaxy_node_label;
}
::baidu::galaxy::sdk::PodDescription & pod_desc = galaxy_job.job.pod;
pod_desc.workspace_volum.size = (3L << 30);
pod_desc.workspace_volum.medium = ::baidu::galaxy::sdk::kDisk;
pod_desc.workspace_volum.exclusive = false;
pod_desc.workspace_volum.readonly = false;
pod_desc.workspace_volum.use_symlink = false;
pod_desc.workspace_volum.dest_path = "/home/shuttle";
pod_desc.workspace_volum.type = ::baidu::galaxy::sdk::kEmptyDir;
::baidu::galaxy::sdk::TaskDescription task_desc;
if (mode_str_ == "map") {
task_desc.cpu.milli_core = job_->millicores() + additional_map_millicores;
} else {
task_desc.cpu.milli_core = job_->millicores() + additional_reduce_millicores;
}
task_desc.memory.size = job_->memory() +
((mode_ == kReduce) ? additional_reduce_memory : additional_map_memory);
std::string app_package;
std::vector<std::string> cache_archive_list;
int file_size = job_->files().size();
for (int i = 0; i < file_size; ++i) {
const std::string& file = job_->files(i);
if (boost::starts_with(file, "hdfs://")) {
cache_archive_list.push_back(file);
} else {
app_package = file;
}
}
std::stringstream ss;
if (!job_->input_dfs().user().empty()) {
ss << "hadoop_job_ugi=" << job_->input_dfs().user()
<< "," << job_->input_dfs().password()
<< " fs_default_name=hdfs://" << job_->input_dfs().host()
<< ":" << job_->input_dfs().port() << " ";
}
for (size_t i = 0; i < cache_archive_list.size(); i++) {
ss << "cache_archive_" << i << "=" << cache_archive_list[i] << " ";
}
ss << "app_package=" << app_package
<< " ./minion_boot.sh -jobid=" << job_id_ << " -nexus_addr=" << FLAGS_nexus_server_list
<< " -master_nexus_path=" << FLAGS_nexus_root_path + FLAGS_master_path
<< " -work_mode=" << ((mode_ == kMapOnly) ? "map-only" : mode_str_);
std::stringstream ss_stop;
ss_stop << "source ./hdfs_env.sh; ./minion -jobid=" << job_id_ << " -nexus_addr=" << FLAGS_nexus_server_list
<< " -master_nexus_path=" << FLAGS_nexus_root_path + FLAGS_master_path
<< " -work_mode=" << ((mode_ == kMapOnly) ? "map-only" : mode_str_)
<< " -kill_task";
task_desc.exe_package.package.source_path = FLAGS_minion_path;
task_desc.exe_package.package.dest_path = ".";
task_desc.exe_package.package.version = "1.0";
task_desc.exe_package.start_cmd = ss.str();
task_desc.exe_package.stop_cmd = ss_stop.str().c_str();
task_desc.data_package.reload_cmd = ss.str();
task_desc.tcp_throt.recv_bps_quota = (80L << 20);
task_desc.tcp_throt.send_bps_quota = (80L << 20);
task_desc.blkio.weight = 50;
::baidu::galaxy::sdk::PortRequired port_req;
port_req.port = "dynamic";
port_req.port_name = "NFS_CLIENT_PORT";
task_desc.ports.push_back(port_req);
port_req.port = "dynamic";
port_req.port_name = "MINION_PORT";
task_desc.ports.push_back(port_req);
if (FLAGS_enable_cpu_soft_limit) {
task_desc.cpu.excess = true;
} else {
task_desc.cpu.excess = false;
}
if (FLAGS_enable_memory_soft_limit) {
task_desc.memory.excess = true;
} else {
task_desc.memory.excess = false;
}
pod_desc.tasks.push_back(task_desc);
std::string minion_id;
::baidu::galaxy::sdk::SubmitJobResponse rsps;
if (galaxy_->SubmitJob(galaxy_job, &rsps)) {
minion_id = rsps.jobid;
LOG(INFO, "galaxy job id: %s", minion_id.c_str());
minion_id_ = minion_id;
galaxy_job_ = galaxy_job;
if (minion_id_.empty()) {
LOG(INFO, "can not get galaxy job id");
return kGalaxyError;
}
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
Status Gru::Kill() {
LOG(INFO, "kill galaxy job: %s", minion_id_.c_str());
if (minion_id_.empty()) {
return kOk;
}
::baidu::galaxy::sdk::RemoveJobRequest rqst;
::baidu::galaxy::sdk::RemoveJobResponse rsps;
rqst.jobid = minion_id_;
rqst.user = galaxy_job_.user;
rqst.hostname = ::baidu::common::util::GetLocalHostName();
if (galaxy_->RemoveJob(rqst, &rsps)) {
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
Status Gru::Update(const std::string& priority,
int capacity) {
::baidu::galaxy::sdk::JobDescription job_desc = galaxy_job_.job;
if (!priority.empty()) {
//job_desc.priority = priority;
}
if (capacity != -1) {
job_desc.deploy.replica = capacity;
}
::baidu::galaxy::sdk::UpdateJobRequest rqst;
::baidu::galaxy::sdk::UpdateJobResponse rsps;
rqst.user = galaxy_job_.user;
rqst.job = job_desc;
rqst.jobid = minion_id_;
rqst.hostname = ::baidu::common::util::GetLocalHostName();
rqst.operate = ::baidu::galaxy::sdk::kUpdateJobStart;
if (galaxy_->UpdateJob(rqst, &rsps)) {
if (!priority.empty()) {
//galaxy_job_.priority = priority;
}
if (capacity != -1) {
galaxy_job_.job.deploy.replica = capacity;
}
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
}
}
<|endoftext|> |
<commit_before>#include "gru.h"
#include <sstream>
#include <gflags/gflags.h>
#include <boost/algorithm/string.hpp>
#include <vector>
#include "logging.h"
#include "util.h"
DECLARE_int32(galaxy_deploy_step);
DECLARE_string(minion_path);
DECLARE_string(nexus_server_list);
DECLARE_string(nexus_root_path);
DECLARE_string(master_path);
DECLARE_bool(enable_cpu_soft_limit);
DECLARE_bool(enable_memory_soft_limit);
DECLARE_string(galaxy_node_label);
DECLARE_string(galaxy_user);
DECLARE_string(galaxy_token);
DECLARE_string(galaxy_pool);
DECLARE_int32(max_minions_per_host);
namespace baidu {
namespace shuttle {
static const int64_t default_additional_map_memory = 1024l * 1024 * 1024;
static const int64_t default_additional_reduce_memory = 2048l * 1024 * 1024;
static const int default_map_additional_millicores = 0;
static const int default_reduce_additional_millicores = 500;
int Gru::additional_map_millicores = default_map_additional_millicores;
int Gru::additional_reduce_millicores = default_reduce_additional_millicores;
int64_t Gru::additional_map_memory = default_additional_map_memory;
int64_t Gru::additional_reduce_memory = default_additional_reduce_memory;
Gru::Gru(::baidu::galaxy::sdk::AppMaster* galaxy, JobDescriptor* job,
const std::string& job_id, WorkMode mode) :
galaxy_(galaxy), job_(job), job_id_(job_id), mode_(mode) {
mode_str_ = ((mode == kReduce) ? "reduce" : "map");
minion_name_ = job->name() + "_" + mode_str_;
}
Status Gru::Start() {
::baidu::galaxy::sdk::SubmitJobRequest galaxy_job;
galaxy_job.user.user = FLAGS_galaxy_user;
galaxy_job.user.token = FLAGS_galaxy_token;
galaxy_job.hostname = ::baidu::common::util::GetLocalHostName();
galaxy_job.job.deploy.pools.push_back(FLAGS_galaxy_pool);
galaxy_job.job.name = minion_name_ + "@minion";
galaxy_job.job.type = ::baidu::galaxy::sdk::kJobBatch;
galaxy_job.job.deploy.replica = (mode_ == kReduce) ? job_->reduce_capacity() : job_->map_capacity();
galaxy_job.job.deploy.step = FLAGS_galaxy_deploy_step;
galaxy_job.job.deploy.interval = 1;
galaxy_job.job.deploy.max_per_host = FLAGS_max_minions_per_host;
galaxy_job.job.deploy.update_break_count = 0;
galaxy_job.job.version = "1.0.0";
galaxy_job.job.run_user = "galaxy";
if (!FLAGS_galaxy_node_label.empty()) {
galaxy_job.job.deploy.tag = FLAGS_galaxy_node_label;
}
::baidu::galaxy::sdk::PodDescription & pod_desc = galaxy_job.job.pod;
pod_desc.workspace_volum.size = (3L << 30);
pod_desc.workspace_volum.medium = ::baidu::galaxy::sdk::kDisk;
pod_desc.workspace_volum.exclusive = false;
pod_desc.workspace_volum.readonly = false;
pod_desc.workspace_volum.use_symlink = false;
pod_desc.workspace_volum.dest_path = "/home/shuttle";
pod_desc.workspace_volum.type = ::baidu::galaxy::sdk::kEmptyDir;
::baidu::galaxy::sdk::TaskDescription task_desc;
if (mode_str_ == "map") {
task_desc.cpu.milli_core = job_->millicores() + additional_map_millicores;
} else {
task_desc.cpu.milli_core = job_->millicores() + additional_reduce_millicores;
}
task_desc.memory.size = job_->memory() +
((mode_ == kReduce) ? additional_reduce_memory : additional_map_memory);
std::string app_package;
std::vector<std::string> cache_archive_list;
int file_size = job_->files().size();
for (int i = 0; i < file_size; ++i) {
const std::string& file = job_->files(i);
if (boost::starts_with(file, "hdfs://")) {
cache_archive_list.push_back(file);
} else {
app_package = file;
}
}
std::stringstream ss;
if (!job_->input_dfs().user().empty()) {
ss << "hadoop_job_ugi=" << job_->input_dfs().user()
<< "," << job_->input_dfs().password()
<< " fs_default_name=hdfs://" << job_->input_dfs().host()
<< ":" << job_->input_dfs().port() << " ";
}
for (size_t i = 0; i < cache_archive_list.size(); i++) {
ss << "cache_archive_" << i << "=" << cache_archive_list[i] << " ";
}
ss << "app_package=" << app_package
<< " ./minion_boot.sh -jobid=" << job_id_ << " -nexus_addr=" << FLAGS_nexus_server_list
<< " -master_nexus_path=" << FLAGS_nexus_root_path + FLAGS_master_path
<< " -work_mode=" << ((mode_ == kMapOnly) ? "map-only" : mode_str_);
std::stringstream ss_stop;
ss_stop << "source hdfs_env.sh; ./minion -jobid=" << job_id_ << " -nexus_addr=" << FLAGS_nexus_server_list
<< " -master_nexus_path=" << FLAGS_nexus_root_path + FLAGS_master_path
<< " -work_mode=" << ((mode_ == kMapOnly) ? "map-only" : mode_str_)
<< " -kill_task";
task_desc.exe_package.package.source_path = FLAGS_minion_path;
task_desc.exe_package.package.dest_path = ".";
task_desc.exe_package.package.version = "1.0";
task_desc.exe_package.start_cmd = ss.str().c_str();
task_desc.exe_package.stop_cmd = ss_stop.str().c_str();
task_desc.tcp_throt.recv_bps_quota = (50L << 20);
task_desc.tcp_throt.send_bps_quota = (50L << 20);
task_desc.blkio.weight = 100;
::baidu::galaxy::sdk::PortRequired port_req;
port_req.port = "dynamic";
port_req.port_name = "NFS_CLIENT_PORT";
task_desc.ports.push_back(port_req);
port_req.port = "dynamic";
port_req.port_name = "MINION_PORT";
task_desc.ports.push_back(port_req);
if (FLAGS_enable_cpu_soft_limit) {
task_desc.cpu.excess = true;
} else {
task_desc.cpu.excess = false;
}
if (FLAGS_enable_memory_soft_limit) {
task_desc.memory.excess = true;
} else {
task_desc.memory.excess = false;
}
pod_desc.tasks.push_back(task_desc);
std::string minion_id;
::baidu::galaxy::sdk::SubmitJobResponse rsps;
if (galaxy_->SubmitJob(galaxy_job, &rsps)) {
minion_id = rsps.jobid;
LOG(INFO, "galaxy job id: %s", minion_id.c_str());
minion_id_ = minion_id;
galaxy_job_ = galaxy_job;
if (minion_id_.empty()) {
LOG(INFO, "can not get galaxy job id");
return kGalaxyError;
}
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
Status Gru::Kill() {
LOG(INFO, "kill galaxy job: %s", minion_id_.c_str());
if (minion_id_.empty()) {
return kOk;
}
::baidu::galaxy::sdk::RemoveJobRequest rqst;
::baidu::galaxy::sdk::RemoveJobResponse rsps;
rqst.jobid = minion_id_;
rqst.user = galaxy_job_.user;
rqst.hostname = ::baidu::common::util::GetLocalHostName();
if (galaxy_->RemoveJob(rqst, &rsps)) {
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
Status Gru::Update(const std::string& priority,
int capacity) {
::baidu::galaxy::sdk::JobDescription job_desc = galaxy_job_.job;
if (!priority.empty()) {
//job_desc.priority = priority;
}
if (capacity != -1) {
job_desc.deploy.replica = capacity;
}
::baidu::galaxy::sdk::UpdateJobRequest rqst;
::baidu::galaxy::sdk::UpdateJobResponse rsps;
rqst.user = galaxy_job_.user;
rqst.job = job_desc;
rqst.jobid = minion_id_;
rqst.oprate = ::baidu::galaxy::sdk::kUpdateJobDefault;
rqst.hostname = ::baidu::common::util::GetLocalHostName();
if (galaxy_->UpdateJob(rqst, &rsps)) {
if (!priority.empty()) {
//galaxy_job_.priority = priority;
}
if (capacity != -1) {
galaxy_job_.job.deploy.replica = capacity;
}
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
}
}
<commit_msg>fix typo<commit_after>#include "gru.h"
#include <sstream>
#include <gflags/gflags.h>
#include <boost/algorithm/string.hpp>
#include <vector>
#include "logging.h"
#include "util.h"
DECLARE_int32(galaxy_deploy_step);
DECLARE_string(minion_path);
DECLARE_string(nexus_server_list);
DECLARE_string(nexus_root_path);
DECLARE_string(master_path);
DECLARE_bool(enable_cpu_soft_limit);
DECLARE_bool(enable_memory_soft_limit);
DECLARE_string(galaxy_node_label);
DECLARE_string(galaxy_user);
DECLARE_string(galaxy_token);
DECLARE_string(galaxy_pool);
DECLARE_int32(max_minions_per_host);
namespace baidu {
namespace shuttle {
static const int64_t default_additional_map_memory = 1024l * 1024 * 1024;
static const int64_t default_additional_reduce_memory = 2048l * 1024 * 1024;
static const int default_map_additional_millicores = 0;
static const int default_reduce_additional_millicores = 500;
int Gru::additional_map_millicores = default_map_additional_millicores;
int Gru::additional_reduce_millicores = default_reduce_additional_millicores;
int64_t Gru::additional_map_memory = default_additional_map_memory;
int64_t Gru::additional_reduce_memory = default_additional_reduce_memory;
Gru::Gru(::baidu::galaxy::sdk::AppMaster* galaxy, JobDescriptor* job,
const std::string& job_id, WorkMode mode) :
galaxy_(galaxy), job_(job), job_id_(job_id), mode_(mode) {
mode_str_ = ((mode == kReduce) ? "reduce" : "map");
minion_name_ = job->name() + "_" + mode_str_;
}
Status Gru::Start() {
::baidu::galaxy::sdk::SubmitJobRequest galaxy_job;
galaxy_job.user.user = FLAGS_galaxy_user;
galaxy_job.user.token = FLAGS_galaxy_token;
galaxy_job.hostname = ::baidu::common::util::GetLocalHostName();
galaxy_job.job.deploy.pools.push_back(FLAGS_galaxy_pool);
galaxy_job.job.name = minion_name_ + "@minion";
galaxy_job.job.type = ::baidu::galaxy::sdk::kJobBatch;
galaxy_job.job.deploy.replica = (mode_ == kReduce) ? job_->reduce_capacity() : job_->map_capacity();
galaxy_job.job.deploy.step = FLAGS_galaxy_deploy_step;
galaxy_job.job.deploy.interval = 1;
galaxy_job.job.deploy.max_per_host = FLAGS_max_minions_per_host;
galaxy_job.job.deploy.update_break_count = 0;
galaxy_job.job.version = "1.0.0";
galaxy_job.job.run_user = "galaxy";
if (!FLAGS_galaxy_node_label.empty()) {
galaxy_job.job.deploy.tag = FLAGS_galaxy_node_label;
}
::baidu::galaxy::sdk::PodDescription & pod_desc = galaxy_job.job.pod;
pod_desc.workspace_volum.size = (3L << 30);
pod_desc.workspace_volum.medium = ::baidu::galaxy::sdk::kDisk;
pod_desc.workspace_volum.exclusive = false;
pod_desc.workspace_volum.readonly = false;
pod_desc.workspace_volum.use_symlink = false;
pod_desc.workspace_volum.dest_path = "/home/shuttle";
pod_desc.workspace_volum.type = ::baidu::galaxy::sdk::kEmptyDir;
::baidu::galaxy::sdk::TaskDescription task_desc;
if (mode_str_ == "map") {
task_desc.cpu.milli_core = job_->millicores() + additional_map_millicores;
} else {
task_desc.cpu.milli_core = job_->millicores() + additional_reduce_millicores;
}
task_desc.memory.size = job_->memory() +
((mode_ == kReduce) ? additional_reduce_memory : additional_map_memory);
std::string app_package;
std::vector<std::string> cache_archive_list;
int file_size = job_->files().size();
for (int i = 0; i < file_size; ++i) {
const std::string& file = job_->files(i);
if (boost::starts_with(file, "hdfs://")) {
cache_archive_list.push_back(file);
} else {
app_package = file;
}
}
std::stringstream ss;
if (!job_->input_dfs().user().empty()) {
ss << "hadoop_job_ugi=" << job_->input_dfs().user()
<< "," << job_->input_dfs().password()
<< " fs_default_name=hdfs://" << job_->input_dfs().host()
<< ":" << job_->input_dfs().port() << " ";
}
for (size_t i = 0; i < cache_archive_list.size(); i++) {
ss << "cache_archive_" << i << "=" << cache_archive_list[i] << " ";
}
ss << "app_package=" << app_package
<< " ./minion_boot.sh -jobid=" << job_id_ << " -nexus_addr=" << FLAGS_nexus_server_list
<< " -master_nexus_path=" << FLAGS_nexus_root_path + FLAGS_master_path
<< " -work_mode=" << ((mode_ == kMapOnly) ? "map-only" : mode_str_);
std::stringstream ss_stop;
ss_stop << "source hdfs_env.sh; ./minion -jobid=" << job_id_ << " -nexus_addr=" << FLAGS_nexus_server_list
<< " -master_nexus_path=" << FLAGS_nexus_root_path + FLAGS_master_path
<< " -work_mode=" << ((mode_ == kMapOnly) ? "map-only" : mode_str_)
<< " -kill_task";
task_desc.exe_package.package.source_path = FLAGS_minion_path;
task_desc.exe_package.package.dest_path = ".";
task_desc.exe_package.package.version = "1.0";
task_desc.exe_package.start_cmd = ss.str().c_str();
task_desc.exe_package.stop_cmd = ss_stop.str().c_str();
task_desc.tcp_throt.recv_bps_quota = (50L << 20);
task_desc.tcp_throt.send_bps_quota = (50L << 20);
task_desc.blkio.weight = 100;
::baidu::galaxy::sdk::PortRequired port_req;
port_req.port = "dynamic";
port_req.port_name = "NFS_CLIENT_PORT";
task_desc.ports.push_back(port_req);
port_req.port = "dynamic";
port_req.port_name = "MINION_PORT";
task_desc.ports.push_back(port_req);
if (FLAGS_enable_cpu_soft_limit) {
task_desc.cpu.excess = true;
} else {
task_desc.cpu.excess = false;
}
if (FLAGS_enable_memory_soft_limit) {
task_desc.memory.excess = true;
} else {
task_desc.memory.excess = false;
}
pod_desc.tasks.push_back(task_desc);
std::string minion_id;
::baidu::galaxy::sdk::SubmitJobResponse rsps;
if (galaxy_->SubmitJob(galaxy_job, &rsps)) {
minion_id = rsps.jobid;
LOG(INFO, "galaxy job id: %s", minion_id.c_str());
minion_id_ = minion_id;
galaxy_job_ = galaxy_job;
if (minion_id_.empty()) {
LOG(INFO, "can not get galaxy job id");
return kGalaxyError;
}
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
Status Gru::Kill() {
LOG(INFO, "kill galaxy job: %s", minion_id_.c_str());
if (minion_id_.empty()) {
return kOk;
}
::baidu::galaxy::sdk::RemoveJobRequest rqst;
::baidu::galaxy::sdk::RemoveJobResponse rsps;
rqst.jobid = minion_id_;
rqst.user = galaxy_job_.user;
rqst.hostname = ::baidu::common::util::GetLocalHostName();
if (galaxy_->RemoveJob(rqst, &rsps)) {
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
Status Gru::Update(const std::string& priority,
int capacity) {
::baidu::galaxy::sdk::JobDescription job_desc = galaxy_job_.job;
if (!priority.empty()) {
//job_desc.priority = priority;
}
if (capacity != -1) {
job_desc.deploy.replica = capacity;
}
::baidu::galaxy::sdk::UpdateJobRequest rqst;
::baidu::galaxy::sdk::UpdateJobResponse rsps;
rqst.user = galaxy_job_.user;
rqst.job = job_desc;
rqst.jobid = minion_id_;
rqst.operate = ::baidu::galaxy::sdk::kUpdateJobDefault;
rqst.hostname = ::baidu::common::util::GetLocalHostName();
if (galaxy_->UpdateJob(rqst, &rsps)) {
if (!priority.empty()) {
//galaxy_job_.priority = priority;
}
if (capacity != -1) {
galaxy_job_.job.deploy.replica = capacity;
}
return kOk;
} else {
LOG(WARNING, "galaxy error: %s", rsps.error_code.reason.c_str());
}
return kGalaxyError;
}
}
}
<|endoftext|> |
<commit_before>// Implementation of a linear time algorithm that find the longest palindromic
// substring of a given string.
//
// Author: Mikhail Andrenkov
// Date: October 22, 2017
//
// Credit: This code is a modification of a Manacher's Algorithm implementation
// from https://algs4.cs.princeton.edu/53substring/Manacher.java.html
////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
std::string expand(const std::string&);
std::string solve(const std::string&);
// Returns the longest palindromic substring of |given|.
std::string solve(const std::string &given) {
// Expand the given string to include all palindrome indexes.
std::string pad = expand(given);
// Declare the LPS array to store the longest palindromic substring values.
std::vector<int> lps(pad.size(), 1);
// The center of the active palindrome.
int c = 0;
// The rightmost index of the active palindrome;
int r = 0;
for (int i = 0; i < pad.size(); ++i) {
// The center index of the mirror palindrome.
int j = 2*c - i;
// If |i| is past |r|, no information can be recycled.
if (i < r) {
lps[i] = std::min(r - i, lps[j]);
}
// Check if the current palindrome extends beyond the active palindrome.
int l = lps[i];
while (i - l >= 0 && i + l < pad.size() && pad[i - l] == pad[i + l]) {
++lps[i];
++l;
}
// Update the active palindrome if the current palindrome reaches further right.
if (i + lps[i] - 1 > r) {
c = i;
r = i + lps[i] - 1;
}
}
// Extract the longest palindrome.
auto it = std::max_element(lps.begin(), lps.end());
int index = std::distance(lps.begin(), it);
int size = lps[index];
// Convert the expanded index and length to match the original string.
int start = (index + 1)/2 - size/2;
int length = std::max(1, size - 1);
return given.substr(start, length);
}
// Returns |given| with a "|" inserted before and after character.
std::string expand(const std::string &given) {
std::string buffer = "|";
for (const auto &c : given) {
buffer += c;
buffer += "|";
}
return buffer;
}
// Execution entry point.
int main() {
// Declare some sanity-check tests.
std::vector<std::pair<const std::string, const std::string>> tests = {
{"a", "a"},
{"aba", "aba"},
{"xabbab", "abba"},
{"xababay", "ababa"}
};
for (const auto &p : tests) {
std::string given = p.first;
std::string want = p.second;
std::string lps = solve(given);
std::string result = want == lps ? "PASS" : "FAIL";
std::cout << result << ": ";
std::cout << "solve(\"" << given << "\") = \"" << lps << "\"";
std::cout << ", want \"" << want << "\".\n";
}
return 0;
}
<commit_msg>Fixed several typos in comments.<commit_after>// Implementation of a linear time algorithm that find the longest palindromic
// substring of a given string.
//
// Author: Mikhail Andrenkov
// Date: October 22, 2017
//
// Credit: This code is a modification of a Manacher's Algorithm implementation
// from https://algs4.cs.princeton.edu/53substring/Manacher.java.html
////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
std::string expand(const std::string&);
std::string solve(const std::string&);
// Returns the longest palindromic substring of |given|.
std::string solve(const std::string &given) {
// Expand |given| to represent all palindrome indices.
std::string pad = expand(given);
// Declare an array to store the size of the longest palindromic substring
// at each index of |pad|.
std::vector<int> lps(pad.size(), 1);
// The center of the active palindrome.
int c = 0;
// The rightmost index of the active palindrome.
int r = 0;
for (int i = 0; i < pad.size(); ++i) {
// The center index of the mirror palindrome.
int j = 2*c - i;
// If |i| is past |r|, no previous LPS entries can be reused.
if (i < r) {
lps[i] = std::min(r - i + 1, lps[j]);
}
// Check if the current palindrome extends beyond the active palindrome.
int length = lps[i];
while (i - length >= 0 && i + length < pad.size() && pad[i - length] == pad[i + length]) {
++lps[i];
++length;
}
// Update the active palindrome if the current palindrome reaches further to the right.
int i_r = i + lps[i] - 1;
if (i_r > r) {
c = i;
r = i_r;
}
}
// Extract the index and size of the longest palindromic substring.
auto it = std::max_element(lps.begin(), lps.end());
int index = std::distance(lps.begin(), it);
int size = lps[index];
// Convert the expanded index and size to match the original string.
int start = (index + 1)/2 - size/2;
int length = std::max(1, size - 1);
return given.substr(start, length);
}
// Returns |given| with a "|" inserted before and after character.
std::string expand(const std::string &given) {
std::string buffer = "|";
for (const auto &c : given) {
buffer += c;
buffer += "|";
}
return buffer;
}
// Execution entry point.
int main() {
// Declare some sanity-check tests.
std::vector<std::pair<const std::string, const std::string>> tests = {
{"", ""},
{"a", "a"},
{"aba", "aba"},
{"xabbab", "abba"},
{"xababay", "ababa"}
};
for (const auto &p : tests) {
std::string given = p.first;
std::string want = p.second;
std::string lps = solve(given);
std::string result = want == lps ? "PASS" : "FAIL";
std::cout << result << ": ";
std::cout << "solve(\"" << given << "\") = \"" << lps << "\"";
std::cout << ", want \"" << want << "\".\n";
}
return 0;
}
<|endoftext|> |
<commit_before>/* *** This file is part of bbox ***
*
* Copyright (C) 2010 Andrea Marchesini <baku@ippolita.net>.
*
* This program is free software. It is released under the terms of
* the BSD License. See license.txt for more details.
*/
#include "bbsvn.h"
#include "bbsvnmanager.h"
#include "bbsvnstatus.h"
#include "bbsvninfo.h"
#include "bbsvnlog.h"
#include "bbsettings.h"
#include "bbdebug.h"
#include "bbconst.h"
#include <QDir>
#include <QDateTime>
#include <QMessageBox>
#include <QDesktopServices>
#include <QUrl>
#ifdef Q_OS_WIN32
#include <windows.h>
#include <winbase.h>
#include <Lmcons.h>
#endif
BBSvn::BBSvn(QObject *parent) :
QProcess(0)
{
BBDEBUG;
connect(this,
SIGNAL(finished(int, QProcess::ExitStatus)),
SLOT(onFinished(int, QProcess::ExitStatus)));
if (parent) {
connect(parent,
SIGNAL(destroyed()),
SLOT(onParentDestroyed()));
}
}
BBSvn::~BBSvn()
{
BBDEBUG;
}
void BBSvn::onParentDestroyed()
{
BBDEBUG;
if (state() == NotRunning)
deleteLater();
else {
connect(this,
SIGNAL(done(bool)),
SLOT(deleteLater()));
}
}
void BBSvn::start(const QStringList &arguments)
{
BBDEBUG << arguments;
m_arguments = arguments;
BBSvnManager::instance()->registerForSchedule(this);
}
void BBSvn::schedule()
{
BBDEBUG;
QProcess::start(BBSettings::instance()->svn(), m_arguments, QIODevice::ReadOnly);
}
void BBSvn::onFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
m_errorMessage = readAllStandardError().trimmed();
BBDEBUG << exitCode << exitStatus << m_errorMessage;
bool status(true);
if (exitCode || exitStatus != QProcess::NormalExit)
status = false;
emit done(status);
}
void BBSvn::cleanup()
{
BBDEBUG;
start(QStringList() << "cleanup"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< BBSettings::instance()->directory());
}
void BBSvn::addFile(const QStringList &filenames)
{
BBDEBUG << filenames;
start(QStringList() << "add"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< filenames);
}
void BBSvn::deleteFile(const QString &filename)
{
BBDEBUG << filename;
start(QStringList() << "delete"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< "--keep-local"
<< filename);
}
void BBSvn::status()
{
BBDEBUG;
start(QStringList() << "status"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< BBSettings::instance()->directory());
}
QList<BBSvnStatus*> BBSvn::parseStatus()
{
BBDEBUG;
QByteArray output = readAllStandardOutput();
BBDEBUG << output;
QList<QByteArray> files = output.split('\n');
QList<BBSvnStatus*> list;
foreach(QByteArray file, files) {
BBSvnStatus *status = new BBSvnStatus(this);
switch (file[0]) {
case 'A': // Added
status->setStatus(BBSvnStatus::StatusAdded);
break;
case 'C': // Conflicted
status->setStatus(BBSvnStatus::StatusConflicted);
break;
case 'D': // Deleted
status->setStatus(BBSvnStatus::StatusDeleted);
break;
case 'I': // Ignored
break;
case 'M': // Modified
status->setStatus(BBSvnStatus::StatusModified);
break;
case 'R': // Replaced
status->setStatus(BBSvnStatus::StatusReplaced);
break;
case 'X': // an unversioned directory created by an externals definition
break;
case '?': // item is not under version control
status->setStatus(BBSvnStatus::StatusNew);
break;
case '!': // item is missing (removed by non-svn command) or incomplete
status->setStatus(BBSvnStatus::StatusMissing);
break;
case '~': // versioned item obstructed by some item of a different kind
status->setStatus(BBSvnStatus::StatusObstructed);
break;
}
// Second column is property related
// Third column: lock
if (file[2] == 'L')
status->setLocked(true);
status->setFile(QString(file.remove(0, 8)).trimmed());
if (!status->isValid()) {
status->deleteLater();
} else {
list << status;
}
}
return list;
}
void BBSvn::remoteInfo(const QString& url)
{
BBDEBUG;
start(QStringList() << "info"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< url);
}
void BBSvn::localInfo()
{
BBDEBUG;
start(QStringList() << "info"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< BBSettings::instance()->directory());
}
BBSvnInfo* BBSvn::parseInfo()
{
BBDEBUG;
QByteArray output = readAllStandardOutput();
BBDEBUG << output;
QList<QByteArray> lines = output.split('\n');
BBSvnInfo *info = new BBSvnInfo(this);
foreach (QByteArray line, lines) {
if (line.startsWith("URL: "))
info->setURL(QString(line.remove(0, 5)).trimmed());
else if(line.startsWith("Revision: "))
info->setRevision(QString(line.remove(0, 10)).toUInt());
}
return info;
}
void BBSvn::commit()
{
BBDEBUG;
start(QStringList() << "commit"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< "--trust-server-cert"
<< "-m" << commitMessage()
<< BBSettings::instance()->directory());
}
QString BBSvn::userName() {
#ifdef Q_OS_WIN32
wchar_t winUserName[UNLEN + 1]; // UNLEN is defined in LMCONS.H
DWORD winUserNameSize = sizeof(winUserName);
GetUserNameW( winUserName, &winUserNameSize );
return QString::fromWCharArray( winUserName );
#endif
#ifdef Q_OS_UNIX
return getenv("USER");
#endif
return QString();
}
QString BBSvn::commitMessage()
{
BBDEBUG;
return tr("Update by %1 (user: %2, date: %3)").arg(BBPACKAGE)
.arg(userName())
.arg(QDateTime::currentDateTime().toString());
}
void BBSvn::update()
{
BBDEBUG;
start(QStringList() << "update"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< "--accept" << "postpone"
<< BBSettings::instance()->directory());
}
QList<BBSvnStatus*> BBSvn::parseUpdate()
{
BBDEBUG;
QByteArray output = readAllStandardOutput();
BBDEBUG << output;
QList<QByteArray> files = output.split('\n');
QList<BBSvnStatus*> list;
foreach(QByteArray file, files) {
BBSvnStatus *status = new BBSvnStatus(this);
switch (file[0]) {
case 'A': // Added
status->setStatus(BBSvnStatus::StatusAdded);
break;
case 'D': // Deleted
status->setStatus(BBSvnStatus::StatusDeleted);
break;
case 'U': // Updated
status->setStatus(BBSvnStatus::StatusUpdated);
break;
case 'C': // Conflicted
status->setStatus(BBSvnStatus::StatusConflicted);
break;
case 'G': // Merged
status->setStatus(BBSvnStatus::StatusMerged);
break;
case 'E': // Existed
status->setStatus(BBSvnStatus::StatusExisted);
break;
}
status->setFile(QString(file.remove(0, 5)).trimmed());
if (!status->isValid()) {
status->deleteLater();
} else {
list << status;
}
}
return list;
}
void BBSvn::resolveConflict(const QString& file, bool isLocal)
{
BBDEBUG << file << isLocal;
start(QStringList() << "resolve"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< "--accept"
<< (isLocal ? "mine-full" : "theirs-full")
<< file);
}
bool BBSvn::isACheckout()
{
QDir dir(BBSettings::instance()->directory());
QFileInfo info(dir.absoluteFilePath(".svn"));
return info.exists();
}
void BBSvn::checkout(const QString& url, const QString& username, const QString& password)
{
BBDEBUG << url << username << password;
QStringList list;
list << "checkout"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive";
if (!username.isEmpty())
list << "--username" << username;
if (!password.isEmpty())
list << "--password" << password;
list << url << BBSettings::instance()->directory();
start(list);
}
void BBSvn::remoteLog(const QString& url)
{
BBDEBUG << url;
start(QStringList() << "log"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< "-v" << url);
}
QList<BBSvnLog*> BBSvn::parseLog()
{
BBDEBUG;
QByteArray output = readAllStandardOutput();
BBDEBUG << output;
QList<QByteArray> lines = output.split('\n');
QList<BBSvnLog*> list;
while(!lines.isEmpty()) {
QByteArray line;
line = lines.takeFirst();
if (!line.startsWith("----------------"))
continue;
line = lines.takeFirst();
if (!line.startsWith("r"))
break;
QList<QByteArray> parts = line.split('|');
if (parts.size() < 3)
break;
BBSvnLog *log = new BBSvnLog(parts[0].remove(0,1).trimmed().toUInt(),
parts[1].trimmed(),
parts[2].trimmed(),
this);
line = lines.takeFirst();
if (!line.startsWith("Changed paths:"))
break;
while (1) {
line = lines.takeFirst();
if (line.isEmpty() || line.trimmed().isEmpty())
break;
log->addOperation(line);
}
list << log;
}
return list;
}
void BBSvn::restoreFile(const QString& file, int revision, const QString& destFile)
{
BBDEBUG << file << revision << destFile;
start(QStringList() << "export"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< QString("%1@%2").arg(file).arg(revision)
<< destFile);
}
void BBSvn::openFile(const QString& file, bool local)
{
BBDEBUG << file << local;
QFileInfo info(file);
QString filename(info.fileName());
if (local) {
if (QFile::exists(QString("%1.mine").arg(file)))
openFile(QString("%1.mine").arg(file), filename);
else {
QMessageBox::warning(0,
QString(BBPACKAGE " - %1").arg(tr("Warning")),
tr("The local version seems missing."));
}
} else {
QDir dir(info.dir());
uint maxValue(0);
QFileInfoList list = dir.entryInfoList(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
foreach (QFileInfo info, list) {
if (!info.fileName().startsWith(filename))
continue;
QString ext = info.completeSuffix();
if (!ext.startsWith("r"))
continue;
ext.remove(0, 1);
uint value(ext.toUInt());
if (maxValue < value)
maxValue = value;
}
if (maxValue == 0) {
QMessageBox::warning(0,
QString(BBPACKAGE " - %1").arg(tr("Warning")),
tr("The remove version seems missing."));
} else {
openFile(QString("%1.r%2").arg(file).arg(maxValue), filename);
}
}
}
void BBSvn::openFile(const QString& file, const QString& name)
{
BBDEBUG << file << name;
QString newFile(QDir::temp().absoluteFilePath(name));
if (QFile::exists(newFile))
QFile::remove(newFile);
QFile::copy(file, newFile);
QDesktopServices::openUrl(QUrl::fromLocalFile(newFile));
}
void BBSvn::removeDir(const QDir& dir)
{
BBDEBUG << dir;
if (!dir.exists(BB_SVN_DIR))
return;
BBSvn::removeDir(dir, BB_SVN_DIR);
}
bool BBSvn::removeDir(const QDir& dir, const QString& dirname)
{
BBDEBUG << dir << dirname;
QDir child(dir.absoluteFilePath(dirname));
bool result(true);
QFileInfoList files = child.entryInfoList(QDir::AllEntries | QDir::Hidden | QDir::NoDotAndDotDot);
foreach (QFileInfo file, files) {
if (file.isDir())
result = removeDir(child, file.fileName());
else {
// For windows we need the permission to delete this file:
QFile f(file.absoluteFilePath());
f.setPermissions(QFile::WriteUser | QFile::ReadUser | QFile::ReadOwner | QFile::WriteOwner);
result = f.remove();
}
if (result == false)
return false;
}
return dir.rmdir(dirname);
}
<commit_msg>Close #14 about SSL connections<commit_after>/* *** This file is part of bbox ***
*
* Copyright (C) 2010 Andrea Marchesini <baku@ippolita.net>.
*
* This program is free software. It is released under the terms of
* the BSD License. See license.txt for more details.
*/
#include "bbsvn.h"
#include "bbsvnmanager.h"
#include "bbsvnstatus.h"
#include "bbsvninfo.h"
#include "bbsvnlog.h"
#include "bbsettings.h"
#include "bbdebug.h"
#include "bbconst.h"
#include <QDir>
#include <QDateTime>
#include <QMessageBox>
#include <QDesktopServices>
#include <QUrl>
#ifdef Q_OS_WIN32
#include <windows.h>
#include <winbase.h>
#include <Lmcons.h>
#endif
BBSvn::BBSvn(QObject *parent) :
QProcess(0)
{
BBDEBUG;
connect(this,
SIGNAL(finished(int, QProcess::ExitStatus)),
SLOT(onFinished(int, QProcess::ExitStatus)));
if (parent) {
connect(parent,
SIGNAL(destroyed()),
SLOT(onParentDestroyed()));
}
}
BBSvn::~BBSvn()
{
BBDEBUG;
}
void BBSvn::onParentDestroyed()
{
BBDEBUG;
if (state() == NotRunning)
deleteLater();
else {
connect(this,
SIGNAL(done(bool)),
SLOT(deleteLater()));
}
}
void BBSvn::start(const QStringList &arguments)
{
BBDEBUG << arguments;
m_arguments = arguments;
BBSvnManager::instance()->registerForSchedule(this);
}
void BBSvn::schedule()
{
BBDEBUG;
QProcess::start(BBSettings::instance()->svn(), m_arguments, QIODevice::ReadOnly);
}
void BBSvn::onFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
m_errorMessage = readAllStandardError().trimmed();
BBDEBUG << exitCode << exitStatus << m_errorMessage;
bool status(true);
if (exitCode || exitStatus != QProcess::NormalExit)
status = false;
emit done(status);
}
void BBSvn::cleanup()
{
BBDEBUG;
start(QStringList() << "cleanup"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< "--trust-server-cert"
<< BBSettings::instance()->directory());
}
void BBSvn::addFile(const QStringList &filenames)
{
BBDEBUG << filenames;
start(QStringList() << "add"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< "--trust-server-cert"
<< filenames);
}
void BBSvn::deleteFile(const QString &filename)
{
BBDEBUG << filename;
start(QStringList() << "delete"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< "--trust-server-cert"
<< "--keep-local"
<< filename);
}
void BBSvn::status()
{
BBDEBUG;
start(QStringList() << "status"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< "--trust-server-cert"
<< BBSettings::instance()->directory());
}
QList<BBSvnStatus*> BBSvn::parseStatus()
{
BBDEBUG;
QByteArray output = readAllStandardOutput();
BBDEBUG << output;
QList<QByteArray> files = output.split('\n');
QList<BBSvnStatus*> list;
foreach(QByteArray file, files) {
BBSvnStatus *status = new BBSvnStatus(this);
switch (file[0]) {
case 'A': // Added
status->setStatus(BBSvnStatus::StatusAdded);
break;
case 'C': // Conflicted
status->setStatus(BBSvnStatus::StatusConflicted);
break;
case 'D': // Deleted
status->setStatus(BBSvnStatus::StatusDeleted);
break;
case 'I': // Ignored
break;
case 'M': // Modified
status->setStatus(BBSvnStatus::StatusModified);
break;
case 'R': // Replaced
status->setStatus(BBSvnStatus::StatusReplaced);
break;
case 'X': // an unversioned directory created by an externals definition
break;
case '?': // item is not under version control
status->setStatus(BBSvnStatus::StatusNew);
break;
case '!': // item is missing (removed by non-svn command) or incomplete
status->setStatus(BBSvnStatus::StatusMissing);
break;
case '~': // versioned item obstructed by some item of a different kind
status->setStatus(BBSvnStatus::StatusObstructed);
break;
}
// Second column is property related
// Third column: lock
if (file[2] == 'L')
status->setLocked(true);
status->setFile(QString(file.remove(0, 8)).trimmed());
if (!status->isValid()) {
status->deleteLater();
} else {
list << status;
}
}
return list;
}
void BBSvn::remoteInfo(const QString& url)
{
BBDEBUG;
start(QStringList() << "info"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< "--trust-server-cert"
<< url);
}
void BBSvn::localInfo()
{
BBDEBUG;
start(QStringList() << "info"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< "--trust-server-cert"
<< BBSettings::instance()->directory());
}
BBSvnInfo* BBSvn::parseInfo()
{
BBDEBUG;
QByteArray output = readAllStandardOutput();
BBDEBUG << output;
QList<QByteArray> lines = output.split('\n');
BBSvnInfo *info = new BBSvnInfo(this);
foreach (QByteArray line, lines) {
if (line.startsWith("URL: "))
info->setURL(QString(line.remove(0, 5)).trimmed());
else if(line.startsWith("Revision: "))
info->setRevision(QString(line.remove(0, 10)).toUInt());
}
return info;
}
void BBSvn::commit()
{
BBDEBUG;
start(QStringList() << "commit"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< "--trust-server-cert"
<< "-m" << commitMessage()
<< BBSettings::instance()->directory());
}
QString BBSvn::userName() {
#ifdef Q_OS_WIN32
wchar_t winUserName[UNLEN + 1]; // UNLEN is defined in LMCONS.H
DWORD winUserNameSize = sizeof(winUserName);
GetUserNameW( winUserName, &winUserNameSize );
return QString::fromWCharArray( winUserName );
#endif
#ifdef Q_OS_UNIX
return getenv("USER");
#endif
return QString();
}
QString BBSvn::commitMessage()
{
BBDEBUG;
return tr("Update by %1 (user: %2, date: %3)").arg(BBPACKAGE)
.arg(userName())
.arg(QDateTime::currentDateTime().toString());
}
void BBSvn::update()
{
BBDEBUG;
start(QStringList() << "update"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< "--trust-server-cert"
<< "--accept" << "postpone"
<< BBSettings::instance()->directory());
}
QList<BBSvnStatus*> BBSvn::parseUpdate()
{
BBDEBUG;
QByteArray output = readAllStandardOutput();
BBDEBUG << output;
QList<QByteArray> files = output.split('\n');
QList<BBSvnStatus*> list;
foreach(QByteArray file, files) {
BBSvnStatus *status = new BBSvnStatus(this);
switch (file[0]) {
case 'A': // Added
status->setStatus(BBSvnStatus::StatusAdded);
break;
case 'D': // Deleted
status->setStatus(BBSvnStatus::StatusDeleted);
break;
case 'U': // Updated
status->setStatus(BBSvnStatus::StatusUpdated);
break;
case 'C': // Conflicted
status->setStatus(BBSvnStatus::StatusConflicted);
break;
case 'G': // Merged
status->setStatus(BBSvnStatus::StatusMerged);
break;
case 'E': // Existed
status->setStatus(BBSvnStatus::StatusExisted);
break;
}
status->setFile(QString(file.remove(0, 5)).trimmed());
if (!status->isValid()) {
status->deleteLater();
} else {
list << status;
}
}
return list;
}
void BBSvn::resolveConflict(const QString& file, bool isLocal)
{
BBDEBUG << file << isLocal;
start(QStringList() << "resolve"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< "--trust-server-cert"
<< "--accept"
<< (isLocal ? "mine-full" : "theirs-full")
<< file);
}
bool BBSvn::isACheckout()
{
QDir dir(BBSettings::instance()->directory());
QFileInfo info(dir.absoluteFilePath(".svn"));
return info.exists();
}
void BBSvn::checkout(const QString& url, const QString& username, const QString& password)
{
BBDEBUG << url << username << password;
QStringList list;
list << "checkout"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< "--trust-server-cert";
if (!username.isEmpty())
list << "--username" << username;
if (!password.isEmpty())
list << "--password" << password;
list << url << BBSettings::instance()->directory();
start(list);
}
void BBSvn::remoteLog(const QString& url)
{
BBDEBUG << url;
start(QStringList() << "log"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< "--trust-server-cert"
<< "-v" << url);
}
QList<BBSvnLog*> BBSvn::parseLog()
{
BBDEBUG;
QByteArray output = readAllStandardOutput();
BBDEBUG << output;
QList<QByteArray> lines = output.split('\n');
QList<BBSvnLog*> list;
while(!lines.isEmpty()) {
QByteArray line;
line = lines.takeFirst();
if (!line.startsWith("----------------"))
continue;
line = lines.takeFirst();
if (!line.startsWith("r"))
break;
QList<QByteArray> parts = line.split('|');
if (parts.size() < 3)
break;
BBSvnLog *log = new BBSvnLog(parts[0].remove(0,1).trimmed().toUInt(),
parts[1].trimmed(),
parts[2].trimmed(),
this);
line = lines.takeFirst();
if (!line.startsWith("Changed paths:"))
break;
while (1) {
line = lines.takeFirst();
if (line.isEmpty() || line.trimmed().isEmpty())
break;
log->addOperation(line);
}
list << log;
}
return list;
}
void BBSvn::restoreFile(const QString& file, int revision, const QString& destFile)
{
BBDEBUG << file << revision << destFile;
start(QStringList() << "export"
<< BBSvnManager::instance()->svnConfigParams()
<< "--non-interactive"
<< "--trust-server-cert"
<< QString("%1@%2").arg(file).arg(revision)
<< destFile);
}
void BBSvn::openFile(const QString& file, bool local)
{
BBDEBUG << file << local;
QFileInfo info(file);
QString filename(info.fileName());
if (local) {
if (QFile::exists(QString("%1.mine").arg(file)))
openFile(QString("%1.mine").arg(file), filename);
else {
QMessageBox::warning(0,
QString(BBPACKAGE " - %1").arg(tr("Warning")),
tr("The local version seems missing."));
}
} else {
QDir dir(info.dir());
uint maxValue(0);
QFileInfoList list = dir.entryInfoList(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
foreach (QFileInfo info, list) {
if (!info.fileName().startsWith(filename))
continue;
QString ext = info.completeSuffix();
if (!ext.startsWith("r"))
continue;
ext.remove(0, 1);
uint value(ext.toUInt());
if (maxValue < value)
maxValue = value;
}
if (maxValue == 0) {
QMessageBox::warning(0,
QString(BBPACKAGE " - %1").arg(tr("Warning")),
tr("The remove version seems missing."));
} else {
openFile(QString("%1.r%2").arg(file).arg(maxValue), filename);
}
}
}
void BBSvn::openFile(const QString& file, const QString& name)
{
BBDEBUG << file << name;
QString newFile(QDir::temp().absoluteFilePath(name));
if (QFile::exists(newFile))
QFile::remove(newFile);
QFile::copy(file, newFile);
QDesktopServices::openUrl(QUrl::fromLocalFile(newFile));
}
void BBSvn::removeDir(const QDir& dir)
{
BBDEBUG << dir;
if (!dir.exists(BB_SVN_DIR))
return;
BBSvn::removeDir(dir, BB_SVN_DIR);
}
bool BBSvn::removeDir(const QDir& dir, const QString& dirname)
{
BBDEBUG << dir << dirname;
QDir child(dir.absoluteFilePath(dirname));
bool result(true);
QFileInfoList files = child.entryInfoList(QDir::AllEntries | QDir::Hidden | QDir::NoDotAndDotDot);
foreach (QFileInfo file, files) {
if (file.isDir())
result = removeDir(child, file.fileName());
else {
// For windows we need the permission to delete this file:
QFile f(file.absoluteFilePath());
f.setPermissions(QFile::WriteUser | QFile::ReadUser | QFile::ReadOwner | QFile::WriteOwner);
result = f.remove();
}
if (result == false)
return false;
}
return dir.rmdir(dirname);
}
<|endoftext|> |
<commit_before>// This code is licensed under the New BSD license.
// See LICENSE.txt for more details.
#include <iostream>
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Host.h"
#include "clang/Frontend/DiagnosticOptions.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Basic/FileManager.h"
#include "clang/Frontend/HeaderSearchOptions.h"
#include "clang/Frontend/Utils.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Frontend/PreprocessorOptions.h"
#include "clang/Frontend/FrontendOptions.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/Builtins.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/Sema/Sema.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/Type.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Ownership.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Parse/Parser.h"
#include "clang/Parse/ParseAST.h"
class MyASTConsumer : public clang::ASTConsumer
{
public:
clang::SourceManager *aSourceManager;
MyASTConsumer(clang::SourceManager *sourceManager) : clang::ASTConsumer(), aSourceManager(sourceManager) { }
virtual ~MyASTConsumer() { }
virtual void HandleTopLevelDecl( clang::DeclGroupRef d)
{
static int count = 0;
clang::DeclGroupRef::iterator it;
for( it = d.begin(); it != d.end(); it++)
{
count++;
clang::ObjCInterfaceDecl *vdc = dyn_cast<clang::ObjCInterfaceDecl>(*it);
if (!vdc)
{
continue;
}
std::cout << "Classname: "
<< vdc->getNameAsString()
<< " LineNum: "
<< aSourceManager->getInstantiationLineNumber(vdc->getClassLoc())
<< " Column: "
<< aSourceManager->getInstantiationColumnNumber(vdc->getClassLoc())
<< " Filename: "
<< aSourceManager->getBufferName(vdc->getClassLoc())
<< " File offset "
<< aSourceManager->getFileOffset(vdc->getClassLoc())
<< std::endl;
}
}
};
class ETagsWriter
{
public:
ETagsWriter() { }
virtual ~ETagsWriter() { }
virtual int openFile(const char* filename)
{
// return FD
return 0;
}
virtual void closeFile(int file)
{
}
virtual void startSection(const char* sourceName)
{
}
virtual void closeSection()
{
}
virtual void addTag(const char* tagDefinition, const char* tagName, unsigned int lineNumber, unsigned int byteOffset)
{
}
};
int main()
{
clang::DiagnosticOptions diagnosticOptions;
clang::TextDiagnosticPrinter *pTextDiagnosticPrinter =
new clang::TextDiagnosticPrinter(
llvm::outs(),
diagnosticOptions);
llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> pDiagIDs;
clang::Diagnostic diagnostic(pDiagIDs, pTextDiagnosticPrinter);
clang::LangOptions languageOptions;
languageOptions.ObjC1 = 1;
languageOptions.ObjC2 = 1;
clang::FileSystemOptions fileSystemOptions;
clang::FileManager fileManager(fileSystemOptions);
clang::SourceManager sourceManager(
diagnostic,
fileManager);
clang::HeaderSearch headerSearch(fileManager);
clang::HeaderSearchOptions headerSearchOptions;
// <Warning!!> -- Platform Specific Code lives here
// This depends on A) that you're running linux and
// B) that you have the same GCC LIBs installed that
// I do.
// Search through Clang itself for something like this,
// go on, you won't find it. The reason why is Clang
// has its own versions of std* which are installed under
// /usr/local/lib/clang/<version>/include/
// See somewhere around Driver.cpp:77 to see Clang adding
// its version of the headers to its include path.
headerSearchOptions.AddPath("/usr/include/linux",
clang::frontend::Angled,
false,
false,
false);
headerSearchOptions.AddPath("/usr/include/c++/4.4/tr1",
clang::frontend::Angled,
false,
false,
false);
headerSearchOptions.AddPath("/usr/include/c++/4.4",
clang::frontend::Angled,
false,
false,
false);
// </Warning!!> -- End of Platform Specific Code
clang::TargetOptions targetOptions;
targetOptions.Triple = llvm::sys::getHostTriple();
clang::TargetInfo *pTargetInfo =
clang::TargetInfo::CreateTargetInfo(
diagnostic,
targetOptions);
clang::ApplyHeaderSearchOptions(
headerSearch,
headerSearchOptions,
languageOptions,
pTargetInfo->getTriple());
clang::Preprocessor preprocessor(
diagnostic,
languageOptions,
*pTargetInfo,
sourceManager,
headerSearch);
clang::PreprocessorOptions preprocessorOptions;
clang::FrontendOptions frontendOptions;
clang::InitializePreprocessor(
preprocessor,
preprocessorOptions,
headerSearchOptions,
frontendOptions);
const clang::FileEntry *pFile = fileManager.getFile(
"DCILatLon.m");
sourceManager.createMainFileID(pFile);
//preprocessor.EnterMainSourceFile();
const clang::TargetInfo &targetInfo = *pTargetInfo;
clang::IdentifierTable identifierTable(languageOptions);
clang::SelectorTable selectorTable;
clang::Builtin::Context builtinContext(targetInfo);
clang::ASTContext astContext(
languageOptions,
sourceManager,
targetInfo,
identifierTable,
selectorTable,
builtinContext,
0 /* size_reserve*/);
// clang::ASTConsumer astConsumer;
MyASTConsumer astConsumer(&sourceManager);
clang::Sema sema(
preprocessor,
astContext,
astConsumer);
sema.Initialize();
//MySemanticAnalisys mySema( preprocessor, astContext, astConsumer);
//clang::Parser parser( preprocessor, sema);
//parser.ParseTranslationUnit();
pTextDiagnosticPrinter->BeginSourceFile(languageOptions, &preprocessor);
clang::ParseAST(preprocessor, &astConsumer, astContext);
pTextDiagnosticPrinter->EndSourceFile();
return 0;
}
<commit_msg>Flesh out ETagsWriter. Change closeFile to not take any params.<commit_after>// This code is licensed under the New BSD license.
// See LICENSE.txt for more details.
#include <iostream>
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Host.h"
#include "clang/Frontend/DiagnosticOptions.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Basic/FileManager.h"
#include "clang/Frontend/HeaderSearchOptions.h"
#include "clang/Frontend/Utils.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Frontend/PreprocessorOptions.h"
#include "clang/Frontend/FrontendOptions.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/Builtins.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/Sema/Sema.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/Type.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Ownership.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Parse/Parser.h"
#include "clang/Parse/ParseAST.h"
#include <fcntl.h>
#include <unistd.h>
//std-c lib
#include <list>
class MyASTConsumer : public clang::ASTConsumer
{
public:
clang::SourceManager *aSourceManager;
MyASTConsumer(clang::SourceManager *sourceManager) : clang::ASTConsumer(), aSourceManager(sourceManager) { }
virtual ~MyASTConsumer() { }
virtual void HandleTopLevelDecl( clang::DeclGroupRef d)
{
static int count = 0;
clang::DeclGroupRef::iterator it;
for( it = d.begin(); it != d.end(); it++)
{
count++;
clang::ObjCInterfaceDecl *vdc = dyn_cast<clang::ObjCInterfaceDecl>(*it);
if (!vdc)
{
continue;
}
std::cout << "Classname: "
<< vdc->getNameAsString()
<< " LineNum: "
<< aSourceManager->getInstantiationLineNumber(vdc->getClassLoc())
<< " Column: "
<< aSourceManager->getInstantiationColumnNumber(vdc->getClassLoc())
<< " Filename: "
<< aSourceManager->getBufferName(vdc->getClassLoc())
<< " File offset "
<< aSourceManager->getFileOffset(vdc->getClassLoc())
<< std::endl;
}
}
};
class ETagsWriter
{
public:
ETagsWriter() : m_FD(-1) { }
virtual ~ETagsWriter()
{
if (m_FD != -1)
{
close(m_FD);
m_FD = -1;
}
}
virtual int openFile(const char* filename)
{
m_FD = open(filename, O_CREAT | O_TRUNC);
return m_FD;
}
virtual void closeFile()
{
close(m_FD);
m_FD = -1;
}
virtual void startSection(const char* sourceName)
{
char c[2] = { 0x0c, 0x0a };
int result = doWrite(m_FD, c, 2);
result = doWrite(m_FD, sourceName, strlen(sourceName));
result = doWrite(m_FD, ",", 1);
}
virtual void closeSection()
{
int totalSize = 0;
char buf[32];
for (std::list<const char*>::iterator it = m_tagDefinitions.begin(); it != m_tagDefinitions.end(); it++)
{
std::cout << "Symbol: '" << (*it) << "' is " << strlen(*it) << " bytes long" << std::endl;
totalSize += strlen(*it);
}
// Now that I have the total size, write it out to the head
sprintf(buf, "%d\n", totalSize);
int result = doWrite(m_FD, buf, strlen(buf));
for (std::list<const char*>::iterator it = m_tagDefinitions.begin(); it != m_tagDefinitions.end(); it++)
{
result = doWrite(m_FD, (*it), strlen(*it));
delete *it;
}
}
virtual void addTag(const char* tagDefinition, const char* tagName, unsigned int lineNumber, unsigned int byteOffset)
{
char buf[2048];
sprintf(buf, "%s%d%s%d%d,%d\n", tagDefinition, 0x7f, tagName, 0x01, lineNumber, byteOffset);
m_tagDefinitions.push_back(buf);
}
protected:
int doWrite(int FD, const void* buf, int totalBytes)
{
int result = write(FD, buf, totalBytes);
if (result <= 0)
{
std::cout << "Error " << result << "writing to file; ETAGS file probably won't be readable" << std::endl;
}
return result;
}
private:
mutable int m_FD; // File Descriptor.
std::list<const char *> m_tagDefinitions;
};
int main()
{
clang::DiagnosticOptions diagnosticOptions;
clang::TextDiagnosticPrinter *pTextDiagnosticPrinter =
new clang::TextDiagnosticPrinter(
llvm::outs(),
diagnosticOptions);
llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> pDiagIDs;
clang::Diagnostic diagnostic(pDiagIDs, pTextDiagnosticPrinter);
clang::LangOptions languageOptions;
languageOptions.ObjC1 = 1;
languageOptions.ObjC2 = 1;
clang::FileSystemOptions fileSystemOptions;
clang::FileManager fileManager(fileSystemOptions);
clang::SourceManager sourceManager(
diagnostic,
fileManager);
clang::HeaderSearch headerSearch(fileManager);
clang::HeaderSearchOptions headerSearchOptions;
// <Warning!!> -- Platform Specific Code lives here
// This depends on A) that you're running linux and
// B) that you have the same GCC LIBs installed that
// I do.
// Search through Clang itself for something like this,
// go on, you won't find it. The reason why is Clang
// has its own versions of std* which are installed under
// /usr/local/lib/clang/<version>/include/
// See somewhere around Driver.cpp:77 to see Clang adding
// its version of the headers to its include path.
headerSearchOptions.AddPath("/usr/include/linux",
clang::frontend::Angled,
false,
false,
false);
headerSearchOptions.AddPath("/usr/include/c++/4.4/tr1",
clang::frontend::Angled,
false,
false,
false);
headerSearchOptions.AddPath("/usr/include/c++/4.4",
clang::frontend::Angled,
false,
false,
false);
// </Warning!!> -- End of Platform Specific Code
clang::TargetOptions targetOptions;
targetOptions.Triple = llvm::sys::getHostTriple();
clang::TargetInfo *pTargetInfo =
clang::TargetInfo::CreateTargetInfo(
diagnostic,
targetOptions);
clang::ApplyHeaderSearchOptions(
headerSearch,
headerSearchOptions,
languageOptions,
pTargetInfo->getTriple());
clang::Preprocessor preprocessor(
diagnostic,
languageOptions,
*pTargetInfo,
sourceManager,
headerSearch);
clang::PreprocessorOptions preprocessorOptions;
clang::FrontendOptions frontendOptions;
clang::InitializePreprocessor(
preprocessor,
preprocessorOptions,
headerSearchOptions,
frontendOptions);
const clang::FileEntry *pFile = fileManager.getFile(
"DCILatLon.m");
sourceManager.createMainFileID(pFile);
//preprocessor.EnterMainSourceFile();
const clang::TargetInfo &targetInfo = *pTargetInfo;
clang::IdentifierTable identifierTable(languageOptions);
clang::SelectorTable selectorTable;
clang::Builtin::Context builtinContext(targetInfo);
clang::ASTContext astContext(
languageOptions,
sourceManager,
targetInfo,
identifierTable,
selectorTable,
builtinContext,
0 /* size_reserve*/);
// clang::ASTConsumer astConsumer;
MyASTConsumer astConsumer(&sourceManager);
clang::Sema sema(
preprocessor,
astContext,
astConsumer);
sema.Initialize();
//MySemanticAnalisys mySema( preprocessor, astContext, astConsumer);
//clang::Parser parser( preprocessor, sema);
//parser.ParseTranslationUnit();
pTextDiagnosticPrinter->BeginSourceFile(languageOptions, &preprocessor);
clang::ParseAST(preprocessor, &astConsumer, astContext);
pTextDiagnosticPrinter->EndSourceFile();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009 Toni Gundogdu.
*
* This file is part of cclive.
*
* cclive 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.
*
* cclive is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "hosthandler.h"
BreakHandler::BreakHandler()
: HostHandler()
{
props.setHost ("break");
props.setDomain ("break.com");
props.setFormats("flv");
}
void
BreakHandler::parseId() {
std::string id;
partialMatch("(?i)contentid='(.*?)'", &id);
props.setId(id);
}
void
BreakHandler::parseTitle() {
std::string title;
partialMatch("(?i)id=\"vid_title\" content=\"(.*?)\"", &title);
props.setTitle(title);
}
void
BreakHandler::parseLink() {
std::string fpath;
partialMatch("(?i)contentfilepath='(.*?)'", &fpath);
std::string fname;
partialMatch("(?i)filename='(.*?)'", &fname);
std::string lnk =
"http://media1.break.com/dnet/media/" +fpath+ "/" +fname+ ".flv";
props.setLink(lnk);
}
<commit_msg>Fix: break.com support (http/403).<commit_after>/*
* Copyright (C) 2009 Toni Gundogdu.
*
* This file is part of cclive.
*
* cclive 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.
*
* cclive is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "hosthandler.h"
BreakHandler::BreakHandler()
: HostHandler()
{
props.setHost ("break");
props.setDomain ("break.com");
props.setFormats("flv");
}
void
BreakHandler::parseId() {
std::string id;
partialMatch("(?i)contentid='(.*?)'", &id);
props.setId(id);
}
void
BreakHandler::parseTitle() {
std::string title;
partialMatch("(?i)id=\"vid_title\" content=\"(.*?)\"", &title);
props.setTitle(title);
}
void
BreakHandler::parseLink() {
std::string fpath;
partialMatch("(?i)contentfilepath='(.*?)'", &fpath);
std::string fname;
partialMatch("(?i)filename='(.*?)'", &fname);
std::string lnk =
"http://video1.break.com/dnet/media/" +fpath+ "/" +fname+ ".flv";
props.setLink(lnk);
}
<|endoftext|> |
<commit_before>#include <v8.h>
#include <node.h>
#include <string>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include "sass_context_wrapper.h"
using namespace v8;
using namespace std;
void WorkOnContext(uv_work_t* req) {
sass_context_wrapper* ctx_w = static_cast<sass_context_wrapper*>(req->data);
sass_context* ctx = static_cast<sass_context*>(ctx_w->ctx);
sass_compile(ctx);
}
void MakeOldCallback(uv_work_t* req) {
HandleScope scope;
TryCatch try_catch;
sass_context_wrapper* ctx_w = static_cast<sass_context_wrapper*>(req->data);
sass_context* ctx = static_cast<sass_context*>(ctx_w->ctx);
if (ctx->error_status == 0) {
// if no error, do callback(null, result)
const unsigned argc = 2;
Local<Value> argv[argc] = {
Local<Value>::New(Null()),
Local<Value>::New(String::New(ctx->output_string))
};
ctx_w->callback->Call(Context::GetCurrent()->Global(), argc, argv);
} else {
// if error, do callback(error)
const unsigned argc = 1;
Local<Value> argv[argc] = {
Local<Value>::New(String::New(ctx->error_message))
};
ctx_w->callback->Call(Context::GetCurrent()->Global(), argc, argv);
}
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
delete ctx->source_string;
sass_free_context_wrapper(ctx_w);
}
Handle<Value> OldRender(const Arguments& args) {
HandleScope scope;
sass_context* ctx = sass_new_context();
sass_context_wrapper* ctx_w = sass_new_context_wrapper();
char *source;
String::AsciiValue astr(args[0]);
Local<Function> callback = Local<Function>::Cast(args[1]);
String::AsciiValue bstr(args[2]);
source = new char[strlen(*astr)+1];
strcpy(source, *astr);
ctx->source_string = source;
ctx->options.include_paths = new char[strlen(*bstr)+1];
ctx->options.image_path = new char[0];
strcpy(ctx->options.include_paths, *bstr);
// ctx->options.output_style = SASS_STYLE_NESTED;
ctx->options.output_style = args[3]->Int32Value();
ctx->options.source_comments = args[4]->Int32Value();
ctx_w->ctx = ctx;
ctx_w->callback = Persistent<Function>::New(callback);
ctx_w->request.data = ctx_w;
int status = uv_queue_work(uv_default_loop(), &ctx_w->request, WorkOnContext, (uv_after_work_cb)MakeOldCallback);
assert(status == 0);
return scope.Close(Undefined());
}
void MakeCallback(uv_work_t* req) {
HandleScope scope;
TryCatch try_catch;
sass_context_wrapper* ctx_w = static_cast<sass_context_wrapper*>(req->data);
sass_context* ctx = static_cast<sass_context*>(ctx_w->ctx);
if (ctx->error_status == 0) {
// if no error, do callback(null, result)
const unsigned argc = 1;
Local<Value> argv[argc] = {
Local<Value>::New(String::New(ctx->output_string))
};
ctx_w->callback->Call(Context::GetCurrent()->Global(), argc, argv);
} else {
// if error, do callback(error)
const unsigned argc = 1;
Local<Value> argv[argc] = {
Local<Value>::New(String::New(ctx->error_message))
};
ctx_w->errorCallback->Call(Context::GetCurrent()->Global(), argc, argv);
}
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
delete ctx->source_string;
sass_free_context_wrapper(ctx_w);
}
Handle<Value> Render(const Arguments& args) {
HandleScope scope;
sass_context* ctx = sass_new_context();
sass_context_wrapper* ctx_w = sass_new_context_wrapper();
char *source;
String::AsciiValue astr(args[0]);
Local<Function> callback = Local<Function>::Cast(args[1]);
Local<Function> errorCallback = Local<Function>::Cast(args[2]);
String::AsciiValue bstr(args[3]);
source = new char[strlen(*astr)+1];
strcpy(source, *astr);
ctx->source_string = source;
ctx->options.include_paths = new char[strlen(*bstr)+1];
strcpy(ctx->options.include_paths, *bstr);
// ctx->options.output_style = SASS_STYLE_NESTED;
ctx->options.image_path = new char[0];
ctx->options.output_style = args[4]->Int32Value();
ctx->options.source_comments = args[5]->Int32Value();
ctx_w->ctx = ctx;
ctx_w->callback = Persistent<Function>::New(callback);
ctx_w->errorCallback = Persistent<Function>::New(errorCallback);
ctx_w->request.data = ctx_w;
int status = uv_queue_work(uv_default_loop(), &ctx_w->request, WorkOnContext, (uv_after_work_cb)MakeCallback);
assert(status == 0);
return scope.Close(Undefined());
}
Handle<Value> RenderSync(const Arguments& args) {
HandleScope scope;
sass_context* ctx = sass_new_context();
char *source;
String::AsciiValue astr(args[0]);
String::AsciiValue bstr(args[1]);
source = new char[strlen(*astr)+1];
strcpy(source, *astr);
ctx->source_string = source;
ctx->options.include_paths = new char[strlen(*bstr)+1];
strcpy(ctx->options.include_paths, *bstr);
ctx->options.output_style = args[2]->Int32Value();
ctx->options.image_path = new char[0];
ctx->options.source_comments = args[3]->Int32Value();
sass_compile(ctx);
source = NULL;
delete ctx->source_string;
ctx->source_string = NULL;
delete ctx->options.include_paths;
ctx->options.include_paths = NULL;
if (ctx->error_status == 0) {
Local<Value> output = Local<Value>::New(String::New(ctx->output_string));
sass_free_context(ctx);
return scope.Close(output);
}
Local<String> error = String::New(ctx->error_message);
sass_free_context(ctx);
ThrowException(Exception::Error(error));
return scope.Close(Undefined());
}
/**
Rendering Files
**/
void WorkOnFileContext(uv_work_t* req) {
sass_file_context_wrapper* ctx_w = static_cast<sass_file_context_wrapper*>(req->data);
sass_file_context* ctx = static_cast<sass_file_context*>(ctx_w->ctx);
sass_compile_file(ctx);
}
void MakeFileCallback(uv_work_t* req) {
HandleScope scope;
TryCatch try_catch;
sass_file_context_wrapper* ctx_w = static_cast<sass_file_context_wrapper*>(req->data);
sass_file_context* ctx = static_cast<sass_file_context*>(ctx_w->ctx);
if (ctx->error_status == 0) {
// if no error, do callback(null, result)
const unsigned argc = 1;
Local<Value> argv[argc] = {
Local<Value>::New(String::New(ctx->output_string))
};
ctx_w->callback->Call(Context::GetCurrent()->Global(), argc, argv);
} else {
// if error, do callback(error)
const unsigned argc = 1;
Local<Value> argv[argc] = {
Local<Value>::New(String::New(ctx->error_message))
};
ctx_w->errorCallback->Call(Context::GetCurrent()->Global(), argc, argv);
}
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
delete ctx->input_path;
sass_free_file_context_wrapper(ctx_w);
}
Handle<Value> RenderFile(const Arguments& args) {
HandleScope scope;
sass_file_context* ctx = sass_new_file_context();
sass_file_context_wrapper* ctx_w = sass_new_file_context_wrapper();
char *filename;
String::AsciiValue astr(args[0]);
Local<Function> callback = Local<Function>::Cast(args[1]);
Local<Function> errorCallback = Local<Function>::Cast(args[2]);
String::AsciiValue bstr(args[3]);
filename = new char[strlen(*astr)+1];
strcpy(filename, *astr);
ctx->input_path = filename;
ctx->options.include_paths = new char[strlen(*bstr)+1];
strcpy(ctx->options.include_paths, *bstr);
// ctx->options.output_style = SASS_STYLE_NESTED;
ctx->options.output_style = args[4]->Int32Value();
ctx->options.image_path = new char[0];
ctx->options.source_comments = args[5]->Int32Value();
ctx_w->ctx = ctx;
ctx_w->callback = Persistent<Function>::New(callback);
ctx_w->errorCallback = Persistent<Function>::New(errorCallback);
ctx_w->request.data = ctx_w;
int status = uv_queue_work(uv_default_loop(), &ctx_w->request, WorkOnFileContext, (uv_after_work_cb)MakeFileCallback);
assert(status == 0);
return scope.Close(Undefined());
}
Handle<Value> RenderFileSync(const Arguments& args) {
HandleScope scope;
sass_file_context* ctx = sass_new_file_context();
char *filename;
String::AsciiValue astr(args[0]);
String::AsciiValue bstr(args[1]);
filename = new char[strlen(*astr)+1];
strcpy(filename, *astr);
ctx->input_path = filename;
ctx->options.include_paths = new char[strlen(*bstr)+1];
strcpy(ctx->options.include_paths, *bstr);
ctx->options.output_style = args[2]->Int32Value();
ctx->options.source_comments = args[3]->Int32Value();
sass_compile_file(ctx);
filename = NULL;
delete ctx->input_path;
ctx->input_path = NULL;
delete ctx->options.include_paths;
ctx->options.include_paths = NULL;
if (ctx->error_status == 0) {
Local<Value> output = Local<Value>::New(String::New(ctx->output_string));
sass_free_file_context(ctx);
return scope.Close(output);
}
Local<String> error = String::New(ctx->error_message);
sass_free_file_context(ctx);
ThrowException(Exception::Error(error));
return scope.Close(Undefined());
}
void RegisterModule(v8::Handle<v8::Object> target) {
NODE_SET_METHOD(target, "oldRender", OldRender);
NODE_SET_METHOD(target, "render", Render);
NODE_SET_METHOD(target, "renderSync", RenderSync);
NODE_SET_METHOD(target, "renderFile", RenderFile);
NODE_SET_METHOD(target, "renderFileSync", RenderFileSync);
}
NODE_MODULE(binding, RegisterModule);
<commit_msg>Fixed issue with sync rendering<commit_after>#include <v8.h>
#include <node.h>
#include <string>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include "sass_context_wrapper.h"
using namespace v8;
using namespace std;
void WorkOnContext(uv_work_t* req) {
sass_context_wrapper* ctx_w = static_cast<sass_context_wrapper*>(req->data);
sass_context* ctx = static_cast<sass_context*>(ctx_w->ctx);
sass_compile(ctx);
}
void MakeOldCallback(uv_work_t* req) {
HandleScope scope;
TryCatch try_catch;
sass_context_wrapper* ctx_w = static_cast<sass_context_wrapper*>(req->data);
sass_context* ctx = static_cast<sass_context*>(ctx_w->ctx);
if (ctx->error_status == 0) {
// if no error, do callback(null, result)
const unsigned argc = 2;
Local<Value> argv[argc] = {
Local<Value>::New(Null()),
Local<Value>::New(String::New(ctx->output_string))
};
ctx_w->callback->Call(Context::GetCurrent()->Global(), argc, argv);
} else {
// if error, do callback(error)
const unsigned argc = 1;
Local<Value> argv[argc] = {
Local<Value>::New(String::New(ctx->error_message))
};
ctx_w->callback->Call(Context::GetCurrent()->Global(), argc, argv);
}
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
delete ctx->source_string;
sass_free_context_wrapper(ctx_w);
}
Handle<Value> OldRender(const Arguments& args) {
HandleScope scope;
sass_context* ctx = sass_new_context();
sass_context_wrapper* ctx_w = sass_new_context_wrapper();
char *source;
String::AsciiValue astr(args[0]);
Local<Function> callback = Local<Function>::Cast(args[1]);
String::AsciiValue bstr(args[2]);
source = new char[strlen(*astr)+1];
strcpy(source, *astr);
ctx->source_string = source;
ctx->options.include_paths = new char[strlen(*bstr)+1];
ctx->options.image_path = new char[0];
strcpy(ctx->options.include_paths, *bstr);
// ctx->options.output_style = SASS_STYLE_NESTED;
ctx->options.output_style = args[3]->Int32Value();
ctx->options.source_comments = args[4]->Int32Value();
ctx_w->ctx = ctx;
ctx_w->callback = Persistent<Function>::New(callback);
ctx_w->request.data = ctx_w;
int status = uv_queue_work(uv_default_loop(), &ctx_w->request, WorkOnContext, (uv_after_work_cb)MakeOldCallback);
assert(status == 0);
return scope.Close(Undefined());
}
void MakeCallback(uv_work_t* req) {
HandleScope scope;
TryCatch try_catch;
sass_context_wrapper* ctx_w = static_cast<sass_context_wrapper*>(req->data);
sass_context* ctx = static_cast<sass_context*>(ctx_w->ctx);
if (ctx->error_status == 0) {
// if no error, do callback(null, result)
const unsigned argc = 1;
Local<Value> argv[argc] = {
Local<Value>::New(String::New(ctx->output_string))
};
ctx_w->callback->Call(Context::GetCurrent()->Global(), argc, argv);
} else {
// if error, do callback(error)
const unsigned argc = 1;
Local<Value> argv[argc] = {
Local<Value>::New(String::New(ctx->error_message))
};
ctx_w->errorCallback->Call(Context::GetCurrent()->Global(), argc, argv);
}
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
delete ctx->source_string;
sass_free_context_wrapper(ctx_w);
}
Handle<Value> Render(const Arguments& args) {
HandleScope scope;
sass_context* ctx = sass_new_context();
sass_context_wrapper* ctx_w = sass_new_context_wrapper();
char *source;
String::AsciiValue astr(args[0]);
Local<Function> callback = Local<Function>::Cast(args[1]);
Local<Function> errorCallback = Local<Function>::Cast(args[2]);
String::AsciiValue bstr(args[3]);
source = new char[strlen(*astr)+1];
strcpy(source, *astr);
ctx->source_string = source;
ctx->options.include_paths = new char[strlen(*bstr)+1];
strcpy(ctx->options.include_paths, *bstr);
// ctx->options.output_style = SASS_STYLE_NESTED;
ctx->options.image_path = new char[0];
ctx->options.output_style = args[4]->Int32Value();
ctx->options.source_comments = args[5]->Int32Value();
ctx_w->ctx = ctx;
ctx_w->callback = Persistent<Function>::New(callback);
ctx_w->errorCallback = Persistent<Function>::New(errorCallback);
ctx_w->request.data = ctx_w;
int status = uv_queue_work(uv_default_loop(), &ctx_w->request, WorkOnContext, (uv_after_work_cb)MakeCallback);
assert(status == 0);
return scope.Close(Undefined());
}
Handle<Value> RenderSync(const Arguments& args) {
HandleScope scope;
sass_context* ctx = sass_new_context();
char *source;
String::AsciiValue astr(args[0]);
String::AsciiValue bstr(args[1]);
source = new char[strlen(*astr)+1];
strcpy(source, *astr);
ctx->source_string = source;
ctx->options.include_paths = new char[strlen(*bstr)+1];
strcpy(ctx->options.include_paths, *bstr);
ctx->options.output_style = args[2]->Int32Value();
ctx->options.image_path = new char[0];
ctx->options.source_comments = args[3]->Int32Value();
sass_compile(ctx);
source = NULL;
delete ctx->source_string;
ctx->source_string = NULL;
delete ctx->options.include_paths;
ctx->options.include_paths = NULL;
delete ctx->options.image_path;
ctx->options.image_path = NULL;
if (ctx->error_status == 0) {
Local<Value> output = Local<Value>::New(String::New(ctx->output_string));
sass_free_context(ctx);
return scope.Close(output);
}
Local<String> error = String::New(ctx->error_message);
sass_free_context(ctx);
ThrowException(Exception::Error(error));
return scope.Close(Undefined());
}
/**
Rendering Files
**/
void WorkOnFileContext(uv_work_t* req) {
sass_file_context_wrapper* ctx_w = static_cast<sass_file_context_wrapper*>(req->data);
sass_file_context* ctx = static_cast<sass_file_context*>(ctx_w->ctx);
sass_compile_file(ctx);
}
void MakeFileCallback(uv_work_t* req) {
HandleScope scope;
TryCatch try_catch;
sass_file_context_wrapper* ctx_w = static_cast<sass_file_context_wrapper*>(req->data);
sass_file_context* ctx = static_cast<sass_file_context*>(ctx_w->ctx);
if (ctx->error_status == 0) {
// if no error, do callback(null, result)
const unsigned argc = 1;
Local<Value> argv[argc] = {
Local<Value>::New(String::New(ctx->output_string))
};
ctx_w->callback->Call(Context::GetCurrent()->Global(), argc, argv);
} else {
// if error, do callback(error)
const unsigned argc = 1;
Local<Value> argv[argc] = {
Local<Value>::New(String::New(ctx->error_message))
};
ctx_w->errorCallback->Call(Context::GetCurrent()->Global(), argc, argv);
}
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
delete ctx->input_path;
sass_free_file_context_wrapper(ctx_w);
}
Handle<Value> RenderFile(const Arguments& args) {
HandleScope scope;
sass_file_context* ctx = sass_new_file_context();
sass_file_context_wrapper* ctx_w = sass_new_file_context_wrapper();
char *filename;
String::AsciiValue astr(args[0]);
Local<Function> callback = Local<Function>::Cast(args[1]);
Local<Function> errorCallback = Local<Function>::Cast(args[2]);
String::AsciiValue bstr(args[3]);
filename = new char[strlen(*astr)+1];
strcpy(filename, *astr);
ctx->input_path = filename;
ctx->options.include_paths = new char[strlen(*bstr)+1];
strcpy(ctx->options.include_paths, *bstr);
// ctx->options.output_style = SASS_STYLE_NESTED;
ctx->options.output_style = args[4]->Int32Value();
ctx->options.image_path = new char[0];
ctx->options.source_comments = args[5]->Int32Value();
ctx_w->ctx = ctx;
ctx_w->callback = Persistent<Function>::New(callback);
ctx_w->errorCallback = Persistent<Function>::New(errorCallback);
ctx_w->request.data = ctx_w;
int status = uv_queue_work(uv_default_loop(), &ctx_w->request, WorkOnFileContext, (uv_after_work_cb)MakeFileCallback);
assert(status == 0);
return scope.Close(Undefined());
}
Handle<Value> RenderFileSync(const Arguments& args) {
HandleScope scope;
sass_file_context* ctx = sass_new_file_context();
char *filename;
String::AsciiValue astr(args[0]);
String::AsciiValue bstr(args[1]);
filename = new char[strlen(*astr)+1];
strcpy(filename, *astr);
ctx->input_path = filename;
ctx->options.include_paths = new char[strlen(*bstr)+1];
strcpy(ctx->options.include_paths, *bstr);
ctx->options.image_path = new char[0];
ctx->options.output_style = args[2]->Int32Value();
ctx->options.source_comments = args[3]->Int32Value();
sass_compile_file(ctx);
filename = NULL;
delete ctx->input_path;
ctx->input_path = NULL;
delete ctx->options.include_paths;
ctx->options.include_paths = NULL;
delete ctx->options.image_path;
ctx->options.image_path = NULL;
if (ctx->error_status == 0) {
Local<Value> output = Local<Value>::New(String::New(ctx->output_string));
sass_free_file_context(ctx);
return scope.Close(output);
}
Local<String> error = String::New(ctx->error_message);
sass_free_file_context(ctx);
ThrowException(Exception::Error(error));
return scope.Close(Undefined());
}
void RegisterModule(v8::Handle<v8::Object> target) {
NODE_SET_METHOD(target, "oldRender", OldRender);
NODE_SET_METHOD(target, "render", Render);
NODE_SET_METHOD(target, "renderSync", RenderSync);
NODE_SET_METHOD(target, "renderFile", RenderFile);
NODE_SET_METHOD(target, "renderFileSync", RenderFileSync);
}
NODE_MODULE(binding, RegisterModule);
<|endoftext|> |
<commit_before>#include "buffer.hh"
#include "buffer_manager.hh"
#include "window.hh"
#include "assert.hh"
#include "utils.hh"
#include "context.hh"
#include "utf8.hh"
#include <algorithm>
namespace Kakoune
{
Buffer::Buffer(String name, Flags flags, std::vector<String> lines)
: m_name(std::move(name)), m_flags(flags | Flags::NoUndo),
m_history(), m_history_cursor(m_history.begin()),
m_last_save_undo_index(0),
m_timestamp(0),
m_hooks(GlobalHooks::instance()),
m_options(GlobalOptions::instance())
{
BufferManager::instance().register_buffer(*this);
if (lines.empty())
lines.emplace_back("\n");
ByteCount pos = 0;
m_lines.reserve(lines.size());
for (auto& line : lines)
{
assert(not line.empty() and line.back() == '\n');
m_lines.emplace_back(Line{ pos, std::move(line) });
pos += m_lines.back().length();
}
Editor editor_for_hooks(*this);
Context context(editor_for_hooks);
if (flags & Flags::File and flags & Flags::New)
m_hooks.run_hook("BufNew", m_name, context);
else
m_hooks.run_hook("BufOpen", m_name, context);
m_hooks.run_hook("BufCreate", m_name, context);
// now we may begin to record undo data
m_flags = flags;
}
Buffer::~Buffer()
{
{
Editor hook_editor{*this};
Context hook_context{hook_editor};
m_hooks.run_hook("BufClose", m_name, hook_context);
}
BufferManager::instance().unregister_buffer(*this);
assert(m_change_listeners.empty());
}
BufferIterator Buffer::iterator_at(const BufferCoord& line_and_column,
bool avoid_eol) const
{
return BufferIterator(*this, clamp(line_and_column, avoid_eol));
}
ByteCount Buffer::line_length(LineCount line) const
{
assert(line < line_count());
ByteCount end = (line < line_count() - 1) ?
m_lines[line + 1].start : character_count();
return end - m_lines[line].start;
}
BufferCoord Buffer::clamp(const BufferCoord& line_and_column,
bool avoid_eol) const
{
if (m_lines.empty())
return BufferCoord();
BufferCoord result(line_and_column.line, line_and_column.column);
result.line = Kakoune::clamp(result.line, 0_line, line_count() - 1);
ByteCount max_col = std::max(0_byte, line_length(result.line) - (avoid_eol ? 2 : 1));
result.column = Kakoune::clamp(result.column, 0_byte, max_col);
return result;
}
BufferIterator Buffer::iterator_at_line_begin(const BufferIterator& iterator) const
{
return BufferIterator(*this, { iterator.line(), 0 });
}
BufferIterator Buffer::iterator_at_line_begin(LineCount line) const
{
line = Kakoune::clamp(line, 0_line, line_count()-1);
assert(line_length(line) > 0);
return BufferIterator(*this, { line, 0 });
}
BufferIterator Buffer::iterator_at_line_end(const BufferIterator& iterator) const
{
LineCount line = iterator.line();
assert(line_length(line) > 0);
return ++BufferIterator(*this, { line, line_length(line) - 1 });
}
BufferIterator Buffer::iterator_at_line_end(LineCount line) const
{
line = Kakoune::clamp(line, 0_line, line_count()-1);
assert(line_length(line) > 0);
return ++BufferIterator(*this, { line, line_length(line) - 1 });
}
BufferIterator Buffer::begin() const
{
return BufferIterator(*this, { 0_line, 0 });
}
BufferIterator Buffer::end() const
{
if (m_lines.empty())
return BufferIterator(*this, { 0_line, 0 });
return BufferIterator(*this, { line_count()-1, m_lines.back().length() });
}
ByteCount Buffer::character_count() const
{
if (m_lines.empty())
return 0;
return m_lines.back().start + m_lines.back().length();
}
LineCount Buffer::line_count() const
{
return LineCount(m_lines.size());
}
String Buffer::string(const BufferIterator& begin, const BufferIterator& end) const
{
String res;
for (LineCount line = begin.line(); line <= end.line(); ++line)
{
ByteCount start = 0;
if (line == begin.line())
start = begin.column();
ByteCount count = -1;
if (line == end.line())
count = end.column() - start;
res += m_lines[line].content.substr(start, count);
}
return res;
}
void Buffer::begin_undo_group()
{
if (m_flags & Flags::NoUndo)
return;
assert(m_current_undo_group.empty());
m_history.erase(m_history_cursor, m_history.end());
if (m_history.size() < m_last_save_undo_index)
m_last_save_undo_index = -1;
m_history_cursor = m_history.end();
}
void Buffer::end_undo_group()
{
if (m_flags & Flags::NoUndo)
return;
if (m_current_undo_group.empty())
return;
m_history.push_back(std::move(m_current_undo_group));
m_history_cursor = m_history.end();
m_current_undo_group.clear();
}
// A Modification holds a single atomic modification to Buffer
struct Buffer::Modification
{
enum Type { Insert, Erase };
Type type;
BufferIterator position;
String content;
Modification(Type type, BufferIterator position, String content)
: type(type), position(position), content(std::move(content)) {}
Modification inverse() const
{
Type inverse_type;
switch (type)
{
case Insert: inverse_type = Erase; break;
case Erase: inverse_type = Insert; break;
default: assert(false);
}
return Modification(inverse_type, position, content);
}
};
bool Buffer::undo()
{
if (m_history_cursor == m_history.begin())
return false;
--m_history_cursor;
for (const Modification& modification : reversed(*m_history_cursor))
apply_modification(modification.inverse());
return true;
}
bool Buffer::redo()
{
if (m_history_cursor == m_history.end())
return false;
for (const Modification& modification : *m_history_cursor)
apply_modification(modification);
++m_history_cursor;
return true;
}
void Buffer::check_invariant() const
{
ByteCount start = 0;
assert(not m_lines.empty());
for (auto& line : m_lines)
{
assert(line.start == start);
assert(line.length() > 0);
assert(line.content.back() == '\n');
start += line.length();
}
}
void Buffer::do_insert(const BufferIterator& pos, const String& content)
{
assert(pos.is_end() or utf8::is_character_start(pos));
++m_timestamp;
ByteCount offset = pos.offset();
// all following lines advanced by length
for (LineCount i = pos.line()+1; i < line_count(); ++i)
m_lines[i].start += content.length();
BufferIterator begin_it;
BufferIterator end_it;
// if we inserted at the end of the buffer, we may have created a new
// line without inserting a '\n'
if (pos == end() and (pos == begin() or *(pos-1) == '\n'))
{
ByteCount start = 0;
for (ByteCount i = 0; i < content.length(); ++i)
{
if (content[i] == '\n')
{
m_lines.push_back({ offset + start, content.substr(start, i + 1 - start) });
start = i + 1;
}
}
if (start != content.length())
m_lines.push_back({ offset + start, content.substr(start) });
begin_it = pos;
end_it = end();
}
else
{
String prefix = m_lines[pos.line()].content.substr(0, pos.column());
String suffix = m_lines[pos.line()].content.substr(pos.column());
auto line_it = m_lines.begin() + (int)pos.line();
line_it = m_lines.erase(line_it);
ByteCount start = 0;
for (ByteCount i = 0; i < content.length(); ++i)
{
if (content[i] == '\n')
{
String line_content = content.substr(start, i + 1 - start);
if (start == 0)
{
line_content = prefix + line_content;
line_it = m_lines.insert(line_it, { offset + start - prefix.length(),
std::move(line_content) });
}
else
line_it = m_lines.insert(line_it, { offset + start,
std::move(line_content) });
++line_it;
start = i + 1;
}
}
if (start == 0)
line_it = m_lines.insert(line_it, { offset + start - prefix.length(), prefix + content + suffix });
else if (start != content.length() or not suffix.empty())
line_it = m_lines.insert(line_it, { offset + start, content.substr(start) + suffix });
else
--line_it;
begin_it = pos;
end_it = BufferIterator(*this, { LineCount(line_it - m_lines.begin()),
line_it->length() - suffix.length() });
}
check_invariant();
for (auto listener : m_change_listeners)
listener->on_insert(begin_it, end_it);
}
void Buffer::do_erase(const BufferIterator& begin, const BufferIterator& end)
{
assert(utf8::is_character_start(begin) and
(end.is_end() or utf8::is_character_start(end)));
++m_timestamp;
const ByteCount length = end - begin;
String prefix = m_lines[begin.line()].content.substr(0, begin.column());
String suffix = m_lines[end.line()].content.substr(end.column());
Line new_line = { m_lines[begin.line()].start, prefix + suffix };
m_lines.erase(m_lines.begin() + (int)begin.line(), m_lines.begin() + (int)end.line() + 1);
if (new_line.length() != 0)
m_lines.insert(m_lines.begin() + (int)begin.line(), std::move(new_line));
for (LineCount i = begin.line()+1; i < line_count(); ++i)
m_lines[i].start -= length;
check_invariant();
for (auto listener : m_change_listeners)
listener->on_erase(begin, end);
}
void Buffer::apply_modification(const Modification& modification)
{
const String& content = modification.content;
const BufferIterator& pos = modification.position;
switch (modification.type)
{
case Modification::Insert:
{
do_insert(pos < end() ? pos : end(), content);
break;
}
case Modification::Erase:
{
ByteCount count = content.length();
BufferIterator end = pos + count;
assert(string(pos, end) == content);
do_erase(pos, end);
break;
}
default:
assert(false);
}
}
void Buffer::insert(BufferIterator pos, String content)
{
if (content.empty())
return;
if (pos.is_end() and content.back() != '\n')
content += '\n';
if (not (m_flags & Flags::NoUndo))
m_current_undo_group.emplace_back(Modification::Insert, pos, content);
do_insert(pos, content);
}
void Buffer::erase(BufferIterator begin, BufferIterator end)
{
if (end.is_end() and (begin.column() != 0 or begin.is_begin()))
--end;
if (begin == end)
return;
if (not (m_flags & Flags::NoUndo))
m_current_undo_group.emplace_back(Modification::Erase, begin,
string(begin, end));
do_erase(begin, end);
}
bool Buffer::is_modified() const
{
size_t history_cursor_index = m_history_cursor - m_history.begin();
return m_last_save_undo_index != history_cursor_index
or not m_current_undo_group.empty();
}
void Buffer::notify_saved()
{
if (not m_current_undo_group.empty())
{
end_undo_group();
begin_undo_group();
}
m_flags &= ~Flags::New;
size_t history_cursor_index = m_history_cursor - m_history.begin();
if (m_last_save_undo_index != history_cursor_index)
{
++m_timestamp;
m_last_save_undo_index = history_cursor_index;
}
}
}
<commit_msg>Buffer: check that newlines are at the end of lines<commit_after>#include "buffer.hh"
#include "buffer_manager.hh"
#include "window.hh"
#include "assert.hh"
#include "utils.hh"
#include "context.hh"
#include "utf8.hh"
#include <algorithm>
namespace Kakoune
{
Buffer::Buffer(String name, Flags flags, std::vector<String> lines)
: m_name(std::move(name)), m_flags(flags | Flags::NoUndo),
m_history(), m_history_cursor(m_history.begin()),
m_last_save_undo_index(0),
m_timestamp(0),
m_hooks(GlobalHooks::instance()),
m_options(GlobalOptions::instance())
{
BufferManager::instance().register_buffer(*this);
if (lines.empty())
lines.emplace_back("\n");
ByteCount pos = 0;
m_lines.reserve(lines.size());
for (auto& line : lines)
{
assert(not line.empty() and line.back() == '\n');
m_lines.emplace_back(Line{ pos, std::move(line) });
pos += m_lines.back().length();
}
Editor editor_for_hooks(*this);
Context context(editor_for_hooks);
if (flags & Flags::File and flags & Flags::New)
m_hooks.run_hook("BufNew", m_name, context);
else
m_hooks.run_hook("BufOpen", m_name, context);
m_hooks.run_hook("BufCreate", m_name, context);
// now we may begin to record undo data
m_flags = flags;
}
Buffer::~Buffer()
{
{
Editor hook_editor{*this};
Context hook_context{hook_editor};
m_hooks.run_hook("BufClose", m_name, hook_context);
}
BufferManager::instance().unregister_buffer(*this);
assert(m_change_listeners.empty());
}
BufferIterator Buffer::iterator_at(const BufferCoord& line_and_column,
bool avoid_eol) const
{
return BufferIterator(*this, clamp(line_and_column, avoid_eol));
}
ByteCount Buffer::line_length(LineCount line) const
{
assert(line < line_count());
ByteCount end = (line < line_count() - 1) ?
m_lines[line + 1].start : character_count();
return end - m_lines[line].start;
}
BufferCoord Buffer::clamp(const BufferCoord& line_and_column,
bool avoid_eol) const
{
if (m_lines.empty())
return BufferCoord();
BufferCoord result(line_and_column.line, line_and_column.column);
result.line = Kakoune::clamp(result.line, 0_line, line_count() - 1);
ByteCount max_col = std::max(0_byte, line_length(result.line) - (avoid_eol ? 2 : 1));
result.column = Kakoune::clamp(result.column, 0_byte, max_col);
return result;
}
BufferIterator Buffer::iterator_at_line_begin(const BufferIterator& iterator) const
{
return BufferIterator(*this, { iterator.line(), 0 });
}
BufferIterator Buffer::iterator_at_line_begin(LineCount line) const
{
line = Kakoune::clamp(line, 0_line, line_count()-1);
assert(line_length(line) > 0);
return BufferIterator(*this, { line, 0 });
}
BufferIterator Buffer::iterator_at_line_end(const BufferIterator& iterator) const
{
LineCount line = iterator.line();
assert(line_length(line) > 0);
return ++BufferIterator(*this, { line, line_length(line) - 1 });
}
BufferIterator Buffer::iterator_at_line_end(LineCount line) const
{
line = Kakoune::clamp(line, 0_line, line_count()-1);
assert(line_length(line) > 0);
return ++BufferIterator(*this, { line, line_length(line) - 1 });
}
BufferIterator Buffer::begin() const
{
return BufferIterator(*this, { 0_line, 0 });
}
BufferIterator Buffer::end() const
{
if (m_lines.empty())
return BufferIterator(*this, { 0_line, 0 });
return BufferIterator(*this, { line_count()-1, m_lines.back().length() });
}
ByteCount Buffer::character_count() const
{
if (m_lines.empty())
return 0;
return m_lines.back().start + m_lines.back().length();
}
LineCount Buffer::line_count() const
{
return LineCount(m_lines.size());
}
String Buffer::string(const BufferIterator& begin, const BufferIterator& end) const
{
String res;
for (LineCount line = begin.line(); line <= end.line(); ++line)
{
ByteCount start = 0;
if (line == begin.line())
start = begin.column();
ByteCount count = -1;
if (line == end.line())
count = end.column() - start;
res += m_lines[line].content.substr(start, count);
}
return res;
}
void Buffer::begin_undo_group()
{
if (m_flags & Flags::NoUndo)
return;
assert(m_current_undo_group.empty());
m_history.erase(m_history_cursor, m_history.end());
if (m_history.size() < m_last_save_undo_index)
m_last_save_undo_index = -1;
m_history_cursor = m_history.end();
}
void Buffer::end_undo_group()
{
if (m_flags & Flags::NoUndo)
return;
if (m_current_undo_group.empty())
return;
m_history.push_back(std::move(m_current_undo_group));
m_history_cursor = m_history.end();
m_current_undo_group.clear();
}
// A Modification holds a single atomic modification to Buffer
struct Buffer::Modification
{
enum Type { Insert, Erase };
Type type;
BufferIterator position;
String content;
Modification(Type type, BufferIterator position, String content)
: type(type), position(position), content(std::move(content)) {}
Modification inverse() const
{
Type inverse_type;
switch (type)
{
case Insert: inverse_type = Erase; break;
case Erase: inverse_type = Insert; break;
default: assert(false);
}
return Modification(inverse_type, position, content);
}
};
bool Buffer::undo()
{
if (m_history_cursor == m_history.begin())
return false;
--m_history_cursor;
for (const Modification& modification : reversed(*m_history_cursor))
apply_modification(modification.inverse());
return true;
}
bool Buffer::redo()
{
if (m_history_cursor == m_history.end())
return false;
for (const Modification& modification : *m_history_cursor)
apply_modification(modification);
++m_history_cursor;
return true;
}
void Buffer::check_invariant() const
{
ByteCount start = 0;
assert(not m_lines.empty());
for (auto& line : m_lines)
{
assert(line.start == start);
assert(line.length() > 0);
assert(line.content.back() == '\n');
assert(find(line.content, '\n') == line.content.end()-1);
start += line.length();
}
}
void Buffer::do_insert(const BufferIterator& pos, const String& content)
{
assert(pos.is_end() or utf8::is_character_start(pos));
++m_timestamp;
ByteCount offset = pos.offset();
// all following lines advanced by length
for (LineCount i = pos.line()+1; i < line_count(); ++i)
m_lines[i].start += content.length();
BufferIterator begin_it;
BufferIterator end_it;
// if we inserted at the end of the buffer, we may have created a new
// line without inserting a '\n'
if (pos == end() and (pos == begin() or *(pos-1) == '\n'))
{
ByteCount start = 0;
for (ByteCount i = 0; i < content.length(); ++i)
{
if (content[i] == '\n')
{
m_lines.push_back({ offset + start, content.substr(start, i + 1 - start) });
start = i + 1;
}
}
if (start != content.length())
m_lines.push_back({ offset + start, content.substr(start) });
begin_it = pos;
end_it = end();
}
else
{
String prefix = m_lines[pos.line()].content.substr(0, pos.column());
String suffix = m_lines[pos.line()].content.substr(pos.column());
auto line_it = m_lines.begin() + (int)pos.line();
line_it = m_lines.erase(line_it);
ByteCount start = 0;
for (ByteCount i = 0; i < content.length(); ++i)
{
if (content[i] == '\n')
{
String line_content = content.substr(start, i + 1 - start);
if (start == 0)
{
line_content = prefix + line_content;
line_it = m_lines.insert(line_it, { offset + start - prefix.length(),
std::move(line_content) });
}
else
line_it = m_lines.insert(line_it, { offset + start,
std::move(line_content) });
++line_it;
start = i + 1;
}
}
if (start == 0)
line_it = m_lines.insert(line_it, { offset + start - prefix.length(), prefix + content + suffix });
else if (start != content.length() or not suffix.empty())
line_it = m_lines.insert(line_it, { offset + start, content.substr(start) + suffix });
else
--line_it;
begin_it = pos;
end_it = BufferIterator(*this, { LineCount(line_it - m_lines.begin()),
line_it->length() - suffix.length() });
}
check_invariant();
for (auto listener : m_change_listeners)
listener->on_insert(begin_it, end_it);
}
void Buffer::do_erase(const BufferIterator& begin, const BufferIterator& end)
{
assert(utf8::is_character_start(begin) and
(end.is_end() or utf8::is_character_start(end)));
++m_timestamp;
const ByteCount length = end - begin;
String prefix = m_lines[begin.line()].content.substr(0, begin.column());
String suffix = m_lines[end.line()].content.substr(end.column());
Line new_line = { m_lines[begin.line()].start, prefix + suffix };
m_lines.erase(m_lines.begin() + (int)begin.line(), m_lines.begin() + (int)end.line() + 1);
if (new_line.length() != 0)
m_lines.insert(m_lines.begin() + (int)begin.line(), std::move(new_line));
for (LineCount i = begin.line()+1; i < line_count(); ++i)
m_lines[i].start -= length;
check_invariant();
for (auto listener : m_change_listeners)
listener->on_erase(begin, end);
}
void Buffer::apply_modification(const Modification& modification)
{
const String& content = modification.content;
const BufferIterator& pos = modification.position;
switch (modification.type)
{
case Modification::Insert:
{
do_insert(pos < end() ? pos : end(), content);
break;
}
case Modification::Erase:
{
ByteCount count = content.length();
BufferIterator end = pos + count;
assert(string(pos, end) == content);
do_erase(pos, end);
break;
}
default:
assert(false);
}
}
void Buffer::insert(BufferIterator pos, String content)
{
if (content.empty())
return;
if (pos.is_end() and content.back() != '\n')
content += '\n';
if (not (m_flags & Flags::NoUndo))
m_current_undo_group.emplace_back(Modification::Insert, pos, content);
do_insert(pos, content);
}
void Buffer::erase(BufferIterator begin, BufferIterator end)
{
if (end.is_end() and (begin.column() != 0 or begin.is_begin()))
--end;
if (begin == end)
return;
if (not (m_flags & Flags::NoUndo))
m_current_undo_group.emplace_back(Modification::Erase, begin,
string(begin, end));
do_erase(begin, end);
}
bool Buffer::is_modified() const
{
size_t history_cursor_index = m_history_cursor - m_history.begin();
return m_last_save_undo_index != history_cursor_index
or not m_current_undo_group.empty();
}
void Buffer::notify_saved()
{
if (not m_current_undo_group.empty())
{
end_undo_group();
begin_undo_group();
}
m_flags &= ~Flags::New;
size_t history_cursor_index = m_history_cursor - m_history.begin();
if (m_last_save_undo_index != history_cursor_index)
{
++m_timestamp;
m_last_save_undo_index = history_cursor_index;
}
}
}
<|endoftext|> |
<commit_before>#include "ext-common.h"
#include "log.h"
#include "applet-connection.h"
#include "ext-utils.h"
#include "commands.h"
namespace seafile {
uint64_t reposInfoTimestamp = 0;
std::string toString(RepoInfo::Status st) {
switch (st) {
case RepoInfo::NoStatus:
return "nostatus";
case RepoInfo::Paused:
return "paused";
case RepoInfo::Normal:
return "synced";
case RepoInfo::Syncing:
return "syncing";
case RepoInfo::Error:
return "error";
case RepoInfo::N_Status:
return "";
}
return "";
}
GetShareLinkCommand::GetShareLinkCommand(const std::string path)
: AppletCommand<void>("get-share-link"),
path_(path)
{
}
std::string GetShareLinkCommand::serialize()
{
return path_;
}
ListReposCommand::ListReposCommand()
: AppletCommand<RepoInfoList>("list-repos")
{
}
std::string ListReposCommand::serialize()
{
char buf[512];
snprintf (buf, sizeof(buf), "%I64u", reposInfoTimestamp);
return buf;
}
bool ListReposCommand::parseResponse(const std::string& raw_resp,
RepoInfoList *infos)
{
std::vector<std::string> lines = utils::split(raw_resp, '\n');
if (lines.empty()) {
return true;
}
for (size_t i = 0; i < lines.size(); i++) {
std::string line = lines[i];
std::vector<std::string> parts = utils::split(line, '\t');
if (parts.size() != 4) {
continue;
}
std::string repo_id, repo_name, worktree, status;
RepoInfo::Status st;
repo_id = parts[0];
repo_name = parts[1];
worktree = utils::normalizedPath(parts[2]);
status = parts[3];
if (status == "paused") {
st = RepoInfo::Paused;
} else if (status == "syncing") {
st = RepoInfo::Syncing;
} else if (status == "error") {
st = RepoInfo::Error;
} else if (status == "normal") {
st = RepoInfo::Normal;
} else {
// impossible
seaf_ext_log ("bad repo status \"%s\"", status.c_str());
continue;
}
// seaf_ext_log ("status for %s is \"%s\"", repo_name.c_str(), status.c_str());
infos->push_back(RepoInfo(repo_id, repo_name, worktree, st));
}
reposInfoTimestamp = utils::currentMSecsSinceEpoch();
return true;
}
GetFileStatusCommand::GetFileStatusCommand(const std::string& repo_id,
const std::string& path_in_repo,
bool isdir)
: AppletCommand<RepoInfo::Status>("get-file-status"),
repo_id_(repo_id),
path_in_repo_(path_in_repo),
isdir_(isdir)
{
}
std::string GetFileStatusCommand::serialize()
{
char buf[512];
snprintf (buf, sizeof(buf), "%s\t%s\t%s",
repo_id_.c_str(), path_in_repo_.c_str(), isdir_ ? "true" : "false");
return buf;
}
bool GetFileStatusCommand::parseResponse(const std::string& raw_resp,
RepoInfo::Status *status)
{
// seaf_ext_log ("raw_resp is %s\n", raw_resp.c_str());
if (raw_resp == "syncing") {
*status = RepoInfo::Syncing;
} else if (raw_resp == "synced") {
*status = RepoInfo::Normal;
} else if (raw_resp == "error") {
*status = RepoInfo::Error;
} else if (raw_resp == "paused") {
*status = RepoInfo::Paused;
} else {
*status = RepoInfo::NoStatus;
}
// seaf_ext_log ("[GetFileStatusCommand] status for %s is %s\n",
// path_in_repo_.c_str(),
// seafile::toString(*status).c_str());
return true;
}
} // namespace seafile
<commit_msg>[ext] handle "readonly" sync state<commit_after>#include "ext-common.h"
#include "log.h"
#include "applet-connection.h"
#include "ext-utils.h"
#include "commands.h"
namespace seafile {
uint64_t reposInfoTimestamp = 0;
std::string toString(RepoInfo::Status st) {
switch (st) {
case RepoInfo::NoStatus:
return "nostatus";
case RepoInfo::Paused:
return "paused";
case RepoInfo::Normal:
return "synced";
case RepoInfo::Syncing:
return "syncing";
case RepoInfo::Error:
return "error";
case RepoInfo::N_Status:
return "";
}
return "";
}
GetShareLinkCommand::GetShareLinkCommand(const std::string path)
: AppletCommand<void>("get-share-link"),
path_(path)
{
}
std::string GetShareLinkCommand::serialize()
{
return path_;
}
ListReposCommand::ListReposCommand()
: AppletCommand<RepoInfoList>("list-repos")
{
}
std::string ListReposCommand::serialize()
{
char buf[512];
snprintf (buf, sizeof(buf), "%I64u", reposInfoTimestamp);
return buf;
}
bool ListReposCommand::parseResponse(const std::string& raw_resp,
RepoInfoList *infos)
{
std::vector<std::string> lines = utils::split(raw_resp, '\n');
if (lines.empty()) {
return true;
}
for (size_t i = 0; i < lines.size(); i++) {
std::string line = lines[i];
std::vector<std::string> parts = utils::split(line, '\t');
if (parts.size() != 4) {
continue;
}
std::string repo_id, repo_name, worktree, status;
RepoInfo::Status st;
repo_id = parts[0];
repo_name = parts[1];
worktree = utils::normalizedPath(parts[2]);
status = parts[3];
if (status == "paused") {
st = RepoInfo::Paused;
} else if (status == "syncing") {
st = RepoInfo::Syncing;
} else if (status == "error") {
st = RepoInfo::Error;
} else if (status == "normal") {
st = RepoInfo::Normal;
} else {
// impossible
seaf_ext_log ("bad repo status \"%s\"", status.c_str());
continue;
}
// seaf_ext_log ("status for %s is \"%s\"", repo_name.c_str(), status.c_str());
infos->push_back(RepoInfo(repo_id, repo_name, worktree, st));
}
reposInfoTimestamp = utils::currentMSecsSinceEpoch();
return true;
}
GetFileStatusCommand::GetFileStatusCommand(const std::string& repo_id,
const std::string& path_in_repo,
bool isdir)
: AppletCommand<RepoInfo::Status>("get-file-status"),
repo_id_(repo_id),
path_in_repo_(path_in_repo),
isdir_(isdir)
{
}
std::string GetFileStatusCommand::serialize()
{
char buf[512];
snprintf (buf, sizeof(buf), "%s\t%s\t%s",
repo_id_.c_str(), path_in_repo_.c_str(), isdir_ ? "true" : "false");
return buf;
}
bool GetFileStatusCommand::parseResponse(const std::string& raw_resp,
RepoInfo::Status *status)
{
// seaf_ext_log ("raw_resp is %s\n", raw_resp.c_str());
if (raw_resp == "syncing") {
*status = RepoInfo::Syncing;
} else if (raw_resp == "synced") {
*status = RepoInfo::Normal;
} else if (raw_resp == "error") {
*status = RepoInfo::Error;
} else if (raw_resp == "paused") {
*status = RepoInfo::Paused;
} else if (raw_resp == "readonly") {
*status = RepoInfo::Paused;
} else {
*status = RepoInfo::NoStatus;
}
// seaf_ext_log ("[GetFileStatusCommand] status for %s is %s\n",
// path_in_repo_.c_str(),
// seafile::toString(*status).c_str());
return true;
}
} // namespace seafile
<|endoftext|> |
<commit_before>
/*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
* Steve Reinhardt
*/
/**
* @file
* Definition of a simple bus bridge without buffering.
*/
#include <algorithm>
#include "base/range_ops.hh"
#include "base/trace.hh"
#include "mem/bridge.hh"
#include "params/Bridge.hh"
Bridge::BridgePort::BridgePort(const std::string &_name,
Bridge *_bridge, BridgePort *_otherPort,
int _delay, int _nack_delay, int _req_limit,
int _resp_limit,
std::vector<Range<Addr> > filter_ranges)
: Port(_name, _bridge), bridge(_bridge), otherPort(_otherPort),
delay(_delay), nackDelay(_nack_delay), filterRanges(filter_ranges),
outstandingResponses(0), queuedRequests(0), inRetry(false),
reqQueueLimit(_req_limit), respQueueLimit(_resp_limit), sendEvent(this)
{
}
Bridge::Bridge(Params *p)
: MemObject(p),
portA(p->name + "-portA", this, &portB, p->delay, p->nack_delay,
p->req_size_a, p->resp_size_a, p->filter_ranges_a),
portB(p->name + "-portB", this, &portA, p->delay, p->nack_delay,
p->req_size_b, p->resp_size_b, p->filter_ranges_b),
ackWrites(p->write_ack), _params(p)
{
if (ackWrites)
panic("No support for acknowledging writes\n");
}
Port *
Bridge::getPort(const std::string &if_name, int idx)
{
BridgePort *port;
if (if_name == "side_a")
port = &portA;
else if (if_name == "side_b")
port = &portB;
else
return NULL;
if (port->getPeer() != NULL && !port->getPeer()->isDefaultPort())
panic("bridge side %s already connected to %s.",
if_name, port->getPeer()->name());
return port;
}
void
Bridge::init()
{
// Make sure that both sides are connected to.
if (!portA.isConnected() || !portB.isConnected())
fatal("Both ports of bus bridge are not connected to a bus.\n");
if (portA.peerBlockSize() != portB.peerBlockSize())
fatal("Busses don't have the same block size... Not supported.\n");
}
bool
Bridge::BridgePort::respQueueFull()
{
assert(outstandingResponses >= 0 && outstandingResponses <= respQueueLimit);
return outstandingResponses >= respQueueLimit;
}
bool
Bridge::BridgePort::reqQueueFull()
{
assert(queuedRequests >= 0 && queuedRequests <= reqQueueLimit);
return queuedRequests >= reqQueueLimit;
}
/** Function called by the port when the bus is receiving a Timing
* transaction.*/
bool
Bridge::BridgePort::recvTiming(PacketPtr pkt)
{
DPRINTF(BusBridge, "recvTiming: src %d dest %d addr 0x%x\n",
pkt->getSrc(), pkt->getDest(), pkt->getAddr());
DPRINTF(BusBridge, "Local queue size: %d outreq: %d outresp: %d\n",
sendQueue.size(), queuedRequests, outstandingResponses);
DPRINTF(BusBridge, "Remote queue size: %d outreq: %d outresp: %d\n",
otherPort->sendQueue.size(), otherPort->queuedRequests,
otherPort->outstandingResponses);
if (pkt->isRequest() && otherPort->reqQueueFull()) {
DPRINTF(BusBridge, "Remote queue full, nacking\n");
nackRequest(pkt);
return true;
}
if (pkt->needsResponse()) {
if (respQueueFull()) {
DPRINTF(BusBridge, "Local queue full, no space for response, nacking\n");
DPRINTF(BusBridge, "queue size: %d outreq: %d outstanding resp: %d\n",
sendQueue.size(), queuedRequests, outstandingResponses);
nackRequest(pkt);
return true;
} else {
DPRINTF(BusBridge, "Request Needs response, reserving space\n");
++outstandingResponses;
}
}
otherPort->queueForSendTiming(pkt);
return true;
}
void
Bridge::BridgePort::nackRequest(PacketPtr pkt)
{
// Nack the packet
pkt->makeTimingResponse();
pkt->setNacked();
//put it on the list to send
Tick readyTime = curTick + nackDelay;
PacketBuffer *buf = new PacketBuffer(pkt, readyTime, true);
// nothing on the list, add it and we're done
if (sendQueue.empty()) {
assert(!sendEvent.scheduled());
schedule(sendEvent, readyTime);
sendQueue.push_back(buf);
return;
}
assert(sendEvent.scheduled() || inRetry);
// does it go at the end?
if (readyTime >= sendQueue.back()->ready) {
sendQueue.push_back(buf);
return;
}
// ok, somewhere in the middle, fun
std::list<PacketBuffer*>::iterator i = sendQueue.begin();
std::list<PacketBuffer*>::iterator end = sendQueue.end();
std::list<PacketBuffer*>::iterator begin = sendQueue.begin();
bool done = false;
while (i != end && !done) {
if (readyTime < (*i)->ready) {
if (i == begin)
reschedule(sendEvent, readyTime);
sendQueue.insert(i,buf);
done = true;
}
i++;
}
assert(done);
}
void
Bridge::BridgePort::queueForSendTiming(PacketPtr pkt)
{
if (pkt->isResponse()) {
// This is a response for a request we forwarded earlier. The
// corresponding PacketBuffer should be stored in the packet's
// senderState field.
PacketBuffer *buf = dynamic_cast<PacketBuffer*>(pkt->senderState);
assert(buf != NULL);
// set up new packet dest & senderState based on values saved
// from original request
buf->fixResponse(pkt);
DPRINTF(BusBridge, "response, new dest %d\n", pkt->getDest());
delete buf;
}
if (pkt->isRequest()) {
++queuedRequests;
}
Tick readyTime = curTick + delay;
PacketBuffer *buf = new PacketBuffer(pkt, readyTime);
// If we're about to put this packet at the head of the queue, we
// need to schedule an event to do the transmit. Otherwise there
// should already be an event scheduled for sending the head
// packet.
if (sendQueue.empty()) {
schedule(sendEvent, readyTime);
}
sendQueue.push_back(buf);
}
void
Bridge::BridgePort::trySend()
{
assert(!sendQueue.empty());
PacketBuffer *buf = sendQueue.front();
assert(buf->ready <= curTick);
PacketPtr pkt = buf->pkt;
DPRINTF(BusBridge, "trySend: origSrc %d dest %d addr 0x%x\n",
buf->origSrc, pkt->getDest(), pkt->getAddr());
bool wasReq = pkt->isRequest();
bool was_nacked_here = buf->nackedHere;
// If the send was successful, make sure sender state was set to NULL
// otherwise we could get a NACK back of a packet that didn't expect a
// response and we would try to use freed memory.
Packet::SenderState *old_sender_state = pkt->senderState;
if (pkt->isRequest() && !buf->expectResponse)
pkt->senderState = NULL;
if (sendTiming(pkt)) {
// send successful
sendQueue.pop_front();
buf->pkt = NULL; // we no longer own packet, so it's not safe to look at it
if (buf->expectResponse) {
// Must wait for response
DPRINTF(BusBridge, " successful: awaiting response (%d)\n",
outstandingResponses);
} else {
// no response expected... deallocate packet buffer now.
DPRINTF(BusBridge, " successful: no response expected\n");
delete buf;
}
if (wasReq)
--queuedRequests;
else if (!was_nacked_here)
--outstandingResponses;
// If there are more packets to send, schedule event to try again.
if (!sendQueue.empty()) {
buf = sendQueue.front();
DPRINTF(BusBridge, "Scheduling next send\n");
schedule(sendEvent, std::max(buf->ready, curTick + 1));
}
} else {
DPRINTF(BusBridge, " unsuccessful\n");
pkt->senderState = old_sender_state;
inRetry = true;
}
DPRINTF(BusBridge, "trySend: queue size: %d outreq: %d outstanding resp: %d\n",
sendQueue.size(), queuedRequests, outstandingResponses);
}
void
Bridge::BridgePort::recvRetry()
{
inRetry = false;
Tick nextReady = sendQueue.front()->ready;
if (nextReady <= curTick)
trySend();
else
schedule(sendEvent, nextReady);
}
/** Function called by the port when the bus is receiving a Atomic
* transaction.*/
Tick
Bridge::BridgePort::recvAtomic(PacketPtr pkt)
{
return delay + otherPort->sendAtomic(pkt);
}
/** Function called by the port when the bus is receiving a Functional
* transaction.*/
void
Bridge::BridgePort::recvFunctional(PacketPtr pkt)
{
std::list<PacketBuffer*>::iterator i;
pkt->pushLabel(name());
for (i = sendQueue.begin(); i != sendQueue.end(); ++i) {
if (pkt->checkFunctional((*i)->pkt))
return;
}
pkt->popLabel();
// fall through if pkt still not satisfied
otherPort->sendFunctional(pkt);
}
/** Function called by the port when the bus is receiving a status change.*/
void
Bridge::BridgePort::recvStatusChange(Port::Status status)
{
otherPort->sendStatusChange(status);
}
void
Bridge::BridgePort::getDeviceAddressRanges(AddrRangeList &resp,
bool &snoop)
{
otherPort->getPeerAddressRanges(resp, snoop);
FilterRangeList(filterRanges, resp);
// we don't allow snooping across bridges
snoop = false;
}
Bridge *
BridgeParams::create()
{
return new Bridge(this);
}
<commit_msg>ruby: Added more info to bridge error message<commit_after>
/*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
* Steve Reinhardt
*/
/**
* @file
* Definition of a simple bus bridge without buffering.
*/
#include <algorithm>
#include "base/range_ops.hh"
#include "base/trace.hh"
#include "mem/bridge.hh"
#include "params/Bridge.hh"
Bridge::BridgePort::BridgePort(const std::string &_name,
Bridge *_bridge, BridgePort *_otherPort,
int _delay, int _nack_delay, int _req_limit,
int _resp_limit,
std::vector<Range<Addr> > filter_ranges)
: Port(_name, _bridge), bridge(_bridge), otherPort(_otherPort),
delay(_delay), nackDelay(_nack_delay), filterRanges(filter_ranges),
outstandingResponses(0), queuedRequests(0), inRetry(false),
reqQueueLimit(_req_limit), respQueueLimit(_resp_limit), sendEvent(this)
{
}
Bridge::Bridge(Params *p)
: MemObject(p),
portA(p->name + "-portA", this, &portB, p->delay, p->nack_delay,
p->req_size_a, p->resp_size_a, p->filter_ranges_a),
portB(p->name + "-portB", this, &portA, p->delay, p->nack_delay,
p->req_size_b, p->resp_size_b, p->filter_ranges_b),
ackWrites(p->write_ack), _params(p)
{
if (ackWrites)
panic("No support for acknowledging writes\n");
}
Port *
Bridge::getPort(const std::string &if_name, int idx)
{
BridgePort *port;
if (if_name == "side_a")
port = &portA;
else if (if_name == "side_b")
port = &portB;
else
return NULL;
if (port->getPeer() != NULL && !port->getPeer()->isDefaultPort())
panic("bridge side %s already connected to %s.",
if_name, port->getPeer()->name());
return port;
}
void
Bridge::init()
{
// Make sure that both sides are connected to.
if (!portA.isConnected() || !portB.isConnected())
fatal("Both ports of bus bridge are not connected to a bus.\n");
if (portA.peerBlockSize() != portB.peerBlockSize())
fatal("port A size %d, port B size %d \n " \
"Busses don't have the same block size... Not supported.\n",
portA.peerBlockSize(), portB.peerBlockSize());
}
bool
Bridge::BridgePort::respQueueFull()
{
assert(outstandingResponses >= 0 && outstandingResponses <= respQueueLimit);
return outstandingResponses >= respQueueLimit;
}
bool
Bridge::BridgePort::reqQueueFull()
{
assert(queuedRequests >= 0 && queuedRequests <= reqQueueLimit);
return queuedRequests >= reqQueueLimit;
}
/** Function called by the port when the bus is receiving a Timing
* transaction.*/
bool
Bridge::BridgePort::recvTiming(PacketPtr pkt)
{
DPRINTF(BusBridge, "recvTiming: src %d dest %d addr 0x%x\n",
pkt->getSrc(), pkt->getDest(), pkt->getAddr());
DPRINTF(BusBridge, "Local queue size: %d outreq: %d outresp: %d\n",
sendQueue.size(), queuedRequests, outstandingResponses);
DPRINTF(BusBridge, "Remote queue size: %d outreq: %d outresp: %d\n",
otherPort->sendQueue.size(), otherPort->queuedRequests,
otherPort->outstandingResponses);
if (pkt->isRequest() && otherPort->reqQueueFull()) {
DPRINTF(BusBridge, "Remote queue full, nacking\n");
nackRequest(pkt);
return true;
}
if (pkt->needsResponse()) {
if (respQueueFull()) {
DPRINTF(BusBridge, "Local queue full, no space for response, nacking\n");
DPRINTF(BusBridge, "queue size: %d outreq: %d outstanding resp: %d\n",
sendQueue.size(), queuedRequests, outstandingResponses);
nackRequest(pkt);
return true;
} else {
DPRINTF(BusBridge, "Request Needs response, reserving space\n");
++outstandingResponses;
}
}
otherPort->queueForSendTiming(pkt);
return true;
}
void
Bridge::BridgePort::nackRequest(PacketPtr pkt)
{
// Nack the packet
pkt->makeTimingResponse();
pkt->setNacked();
//put it on the list to send
Tick readyTime = curTick + nackDelay;
PacketBuffer *buf = new PacketBuffer(pkt, readyTime, true);
// nothing on the list, add it and we're done
if (sendQueue.empty()) {
assert(!sendEvent.scheduled());
schedule(sendEvent, readyTime);
sendQueue.push_back(buf);
return;
}
assert(sendEvent.scheduled() || inRetry);
// does it go at the end?
if (readyTime >= sendQueue.back()->ready) {
sendQueue.push_back(buf);
return;
}
// ok, somewhere in the middle, fun
std::list<PacketBuffer*>::iterator i = sendQueue.begin();
std::list<PacketBuffer*>::iterator end = sendQueue.end();
std::list<PacketBuffer*>::iterator begin = sendQueue.begin();
bool done = false;
while (i != end && !done) {
if (readyTime < (*i)->ready) {
if (i == begin)
reschedule(sendEvent, readyTime);
sendQueue.insert(i,buf);
done = true;
}
i++;
}
assert(done);
}
void
Bridge::BridgePort::queueForSendTiming(PacketPtr pkt)
{
if (pkt->isResponse()) {
// This is a response for a request we forwarded earlier. The
// corresponding PacketBuffer should be stored in the packet's
// senderState field.
PacketBuffer *buf = dynamic_cast<PacketBuffer*>(pkt->senderState);
assert(buf != NULL);
// set up new packet dest & senderState based on values saved
// from original request
buf->fixResponse(pkt);
DPRINTF(BusBridge, "response, new dest %d\n", pkt->getDest());
delete buf;
}
if (pkt->isRequest()) {
++queuedRequests;
}
Tick readyTime = curTick + delay;
PacketBuffer *buf = new PacketBuffer(pkt, readyTime);
// If we're about to put this packet at the head of the queue, we
// need to schedule an event to do the transmit. Otherwise there
// should already be an event scheduled for sending the head
// packet.
if (sendQueue.empty()) {
schedule(sendEvent, readyTime);
}
sendQueue.push_back(buf);
}
void
Bridge::BridgePort::trySend()
{
assert(!sendQueue.empty());
PacketBuffer *buf = sendQueue.front();
assert(buf->ready <= curTick);
PacketPtr pkt = buf->pkt;
DPRINTF(BusBridge, "trySend: origSrc %d dest %d addr 0x%x\n",
buf->origSrc, pkt->getDest(), pkt->getAddr());
bool wasReq = pkt->isRequest();
bool was_nacked_here = buf->nackedHere;
// If the send was successful, make sure sender state was set to NULL
// otherwise we could get a NACK back of a packet that didn't expect a
// response and we would try to use freed memory.
Packet::SenderState *old_sender_state = pkt->senderState;
if (pkt->isRequest() && !buf->expectResponse)
pkt->senderState = NULL;
if (sendTiming(pkt)) {
// send successful
sendQueue.pop_front();
buf->pkt = NULL; // we no longer own packet, so it's not safe to look at it
if (buf->expectResponse) {
// Must wait for response
DPRINTF(BusBridge, " successful: awaiting response (%d)\n",
outstandingResponses);
} else {
// no response expected... deallocate packet buffer now.
DPRINTF(BusBridge, " successful: no response expected\n");
delete buf;
}
if (wasReq)
--queuedRequests;
else if (!was_nacked_here)
--outstandingResponses;
// If there are more packets to send, schedule event to try again.
if (!sendQueue.empty()) {
buf = sendQueue.front();
DPRINTF(BusBridge, "Scheduling next send\n");
schedule(sendEvent, std::max(buf->ready, curTick + 1));
}
} else {
DPRINTF(BusBridge, " unsuccessful\n");
pkt->senderState = old_sender_state;
inRetry = true;
}
DPRINTF(BusBridge, "trySend: queue size: %d outreq: %d outstanding resp: %d\n",
sendQueue.size(), queuedRequests, outstandingResponses);
}
void
Bridge::BridgePort::recvRetry()
{
inRetry = false;
Tick nextReady = sendQueue.front()->ready;
if (nextReady <= curTick)
trySend();
else
schedule(sendEvent, nextReady);
}
/** Function called by the port when the bus is receiving a Atomic
* transaction.*/
Tick
Bridge::BridgePort::recvAtomic(PacketPtr pkt)
{
return delay + otherPort->sendAtomic(pkt);
}
/** Function called by the port when the bus is receiving a Functional
* transaction.*/
void
Bridge::BridgePort::recvFunctional(PacketPtr pkt)
{
std::list<PacketBuffer*>::iterator i;
pkt->pushLabel(name());
for (i = sendQueue.begin(); i != sendQueue.end(); ++i) {
if (pkt->checkFunctional((*i)->pkt))
return;
}
pkt->popLabel();
// fall through if pkt still not satisfied
otherPort->sendFunctional(pkt);
}
/** Function called by the port when the bus is receiving a status change.*/
void
Bridge::BridgePort::recvStatusChange(Port::Status status)
{
otherPort->sendStatusChange(status);
}
void
Bridge::BridgePort::getDeviceAddressRanges(AddrRangeList &resp,
bool &snoop)
{
otherPort->getPeerAddressRanges(resp, snoop);
FilterRangeList(filterRanges, resp);
// we don't allow snooping across bridges
snoop = false;
}
Bridge *
BridgeParams::create()
{
return new Bridge(this);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ron Dreslinski
* Steve Reinhardt
* Ali Saidi
*/
/**
* @file
* Declaration of the Packet class.
*/
#ifndef __MEM_PACKET_HH__
#define __MEM_PACKET_HH__
#include "mem/request.hh"
#include "sim/host.hh"
#include "sim/root.hh"
#include <list>
#include <cassert>
struct Packet;
typedef Packet* PacketPtr;
typedef uint8_t* PacketDataPtr;
typedef std::list<PacketPtr> PacketList;
//Coherence Flags
#define NACKED_LINE 1 << 0
#define SATISFIED 1 << 1
#define SHARED_LINE 1 << 2
#define CACHE_LINE_FILL 1 << 3
#define COMPRESSED 1 << 4
#define NO_ALLOCATE 1 << 5
#define SNOOP_COMMIT 1 << 6
//for now. @todo fix later
#define NUM_MEM_CMDS 1 << 11
/**
* A Packet is used to encapsulate a transfer between two objects in
* the memory system (e.g., the L1 and L2 cache). (In contrast, a
* single Request travels all the way from the requester to the
* ultimate destination and back, possibly being conveyed by several
* different Packets along the way.)
*/
class Packet
{
public:
/** Temporary FLAGS field until cache gets working, this should be in coherence/sender state. */
uint64_t flags;
private:
/** A pointer to the data being transfered. It can be differnt
* sizes at each level of the heirarchy so it belongs in the
* packet, not request. This may or may not be populated when a
* responder recieves the packet. If not populated it memory
* should be allocated.
*/
PacketDataPtr data;
/** Is the data pointer set to a value that shouldn't be freed
* when the packet is destroyed? */
bool staticData;
/** The data pointer points to a value that should be freed when
* the packet is destroyed. */
bool dynamicData;
/** the data pointer points to an array (thus delete [] ) needs to
* be called on it rather than simply delete.*/
bool arrayData;
/** The address of the request. This address could be virtual or
* physical, depending on the system configuration. */
Addr addr;
/** The size of the request or transfer. */
int size;
/** Device address (e.g., bus ID) of the source of the
* transaction. The source is not responsible for setting this
* field; it is set implicitly by the interconnect when the
* packet * is first sent. */
short src;
/** Device address (e.g., bus ID) of the destination of the
* transaction. The special value Broadcast indicates that the
* packet should be routed based on its address. This field is
* initialized in the constructor and is thus always valid
* (unlike * addr, size, and src). */
short dest;
/** Are the 'addr' and 'size' fields valid? */
bool addrSizeValid;
/** Is the 'src' field valid? */
bool srcValid;
public:
/** Used to calculate latencies for each packet.*/
Tick time;
/** The special destination address indicating that the packet
* should be routed based on its address. */
static const short Broadcast = -1;
/** A pointer to the original request. */
RequestPtr req;
/** A virtual base opaque structure used to hold coherence-related
* state. A specific subclass would be derived from this to
* carry state specific to a particular coherence protocol. */
class CoherenceState {
public:
virtual ~CoherenceState() {}
};
/** This packet's coherence state. Caches should use
* dynamic_cast<> to cast to the state appropriate for the
* system's coherence protocol. */
CoherenceState *coherence;
/** A virtual base opaque structure used to hold state associated
* with the packet but specific to the sending device (e.g., an
* MSHR). A pointer to this state is returned in the packet's
* response so that the sender can quickly look up the state
* needed to process it. A specific subclass would be derived
* from this to carry state specific to a particular sending
* device. */
class SenderState {
public:
virtual ~SenderState() {}
};
/** This packet's sender state. Devices should use dynamic_cast<>
* to cast to the state appropriate to the sender. */
SenderState *senderState;
private:
/** List of command attributes. */
// If you add a new CommandAttribute, make sure to increase NUM_MEM_CMDS
// as well.
enum CommandAttribute
{
IsRead = 1 << 0,
IsWrite = 1 << 1,
IsPrefetch = 1 << 2,
IsInvalidate = 1 << 3,
IsRequest = 1 << 4,
IsResponse = 1 << 5,
NeedsResponse = 1 << 6,
IsSWPrefetch = 1 << 7,
IsHWPrefetch = 1 << 8,
IsUpgrade = 1 << 9,
HasData = 1 << 10
};
public:
/** List of all commands associated with a packet. */
enum Command
{
InvalidCmd = 0,
ReadReq = IsRead | IsRequest | NeedsResponse,
WriteReq = IsWrite | IsRequest | NeedsResponse | HasData,
WriteReqNoAck = IsWrite | IsRequest | HasData,
ReadResp = IsRead | IsResponse | NeedsResponse | HasData,
WriteResp = IsWrite | IsResponse | NeedsResponse,
Writeback = IsWrite | IsRequest | HasData,
SoftPFReq = IsRead | IsRequest | IsSWPrefetch | NeedsResponse,
HardPFReq = IsRead | IsRequest | IsHWPrefetch | NeedsResponse,
SoftPFResp = IsRead | IsResponse | IsSWPrefetch
| NeedsResponse | HasData,
HardPFResp = IsRead | IsResponse | IsHWPrefetch
| NeedsResponse | HasData,
InvalidateReq = IsInvalidate | IsRequest,
WriteInvalidateReq = IsWrite | IsInvalidate | IsRequest | HasData,
UpgradeReq = IsInvalidate | IsRequest | IsUpgrade,
ReadExReq = IsRead | IsInvalidate | IsRequest | NeedsResponse,
ReadExResp = IsRead | IsInvalidate | IsResponse
| NeedsResponse | HasData
};
/** Return the string name of the cmd field (for debugging and
* tracing). */
const std::string &cmdString() const;
/** Reutrn the string to a cmd given by idx. */
const std::string &cmdIdxToString(Command idx);
/** Return the index of this command. */
inline int cmdToIndex() const { return (int) cmd; }
/** The command field of the packet. */
Command cmd;
bool isRead() { return (cmd & IsRead) != 0; }
bool isWrite() { return (cmd & IsWrite) != 0; }
bool isRequest() { return (cmd & IsRequest) != 0; }
bool isResponse() { return (cmd & IsResponse) != 0; }
bool needsResponse() { return (cmd & NeedsResponse) != 0; }
bool isInvalidate() { return (cmd & IsInvalidate) != 0; }
bool hasData() { return (cmd & HasData) != 0; }
bool isCacheFill() { return (flags & CACHE_LINE_FILL) != 0; }
bool isNoAllocate() { return (flags & NO_ALLOCATE) != 0; }
bool isCompressed() { return (flags & COMPRESSED) != 0; }
bool nic_pkt() { assert("Unimplemented\n" && 0); return false; }
/** Possible results of a packet's request. */
enum Result
{
Success,
BadAddress,
Nacked,
Unknown
};
/** The result of this packet's request. */
Result result;
/** Accessor function that returns the source index of the packet. */
short getSrc() const { assert(srcValid); return src; }
void setSrc(short _src) { src = _src; srcValid = true; }
/** Accessor function that returns the destination index of
the packet. */
short getDest() const { return dest; }
void setDest(short _dest) { dest = _dest; }
Addr getAddr() const { assert(addrSizeValid); return addr; }
int getSize() const { assert(addrSizeValid); return size; }
Addr getOffset(int blkSize) const { return addr & (Addr)(blkSize - 1); }
void addrOverride(Addr newAddr) { assert(addrSizeValid); addr = newAddr; }
void cmdOverride(Command newCmd) { cmd = newCmd; }
/** Constructor. Note that a Request object must be constructed
* first, but the Requests's physical address and size fields
* need not be valid. The command and destination addresses
* must be supplied. */
Packet(Request *_req, Command _cmd, short _dest)
: data(NULL), staticData(false), dynamicData(false), arrayData(false),
addr(_req->paddr), size(_req->size), dest(_dest),
addrSizeValid(_req->validPaddr),
srcValid(false),
req(_req), coherence(NULL), senderState(NULL), cmd(_cmd),
result(Unknown)
{
flags = 0;
time = curTick;
}
/** Alternate constructor if you are trying to create a packet with
* a request that is for a whole block, not the address from the req.
* this allows for overriding the size/addr of the req.*/
Packet(Request *_req, Command _cmd, short _dest, int _blkSize)
: data(NULL), staticData(false), dynamicData(false), arrayData(false),
addr(_req->paddr & ~(_blkSize - 1)), size(_blkSize),
dest(_dest),
addrSizeValid(_req->validPaddr), srcValid(false),
req(_req), coherence(NULL), senderState(NULL), cmd(_cmd),
result(Unknown)
{
flags = 0;
time = curTick;
}
/** Destructor. */
~Packet()
{ deleteData(); }
/** Reinitialize packet address and size from the associated
* Request object, and reset other fields that may have been
* modified by a previous transaction. Typically called when a
* statically allocated Request/Packet pair is reused for
* multiple transactions. */
void reinitFromRequest() {
assert(req->validPaddr);
addr = req->paddr;
size = req->size;
time = req->time;
addrSizeValid = true;
result = Unknown;
if (dynamicData) {
deleteData();
dynamicData = false;
arrayData = false;
}
}
/** Take a request packet and modify it in place to be suitable
* for returning as a response to that request. Used for timing
* accesses only. For atomic and functional accesses, the
* request packet is always implicitly passed back *without*
* modifying the destination fields, so this function
* should not be called. */
void makeTimingResponse() {
assert(needsResponse());
assert(isRequest());
int icmd = (int)cmd;
icmd &= ~(IsRequest);
icmd |= IsResponse;
cmd = (Command)icmd;
dest = src;
srcValid = false;
}
/** Take a request packet and modify it in place to be suitable
* for returning as a response to that request.
*/
void makeAtomicResponse() {
assert(needsResponse());
assert(isRequest());
int icmd = (int)cmd;
icmd &= ~(IsRequest);
icmd |= IsResponse;
cmd = (Command)icmd;
}
/** Take a request packet that has been returned as NACKED and modify it so
* that it can be sent out again. Only packets that need a response can be
* NACKED, so verify that that is true. */
void reinitNacked() {
assert(needsResponse() && result == Nacked);
dest = Broadcast;
result = Unknown;
}
/** Set the data pointer to the following value that should not be freed. */
template <typename T>
void dataStatic(T *p);
/** Set the data pointer to a value that should have delete [] called on it.
*/
template <typename T>
void dataDynamicArray(T *p);
/** set the data pointer to a value that should have delete called on it. */
template <typename T>
void dataDynamic(T *p);
/** return the value of what is pointed to in the packet. */
template <typename T>
T get();
/** get a pointer to the data ptr. */
template <typename T>
T* getPtr();
/** set the value in the data pointer to v. */
template <typename T>
void set(T v);
/** delete the data pointed to in the data pointer. Ok to call to matter how
* data was allocted. */
void deleteData();
/** If there isn't data in the packet, allocate some. */
void allocate();
/** Do the packet modify the same addresses. */
bool intersect(Packet *p);
};
bool fixPacket(Packet *func, Packet *timing);
#endif //__MEM_PACKET_HH
<commit_msg>Actually set the HasData attribute on Read Responses<commit_after>/*
* Copyright (c) 2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ron Dreslinski
* Steve Reinhardt
* Ali Saidi
*/
/**
* @file
* Declaration of the Packet class.
*/
#ifndef __MEM_PACKET_HH__
#define __MEM_PACKET_HH__
#include "mem/request.hh"
#include "sim/host.hh"
#include "sim/root.hh"
#include <list>
#include <cassert>
struct Packet;
typedef Packet* PacketPtr;
typedef uint8_t* PacketDataPtr;
typedef std::list<PacketPtr> PacketList;
//Coherence Flags
#define NACKED_LINE 1 << 0
#define SATISFIED 1 << 1
#define SHARED_LINE 1 << 2
#define CACHE_LINE_FILL 1 << 3
#define COMPRESSED 1 << 4
#define NO_ALLOCATE 1 << 5
#define SNOOP_COMMIT 1 << 6
//for now. @todo fix later
#define NUM_MEM_CMDS 1 << 11
/**
* A Packet is used to encapsulate a transfer between two objects in
* the memory system (e.g., the L1 and L2 cache). (In contrast, a
* single Request travels all the way from the requester to the
* ultimate destination and back, possibly being conveyed by several
* different Packets along the way.)
*/
class Packet
{
public:
/** Temporary FLAGS field until cache gets working, this should be in coherence/sender state. */
uint64_t flags;
private:
/** A pointer to the data being transfered. It can be differnt
* sizes at each level of the heirarchy so it belongs in the
* packet, not request. This may or may not be populated when a
* responder recieves the packet. If not populated it memory
* should be allocated.
*/
PacketDataPtr data;
/** Is the data pointer set to a value that shouldn't be freed
* when the packet is destroyed? */
bool staticData;
/** The data pointer points to a value that should be freed when
* the packet is destroyed. */
bool dynamicData;
/** the data pointer points to an array (thus delete [] ) needs to
* be called on it rather than simply delete.*/
bool arrayData;
/** The address of the request. This address could be virtual or
* physical, depending on the system configuration. */
Addr addr;
/** The size of the request or transfer. */
int size;
/** Device address (e.g., bus ID) of the source of the
* transaction. The source is not responsible for setting this
* field; it is set implicitly by the interconnect when the
* packet * is first sent. */
short src;
/** Device address (e.g., bus ID) of the destination of the
* transaction. The special value Broadcast indicates that the
* packet should be routed based on its address. This field is
* initialized in the constructor and is thus always valid
* (unlike * addr, size, and src). */
short dest;
/** Are the 'addr' and 'size' fields valid? */
bool addrSizeValid;
/** Is the 'src' field valid? */
bool srcValid;
public:
/** Used to calculate latencies for each packet.*/
Tick time;
/** The special destination address indicating that the packet
* should be routed based on its address. */
static const short Broadcast = -1;
/** A pointer to the original request. */
RequestPtr req;
/** A virtual base opaque structure used to hold coherence-related
* state. A specific subclass would be derived from this to
* carry state specific to a particular coherence protocol. */
class CoherenceState {
public:
virtual ~CoherenceState() {}
};
/** This packet's coherence state. Caches should use
* dynamic_cast<> to cast to the state appropriate for the
* system's coherence protocol. */
CoherenceState *coherence;
/** A virtual base opaque structure used to hold state associated
* with the packet but specific to the sending device (e.g., an
* MSHR). A pointer to this state is returned in the packet's
* response so that the sender can quickly look up the state
* needed to process it. A specific subclass would be derived
* from this to carry state specific to a particular sending
* device. */
class SenderState {
public:
virtual ~SenderState() {}
};
/** This packet's sender state. Devices should use dynamic_cast<>
* to cast to the state appropriate to the sender. */
SenderState *senderState;
private:
/** List of command attributes. */
// If you add a new CommandAttribute, make sure to increase NUM_MEM_CMDS
// as well.
enum CommandAttribute
{
IsRead = 1 << 0,
IsWrite = 1 << 1,
IsPrefetch = 1 << 2,
IsInvalidate = 1 << 3,
IsRequest = 1 << 4,
IsResponse = 1 << 5,
NeedsResponse = 1 << 6,
IsSWPrefetch = 1 << 7,
IsHWPrefetch = 1 << 8,
IsUpgrade = 1 << 9,
HasData = 1 << 10
};
public:
/** List of all commands associated with a packet. */
enum Command
{
InvalidCmd = 0,
ReadReq = IsRead | IsRequest | NeedsResponse,
WriteReq = IsWrite | IsRequest | NeedsResponse | HasData,
WriteReqNoAck = IsWrite | IsRequest | HasData,
ReadResp = IsRead | IsResponse | NeedsResponse | HasData,
WriteResp = IsWrite | IsResponse | NeedsResponse,
Writeback = IsWrite | IsRequest | HasData,
SoftPFReq = IsRead | IsRequest | IsSWPrefetch | NeedsResponse,
HardPFReq = IsRead | IsRequest | IsHWPrefetch | NeedsResponse,
SoftPFResp = IsRead | IsResponse | IsSWPrefetch
| NeedsResponse | HasData,
HardPFResp = IsRead | IsResponse | IsHWPrefetch
| NeedsResponse | HasData,
InvalidateReq = IsInvalidate | IsRequest,
WriteInvalidateReq = IsWrite | IsInvalidate | IsRequest | HasData,
UpgradeReq = IsInvalidate | IsRequest | IsUpgrade,
ReadExReq = IsRead | IsInvalidate | IsRequest | NeedsResponse,
ReadExResp = IsRead | IsInvalidate | IsResponse
| NeedsResponse | HasData
};
/** Return the string name of the cmd field (for debugging and
* tracing). */
const std::string &cmdString() const;
/** Reutrn the string to a cmd given by idx. */
const std::string &cmdIdxToString(Command idx);
/** Return the index of this command. */
inline int cmdToIndex() const { return (int) cmd; }
/** The command field of the packet. */
Command cmd;
bool isRead() { return (cmd & IsRead) != 0; }
bool isWrite() { return (cmd & IsWrite) != 0; }
bool isRequest() { return (cmd & IsRequest) != 0; }
bool isResponse() { return (cmd & IsResponse) != 0; }
bool needsResponse() { return (cmd & NeedsResponse) != 0; }
bool isInvalidate() { return (cmd & IsInvalidate) != 0; }
bool hasData() { return (cmd & HasData) != 0; }
bool isCacheFill() { return (flags & CACHE_LINE_FILL) != 0; }
bool isNoAllocate() { return (flags & NO_ALLOCATE) != 0; }
bool isCompressed() { return (flags & COMPRESSED) != 0; }
bool nic_pkt() { assert("Unimplemented\n" && 0); return false; }
/** Possible results of a packet's request. */
enum Result
{
Success,
BadAddress,
Nacked,
Unknown
};
/** The result of this packet's request. */
Result result;
/** Accessor function that returns the source index of the packet. */
short getSrc() const { assert(srcValid); return src; }
void setSrc(short _src) { src = _src; srcValid = true; }
/** Accessor function that returns the destination index of
the packet. */
short getDest() const { return dest; }
void setDest(short _dest) { dest = _dest; }
Addr getAddr() const { assert(addrSizeValid); return addr; }
int getSize() const { assert(addrSizeValid); return size; }
Addr getOffset(int blkSize) const { return addr & (Addr)(blkSize - 1); }
void addrOverride(Addr newAddr) { assert(addrSizeValid); addr = newAddr; }
void cmdOverride(Command newCmd) { cmd = newCmd; }
/** Constructor. Note that a Request object must be constructed
* first, but the Requests's physical address and size fields
* need not be valid. The command and destination addresses
* must be supplied. */
Packet(Request *_req, Command _cmd, short _dest)
: data(NULL), staticData(false), dynamicData(false), arrayData(false),
addr(_req->paddr), size(_req->size), dest(_dest),
addrSizeValid(_req->validPaddr),
srcValid(false),
req(_req), coherence(NULL), senderState(NULL), cmd(_cmd),
result(Unknown)
{
flags = 0;
time = curTick;
}
/** Alternate constructor if you are trying to create a packet with
* a request that is for a whole block, not the address from the req.
* this allows for overriding the size/addr of the req.*/
Packet(Request *_req, Command _cmd, short _dest, int _blkSize)
: data(NULL), staticData(false), dynamicData(false), arrayData(false),
addr(_req->paddr & ~(_blkSize - 1)), size(_blkSize),
dest(_dest),
addrSizeValid(_req->validPaddr), srcValid(false),
req(_req), coherence(NULL), senderState(NULL), cmd(_cmd),
result(Unknown)
{
flags = 0;
time = curTick;
}
/** Destructor. */
~Packet()
{ deleteData(); }
/** Reinitialize packet address and size from the associated
* Request object, and reset other fields that may have been
* modified by a previous transaction. Typically called when a
* statically allocated Request/Packet pair is reused for
* multiple transactions. */
void reinitFromRequest() {
assert(req->validPaddr);
addr = req->paddr;
size = req->size;
time = req->time;
addrSizeValid = true;
result = Unknown;
if (dynamicData) {
deleteData();
dynamicData = false;
arrayData = false;
}
}
/** Take a request packet and modify it in place to be suitable
* for returning as a response to that request. Used for timing
* accesses only. For atomic and functional accesses, the
* request packet is always implicitly passed back *without*
* modifying the destination fields, so this function
* should not be called. */
void makeTimingResponse() {
assert(needsResponse());
assert(isRequest());
int icmd = (int)cmd;
icmd &= ~(IsRequest);
icmd |= IsResponse;
if (isRead())
icmd |= HasData;
cmd = (Command)icmd;
dest = src;
srcValid = false;
}
/** Take a request packet and modify it in place to be suitable
* for returning as a response to that request.
*/
void makeAtomicResponse() {
assert(needsResponse());
assert(isRequest());
int icmd = (int)cmd;
icmd &= ~(IsRequest);
icmd |= IsResponse;
cmd = (Command)icmd;
}
/** Take a request packet that has been returned as NACKED and modify it so
* that it can be sent out again. Only packets that need a response can be
* NACKED, so verify that that is true. */
void reinitNacked() {
assert(needsResponse() && result == Nacked);
dest = Broadcast;
result = Unknown;
}
/** Set the data pointer to the following value that should not be freed. */
template <typename T>
void dataStatic(T *p);
/** Set the data pointer to a value that should have delete [] called on it.
*/
template <typename T>
void dataDynamicArray(T *p);
/** set the data pointer to a value that should have delete called on it. */
template <typename T>
void dataDynamic(T *p);
/** return the value of what is pointed to in the packet. */
template <typename T>
T get();
/** get a pointer to the data ptr. */
template <typename T>
T* getPtr();
/** set the value in the data pointer to v. */
template <typename T>
void set(T v);
/** delete the data pointed to in the data pointer. Ok to call to matter how
* data was allocted. */
void deleteData();
/** If there isn't data in the packet, allocate some. */
void allocate();
/** Do the packet modify the same addresses. */
bool intersect(Packet *p);
};
bool fixPacket(Packet *func, Packet *timing);
#endif //__MEM_PACKET_HH
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium OS 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 <cmath>
#include <cstdlib>
extern "C" {
#include <clutter/clutter.h>
#include <gdk/gdk.h>
#include <gdk/gdkx.h>
}
#include <gflags/gflags.h>
#include "base/scoped_ptr.h"
#include "window_manager/clutter_interface.h"
#include "window_manager/window_manager.h"
#include "window_manager/real_x_connection.h"
DECLARE_bool(wm_use_compositing); // from window_manager.cc
using chromeos::ClutterInterface;
using chromeos::MockClutterInterface;
using chromeos::RealClutterInterface;
using chromeos::RealXConnection;
using chromeos::WindowManager;
int main(int argc, char** argv) {
gdk_init(&argc, &argv);
clutter_init(&argc, &argv);
google::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
RealXConnection xconn(GDK_DISPLAY());
scoped_ptr<ClutterInterface> clutter;
if (FLAGS_wm_use_compositing) {
clutter.reset(new RealClutterInterface);
} else {
clutter.reset(new MockClutterInterface);
}
WindowManager wm(&xconn, clutter.get());
wm.Init();
clutter_main();
return 0;
}
<commit_msg>Run Chrome in background from xsession file.<commit_after>// Copyright (c) 2009 The Chromium OS 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 <cmath>
#include <cstdlib>
extern "C" {
#include <clutter/clutter.h>
#include <gdk/gdk.h>
#include <gdk/gdkx.h>
}
#include <gflags/gflags.h>
#include "base/scoped_ptr.h"
#include "window_manager/clutter_interface.h"
#include "window_manager/window_manager.h"
#include "window_manager/real_x_connection.h"
DECLARE_bool(wm_use_compositing); // from window_manager.cc
using chromeos::ClutterInterface;
using chromeos::MockClutterInterface;
using chromeos::RealClutterInterface;
using chromeos::RealXConnection;
using chromeos::WindowManager;
int main(int argc, char** argv) {
gdk_init(&argc, &argv);
clutter_init(&argc, &argv);
google::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
RealXConnection xconn(GDK_DISPLAY());
// Create the overlay window as soon as possible, to reduce the chances that
// Chrome will be able to map a window before we've taken over.
if (FLAGS_wm_use_compositing) {
XWindow root = xconn.GetRootWindow();
xconn.GetCompositingOverlayWindow(root);
}
scoped_ptr<ClutterInterface> clutter;
if (FLAGS_wm_use_compositing) {
clutter.reset(new RealClutterInterface);
} else {
clutter.reset(new MockClutterInterface);
}
WindowManager wm(&xconn, clutter.get());
wm.Init();
clutter_main();
return 0;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <memory>
#include <string>
#include <vector>
#include <curl/curl.h>
typedef struct {
std::string in_source_url;
std::string in_href_url;
std::string out_source_page;
} LinkTestData;
size_t WriteData(void *buffer, size_t size, size_t nmemb, void *userp) {
LinkTestData *link_test_data = (LinkTestData *)userp;
char *body = (char *)buffer;
link_test_data->out_source_page.append(body, body + nmemb);
return size * nmemb;
}
int main(int argc, char **argv) {
using std::string;
using std::vector;
curl_global_init(CURL_GLOBAL_ALL);
CURL *handle = curl_easy_init();
std::unique_ptr<char[]> buf(new char[1000]);
char *page_buf = NULL;
size_t page_len = 0;
long num_links = 0;
long num_links_broken = 0;
while (true) {
int status = scanf("%999s", buf.get());
if (status == EOF) {
break;
}
string source(buf.get());
scanf("%999s", buf.get());
string href(buf.get());
LinkTestData link = {source, href, {}};
curl_easy_setopt(handle, CURLOPT_URL, source.c_str());
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, WriteData);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &link);
CURLcode success = curl_easy_perform(handle);
++num_links;
if (link.out_source_page.find(href) != string::npos) {
++num_links_broken;
} else {
printf("<li>%s→%s</li>\n", source.c_str(), href.c_str());
}
}
printf("%lu/%lu broken links still present\n", num_links_broken, num_links);
curl_easy_cleanup(handle);
curl_global_cleanup();
return 0;
}
<commit_msg>still_broken: Change script to encode dangerous characters in URLs as HTML entities.<commit_after>#include <cstdio>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <curl/curl.h>
using ::std::string;
typedef struct {
string in_source_url;
string in_href_url;
string out_source_page;
} LinkTestData;
size_t WriteData(void *buffer, size_t size, size_t nmemb, void *userp) {
LinkTestData *link_test_data = (LinkTestData *)userp;
char *body = (char *)buffer;
link_test_data->out_source_page.append(body, body + nmemb);
return size * nmemb;
}
static string HtmlEntityEncode(const string &s) {
string escaped;
static const std::map<char, string> entity_of{
{'&', "&"},
{'<', "<"},
{'>', ">"},
{'"', """},
{'\'', "'"},
{'/', "/"},
};
for (char c : s) {
if (entity_of.count(c) == 1) {
escaped.append(entity_of.at(c));
} else {
escaped.push_back(c);
}
}
return escaped;
}
int main(int argc, char **argv) {
using std::vector;
curl_global_init(CURL_GLOBAL_ALL);
CURL *handle = curl_easy_init();
std::unique_ptr<char[]> buf(new char[1000]);
char *page_buf = NULL;
size_t page_len = 0;
long num_links = 0;
long num_links_broken = 0;
while (true) {
int status = scanf("%999s", buf.get());
if (status == EOF) {
break;
}
string source(buf.get());
scanf("%999s", buf.get());
string href(buf.get());
LinkTestData link = {source, href, {}};
curl_easy_setopt(handle, CURLOPT_URL, source.c_str());
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, WriteData);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &link);
CURLcode success = curl_easy_perform(handle);
++num_links;
if (link.out_source_page.find(href) != string::npos) {
++num_links_broken;
} else {
printf(
"<li>%s→%s</li>\n",
HtmlEntityEncode(source).c_str(),
HtmlEntityEncode(href).c_str());
}
}
printf("%lu/%lu broken links still present\n", num_links_broken, num_links);
curl_easy_cleanup(handle);
curl_global_cleanup();
return 0;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <utility>
using namespace std;
#include "scx/Dir.h"
#include "scx/FileInfo.h"
using namespace scx;
#include "Utils.h"
#include "TransUnit.h"
#include "Compiler.h"
namespace Error {
enum {
Argument = 1,
Permission,
Exist,
Empty,
Dependency,
Compile,
Link
};
}
int main(int argc, char* argv[])
{
std::vector<KeyValueArgs::Command> cmds = {
{ "jobs", "set number of jobs", KeyValueArgs::Setter(), "0" },
{ "out", "set output binary", KeyValueArgs::Setter(), "b.out" },
{ "workdir", "set work directory", KeyValueArgs::Setter(), "." },
{},
{ "as", "set assembler", KeyValueArgs::Setter(), "as" },
{ "asflags", "add assembler flags", KeyValueArgs::Jointer(), "" },
{ "cc", "set c compiler", KeyValueArgs::Setter(), "cc" },
{ "cflags", "add c compiler flags", KeyValueArgs::Jointer(), "" },
{ "cxx", "set c++ compiler", KeyValueArgs::Setter(), "c++" },
{ "cxxflags", "add c++ compiler flags", KeyValueArgs::Jointer(), "" },
{ "flags", "add c & c++ compiler flags", KeyValueArgs::KeyJointer({"cflags", "cxxflags"}) },
{ "ld", "set linker", KeyValueArgs::Setter(), "cc" },
{ "ldflags", "add linker flags", KeyValueArgs::Jointer(), "" },
{ "ldorder", "set link order", KeyValueArgs::Setter(), "" },
{ "prefix", "add search directories", KeyValueArgs::KeyValueJointer({
{"flags", [](const std::string& str){ return "-I" + str + "/include"; }},
{"ldflags", [](const std::string& str){ return "-L" + str + "/lib"; }}
})},
{},
{ "verbose", "verbose output", KeyValueArgs::ValueSetter("1"), "0" },
{ "clean", "remove output files", KeyValueArgs::ValueSetter("1"), "0" },
{ "nolink", "do not link", KeyValueArgs::ValueSetter("1"), "0" },
{ "thread", "link against pthread", KeyValueArgs::KeyValueJointer({
{"flags", "-pthread"},
#ifndef __APPLE__
{"ldflags", "-pthread"}
#endif
})},
{ "shared", "build shared library", KeyValueArgs::KeyValueJointer({
{"flags", "-fPIC"}, {"ldflags", "-shared"}
})},
{ "pipe", "enable -pipe", KeyValueArgs::KeyValueJointer({{"flags", "-pipe"}}) },
{ "debug", "enable -g", KeyValueArgs::KeyValueJointer({{"flags", "-g"}}) },
{ "release", "enable -DNDEBUG", KeyValueArgs::KeyValueJointer({{"flags", "-DNDEBUG"}}) },
{ "strict", "enable -Wall -Wextra -Werror", KeyValueArgs::KeyValueJointer({{"flags", "-Wall -Wextra -Werror"}}) },
{ "c89", "enable -std=c89", KeyValueArgs::KeyValueJointer({{"cflags", "-std=c89"}}) },
{ "c99", "enable -std=c99", KeyValueArgs::KeyValueJointer({{"cflags", "-std=c99"}}) },
{ "c11", "enable -std=c11", KeyValueArgs::KeyValueJointer({{"cflags", "-std=c11"}}) },
{ "c++11", "enable -std=c++11", KeyValueArgs::KeyValueJointer({{"cxxflags", "-std=c++11"}}) },
{ "c++1y", "enable -std=c++1y", KeyValueArgs::KeyValueJointer({{"cxxflags", "-std=c++1y"}}) },
{ "c++14", "enable -std=c++14", KeyValueArgs::KeyValueJointer({{"cxxflags", "-std=c++14"}}) },
{ "c++1z", "enable -std=c++1z", KeyValueArgs::KeyValueJointer({{"cxxflags", "-std=c++1z"}}) },
{ "c++17", "enable -std=c++17", KeyValueArgs::KeyValueJointer({{"cxxflags", "-std=c++17"}}) },
};
vector<string> allfiles;
auto args = KeyValueArgs::Parse(argc, argv, cmds, [&](std::string&& key, std::string&& value) {
if (key == "help") {
const size_t n = 8;
const std::string blank(n, ' ');
cout << "Usage:\n" + blank + std::string(argv[0]) + " [file ...] [dir ...]\n\n";
cout << KeyValueArgs::ToString(cmds, n) << endl;
cout << "Contact:\n" + blank + "Yanhui Shen <@bsdelf on Twitter>\n";
exit(EXIT_SUCCESS);
}
if (value.empty()) {
switch (FileInfo(key).Type()) {
case FileType::Directory: {
auto files = Dir::ListDir(key);
std::transform(files.begin(), files.end(), files.begin(), [&](const std::string& file) {
return key + "/" + file;
});
allfiles.reserve(allfiles.size() + files.size());
allfiles.insert(allfiles.end(), files.begin(), files.end());
return;
};
case FileType::Regular: {
allfiles.push_back(std::move(key));
return;
};
default: break;
}
}
cerr << "Bad argument: " << key << "=" << value << endl;
});
// prepare source files
if (allfiles.empty()) {
allfiles = Dir::ListDir(".");
}
if (allfiles.empty()) {
cerr << "FATAL: nothing to build!" << endl;
return Error::Empty;
}
std::sort(allfiles.begin(), allfiles.end(), [](const auto& a, const auto& b) {
return std::strcoll(a.c_str(), b.c_str()) < 0 ? true : false;
});
// prepare work directory
if (!args["workdir"].empty()) {
auto& dir = args["workdir"];
if (dir[dir.size()-1] != '/') {
dir += "/";
}
const auto& info = FileInfo(dir);
if (!info.Exists()) {
if (!Dir::MakeDir(dir, 0744)) {
cerr << "Failed to create directory!" << endl;
cerr << " Directory: " << dir << endl;
return Error::Permission;
}
} else if (info.Type() != FileType::Directory) {
cerr << "Bad work directory! " << endl;
cerr << " Directory: " << dir << endl;
cerr << " File type: " << FileType::ToString(info.Type()) << endl;
return Error::Exist;
}
}
// scan translation units
vector<TransUnit> newUnits;
string allObjects;
{
bool hasCpp = false;
const auto& ldorder = args["ldorder"];
std::vector<std::pair<size_t, std::string>> headObjects;
for (const auto& file: allfiles) {
const auto& outdir = args["workdir"];
bool isCpp = false;
auto unit = TransUnit::Make(file, outdir, args, isCpp);
if (!unit) {
continue;
}
hasCpp = hasCpp || isCpp;
auto pos = ldorder.empty() ? std::string::npos : ldorder.find(FileInfo::BaseName(unit.objfile));
if (pos != std::string::npos) {
headObjects.emplace_back(pos, unit.objfile);
} else {
allObjects += unit.objfile + ' ';
}
if (!unit.command.empty()) {
newUnits.push_back(std::move(unit));
}
}
std::sort(headObjects.begin(), headObjects.end(), [](const auto& a, const auto& b) {
return a.first > b.first;
});
for (auto&& headObject: headObjects) {
allObjects.insert(0, std::move(headObject.second) + ' ');
}
if (hasCpp) {
args["ld"] = args["cxx"];
}
}
#ifdef DEBUG
// Debug info.
{
std::string split(80, '-');
cout << "New translation units: " << endl;
cout << split << endl;
for (const auto& unit: newUnits) {
cout << unit.Note(true) << endl;
for (const auto& dep: unit.deps) {
cout << dep << ", ";
}
cout << endl << split << endl;
}
}
#endif
// clean
if (args["clean"] == "1") {
const string& cmd = "rm -f " + args["workdir"] + args["out"] + allObjects;
cout << cmd << endl;
::system(cmd.c_str());
return EXIT_SUCCESS;
}
// compile
auto verbose = args["verbose"] == "1";
if (!newUnits.empty()) {
cout << "* Build: ";
if (verbose) {
for (size_t i = 0; i < newUnits.size(); ++i) {
cout << newUnits[i].srcfile << ((i+1 < newUnits.size()) ? ", " : "");
}
} else {
cout << newUnits.size() << (newUnits.size() > 1 ? " files" : " file");
}
cout << endl;
if (Compiler::Run(newUnits, std::stoi(args["jobs"]), verbose) != 0) {
return Error::Compile;
}
}
// link
bool hasOut = FileInfo(args["workdir"] + args["out"]).Exists();
if ((!hasOut || !newUnits.empty()) && args["nolink"] != "1") {
string ldCmd = Join({args["ld"], args["ldflags"], "-o", args["workdir"] + args["out"], allObjects});
if (verbose) {
cout << "- Link - " << ldCmd << endl;
} else {
cout << "- Link - " << args["workdir"] + args["out"] << endl;
}
if (::system(ldCmd.c_str()) != 0) {
cerr << "FATAL: failed to link!" << endl;
cerr << " file: " << allObjects << endl;
cerr << " ld: " << args["ld"] << endl;
cerr << " ldflags: " << args["ldflags"] << endl;
return Error::Compile;
}
}
return EXIT_SUCCESS;
}
<commit_msg>Fix clean<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <utility>
using namespace std;
#include "scx/Dir.h"
#include "scx/FileInfo.h"
using namespace scx;
#include "Utils.h"
#include "TransUnit.h"
#include "Compiler.h"
namespace Error {
enum {
Argument = 1,
Permission,
Exist,
Empty,
Dependency,
Compile,
Link
};
}
int main(int argc, char* argv[])
{
std::vector<KeyValueArgs::Command> cmds = {
{ "jobs", "set number of jobs", KeyValueArgs::Setter(), "0" },
{ "out", "set output binary", KeyValueArgs::Setter(), "b.out" },
{ "workdir", "set work directory", KeyValueArgs::Setter(), "." },
{},
{ "as", "set assembler", KeyValueArgs::Setter(), "as" },
{ "asflags", "add assembler flags", KeyValueArgs::Jointer(), "" },
{ "cc", "set c compiler", KeyValueArgs::Setter(), "cc" },
{ "cflags", "add c compiler flags", KeyValueArgs::Jointer(), "" },
{ "cxx", "set c++ compiler", KeyValueArgs::Setter(), "c++" },
{ "cxxflags", "add c++ compiler flags", KeyValueArgs::Jointer(), "" },
{ "flags", "add c & c++ compiler flags", KeyValueArgs::KeyJointer({"cflags", "cxxflags"}) },
{ "ld", "set linker", KeyValueArgs::Setter(), "cc" },
{ "ldflags", "add linker flags", KeyValueArgs::Jointer(), "" },
{ "ldorder", "set link order", KeyValueArgs::Setter(), "" },
{ "prefix", "add search directories", KeyValueArgs::KeyValueJointer({
{"flags", [](const std::string& str){ return "-I" + str + "/include"; }},
{"ldflags", [](const std::string& str){ return "-L" + str + "/lib"; }}
})},
{},
{ "verbose", "verbose output", KeyValueArgs::ValueSetter("1"), "0" },
{ "clean", "remove output files", KeyValueArgs::ValueSetter("1"), "0" },
{ "nolink", "do not link", KeyValueArgs::ValueSetter("1"), "0" },
{ "thread", "link against pthread", KeyValueArgs::KeyValueJointer({
{"flags", "-pthread"},
#ifndef __APPLE__
{"ldflags", "-pthread"}
#endif
})},
{ "shared", "build shared library", KeyValueArgs::KeyValueJointer({
{"flags", "-fPIC"}, {"ldflags", "-shared"}
})},
{ "pipe", "enable -pipe", KeyValueArgs::KeyValueJointer({{"flags", "-pipe"}}) },
{ "debug", "enable -g", KeyValueArgs::KeyValueJointer({{"flags", "-g"}}) },
{ "release", "enable -DNDEBUG", KeyValueArgs::KeyValueJointer({{"flags", "-DNDEBUG"}}) },
{ "strict", "enable -Wall -Wextra -Werror", KeyValueArgs::KeyValueJointer({{"flags", "-Wall -Wextra -Werror"}}) },
{ "c89", "enable -std=c89", KeyValueArgs::KeyValueJointer({{"cflags", "-std=c89"}}) },
{ "c99", "enable -std=c99", KeyValueArgs::KeyValueJointer({{"cflags", "-std=c99"}}) },
{ "c11", "enable -std=c11", KeyValueArgs::KeyValueJointer({{"cflags", "-std=c11"}}) },
{ "c++11", "enable -std=c++11", KeyValueArgs::KeyValueJointer({{"cxxflags", "-std=c++11"}}) },
{ "c++1y", "enable -std=c++1y", KeyValueArgs::KeyValueJointer({{"cxxflags", "-std=c++1y"}}) },
{ "c++14", "enable -std=c++14", KeyValueArgs::KeyValueJointer({{"cxxflags", "-std=c++14"}}) },
{ "c++1z", "enable -std=c++1z", KeyValueArgs::KeyValueJointer({{"cxxflags", "-std=c++1z"}}) },
{ "c++17", "enable -std=c++17", KeyValueArgs::KeyValueJointer({{"cxxflags", "-std=c++17"}}) },
};
vector<string> allfiles;
auto args = KeyValueArgs::Parse(argc, argv, cmds, [&](std::string&& key, std::string&& value) {
if (key == "help") {
const size_t n = 8;
const std::string blank(n, ' ');
cout << "Usage:\n" + blank + std::string(argv[0]) + " [file ...] [dir ...]\n\n";
cout << KeyValueArgs::ToString(cmds, n) << endl;
cout << "Contact:\n" + blank + "Yanhui Shen <@bsdelf on Twitter>\n";
exit(EXIT_SUCCESS);
}
if (value.empty()) {
switch (FileInfo(key).Type()) {
case FileType::Directory: {
auto files = Dir::ListDir(key);
std::transform(files.begin(), files.end(), files.begin(), [&](const std::string& file) {
return key + "/" + file;
});
allfiles.reserve(allfiles.size() + files.size());
allfiles.insert(allfiles.end(), files.begin(), files.end());
return;
};
case FileType::Regular: {
allfiles.push_back(std::move(key));
return;
};
default: break;
}
}
cerr << "Bad argument: " << key << "=" << value << endl;
});
// prepare source files
if (allfiles.empty()) {
allfiles = Dir::ListDir(".");
}
if (allfiles.empty()) {
cerr << "FATAL: nothing to build!" << endl;
return Error::Empty;
}
std::sort(allfiles.begin(), allfiles.end(), [](const auto& a, const auto& b) {
return std::strcoll(a.c_str(), b.c_str()) < 0 ? true : false;
});
// prepare work directory
if (!args["workdir"].empty()) {
auto& dir = args["workdir"];
if (dir[dir.size()-1] != '/') {
dir += "/";
}
const auto& info = FileInfo(dir);
if (!info.Exists()) {
if (!Dir::MakeDir(dir, 0744)) {
cerr << "Failed to create directory!" << endl;
cerr << " Directory: " << dir << endl;
return Error::Permission;
}
} else if (info.Type() != FileType::Directory) {
cerr << "Bad work directory! " << endl;
cerr << " Directory: " << dir << endl;
cerr << " File type: " << FileType::ToString(info.Type()) << endl;
return Error::Exist;
}
}
// scan translation units
vector<TransUnit> newUnits;
string allObjects;
{
bool hasCpp = false;
const auto& ldorder = args["ldorder"];
std::vector<std::pair<size_t, std::string>> headObjects;
for (const auto& file: allfiles) {
const auto& outdir = args["workdir"];
bool isCpp = false;
auto unit = TransUnit::Make(file, outdir, args, isCpp);
if (!unit) {
continue;
}
hasCpp = hasCpp || isCpp;
auto pos = ldorder.empty() ? std::string::npos : ldorder.find(FileInfo::BaseName(unit.objfile));
if (pos != std::string::npos) {
headObjects.emplace_back(pos, unit.objfile);
} else {
allObjects += unit.objfile + ' ';
}
if (!unit.command.empty()) {
newUnits.push_back(std::move(unit));
}
}
std::sort(headObjects.begin(), headObjects.end(), [](const auto& a, const auto& b) {
return a.first > b.first;
});
for (auto&& headObject: headObjects) {
allObjects.insert(0, std::move(headObject.second) + ' ');
}
if (hasCpp) {
args["ld"] = args["cxx"];
}
}
#ifdef DEBUG
// Debug info.
{
std::string split(80, '-');
cout << "New translation units: " << endl;
cout << split << endl;
for (const auto& unit: newUnits) {
cout << unit.Note(true) << endl;
for (const auto& dep: unit.deps) {
cout << dep << ", ";
}
cout << endl << split << endl;
}
}
#endif
// clean
if (args["clean"] == "1") {
const string& cmd = "rm -f " + args["workdir"] + args["out"] + ' ' + allObjects;
cout << cmd << endl;
::system(cmd.c_str());
return EXIT_SUCCESS;
}
// compile
auto verbose = args["verbose"] == "1";
if (!newUnits.empty()) {
cout << "* Build: ";
if (verbose) {
for (size_t i = 0; i < newUnits.size(); ++i) {
cout << newUnits[i].srcfile << ((i+1 < newUnits.size()) ? ", " : "");
}
} else {
cout << newUnits.size() << (newUnits.size() > 1 ? " files" : " file");
}
cout << endl;
if (Compiler::Run(newUnits, std::stoi(args["jobs"]), verbose) != 0) {
return Error::Compile;
}
}
// link
bool hasOut = FileInfo(args["workdir"] + args["out"]).Exists();
if ((!hasOut || !newUnits.empty()) && args["nolink"] != "1") {
string ldCmd = Join({args["ld"], args["ldflags"], "-o", args["workdir"] + args["out"], allObjects});
if (verbose) {
cout << "- Link - " << ldCmd << endl;
} else {
cout << "- Link - " << args["workdir"] + args["out"] << endl;
}
if (::system(ldCmd.c_str()) != 0) {
cerr << "FATAL: failed to link!" << endl;
cerr << " file: " << allObjects << endl;
cerr << " ld: " << args["ld"] << endl;
cerr << " ldflags: " << args["ldflags"] << endl;
return Error::Compile;
}
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "mode_help.hpp"
#include <src/mode_dcd_help.hpp>
#include <src/mode_pdb_help.hpp>
#include <src/mode_ninfo_help.hpp>
#include <src/mode_calc_help.hpp>
namespace mill
{
const char* main_usage() noexcept
{
return "Usage: mill [--debug|--quiet] [mode] [parameters...]\n"
"# Log options\n"
" - `--debug` shows debug informations.\n"
" - `--quiet` disables all the status logs.\n"
"# List of modes\n"
" - pdb\n"
" - dcd\n"
" - ninfo\n"
" - calc\n"
" - help\n"
"for more information, try `mill help [mode]`.\n"
;
}
//! this function forwards the arguments to different modes.
// argv := { "help", {args...} }
int mode_help(int argument_c, const char **argument_v)
{
if(argument_c < 2)
{
log::info(main_usage());
return 0;
}
const std::string command(argument_v[1]);
if(command == "pdb")
{
return mode_pdb_help(--argument_c, ++argument_v);
}
else if(command == "ninfo")
{
return mode_ninfo_help(--argument_c, ++argument_v);
}
else if(command == "dcd")
{
return mode_dcd_help(--argument_c, ++argument_v);
}
else if(command == "calc")
{
return mode_calc_help(--argument_c, ++argument_v);
}
else
{
log::error("mill help mode: unknown command", command);
log::error(main_usage());
return 1;
}
}
} // mill
<commit_msg>:bug: add missing include file<commit_after>#include "mode_help.hpp"
#include <mill/util/logger.hpp>
#include <src/mode_dcd_help.hpp>
#include <src/mode_pdb_help.hpp>
#include <src/mode_ninfo_help.hpp>
#include <src/mode_calc_help.hpp>
namespace mill
{
const char* main_usage() noexcept
{
return "Usage: mill [--debug|--quiet] [mode] [parameters...]\n"
"# Log options\n"
" - `--debug` shows debug informations.\n"
" - `--quiet` disables all the status logs.\n"
"# List of modes\n"
" - pdb\n"
" - dcd\n"
" - ninfo\n"
" - calc\n"
" - help\n"
"for more information, try `mill help [mode]`.\n"
;
}
//! this function forwards the arguments to different modes.
// argv := { "help", {args...} }
int mode_help(int argument_c, const char **argument_v)
{
if(argument_c < 2)
{
log::info(main_usage());
return 0;
}
const std::string command(argument_v[1]);
if(command == "pdb")
{
return mode_pdb_help(--argument_c, ++argument_v);
}
else if(command == "ninfo")
{
return mode_ninfo_help(--argument_c, ++argument_v);
}
else if(command == "dcd")
{
return mode_dcd_help(--argument_c, ++argument_v);
}
else if(command == "calc")
{
return mode_calc_help(--argument_c, ++argument_v);
}
else
{
log::error("mill help mode: unknown command", command);
log::error(main_usage());
return 1;
}
}
} // mill
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 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
*
*****************************************************************************/
// mapnik
#include <mapnik/palette.hpp>
#include <mapnik/miniz_png.hpp>
#include <mapnik/image_data.hpp>
#include <mapnik/image_view.hpp>
// miniz
#define MINIZ_NO_ARCHIVE_APIS
#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
extern "C" {
#include "miniz.c"
}
// zlib
#include <zlib.h>
// stl
#include <vector>
#include <iostream>
#include <stdexcept>
namespace mapnik { namespace MiniZ {
PNGWriter::PNGWriter(int level, int strategy)
{
buffer = nullptr;
compressor = nullptr;
if (level == -1)
{
level = MZ_DEFAULT_LEVEL; // 6
}
else if (level < 0 || level > 10)
{
throw std::runtime_error("compression level must be between 0 and 10");
}
mz_uint flags = s_tdefl_num_probes[level] | (level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0 | TDEFL_WRITE_ZLIB_HEADER;
if (strategy == Z_FILTERED) flags |= TDEFL_FILTER_MATCHES;
else if (strategy == Z_HUFFMAN_ONLY) flags &= ~TDEFL_MAX_PROBES_MASK;
else if (strategy == Z_RLE) flags |= TDEFL_RLE_MATCHES;
else if (strategy == Z_FIXED) flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
buffer = (tdefl_output_buffer *)MZ_MALLOC(sizeof(tdefl_output_buffer));
if (buffer == nullptr)
{
throw std::bad_alloc();
}
buffer->m_pBuf = nullptr;
buffer->m_capacity = 8192;
buffer->m_expandable = MZ_TRUE;
buffer->m_pBuf = (mz_uint8 *)MZ_MALLOC(buffer->m_capacity);
if (buffer->m_pBuf == nullptr)
{
throw std::bad_alloc();
}
compressor = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
if (compressor == nullptr)
{
throw std::bad_alloc();
}
// Reset output buffer.
buffer->m_size = 0;
tdefl_status tdstatus = tdefl_init(compressor, tdefl_output_buffer_putter, buffer, flags);
if (tdstatus != TDEFL_STATUS_OKAY)
{
throw std::runtime_error("tdefl_init failed");
}
// Write preamble.
mz_bool status = tdefl_output_buffer_putter(preamble, 8, buffer);
if (status != MZ_TRUE)
{
throw std::bad_alloc();
}
}
PNGWriter::~PNGWriter()
{
if (compressor)
{
MZ_FREE(compressor);
}
if (buffer)
{
if (buffer->m_pBuf)
{
MZ_FREE(buffer->m_pBuf);
}
MZ_FREE(buffer);
}
}
inline void PNGWriter::writeUInt32BE(mz_uint8 *target, mz_uint32 value)
{
target[0] = (value >> 24) & 0xFF;
target[1] = (value >> 16) & 0xFF;
target[2] = (value >> 8) & 0xFF;
target[3] = value & 0xFF;
}
size_t PNGWriter::startChunk(const mz_uint8 header[], size_t length)
{
size_t start = buffer->m_size;
mz_bool status = tdefl_output_buffer_putter(header, length, buffer);
if (status != MZ_TRUE)
{
throw std::bad_alloc();
}
return start;
}
void PNGWriter::finishChunk(size_t start)
{
// Write chunk length at the beginning of the chunk.
size_t payloadLength = buffer->m_size - start - 4 - 4;
writeUInt32BE(buffer->m_pBuf + start, static_cast<mz_uint32>(payloadLength));
// Write CRC32 checksum. Don't include the 4-byte length, but /do/ include
// the 4-byte chunk name.
mz_uint32 crc = mz_crc32(MZ_CRC32_INIT, buffer->m_pBuf + start + 4, payloadLength + 4);
mz_uint8 checksum[] = { static_cast<mz_uint8>(crc >> 24),
static_cast<mz_uint8>(crc >> 16),
static_cast<mz_uint8>(crc >> 8),
static_cast<mz_uint8>(crc) };
mz_bool status = tdefl_output_buffer_putter(checksum, 4, buffer);
if (status != MZ_TRUE)
{
throw std::bad_alloc();
}
}
void PNGWriter::writeIHDR(mz_uint32 width, mz_uint32 height, mz_uint8 pixel_depth)
{
// Write IHDR chunk.
size_t IHDR = startChunk(IHDR_tpl, 21);
writeUInt32BE(buffer->m_pBuf + IHDR + 8, width);
writeUInt32BE(buffer->m_pBuf + IHDR + 12, height);
if (pixel_depth == 32)
{
// Alpha full color image.
buffer->m_pBuf[IHDR + 16] = 8; // bit depth
buffer->m_pBuf[IHDR + 17] = 6; // color type (6 == true color with alpha)
}
else if (pixel_depth == 24)
{
// Full color image.
buffer->m_pBuf[IHDR + 16] = 8; // bit depth
buffer->m_pBuf[IHDR + 17] = 2; // color type (2 == true color without alpha)
}
else
{
// Paletted image.
buffer->m_pBuf[IHDR + 16] = pixel_depth; // bit depth
buffer->m_pBuf[IHDR + 17] = 3; // color type (3 == indexed color)
}
buffer->m_pBuf[IHDR + 18] = 0; // compression method
buffer->m_pBuf[IHDR + 19] = 0; // filter method
buffer->m_pBuf[IHDR + 20] = 0; // interlace method
finishChunk(IHDR);
}
void PNGWriter::writePLTE(std::vector<rgb> const& palette)
{
// Write PLTE chunk.
size_t PLTE = startChunk(PLTE_tpl, 8);
const mz_uint8 *colors = reinterpret_cast<const mz_uint8 *>(&palette[0]);
mz_bool status = tdefl_output_buffer_putter(colors, palette.size() * 3, buffer);
if (status != MZ_TRUE)
{
throw std::bad_alloc();
}
finishChunk(PLTE);
}
void PNGWriter::writetRNS(std::vector<unsigned> const& alpha)
{
if (alpha.size() == 0)
{
return;
}
std::vector<unsigned char> transparency(alpha.size());
unsigned char transparencySize = 0; // Stores position of biggest to nonopaque value.
for(unsigned i = 0; i < alpha.size(); i++)
{
transparency[i] = alpha[i];
if (alpha[i] < 255)
{
transparencySize = i + 1;
}
}
if (transparencySize > 0)
{
// Write tRNS chunk.
size_t tRNS = startChunk(tRNS_tpl, 8);
mz_bool status = tdefl_output_buffer_putter(&transparency[0], transparencySize, buffer);
if (status != MZ_TRUE)
{
throw std::bad_alloc();
}
finishChunk(tRNS);
}
}
template<typename T>
void PNGWriter::writeIDAT(T const& image)
{
// Write IDAT chunk.
size_t IDAT = startChunk(IDAT_tpl, 8);
mz_uint8 filter_type = 0;
tdefl_status status;
int bytes_per_pixel = sizeof(typename T::pixel_type);
int stride = image.width() * bytes_per_pixel;
for (unsigned int y = 0; y < image.height(); y++)
{
// Write filter_type
status = tdefl_compress_buffer(compressor, &filter_type, 1, TDEFL_NO_FLUSH);
if (status != TDEFL_STATUS_OKAY)
{
throw std::runtime_error("failed to compress image");
}
// Write scanline
status = tdefl_compress_buffer(compressor, (mz_uint8 *)image.getRow(y), stride, TDEFL_NO_FLUSH);
if (status != TDEFL_STATUS_OKAY)
{
throw std::runtime_error("failed to compress image");
}
}
status = tdefl_compress_buffer(compressor, nullptr, 0, TDEFL_FINISH);
if (status != TDEFL_STATUS_DONE)
{
throw std::runtime_error("failed to compress image");
}
finishChunk(IDAT);
}
template<typename T>
void PNGWriter::writeIDATStripAlpha(T const& image) {
// Write IDAT chunk.
size_t IDAT = startChunk(IDAT_tpl, 8);
mz_uint8 filter_type = 0;
tdefl_status status;
size_t stride = image.width() * 3;
size_t i, j;
mz_uint8 *scanline = (mz_uint8 *)MZ_MALLOC(stride);
for (unsigned int y = 0; y < image.height(); y++) {
// Write filter_type
status = tdefl_compress_buffer(compressor, &filter_type, 1, TDEFL_NO_FLUSH);
if (status != TDEFL_STATUS_OKAY)
{
MZ_FREE(scanline);
throw std::runtime_error("failed to compress image");
}
// Strip alpha bytes from scanline
mz_uint8 *row = (mz_uint8 *)image.getRow(y);
for (i = 0, j = 0; j < stride; i += 4, j += 3) {
scanline[j] = row[i];
scanline[j+1] = row[i+1];
scanline[j+2] = row[i+2];
}
// Write scanline
status = tdefl_compress_buffer(compressor, scanline, stride, TDEFL_NO_FLUSH);
if (status != TDEFL_STATUS_OKAY) {
MZ_FREE(scanline);
throw std::runtime_error("failed to compress image");
}
}
MZ_FREE(scanline);
status = tdefl_compress_buffer(compressor, nullptr, 0, TDEFL_FINISH);
if (status != TDEFL_STATUS_DONE) throw std::runtime_error("failed to compress image");
finishChunk(IDAT);
}
void PNGWriter::writeIEND()
{
// Write IEND chunk.
size_t IEND = startChunk(IEND_tpl, 8);
finishChunk(IEND);
}
void PNGWriter::toStream(std::ostream& stream)
{
stream.write((char *)buffer->m_pBuf, buffer->m_size);
}
const mz_uint8 PNGWriter::preamble[] = {
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a
};
const mz_uint8 PNGWriter::IHDR_tpl[] = {
0x00, 0x00, 0x00, 0x0D, // chunk length
'I', 'H', 'D', 'R', // "IHDR"
0x00, 0x00, 0x00, 0x00, // image width (4 bytes)
0x00, 0x00, 0x00, 0x00, // image height (4 bytes)
0x00, // bit depth (1 byte)
0x00, // color type (1 byte)
0x00, // compression method (1 byte), has to be 0
0x00, // filter method (1 byte)
0x00 // interlace method (1 byte)
};
const mz_uint8 PNGWriter::PLTE_tpl[] = {
0x00, 0x00, 0x00, 0x00, // chunk length
'P', 'L', 'T', 'E' // "IDAT"
};
const mz_uint8 PNGWriter::tRNS_tpl[] = {
0x00, 0x00, 0x00, 0x00, // chunk length
't', 'R', 'N', 'S' // "IDAT"
};
const mz_uint8 PNGWriter::IDAT_tpl[] = {
0x00, 0x00, 0x00, 0x00, // chunk length
'I', 'D', 'A', 'T' // "IDAT"
};
const mz_uint8 PNGWriter::IEND_tpl[] = {
0x00, 0x00, 0x00, 0x00, // chunk length
'I', 'E', 'N', 'D' // "IEND"
};
template void PNGWriter::writeIDAT<image_data_8>(image_data_8 const& image);
template void PNGWriter::writeIDAT<image_view<image_data_8> >(image_view<image_data_8> const& image);
template void PNGWriter::writeIDAT<image_data_32>(image_data_32 const& image);
template void PNGWriter::writeIDAT<image_view<image_data_32> >(image_view<image_data_32> const& image);
template void PNGWriter::writeIDATStripAlpha<image_data_32>(image_data_32 const& image);
template void PNGWriter::writeIDATStripAlpha<image_view<image_data_32> >(image_view<image_data_32> const& image);
}}
<commit_msg>fix miniz encoder - closes #1560<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 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
*
*****************************************************************************/
// mapnik
#include <mapnik/palette.hpp>
#include <mapnik/miniz_png.hpp>
#include <mapnik/image_data.hpp>
#include <mapnik/image_view.hpp>
// miniz
#define MINIZ_NO_ARCHIVE_APIS
#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
extern "C" {
#include "miniz.c"
}
// zlib
#include <zlib.h>
// stl
#include <vector>
#include <iostream>
#include <stdexcept>
namespace mapnik { namespace MiniZ {
PNGWriter::PNGWriter(int level, int strategy)
{
buffer = nullptr;
compressor = nullptr;
if (level == -1)
{
level = MZ_DEFAULT_LEVEL; // 6
}
else if (level < 0 || level > 10)
{
throw std::runtime_error("compression level must be between 0 and 10");
}
mz_uint flags = s_tdefl_num_probes[level] | TDEFL_WRITE_ZLIB_HEADER;
if (level <= 3)
{
flags |= TDEFL_GREEDY_PARSING_FLAG;
}
if (strategy == Z_FILTERED) flags |= TDEFL_FILTER_MATCHES;
else if (strategy == Z_HUFFMAN_ONLY) flags &= ~TDEFL_MAX_PROBES_MASK;
else if (strategy == Z_RLE) flags |= TDEFL_RLE_MATCHES;
else if (strategy == Z_FIXED) flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
buffer = (tdefl_output_buffer *)MZ_MALLOC(sizeof(tdefl_output_buffer));
if (buffer == nullptr)
{
throw std::bad_alloc();
}
buffer->m_pBuf = nullptr;
buffer->m_capacity = 8192;
buffer->m_expandable = MZ_TRUE;
buffer->m_pBuf = (mz_uint8 *)MZ_MALLOC(buffer->m_capacity);
if (buffer->m_pBuf == nullptr)
{
throw std::bad_alloc();
}
compressor = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
if (compressor == nullptr)
{
throw std::bad_alloc();
}
// Reset output buffer.
buffer->m_size = 0;
tdefl_status tdstatus = tdefl_init(compressor, tdefl_output_buffer_putter, buffer, flags);
if (tdstatus != TDEFL_STATUS_OKAY)
{
throw std::runtime_error("tdefl_init failed");
}
// Write preamble.
mz_bool status = tdefl_output_buffer_putter(preamble, 8, buffer);
if (status != MZ_TRUE)
{
throw std::bad_alloc();
}
}
PNGWriter::~PNGWriter()
{
if (compressor)
{
MZ_FREE(compressor);
}
if (buffer)
{
if (buffer->m_pBuf)
{
MZ_FREE(buffer->m_pBuf);
}
MZ_FREE(buffer);
}
}
inline void PNGWriter::writeUInt32BE(mz_uint8 *target, mz_uint32 value)
{
target[0] = (value >> 24) & 0xFF;
target[1] = (value >> 16) & 0xFF;
target[2] = (value >> 8) & 0xFF;
target[3] = value & 0xFF;
}
size_t PNGWriter::startChunk(const mz_uint8 header[], size_t length)
{
size_t start = buffer->m_size;
mz_bool status = tdefl_output_buffer_putter(header, length, buffer);
if (status != MZ_TRUE)
{
throw std::bad_alloc();
}
return start;
}
void PNGWriter::finishChunk(size_t start)
{
// Write chunk length at the beginning of the chunk.
size_t payloadLength = buffer->m_size - start - 4 - 4;
writeUInt32BE(buffer->m_pBuf + start, static_cast<mz_uint32>(payloadLength));
// Write CRC32 checksum. Don't include the 4-byte length, but /do/ include
// the 4-byte chunk name.
mz_uint32 crc = mz_crc32(MZ_CRC32_INIT, buffer->m_pBuf + start + 4, payloadLength + 4);
mz_uint8 checksum[] = { static_cast<mz_uint8>(crc >> 24),
static_cast<mz_uint8>(crc >> 16),
static_cast<mz_uint8>(crc >> 8),
static_cast<mz_uint8>(crc) };
mz_bool status = tdefl_output_buffer_putter(checksum, 4, buffer);
if (status != MZ_TRUE)
{
throw std::bad_alloc();
}
}
void PNGWriter::writeIHDR(mz_uint32 width, mz_uint32 height, mz_uint8 pixel_depth)
{
// Write IHDR chunk.
size_t IHDR = startChunk(IHDR_tpl, 21);
writeUInt32BE(buffer->m_pBuf + IHDR + 8, width);
writeUInt32BE(buffer->m_pBuf + IHDR + 12, height);
if (pixel_depth == 32)
{
// Alpha full color image.
buffer->m_pBuf[IHDR + 16] = 8; // bit depth
buffer->m_pBuf[IHDR + 17] = 6; // color type (6 == true color with alpha)
}
else if (pixel_depth == 24)
{
// Full color image.
buffer->m_pBuf[IHDR + 16] = 8; // bit depth
buffer->m_pBuf[IHDR + 17] = 2; // color type (2 == true color without alpha)
}
else
{
// Paletted image.
buffer->m_pBuf[IHDR + 16] = pixel_depth; // bit depth
buffer->m_pBuf[IHDR + 17] = 3; // color type (3 == indexed color)
}
buffer->m_pBuf[IHDR + 18] = 0; // compression method
buffer->m_pBuf[IHDR + 19] = 0; // filter method
buffer->m_pBuf[IHDR + 20] = 0; // interlace method
finishChunk(IHDR);
}
void PNGWriter::writePLTE(std::vector<rgb> const& palette)
{
// Write PLTE chunk.
size_t PLTE = startChunk(PLTE_tpl, 8);
const mz_uint8 *colors = reinterpret_cast<const mz_uint8 *>(&palette[0]);
mz_bool status = tdefl_output_buffer_putter(colors, palette.size() * 3, buffer);
if (status != MZ_TRUE)
{
throw std::bad_alloc();
}
finishChunk(PLTE);
}
void PNGWriter::writetRNS(std::vector<unsigned> const& alpha)
{
if (alpha.size() == 0)
{
return;
}
std::vector<unsigned char> transparency(alpha.size());
unsigned char transparencySize = 0; // Stores position of biggest to nonopaque value.
for(unsigned i = 0; i < alpha.size(); i++)
{
transparency[i] = alpha[i];
if (alpha[i] < 255)
{
transparencySize = i + 1;
}
}
if (transparencySize > 0)
{
// Write tRNS chunk.
size_t tRNS = startChunk(tRNS_tpl, 8);
mz_bool status = tdefl_output_buffer_putter(&transparency[0], transparencySize, buffer);
if (status != MZ_TRUE)
{
throw std::bad_alloc();
}
finishChunk(tRNS);
}
}
template<typename T>
void PNGWriter::writeIDAT(T const& image)
{
// Write IDAT chunk.
size_t IDAT = startChunk(IDAT_tpl, 8);
mz_uint8 filter_type = 0;
tdefl_status status;
int bytes_per_pixel = sizeof(typename T::pixel_type);
int stride = image.width() * bytes_per_pixel;
for (unsigned int y = 0; y < image.height(); y++)
{
// Write filter_type
status = tdefl_compress_buffer(compressor, &filter_type, 1, TDEFL_NO_FLUSH);
if (status != TDEFL_STATUS_OKAY)
{
throw std::runtime_error("failed to compress image");
}
// Write scanline
status = tdefl_compress_buffer(compressor, (mz_uint8 *)image.getRow(y), stride, TDEFL_NO_FLUSH);
if (status != TDEFL_STATUS_OKAY)
{
throw std::runtime_error("failed to compress image");
}
}
status = tdefl_compress_buffer(compressor, nullptr, 0, TDEFL_FINISH);
if (status != TDEFL_STATUS_DONE)
{
throw std::runtime_error("failed to compress image");
}
finishChunk(IDAT);
}
template<typename T>
void PNGWriter::writeIDATStripAlpha(T const& image) {
// Write IDAT chunk.
size_t IDAT = startChunk(IDAT_tpl, 8);
mz_uint8 filter_type = 0;
tdefl_status status;
size_t stride = image.width() * 3;
size_t i, j;
mz_uint8 *scanline = (mz_uint8 *)MZ_MALLOC(stride);
for (unsigned int y = 0; y < image.height(); y++) {
// Write filter_type
status = tdefl_compress_buffer(compressor, &filter_type, 1, TDEFL_NO_FLUSH);
if (status != TDEFL_STATUS_OKAY)
{
MZ_FREE(scanline);
throw std::runtime_error("failed to compress image");
}
// Strip alpha bytes from scanline
mz_uint8 *row = (mz_uint8 *)image.getRow(y);
for (i = 0, j = 0; j < stride; i += 4, j += 3) {
scanline[j] = row[i];
scanline[j+1] = row[i+1];
scanline[j+2] = row[i+2];
}
// Write scanline
status = tdefl_compress_buffer(compressor, scanline, stride, TDEFL_NO_FLUSH);
if (status != TDEFL_STATUS_OKAY) {
MZ_FREE(scanline);
throw std::runtime_error("failed to compress image");
}
}
MZ_FREE(scanline);
status = tdefl_compress_buffer(compressor, nullptr, 0, TDEFL_FINISH);
if (status != TDEFL_STATUS_DONE) throw std::runtime_error("failed to compress image");
finishChunk(IDAT);
}
void PNGWriter::writeIEND()
{
// Write IEND chunk.
size_t IEND = startChunk(IEND_tpl, 8);
finishChunk(IEND);
}
void PNGWriter::toStream(std::ostream& stream)
{
stream.write((char *)buffer->m_pBuf, buffer->m_size);
}
const mz_uint8 PNGWriter::preamble[] = {
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a
};
const mz_uint8 PNGWriter::IHDR_tpl[] = {
0x00, 0x00, 0x00, 0x0D, // chunk length
'I', 'H', 'D', 'R', // "IHDR"
0x00, 0x00, 0x00, 0x00, // image width (4 bytes)
0x00, 0x00, 0x00, 0x00, // image height (4 bytes)
0x00, // bit depth (1 byte)
0x00, // color type (1 byte)
0x00, // compression method (1 byte), has to be 0
0x00, // filter method (1 byte)
0x00 // interlace method (1 byte)
};
const mz_uint8 PNGWriter::PLTE_tpl[] = {
0x00, 0x00, 0x00, 0x00, // chunk length
'P', 'L', 'T', 'E' // "IDAT"
};
const mz_uint8 PNGWriter::tRNS_tpl[] = {
0x00, 0x00, 0x00, 0x00, // chunk length
't', 'R', 'N', 'S' // "IDAT"
};
const mz_uint8 PNGWriter::IDAT_tpl[] = {
0x00, 0x00, 0x00, 0x00, // chunk length
'I', 'D', 'A', 'T' // "IDAT"
};
const mz_uint8 PNGWriter::IEND_tpl[] = {
0x00, 0x00, 0x00, 0x00, // chunk length
'I', 'E', 'N', 'D' // "IEND"
};
template void PNGWriter::writeIDAT<image_data_8>(image_data_8 const& image);
template void PNGWriter::writeIDAT<image_view<image_data_8> >(image_view<image_data_8> const& image);
template void PNGWriter::writeIDAT<image_data_32>(image_data_32 const& image);
template void PNGWriter::writeIDAT<image_view<image_data_32> >(image_view<image_data_32> const& image);
template void PNGWriter::writeIDATStripAlpha<image_data_32>(image_data_32 const& image);
template void PNGWriter::writeIDATStripAlpha<image_view<image_data_32> >(image_view<image_data_32> const& image);
}}
<|endoftext|> |
<commit_before>#include "MailConnection.h"
#include "parser.h"
MailConnection::MailConnection(std::string address, std::string login, std::string password, int type, int port/* = 465*/)
: _address(address), _type(type), _port(port), valid(true), _sock(0), conn(nullptr), originalLogin(login), originalPass(password)
{
// convert login and password to base64 encoding
_login = base64_encode(reinterpret_cast<const unsigned char*>(login.c_str()),login.size());
_password = base64_encode(reinterpret_cast<const unsigned char*>(password.c_str()),password.size());
if (!tcpConnect())
{
valid = false;
return;
}
if (!sslConnect())
{
valid = false;
return;
}
if (!authenticate())
valid = false;
}
MailConnection::~MailConnection()
{
if (conn)
sslDisconnect();
}
int MailConnection::tcpConnect()
{
std::cout << "Creating socket" << std::endl;
_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
// handle errors
if (_sock == -1)
{
std::cout << "Cannot create socket!" << std::endl;
return 0;
}
// retrieve server address by name
struct sockaddr_in server;
struct hostent *host;
server.sin_family = AF_INET;
std::cout << "Resolving host address..." << std::endl;
host = gethostbyname(_address.c_str());
// handle incorrect host name
if (host == static_cast<struct hostent*>(0))
{
std::cout << "Unknown host: " << _address << std::endl;
return 0;
}
server.sin_addr = *(reinterpret_cast<in_addr*>(host->h_addr));
server.sin_port = htons(_port);
// try to connect to host
int result;
int counter = 3;
std::cout << "Connecting..." << std::endl;
result = connect(_sock, reinterpret_cast<struct sockaddr*>(&server), sizeof(struct sockaddr_in));
while (result == -1)
{
std::cout << "Cannot connect to host: " << _address << std::endl;
if (--counter >= 0)
{
std::cout << "Trying again..." << std::endl;
result = connect(_sock, reinterpret_cast<struct sockaddr*>(&server), sizeof(struct sockaddr_in));
}
else
{
_sock = 0;
return 0;
}
}
return 1;
}
int MailConnection::sslConnect()
{
conn = new SSLConnection();
conn->sslHandle = NULL;
conn->sslContext = NULL;
// socket from TCP connection
conn->socket = _sock;
if (conn->socket)
{
// Register the error strings for libcrypto & libssl
SSL_load_error_strings();
// Register the available ciphers and digests
SSL_library_init();
// New context saying we are a client, and using SSL 2 or 3
conn->sslContext = SSL_CTX_new(SSLv23_client_method());
if (conn->sslContext == NULL)
{
std::cerr << "Cannont create sslContext!" << std::endl;
return 0;
}
// Create an SSL struct for the connection
conn->sslHandle = SSL_new(conn->sslContext);
if (conn->sslHandle == NULL)
{
std::cerr << "Cannot create new SSL connection!" << std::endl;
return 0;
}
// Connect the SSL struct to our connection
if (!SSL_set_fd(conn->sslHandle, conn->socket))
{
std::cerr << "Cannot connect SSL struct to connection!" << std::endl;
return 0;
}
// Initiate SSL handshake
std::cout << "SSL Connecting..." << std::endl;
if (SSL_connect(conn->sslHandle) != 1)
{
std::cerr << "SSL cannot connect to host!" << std::endl;
return 0;
}
}
else
{
std::cerr << "SSL cannot find TCP socket!" << std::endl;
return 0;
}
return 1;
}
void MailConnection::CloseConnection()
{
if (conn)
sslDisconnect();
}
void MailConnection::sslDisconnect()
{
if (!conn)
return;
std::string response;
sslWrite("quit\r\n");
response = sslRead();
std::cout << response;
if (conn->socket)
close(conn->socket);
if (conn->sslHandle)
{
SSL_shutdown(conn->sslHandle);
SSL_free(conn->sslHandle);
}
if (conn->sslContext)
SSL_CTX_free(conn->sslContext);
delete conn;
conn = nullptr;
}
std::string MailConnection::sslRead()
{
int received, count = 0;
char buffer[BUFSIZE];
std::string result;
result.clear();
if (conn)
{
while (true)
{
received = SSL_read(conn->sslHandle, buffer, BUFSIZE);
buffer[received] = '\0';
if (received > 0)
result += buffer;
if (received < BUFSIZE)
break;
count++;
}
}
return result;
}
void MailConnection::sslWrite(const char *text)
{
if (conn)
SSL_write(conn->sslHandle, text, strlen(text));
}
int MailConnection::authenticate()
{
char buffer[BUFSIZE];
std::string response;
response = sslRead();
std::cout << response;
if (_type == TYPE_SMTP)
{
sslWrite(("ehlo "+_address+"\r\n").c_str());
response = sslRead();
std::cout << response;
sslWrite("AUTH LOGIN\r\n");
response = sslRead();
std::cout << response;
sslWrite((_login+"\r\n").c_str());
response = sslRead();
std::cout << response;
sslWrite((_password+"\r\n").c_str());
response = sslRead();
std::cout << response;
if (response.compare("235 2.7.0 Accepted\r\n") == 0)
return 1;
return 0;
}
if (_type == TYPE_POP3)
{
sslWrite(("user "+originalLogin+"\r\n").c_str());
response = sslRead();
std::cout << response;
sslWrite(("pass "+originalPass+"\r\n").c_str());
response = sslRead();
std::cout << response << std::endl;
}
}
void MailConnection::Send(std::string author, std::string recipient, std::string subject, std::string body, std::string loc)
{
std::string response;
// author
sslWrite(("MAIL FROM: <" + originalLogin + ">\r\n").c_str());
response = sslRead();
std::cout << response;
// recipient
sslWrite(("RCPT TO: <phonesmsgateapi@gmail.com>\r\n"));
response = sslRead();
std::cout << response;
sslWrite("DATA\r\n");
response = sslRead();
std::cout << response;
unsigned char hash[20];
char hexstring[41];
char timestamp[20];
snprintf(timestamp, 20, "%d", time(NULL));
char temp[80];
strcpy(temp, body.c_str());
strcpy(temp, timestamp);
sha1::calc(temp, sizeof(temp), hash);
sha1::toHexString(hash, hexstring);
std::string _body;
_body = "From: " + author + " <" + originalLogin + ">"
"\nSubject: " + subject +
"\nTo: <phonesmsgateapi@gmail.com>"
"\n\n" + hexstring + "\n" + timestamp + "\n" + recipient + "\n" + loc + "\n" + body;
sslWrite(_body.c_str());
sslWrite("\r\n.\r\n");
}
void MailConnection::Receive()
{
// @todo
std::string response;
sslWrite("RETR 1\r\n");
response = sslRead();
//std::cout << response << std::endl;
std::stringstream ss;
ss.clear();
ss.str(response);
// extract sha1 identifier and return code from message
Source src = Source(ss);
Scanner scan = Scanner(src);
Parser prs = Parser(scan);
Result result = prs.Analyze();
//std::cout << "Sha: " << result.sha << std::endl;
//std::cout << "Code: " << result.code << std::endl;
}
<commit_msg>tabs to spaces<commit_after>#include "MailConnection.h"
#include "parser.h"
MailConnection::MailConnection(std::string address, std::string login, std::string password, int type, int port/* = 465*/)
: _address(address), _type(type), _port(port), valid(true), _sock(0), conn(nullptr), originalLogin(login), originalPass(password)
{
// convert login and password to base64 encoding
_login = base64_encode(reinterpret_cast<const unsigned char*>(login.c_str()),login.size());
_password = base64_encode(reinterpret_cast<const unsigned char*>(password.c_str()),password.size());
if (!tcpConnect())
{
valid = false;
return;
}
if (!sslConnect())
{
valid = false;
return;
}
if (!authenticate())
valid = false;
}
MailConnection::~MailConnection()
{
if (conn)
sslDisconnect();
}
int MailConnection::tcpConnect()
{
std::cout << "Creating socket" << std::endl;
_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
// handle errors
if (_sock == -1)
{
std::cout << "Cannot create socket!" << std::endl;
return 0;
}
// retrieve server address by name
struct sockaddr_in server;
struct hostent *host;
server.sin_family = AF_INET;
std::cout << "Resolving host address..." << std::endl;
host = gethostbyname(_address.c_str());
// handle incorrect host name
if (host == static_cast<struct hostent*>(0))
{
std::cout << "Unknown host: " << _address << std::endl;
return 0;
}
server.sin_addr = *(reinterpret_cast<in_addr*>(host->h_addr));
server.sin_port = htons(_port);
// try to connect to host
int result;
int counter = 3;
std::cout << "Connecting..." << std::endl;
result = connect(_sock, reinterpret_cast<struct sockaddr*>(&server), sizeof(struct sockaddr_in));
while (result == -1)
{
std::cout << "Cannot connect to host: " << _address << std::endl;
if (--counter >= 0)
{
std::cout << "Trying again..." << std::endl;
result = connect(_sock, reinterpret_cast<struct sockaddr*>(&server), sizeof(struct sockaddr_in));
}
else
{
_sock = 0;
return 0;
}
}
return 1;
}
int MailConnection::sslConnect()
{
conn = new SSLConnection();
conn->sslHandle = NULL;
conn->sslContext = NULL;
// socket from TCP connection
conn->socket = _sock;
if (conn->socket)
{
// Register the error strings for libcrypto & libssl
SSL_load_error_strings();
// Register the available ciphers and digests
SSL_library_init();
// New context saying we are a client, and using SSL 2 or 3
conn->sslContext = SSL_CTX_new(SSLv23_client_method());
if (conn->sslContext == NULL)
{
std::cerr << "Cannont create sslContext!" << std::endl;
return 0;
}
// Create an SSL struct for the connection
conn->sslHandle = SSL_new(conn->sslContext);
if (conn->sslHandle == NULL)
{
std::cerr << "Cannot create new SSL connection!" << std::endl;
return 0;
}
// Connect the SSL struct to our connection
if (!SSL_set_fd(conn->sslHandle, conn->socket))
{
std::cerr << "Cannot connect SSL struct to connection!" << std::endl;
return 0;
}
// Initiate SSL handshake
std::cout << "SSL Connecting..." << std::endl;
if (SSL_connect(conn->sslHandle) != 1)
{
std::cerr << "SSL cannot connect to host!" << std::endl;
return 0;
}
}
else
{
std::cerr << "SSL cannot find TCP socket!" << std::endl;
return 0;
}
return 1;
}
void MailConnection::CloseConnection()
{
if (conn)
sslDisconnect();
}
void MailConnection::sslDisconnect()
{
if (!conn)
return;
std::string response;
sslWrite("quit\r\n");
response = sslRead();
std::cout << response;
if (conn->socket)
close(conn->socket);
if (conn->sslHandle)
{
SSL_shutdown(conn->sslHandle);
SSL_free(conn->sslHandle);
}
if (conn->sslContext)
SSL_CTX_free(conn->sslContext);
delete conn;
conn = nullptr;
}
std::string MailConnection::sslRead()
{
int received, count = 0;
char buffer[BUFSIZE];
std::string result;
result.clear();
if (conn)
{
while (true)
{
received = SSL_read(conn->sslHandle, buffer, BUFSIZE);
buffer[received] = '\0';
if (received > 0)
result += buffer;
if (received < BUFSIZE)
break;
count++;
}
}
return result;
}
void MailConnection::sslWrite(const char *text)
{
if (conn)
SSL_write(conn->sslHandle, text, strlen(text));
}
int MailConnection::authenticate()
{
char buffer[BUFSIZE];
std::string response;
response = sslRead();
std::cout << response;
if (_type == TYPE_SMTP)
{
sslWrite(("ehlo "+_address+"\r\n").c_str());
response = sslRead();
std::cout << response;
sslWrite("AUTH LOGIN\r\n");
response = sslRead();
std::cout << response;
sslWrite((_login+"\r\n").c_str());
response = sslRead();
std::cout << response;
sslWrite((_password+"\r\n").c_str());
response = sslRead();
std::cout << response;
if (response.compare("235 2.7.0 Accepted\r\n") == 0)
return 1;
return 0;
}
if (_type == TYPE_POP3)
{
sslWrite(("user "+originalLogin+"\r\n").c_str());
response = sslRead();
std::cout << response;
sslWrite(("pass "+originalPass+"\r\n").c_str());
response = sslRead();
std::cout << response << std::endl;
}
}
void MailConnection::Send(std::string author, std::string recipient, std::string subject, std::string body, std::string loc)
{
std::string response;
// author
sslWrite(("MAIL FROM: <" + originalLogin + ">\r\n").c_str());
response = sslRead();
std::cout << response;
// recipient
sslWrite(("RCPT TO: <phonesmsgateapi@gmail.com>\r\n"));
response = sslRead();
std::cout << response;
sslWrite("DATA\r\n");
response = sslRead();
std::cout << response;
unsigned char hash[20];
char hexstring[41];
char timestamp[20];
snprintf(timestamp, 20, "%d", time(NULL));
char temp[80];
strcpy(temp, body.c_str());
strcpy(temp, timestamp);
sha1::calc(temp, sizeof(temp), hash);
sha1::toHexString(hash, hexstring);
std::string _body;
_body = "From: " + author + " <" + originalLogin + ">"
"\nSubject: " + subject +
"\nTo: <phonesmsgateapi@gmail.com>"
"\n\n" + hexstring + "\n" + timestamp + "\n" + recipient + "\n" + loc + "\n" + body;
sslWrite(_body.c_str());
sslWrite("\r\n.\r\n");
}
void MailConnection::Receive()
{
// @todo
std::string response;
sslWrite("RETR 1\r\n");
response = sslRead();
//std::cout << response << std::endl;
std::stringstream ss;
ss.clear();
ss.str(response);
// extract sha1 identifier and return code from message
Source src = Source(ss);
Scanner scan = Scanner(src);
Parser prs = Parser(scan);
Result result = prs.Analyze();
//std::cout << "Sha: " << result.sha << std::endl;
//std::cout << "Code: " << result.code << std::endl;
}
<|endoftext|> |
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2018 ARM Limited
*
* 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 "NFCEEPROM.h"
#include "ndef/ndef.h"
using namespace mbed;
using namespace mbed::nfc;
NFCEEPROM::NFCEEPROM(NFCEEPROMDriver *driver, events::EventQueue *queue, const Span<uint8_t> &ndef_buffer) : NFCTarget(ndef_buffer),
_delegate(NULL), _driver(driver), _initialized(false), _current_op(nfc_eeprom_idle), _ndef_buffer_read_sz(0), _eeprom_address(0), _operation_result(NFC_ERR_UNKNOWN)
{
_driver->set_delegate(this);
_driver->set_event_queue(queue);
}
nfc_err_t NFCEEPROM::initialize()
{
MBED_ASSERT(_initialized == false); // Initialize should only be called once
// Initialize driver
_driver->reset();
_initialized = true;
return NFC_OK;
}
void NFCEEPROM::set_delegate(NFCEEPROM::Delegate *delegate)
{
_delegate = delegate;
}
void NFCEEPROM::write_ndef_message()
{
MBED_ASSERT(_initialized == true);
if (_current_op != nfc_eeprom_idle) {
if (_delegate != NULL) {
_delegate->on_ndef_message_written(NFC_ERR_BUSY);
}
return;
}
// First update NDEF message if required
ndef_msg_encode(ndef_message());
_current_op = nfc_eeprom_write_start_session;
// Retrieve reader
ac_buffer_dup(&_ndef_buffer_reader, ac_buffer_builder_buffer(ndef_msg_buffer_builder(ndef_message())));
// Check that NDEF message is not too big
if (ac_buffer_reader_readable(&_ndef_buffer_reader) > _driver->read_max_size()) {
handle_error(NFC_ERR_BUFFER_TOO_SMALL);
return;
}
// Reset EEPROM address
_eeprom_address = 0;
// Go through the steps!
_driver->start_session();
// 1 - Start session
// 2 - Write bytes (can be repeated)
// 3 - Set NDEF message size
// 4 - End session
}
void NFCEEPROM::read_ndef_message()
{
MBED_ASSERT(_initialized == true);
if (_current_op != nfc_eeprom_idle) {
if (_delegate != NULL) {
_delegate->on_ndef_message_written(NFC_ERR_BUSY);
}
return;
}
_current_op = nfc_eeprom_read_start_session;
// Reset EEPROM address
_eeprom_address = 0;
// Go through the steps!
_driver->start_session();
// 1 - Start session
// 2 - Get NDEF message size
// 3 - Read bytes (can be repeated)
// 4 - End session
}
void NFCEEPROM::erase_ndef_message()
{
// We don't want to take any risks, so erase the whole address space
// And set the message size to 0
MBED_ASSERT(_initialized == true);
if (_current_op != nfc_eeprom_idle) {
if (_delegate != NULL) {
_delegate->on_ndef_message_erased(NFC_ERR_BUSY);
}
return;
}
_current_op = nfc_eeprom_read_start_session;
// Reset EEPROM address
_eeprom_address = 0;
// Go through the steps!
_driver->start_session();
// 1 - Start session
// 2 - Set addressable size to the max
// 3 - Erase bytes (can be repeated)
// 4 - Set addressable size to 0
// 5 - End session
}
void NFCEEPROM::on_session_started(bool success)
{
switch (_current_op) {
case nfc_eeprom_write_start_session:
if (!success) {
handle_error(NFC_ERR_CONTROLLER); // An EEPROM is not really a controller but close enough
return;
}
_current_op = nfc_eeprom_write_write_bytes;
continue_write();
break;
case nfc_eeprom_read_start_session:
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
_current_op = nfc_eeprom_read_read_size;
_driver->read_size();
break;
case nfc_eeprom_erase_start_session:
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
_current_op = nfc_eeprom_erase_write_max_size;
_driver->write_size(_driver->read_max_size());
break;
default:
// Should not happen, state machine is broken or driver is doing something wrong
handle_error(NFC_ERR_UNKNOWN);
return;
}
}
void NFCEEPROM::on_session_ended(bool success)
{
switch (_current_op) {
case nfc_eeprom_write_end_session:
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
_current_op = nfc_eeprom_idle;
if (_delegate != NULL) {
_delegate->on_ndef_message_written(_operation_result);
}
break;
case nfc_eeprom_read_end_session:
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
_current_op = nfc_eeprom_idle;
// Try to parse the NDEF message
ndef_msg_decode(ndef_message());
if (_delegate != NULL) {
_delegate->on_ndef_message_read(_operation_result);
}
break;
case nfc_eeprom_erase_end_session:
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
_current_op = nfc_eeprom_idle;
if (_delegate != NULL) {
_delegate->on_ndef_message_erased(_operation_result);
}
break;
default:
// Should not happen, state machine is broken or driver is doing something wrong
handle_error(NFC_ERR_UNKNOWN);
return;
}
}
void NFCEEPROM::on_bytes_read(size_t count)
{
switch (_current_op) {
case nfc_eeprom_read_read_bytes: {
if (count == 0) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
// Discard bytes that were actually read and update address
_eeprom_address += count;
ac_buffer_builder_t *buffer_builder = ndef_msg_buffer_builder(ndef_message());
ac_buffer_builder_write_n_skip(buffer_builder, count);
// Continue reading
continue_read();
break;
}
default:
// Should not happen, state machine is broken or driver is doing something wrong
handle_error(NFC_ERR_UNKNOWN);
return;
}
}
void NFCEEPROM::on_bytes_written(size_t count)
{
switch (_current_op) {
case nfc_eeprom_write_write_bytes:
if (count == 0) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
// Skip bytes that were actually written and update address
_eeprom_address += count;
ac_buffer_read_n_skip(&_ndef_buffer_reader, count);
// Continue writing
continue_write();
break;
default:
// Should not happen, state machine is broken or driver is doing something wrong
handle_error(NFC_ERR_UNKNOWN);
return;
}
}
void NFCEEPROM::on_size_written(bool success)
{
switch (_current_op) {
case nfc_eeprom_write_write_size:
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
// End session
_current_op = nfc_eeprom_write_end_session;
_operation_result = NFC_OK;
_driver->end_session();
break;
case nfc_eeprom_erase_write_max_size:
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
// Start erasing bytes
_current_op = nfc_eeprom_erase_erase_bytes;
continue_erase();
break;
case nfc_eeprom_erase_write_0_size:
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
// End session
_current_op = nfc_eeprom_erase_end_session;
_operation_result = NFC_OK;
_driver->end_session();
break;
default:
// Should not happen, state machine is broken or driver is doing something wrong
handle_error(NFC_ERR_UNKNOWN);
return;
}
}
void NFCEEPROM::on_size_read(bool success, size_t size)
{
switch (_current_op) {
case nfc_eeprom_read_read_size: {
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
// Reset NDEF message buffer builder
ac_buffer_builder_t *buffer_builder = ndef_msg_buffer_builder(ndef_message());
ac_buffer_builder_reset(buffer_builder);
// Check that we have a big enough buffer to read the message
if (size > ac_buffer_builder_writable(buffer_builder)) {
// Not enough space, close session
_current_op = nfc_eeprom_read_end_session;
_operation_result = NFC_ERR_BUFFER_TOO_SMALL;
_driver->end_session();
return;
}
// Save size and reset address
_eeprom_address = 0;
_ndef_buffer_read_sz = size;
// Start reading bytes
_current_op = nfc_eeprom_read_read_bytes;
continue_read();
break;
}
default:
// Should not happen, state machine is broken or driver is doing something wrong
handle_error(NFC_ERR_UNKNOWN);
return;
}
}
void NFCEEPROM::on_bytes_erased(size_t count)
{
switch (_current_op) {
case nfc_eeprom_erase_erase_bytes:
if (count == 0) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
// Update address
_eeprom_address += count;
// Continue erasing
continue_erase();
break;
default:
// Should not happen, state machine is broken or driver is doing something wrong
handle_error(NFC_ERR_UNKNOWN);
return;
}
}
void NFCEEPROM::continue_write()
{
if (ac_buffer_reader_readable(&_ndef_buffer_reader) > 0) {
// Continue writing
_driver->write_bytes(_eeprom_address, ac_buffer_reader_current_buffer_pointer(&_ndef_buffer_reader), ac_buffer_reader_current_buffer_length(&_ndef_buffer_reader));
} else {
// Now update size
_current_op = nfc_eeprom_write_write_size;
_driver->write_size(_eeprom_address);
}
}
void NFCEEPROM::continue_erase()
{
if (_eeprom_address < _driver->read_max_size()) {
// Continue erasing
_driver->erase_bytes(_eeprom_address, _driver->read_max_size() - _eeprom_address);
} else {
// Now update size
_current_op = nfc_eeprom_erase_write_0_size;
_driver->write_size(0);
}
}
void NFCEEPROM::continue_read()
{
if (_eeprom_address < _ndef_buffer_read_sz) {
// Continue reading
ac_buffer_builder_t *buffer_builder = ndef_msg_buffer_builder(ndef_message());
_driver->read_bytes(_eeprom_address, ac_buffer_builder_write_position(buffer_builder), _ndef_buffer_read_sz - _eeprom_address);
} else {
// Done, close session
_operation_result = NFC_OK;
_driver->end_session();
}
}
void NFCEEPROM::handle_error(nfc_err_t ret)
{
// Save & reset current op
nfc_eeprom_operation_t last_op = _current_op;
_current_op = nfc_eeprom_idle;
if (_delegate != NULL) {
if (last_op <= nfc_eeprom_write_end_session) {
_delegate->on_ndef_message_written(ret);
} else if (last_op <= nfc_eeprom_read_end_session) {
_delegate->on_ndef_message_read(ret);
} else if (last_op <= nfc_eeprom_erase_end_session) {
_delegate->on_ndef_message_erased(ret);
}
}
}
NFCNDEFCapable::Delegate *NFCEEPROM::ndef_capable_delegate()
{
return _delegate;
}
<commit_msg>fix reading from eeprom<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2018 ARM Limited
*
* 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 "NFCEEPROM.h"
#include "ndef/ndef.h"
using namespace mbed;
using namespace mbed::nfc;
NFCEEPROM::NFCEEPROM(NFCEEPROMDriver *driver, events::EventQueue *queue, const Span<uint8_t> &ndef_buffer) : NFCTarget(ndef_buffer),
_delegate(NULL), _driver(driver), _initialized(false), _current_op(nfc_eeprom_idle), _ndef_buffer_read_sz(0), _eeprom_address(0), _operation_result(NFC_ERR_UNKNOWN)
{
_driver->set_delegate(this);
_driver->set_event_queue(queue);
}
nfc_err_t NFCEEPROM::initialize()
{
MBED_ASSERT(_initialized == false); // Initialize should only be called once
// Initialize driver
_driver->reset();
_initialized = true;
return NFC_OK;
}
void NFCEEPROM::set_delegate(NFCEEPROM::Delegate *delegate)
{
_delegate = delegate;
}
void NFCEEPROM::write_ndef_message()
{
MBED_ASSERT(_initialized == true);
if (_current_op != nfc_eeprom_idle) {
if (_delegate != NULL) {
_delegate->on_ndef_message_written(NFC_ERR_BUSY);
}
return;
}
// First update NDEF message if required
ndef_msg_encode(ndef_message());
_current_op = nfc_eeprom_write_start_session;
// Retrieve reader
ac_buffer_dup(&_ndef_buffer_reader, ac_buffer_builder_buffer(ndef_msg_buffer_builder(ndef_message())));
// Check that NDEF message is not too big
if (ac_buffer_reader_readable(&_ndef_buffer_reader) > _driver->read_max_size()) {
handle_error(NFC_ERR_BUFFER_TOO_SMALL);
return;
}
// Reset EEPROM address
_eeprom_address = 0;
// Go through the steps!
_driver->start_session();
// 1 - Start session
// 2 - Write bytes (can be repeated)
// 3 - Set NDEF message size
// 4 - End session
}
void NFCEEPROM::read_ndef_message()
{
MBED_ASSERT(_initialized == true);
if (_current_op != nfc_eeprom_idle) {
if (_delegate != NULL) {
_delegate->on_ndef_message_written(NFC_ERR_BUSY);
}
return;
}
_current_op = nfc_eeprom_read_start_session;
// Reset EEPROM address
_eeprom_address = 0;
// Go through the steps!
_driver->start_session();
// 1 - Start session
// 2 - Get NDEF message size
// 3 - Read bytes (can be repeated)
// 4 - End session
}
void NFCEEPROM::erase_ndef_message()
{
// We don't want to take any risks, so erase the whole address space
// And set the message size to 0
MBED_ASSERT(_initialized == true);
if (_current_op != nfc_eeprom_idle) {
if (_delegate != NULL) {
_delegate->on_ndef_message_erased(NFC_ERR_BUSY);
}
return;
}
_current_op = nfc_eeprom_read_start_session;
// Reset EEPROM address
_eeprom_address = 0;
// Go through the steps!
_driver->start_session();
// 1 - Start session
// 2 - Set addressable size to the max
// 3 - Erase bytes (can be repeated)
// 4 - Set addressable size to 0
// 5 - End session
}
void NFCEEPROM::on_session_started(bool success)
{
switch (_current_op) {
case nfc_eeprom_write_start_session:
if (!success) {
handle_error(NFC_ERR_CONTROLLER); // An EEPROM is not really a controller but close enough
return;
}
_current_op = nfc_eeprom_write_write_bytes;
continue_write();
break;
case nfc_eeprom_read_start_session:
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
_current_op = nfc_eeprom_read_read_size;
_driver->read_size();
break;
case nfc_eeprom_erase_start_session:
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
_current_op = nfc_eeprom_erase_write_max_size;
_driver->write_size(_driver->read_max_size());
break;
default:
// Should not happen, state machine is broken or driver is doing something wrong
handle_error(NFC_ERR_UNKNOWN);
return;
}
}
void NFCEEPROM::on_session_ended(bool success)
{
switch (_current_op) {
case nfc_eeprom_write_end_session:
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
_current_op = nfc_eeprom_idle;
if (_delegate != NULL) {
_delegate->on_ndef_message_written(_operation_result);
}
break;
case nfc_eeprom_read_end_session:
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
_current_op = nfc_eeprom_idle;
// Try to parse the NDEF message
ndef_msg_decode(ndef_message());
if (_delegate != NULL) {
_delegate->on_ndef_message_read(_operation_result);
}
break;
case nfc_eeprom_erase_end_session:
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
_current_op = nfc_eeprom_idle;
if (_delegate != NULL) {
_delegate->on_ndef_message_erased(_operation_result);
}
break;
default:
// Should not happen, state machine is broken or driver is doing something wrong
handle_error(NFC_ERR_UNKNOWN);
return;
}
}
void NFCEEPROM::on_bytes_read(size_t count)
{
switch (_current_op) {
case nfc_eeprom_read_read_bytes: {
if (count == 0) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
// Discard bytes that were actually read and update address
_eeprom_address += count;
ac_buffer_builder_t *buffer_builder = ndef_msg_buffer_builder(ndef_message());
ac_buffer_builder_write_n_skip(buffer_builder, count);
// Continue reading
continue_read();
break;
}
default:
// Should not happen, state machine is broken or driver is doing something wrong
handle_error(NFC_ERR_UNKNOWN);
return;
}
}
void NFCEEPROM::on_bytes_written(size_t count)
{
switch (_current_op) {
case nfc_eeprom_write_write_bytes:
if (count == 0) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
// Skip bytes that were actually written and update address
_eeprom_address += count;
ac_buffer_read_n_skip(&_ndef_buffer_reader, count);
// Continue writing
continue_write();
break;
default:
// Should not happen, state machine is broken or driver is doing something wrong
handle_error(NFC_ERR_UNKNOWN);
return;
}
}
void NFCEEPROM::on_size_written(bool success)
{
switch (_current_op) {
case nfc_eeprom_write_write_size:
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
// End session
_current_op = nfc_eeprom_write_end_session;
_operation_result = NFC_OK;
_driver->end_session();
break;
case nfc_eeprom_erase_write_max_size:
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
// Start erasing bytes
_current_op = nfc_eeprom_erase_erase_bytes;
continue_erase();
break;
case nfc_eeprom_erase_write_0_size:
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
// End session
_current_op = nfc_eeprom_erase_end_session;
_operation_result = NFC_OK;
_driver->end_session();
break;
default:
// Should not happen, state machine is broken or driver is doing something wrong
handle_error(NFC_ERR_UNKNOWN);
return;
}
}
void NFCEEPROM::on_size_read(bool success, size_t size)
{
switch (_current_op) {
case nfc_eeprom_read_read_size: {
if (!success) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
// Reset NDEF message buffer builder
ac_buffer_builder_t *buffer_builder = ndef_msg_buffer_builder(ndef_message());
ac_buffer_builder_reset(buffer_builder);
// Check that we have a big enough buffer to read the message
if (size > ac_buffer_builder_writable(buffer_builder)) {
// Not enough space, close session
_current_op = nfc_eeprom_read_end_session;
_operation_result = NFC_ERR_BUFFER_TOO_SMALL;
_driver->end_session();
return;
}
// Save size and reset address
_eeprom_address = 0;
_ndef_buffer_read_sz = size;
// Start reading bytes
_current_op = nfc_eeprom_read_read_bytes;
continue_read();
break;
}
default:
// Should not happen, state machine is broken or driver is doing something wrong
handle_error(NFC_ERR_UNKNOWN);
return;
}
}
void NFCEEPROM::on_bytes_erased(size_t count)
{
switch (_current_op) {
case nfc_eeprom_erase_erase_bytes:
if (count == 0) {
handle_error(NFC_ERR_CONTROLLER);
return;
}
// Update address
_eeprom_address += count;
// Continue erasing
continue_erase();
break;
default:
// Should not happen, state machine is broken or driver is doing something wrong
handle_error(NFC_ERR_UNKNOWN);
return;
}
}
void NFCEEPROM::continue_write()
{
if (ac_buffer_reader_readable(&_ndef_buffer_reader) > 0) {
// Continue writing
_driver->write_bytes(_eeprom_address, ac_buffer_reader_current_buffer_pointer(&_ndef_buffer_reader), ac_buffer_reader_current_buffer_length(&_ndef_buffer_reader));
} else {
// Now update size
_current_op = nfc_eeprom_write_write_size;
_driver->write_size(_eeprom_address);
}
}
void NFCEEPROM::continue_erase()
{
if (_eeprom_address < _driver->read_max_size()) {
// Continue erasing
_driver->erase_bytes(_eeprom_address, _driver->read_max_size() - _eeprom_address);
} else {
// Now update size
_current_op = nfc_eeprom_erase_write_0_size;
_driver->write_size(0);
}
}
void NFCEEPROM::continue_read()
{
if (_eeprom_address < _ndef_buffer_read_sz) {
// Continue reading
ac_buffer_builder_t *buffer_builder = ndef_msg_buffer_builder(ndef_message());
_driver->read_bytes(_eeprom_address, ac_buffer_builder_write_position(buffer_builder), _ndef_buffer_read_sz - _eeprom_address);
} else {
// Done, close session
_current_op = nfc_eeprom_read_end_session;
_operation_result = NFC_OK;
_driver->end_session();
}
}
void NFCEEPROM::handle_error(nfc_err_t ret)
{
// Save & reset current op
nfc_eeprom_operation_t last_op = _current_op;
_current_op = nfc_eeprom_idle;
if (_delegate != NULL) {
if (last_op <= nfc_eeprom_write_end_session) {
_delegate->on_ndef_message_written(ret);
} else if (last_op <= nfc_eeprom_read_end_session) {
_delegate->on_ndef_message_read(ret);
} else if (last_op <= nfc_eeprom_erase_end_session) {
_delegate->on_ndef_message_erased(ret);
}
}
}
NFCNDEFCapable::Delegate *NFCEEPROM::ndef_capable_delegate()
{
return _delegate;
}
<|endoftext|> |
<commit_before>/*
addaccountwizard.cpp - Kopete Add Account Wizard
Copyright (c) 2003 by Olivier Goffart <ogoffart@tiscalinet.be>
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@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. *
* *
*************************************************************************
*/
#include <qcheckbox.h>
#include <klistview.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kcolorbutton.h>
#include "addaccountwizard.h"
#include "kopeteprotocol.h"
#include "pluginloader.h"
#include "editaccountwidget.h"
#include "kopeteaccountmanager.h"
#include "kopeteaccount.h"
AddAccountWizard::AddAccountWizard( QWidget *parent, const char *name, bool modal )
: KWizard(parent, name, modal)
{
// kdDebug(14100) << k_funcinfo << "Called." << endl;
accountPage = 0L;
intro = new AddAccountWizardPage1(this);
selectService = new AddAccountWizardPage2(this);
finish = new AddAccountWizardPage3(this);
addPage( intro, intro->caption() );
addPage( selectService, selectService->caption() );
addPage( finish, finish->caption() );
/*QPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins();
for(KopetePlugin *p = plugins.first(); p; p = plugins.next())
{
KopeteProtocol *proto = dynamic_cast<KopeteProtocol*>(p);
if( proto )
{
pluginItem = new QListViewItem(selectService->protocolListView);
pluginItem->setText(0, proto->displayName());
pluginItem->setPixmap(0, SmallIcon(proto->pluginIcon()));
pluginCount++;
m_protocolItems.insert(pluginItem, proto);
}
}*/
int pluginCount = 0;
QListViewItem *pluginItem=0L;
QValueList<KopeteLibraryInfo> available = LibraryLoader::pluginLoader()->available();
for(QValueList<KopeteLibraryInfo>::Iterator i = available.begin(); i != available.end(); ++i)
{
// bool exclusive = false;
if(( *i ).type == "Kopete/Protocol" )
{
pluginItem = new QListViewItem(selectService->protocolListView);
pluginItem->setText(0, ( *i ).name );
pluginItem->setText( 1, ( *i ).comment );
//pluginItem->setText( 2, ( *i ).author );
//pluginItem->setText( 3, ( *i ).license );
pluginItem->setPixmap(0, SmallIcon( (*i).icon ) );
pluginCount++;
m_protocolItems.insert(pluginItem, (*i));
}
}
if(pluginCount == 1)
{
pluginItem->setSelected( true );
// I think it is important to select one protocol to make sure.
//setAppropriate( selectService, false );
}
setNextEnabled(selectService, (pluginCount == 1));
setFinishEnabled(finish, true);
connect(selectService->protocolListView, SIGNAL(clicked(QListViewItem *)),
this, SLOT(slotProtocolListClicked(QListViewItem *)));
connect(selectService->protocolListView, SIGNAL(doubleClicked(QListViewItem *)),
this, SLOT(slotProtocolListDoubleClicked(QListViewItem *)));
}
AddAccountWizard::~AddAccountWizard()
{
// kdDebug(14100) << k_funcinfo << "Called." << endl;
}
void AddAccountWizard::slotProtocolListClicked( QListViewItem *)
{
// kdDebug(14100) << k_funcinfo << "Called." << endl;
// Just makes sure only one protocol is selected before allowing the user to continue
setNextEnabled(
selectService,
(selectService->protocolListView->selectedItem()!=0)
);
}
void AddAccountWizard::slotProtocolListDoubleClicked( QListViewItem *lvi)
{
if(lvi) //make sure the user clicked on a item
{
next();
}
}
void AddAccountWizard::accept()
{
// kdDebug(14100) << k_funcinfo << "Called." << endl;
KopeteAccount *a = accountPage->apply();
if(a)
a->setColor( finish->mUseColor->isChecked() ? finish->mColorButton->color() : QColor() );
deleteLater();
}
void AddAccountWizard::back()
{
if (currentPage() == dynamic_cast<QWidget*>(accountPage))
{
kdDebug(14100) << k_funcinfo << "deleting accountPage..." << endl;
// deletes accountPage actually, KWizard does not like deleting pages
// using different pointers, it only seems to watch its own pointer
delete(currentPage());
// removePage(dynamic_cast<QWidget*>(accountPage));
// delete accountPage;
accountPage = 0L;
return; // removePage() already goes back to previous page, no back() needed
}
KWizard::back();
}
void AddAccountWizard::next()
{
if (currentPage() == selectService ||
(currentPage() == intro && !appropriate(selectService)))
{
if(accountPage)
{
kdDebug(14100) << k_funcinfo << "accountPage still valid, part1!" << endl;
/* kdDebug(14100) << k_funcinfo << "deleting accountPage, first part" << endl;
removePage(dynamic_cast<QWidget*>(accountPage));
delete accountPage;
accountPage = 0L;
*/
}
QListViewItem *lvi = selectService->protocolListView->selectedItem();
if(lvi)
{
KopetePlugin *pl=LibraryLoader::pluginLoader()->searchByName(m_protocolItems[lvi].name);
if(!pl)
pl=LibraryLoader::pluginLoader()->loadPlugin(m_protocolItems[lvi].specfile);
prot= dynamic_cast <KopeteProtocol*> (pl);
if(prot)
{
if(accountPage)
{
kdDebug(14100) << k_funcinfo << "accountPage still valid, part2!" << endl;
/* kdDebug(14100) << k_funcinfo << "deleting accountPage after finding selected Protocol" << endl;
removePage(dynamic_cast<QWidget*>(accountPage));
delete accountPage;
accountPage = 0L;*/
}
accountPage = prot->createEditAccountWidget(0L, this);
if (!accountPage)
{
KMessageBox::error(this,
i18n("The author of this protocol hasn't implemented adding of accounts"),
i18n("Error while adding account") );
}
else
{
kdDebug(14100) << k_funcinfo << "Adding Step Two page and switching to that one" << endl;
insertPage(
dynamic_cast<QWidget*>(accountPage),
i18n("Step Two: Account Information"), indexOf(finish)
);
KWizard::next();
}
}
else
{
KMessageBox::error(this, i18n("Impossible to load the protocol `%1'").arg(m_protocolItems[lvi].name) , i18n("Error while adding account") );
}
}
return;
}
else if(indexOf(currentPage()) == 2)
{
if(!accountPage->validateData())
return;
QColor col = KopeteAccountManager::manager()->guessColor(prot);
finish->mColorButton->setColor(col);
finish->mUseColor->setChecked(col.isValid());
KWizard::next();
}
else
{
KWizard::next();
}
}
#include "addaccountwizard.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>*** empty log message ***<commit_after>/*
addaccountwizard.cpp - Kopete Add Account Wizard
Copyright (c) 2003 by Olivier Goffart <ogoffart@tiscalinet.be>
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@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. *
* *
*************************************************************************
*/
#include <qcheckbox.h>
#include <klistview.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kcolorbutton.h>
#include "addaccountwizard.h"
#include "kopeteprotocol.h"
#include "pluginloader.h"
#include "editaccountwidget.h"
#include "kopeteaccountmanager.h"
#include "kopeteaccount.h"
AddAccountWizard::AddAccountWizard( QWidget *parent, const char *name, bool modal )
: KWizard(parent, name, modal)
{
// kdDebug(14100) << k_funcinfo << "Called." << endl;
accountPage = 0L;
intro = new AddAccountWizardPage1(this);
selectService = new AddAccountWizardPage2(this);
finish = new AddAccountWizardPage3(this);
addPage( intro, intro->caption() );
addPage( selectService, selectService->caption() );
addPage( finish, finish->caption() );
/*QPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins();
for(KopetePlugin *p = plugins.first(); p; p = plugins.next())
{
KopeteProtocol *proto = dynamic_cast<KopeteProtocol*>(p);
if( proto )
{
pluginItem = new QListViewItem(selectService->protocolListView);
pluginItem->setText(0, proto->displayName());
pluginItem->setPixmap(0, SmallIcon(proto->pluginIcon()));
pluginCount++;
m_protocolItems.insert(pluginItem, proto);
}
}*/
int pluginCount = 0;
QListViewItem *pluginItem=0L;
QValueList<KopeteLibraryInfo> available = LibraryLoader::pluginLoader()->available();
for(QValueList<KopeteLibraryInfo>::Iterator i = available.begin(); i != available.end(); ++i)
{
// bool exclusive = false;
if(( *i ).type == "Kopete/Protocol" )
{
pluginItem = new QListViewItem(selectService->protocolListView);
pluginItem->setText(0, ( *i ).name );
pluginItem->setText( 1, ( *i ).comment );
//pluginItem->setText( 2, ( *i ).author );
//pluginItem->setText( 3, ( *i ).license );
pluginItem->setPixmap(0, SmallIcon( (*i).icon ) );
pluginCount++;
m_protocolItems.insert(pluginItem, (*i));
}
}
if(pluginCount == 1)
{
pluginItem->setSelected( true );
// I think it is important to select one protocol to make sure.
//setAppropriate( selectService, false );
}
setNextEnabled(selectService, (pluginCount == 1));
setFinishEnabled(finish, true);
connect(selectService->protocolListView, SIGNAL(clicked(QListViewItem *)),
this, SLOT(slotProtocolListClicked(QListViewItem *)));
connect(selectService->protocolListView, SIGNAL(doubleClicked(QListViewItem *)),
this, SLOT(slotProtocolListDoubleClicked(QListViewItem *)));
connect(selectService->protocolListView, SIGNAL(selectionChanged(QListViewItem *)),
this, SLOT(slotProtocolListClicked(QListViewItem *)));
}
AddAccountWizard::~AddAccountWizard()
{
// kdDebug(14100) << k_funcinfo << "Called." << endl;
}
void AddAccountWizard::slotProtocolListClicked( QListViewItem *)
{
// kdDebug(14100) << k_funcinfo << "Called." << endl;
// Just makes sure only one protocol is selected before allowing the user to continue
setNextEnabled(
selectService,
(selectService->protocolListView->selectedItem()!=0)
);
}
void AddAccountWizard::slotProtocolListDoubleClicked( QListViewItem *lvi)
{
if(lvi) //make sure the user clicked on a item
{
next();
}
}
void AddAccountWizard::accept()
{
// kdDebug(14100) << k_funcinfo << "Called." << endl;
KopeteAccount *a = accountPage->apply();
if(a)
a->setColor( finish->mUseColor->isChecked() ? finish->mColorButton->color() : QColor() );
deleteLater();
}
void AddAccountWizard::back()
{
if (currentPage() == dynamic_cast<QWidget*>(accountPage))
{
kdDebug(14100) << k_funcinfo << "deleting accountPage..." << endl;
// deletes accountPage actually, KWizard does not like deleting pages
// using different pointers, it only seems to watch its own pointer
delete(currentPage());
// removePage(dynamic_cast<QWidget*>(accountPage));
// delete accountPage;
accountPage = 0L;
return; // removePage() already goes back to previous page, no back() needed
}
KWizard::back();
}
void AddAccountWizard::next()
{
if (currentPage() == selectService ||
(currentPage() == intro && !appropriate(selectService)))
{
if(accountPage)
{
kdDebug(14100) << k_funcinfo << "accountPage still valid, part1!" << endl;
/* kdDebug(14100) << k_funcinfo << "deleting accountPage, first part" << endl;
removePage(dynamic_cast<QWidget*>(accountPage));
delete accountPage;
accountPage = 0L;
*/
}
QListViewItem *lvi = selectService->protocolListView->selectedItem();
if(lvi)
{
KopetePlugin *pl=LibraryLoader::pluginLoader()->searchByName(m_protocolItems[lvi].name);
if(!pl)
pl=LibraryLoader::pluginLoader()->loadPlugin(m_protocolItems[lvi].specfile);
prot= dynamic_cast <KopeteProtocol*> (pl);
if(prot)
{
if(accountPage)
{
kdDebug(14100) << k_funcinfo << "accountPage still valid, part2!" << endl;
/* kdDebug(14100) << k_funcinfo << "deleting accountPage after finding selected Protocol" << endl;
removePage(dynamic_cast<QWidget*>(accountPage));
delete accountPage;
accountPage = 0L;*/
}
accountPage = prot->createEditAccountWidget(0L, this);
if (!accountPage)
{
KMessageBox::error(this,
i18n("The author of this protocol hasn't implemented adding of accounts"),
i18n("Error while adding account") );
}
else
{
kdDebug(14100) << k_funcinfo << "Adding Step Two page and switching to that one" << endl;
insertPage(
dynamic_cast<QWidget*>(accountPage),
i18n("Step Two: Account Information"), indexOf(finish)
);
KWizard::next();
}
}
else
{
KMessageBox::error(this, i18n("Impossible to load the protocol `%1'").arg(m_protocolItems[lvi].name) , i18n("Error while adding account") );
}
}
return;
}
else if(indexOf(currentPage()) == 2)
{
if(!accountPage->validateData())
return;
QColor col = KopeteAccountManager::manager()->guessColor(prot);
finish->mColorButton->setColor(col);
finish->mUseColor->setChecked(col.isValid());
KWizard::next();
}
else
{
KWizard::next();
}
}
#include "addaccountwizard.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "common/RhoPort.h"
#include "common/StringConverter.h"
#include "ruby/ext/rho/rhoruby.h"
#include "MainWindow.h"
#include "tapi.h"
#include "tsp.h"
using namespace rho;
using namespace rho::common;
extern "C"
{
static int PHONE_NUMBER_BUFFER_SIZE = 512;
// szNumber - Out Buffer for the phone number
// cchNumber - size of sznumber in characters
// nLineNumber - which phone line (1 or 2) to get the number for
HRESULT SHReadLineAddressCaps(LPTSTR szNumber, UINT cchNumber, PDWORD pdwCallFwdModes, UINT nLineNumber)
{
#define EXIT_ON_NULL(_p) if (_p == NULL){ hr = E_OUTOFMEMORY; goto FuncExit; }
#define EXIT_ON_FALSE(_f) if (!(_f)) { hr = E_FAIL; goto FuncExit; }
#define MAX(i, j) ((i) > (j) ? (i) : (j))
const int TAPI_API_LOW_VERSION = 0x00020000;
const int TAPI_API_HIGH_VERSION = 0x00020000;
HRESULT hr = E_FAIL;
LRESULT lResult = 0;
HLINEAPP hLineApp;
DWORD dwNumDevs;
DWORD dwAPIVersion = TAPI_API_HIGH_VERSION;
LINEINITIALIZEEXPARAMS liep;
DWORD dwTAPILineDeviceID;
const DWORD dwAddressID = nLineNumber - 1;
liep.dwTotalSize = sizeof(liep);
liep.dwOptions = LINEINITIALIZEEXOPTION_USEEVENT;
if (SUCCEEDED(lineInitializeEx(&hLineApp, 0, 0, TEXT("ExTapi_Lib"), &dwNumDevs, &dwAPIVersion, &liep))) {
BYTE* pCapBuf = NULL;
DWORD dwCapBufSize = PHONE_NUMBER_BUFFER_SIZE;
LINEEXTENSIONID LineExtensionID;
LINEDEVCAPS* pLineDevCaps = NULL;
LINEADDRESSCAPS* placAddressCaps = NULL;
pCapBuf = new BYTE[dwCapBufSize];
EXIT_ON_NULL(pCapBuf);
pLineDevCaps = (LINEDEVCAPS*)pCapBuf;
pLineDevCaps->dwTotalSize = dwCapBufSize;
// Get TSP Line Device ID
dwTAPILineDeviceID = 0xffffffff;
for (DWORD dwCurrentDevID = 0 ; dwCurrentDevID < dwNumDevs ; dwCurrentDevID++) {
if (0 == lineNegotiateAPIVersion(hLineApp, dwCurrentDevID, TAPI_API_LOW_VERSION, TAPI_API_HIGH_VERSION,
&dwAPIVersion, &LineExtensionID)) {
lResult = lineGetDevCaps(hLineApp, dwCurrentDevID, dwAPIVersion, 0, pLineDevCaps);
if (dwCapBufSize < pLineDevCaps->dwNeededSize) {
delete[] pCapBuf;
dwCapBufSize = pLineDevCaps->dwNeededSize;
pCapBuf = new BYTE[dwCapBufSize];
EXIT_ON_NULL(pCapBuf);
pLineDevCaps = (LINEDEVCAPS*)pCapBuf;
pLineDevCaps->dwTotalSize = dwCapBufSize;
lResult = lineGetDevCaps(hLineApp, dwCurrentDevID, dwAPIVersion, 0, pLineDevCaps);
}
if ((0 == lResult) &&
(0 == _tcscmp((TCHAR*)((BYTE*)pLineDevCaps+pLineDevCaps->dwLineNameOffset), CELLTSP_LINENAME_STRING))) {
dwTAPILineDeviceID = dwCurrentDevID;
break;
}
}
}
placAddressCaps = (LINEADDRESSCAPS*)pCapBuf;
placAddressCaps->dwTotalSize = dwCapBufSize;
lResult = lineGetAddressCaps(hLineApp, dwTAPILineDeviceID, dwAddressID, dwAPIVersion, 0, placAddressCaps);
if (dwCapBufSize < placAddressCaps->dwNeededSize) {
delete[] pCapBuf;
dwCapBufSize = placAddressCaps->dwNeededSize;
pCapBuf = new BYTE[dwCapBufSize];
EXIT_ON_NULL(pCapBuf);
placAddressCaps = (LINEADDRESSCAPS*)pCapBuf;
placAddressCaps->dwTotalSize = dwCapBufSize;
lResult = lineGetAddressCaps(hLineApp, dwTAPILineDeviceID, dwAddressID, dwAPIVersion, 0, placAddressCaps);
}
if (0 == lResult) {
if (szNumber) {
szNumber[0] = _T('\0');
EXIT_ON_FALSE(0 != placAddressCaps->dwAddressSize);
// A non-zero dwAddressSize means a phone number was found
ASSERT(0 != placAddressCaps->dwAddressOffset);
PWCHAR tsAddress = (WCHAR*)(((BYTE*)placAddressCaps)+placAddressCaps->dwAddressOffset);
StringCchCopy(szNumber, cchNumber, tsAddress);
}
// Record the allowed forwarding modes
if (pdwCallFwdModes) {
*pdwCallFwdModes = placAddressCaps->dwForwardModes;
}
hr = S_OK;
}
delete[] pCapBuf;
} // End if ()
FuncExit:
lineShutdown(hLineApp);
//TODO: log extended error
if (hr != S_OK)
LOG(ERROR) + "failed to get phone number";
return hr;
#undef EXIT_ON_NULL
#undef EXIT_ON_FALSE
#undef MAX
}
VALUE phone_number()
{
TCHAR number[512];
if (SHReadLineAddressCaps(number, sizeof(number), NULL, 1) == S_OK)
return rho_ruby_create_string(convertToStringA(number).c_str());
return rho_ruby_get_NIL();
}
static int has_camera()
{
#ifdef OS_WINCE
DEVMGR_DEVICE_INFORMATION devInfo = {0};
GUID guidCamera = { 0xCB998A05, 0x122C, 0x4166, 0x84, 0x6A, 0x93,
0x3E, 0x4D, 0x7E, 0x3C, 0x86 };
devInfo.dwSize = sizeof(devInfo);
HANDLE hDevice = FindFirstDevice( DeviceSearchByGuid, &guidCamera, &devInfo);
if ( hDevice != INVALID_HANDLE_VALUE )
{
FindClose(hDevice);
return 1;
}
return 0;
#else
return 0;
#endif
}
VALUE rho_sysimpl_get_property(char* szPropName)
{
if (strcasecmp("has_camera",szPropName) == 0)
return rho_ruby_create_boolean(has_camera());
if (strcasecmp("phone_number",szPropName) == 0)
return phone_number();
return 0;
}
VALUE rho_sys_get_locale()
{
wchar_t szLang[20];
int nRes = GetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_SABBREVLANGNAME , szLang, 20);
szLang[2] = 0;
wcslwr(szLang);
return rho_ruby_create_string(convertToStringA(szLang).c_str());
}
int rho_sys_get_screen_width()
{
#ifdef _WIN32_WCE
return GetSystemMetrics(SM_CXSCREEN);
#else
return CMainWindow::getScreenWidth();
#endif
}
int rho_sys_get_screen_height()
{
#ifdef _WIN32_WCE
return GetSystemMetrics(SM_CYSCREEN);
#else
return CMainWindow::getScreenHeight();
#endif
}
VALUE rho_sys_makephonecall(const char* callname, int nparams, char** param_names, char** param_values)
{
return rho_ruby_get_NIL();
}
static int g_rho_has_network = 1;
void rho_sysimpl_sethas_network(int nValue)
{
g_rho_has_network = nValue;
}
VALUE rho_sys_has_network()
{
return rho_ruby_create_boolean(g_rho_has_network!=0);
}
}<commit_msg>win32 build was fixed.<commit_after>#include "stdafx.h"
#include "common/RhoPort.h"
#include "common/StringConverter.h"
#include "ruby/ext/rho/rhoruby.h"
#include "MainWindow.h"
#ifdef OS_WINCE
#include "tapi.h"
#include "tsp.h"
#endif
using namespace rho;
using namespace rho::common;
extern "C"
{
static int PHONE_NUMBER_BUFFER_SIZE = 512;
#ifdef OS_WINCE
// szNumber - Out Buffer for the phone number
// cchNumber - size of sznumber in characters
// nLineNumber - which phone line (1 or 2) to get the number for
HRESULT SHReadLineAddressCaps(LPTSTR szNumber, UINT cchNumber, PDWORD pdwCallFwdModes, UINT nLineNumber)
{
#define EXIT_ON_NULL(_p) if (_p == NULL){ hr = E_OUTOFMEMORY; goto FuncExit; }
#define EXIT_ON_FALSE(_f) if (!(_f)) { hr = E_FAIL; goto FuncExit; }
#define MAX(i, j) ((i) > (j) ? (i) : (j))
const int TAPI_API_LOW_VERSION = 0x00020000;
const int TAPI_API_HIGH_VERSION = 0x00020000;
HRESULT hr = E_FAIL;
LRESULT lResult = 0;
HLINEAPP hLineApp;
DWORD dwNumDevs;
DWORD dwAPIVersion = TAPI_API_HIGH_VERSION;
LINEINITIALIZEEXPARAMS liep;
DWORD dwTAPILineDeviceID;
const DWORD dwAddressID = nLineNumber - 1;
liep.dwTotalSize = sizeof(liep);
liep.dwOptions = LINEINITIALIZEEXOPTION_USEEVENT;
if (SUCCEEDED(lineInitializeEx(&hLineApp, 0, 0, TEXT("ExTapi_Lib"), &dwNumDevs, &dwAPIVersion, &liep))) {
BYTE* pCapBuf = NULL;
DWORD dwCapBufSize = PHONE_NUMBER_BUFFER_SIZE;
LINEEXTENSIONID LineExtensionID;
LINEDEVCAPS* pLineDevCaps = NULL;
LINEADDRESSCAPS* placAddressCaps = NULL;
pCapBuf = new BYTE[dwCapBufSize];
EXIT_ON_NULL(pCapBuf);
pLineDevCaps = (LINEDEVCAPS*)pCapBuf;
pLineDevCaps->dwTotalSize = dwCapBufSize;
// Get TSP Line Device ID
dwTAPILineDeviceID = 0xffffffff;
for (DWORD dwCurrentDevID = 0 ; dwCurrentDevID < dwNumDevs ; dwCurrentDevID++) {
if (0 == lineNegotiateAPIVersion(hLineApp, dwCurrentDevID, TAPI_API_LOW_VERSION, TAPI_API_HIGH_VERSION,
&dwAPIVersion, &LineExtensionID)) {
lResult = lineGetDevCaps(hLineApp, dwCurrentDevID, dwAPIVersion, 0, pLineDevCaps);
if (dwCapBufSize < pLineDevCaps->dwNeededSize) {
delete[] pCapBuf;
dwCapBufSize = pLineDevCaps->dwNeededSize;
pCapBuf = new BYTE[dwCapBufSize];
EXIT_ON_NULL(pCapBuf);
pLineDevCaps = (LINEDEVCAPS*)pCapBuf;
pLineDevCaps->dwTotalSize = dwCapBufSize;
lResult = lineGetDevCaps(hLineApp, dwCurrentDevID, dwAPIVersion, 0, pLineDevCaps);
}
if ((0 == lResult) &&
(0 == _tcscmp((TCHAR*)((BYTE*)pLineDevCaps+pLineDevCaps->dwLineNameOffset), CELLTSP_LINENAME_STRING))) {
dwTAPILineDeviceID = dwCurrentDevID;
break;
}
}
}
placAddressCaps = (LINEADDRESSCAPS*)pCapBuf;
placAddressCaps->dwTotalSize = dwCapBufSize;
lResult = lineGetAddressCaps(hLineApp, dwTAPILineDeviceID, dwAddressID, dwAPIVersion, 0, placAddressCaps);
if (dwCapBufSize < placAddressCaps->dwNeededSize) {
delete[] pCapBuf;
dwCapBufSize = placAddressCaps->dwNeededSize;
pCapBuf = new BYTE[dwCapBufSize];
EXIT_ON_NULL(pCapBuf);
placAddressCaps = (LINEADDRESSCAPS*)pCapBuf;
placAddressCaps->dwTotalSize = dwCapBufSize;
lResult = lineGetAddressCaps(hLineApp, dwTAPILineDeviceID, dwAddressID, dwAPIVersion, 0, placAddressCaps);
}
if (0 == lResult) {
if (szNumber) {
szNumber[0] = _T('\0');
EXIT_ON_FALSE(0 != placAddressCaps->dwAddressSize);
// A non-zero dwAddressSize means a phone number was found
ASSERT(0 != placAddressCaps->dwAddressOffset);
PWCHAR tsAddress = (WCHAR*)(((BYTE*)placAddressCaps)+placAddressCaps->dwAddressOffset);
StringCchCopy(szNumber, cchNumber, tsAddress);
}
// Record the allowed forwarding modes
if (pdwCallFwdModes) {
*pdwCallFwdModes = placAddressCaps->dwForwardModes;
}
hr = S_OK;
}
delete[] pCapBuf;
} // End if ()
FuncExit:
lineShutdown(hLineApp);
//TODO: log extended error
if (hr != S_OK)
LOG(ERROR) + "failed to get phone number";
return hr;
#undef EXIT_ON_NULL
#undef EXIT_ON_FALSE
#undef MAX
}
#endif //OS_WINCE
VALUE phone_number()
{
TCHAR number[512];
#ifdef OS_WINCE
if (SHReadLineAddressCaps(number, sizeof(number), NULL, 1) == S_OK)
return rho_ruby_create_string(convertToStringA(number).c_str());
#endif
return rho_ruby_get_NIL();
}
static int has_camera()
{
#ifdef OS_WINCE
DEVMGR_DEVICE_INFORMATION devInfo = {0};
GUID guidCamera = { 0xCB998A05, 0x122C, 0x4166, 0x84, 0x6A, 0x93,
0x3E, 0x4D, 0x7E, 0x3C, 0x86 };
devInfo.dwSize = sizeof(devInfo);
HANDLE hDevice = FindFirstDevice( DeviceSearchByGuid, &guidCamera, &devInfo);
if ( hDevice != INVALID_HANDLE_VALUE )
{
FindClose(hDevice);
return 1;
}
return 0;
#else
return 0;
#endif
}
VALUE rho_sysimpl_get_property(char* szPropName)
{
if (strcasecmp("has_camera",szPropName) == 0)
return rho_ruby_create_boolean(has_camera());
if (strcasecmp("phone_number",szPropName) == 0)
return phone_number();
return 0;
}
VALUE rho_sys_get_locale()
{
wchar_t szLang[20];
int nRes = GetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_SABBREVLANGNAME , szLang, 20);
szLang[2] = 0;
wcslwr(szLang);
return rho_ruby_create_string(convertToStringA(szLang).c_str());
}
int rho_sys_get_screen_width()
{
#ifdef _WIN32_WCE
return GetSystemMetrics(SM_CXSCREEN);
#else
return CMainWindow::getScreenWidth();
#endif
}
int rho_sys_get_screen_height()
{
#ifdef _WIN32_WCE
return GetSystemMetrics(SM_CYSCREEN);
#else
return CMainWindow::getScreenHeight();
#endif
}
VALUE rho_sys_makephonecall(const char* callname, int nparams, char** param_names, char** param_values)
{
return rho_ruby_get_NIL();
}
static int g_rho_has_network = 1;
void rho_sysimpl_sethas_network(int nValue)
{
g_rho_has_network = nValue;
}
VALUE rho_sys_has_network()
{
return rho_ruby_create_boolean(g_rho_has_network!=0);
}
}<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "mtac/Loop.hpp"
#include "mtac/basic_block.hpp"
using namespace eddic;
mtac::Loop::Loop(const std::set<mtac::basic_block_p>& blocks) : m_blocks(blocks) {
//Nothing
}
mtac::Loop::iterator mtac::Loop::begin(){
return m_blocks.begin();
}
mtac::Loop::iterator mtac::Loop::end(){
return m_blocks.begin();
}
int mtac::Loop::estimate(){
return m_estimate;
}
void mtac::Loop::set_estimate(int estimate){
this->m_estimate = estimate;
}
mtac::Loop::iterator mtac::begin(std::shared_ptr<mtac::Loop> loop){
return loop->end();
}
mtac::Loop::iterator mtac::end(std::shared_ptr<mtac::Loop> loop){
return loop->begin();
}
std::set<mtac::basic_block_p>& mtac::Loop::blocks(){
return m_blocks;
}
<commit_msg>Fix iteration through loop bb<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "mtac/Loop.hpp"
#include "mtac/basic_block.hpp"
using namespace eddic;
mtac::Loop::Loop(const std::set<mtac::basic_block_p>& blocks) : m_blocks(blocks) {
//Nothing
}
mtac::Loop::iterator mtac::Loop::begin(){
return m_blocks.begin();
}
mtac::Loop::iterator mtac::Loop::end(){
return m_blocks.end();
}
int mtac::Loop::estimate(){
return m_estimate;
}
void mtac::Loop::set_estimate(int estimate){
this->m_estimate = estimate;
}
mtac::Loop::iterator mtac::begin(std::shared_ptr<mtac::Loop> loop){
return loop->begin();
}
mtac::Loop::iterator mtac::end(std::shared_ptr<mtac::Loop> loop){
return loop->end();
}
std::set<mtac::basic_block_p>& mtac::Loop::blocks(){
return m_blocks;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "multivalue.h"
#include "exception.h"
#include "length.h"
#include <assert.h>
void
StringList::unserialise(const std::string& serialised)
{
const char* ptr = serialised.data();
const char* end = serialised.data() + serialised.size();
unserialise(&ptr, end);
}
void
StringList::unserialise(const char** ptr, const char* end)
{
ssize_t length;
const char* pos = *ptr;
clear();
try {
length = unserialise_length(&pos, end, true);
} catch(Xapian::SerialisationError) {
length = -1;
}
if (length == -1 || length != end - pos) {
push_back(std::string(pos, end - pos));
} else {
while (pos != end) {
length = unserialise_length(&pos, end, true);
push_back(std::string(pos, length));
pos += length;
}
}
*ptr = pos;
}
std::string
StringList::serialise() const
{
std::string serialised, values;
StringList::const_iterator i(begin());
if (size() > 1) {
for ( ; i != end(); ++i) {
values.append(serialise_length((*i).size()));
values.append(*i);
}
serialised.append(serialise_length(values.size()));
} else if (i != end()) {
values.assign(*i);
}
serialised.append(values);
return serialised;
}
void
MultiValueCountMatchSpy::operator()(const Xapian::Document &doc, double)
{
assert(internal.get());
++(internal->total);
StringList list;
list.unserialise(doc.get_value(internal->slot));
if (is_geo) {
for (auto i = list.begin(); i != list.end(); ++i) {
if (!i->empty()) {
StringList s;
s.push_back(*i);
s.push_back(*(++i));
++(internal->values[s.serialise()]);
}
}
} else {
for (auto i = list.begin(); i != list.end(); ++i) {
if (!i->empty()) ++(internal->values[*i]);
}
}
}
Xapian::MatchSpy*
MultiValueCountMatchSpy::clone() const
{
assert(internal.get());
return new MultiValueCountMatchSpy(internal->slot);
}
std::string
MultiValueCountMatchSpy::name() const
{
return "Xapian::MultiValueCountMatchSpy";
}
std::string
MultiValueCountMatchSpy::serialise() const
{
assert(internal.get());
std::string result;
result += serialise_length(internal->slot);
return result;
}
Xapian::MatchSpy*
MultiValueCountMatchSpy::unserialise(const std::string& s, const Xapian::Registry&) const
{
const char* p = s.data();
const char* end = p + s.size();
Xapian::valueno new_slot = (Xapian::valueno)unserialise_length(&p, end, false);
if (new_slot == Xapian::BAD_VALUENO) {
throw MSG_NetworkError("Decoding error of serialised MultiValueCountMatchSpy");
}
if (p != end) {
throw MSG_NetworkError("Junk at end of serialised MultiValueCountMatchSpy");
}
return new MultiValueCountMatchSpy(new_slot);
}
std::string
MultiValueCountMatchSpy::get_description() const
{
char buffer[20];
std::string d("MultiValueCountMatchSpy(");
if (internal.get()) {
snprintf(buffer, sizeof(buffer), "%u", internal->total);
d += buffer;
d += " docs seen, looking in ";
snprintf(buffer, sizeof(buffer), "%lu", internal->values.size());
d += buffer;
d += " slots)";
} else {
d += ")";
}
return d;
}
<commit_msg>Improve unserialise list<commit_after>/*
* Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "multivalue.h"
#include "exception.h"
#include "length.h"
#include <assert.h>
void
StringList::unserialise(const std::string& serialised)
{
const char* ptr = serialised.data();
const char* end = serialised.data() + serialised.size();
unserialise(&ptr, end);
}
void
StringList::unserialise(const char** ptr, const char* end)
{
ssize_t length = -1;
const char* pos = *ptr;
clear();
if (!*pos++) {
try {
length = unserialise_length(&pos, end, true);
reserve(length);
while (pos != end) {
length = unserialise_length(&pos, end, true);
push_back(std::string(pos, length));
pos += length;
}
} catch(Xapian::SerialisationError) {
length = -1;
}
}
if (length == -1) {
pos = *ptr;
push_back(std::string(pos, end - pos));
}
*ptr = pos;
}
std::string
StringList::serialise() const
{
std::string serialised, values("\0");
values.append(serialise_length(size()));
StringList::const_iterator i(begin());
if (size() > 1) {
for ( ; i != end(); ++i) {
values.append(serialise_length((*i).size()));
values.append(*i);
}
serialised.append(serialise_length(values.size()));
} else if (i != end()) {
values.assign(*i);
}
serialised.append(values);
return serialised;
}
void
MultiValueCountMatchSpy::operator()(const Xapian::Document &doc, double)
{
assert(internal.get());
++(internal->total);
StringList list;
list.unserialise(doc.get_value(internal->slot));
if (is_geo) {
for (auto i = list.begin(); i != list.end(); ++i) {
if (!i->empty()) {
StringList s;
s.push_back(*i);
s.push_back(*(++i));
++(internal->values[s.serialise()]);
}
}
} else {
for (auto i = list.begin(); i != list.end(); ++i) {
if (!i->empty()) ++(internal->values[*i]);
}
}
}
Xapian::MatchSpy*
MultiValueCountMatchSpy::clone() const
{
assert(internal.get());
return new MultiValueCountMatchSpy(internal->slot);
}
std::string
MultiValueCountMatchSpy::name() const
{
return "Xapian::MultiValueCountMatchSpy";
}
std::string
MultiValueCountMatchSpy::serialise() const
{
assert(internal.get());
std::string result;
result += serialise_length(internal->slot);
return result;
}
Xapian::MatchSpy*
MultiValueCountMatchSpy::unserialise(const std::string& s, const Xapian::Registry&) const
{
const char* p = s.data();
const char* end = p + s.size();
Xapian::valueno new_slot = (Xapian::valueno)unserialise_length(&p, end, false);
if (new_slot == Xapian::BAD_VALUENO) {
throw MSG_NetworkError("Decoding error of serialised MultiValueCountMatchSpy");
}
if (p != end) {
throw MSG_NetworkError("Junk at end of serialised MultiValueCountMatchSpy");
}
return new MultiValueCountMatchSpy(new_slot);
}
std::string
MultiValueCountMatchSpy::get_description() const
{
char buffer[20];
std::string d("MultiValueCountMatchSpy(");
if (internal.get()) {
snprintf(buffer, sizeof(buffer), "%u", internal->total);
d += buffer;
d += " docs seen, looking in ";
snprintf(buffer, sizeof(buffer), "%lu", internal->values.size());
d += buffer;
d += " slots)";
} else {
d += ")";
}
return d;
}
<|endoftext|> |
<commit_before>/**
* @copyright Copyright (c) 2014, J-PET collaboration
* @file JPetManager.cp
* @author Wojciech Krzemien, wojciech.krzemien@if.uj.edu.pl
*/
#include "./JPetManager.h"
#include <cassert>
#include <ctime>
#include <string>
#include "../../JPetLoggerInclude.h"
#include "../JPetScopeModule/JPetScopeModule.h"
//ClassImp(JPetManager);
JPetManager& JPetManager::GetManager()
{
static JPetManager instance;
return instance;
}
JPetManager::JPetManager(): TNamed("JPetMainManager", "JPetMainManager"), fIsProgressBarEnabled(false)
{
}
// adds the given analysis module to a list of registered task
// @todo check if the module is not already registered
void JPetManager::AddTask(JPetAnalysisModule* mod)
{
assert(mod);
fTasks.push_back(mod);
}
void JPetManager::Run()
{
// write to log about starting
INFO( "========== Starting processing tasks: " + GetTimeString() + " ==========" );
if (fCmdParser.IsFileTypeSet()) {
if (fCmdParser.getFileType() == "scope") {
JPetScopeModule* module = new JPetScopeModule("JPetScopeModule", "Process Oscilloscope ASCII data into JPetLOR structures.");
module->setFileName(getInputFileName().c_str());
fTasks.push_front(module);
} else if (fCmdParser.getFileType() == "hld"){
UnpackFile();
}
}
JPetWriter* currentWriter = 0;
std::list<JPetAnalysisModule*>::iterator taskIter;
// pseudo-input container
long long kNevent = 0;
long long kFirstEvent = 0;
long long kLastEvent = 0;
for (taskIter = fTasks.begin(); taskIter != fTasks.end(); taskIter++) {
(*taskIter)->createInputObjects( getInputFileName().c_str() ); /// readers
(*taskIter)->createOutputObjects( getInputFileName().c_str() ); /// writers + histograms
kNevent = (*taskIter)->getEventNb();
kFirstEvent = 0;
kLastEvent = kNevent-1;
// handle the user-provided range of events to process,
// but only for the first module to process
if( taskIter==fTasks.begin() ){// only for first module
if( fCmdParser.getLowerEventBound() != -1 &&
fCmdParser.getHigherEventBound() != -1 &&
fCmdParser.getHigherEventBound() < kNevent){ // only if user provided reasonable bounds
kFirstEvent = fCmdParser.getLowerEventBound();
kLastEvent = fCmdParser.getHigherEventBound();
kNevent = kLastEvent - kFirstEvent + 1;
}
}
for (long long i = 0; i <= kLastEvent; i++) {
if(fIsProgressBarEnabled)
{
std::cout << "Progressbar: " << setProgressBar(i, kNevent) << " %" << std::endl;
}
(*taskIter)->exec();
}
(*taskIter)->terminate();
}
INFO( "======== Finished processing all tasks: " + GetTimeString() + " ========\n" );
}
void JPetManager::ParseCmdLine(int argc, char** argv)
{
fCmdParser.parse(argc, (const char**)argv);
if (fCmdParser.isRunNumberSet()) { /// we should connect to the database
fParamManager.getParametersFromDatabase(fCmdParser.getRunNumber()); /// @todo some error handling
}
if (fCmdParser.IsFileTypeSet()) {
if (fCmdParser.getFileType() == "hld") {
fUnpacker.setParams(fCmdParser.getFileName().c_str());
}
}
if (fCmdParser.isProgressBarSet()) {
fIsProgressBarEnabled = true;
}
}
int JPetManager::getRunNumber() const
{
if (fCmdParser.isRunNumberSet()) {
return fCmdParser.getRunNumber();
}
return -1;
}
JPetManager::~JPetManager()
{
std::list<JPetAnalysisModule*>::iterator taskIter;
for (taskIter = fTasks.begin(); taskIter != fTasks.end(); taskIter++) {
delete (*taskIter);
*taskIter = 0;
}
}
/**
* @brief Get Input File name stripped off the extension and the suffixes like .tslot.* or .phys.*
*
* Example: if the file given on command line was ../file.phys.hit.root, this method will return ../file
*/
std::string JPetManager::getInputFileName() const
{
std::string name = fCmdParser.getFileName().c_str();
// strip suffixes of type .tslot.* and .phys.*
int pos = name.find(".tslot");
if ( pos == std::string::npos ) {
pos = name.find(".phys");
}
if ( pos == std::string::npos ) {
pos = name.find(".hld");
}
if ( pos == std::string::npos ) {
pos = name.find(".root");
}
if ( pos != std::string::npos ) {
name.erase( pos );
}
return name;
}
/**
* @brief returns the time TString in the format dd.mm.yyyy HH:MM
*/
TString JPetManager::GetTimeString() const
{
time_t _tm = time(NULL );
struct tm* curtime = localtime ( &_tm );
char buf[100];
strftime( buf, 100, "%d.%m.%Y %R", curtime);
return TString( buf );
}
float JPetManager::setProgressBar(int currentEventNumber, int numberOfEvents)
{
return ( ((float)currentEventNumber) / numberOfEvents ) * 100;
}
<commit_msg>Fixed a bug in the user-defined events range.<commit_after>/**
* @copyright Copyright (c) 2014, J-PET collaboration
* @file JPetManager.cp
* @author Wojciech Krzemien, wojciech.krzemien@if.uj.edu.pl
*/
#include "./JPetManager.h"
#include <cassert>
#include <ctime>
#include <string>
#include "../../JPetLoggerInclude.h"
#include "../JPetScopeModule/JPetScopeModule.h"
//ClassImp(JPetManager);
JPetManager& JPetManager::GetManager()
{
static JPetManager instance;
return instance;
}
JPetManager::JPetManager(): TNamed("JPetMainManager", "JPetMainManager"), fIsProgressBarEnabled(false)
{
}
// adds the given analysis module to a list of registered task
// @todo check if the module is not already registered
void JPetManager::AddTask(JPetAnalysisModule* mod)
{
assert(mod);
fTasks.push_back(mod);
}
void JPetManager::Run()
{
// write to log about starting
INFO( "========== Starting processing tasks: " + GetTimeString() + " ==========" );
if (fCmdParser.IsFileTypeSet()) {
if (fCmdParser.getFileType() == "scope") {
JPetScopeModule* module = new JPetScopeModule("JPetScopeModule", "Process Oscilloscope ASCII data into JPetLOR structures.");
module->setFileName(getInputFileName().c_str());
fTasks.push_front(module);
} else if (fCmdParser.getFileType() == "hld"){
UnpackFile();
}
}
JPetWriter* currentWriter = 0;
std::list<JPetAnalysisModule*>::iterator taskIter;
// pseudo-input container
long long kNevent = 0;
long long kFirstEvent = 0;
long long kLastEvent = 0;
for (taskIter = fTasks.begin(); taskIter != fTasks.end(); taskIter++) {
(*taskIter)->createInputObjects( getInputFileName().c_str() ); /// readers
(*taskIter)->createOutputObjects( getInputFileName().c_str() ); /// writers + histograms
kNevent = (*taskIter)->getEventNb();
kFirstEvent = 0;
kLastEvent = kNevent-1;
// handle the user-provided range of events to process,
// but only for the first module to process
if( taskIter==fTasks.begin() ){// only for first module
if( fCmdParser.getLowerEventBound() != -1 &&
fCmdParser.getHigherEventBound() != -1 &&
fCmdParser.getHigherEventBound() < kNevent){ // only if user provided reasonable bounds
kFirstEvent = fCmdParser.getLowerEventBound();
kLastEvent = fCmdParser.getHigherEventBound();
kNevent = kLastEvent - kFirstEvent + 1;
}
}
for (long long i = kFirstEvent; i <= kLastEvent; i++) {
if(fIsProgressBarEnabled)
{
std::cout << "Progressbar: " << setProgressBar(i, kNevent) << " %" << std::endl;
}
(*taskIter)->exec();
}
(*taskIter)->terminate();
}
INFO( "======== Finished processing all tasks: " + GetTimeString() + " ========\n" );
}
void JPetManager::ParseCmdLine(int argc, char** argv)
{
fCmdParser.parse(argc, (const char**)argv);
if (fCmdParser.isRunNumberSet()) { /// we should connect to the database
fParamManager.getParametersFromDatabase(fCmdParser.getRunNumber()); /// @todo some error handling
}
if (fCmdParser.IsFileTypeSet()) {
if (fCmdParser.getFileType() == "hld") {
fUnpacker.setParams(fCmdParser.getFileName().c_str());
}
}
if (fCmdParser.isProgressBarSet()) {
fIsProgressBarEnabled = true;
}
}
int JPetManager::getRunNumber() const
{
if (fCmdParser.isRunNumberSet()) {
return fCmdParser.getRunNumber();
}
return -1;
}
JPetManager::~JPetManager()
{
std::list<JPetAnalysisModule*>::iterator taskIter;
for (taskIter = fTasks.begin(); taskIter != fTasks.end(); taskIter++) {
delete (*taskIter);
*taskIter = 0;
}
}
/**
* @brief Get Input File name stripped off the extension and the suffixes like .tslot.* or .phys.*
*
* Example: if the file given on command line was ../file.phys.hit.root, this method will return ../file
*/
std::string JPetManager::getInputFileName() const
{
std::string name = fCmdParser.getFileName().c_str();
// strip suffixes of type .tslot.* and .phys.*
int pos = name.find(".tslot");
if ( pos == std::string::npos ) {
pos = name.find(".phys");
}
if ( pos == std::string::npos ) {
pos = name.find(".hld");
}
if ( pos == std::string::npos ) {
pos = name.find(".root");
}
if ( pos != std::string::npos ) {
name.erase( pos );
}
return name;
}
/**
* @brief returns the time TString in the format dd.mm.yyyy HH:MM
*/
TString JPetManager::GetTimeString() const
{
time_t _tm = time(NULL );
struct tm* curtime = localtime ( &_tm );
char buf[100];
strftime( buf, 100, "%d.%m.%Y %R", curtime);
return TString( buf );
}
float JPetManager::setProgressBar(int currentEventNumber, int numberOfEvents)
{
return ( ((float)currentEventNumber) / numberOfEvents ) * 100;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* Copyright (c) 2009-2014, MAV'RIC Development Team
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
/*******************************************************************************
* \file mavrinux.hpp
*
* \author MAV'RIC Team
*
* \brief Emulated board running on linux
*
******************************************************************************/
#ifndef MAVRINUX_HPP_
#define MAVRINUX_HPP_
#include "imu.hpp"
#include "gpio_dummy.hpp"
#include "serial_dummy.hpp"
#include "spektrum_satellite.hpp"
#include "simulation.hpp"
#include "dynamic_model_quad_diag.hpp"
#include "serial_linux_io.hpp"
#include "serial_udp.hpp"
#include "file_linux.hpp"
#include "adc_dummy.hpp"
#include "battery.hpp"
#include "Pwm_servos_dummy.hpp"
extern "C"
{
#include "streams.h"
#include "servos.h"
}
/**
* \brief Configuration structure
*/
typedef struct
{
imu_conf_t imu_config;
serial_udp_conf_t serial_udp_config;
std::string flash_filename;
} mavrinux_conf_t;
/**
* \brief Default configuration for the board
*
* \return Config structure
*/
static inline mavrinux_conf_t mavrinux_default_config();
/**
* \brief Emulated board running on linux
*
*/
class Mavrinux
{
public:
/**
* \brief Constructor
*
* \param config Board configuration
*/
Mavrinux( mavrinux_conf_t config = mavrinux_default_config() );
/**
* \brief Hardware initialisation
*
* \return Success
*/
bool init(void);
/**
* Public Members
*/
servos_t servos;
Dynamic_model_quad_diag dynamic_model;
Simulation sim;
Imu imu;
Adc_dummy adc_battery;
Battery battery;
Gpio_dummy dsm_receiver_pin;
Gpio_dummy dsm_power_pin;
Serial_dummy dsm_serial;
Spektrum_satellite spektrum_satellite;
Serial_udp mavlink_serial;
Serial_linux_io debug_serial;
File_linux file_flash;
Pwm_servos_dummy pwm_servos;
private:
byte_stream_t dbg_stream_; ///< Temporary member to make print_util work TODO: remove
};
/**
* \brief Default configuration for the board
*
* \return Config structure
*/
static inline mavrinux_conf_t mavrinux_default_config()
{
mavrinux_conf_t conf = {};
// -------------------------------------------------------------------------
// Imu config
// -------------------------------------------------------------------------
conf.imu_config = imu_default_config();
// -------------------------------------------------------------------------
// UDP config
// -------------------------------------------------------------------------
conf.serial_udp_config = serial_udp_default_config();
// -------------------------------------------------------------------------
// Flash config
// -------------------------------------------------------------------------
conf.flash_filename = "flash000.bin";
return conf;
}
#endif /* MAVRINUX_HPP_ */
<commit_msg>Misspelling correction<commit_after>/*******************************************************************************
* Copyright (c) 2009-2014, MAV'RIC Development Team
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
/*******************************************************************************
* \file mavrinux.hpp
*
* \author MAV'RIC Team
*
* \brief Emulated board running on linux
*
******************************************************************************/
#ifndef MAVRINUX_HPP_
#define MAVRINUX_HPP_
#include "imu.hpp"
#include "gpio_dummy.hpp"
#include "serial_dummy.hpp"
#include "spektrum_satellite.hpp"
#include "simulation.hpp"
#include "dynamic_model_quad_diag.hpp"
#include "serial_linux_io.hpp"
#include "serial_udp.hpp"
#include "file_linux.hpp"
#include "adc_dummy.hpp"
#include "battery.hpp"
#include "pwm_servos_dummy.hpp"
extern "C"
{
#include "streams.h"
#include "servos.h"
}
/**
* \brief Configuration structure
*/
typedef struct
{
imu_conf_t imu_config;
serial_udp_conf_t serial_udp_config;
std::string flash_filename;
} mavrinux_conf_t;
/**
* \brief Default configuration for the board
*
* \return Config structure
*/
static inline mavrinux_conf_t mavrinux_default_config();
/**
* \brief Emulated board running on linux
*
*/
class Mavrinux
{
public:
/**
* \brief Constructor
*
* \param config Board configuration
*/
Mavrinux( mavrinux_conf_t config = mavrinux_default_config() );
/**
* \brief Hardware initialisation
*
* \return Success
*/
bool init(void);
/**
* Public Members
*/
servos_t servos;
Dynamic_model_quad_diag dynamic_model;
Simulation sim;
Imu imu;
Adc_dummy adc_battery;
Battery battery;
Gpio_dummy dsm_receiver_pin;
Gpio_dummy dsm_power_pin;
Serial_dummy dsm_serial;
Spektrum_satellite spektrum_satellite;
Serial_udp mavlink_serial;
Serial_linux_io debug_serial;
File_linux file_flash;
Pwm_servos_dummy pwm_servos;
private:
byte_stream_t dbg_stream_; ///< Temporary member to make print_util work TODO: remove
};
/**
* \brief Default configuration for the board
*
* \return Config structure
*/
static inline mavrinux_conf_t mavrinux_default_config()
{
mavrinux_conf_t conf = {};
// -------------------------------------------------------------------------
// Imu config
// -------------------------------------------------------------------------
conf.imu_config = imu_default_config();
// -------------------------------------------------------------------------
// UDP config
// -------------------------------------------------------------------------
conf.serial_udp_config = serial_udp_default_config();
// -------------------------------------------------------------------------
// Flash config
// -------------------------------------------------------------------------
conf.flash_filename = "flash000.bin";
return conf;
}
#endif /* MAVRINUX_HPP_ */
<|endoftext|> |
<commit_before>#include "command.hh"
#include "serve-protocol.hh"
#include "shared.hh"
#include "store-api.hh"
#include "worker-protocol.hh"
using namespace nix;
std::string formatProtocol(unsigned int proto)
{
if (proto) {
auto major = GET_PROTOCOL_MAJOR(proto) >> 8;
auto minor = GET_PROTOCOL_MINOR(proto);
return (format("%1%.%2%") % major % minor).str();
}
return "unknown";
}
struct CmdDoctor : StoreCommand
{
std::string name() override
{
return "doctor";
}
std::string description() override
{
return "check your system for potential problems";
}
void run(ref<Store> store) override
{
std::cout << "Store uri: " << store->getUri() << std::endl;
std::cout << std::endl;
auto type = getStoreType();
if (type < tOther) {
checkNixInPath();
checkProfileRoots(store);
}
checkStoreProtocol(store->getProtocol());
}
void checkNixInPath() {
PathSet dirs;
for (auto & dir : tokenizeString<Strings>(getEnv("PATH"), ":"))
if (pathExists(dir + "/nix-env"))
dirs.insert(dirOf(canonPath(dir + "/nix-env", true)));
if (dirs.size() != 1) {
std::cout << "Warning: multiple versions of nix found in PATH." << std::endl;
std::cout << std::endl;
for (auto & dir : dirs)
std::cout << " " << dir << std::endl;
std::cout << std::endl;
}
}
void checkProfileRoots(ref<Store> store) {
PathSet dirs;
Roots roots = store->findRoots();
for (auto & dir : tokenizeString<Strings>(getEnv("PATH"), ":"))
try {
auto profileDir = canonPath(dirOf(dir), true);
if (hasSuffix(profileDir, "user-environment") &&
store->isValidPath(profileDir)) {
PathSet referrers;
store->computeFSClosure({profileDir}, referrers, true,
settings.gcKeepOutputs, settings.gcKeepDerivations);
bool found = false;
for (auto & i : roots)
if (referrers.find(i.second) != referrers.end())
found = true;
if (!found)
dirs.insert(dir);
}
} catch (SysError &) {}
if (!dirs.empty()) {
std::cout << "Warning: found profiles without a gcroot." << std::endl;
std::cout << "The generation this profile points to will be deleted with the next gc, resulting" << std::endl;
std::cout << "in broken symlinks. Make sure your profiles are in " << settings.nixStateDir << "/profiles." << std::endl;
std::cout << std::endl;
for (auto & dir : dirs)
std::cout << " " << dir << std::endl;
std::cout << std::endl;
}
}
void checkStoreProtocol(unsigned int storeProto) {
auto clientProto = GET_PROTOCOL_MAJOR(SERVE_PROTOCOL_VERSION) == GET_PROTOCOL_MAJOR(storeProto)
? SERVE_PROTOCOL_VERSION
: PROTOCOL_VERSION;
if (clientProto != storeProto) {
std::cout << "Warning: protocol version of this client does not match the store." << std::endl;
std::cout << "While this is not necessarily a problem it's recommended to keep the client in" << std::endl;
std::cout << "sync with the daemon." << std::endl;
std::cout << std::endl;
std::cout << "Client protocol: " << formatProtocol(clientProto) << std::endl;
std::cout << "Store protocol: " << formatProtocol(storeProto) << std::endl;
std::cout << std::endl;
}
}
};
static RegisterCommand r1(make_ref<CmdDoctor>());
<commit_msg>nix doctor: reimplement profile warning without gcroot check<commit_after>#include "command.hh"
#include "serve-protocol.hh"
#include "shared.hh"
#include "store-api.hh"
#include "worker-protocol.hh"
using namespace nix;
std::string formatProtocol(unsigned int proto)
{
if (proto) {
auto major = GET_PROTOCOL_MAJOR(proto) >> 8;
auto minor = GET_PROTOCOL_MINOR(proto);
return (format("%1%.%2%") % major % minor).str();
}
return "unknown";
}
struct CmdDoctor : StoreCommand
{
std::string name() override
{
return "doctor";
}
std::string description() override
{
return "check your system for potential problems";
}
void run(ref<Store> store) override
{
std::cout << "Store uri: " << store->getUri() << std::endl;
std::cout << std::endl;
auto type = getStoreType();
if (type < tOther) {
checkNixInPath();
checkProfileRoots(store);
}
checkStoreProtocol(store->getProtocol());
}
void checkNixInPath() {
PathSet dirs;
for (auto & dir : tokenizeString<Strings>(getEnv("PATH"), ":"))
if (pathExists(dir + "/nix-env"))
dirs.insert(dirOf(canonPath(dir + "/nix-env", true)));
if (dirs.size() != 1) {
std::cout << "Warning: multiple versions of nix found in PATH." << std::endl;
std::cout << std::endl;
for (auto & dir : dirs)
std::cout << " " << dir << std::endl;
std::cout << std::endl;
}
}
void checkProfileRoots(ref<Store> store) {
PathSet dirs;
for (auto & dir : tokenizeString<Strings>(getEnv("PATH"), ":")) {
Path profileDir = dirOf(dir);
try {
Path userEnv = canonPath(profileDir, true);
if (store->isStorePath(userEnv) && hasSuffix(userEnv, "user-environment")) {
while (profileDir.find("/profiles/") == std::string::npos && isLink(profileDir))
profileDir = absPath(readLink(profileDir), dirOf(profileDir));
if (profileDir.find("/profiles/") == std::string::npos)
dirs.insert(dir);
}
} catch (SysError &) {}
}
if (!dirs.empty()) {
std::cout << "Warning: found profiles outside of " << settings.nixStateDir << "/profiles." << std::endl;
std::cout << "The generation this profile points to might not have a gcroot and could be" << std::endl;
std::cout << "garbage collected, resulting in broken symlinks." << std::endl;
std::cout << std::endl;
for (auto & dir : dirs)
std::cout << " " << dir << std::endl;
std::cout << std::endl;
}
}
void checkStoreProtocol(unsigned int storeProto) {
auto clientProto = GET_PROTOCOL_MAJOR(SERVE_PROTOCOL_VERSION) == GET_PROTOCOL_MAJOR(storeProto)
? SERVE_PROTOCOL_VERSION
: PROTOCOL_VERSION;
if (clientProto != storeProto) {
std::cout << "Warning: protocol version of this client does not match the store." << std::endl;
std::cout << "While this is not necessarily a problem it's recommended to keep the client in" << std::endl;
std::cout << "sync with the daemon." << std::endl;
std::cout << std::endl;
std::cout << "Client protocol: " << formatProtocol(clientProto) << std::endl;
std::cout << "Store protocol: " << formatProtocol(storeProto) << std::endl;
std::cout << std::endl;
}
}
};
static RegisterCommand r1(make_ref<CmdDoctor>());
<|endoftext|> |
<commit_before>/**
* 24-hour NTP clock
* For use with a 4-digit 7-segment display and an ESP8266
* @copyright 2016 Christopher Hiller <boneskull@boneskull.com>
* @license MIT
*/
#include <ESP8266WiFi.h>
#include <NTPClient.h>
#include <Adafruit_LEDBackpack.h>
#include <Task.h>
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#define SSID "YOUR WIFI NETWORK"
#define PASS "AND ITS PASSWORD"
#define TZ -8 // your time zone offset
#define HOST "time.apple.com" // your favorite NTP server
TaskManager taskManager;
NTPClient timeClient(HOST, TZ * 3600);
Adafruit_7segment matrix = Adafruit_7segment();
/**
* Is the colon supposed to be on or off?
*/
bool colon = true;
/**
* Check this in the loop; if it differs from what NTPClient tells us
* then it's time to update the time.
*/
unsigned long prevMin = 0;
void toggleColon(uint32_t delta);
void updateTime(uint32_t delta);
void waitForConnection(uint32_t delta);
void keepConnected(uint32_t delta);
FunctionTask taskToggleColon(toggleColon, MsToTaskTime(500));
FunctionTask taskUpdateTime(updateTime, MsToTaskTime(1000));
FunctionTask taskWaitForConnection(waitForConnection, MsToTaskTime(250));
FunctionTask taskKeepConnected(keepConnected, MsToTaskTime(250));
/**
* Toggles the colon state and writes the display.
*/
void toggleColon(uint32_t delta) {
colon = !colon;
matrix.drawColon((boolean) colon);
matrix.writeDisplay();
}
/**
* Resets 7-segment display.
*/
void reset() {
matrix.clear();
colon = false;
matrix.writeDisplay();
}
/**
* Returns `true` if WiFi is offline.
*/
bool offline() {
return WiFi.status() != WL_CONNECTED;
}
/**
* Pauses normal behavior and waits until we have a WiFi connection again,
* then resumes.
*/
void waitForConnection(uint32_t delta) {
toggleColon(delta);
if (!offline()) {
Serial.println("Connected to " + String(SSID));
taskManager.StopTask(&taskWaitForConnection);
taskManager.StartTask(&taskToggleColon);
taskManager.StartTask(&taskUpdateTime);
taskManager.StartTask(&taskKeepConnected);
}
}
/**
* Connects to WiFi network. Flashes colon quickly during this phase.
*/
void keepConnected(uint32_t delta) {
if (offline()) {
taskManager.StopTask(&taskKeepConnected);
taskManager.StopTask(&taskToggleColon);
taskManager.StopTask(&taskUpdateTime);
Serial.println("Connecting to " + String(SSID));
WiFi.begin(SSID, PASS);
taskManager.StartTask(&taskWaitForConnection);
}
}
/**
* Shortcut to turn a char into an int.
*/
uint8_t charToInt(char c) {
return (uint8_t) c - '0';
}
/**
* Draws the time. Make adjustments for single-digit values.
*/
void drawTime(String hours, String minutes) {
if (hours.length() == 1) {
matrix.writeDigitRaw(0, 0);
matrix.writeDigitNum(1, charToInt(hours.charAt(0)));
} else {
matrix.writeDigitNum(0, charToInt(hours.charAt(0)));
matrix.writeDigitNum(1, charToInt(hours.charAt(1)));
}
if (minutes.length() == 1) {
matrix.writeDigitNum(3, 0);
matrix.writeDigitNum(4, charToInt(minutes.charAt(0)));
} else {
matrix.writeDigitNum(3, charToInt(minutes.charAt(0)));
matrix.writeDigitNum(4, charToInt(minutes.charAt(1)));
}
}
/**
* If a second or more has passed, ensure WiFi connectivity, then check the NTP
* client for the time. Note the client will not actually ping the host more
* than every 60s as configured.
*
* If the time's "minute" value is not equal to the current value we're
* displaying, then draw the new time and save its value.
*/
void updateTime(uint32_t delta) {
timeClient.update();
unsigned long min = (timeClient.getRawTime() % 3600) / 60;
if (min != prevMin) {
drawTime(timeClient.getHours(), timeClient.getMinutes());
Serial.println("Updating time to " + timeClient.getFormattedTime());
prevMin = min;
}
}
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"
/**
* Initializes matrix and connects to WiFi.
*/
void setup() {
Serial.begin(115200);
matrix.begin(0x70);
reset();
taskManager.StartTask(&taskToggleColon);
taskManager.StartTask(&taskUpdateTime);
taskManager.StartTask(&taskKeepConnected);
}
/**
* Flashes colon on/off every second.
* Asks the NTP client for an update every second; if the minute has changed,
* then update the display.
* Keep WiFi connection alive.
*/
void loop() {
taskManager.Loop();
}
#pragma clang diagnostic pop
#pragma clang diagnostic pop<commit_msg>probably don't need an AP<commit_after>/**
* 24-hour NTP clock
* For use with a 4-digit 7-segment display and an ESP8266
* @copyright 2016 Christopher Hiller <boneskull@boneskull.com>
* @license MIT
*/
#include <ESP8266WiFi.h>
#include <NTPClient.h>
#include <Adafruit_LEDBackpack.h>
#include <Task.h>
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#define SSID "YOUR WIFI NETWORK"
#define PASS "AND ITS PASSWORD"
#define TZ -8 // your time zone offset
#define HOST "time.apple.com" // your favorite NTP server
TaskManager taskManager;
NTPClient timeClient(HOST, TZ * 3600);
Adafruit_7segment matrix = Adafruit_7segment();
/**
* Is the colon supposed to be on or off?
*/
bool colon = true;
/**
* Check this in the loop; if it differs from what NTPClient tells us
* then it's time to update the time.
*/
unsigned long prevMin = 0;
void toggleColon(uint32_t delta);
void updateTime(uint32_t delta);
void waitForConnection(uint32_t delta);
void keepConnected(uint32_t delta);
FunctionTask taskToggleColon(toggleColon, MsToTaskTime(500));
FunctionTask taskUpdateTime(updateTime, MsToTaskTime(1000));
FunctionTask taskWaitForConnection(waitForConnection, MsToTaskTime(250));
FunctionTask taskKeepConnected(keepConnected, MsToTaskTime(250));
/**
* Toggles the colon state and writes the display.
*/
void toggleColon(uint32_t delta) {
colon = !colon;
matrix.drawColon((boolean) colon);
matrix.writeDisplay();
}
/**
* Resets 7-segment display.
*/
void reset() {
matrix.clear();
colon = false;
matrix.writeDisplay();
}
/**
* Returns `true` if WiFi is offline.
*/
bool offline() {
return WiFi.status() != WL_CONNECTED;
}
/**
* Pauses normal behavior and waits until we have a WiFi connection again,
* then resumes.
*/
void waitForConnection(uint32_t delta) {
toggleColon(delta);
if (!offline()) {
Serial.println("Connected to " + String(SSID));
taskManager.StopTask(&taskWaitForConnection);
taskManager.StartTask(&taskToggleColon);
taskManager.StartTask(&taskUpdateTime);
taskManager.StartTask(&taskKeepConnected);
}
}
/**
* Connects to WiFi network. Flashes colon quickly during this phase.
*/
void keepConnected(uint32_t delta) {
if (offline()) {
taskManager.StopTask(&taskKeepConnected);
taskManager.StopTask(&taskToggleColon);
taskManager.StopTask(&taskUpdateTime);
Serial.println("Connecting to " + String(SSID));
WiFi.begin(SSID, PASS);
taskManager.StartTask(&taskWaitForConnection);
}
}
/**
* Shortcut to turn a char into an int.
*/
uint8_t charToInt(char c) {
return (uint8_t) c - '0';
}
/**
* Draws the time. Make adjustments for single-digit values.
*/
void drawTime(String hours, String minutes) {
if (hours.length() == 1) {
matrix.writeDigitRaw(0, 0);
matrix.writeDigitNum(1, charToInt(hours.charAt(0)));
} else {
matrix.writeDigitNum(0, charToInt(hours.charAt(0)));
matrix.writeDigitNum(1, charToInt(hours.charAt(1)));
}
if (minutes.length() == 1) {
matrix.writeDigitNum(3, 0);
matrix.writeDigitNum(4, charToInt(minutes.charAt(0)));
} else {
matrix.writeDigitNum(3, charToInt(minutes.charAt(0)));
matrix.writeDigitNum(4, charToInt(minutes.charAt(1)));
}
}
/**
* If a second or more has passed, ensure WiFi connectivity, then check the NTP
* client for the time. Note the client will not actually ping the host more
* than every 60s as configured.
*
* If the time's "minute" value is not equal to the current value we're
* displaying, then draw the new time and save its value.
*/
void updateTime(uint32_t delta) {
timeClient.update();
unsigned long min = (timeClient.getRawTime() % 3600) / 60;
if (min != prevMin) {
drawTime(timeClient.getHours(), timeClient.getMinutes());
Serial.println("Updating time to " + timeClient.getFormattedTime());
prevMin = min;
}
}
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"
/**
* Initializes matrix and connects to WiFi.
*/
void setup() {
WiFi.mode(WIFI_STA);
Serial.begin(115200);
matrix.begin(0x70);
reset();
taskManager.StartTask(&taskToggleColon);
taskManager.StartTask(&taskUpdateTime);
taskManager.StartTask(&taskKeepConnected);
}
/**
* Flashes colon on/off every second.
* Asks the NTP client for an update every second; if the minute has changed,
* then update the display.
* Keep WiFi connection alive.
*/
void loop() {
taskManager.Loop();
}
#pragma clang diagnostic pop
#pragma clang diagnostic pop<|endoftext|> |
<commit_before>#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "ByteBuffer.h"
#include "wav.h"
#include "oamlAudio.h"
oamlAudio::oamlAudio(const char *audioFilename, int audioType, int audioBars, float audioBpm, int audioFadeIn, int audioFadeOut) {
buffer = NULL;
handle = NULL;
strcpy(filename, audioFilename);
type = audioType;
bars = audioBars;
bpm = audioBpm;
fadeIn = audioFadeIn;
fadeOut = audioFadeOut;
buffer = new ByteBuffer();
samplesCount = 0;
samplesPerSec = 0;
samplesToEnd = 0;
totalSamples = 0;
fadeInSamples = 0;
fadeOutSamples = 0;
condId = 0;
condType = 0;
condValue = 0;
}
oamlAudio::~oamlAudio() {
delete buffer;
}
void oamlAudio::SetCondition(int id, int type, int value) {
condId = id;
condType = type;
condValue = value;
}
bool oamlAudio::TestCondition(int id, int value) {
if (id == condId) {
if (condType == 0) {
if (value == condValue) {
return true;
}
}
}
return false;
}
int oamlAudio::Open() {
if (handle != NULL) {
buffer->setReadPos(0);
samplesCount = 0;
} else {
handle = wavOpen(filename);
if (handle == NULL) {
return -1;
}
samplesPerSec = handle->samplesPerSec * handle->channels;
bytesPerSample = handle->bitsPerSample / 8;
totalSamples = handle->chunkSize / bytesPerSample;
float secs = bars * (60.f / bpm) * 4;
samplesToEnd = secs * samplesPerSec;
}
if (fadeIn) {
fadeInSamples = (fadeIn / 1000.f) * samplesPerSec;
} else {
fadeInSamples = 0;
}
if (fadeOut) {
fadeOutSamples = (fadeOut / 1000.f) * samplesPerSec;
fadeOutStart = samplesToEnd - fadeOutSamples;
} else {
fadeOutSamples = 0;
fadeOutStart = 0;
}
return 0;
}
void oamlAudio::DoFadeIn(int msec) {
fadeInSamples = (msec / 1000.f) * samplesPerSec;
}
void oamlAudio::DoFadeOut(int msec) {
fadeOutStart = samplesCount;
fadeOutSamples = (msec / 1000.f) * samplesPerSec;
}
bool oamlAudio::HasFinished() {
return samplesCount >= samplesToEnd;
}
int oamlAudio::Read() {
return wavRead(handle, buffer, 4096*bytesPerSample);
}
int oamlAudio::Read32() {
int ret = 0;
if (buffer->bytesRemaining() < (unsigned int)bytesPerSample) {
Read();
}
ret|= ((unsigned int)buffer->get())<<8;
ret|= ((unsigned int)buffer->get())<<16;
ret|= ((unsigned int)buffer->get())<<24;
if (fadeInSamples) {
if (samplesCount < fadeInSamples) {
float gain = 1.f - float(fadeInSamples - samplesCount) / float(fadeInSamples);
gain = log10(1.f + 9.f * gain);
ret = (int)(ret * gain);
} else {
fadeInSamples = 0;
}
}
if (fadeOutSamples && samplesCount >= fadeOutStart) {
unsigned int fadeOutFinish = fadeOutStart + fadeOutSamples;
if (samplesCount < fadeOutFinish) {
float gain = float(fadeOutFinish - samplesCount) / float(fadeOutSamples);
gain = log10(1.f + 9.f * gain);
ret = (int)(ret * gain);
} else {
ret = 0;
}
}
samplesCount++;
return ret;
}
<commit_msg>Added support for 16bit wave files<commit_after>#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "ByteBuffer.h"
#include "wav.h"
#include "oamlAudio.h"
oamlAudio::oamlAudio(const char *audioFilename, int audioType, int audioBars, float audioBpm, int audioFadeIn, int audioFadeOut) {
buffer = NULL;
handle = NULL;
strcpy(filename, audioFilename);
type = audioType;
bars = audioBars;
bpm = audioBpm;
fadeIn = audioFadeIn;
fadeOut = audioFadeOut;
buffer = new ByteBuffer();
samplesCount = 0;
samplesPerSec = 0;
samplesToEnd = 0;
totalSamples = 0;
fadeInSamples = 0;
fadeOutSamples = 0;
condId = 0;
condType = 0;
condValue = 0;
}
oamlAudio::~oamlAudio() {
delete buffer;
}
void oamlAudio::SetCondition(int id, int type, int value) {
condId = id;
condType = type;
condValue = value;
}
bool oamlAudio::TestCondition(int id, int value) {
if (id == condId) {
if (condType == 0) {
if (value == condValue) {
return true;
}
}
}
return false;
}
int oamlAudio::Open() {
if (handle != NULL) {
buffer->setReadPos(0);
samplesCount = 0;
} else {
handle = wavOpen(filename);
if (handle == NULL) {
return -1;
}
samplesPerSec = handle->samplesPerSec * handle->channels;
bytesPerSample = handle->bitsPerSample / 8;
totalSamples = handle->chunkSize / bytesPerSample;
float secs = bars * (60.f / bpm) * 4;
samplesToEnd = secs * samplesPerSec;
}
if (fadeIn) {
fadeInSamples = (fadeIn / 1000.f) * samplesPerSec;
} else {
fadeInSamples = 0;
}
if (fadeOut) {
fadeOutSamples = (fadeOut / 1000.f) * samplesPerSec;
fadeOutStart = samplesToEnd - fadeOutSamples;
} else {
fadeOutSamples = 0;
fadeOutStart = 0;
}
return 0;
}
void oamlAudio::DoFadeIn(int msec) {
fadeInSamples = (msec / 1000.f) * samplesPerSec;
}
void oamlAudio::DoFadeOut(int msec) {
fadeOutStart = samplesCount;
fadeOutSamples = (msec / 1000.f) * samplesPerSec;
}
bool oamlAudio::HasFinished() {
return samplesCount >= samplesToEnd;
}
int oamlAudio::Read() {
return wavRead(handle, buffer, 4096*bytesPerSample);
}
int oamlAudio::Read32() {
int ret = 0;
if (buffer->bytesRemaining() < (unsigned int)bytesPerSample) {
Read();
}
if (bytesPerSample == 3) {
ret|= ((unsigned int)buffer->get())<<8;
ret|= ((unsigned int)buffer->get())<<16;
ret|= ((unsigned int)buffer->get())<<24;
} else if (bytesPerSample == 2) {
ret|= ((unsigned int)buffer->get())<<16;
ret|= ((unsigned int)buffer->get())<<24;
}
if (fadeInSamples) {
if (samplesCount < fadeInSamples) {
float gain = 1.f - float(fadeInSamples - samplesCount) / float(fadeInSamples);
gain = log10(1.f + 9.f * gain);
ret = (int)(ret * gain);
} else {
fadeInSamples = 0;
}
}
if (fadeOutSamples && samplesCount >= fadeOutStart) {
unsigned int fadeOutFinish = fadeOutStart + fadeOutSamples;
if (samplesCount < fadeOutFinish) {
float gain = float(fadeOutFinish - samplesCount) / float(fadeOutSamples);
gain = log10(1.f + 9.f * gain);
ret = (int)(ret * gain);
} else {
ret = 0;
}
}
samplesCount++;
return ret;
}
<|endoftext|> |
<commit_before>/**
** \file object/fwd.hh
** \brief Forward declarations of all node-classes of OBJECT
** (needed by the visitors)
*/
#ifndef OBJECT_FWD_HH
# define OBJECT_FWD_HH
# include <libport/fwd.hh>
# include <libport/intrusive-ptr.hh>
# include <libport/reserved-vector.hh>
# include <urbi/export.hh>
namespace object
{
// rObject & objects_type.
class Object;
typedef libport::intrusive_ptr<Object> rObject;
typedef libport::ReservedVector<rObject, 8> objects_type;
# define APPLY_ON_ALL_PRIMITIVES(Macro) \
APPLY_ON_ALL_PRIMITIVES_BUT_OBJECT(Macro) \
Macro(object, Object)
# define APPLY_ON_ALL_ROOT_CLASSES_BUT_OBJECT(Macro) \
Macro(global, Global)
# define APPLY_ON_ALL_ROOT_CLASSES(Macro) \
APPLY_ON_ALL_ROOT_CLASSES_BUT_OBJECT(Macro) \
Macro(object, Object)
/*
Help the generation of precompiled symbols.
SYMBOL(Call)
SYMBOL(Code)
SYMBOL(Float)
SYMBOL(Integer)
SYMBOL(List)
SYMBOL(Lobby)
SYMBOL(Object)
SYMBOL(Primitive)
SYMBOL(String)
SYMBOL(Task)
*/
# define FWD_DECL(Class) \
class Class; \
typedef libport::intrusive_ptr<Class> r ## Class \
FWD_DECL(Barrier);
FWD_DECL(Code);
FWD_DECL(Dictionary);
FWD_DECL(Directory);
FWD_DECL(Event);
FWD_DECL(Executable);
FWD_DECL(File);
FWD_DECL(Float);
FWD_DECL(List);
FWD_DECL(Lobby);
FWD_DECL(OutputStream);
FWD_DECL(Path);
FWD_DECL(Primitive);
FWD_DECL(Semaphore);
FWD_DECL(Server);
FWD_DECL(Socket);
FWD_DECL(String);
FWD_DECL(Tag);
FWD_DECL(Task);
FWD_DECL(TextOutputStream);
extern URBI_SDK_API rObject false_class;
extern URBI_SDK_API rObject nil_class;
extern URBI_SDK_API rObject true_class;
extern URBI_SDK_API rObject void_class;
} // namespace object
#endif // !OBJECT_FWD_HH
<commit_msg>fwd: macros.<commit_after>/**
** \file object/fwd.hh
** \brief Forward declarations of all node-classes of OBJECT
** (needed by the visitors)
*/
#ifndef OBJECT_FWD_HH
# define OBJECT_FWD_HH
# include <libport/fwd.hh>
# include <libport/intrusive-ptr.hh>
# include <libport/reserved-vector.hh>
# include <urbi/export.hh>
namespace object
{
// rObject & objects_type.
class Object;
typedef libport::intrusive_ptr<Object> rObject;
typedef libport::ReservedVector<rObject, 8> objects_type;
# define APPLY_ON_ALL_PRIMITIVES(Macro) \
Macro(Barrier); \
Macro(Code); \
Macro(Dictionary); \
Macro(Directory); \
Macro(Executable); \
Macro(File); \
Macro(Float); \
Macro(List); \
Macro(Lobby); \
Macro(OutputStream); \
Macro(Path); \
Macro(Primitive); \
Macro(Semaphore); \
Macro(Server); \
Macro(Socket); \
Macro(String); \
Macro(Tag); \
Macro(Task); \
Macro(TextOutputStream) \
# define APPLY_ON_ALL_OBJECTS(Macro) \
APPLY_ON_ALL_PRIMITIVES(Macro); \
Macro(Event); \
/*
Help the generation of precompiled symbols.
SYMBOL(Call)
SYMBOL(Code)
SYMBOL(Float)
SYMBOL(Integer)
SYMBOL(List)
SYMBOL(Lobby)
SYMBOL(Object)
SYMBOL(Primitive)
SYMBOL(String)
SYMBOL(Task)
*/
# define FWD_DECL(Class) \
class Class; \
typedef libport::intrusive_ptr<Class> r ## Class \
APPLY_ON_ALL_OBJECTS(FWD_DECL);
extern URBI_SDK_API rObject false_class;
extern URBI_SDK_API rObject nil_class;
extern URBI_SDK_API rObject true_class;
extern URBI_SDK_API rObject void_class;
} // namespace object
#endif // !OBJECT_FWD_HH
<|endoftext|> |
<commit_before>#include "ofxKinect.h"
#include "ofMain.h"
// pointer to this class for static callback member functions
ofxKinect* thisKinect = NULL;
//--------------------------------------------------------------------
ofxKinect::ofxKinect()
{
ofLog(OF_LOG_VERBOSE, "ofxKinect: Creating ofxKinect");
bVerbose = false;
bUseTexture = true;
// set defaults
bGrabberInited = false;
depthPixelsRaw = NULL;
depthPixelsBack = NULL;
videoPixels = NULL;
videoPixelsBack = NULL;
bNeedsUpdate = false;
bUpdateTex = false;
bIsFrameNew = false;
kinectContext = NULL;
kinectDevice = NULL;
targetTiltAngleDeg = 0;
bTiltNeedsApplying = false;
thisKinect = this;
}
//--------------------------------------------------------------------
ofxKinect::~ofxKinect(){
close();
clear();
}
//--------------------------------------------------------------------
void ofxKinect::setVerbose(bool bTalkToMe){
bVerbose = bTalkToMe;
}
//---------------------------------------------------------------------------
unsigned char * ofxKinect::getPixels(){
return videoPixels;
}
//---------------------------------------------------------------------------
unsigned char * ofxKinect::getDepthPixels(){
return calibration.getDepthPixels();
}
//---------------------------------------------------------------------------
unsigned short * ofxKinect::getRawDepthPixels(){
return depthPixelsBack;
}
//---------------------------------------------------------------------------
float* ofxKinect::getDistancePixels() {
return calibration.getDistancePixels();
}
//---------------------------------------------------------------------------
unsigned char * ofxKinect::getCalibratedRGBPixels(){
return calibration.getCalibratedRGBPixels(videoPixels);
}
//------------------------------------
ofTexture & ofxKinect::getTextureReference(){
if(!videoTex.bAllocated()){
ofLog(OF_LOG_WARNING, "ofxKinect: getTextureReference - texture is not allocated");
}
return videoTex;
}
//---------------------------------------------------------------------------
ofTexture & ofxKinect::getDepthTextureReference(){
if(!depthTex.bAllocated()){
ofLog(OF_LOG_WARNING, "ofxKinect: getDepthTextureReference - texture is not allocated");
}
return depthTex;
}
//--------------------------------------------------------------------
bool ofxKinect::isFrameNew(){
if(isThreadRunning()){
bool curIsFrameNew = bIsFrameNew;
bIsFrameNew = false;
return curIsFrameNew;
}
return false;
}
//--------------------------------------------------------------------
bool ofxKinect::open(){
if(!bGrabberInited){
ofLog(OF_LOG_WARNING, "ofxKinect: Cannot open, init not called");
return false;
}
int number_devices = freenect_num_devices(kinectContext);
if (number_devices < 1) {
ofLog(OF_LOG_ERROR, "ofxKinect: Did not find a device");
return false;
}
if (freenect_open_device(kinectContext, &kinectDevice, 0) < 0) {
ofLog(OF_LOG_ERROR, "ofxKinect: Could not open device");
return false;
}
freenect_set_user(kinectDevice, this);
freenect_set_depth_callback(kinectDevice, &grabDepthFrame);
freenect_set_video_callback(kinectDevice, &grabRgbFrame);
startThread(true, false); // blocking, not verbose
return true;
}
//---------------------------------------------------------------------------
void ofxKinect::close(){
if(isThreadRunning()){
waitForThread(true);
}
bIsFrameNew = false;
bNeedsUpdate = false;
bUpdateTex = false;
}
//---------------------------------------------------------------------------
bool ofxKinect::isConnected(){
return isThreadRunning();
}
//We update the value here - but apply it in kinect thread.
//--------------------------------------------------------------------
bool ofxKinect::setCameraTiltAngle(float angleInDegrees){
if(!bGrabberInited){
return false;
}
targetTiltAngleDeg = ofClamp(angleInDegrees,-30,30);
bTiltNeedsApplying = true;
return true;
}
//--------------------------------------------------------------------
bool ofxKinect::init(bool infrared, bool setUseTexture){
if(isConnected()){
ofLog(OF_LOG_WARNING, "ofxKinect: Do not call init while ofxKinect is running!");
return false;
}
clear();
bInfrared = infrared;
bytespp = infrared?1:3;
calibration.init(bytespp);
bUseTexture = setUseTexture;
int length = width*height;
depthPixelsRaw = new unsigned short[length];
depthPixelsBack = new unsigned short[length];
videoPixels = new unsigned char[length*bytespp];
videoPixelsBack = new unsigned char[length*bytespp];
memset(depthPixelsRaw, 0, length*sizeof(unsigned short));
memset(depthPixelsBack, 0, length*sizeof(unsigned short));
memset(videoPixels, 0, length*bytespp*sizeof(unsigned char));
memset(videoPixelsBack, 0, length*bytespp*sizeof(unsigned char));
if(bUseTexture){
depthTex.allocate(width, height, GL_LUMINANCE);
videoTex.allocate(width, height, infrared?GL_LUMINANCE:GL_RGB);
}
if (freenect_init(&kinectContext, NULL) < 0){
ofLog(OF_LOG_ERROR, "ofxKinect: freenet_init failed");
return false;
}
ofLog(OF_LOG_VERBOSE, "ofxKinect: Inited");
int number_devices = freenect_num_devices(kinectContext);
ofLog(OF_LOG_VERBOSE, "ofxKinect: Number of Devices found: " + ofToString(number_devices));
bGrabberInited = true;
return bGrabberInited;
}
//---------------------------------------------------------------------------
void ofxKinect::clear(){
if(isConnected()){
ofLog(OF_LOG_WARNING, "ofxKinect: Do not call clear while ofxKinect is running!");
return;
}
if(kinectContext != NULL){
freenect_shutdown(kinectContext);
}
if(depthPixelsRaw != NULL){
delete[] depthPixelsRaw; depthPixelsRaw = NULL;
delete[] depthPixelsBack; depthPixelsBack = NULL;
delete[] videoPixels; videoPixels = NULL;
delete[] videoPixelsBack; videoPixelsBack = NULL;
}
depthTex.clear();
videoTex.clear();
calibration.clear();
bGrabberInited = false;
}
//----------------------------------------------------------
void ofxKinect::update(){
if(!bGrabberInited){
return;
}
if (!bNeedsUpdate){
return;
} else {
bIsFrameNew = true;
bUpdateTex = true;
}
if ( this->lock() ) {
int n = width * height;
calibration.update(depthPixelsBack);
memcpy(depthPixelsRaw,depthPixelsBack,n*sizeof(short));
memcpy(videoPixels, videoPixelsBack, n * bytespp);
//we have done the update
bNeedsUpdate = false;
this->unlock();
}
if(bUseTexture){
depthTex.loadData(calibration.getDepthPixels(), width, height, GL_LUMINANCE);
videoTex.loadData(videoPixels, width, height, bInfrared?GL_LUMINANCE:GL_RGB);
bUpdateTex = false;
}
}
//------------------------------------
float ofxKinect::getDistanceAt(int x, int y) {
return calibration.getDistanceAt(x,y);
}
//------------------------------------
float ofxKinect::getDistanceAt(const ofPoint & p) {
return calibration.getDistanceAt(p);
}
//------------------------------------
ofxVec3f ofxKinect::getWorldCoordinateFor(int x, int y) {
return calibration.getWorldCoordinateFor(x,y);
}
//------------------------------------
ofColor ofxKinect::getColorAt(int x, int y) {
int index = (y * width + x) * bytespp;
ofColor c;
c.r = videoPixels[index + 0];
c.g = videoPixels[index + (bytespp-1)/2];
c.b = videoPixels[index + (bytespp-1)];
c.a = 255;
return c;
}
//------------------------------------
ofColor ofxKinect::getColorAt(const ofPoint & p) {
return getColorAt(p.x, p.y);
}
//------------------------------------
ofColor ofxKinect::getCalibratedColorAt(int x, int y){
return getColorAt(calibration.getCalibratedColorCoordAt(x,y));
}
//------------------------------------
ofColor ofxKinect::getCalibratedColorAt(const ofPoint & p){
return getCalibratedColorAt(calibration.getCalibratedColorCoordAt(p));
}
//------------------------------------
void ofxKinect::setUseTexture(bool bUse){
bUseTexture = bUse;
}
//----------------------------------------------------------
void ofxKinect::draw(float _x, float _y, float _w, float _h){
if(bUseTexture) {
videoTex.draw(_x, _y, _w, _h);
}
}
//----------------------------------------------------------
void ofxKinect::draw(float _x, float _y){
draw(_x, _y, (float)width, (float)height);
}
//----------------------------------------------------------
void ofxKinect::draw(const ofPoint & point){
draw(point.x, point.y);
}
//----------------------------------------------------------
void ofxKinect::drawDepth(const ofPoint & point){
drawDepth(point.x, point.y);
}
//----------------------------------------------------------
void ofxKinect::draw(const ofRectangle & rect){
draw(rect.x, rect.y, rect.width, rect.height);
}
//----------------------------------------------------------
void ofxKinect::drawDepth(const ofRectangle & rect){
drawDepth(rect.x, rect.y, rect.width, rect.height);
}
//----------------------------------------------------------
void ofxKinect::drawDepth(float _x, float _y, float _w, float _h){
if(bUseTexture) {
depthTex.draw(_x, _y, _w, _h);
}
}
//---------------------------------------------------------------------------
void ofxKinect::drawDepth(float _x, float _y){
drawDepth(_x, _y, (float)width, (float)height);
}
//----------------------------------------------------------
float ofxKinect::getHeight(){
return (float)height;
}
//---------------------------------------------------------------------------
float ofxKinect::getWidth(){
return (float)width;
}
//---------------------------------------------------------------------------
ofPoint ofxKinect::getRawAccel(){
return rawAccel;
}
//---------------------------------------------------------------------------
ofPoint ofxKinect::getMksAccel(){
return mksAccel;
}
//---------------------------------------------------------------------------
void ofxKinect::enableDepthNearValueWhite(bool bEnabled){
calibration.enableDepthNearValueWhite(bEnabled);
}
//---------------------------------------------------------------------------
bool ofxKinect::isDepthNearValueWhite(){
return calibration.isDepthNearValueWhite();
}
/* ***** PRIVATE ***** */
//---------------------------------------------------------------------------
void ofxKinect::grabDepthFrame(freenect_device *dev, void *depth, uint32_t timestamp) {
if (thisKinect->lock()) {
try {
memcpy(thisKinect->depthPixelsBack, depth, FREENECT_DEPTH_11BIT_SIZE);
thisKinect->bNeedsUpdate = true;
}
catch(...) {
ofLog(OF_LOG_ERROR, "ofxKinect: Depth memcpy failed");
}
thisKinect->unlock();
} else {
ofLog(OF_LOG_WARNING, "ofxKinect: grabDepthFrame unable to lock mutex");
}
}
//---------------------------------------------------------------------------
void ofxKinect::grabRgbFrame(freenect_device *dev, void *rgb, uint32_t timestamp) {
if (thisKinect->lock()) {
try {
memcpy(thisKinect->videoPixelsBack, rgb, thisKinect->bInfrared?FREENECT_VIDEO_IR_8BIT_SIZE:FREENECT_VIDEO_RGB_SIZE);
thisKinect->bNeedsUpdate = true;
}
catch (...) {
ofLog(OF_LOG_ERROR, "ofxKinect: Rgb memcpy failed");
}
thisKinect->unlock();
} else {
ofLog(OF_LOG_ERROR, "ofxKinect: grabRgbFrame unable to lock mutex");
}
}
//---------------------------------------------------------------------------
void ofxKinect::threadedFunction(){
freenect_set_led(kinectDevice, LED_GREEN);
freenect_set_video_format(kinectDevice, bInfrared?FREENECT_VIDEO_IR_8BIT:FREENECT_VIDEO_RGB);
freenect_set_depth_format(kinectDevice, FREENECT_DEPTH_11BIT);
ofLog(OF_LOG_VERBOSE, "ofxKinect: Connection opened");
freenect_start_depth(kinectDevice);
freenect_start_video(kinectDevice);
while(isThreadRunning()){
if(bTiltNeedsApplying){
freenect_set_tilt_degs(kinectDevice, targetTiltAngleDeg);
bTiltNeedsApplying = false;
}
freenect_update_tilt_state(kinectDevice);
freenect_raw_tilt_state * tilt = freenect_get_tilt_state(kinectDevice);
rawAccel.set(tilt->accelerometer_x, tilt->accelerometer_y, tilt->accelerometer_z);
double dx,dy,dz;
freenect_get_mks_accel(tilt, &dx, &dy, &dz);
mksAccel.set(dx, dy, dz);
ofSleepMillis(10);
// printf("\r raw acceleration: %4d %4d %4d mks acceleration: %4f %4f %4f", ax, ay, az, dx, dy, dz);
}
// finish up a tilt on exit
if(bTiltNeedsApplying){
freenect_set_tilt_degs(kinectDevice, targetTiltAngleDeg);
bTiltNeedsApplying = false;
}
freenect_stop_depth(kinectDevice);
freenect_stop_video(kinectDevice);
freenect_set_led(kinectDevice, LED_YELLOW);
freenect_close_device(kinectDevice);
ofLog(OF_LOG_VERBOSE, "ofxKinect: Connection closed");
}
//---------------------------------------------------------------------------
ofxKinectCalibration& ofxKinect::getCalibration() {
return calibration;
}
<commit_msg>fixed recursive call to getCalibratedColorAt<commit_after>#include "ofxKinect.h"
#include "ofMain.h"
// pointer to this class for static callback member functions
ofxKinect* thisKinect = NULL;
//--------------------------------------------------------------------
ofxKinect::ofxKinect()
{
ofLog(OF_LOG_VERBOSE, "ofxKinect: Creating ofxKinect");
bVerbose = false;
bUseTexture = true;
// set defaults
bGrabberInited = false;
depthPixelsRaw = NULL;
depthPixelsBack = NULL;
videoPixels = NULL;
videoPixelsBack = NULL;
bNeedsUpdate = false;
bUpdateTex = false;
bIsFrameNew = false;
kinectContext = NULL;
kinectDevice = NULL;
targetTiltAngleDeg = 0;
bTiltNeedsApplying = false;
thisKinect = this;
}
//--------------------------------------------------------------------
ofxKinect::~ofxKinect(){
close();
clear();
}
//--------------------------------------------------------------------
void ofxKinect::setVerbose(bool bTalkToMe){
bVerbose = bTalkToMe;
}
//---------------------------------------------------------------------------
unsigned char * ofxKinect::getPixels(){
return videoPixels;
}
//---------------------------------------------------------------------------
unsigned char * ofxKinect::getDepthPixels(){
return calibration.getDepthPixels();
}
//---------------------------------------------------------------------------
unsigned short * ofxKinect::getRawDepthPixels(){
return depthPixelsBack;
}
//---------------------------------------------------------------------------
float* ofxKinect::getDistancePixels() {
return calibration.getDistancePixels();
}
//---------------------------------------------------------------------------
unsigned char * ofxKinect::getCalibratedRGBPixels(){
return calibration.getCalibratedRGBPixels(videoPixels);
}
//------------------------------------
ofTexture & ofxKinect::getTextureReference(){
if(!videoTex.bAllocated()){
ofLog(OF_LOG_WARNING, "ofxKinect: getTextureReference - texture is not allocated");
}
return videoTex;
}
//---------------------------------------------------------------------------
ofTexture & ofxKinect::getDepthTextureReference(){
if(!depthTex.bAllocated()){
ofLog(OF_LOG_WARNING, "ofxKinect: getDepthTextureReference - texture is not allocated");
}
return depthTex;
}
//--------------------------------------------------------------------
bool ofxKinect::isFrameNew(){
if(isThreadRunning()){
bool curIsFrameNew = bIsFrameNew;
bIsFrameNew = false;
return curIsFrameNew;
}
return false;
}
//--------------------------------------------------------------------
bool ofxKinect::open(){
if(!bGrabberInited){
ofLog(OF_LOG_WARNING, "ofxKinect: Cannot open, init not called");
return false;
}
int number_devices = freenect_num_devices(kinectContext);
if (number_devices < 1) {
ofLog(OF_LOG_ERROR, "ofxKinect: Did not find a device");
return false;
}
if (freenect_open_device(kinectContext, &kinectDevice, 0) < 0) {
ofLog(OF_LOG_ERROR, "ofxKinect: Could not open device");
return false;
}
freenect_set_user(kinectDevice, this);
freenect_set_depth_callback(kinectDevice, &grabDepthFrame);
freenect_set_video_callback(kinectDevice, &grabRgbFrame);
startThread(true, false); // blocking, not verbose
return true;
}
//---------------------------------------------------------------------------
void ofxKinect::close(){
if(isThreadRunning()){
waitForThread(true);
}
bIsFrameNew = false;
bNeedsUpdate = false;
bUpdateTex = false;
}
//---------------------------------------------------------------------------
bool ofxKinect::isConnected(){
return isThreadRunning();
}
//We update the value here - but apply it in kinect thread.
//--------------------------------------------------------------------
bool ofxKinect::setCameraTiltAngle(float angleInDegrees){
if(!bGrabberInited){
return false;
}
targetTiltAngleDeg = ofClamp(angleInDegrees,-30,30);
bTiltNeedsApplying = true;
return true;
}
//--------------------------------------------------------------------
bool ofxKinect::init(bool infrared, bool setUseTexture){
if(isConnected()){
ofLog(OF_LOG_WARNING, "ofxKinect: Do not call init while ofxKinect is running!");
return false;
}
clear();
bInfrared = infrared;
bytespp = infrared?1:3;
calibration.init(bytespp);
bUseTexture = setUseTexture;
int length = width*height;
depthPixelsRaw = new unsigned short[length];
depthPixelsBack = new unsigned short[length];
videoPixels = new unsigned char[length*bytespp];
videoPixelsBack = new unsigned char[length*bytespp];
memset(depthPixelsRaw, 0, length*sizeof(unsigned short));
memset(depthPixelsBack, 0, length*sizeof(unsigned short));
memset(videoPixels, 0, length*bytespp*sizeof(unsigned char));
memset(videoPixelsBack, 0, length*bytespp*sizeof(unsigned char));
if(bUseTexture){
depthTex.allocate(width, height, GL_LUMINANCE);
videoTex.allocate(width, height, infrared?GL_LUMINANCE:GL_RGB);
}
if (freenect_init(&kinectContext, NULL) < 0){
ofLog(OF_LOG_ERROR, "ofxKinect: freenet_init failed");
return false;
}
ofLog(OF_LOG_VERBOSE, "ofxKinect: Inited");
int number_devices = freenect_num_devices(kinectContext);
ofLog(OF_LOG_VERBOSE, "ofxKinect: Number of Devices found: " + ofToString(number_devices));
bGrabberInited = true;
return bGrabberInited;
}
//---------------------------------------------------------------------------
void ofxKinect::clear(){
if(isConnected()){
ofLog(OF_LOG_WARNING, "ofxKinect: Do not call clear while ofxKinect is running!");
return;
}
if(kinectContext != NULL){
freenect_shutdown(kinectContext);
}
if(depthPixelsRaw != NULL){
delete[] depthPixelsRaw; depthPixelsRaw = NULL;
delete[] depthPixelsBack; depthPixelsBack = NULL;
delete[] videoPixels; videoPixels = NULL;
delete[] videoPixelsBack; videoPixelsBack = NULL;
}
depthTex.clear();
videoTex.clear();
calibration.clear();
bGrabberInited = false;
}
//----------------------------------------------------------
void ofxKinect::update(){
if(!bGrabberInited){
return;
}
if (!bNeedsUpdate){
return;
} else {
bIsFrameNew = true;
bUpdateTex = true;
}
if ( this->lock() ) {
int n = width * height;
calibration.update(depthPixelsBack);
memcpy(depthPixelsRaw,depthPixelsBack,n*sizeof(short));
memcpy(videoPixels, videoPixelsBack, n * bytespp);
//we have done the update
bNeedsUpdate = false;
this->unlock();
}
if(bUseTexture){
depthTex.loadData(calibration.getDepthPixels(), width, height, GL_LUMINANCE);
videoTex.loadData(videoPixels, width, height, bInfrared?GL_LUMINANCE:GL_RGB);
bUpdateTex = false;
}
}
//------------------------------------
float ofxKinect::getDistanceAt(int x, int y) {
return calibration.getDistanceAt(x,y);
}
//------------------------------------
float ofxKinect::getDistanceAt(const ofPoint & p) {
return calibration.getDistanceAt(p);
}
//------------------------------------
ofxVec3f ofxKinect::getWorldCoordinateFor(int x, int y) {
return calibration.getWorldCoordinateFor(x,y);
}
//------------------------------------
ofColor ofxKinect::getColorAt(int x, int y) {
int index = (y * width + x) * bytespp;
ofColor c;
c.r = videoPixels[index + 0];
c.g = videoPixels[index + (bytespp-1)/2];
c.b = videoPixels[index + (bytespp-1)];
c.a = 255;
return c;
}
//------------------------------------
ofColor ofxKinect::getColorAt(const ofPoint & p) {
return getColorAt(p.x, p.y);
}
//------------------------------------
ofColor ofxKinect::getCalibratedColorAt(int x, int y){
return getColorAt(calibration.getCalibratedColorCoordAt(x,y));
}
//------------------------------------
ofColor ofxKinect::getCalibratedColorAt(const ofPoint & p){
return getColorAt(calibration.getCalibratedColorCoordAt(p));
}
//------------------------------------
void ofxKinect::setUseTexture(bool bUse){
bUseTexture = bUse;
}
//----------------------------------------------------------
void ofxKinect::draw(float _x, float _y, float _w, float _h){
if(bUseTexture) {
videoTex.draw(_x, _y, _w, _h);
}
}
//----------------------------------------------------------
void ofxKinect::draw(float _x, float _y){
draw(_x, _y, (float)width, (float)height);
}
//----------------------------------------------------------
void ofxKinect::draw(const ofPoint & point){
draw(point.x, point.y);
}
//----------------------------------------------------------
void ofxKinect::drawDepth(const ofPoint & point){
drawDepth(point.x, point.y);
}
//----------------------------------------------------------
void ofxKinect::draw(const ofRectangle & rect){
draw(rect.x, rect.y, rect.width, rect.height);
}
//----------------------------------------------------------
void ofxKinect::drawDepth(const ofRectangle & rect){
drawDepth(rect.x, rect.y, rect.width, rect.height);
}
//----------------------------------------------------------
void ofxKinect::drawDepth(float _x, float _y, float _w, float _h){
if(bUseTexture) {
depthTex.draw(_x, _y, _w, _h);
}
}
//---------------------------------------------------------------------------
void ofxKinect::drawDepth(float _x, float _y){
drawDepth(_x, _y, (float)width, (float)height);
}
//----------------------------------------------------------
float ofxKinect::getHeight(){
return (float)height;
}
//---------------------------------------------------------------------------
float ofxKinect::getWidth(){
return (float)width;
}
//---------------------------------------------------------------------------
ofPoint ofxKinect::getRawAccel(){
return rawAccel;
}
//---------------------------------------------------------------------------
ofPoint ofxKinect::getMksAccel(){
return mksAccel;
}
//---------------------------------------------------------------------------
void ofxKinect::enableDepthNearValueWhite(bool bEnabled){
calibration.enableDepthNearValueWhite(bEnabled);
}
//---------------------------------------------------------------------------
bool ofxKinect::isDepthNearValueWhite(){
return calibration.isDepthNearValueWhite();
}
/* ***** PRIVATE ***** */
//---------------------------------------------------------------------------
void ofxKinect::grabDepthFrame(freenect_device *dev, void *depth, uint32_t timestamp) {
if (thisKinect->lock()) {
try {
memcpy(thisKinect->depthPixelsBack, depth, FREENECT_DEPTH_11BIT_SIZE);
thisKinect->bNeedsUpdate = true;
}
catch(...) {
ofLog(OF_LOG_ERROR, "ofxKinect: Depth memcpy failed");
}
thisKinect->unlock();
} else {
ofLog(OF_LOG_WARNING, "ofxKinect: grabDepthFrame unable to lock mutex");
}
}
//---------------------------------------------------------------------------
void ofxKinect::grabRgbFrame(freenect_device *dev, void *rgb, uint32_t timestamp) {
if (thisKinect->lock()) {
try {
memcpy(thisKinect->videoPixelsBack, rgb, thisKinect->bInfrared?FREENECT_VIDEO_IR_8BIT_SIZE:FREENECT_VIDEO_RGB_SIZE);
thisKinect->bNeedsUpdate = true;
}
catch (...) {
ofLog(OF_LOG_ERROR, "ofxKinect: Rgb memcpy failed");
}
thisKinect->unlock();
} else {
ofLog(OF_LOG_ERROR, "ofxKinect: grabRgbFrame unable to lock mutex");
}
}
//---------------------------------------------------------------------------
void ofxKinect::threadedFunction(){
freenect_set_led(kinectDevice, LED_GREEN);
freenect_set_video_format(kinectDevice, bInfrared?FREENECT_VIDEO_IR_8BIT:FREENECT_VIDEO_RGB);
freenect_set_depth_format(kinectDevice, FREENECT_DEPTH_11BIT);
ofLog(OF_LOG_VERBOSE, "ofxKinect: Connection opened");
freenect_start_depth(kinectDevice);
freenect_start_video(kinectDevice);
while(isThreadRunning()){
if(bTiltNeedsApplying){
freenect_set_tilt_degs(kinectDevice, targetTiltAngleDeg);
bTiltNeedsApplying = false;
}
freenect_update_tilt_state(kinectDevice);
freenect_raw_tilt_state * tilt = freenect_get_tilt_state(kinectDevice);
rawAccel.set(tilt->accelerometer_x, tilt->accelerometer_y, tilt->accelerometer_z);
double dx,dy,dz;
freenect_get_mks_accel(tilt, &dx, &dy, &dz);
mksAccel.set(dx, dy, dz);
ofSleepMillis(10);
// printf("\r raw acceleration: %4d %4d %4d mks acceleration: %4f %4f %4f", ax, ay, az, dx, dy, dz);
}
// finish up a tilt on exit
if(bTiltNeedsApplying){
freenect_set_tilt_degs(kinectDevice, targetTiltAngleDeg);
bTiltNeedsApplying = false;
}
freenect_stop_depth(kinectDevice);
freenect_stop_video(kinectDevice);
freenect_set_led(kinectDevice, LED_YELLOW);
freenect_close_device(kinectDevice);
ofLog(OF_LOG_VERBOSE, "ofxKinect: Connection closed");
}
//---------------------------------------------------------------------------
ofxKinectCalibration& ofxKinect::getCalibration() {
return calibration;
}
<|endoftext|> |
<commit_before>#include "operators.hpp"
#include <cmath>
#include <iostream>
#include <map>
#include <numeric>
#include <sstream>
#include <string>
/* explicit instantiation declaration */
template float operators::sum<float> (std::vector<float> values);
template double operators::sum<double> (std::vector<double> values);
operators::operators () {
}
operators::~operators () {
}
float operators::classify_scale (const points_t& reference_points, const points_t& data_points) {
points_t points = data_points;
float scale = 1;
match_points (reference_points, points);
if (points.size () <= _minimum_ref_points || points.size () > _maximum_ref_points) {
return scale;
}
// centroid
point_t centroid_r = centroid (reference_points);
point_t centroid_p = centroid (points);
// two keypoints to use
keypoint_t ref_A = { reference_points.begin ()->first,
reference_points.begin ()->second };
// keypoint_t ref_B = {};
std::map<unsigned int, float> optimal_angle_ratios; // <point ID, ratio>
// 1.0 means a perfect 45 degrees through A
point_t diff = {};
for (auto point : reference_points) {
if (ref_A.id != point.first) {
diff.x = (point.second.x - ref_A.p.x);
diff.y = (point.second.y - ref_A.p.y);
if (diff.y != 0) {
optimal_angle_ratios.insert (
{ point.first, std::fabs (diff.x / diff.y) });
} else {
optimal_angle_ratios.insert ({ point.first, 0 });
}
}
}
// find closest to optimal_ratio
const float optimal_ratio = 1.0;
unsigned int optimal_point = optimal_angle_ratios.begin ()->first;
for (auto ratio : optimal_angle_ratios) {
optimal_point = std::fabs (ratio.second - optimal_ratio) <
std::fabs (optimal_angle_ratios.find (optimal_point)->second - optimal_ratio) ?
ratio.first :
optimal_point;
}
keypoint_t ref_B = { optimal_point, reference_points.find (optimal_point)->second };
// find intersections
point_t intersection_ref = intersections (ref_A.p, ref_B.p, centroid_r);
point_t intersection_ref_x = { intersection_ref.x, 0 };
point_t intersection_ref_y = { 0, intersection_ref.y };
// ratio of intersection
// <------->
// <--->
// A X B
// X
// calculate vector
// Y
float ratio_ref_a_x_b;
float ratio_ref_a_y_b;
// [from reference]
// find line(set of 2 points) that crosses x and y axis at some point
// make sure that this line is as close to 45 degrees to the centroid
// so that an overflow isn't bound to happen due to very large values
//
// with these points, solve Y=AX+B
// (intersection points with X and Y axis)
// where the centroid is the origin
//
// note the ratio where the intersection lays
// on the line between the two points
//
// [from data]
// using the two points and the ratio, look for the x/y intersection
// and compare the vectors from origin to intersections
// The one wit the difference can be used to calculate the scale
// (new size/old size)
//
// for reference
// pick always first point (let's call it A)
// for all points
// calculate the mean x, y difference from point A
// pick point with highest mean difference
// solve Y=AX+B
// solve Y=0
// note ratio of vectors between points
// and X=0
// note ratio of vectors between points
//
// calculate x, y location of x axis
// calculate x, y location of y axis
//
// calculate vector x axis
// calculate vector y axis
//
// line with smallest difference can be used for scale
return scale;
}
translation_t operators::classify_translation (const points_t& reference_points,
const points_t& data_points) {
translation_t translation = { 0, 0 };
points_t points = data_points;
match_points (reference_points, points);
if (points.size () <= _minimum_ref_points) {
return translation;
}
point_t centroid_reference = centroid (reference_points);
point_t centroid_points = centroid (points);
translation.x = centroid_points.x - centroid_reference.x;
translation.y = centroid_points.y - centroid_reference.y;
return translation;
}
float operators::classify_yaw (const points_t& reference_points, const points_t& data_points) {
return 0;
}
float operators::classify_pitch (const points_t& reference_points, const points_t& data_points) {
return 0;
}
float operators::classify_roll (const points_t& reference_points, const points_t& data_points) {
return 0;
}
point_t operators::centroid (const points_t& points) {
point_t centroid = { 0, 0 };
if (points.size () && points.size () <= _maximum_ref_points) {
centroid = sum (points);
centroid.x /= points.size ();
centroid.y /= points.size ();
}
return centroid;
}
template <typename T> T operators::sum (std::vector<T> values) {
kahan_accumulation<T> init;
kahan_accumulation<T> result = std::accumulate (values.begin (),
values.end (), init, [](kahan_accumulation<T> accumulation, T value) {
kahan_accumulation<T> result;
T y = value - accumulation.correction;
T t = accumulation.sum + y;
result.correction = (t - accumulation.sum) - y;
result.sum = t;
return result;
});
return result.sum;
}
point_t operators::sum (const points_t& points) {
point_t keypoint_sum = {};
std::vector<float> vec_x = {};
std::vector<float> vec_y = {};
for (auto point : points) {
vec_x.push_back (point.second.x);
vec_y.push_back (point.second.y);
}
keypoint_sum.x = sum<float> (vec_x);
keypoint_sum.y = sum<float> (vec_y);
return keypoint_sum;
}
point_t operators::intersections (point_t p1, point_t p2, point_t origin) {
point_t I = { 0, 0 }; // intersection
// normalize using the origin
// p1 = { p1.x - origin.x, p1.y - origin.y };
// p2 = { p2.x - origin.x, p2.y - origin.y };
// Y = AX + B
float At = p2.y - p1.y;
float Ab = p2.x - p1.x;
// A
float A;
// horizontal line,
// if Ab == 0 and p1.x == 0, x = 0
// else x = inf
if (At == POINT_ZERO) {
I.y = p1.y - origin.y;
I.x = POINT_INF;
return I;
}
// vertical line
// if At == 0 and pi.y == 0, y = 0
// else Y = inf
if (Ab == POINT_ZERO) {
I.x = p1.x - origin.x;
I.y = POINT_INF;
return I;
}
A = At / Ab;
// B
float B = p1.y - A * p1.x;
// intersection X axis; Y = 0
// x = (y - B) / A
I.x = (0 - B) / A;
// intersection Y axis; X = 0
// y = Ax+b = b
I.y = B;
// de-normalize using the origin
I = { I.x - origin.x, I.y - origin.y };
return I;
}
void operators::match_points (const points_t& reference_points, points_t& data_points) {
for (auto point = data_points.begin (); point != data_points.end ();) {
if (reference_points.find (point->first) == reference_points.end ()) {
point = data_points.erase (point);
} else {
++point;
}
}
}
template <typename T> std::string operators::to_string (T value) {
std::ostringstream os;
os << value;
return os.str ();
}
<commit_msg>switch to two point structure for scale<commit_after>#include "operators.hpp"
#include <cmath>
#include <iostream>
#include <map>
#include <numeric>
#include <sstream>
#include <string>
/* explicit instantiation declaration */
template float operators::sum<float> (std::vector<float> values);
template double operators::sum<double> (std::vector<double> values);
operators::operators () {
}
operators::~operators () {
}
float operators::classify_scale (const points_t& reference_points, const points_t& data_points) {
points_t points = data_points;
float scale = 1;
match_points (reference_points, points);
if (points.size () <= _minimum_ref_points || points.size () > _maximum_ref_points) {
return scale;
}
// centroid
point_t centroid_r = centroid (reference_points);
point_t centroid_p = centroid (points);
// keypoint reference
keypoint_t ref_A = { reference_points.begin ()->first,
reference_points.begin ()->second };
std::map<unsigned int, float> point_ratios; // <point ID, ratio>
// 1.0 means a perfect 45 degrees through A
point_t diff = {};
const float h_ratio = POINT_INF;
const float v_ratio = POINT_ZERO;
for (auto point : reference_points) {
if (ref_A.id != point.first) {
diff.x = (point.second.x - ref_A.p.x);
diff.y = (point.second.y - ref_A.p.y);
if (diff.y == POINT_ZERO) {
// horizontal line
// diff y is 0
point_ratios.insert ({ point.first, h_ratio });
} else if (diff.x == POINT_ZERO) {
// vertical line
// diff x 0
point_ratios.insert ({ point.first, v_ratio });
} else {
// absolute value, 1.0 is right in between
point_ratios.insert ({ point.first, std::fabs (diff.x / diff.y) });
}
}
}
// find optimal vertical and optimal horizontal point
// find closest to v_ratio
// find closes to h_ratio
// horizontal ratio close to 0
// find closest to optimal_ratio
unsigned int h_ratio_optimal = point_ratios.begin ()->first;
unsigned int v_ratio_optimal = point_ratios.begin ()->first;
for (auto ratio : point_ratios) {
h_ratio_optimal = std::fabs (ratio.second - h_ratio) <
std::fabs (point_ratios.find (h_ratio_optimal)->second - h_ratio) ?
ratio.first :
h_ratio_optimal;
v_ratio_optimal = std::fabs (ratio.second - v_ratio) <
std::fabs (point_ratios.find (v_ratio_optimal)->second - v_ratio) ?
ratio.first :
v_ratio_optimal;
}
// keypoint to use for x and y intersections
keypoint_t ref_x = { h_ratio_optimal,
reference_points.find (h_ratio_optimal)->second };
keypoint_t ref_y = { v_ratio_optimal,
reference_points.find (v_ratio_optimal)->second };
// keypoint_t ref_B = { optimal_point, reference_points.find
// (optimal_point)->second };
std::cout << "optimal x: " << ref_x.id << std::endl;
std::cout << "optimal y: " << ref_y.id << std::endl;
// find intersections
// point_t intersection_ref = intersections (ref_A.p, ref_B.p,
// centroid_r);
// point_t intersection_ref_x = { intersection_ref.x, 0 };
// point_t intersection_ref_y = { 0, intersection_ref.y };
// ratio of intersection
// <------->
// <--->
// A X B
// X
// calculate vector
// Y
float ratio_ref_a_x_b;
float ratio_ref_a_y_b;
// [from reference]
// find line(set of 2 points) that crosses x and y axis at some point
// make sure that this line is as close to 45 degrees to the centroid
// so that an overflow isn't bound to happen due to very large values
//
// with these points, solve Y=AX+B
// (intersection points with X and Y axis)
// where the centroid is the origin
//
// note the ratio where the intersection lays
// on the line between the two points
//
// [from data]
// using the two points and the ratio, look for the x/y intersection
// and compare the vectors from origin to intersections
// The one wit the difference can be used to calculate the scale
// (new size/old size)
//
// for reference
// pick always first point (let's call it A)
// for all points
// calculate the mean x, y difference from point A
// pick point with highest mean difference
// solve Y=AX+B
// solve Y=0
// note ratio of vectors between points
// and X=0
// note ratio of vectors between points
//
// calculate x, y location of x axis
// calculate x, y location of y axis
//
// calculate vector x axis
// calculate vector y axis
//
// line with smallest difference can be used for scale
return scale;
}
translation_t operators::classify_translation (const points_t& reference_points,
const points_t& data_points) {
translation_t translation = { 0, 0 };
points_t points = data_points;
match_points (reference_points, points);
if (points.size () <= _minimum_ref_points) {
return translation;
}
point_t centroid_reference = centroid (reference_points);
point_t centroid_points = centroid (points);
translation.x = centroid_points.x - centroid_reference.x;
translation.y = centroid_points.y - centroid_reference.y;
return translation;
}
float operators::classify_yaw (const points_t& reference_points, const points_t& data_points) {
return 0;
}
float operators::classify_pitch (const points_t& reference_points, const points_t& data_points) {
return 0;
}
float operators::classify_roll (const points_t& reference_points, const points_t& data_points) {
return 0;
}
point_t operators::centroid (const points_t& points) {
point_t centroid = { 0, 0 };
if (points.size () && points.size () <= _maximum_ref_points) {
centroid = sum (points);
centroid.x /= points.size ();
centroid.y /= points.size ();
}
return centroid;
}
template <typename T> T operators::sum (std::vector<T> values) {
kahan_accumulation<T> init;
kahan_accumulation<T> result = std::accumulate (values.begin (),
values.end (), init, [](kahan_accumulation<T> accumulation, T value) {
kahan_accumulation<T> result;
T y = value - accumulation.correction;
T t = accumulation.sum + y;
result.correction = (t - accumulation.sum) - y;
result.sum = t;
return result;
});
return result.sum;
}
point_t operators::sum (const points_t& points) {
point_t keypoint_sum = {};
std::vector<float> vec_x = {};
std::vector<float> vec_y = {};
for (auto point : points) {
vec_x.push_back (point.second.x);
vec_y.push_back (point.second.y);
}
keypoint_sum.x = sum<float> (vec_x);
keypoint_sum.y = sum<float> (vec_y);
return keypoint_sum;
}
point_t operators::intersections (point_t p1, point_t p2, point_t origin) {
point_t I = { 0, 0 }; // intersection
// normalize using the origin
// p1 = { p1.x - origin.x, p1.y - origin.y };
// p2 = { p2.x - origin.x, p2.y - origin.y };
// Y = AX + B
float At = p2.y - p1.y;
float Ab = p2.x - p1.x;
// A
float A;
// horizontal line,
// if Ab == 0 and p1.x == 0, x = 0
// else x = inf
if (At == POINT_ZERO) {
I.y = p1.y - origin.y;
I.x = POINT_INF;
return I;
}
// vertical line
// if At == 0 and pi.y == 0, y = 0
// else Y = inf
if (Ab == POINT_ZERO) {
I.x = p1.x - origin.x;
I.y = POINT_INF;
return I;
}
A = At / Ab;
// B
float B = p1.y - A * p1.x;
// intersection X axis; Y = 0
// x = (y - B) / A
I.x = (0 - B) / A;
// intersection Y axis; X = 0
// y = Ax+b = b
I.y = B;
// de-normalize using the origin
I = { I.x - origin.x, I.y - origin.y };
return I;
}
void operators::match_points (const points_t& reference_points, points_t& data_points) {
for (auto point = data_points.begin (); point != data_points.end ();) {
if (reference_points.find (point->first) == reference_points.end ()) {
point = data_points.erase (point);
} else {
++point;
}
}
}
template <typename T> std::string operators::to_string (T value) {
std::ostringstream os;
os << value;
return os.str ();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: plugin.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:29:23 $
*
* 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 __FRAMEWORK_MACROS_DEBUG_PLUGIN_HXX_
#define __FRAMEWORK_MACROS_DEBUG_PLUGIN_HXX_
//*****************************************************************************************************************
// special macros to debug asynchronous methods of plugin frame
//*****************************************************************************************************************
#ifdef ENABLE_PLUGINDEBUG
//_____________________________________________________________________________________________________________
// includes
//_____________________________________________________________________________________________________________
#ifndef _RTL_STRBUF_HXX_
#include <rtl/strbuf.hxx>
#endif
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif
/*_____________________________________________________________________________________________________________
LOGFILE_PLUGIN
For follow macros we need a special log file. If user forget to specify anyone, we must do it for him!
_____________________________________________________________________________________________________________*/
#ifndef LOGFILE_PLUGIN
#define LOGFILE_PLUGIN \
"plugin.log"
#endif
/*_____________________________________________________________________________________________________________
LOG_URLSEND( SFRAMENAME, SSENDMODE, SINTERNALURL, SEXTERNALURL )
Our plugin forward special url's to plugin dll, browser and webserver.
We convert internal url's to an external notation.
With this macro you can log some parameter of this operation.
_____________________________________________________________________________________________________________*/
#define LOG_URLSEND( SFRAMENAME, SSENDMODE, SINTERNALURL, SEXTERNALURL ) \
/* Use new scope to declare local private variables! */ \
{ \
::rtl::OStringBuffer sBuffer(1024); \
sBuffer.append( "PlugInFrame [ \"" ); \
sBuffer.append( SFRAMENAME ); \
sBuffer.append( "\" ] send " ); \
sBuffer.append( SSENDMODE ); \
sBuffer.append( "( internalURL=\"" ); \
sBuffer.append( U2B( SINTERNALURL ) ); \
sBuffer.append( "\", externalURL=\""); \
sBuffer.append( U2B( SEXTERNALURL ) ); \
sBuffer.append( "\" ) to browser.\n"); \
WRITE_LOGFILE( LOGFILE_PLUGIN, sBuffer.makeStringAndClear().getStr() ) \
}
/*_____________________________________________________________________________________________________________
LOG_URLRECEIVE( SFRAMENAME, SRECEIVEMODE, SEXTERNALURL, SINTERNALURL )
A plugin frame can get a url request in two different modes.
1) newURL()
2) newStream()
We convert external url's to an internal notation.
With this macro you can log some parameter of this operations.
_____________________________________________________________________________________________________________*/
#define LOG_URLRECEIVE( SFRAMENAME, SRECEIVEMODE, SEXTERNALURL, SINTERNALURL ) \
/* Use new scope to declare local private variables! */ \
{ \
::rtl::OStringBuffer sBuffer(1024); \
sBuffer.append( "PlugInFrame [ \"" ); \
sBuffer.append( U2B( SFRAMENAME ) ); \
sBuffer.append( "\" ] receive " ); \
sBuffer.append( SRECEIVEMODE ); \
sBuffer.append( "( externalURL=\"" ); \
sBuffer.append( U2B( SEXTERNALURL ) ); \
sBuffer.append( "\", internalURL=\"" ); \
sBuffer.append( U2B( SINTERNALURL ) ); \
sBuffer.append( "\" ) from browser.\n" ); \
WRITE_LOGFILE( LOGFILE_PLUGIN, sBuffer.makeStringAndClear().getStr() ) \
}
/*_____________________________________________________________________________________________________________
LOG_PARAMETER_NEWURL( SFRAMENAME, SMIMETYPE, SURL, AANY )
Log information about parameter of a newURL() at a plugin frame.
_____________________________________________________________________________________________________________*/
#define LOG_PARAMETER_NEWURL( SFRAMENAME, SMIMETYPE, SURL, AANY ) \
/* Use new scope to declare local private variables! */ \
{ \
::rtl::OStringBuffer sBuffer(1024); \
sBuffer.append( "PlugInFrame [ \"" ); \
sBuffer.append( U2B( SFRAMENAME ) ); \
sBuffer.append( "\" ] called with newURL( \"" ); \
sBuffer.append( U2B( SMIMETYPE ) ); \
sBuffer.append( "\", \"" ); \
sBuffer.append( U2B( SURL ) ); \
sBuffer.append( "\", " ); \
if( AANY.hasValue() == sal_True ) \
{ \
sBuffer.append( "filled Any )" ); \
} \
else \
{ \
sBuffer.append( "empty Any )" ); \
} \
sBuffer.append( "\n" ); \
WRITE_LOGFILE( LOGFILE_PLUGIN, sBuffer.makeStringAndClear().getStr() ) \
}
/*_____________________________________________________________________________________________________________
LOG_PARAMETER_NEWSTREAM( SFRAMENAME, SMIMETYPE, SURL, ASTREAM, AANY )
Log information about parameter of a newStream() at a plugin frame.
_____________________________________________________________________________________________________________*/
#define LOG_PARAMETER_NEWSTREAM( SFRAMENAME, SMIMETYPE, SURL, XSTREAM, AANY ) \
/* Use new scope to declare local private variables! */ \
{ \
::rtl::OStringBuffer sBuffer(1024); \
sBuffer.append( "PlugInFrame [ \"" ); \
sBuffer.append( U2B( SFRAMENAME ) ); \
sBuffer.append( "\" ] called with newStream( \""); \
sBuffer.append( U2B( SMIMETYPE ) ); \
sBuffer.append( "\", \"" ); \
sBuffer.append( U2B( SURL ) ); \
sBuffer.append( "\", " ); \
if( XSTREAM.is() == sal_True ) \
{ \
sal_Int32 nBytes = XSTREAM->available(); \
OString sInfo("Stream with "); \
sInfo += OString::valueOf( (sal_Int32)nBytes ); \
sInfo += " Bytes, "; \
sBuffer.append( sInfo ); \
} \
else \
{ \
sBuffer.append( "empty Stream, " ); \
} \
if( AANY.hasValue() == sal_True ) \
{ \
sBuffer.append( "filled Any )" ); \
} \
else \
{ \
sBuffer.append( "empty Any )" ); \
} \
sBuffer.append( "\n" ); \
WRITE_LOGFILE( LOGFILE_PLUGIN, sBuffer.makeStringAndClear().getStr() ) \
}
#else // #ifdef ENABLE_PLUGINDEBUG
/*_____________________________________________________________________________________________________________
If right testmode is'nt set - implements these macro empty!
_____________________________________________________________________________________________________________*/
#undef LOGFILE_PLUGIN
#define LOG_URLSEND( SFRAMENAME, SSENDMODE, SINTERNALURL, SEXTERNALURL )
#define LOG_URLRECEIVE( SFRAMENAME, SRECEIVEMODE, SEXTERNALURL, SINTERNALURL )
#define LOG_PARAMETER_NEWURL( SFRAMENAME, SMIMETYPE, SURL, AANY )
#define LOG_PARAMETER_NEWSTREAM( SFRAMENAME, SMIMETYPE, SURL, XSTREAM, AANY )
#endif // #ifdef ENABLE_PLUGINDEBUG
//*****************************************************************************************************************
// end of file
//*****************************************************************************************************************
#endif // #ifndef __FRAMEWORK_MACROS_DEBUG_PLUGIN_HXX_
<commit_msg>use given filter string for plugin load<commit_after>/*************************************************************************
*
* $RCSfile: plugin.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: as $ $Date: 2000-12-19 10:12:24 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_MACROS_DEBUG_PLUGIN_HXX_
#define __FRAMEWORK_MACROS_DEBUG_PLUGIN_HXX_
//*****************************************************************************************************************
// special macros to debug asynchronous methods of plugin frame
//*****************************************************************************************************************
#ifdef ENABLE_PLUGINDEBUG
//_____________________________________________________________________________________________________________
// includes
//_____________________________________________________________________________________________________________
#ifndef _RTL_STRBUF_HXX_
#include <rtl/strbuf.hxx>
#endif
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif
/*_____________________________________________________________________________________________________________
LOGFILE_PLUGIN
For follow macros we need a special log file. If user forget to specify anyone, we must do it for him!
_____________________________________________________________________________________________________________*/
#ifndef LOGFILE_PLUGIN
#define LOGFILE_PLUGIN \
"plugin.log"
#endif
/*_____________________________________________________________________________________________________________
LOG_URLSEND( SFRAMENAME, SSENDMODE, SINTERNALURL, SEXTERNALURL )
Our plugin forward special url's to plugin dll, browser and webserver.
We convert internal url's to an external notation.
With this macro you can log some parameter of this operation.
_____________________________________________________________________________________________________________*/
#define LOG_URLSEND( SFRAMENAME, SSENDMODE, SINTERNALURL, SEXTERNALURL ) \
/* Use new scope to declare local private variables! */ \
{ \
::rtl::OStringBuffer sBuffer(1024); \
sBuffer.append( "PlugInFrame [ \"" ); \
sBuffer.append( SFRAMENAME ); \
sBuffer.append( "\" ] send " ); \
sBuffer.append( SSENDMODE ); \
sBuffer.append( "( internalURL=\"" ); \
sBuffer.append( U2B( SINTERNALURL ) ); \
sBuffer.append( "\", externalURL=\""); \
sBuffer.append( U2B( SEXTERNALURL ) ); \
sBuffer.append( "\" ) to browser.\n"); \
WRITE_LOGFILE( LOGFILE_PLUGIN, sBuffer.makeStringAndClear().getStr() ) \
}
/*_____________________________________________________________________________________________________________
LOG_URLRECEIVE( SFRAMENAME, SRECEIVEMODE, SEXTERNALURL, SINTERNALURL )
A plugin frame can get a url request in two different modes.
1) newURL()
2) newStream()
We convert external url's to an internal notation.
With this macro you can log some parameter of this operations.
_____________________________________________________________________________________________________________*/
#define LOG_URLRECEIVE( SFRAMENAME, SRECEIVEMODE, SEXTERNALURL, SINTERNALURL ) \
/* Use new scope to declare local private variables! */ \
{ \
::rtl::OStringBuffer sBuffer(1024); \
sBuffer.append( "PlugInFrame [ \"" ); \
sBuffer.append( U2B( SFRAMENAME ) ); \
sBuffer.append( "\" ] receive " ); \
sBuffer.append( SRECEIVEMODE ); \
sBuffer.append( "( externalURL=\"" ); \
sBuffer.append( U2B( SEXTERNALURL ) ); \
sBuffer.append( "\", internalURL=\"" ); \
sBuffer.append( U2B( SINTERNALURL ) ); \
sBuffer.append( "\" ) from browser.\n" ); \
WRITE_LOGFILE( LOGFILE_PLUGIN, sBuffer.makeStringAndClear().getStr() ) \
}
/*_____________________________________________________________________________________________________________
LOG_PARAMETER_NEWURL( SFRAMENAME, SMIMETYPE, SURL, AANY )
Log information about parameter of a newURL() at a plugin frame.
_____________________________________________________________________________________________________________*/
#define LOG_PARAMETER_NEWURL( SFRAMENAME, SMIMETYPE, SURL, sFILTER, AANY ) \
/* Use new scope to declare local private variables! */ \
{ \
::rtl::OStringBuffer sBuffer(1024); \
sBuffer.append( "PlugInFrame [ \"" ); \
sBuffer.append( U2B( SFRAMENAME ) ); \
sBuffer.append( "\" ] called with newURL( \"" ); \
sBuffer.append( U2B( SMIMETYPE ) ); \
sBuffer.append( "\", \"" ); \
sBuffer.append( U2B( SURL ) ); \
sBuffer.append( "\", \"" ); \
sBuffer.append( U2B( SFILTER ) ); \
sBuffer.append( "\", " ); \
if( AANY.hasValue() == sal_True ) \
{ \
sBuffer.append( "filled Any )" ); \
} \
else \
{ \
sBuffer.append( "empty Any )" ); \
} \
sBuffer.append( "\n" ); \
WRITE_LOGFILE( LOGFILE_PLUGIN, sBuffer.makeStringAndClear().getStr() ) \
}
/*_____________________________________________________________________________________________________________
LOG_PARAMETER_NEWSTREAM( SFRAMENAME, SMIMETYPE, SURL, ASTREAM, AANY )
Log information about parameter of a newStream() at a plugin frame.
_____________________________________________________________________________________________________________*/
#define LOG_PARAMETER_NEWSTREAM( SFRAMENAME, SMIMETYPE, SURL, SFILTER, XSTREAM, AANY ) \
/* Use new scope to declare local private variables! */ \
{ \
::rtl::OStringBuffer sBuffer(1024); \
sBuffer.append( "PlugInFrame [ \"" ); \
sBuffer.append( U2B( SFRAMENAME ) ); \
sBuffer.append( "\" ] called with newStream( \""); \
sBuffer.append( U2B( SMIMETYPE ) ); \
sBuffer.append( "\", \"" ); \
sBuffer.append( U2B( SURL ) ); \
sBuffer.append( "\", \"" ); \
sBuffer.append( U2B( SFILTER ) ); \
sBuffer.append( "\", " ); \
if( XSTREAM.is() == sal_True ) \
{ \
sal_Int32 nBytes = XSTREAM->available(); \
OString sInfo("Stream with "); \
sInfo += OString::valueOf( (sal_Int32)nBytes ); \
sInfo += " Bytes, "; \
sBuffer.append( sInfo ); \
} \
else \
{ \
sBuffer.append( "empty Stream, " ); \
} \
if( AANY.hasValue() == sal_True ) \
{ \
sBuffer.append( "filled Any )" ); \
} \
else \
{ \
sBuffer.append( "empty Any )" ); \
} \
sBuffer.append( "\n" ); \
WRITE_LOGFILE( LOGFILE_PLUGIN, sBuffer.makeStringAndClear().getStr() ) \
}
#else // #ifdef ENABLE_PLUGINDEBUG
/*_____________________________________________________________________________________________________________
If right testmode is'nt set - implements these macro empty!
_____________________________________________________________________________________________________________*/
#undef LOGFILE_PLUGIN
#define LOG_URLSEND( SFRAMENAME, SSENDMODE, SINTERNALURL, SEXTERNALURL )
#define LOG_URLRECEIVE( SFRAMENAME, SRECEIVEMODE, SEXTERNALURL, SINTERNALURL )
#define LOG_PARAMETER_NEWURL( SFRAMENAME, SMIMETYPE, SURL, SFILTER, AANY )
#define LOG_PARAMETER_NEWSTREAM( SFRAMENAME, SMIMETYPE, SURL, SFILTER, XSTREAM, AANY )
#endif // #ifdef ENABLE_PLUGINDEBUG
//*****************************************************************************************************************
// end of file
//*****************************************************************************************************************
#endif // #ifndef __FRAMEWORK_MACROS_DEBUG_PLUGIN_HXX_
<|endoftext|> |
<commit_before>#include "nixsection.h"
#include "mex.h"
#include <nix.hpp>
#include "nixgen.h"
#include "handle.h"
#include "arguments.h"
#include "struct.h"
#include "nix2mx.h"
namespace nixsection {
static mxArray* array_from_value(nix::Value v)
{
mxArray *res;
nix::DataType dtype = v.type();
switch (dtype) {
case nix::DataType::Bool: res = make_mx_array(v.get<bool>()); break;
case nix::DataType::String: res = make_mx_array(v.get<std::string>()); break;
case nix::DataType::Double: res = make_mx_array(v.get<double>()); break;
case nix::DataType::Int32: res = make_mx_array(v.get<std::int32_t>()); break;
case nix::DataType::UInt32: res = make_mx_array(v.get<std::uint32_t>()); break;
case nix::DataType::Int64: res = make_mx_array(v.get<std::int64_t>()); break;
case nix::DataType::UInt64: res = make_mx_array(v.get<std::uint64_t>()); break;
default: res = make_mx_array(v.get<std::string>());
}
return res;
}
void describe(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
struct_builder sb({ 1 }, {
"name", "id", "type", "repository", "mapping"
});
sb.set(section.name());
sb.set(section.id());
sb.set(section.type());
sb.set(section.repository());
sb.set(section.mapping());
output.set(0, sb.array());
}
void link(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
nix::Section linked = section.link();
handle lh = handle(linked);
output.set(0, lh);
}
void parent(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
nix::Section parent = section.parent();
handle lh = handle(parent);
output.set(0, lh);
}
void has_section(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
output.set(0, nixgen::has_entity(section.hasSection(input.str(2)), { "hasSection" }));
}
void open_section(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
nix::Section sec = section.getSection(input.str(2));
handle h = handle(sec);
output.set(0, h);
}
void list_sections(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
std::vector<nix::Section> sections = section.sections();
struct_builder sb({ sections.size() }, { "name", "id", "type" });
for (const auto &b : sections) {
sb.set(b.name());
sb.set(b.id());
sb.set(b.type());
sb.next();
}
output.set(0, sb.array());
}
void sections(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
std::vector<nix::Section> sections = section.sections();
const mwSize size = static_cast<mwSize>(sections.size());
mxArray *lst = mxCreateCellArray(1, &size);
for (size_t i = 0; i < sections.size(); i++) {
mxSetCell(lst, i, make_mx_array(handle(sections[i])));
}
output.set(0, lst);
}
void has_property(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
output.set(0, nixgen::has_entity(section.hasProperty(input.str(2)), { "hasProperty" }));
}
void list_properties(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
std::vector<nix::Property> properties = section.properties();
const mwSize size = static_cast<mwSize>(properties.size());
mxArray *lst = mxCreateCellArray(1, &size);
for (size_t i = 0; i < properties.size(); i++) {
nix::Property pr = properties[i];
std::vector<nix::Value> values = pr.values();
const mwSize val_size = static_cast<mwSize>(values.size());
mxArray *mx_values = mxCreateCellArray(1, &val_size);
for (size_t j = 0; j < values.size(); j++) {
mxSetCell(mx_values, j, array_from_value(values[j]));
}
struct_builder sb({ 1 }, {
"name", "id", "definition", "mapping", "unit", "values"
});
sb.set(pr.name());
sb.set(pr.id());
sb.set(pr.definition());
sb.set(pr.mapping());
sb.set(pr.unit());
sb.set(mx_values);
mxSetCell(lst, i, sb.array());
}
output.set(0, lst);
}
} // namespace nixfile
<commit_msg>small typo fix<commit_after>#include "nixsection.h"
#include "mex.h"
#include <nix.hpp>
#include "nixgen.h"
#include "handle.h"
#include "arguments.h"
#include "struct.h"
#include "nix2mx.h"
namespace nixsection {
static mxArray* array_from_value(nix::Value v)
{
mxArray *res;
nix::DataType dtype = v.type();
switch (dtype) {
case nix::DataType::Bool: res = make_mx_array(v.get<bool>()); break;
case nix::DataType::String: res = make_mx_array(v.get<std::string>()); break;
case nix::DataType::Double: res = make_mx_array(v.get<double>()); break;
case nix::DataType::Int32: res = make_mx_array(v.get<std::int32_t>()); break;
case nix::DataType::UInt32: res = make_mx_array(v.get<std::uint32_t>()); break;
case nix::DataType::Int64: res = make_mx_array(v.get<std::int64_t>()); break;
case nix::DataType::UInt64: res = make_mx_array(v.get<std::uint64_t>()); break;
default: res = make_mx_array(v.get<std::string>());
}
return res;
}
void describe(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
struct_builder sb({ 1 }, {
"name", "id", "type", "repository", "mapping"
});
sb.set(section.name());
sb.set(section.id());
sb.set(section.type());
sb.set(section.repository());
sb.set(section.mapping());
output.set(0, sb.array());
}
void link(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
nix::Section linked = section.link();
handle lh = handle(linked);
output.set(0, lh);
}
void parent(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
nix::Section parent = section.parent();
handle lh = handle(parent);
output.set(0, lh);
}
void has_section(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
output.set(0, nixgen::has_entity(section.hasSection(input.str(2)), { "hasSection" }));
}
void open_section(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
nix::Section sec = section.getSection(input.str(2));
handle h = handle(sec);
output.set(0, h);
}
void list_sections(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
std::vector<nix::Section> sections = section.sections();
struct_builder sb({ sections.size() }, { "name", "id", "type" });
for (const auto &b : sections) {
sb.set(b.name());
sb.set(b.id());
sb.set(b.type());
sb.next();
}
output.set(0, sb.array());
}
void sections(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
std::vector<nix::Section> sections = section.sections();
const mwSize size = static_cast<mwSize>(sections.size());
mxArray *lst = mxCreateCellArray(1, &size);
for (size_t i = 0; i < sections.size(); i++) {
mxSetCell(lst, i, make_mx_array(handle(sections[i])));
}
output.set(0, lst);
}
void has_property(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
output.set(0, nixgen::has_entity(section.hasProperty(input.str(2)), { "hasProperty" }));
}
void list_properties(const extractor &input, infusor &output)
{
nix::Section section = input.entity<nix::Section>(1);
std::vector<nix::Property> properties = section.properties();
const mwSize size = static_cast<mwSize>(properties.size());
mxArray *lst = mxCreateCellArray(1, &size);
for (size_t i = 0; i < properties.size(); i++) {
nix::Property pr = properties[i];
std::vector<nix::Value> values = pr.values();
const mwSize val_size = static_cast<mwSize>(values.size());
mxArray *mx_values = mxCreateCellArray(1, &val_size);
for (size_t j = 0; j < values.size(); j++) {
mxSetCell(mx_values, j, array_from_value(values[j]));
}
struct_builder sb({ 1 }, {
"name", "id", "definition", "mapping", "unit", "values"
});
sb.set(pr.name());
sb.set(pr.id());
sb.set(pr.definition());
sb.set(pr.mapping());
sb.set(pr.unit());
sb.set(mx_values);
mxSetCell(lst, i, sb.array());
}
output.set(0, lst);
}
} // namespace nixsection
<|endoftext|> |
<commit_before>#include "compiler.h"
#include "mswin.h"
#include <windowsx.h>
#include "polymorph.h"
#include "resources.h"
#include "glinit.h"
#include "model.h"
#include "aligned-arrays.h"
#include "qpc.h"
#include "print.h"
#define WC_MAIN TEXT ("M")
ALIGN_STACK LRESULT CALLBACK MainWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
LRESULT result = 0;
bool call_def_window_proc = false, close_window = false;
// Retrieve the window-struct pointer from the window userdata.
window_struct_t * ws = reinterpret_cast <window_struct_t *> (::GetWindowLongPtr (hwnd, GWLP_USERDATA));
switch (msg) {
case WM_CREATE: {
result = -1; // Abort window creation.
// Store the window-struct pointer in the window userdata.
CREATESTRUCT * cs = (CREATESTRUCT *) lParam;
ws = (window_struct_t *) cs->lpCreateParams;
::SetWindowLongPtr (hwnd, GWLP_USERDATA, reinterpret_cast <LONG_PTR> (ws));
ws->hglrc = install_rendering_context (hwnd);
if (ws->hglrc) {
ws->model.initialize (qpc ());
result = 0; // Allow window creation to continue.
}
break;
}
case WM_WINDOWPOSCHANGING: {
WINDOWPOS * windowpos = (WINDOWPOS *) lParam;
if (windowpos->flags & SWP_SHOWWINDOW) {
if (ws->mode == parented) {
RECT rect;
::GetClientRect (::GetParent (hwnd), & rect);
windowpos->cx = rect.right;
windowpos->cy = rect.bottom;
}
else {
windowpos->x = ::GetSystemMetrics (SM_XVIRTUALSCREEN);
windowpos->y = ::GetSystemMetrics (SM_YVIRTUALSCREEN);
windowpos->cx = ::GetSystemMetrics (SM_CXVIRTUALSCREEN);
windowpos->cy = ::GetSystemMetrics (SM_CYVIRTUALSCREEN);
}
windowpos->flags &= ~ (SWP_NOSIZE | SWP_NOMOVE);
}
break;
}
case WM_WINDOWPOSCHANGED: {
WINDOWPOS * windowpos = (WINDOWPOS *) lParam;
if (windowpos->flags & SWP_SHOWWINDOW) {
// Remember initial cursor position to detect mouse movement.
::GetCursorPos (& ws->initial_cursor_position);
// (Re-)start the simulation.
ws->model.start (windowpos->cx, windowpos->cy, * ws->settings);
ws->model.draw_next ();
}
break;
}
case WM_APP:
ws->model.draw_next ();
::InvalidateRect (hwnd, NULL, FALSE);
break;
case WM_PAINT: {
PAINTSTRUCT ps;
::BeginPaint (hwnd, & ps);
::SwapBuffers (ps.hdc);
::EndPaint (hwnd, & ps);
::PostMessage (hwnd, WM_APP, 0, 0);
break;
}
case WM_SETCURSOR:
::SetCursor (ws->mode == screensaver || ws->mode == configure ? NULL : ::LoadCursor (NULL, IDC_ARROW));
break;
case WM_MOUSEMOVE:
if (ws->mode == screensaver || ws->mode == configure) {
// Compare the current mouse position with the one stored in the window struct.
DWORD pos = ::GetMessagePos ();
int dx = GET_X_LPARAM (pos) - ws->initial_cursor_position.x;
int dy = GET_Y_LPARAM (pos) - ws->initial_cursor_position.y;
close_window = (dx < -10 || dx > 10) || (dy < -10 || dy > 10);
}
break;
case WM_KEYDOWN: case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN:
close_window = ws->mode != parented;
break;
case WM_ACTIVATE: case WM_ACTIVATEAPP: case WM_NCACTIVATE:
close_window = (ws->mode == screensaver || ws->mode == configure) && LOWORD (wParam) == WA_INACTIVE;
call_def_window_proc = true;
break;
case WM_SYSCOMMAND:
call_def_window_proc = ! ((ws->mode == screensaver || ws->mode == configure) && wParam == SC_SCREENSAVE);
break;
case WM_CLOSE:
if (ws->mode == configure) {
if (::GetWindowLongPtr (hwnd, GWL_STYLE) & WS_VISIBLE) {
// Workaround for bug observed on Windows 8.1 where hiding
// a full-monitor OpenGL window does not remove it from the display:
// resize the window before hiding it.
::SetWindowPos (hwnd, NULL, 0, 0, 0, 0, SWP_NOOWNERZORDER | SWP_NOCOPYBITS);
::ShowWindow (hwnd, SW_HIDE);
}
}
else
::DestroyWindow (hwnd);
break;
case WM_DESTROY:
::wglMakeCurrent (NULL, NULL);
if (ws->hglrc) ::wglDeleteContext (ws->hglrc);
::PostQuitMessage (0);
break;
default:
call_def_window_proc = true;
break;
}
if (close_window) ::PostMessage (hwnd, WM_CLOSE, 0, 0);
if (call_def_window_proc) result = ::DefWindowProc (hwnd, msg, wParam, lParam);
return result;
}
void register_class (HINSTANCE hInstance)
{
// The screensaver window has no taskbar button or system menu, but the small
// icon is inherited by the (owned) configure dialog and used for the taskbar button.
// We could set the dialog's small icon directly, but then it would appear in
// the dialog's system menu, which is not the desired effect.
HICON icon = (HICON) ::LoadImage (hInstance, MAKEINTRESOURCE (IDI_APPICON), IMAGE_ICON, 0, 0, LR_LOADTRANSPARENT);
HICON icon_small = (HICON) ::LoadImage (hInstance, MAKEINTRESOURCE (IDI_APPICON), IMAGE_ICON, 16, 16, LR_LOADTRANSPARENT);
WNDCLASSEX wndclass = { sizeof (WNDCLASSEX), 0, & MainWndProc, 0, 0, hInstance, icon, NULL, NULL, NULL, WC_MAIN, icon_small };
::RegisterClassEx (& wndclass);
}
HWND create_window (HINSTANCE hInstance, HWND parent, LPCTSTR display_name, window_struct_t * ws)
{
// Create the main window. See MainWndProc for details.
DWORD style = ws->mode == parented ? WS_CHILD : WS_POPUP;
DWORD ex_style = (ws->mode == screensaver || ws->mode == configure ? WS_EX_TOPMOST : 0) | WS_EX_TOOLWINDOW;
return ::CreateWindowEx (ex_style, WC_MAIN, display_name, style,
0, 0, 0, 0,
parent, NULL, hInstance, ws);
}
<commit_msg>polymorph.cpp: use WS_EX_APPWINDOW for screensaver window in persistent mode.<commit_after>#include "compiler.h"
#include "mswin.h"
#include <windowsx.h>
#include "polymorph.h"
#include "resources.h"
#include "glinit.h"
#include "model.h"
#include "aligned-arrays.h"
#include "qpc.h"
#include "print.h"
#define WC_MAIN TEXT ("M")
ALIGN_STACK LRESULT CALLBACK MainWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
LRESULT result = 0;
bool call_def_window_proc = false, close_window = false;
// Retrieve the window-struct pointer from the window userdata.
window_struct_t * ws = reinterpret_cast <window_struct_t *> (::GetWindowLongPtr (hwnd, GWLP_USERDATA));
switch (msg) {
case WM_CREATE: {
result = -1; // Abort window creation.
// Store the window-struct pointer in the window userdata.
CREATESTRUCT * cs = (CREATESTRUCT *) lParam;
ws = (window_struct_t *) cs->lpCreateParams;
::SetWindowLongPtr (hwnd, GWLP_USERDATA, reinterpret_cast <LONG_PTR> (ws));
ws->hglrc = install_rendering_context (hwnd);
if (ws->hglrc) {
ws->model.initialize (qpc ());
result = 0; // Allow window creation to continue.
}
break;
}
case WM_WINDOWPOSCHANGING: {
WINDOWPOS * windowpos = (WINDOWPOS *) lParam;
if (windowpos->flags & SWP_SHOWWINDOW) {
if (ws->mode == parented) {
RECT rect;
::GetClientRect (::GetParent (hwnd), & rect);
windowpos->cx = rect.right;
windowpos->cy = rect.bottom;
}
else {
windowpos->x = ::GetSystemMetrics (SM_XVIRTUALSCREEN);
windowpos->y = ::GetSystemMetrics (SM_YVIRTUALSCREEN);
windowpos->cx = ::GetSystemMetrics (SM_CXVIRTUALSCREEN);
windowpos->cy = ::GetSystemMetrics (SM_CYVIRTUALSCREEN);
}
windowpos->flags &= ~ (SWP_NOSIZE | SWP_NOMOVE);
}
break;
}
case WM_WINDOWPOSCHANGED: {
WINDOWPOS * windowpos = (WINDOWPOS *) lParam;
if (windowpos->flags & SWP_SHOWWINDOW) {
// Remember initial cursor position to detect mouse movement.
::GetCursorPos (& ws->initial_cursor_position);
// (Re-)start the simulation.
ws->model.start (windowpos->cx, windowpos->cy, * ws->settings);
ws->model.draw_next ();
}
break;
}
case WM_APP:
ws->model.draw_next ();
::InvalidateRect (hwnd, NULL, FALSE);
break;
case WM_PAINT: {
PAINTSTRUCT ps;
::BeginPaint (hwnd, & ps);
::SwapBuffers (ps.hdc);
::EndPaint (hwnd, & ps);
::PostMessage (hwnd, WM_APP, 0, 0);
break;
}
case WM_SETCURSOR:
::SetCursor (ws->mode == screensaver || ws->mode == configure ? NULL : ::LoadCursor (NULL, IDC_ARROW));
break;
case WM_MOUSEMOVE:
if (ws->mode == screensaver || ws->mode == configure) {
// Compare the current mouse position with the one stored in the window struct.
DWORD pos = ::GetMessagePos ();
int dx = GET_X_LPARAM (pos) - ws->initial_cursor_position.x;
int dy = GET_Y_LPARAM (pos) - ws->initial_cursor_position.y;
close_window = (dx < -10 || dx > 10) || (dy < -10 || dy > 10);
}
break;
case WM_KEYDOWN: case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN:
close_window = ws->mode != parented;
break;
case WM_ACTIVATE: case WM_ACTIVATEAPP: case WM_NCACTIVATE:
close_window = (ws->mode == screensaver || ws->mode == configure) && LOWORD (wParam) == WA_INACTIVE;
call_def_window_proc = true;
break;
case WM_SYSCOMMAND:
call_def_window_proc = ! ((ws->mode == screensaver || ws->mode == configure) && wParam == SC_SCREENSAVE);
break;
case WM_CLOSE:
if (ws->mode == configure) {
if (::GetWindowLongPtr (hwnd, GWL_STYLE) & WS_VISIBLE) {
// Workaround for bug observed on Windows 8.1 where hiding
// a full-monitor OpenGL window does not remove it from the display:
// resize the window before hiding it.
::SetWindowPos (hwnd, NULL, 0, 0, 0, 0, SWP_NOOWNERZORDER | SWP_NOCOPYBITS);
::ShowWindow (hwnd, SW_HIDE);
}
}
else
::DestroyWindow (hwnd);
break;
case WM_DESTROY:
::wglMakeCurrent (NULL, NULL);
if (ws->hglrc) ::wglDeleteContext (ws->hglrc);
::PostQuitMessage (0);
break;
default:
call_def_window_proc = true;
break;
}
if (close_window) ::PostMessage (hwnd, WM_CLOSE, 0, 0);
if (call_def_window_proc) result = ::DefWindowProc (hwnd, msg, wParam, lParam);
return result;
}
void register_class (HINSTANCE hInstance)
{
// The screensaver window has no taskbar button or system menu, but the small
// icon is inherited by the (owned) configure dialog and used for the taskbar button.
// We could set the dialog's small icon directly, but then it would appear in
// the dialog's system menu, which is not the desired effect.
HICON icon = (HICON) ::LoadImage (hInstance, MAKEINTRESOURCE (IDI_APPICON), IMAGE_ICON, 0, 0, LR_LOADTRANSPARENT);
HICON icon_small = (HICON) ::LoadImage (hInstance, MAKEINTRESOURCE (IDI_APPICON), IMAGE_ICON, 16, 16, LR_LOADTRANSPARENT);
WNDCLASSEX wndclass = { sizeof (WNDCLASSEX), 0, & MainWndProc, 0, 0, hInstance, icon, NULL, NULL, NULL, WC_MAIN, icon_small };
::RegisterClassEx (& wndclass);
}
HWND create_window (HINSTANCE hInstance, HWND parent, LPCTSTR display_name, window_struct_t * ws)
{
// Create the main window. See MainWndProc for details.
DWORD style = ws->mode == parented ? WS_CHILD : WS_POPUP;
DWORD ex_style =
(ws->mode == screensaver || ws->mode == configure ? WS_EX_TOPMOST : 0) |
(ws->mode == persistent ? WS_EX_APPWINDOW : WS_EX_TOOLWINDOW);
return ::CreateWindowEx (ex_style, WC_MAIN, display_name, style,
0, 0, 0, 0,
parent, NULL, hInstance, ws);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2018 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* 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
* FOUNDATION 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.
*/
/*
* Memory pool.
*/
#ifndef BENG_PROXY_POOL_HXX
#define BENG_PROXY_POOL_HXX
#include "Type.hxx"
#include "trace.h"
#include "util/Compiler.h"
#include <type_traits>
#include <utility>
#include <new>
#ifndef NDEBUG
#include <assert.h>
#endif
#include <stddef.h>
#include <stdbool.h>
struct pool;
class SlicePool;
struct AllocatorStats;
class PoolPtr;
class PoolLeakDetector;
template<typename T> struct ConstBuffer;
struct StringView;
void
pool_recycler_clear() noexcept;
/**
* Create a new pool which cannot allocate anything; it only serves as
* parent for other pools.
*/
PoolPtr
pool_new_dummy(struct pool *parent, const char *name) noexcept;
PoolPtr
pool_new_libc(struct pool *parent, const char *name) noexcept;
PoolPtr
pool_new_linear(struct pool *parent, const char *name,
size_t initial_size) noexcept;
PoolPtr
pool_new_slice(struct pool *parent, const char *name,
SlicePool *slice_pool) noexcept;
#ifdef NDEBUG
#define pool_set_major(pool)
#else
void
pool_set_major(struct pool *pool) noexcept;
#endif
void
pool_ref_impl(struct pool *pool TRACE_ARGS_DECL) noexcept;
#define pool_ref(pool) pool_ref_impl(pool TRACE_ARGS)
#define pool_ref_fwd(pool) pool_ref_impl(pool TRACE_ARGS_FWD)
unsigned
pool_unref_impl(struct pool *pool TRACE_ARGS_DECL) noexcept;
#define pool_unref(pool) pool_unref_impl(pool TRACE_ARGS)
#define pool_unref_fwd(pool) pool_unref_impl(pool TRACE_ARGS_FWD)
/* not implemented - just here to detect bugs */
void
pool_ref_impl(const PoolPtr &pool TRACE_ARGS_DECL) noexcept;
/* not implemented - just here to detect bugs */
void
pool_unref_impl(const PoolPtr &pool TRACE_ARGS_DECL) noexcept;
/**
* Returns the total size of all allocations in this pool.
*/
gcc_pure
size_t
pool_netto_size(const struct pool *pool) noexcept;
/**
* Returns the total amount of memory allocated by this pool.
*/
gcc_pure
size_t
pool_brutto_size(const struct pool *pool) noexcept;
/**
* Returns the total size of this pool and all of its descendants
* (recursively).
*/
gcc_pure
size_t
pool_recursive_netto_size(const struct pool *pool) noexcept;
gcc_pure
size_t
pool_recursive_brutto_size(const struct pool *pool) noexcept;
/**
* Returns the total size of all descendants of this pool (recursively).
*/
gcc_pure
size_t
pool_children_netto_size(const struct pool *pool) noexcept;
gcc_pure
size_t
pool_children_brutto_size(const struct pool *pool) noexcept;
AllocatorStats
pool_children_stats(const struct pool &pool) noexcept;
void
pool_dump_tree(const struct pool &pool) noexcept;
class ScopePoolRef {
struct pool &pool;
#ifdef TRACE
const char *const file;
unsigned line;
#endif
public:
explicit ScopePoolRef(struct pool &_pool TRACE_ARGS_DECL_) noexcept
:pool(_pool)
TRACE_ARGS_INIT
{
pool_ref_fwd(&_pool);
}
ScopePoolRef(const ScopePoolRef &) = delete;
~ScopePoolRef() noexcept {
pool_unref_fwd(&pool);
}
operator struct pool &() noexcept {
return pool;
}
operator struct pool *() noexcept {
return &pool;
}
};
#ifdef NDEBUG
static inline void
pool_trash(gcc_unused struct pool *pool) noexcept
{
}
static inline void
pool_commit() noexcept
{
}
#else
void
pool_trash(struct pool *pool) noexcept;
void
pool_commit() noexcept;
bool
pool_contains(const struct pool &pool, const void *ptr, size_t size) noexcept;
/**
* Register a #PoolLeakDetector to the pool.
*/
void
pool_register_leak_detector(struct pool &pool, PoolLeakDetector &ld) noexcept;
#endif
/**
* Free all allocations.
*/
void
pool_clear(struct pool &pool) noexcept;
gcc_malloc gcc_returns_nonnull
void *
p_malloc_impl(struct pool *pool, size_t size TYPE_ARG_DECL TRACE_ARGS_DECL) noexcept;
gcc_malloc gcc_returns_nonnull
static inline void *
p_malloc_type(struct pool &pool, size_t size TYPE_ARG_DECL) noexcept
{
return p_malloc_impl(&pool, size TYPE_ARG_FWD TRACE_ARGS);
}
#ifndef NDEBUG
gcc_malloc gcc_returns_nonnull
static inline void *
p_malloc_impl(struct pool *pool, size_t size TRACE_ARGS_DECL) noexcept
{
return p_malloc_impl(pool, size TYPE_ARG_NULL TRACE_ARGS_FWD);
}
#endif
#define p_malloc(pool, size) p_malloc_impl(pool, size TRACE_ARGS)
#define p_malloc_fwd(pool, size) p_malloc_impl(pool, size TRACE_ARGS_FWD)
void
p_free(struct pool *pool, const void *ptr, size_t size) noexcept;
gcc_malloc gcc_returns_nonnull
void *
p_memdup_impl(struct pool *pool, const void *src, size_t length
TRACE_ARGS_DECL) noexcept;
#define p_memdup(pool, src, length) p_memdup_impl(pool, src, length TRACE_ARGS)
#define p_memdup_fwd(pool, src, length) p_memdup_impl(pool, src, length TRACE_ARGS_FWD)
gcc_malloc gcc_returns_nonnull
char *
p_strdup_impl(struct pool *pool, const char *src TRACE_ARGS_DECL) noexcept;
#define p_strdup(pool, src) p_strdup_impl(pool, src TRACE_ARGS)
#define p_strdup_fwd(pool, src) p_strdup_impl(pool, src TRACE_ARGS_FWD)
static inline const char *
p_strdup_checked(struct pool *pool, const char *s) noexcept
{
return s == NULL ? NULL : p_strdup(pool, s);
}
gcc_malloc gcc_returns_nonnull
char *
p_strdup_lower_impl(struct pool *pool, const char *src
TRACE_ARGS_DECL) noexcept;
#define p_strdup_lower(pool, src) p_strdup_lower_impl(pool, src TRACE_ARGS)
#define p_strdup_lower_fwd(pool, src) p_strdup_lower_impl(pool, src TRACE_ARGS_FWD)
gcc_malloc gcc_returns_nonnull
char *
p_strndup_impl(struct pool *pool, const char *src, size_t length
TRACE_ARGS_DECL) noexcept;
#define p_strndup(pool, src, length) p_strndup_impl(pool, src, length TRACE_ARGS)
#define p_strndup_fwd(pool, src, length) p_strndup_impl(pool, src, length TRACE_ARGS_FWD)
gcc_malloc gcc_returns_nonnull
char *
p_strndup_lower_impl(struct pool *pool, const char *src, size_t length
TRACE_ARGS_DECL) noexcept;
#define p_strndup_lower(pool, src, length) p_strndup_lower_impl(pool, src, length TRACE_ARGS)
#define p_strndup_lower_fwd(pool, src, length) p_strndup_lower_impl(pool, src, length TRACE_ARGS_FWD)
gcc_malloc gcc_returns_nonnull gcc_printf(2, 3)
char *
p_sprintf(struct pool *pool, const char *fmt, ...) noexcept;
gcc_malloc gcc_returns_nonnull
char *
p_strcat(struct pool *pool, const char *s, ...) noexcept;
gcc_malloc gcc_returns_nonnull
char *
p_strncat(struct pool *pool, const char *s, size_t length, ...) noexcept;
template<typename T>
gcc_malloc gcc_returns_nonnull
T *
PoolAlloc(pool &p) noexcept
{
static_assert(std::is_trivially_default_constructible<T>::value,
"Must be trivially constructible");
return (T *)p_malloc_type(p, sizeof(T) TYPE_ARG(T));
}
template<typename T>
gcc_malloc gcc_returns_nonnull
T *
PoolAlloc(pool &p, size_t n) noexcept
{
static_assert(std::is_trivially_default_constructible<T>::value,
"Must be trivially constructible");
return (T *)p_malloc_type(p, sizeof(T) * n TYPE_ARG(T));
}
template<>
gcc_malloc gcc_returns_nonnull
inline void *
PoolAlloc<void>(pool &p, size_t n) noexcept
{
return p_malloc(&p, n);
}
template<typename T, typename... Args>
gcc_malloc gcc_returns_nonnull
T *
NewFromPool(pool &p, Args&&... args)
{
void *t = p_malloc_type(p, sizeof(T) TYPE_ARG(T));
return ::new(t) T(std::forward<Args>(args)...);
}
template<typename T>
void
DeleteFromPool(struct pool &pool, T *t) noexcept
{
t->~T();
p_free(&pool, t, sizeof(*t));
}
/**
* A disposer for boost::intrusive that invokes the DeleteFromPool()
* on the given pointer.
*/
class PoolDisposer {
struct pool &p;
public:
explicit PoolDisposer(struct pool &_p) noexcept:p(_p) {}
template<typename T>
void operator()(T *t) noexcept {
DeleteFromPool(p, t);
}
};
gcc_malloc gcc_returns_nonnull
char *
p_strdup_impl(struct pool &pool, StringView src TRACE_ARGS_DECL) noexcept;
gcc_malloc gcc_returns_nonnull
char *
p_strdup_lower_impl(struct pool &pool, StringView src
TRACE_ARGS_DECL) noexcept;
/**
* Concatenate all strings and return a newly allocated
* null-terminated string.
*/
char *
StringConcat(struct pool &pool, ConstBuffer<StringView> src) noexcept;
#endif
<commit_msg>pool/pool: add DeleteFromPool() overload without pool<commit_after>/*
* Copyright 2007-2018 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* 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
* FOUNDATION 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.
*/
/*
* Memory pool.
*/
#ifndef BENG_PROXY_POOL_HXX
#define BENG_PROXY_POOL_HXX
#include "Type.hxx"
#include "trace.h"
#include "util/Compiler.h"
#include <type_traits>
#include <utility>
#include <new>
#ifndef NDEBUG
#include <assert.h>
#endif
#include <stddef.h>
#include <stdbool.h>
struct pool;
class SlicePool;
struct AllocatorStats;
class PoolPtr;
class PoolLeakDetector;
template<typename T> struct ConstBuffer;
struct StringView;
void
pool_recycler_clear() noexcept;
/**
* Create a new pool which cannot allocate anything; it only serves as
* parent for other pools.
*/
PoolPtr
pool_new_dummy(struct pool *parent, const char *name) noexcept;
PoolPtr
pool_new_libc(struct pool *parent, const char *name) noexcept;
PoolPtr
pool_new_linear(struct pool *parent, const char *name,
size_t initial_size) noexcept;
PoolPtr
pool_new_slice(struct pool *parent, const char *name,
SlicePool *slice_pool) noexcept;
#ifdef NDEBUG
#define pool_set_major(pool)
#else
void
pool_set_major(struct pool *pool) noexcept;
#endif
void
pool_ref_impl(struct pool *pool TRACE_ARGS_DECL) noexcept;
#define pool_ref(pool) pool_ref_impl(pool TRACE_ARGS)
#define pool_ref_fwd(pool) pool_ref_impl(pool TRACE_ARGS_FWD)
unsigned
pool_unref_impl(struct pool *pool TRACE_ARGS_DECL) noexcept;
#define pool_unref(pool) pool_unref_impl(pool TRACE_ARGS)
#define pool_unref_fwd(pool) pool_unref_impl(pool TRACE_ARGS_FWD)
/* not implemented - just here to detect bugs */
void
pool_ref_impl(const PoolPtr &pool TRACE_ARGS_DECL) noexcept;
/* not implemented - just here to detect bugs */
void
pool_unref_impl(const PoolPtr &pool TRACE_ARGS_DECL) noexcept;
/**
* Returns the total size of all allocations in this pool.
*/
gcc_pure
size_t
pool_netto_size(const struct pool *pool) noexcept;
/**
* Returns the total amount of memory allocated by this pool.
*/
gcc_pure
size_t
pool_brutto_size(const struct pool *pool) noexcept;
/**
* Returns the total size of this pool and all of its descendants
* (recursively).
*/
gcc_pure
size_t
pool_recursive_netto_size(const struct pool *pool) noexcept;
gcc_pure
size_t
pool_recursive_brutto_size(const struct pool *pool) noexcept;
/**
* Returns the total size of all descendants of this pool (recursively).
*/
gcc_pure
size_t
pool_children_netto_size(const struct pool *pool) noexcept;
gcc_pure
size_t
pool_children_brutto_size(const struct pool *pool) noexcept;
AllocatorStats
pool_children_stats(const struct pool &pool) noexcept;
void
pool_dump_tree(const struct pool &pool) noexcept;
class ScopePoolRef {
struct pool &pool;
#ifdef TRACE
const char *const file;
unsigned line;
#endif
public:
explicit ScopePoolRef(struct pool &_pool TRACE_ARGS_DECL_) noexcept
:pool(_pool)
TRACE_ARGS_INIT
{
pool_ref_fwd(&_pool);
}
ScopePoolRef(const ScopePoolRef &) = delete;
~ScopePoolRef() noexcept {
pool_unref_fwd(&pool);
}
operator struct pool &() noexcept {
return pool;
}
operator struct pool *() noexcept {
return &pool;
}
};
#ifdef NDEBUG
static inline void
pool_trash(gcc_unused struct pool *pool) noexcept
{
}
static inline void
pool_commit() noexcept
{
}
#else
void
pool_trash(struct pool *pool) noexcept;
void
pool_commit() noexcept;
bool
pool_contains(const struct pool &pool, const void *ptr, size_t size) noexcept;
/**
* Register a #PoolLeakDetector to the pool.
*/
void
pool_register_leak_detector(struct pool &pool, PoolLeakDetector &ld) noexcept;
#endif
/**
* Free all allocations.
*/
void
pool_clear(struct pool &pool) noexcept;
gcc_malloc gcc_returns_nonnull
void *
p_malloc_impl(struct pool *pool, size_t size TYPE_ARG_DECL TRACE_ARGS_DECL) noexcept;
gcc_malloc gcc_returns_nonnull
static inline void *
p_malloc_type(struct pool &pool, size_t size TYPE_ARG_DECL) noexcept
{
return p_malloc_impl(&pool, size TYPE_ARG_FWD TRACE_ARGS);
}
#ifndef NDEBUG
gcc_malloc gcc_returns_nonnull
static inline void *
p_malloc_impl(struct pool *pool, size_t size TRACE_ARGS_DECL) noexcept
{
return p_malloc_impl(pool, size TYPE_ARG_NULL TRACE_ARGS_FWD);
}
#endif
#define p_malloc(pool, size) p_malloc_impl(pool, size TRACE_ARGS)
#define p_malloc_fwd(pool, size) p_malloc_impl(pool, size TRACE_ARGS_FWD)
void
p_free(struct pool *pool, const void *ptr, size_t size) noexcept;
gcc_malloc gcc_returns_nonnull
void *
p_memdup_impl(struct pool *pool, const void *src, size_t length
TRACE_ARGS_DECL) noexcept;
#define p_memdup(pool, src, length) p_memdup_impl(pool, src, length TRACE_ARGS)
#define p_memdup_fwd(pool, src, length) p_memdup_impl(pool, src, length TRACE_ARGS_FWD)
gcc_malloc gcc_returns_nonnull
char *
p_strdup_impl(struct pool *pool, const char *src TRACE_ARGS_DECL) noexcept;
#define p_strdup(pool, src) p_strdup_impl(pool, src TRACE_ARGS)
#define p_strdup_fwd(pool, src) p_strdup_impl(pool, src TRACE_ARGS_FWD)
static inline const char *
p_strdup_checked(struct pool *pool, const char *s) noexcept
{
return s == NULL ? NULL : p_strdup(pool, s);
}
gcc_malloc gcc_returns_nonnull
char *
p_strdup_lower_impl(struct pool *pool, const char *src
TRACE_ARGS_DECL) noexcept;
#define p_strdup_lower(pool, src) p_strdup_lower_impl(pool, src TRACE_ARGS)
#define p_strdup_lower_fwd(pool, src) p_strdup_lower_impl(pool, src TRACE_ARGS_FWD)
gcc_malloc gcc_returns_nonnull
char *
p_strndup_impl(struct pool *pool, const char *src, size_t length
TRACE_ARGS_DECL) noexcept;
#define p_strndup(pool, src, length) p_strndup_impl(pool, src, length TRACE_ARGS)
#define p_strndup_fwd(pool, src, length) p_strndup_impl(pool, src, length TRACE_ARGS_FWD)
gcc_malloc gcc_returns_nonnull
char *
p_strndup_lower_impl(struct pool *pool, const char *src, size_t length
TRACE_ARGS_DECL) noexcept;
#define p_strndup_lower(pool, src, length) p_strndup_lower_impl(pool, src, length TRACE_ARGS)
#define p_strndup_lower_fwd(pool, src, length) p_strndup_lower_impl(pool, src, length TRACE_ARGS_FWD)
gcc_malloc gcc_returns_nonnull gcc_printf(2, 3)
char *
p_sprintf(struct pool *pool, const char *fmt, ...) noexcept;
gcc_malloc gcc_returns_nonnull
char *
p_strcat(struct pool *pool, const char *s, ...) noexcept;
gcc_malloc gcc_returns_nonnull
char *
p_strncat(struct pool *pool, const char *s, size_t length, ...) noexcept;
template<typename T>
gcc_malloc gcc_returns_nonnull
T *
PoolAlloc(pool &p) noexcept
{
static_assert(std::is_trivially_default_constructible<T>::value,
"Must be trivially constructible");
return (T *)p_malloc_type(p, sizeof(T) TYPE_ARG(T));
}
template<typename T>
gcc_malloc gcc_returns_nonnull
T *
PoolAlloc(pool &p, size_t n) noexcept
{
static_assert(std::is_trivially_default_constructible<T>::value,
"Must be trivially constructible");
return (T *)p_malloc_type(p, sizeof(T) * n TYPE_ARG(T));
}
template<>
gcc_malloc gcc_returns_nonnull
inline void *
PoolAlloc<void>(pool &p, size_t n) noexcept
{
return p_malloc(&p, n);
}
template<typename T, typename... Args>
gcc_malloc gcc_returns_nonnull
T *
NewFromPool(pool &p, Args&&... args)
{
void *t = p_malloc_type(p, sizeof(T) TYPE_ARG(T));
return ::new(t) T(std::forward<Args>(args)...);
}
template<typename T>
void
DeleteFromPool(struct pool &pool, T *t) noexcept
{
t->~T();
p_free(&pool, t, sizeof(*t));
}
/**
* A disposer for boost::intrusive that invokes the DeleteFromPool()
* on the given pointer.
*/
class PoolDisposer {
struct pool &p;
public:
explicit PoolDisposer(struct pool &_p) noexcept:p(_p) {}
template<typename T>
void operator()(T *t) noexcept {
DeleteFromPool(p, t);
}
};
/**
* An overload without a pool; this one cannot free memory
* (pool_new_libc() only) and has no assertions, but it calls the
* object's destructor. It can sometimes be useful to destruct
* objects which don't have a pointer to the pool they were allocated
* from.
*/
template<typename T>
void
DeleteFromPool(T *t) noexcept
{
t->~T();
}
/**
* Like #PoolDisposer, but calls the DeleteFromPool() overload without
* a pool parameter.
*/
class NoPoolDisposer {
public:
template<typename T>
void operator()(T *t) noexcept {
DeleteFromPool(t);
}
};
gcc_malloc gcc_returns_nonnull
char *
p_strdup_impl(struct pool &pool, StringView src TRACE_ARGS_DECL) noexcept;
gcc_malloc gcc_returns_nonnull
char *
p_strdup_lower_impl(struct pool &pool, StringView src
TRACE_ARGS_DECL) noexcept;
/**
* Concatenate all strings and return a newly allocated
* null-terminated string.
*/
char *
StringConcat(struct pool &pool, ConstBuffer<StringView> src) noexcept;
#endif
<|endoftext|> |
<commit_before>#include <RGBLed.h>
#include <Backlight.h>
#include <AdapterBoard.h>
#include <Arduino.h>
#include "usb_commands.h"
AdapterBoard::AdapterBoard()
{
}
void AdapterBoard::init()
{
//Initialize the led, set to 'standby'
led.init(LED_R, LED_G, LED_B);
led.set(STANDBY_COLOUR);
//Setup backlight, restore previous brightness, but don't enable
backlight.init(BACKLIGHT_PIN, SUPPLY_EN);
backlight.setLast();
//Initialize the switches on board
initSwitches();
}
void AdapterBoard::poll()
{
//Check the switches, execute action if necessary
pollSwitches();
//Handle any USB commands waiting
handleUSB();
}
void AdapterBoard::initSwitches()
{
pinMode(SW_ON, INPUT);
pinMode(SW_UP, INPUT);
pinMode(SW_DOWN, INPUT);
prev_swOn = HIGH;
prev_swUp = HIGH;
prev_swDown = HIGH;
switchDelay = 0;
}
void AdapterBoard::pollSwitches()
{
//Ignore a few polls
if(switchDelay++ < 100000)
return;
int swOn = digitalRead(SW_ON);
int swUp = digitalRead(SW_UP);
int swDown = digitalRead(SW_DOWN);
if(swOn == LOW && prev_swOn == HIGH)
togglePower();
//When both pressed, backlight up button has priority
if(swUp == LOW && prev_swUp == HIGH)
backlight.up();
if(swDown == LOW && prev_swDown == HIGH)
backlight.down();
prev_swOn = swOn;
prev_swUp = swUp;
prev_swDown = swDown;
}
void AdapterBoard::togglePower()
{
if(backlight.isOn())
{
backlight.off();
led.set(STANDBY_COLOUR);
}
else
{
led.set(ON_COLOUR);
backlight.setLast();
backlight.on();
}
}
char buf[EP_LEN];
void AdapterBoard::handleUSB()
{
if(usb.isEnumerated())
{
if(usb.hasData())
{
char resp[EP_LEN];
bool unknown = false;
bool needsAck = true;
usb.read(buf, EP_LEN);
//Command type specifier stored in byte 0
switch(buf[0])
{
case CMD_BL_ON:
led.set(ON_COLOUR);
backlight.on();
break;
case CMD_BL_OFF:
backlight.off();
led.set(STANDBY_COLOUR);
break;
case CMD_BL_LEVEL:
backlight.set(buf[1]);
break;
case CMD_BL_UP:
backlight.up();
break;
case CMD_BL_DOWN:
backlight.down();
break;
case CMD_BL_GET_STATE:
needsAck = false;
//Send state response
resp[0] = CMD_RESP;
resp[1] = CMD_BL_GET_STATE;
resp[2] = backlight.isOn();
resp[3] = backlight.get();
while(!usb.canSend());
usb.write(resp, EP_LEN);
break;
case CMD_RGB_SET:
led.set(buf[1], buf[2], buf[3]);
break;
case CMD_RGB_GET:
needsAck = false;
//Send response
resp[0] = CMD_RESP;
resp[1] = CMD_RGB_GET;
resp[2] = led.r;
resp[2] = led.g;
resp[3] = led.b;
while(!usb.canSend());
usb.write(resp, EP_LEN);
break;
default:
unknown = true;
break;
}
if(!unknown && needsAck)
{
//Send ACK back to PC
resp[0] = CMD_ACK;
resp[1] = buf[0];
while(!usb.canSend());
usb.write(resp, EP_LEN);
}
}
}
}
<commit_msg>Increase button delay by 5x<commit_after>#include <RGBLed.h>
#include <Backlight.h>
#include <AdapterBoard.h>
#include <Arduino.h>
#include "usb_commands.h"
AdapterBoard::AdapterBoard()
{
}
void AdapterBoard::init()
{
//Initialize the led, set to 'standby'
led.init(LED_R, LED_G, LED_B);
led.set(STANDBY_COLOUR);
//Setup backlight, restore previous brightness, but don't enable
backlight.init(BACKLIGHT_PIN, SUPPLY_EN);
backlight.setLast();
//Initialize the switches on board
initSwitches();
}
void AdapterBoard::poll()
{
//Check the switches, execute action if necessary
pollSwitches();
//Handle any USB commands waiting
handleUSB();
}
void AdapterBoard::initSwitches()
{
pinMode(SW_ON, INPUT);
pinMode(SW_UP, INPUT);
pinMode(SW_DOWN, INPUT);
prev_swOn = HIGH;
prev_swUp = HIGH;
prev_swDown = HIGH;
switchDelay = 0;
}
void AdapterBoard::pollSwitches()
{
//Ignore a few polls
if(switchDelay++ < 500000)
return;
int swOn = digitalRead(SW_ON);
int swUp = digitalRead(SW_UP);
int swDown = digitalRead(SW_DOWN);
if(swOn == LOW && prev_swOn == HIGH)
togglePower();
//When both pressed, backlight up button has priority
if(swUp == LOW && prev_swUp == HIGH)
backlight.up();
if(swDown == LOW && prev_swDown == HIGH)
backlight.down();
prev_swOn = swOn;
prev_swUp = swUp;
prev_swDown = swDown;
}
void AdapterBoard::togglePower()
{
if(backlight.isOn())
{
backlight.off();
led.set(STANDBY_COLOUR);
}
else
{
led.set(ON_COLOUR);
backlight.setLast();
backlight.on();
}
}
char buf[EP_LEN];
void AdapterBoard::handleUSB()
{
if(usb.isEnumerated())
{
if(usb.hasData())
{
char resp[EP_LEN];
bool unknown = false;
bool needsAck = true;
usb.read(buf, EP_LEN);
//Command type specifier stored in byte 0
switch(buf[0])
{
case CMD_BL_ON:
led.set(ON_COLOUR);
backlight.on();
break;
case CMD_BL_OFF:
backlight.off();
led.set(STANDBY_COLOUR);
break;
case CMD_BL_LEVEL:
backlight.set(buf[1]);
break;
case CMD_BL_UP:
backlight.up();
break;
case CMD_BL_DOWN:
backlight.down();
break;
case CMD_BL_GET_STATE:
needsAck = false;
//Send state response
resp[0] = CMD_RESP;
resp[1] = CMD_BL_GET_STATE;
resp[2] = backlight.isOn();
resp[3] = backlight.get();
while(!usb.canSend());
usb.write(resp, EP_LEN);
break;
case CMD_RGB_SET:
led.set(buf[1], buf[2], buf[3]);
break;
case CMD_RGB_GET:
needsAck = false;
//Send response
resp[0] = CMD_RESP;
resp[1] = CMD_RGB_GET;
resp[2] = led.r;
resp[2] = led.g;
resp[3] = led.b;
while(!usb.canSend());
usb.write(resp, EP_LEN);
break;
default:
unknown = true;
break;
}
if(!unknown && needsAck)
{
//Send ACK back to PC
resp[0] = CMD_ACK;
resp[1] = buf[0];
while(!usb.canSend());
usb.write(resp, EP_LEN);
}
}
}
}
<|endoftext|> |
<commit_before>#include "helix/order_book.hh"
#include <boost/version.hpp>
#include <stdexcept>
#include <limits>
using namespace std;
namespace helix {
execution::execution(uint64_t price, side_type side, uint64_t remaining)
: price{price}
, side{side}
, remaining{remaining}
{
}
order_book::order_book(std::string symbol, uint64_t timestamp, size_t max_orders)
: _symbol{std::move(symbol)}
, _timestamp{timestamp}
, _state{trading_state::unknown}
{
#if BOOST_VERSION >= 105600
_orders.reserve(max_orders);
#endif
}
void order_book::add(order order)
{
switch (order.side) {
case side_type::buy: {
auto&& level = lookup_or_create(_bids, order.price);
order.level = &level;
level.size += order.quantity;
break;
}
case side_type::sell: {
auto&& level = lookup_or_create(_asks, order.price);
order.level = &level;
level.size += order.quantity;
break;
}
default:
throw invalid_argument(string("invalid side: ") + static_cast<char>(order.side));
}
_orders.emplace(std::move(order));
}
void order_book::replace(uint64_t order_id, order order)
{
remove(order_id);
add(std::move(order));
}
void order_book::cancel(uint64_t order_id, uint64_t quantity)
{
auto it = _orders.find(order_id);
if (it == _orders.end()) {
throw invalid_argument(string("invalid order id: ") + to_string(order_id));
}
_orders.modify(it, [quantity](order& order) {
order.quantity -= quantity;
order.level->size -= quantity;
});
if (!it->quantity) {
remove(it);
}
}
execution order_book::execute(uint64_t order_id, uint64_t quantity)
{
auto it = _orders.find(order_id);
if (it == _orders.end()) {
throw invalid_argument(string("invalid order id: ") + to_string(order_id));
}
_orders.modify(it, [quantity](order& order) {
order.quantity -= quantity;
order.level->size -= quantity;
});
auto result = execution(it->price, it->side, it->level->size);
if (!it->quantity) {
remove(it);
}
return result;
}
void order_book::remove(uint64_t order_id)
{
auto it = _orders.find(order_id);
if (it == _orders.end()) {
throw invalid_argument(string("invalid order id: ") + to_string(order_id));
}
remove(it);
}
void order_book::remove(iterator& iter)
{
auto && order = *iter;
switch (order.side) {
case side_type::buy: {
remove(order, _bids);
break;
}
case side_type::sell: {
remove(order, _asks);
break;
}
default:
throw invalid_argument(string("invalid side: ") + static_cast<char>(order.side));
}
_orders.erase(iter);
}
template<typename T>
void order_book::remove(const order& o, T& levels)
{
auto it = levels.find(o.price);
if (it == levels.end()) {
throw invalid_argument(string("invalid price: ") + to_string(o.price));
}
auto&& level = it->second;
o.level->size -= o.quantity;
if (level.size == 0) {
levels.erase(it);
}
}
template<typename T>
price_level& order_book::lookup_or_create(T& levels, uint64_t price)
{
auto it = levels.find(price);
if (it != levels.end()) {
return it->second;
}
price_level level{price};
levels.emplace(price, level);
it = levels.find(price);
return it->second;
}
side_type order_book::side(uint64_t order_id) const
{
auto it = _orders.find(order_id);
if (it == _orders.end()) {
throw invalid_argument(string("invalid order id: ") + to_string(order_id));
}
return it->side;
}
size_t order_book::bid_levels() const
{
return _bids.size();
}
size_t order_book::ask_levels() const
{
return _asks.size();
}
size_t order_book::order_count() const
{
return _orders.size();
}
uint64_t order_book::bid_price(size_t level) const
{
auto it = _bids.begin();
while (it != _bids.end() && level--) {
it++;
}
if (it != _bids.end()) {
auto&& level = it->second;
return level.price;
}
return std::numeric_limits<uint64_t>::min();
}
uint64_t order_book::bid_size(size_t level) const
{
auto it = _bids.begin();
while (it != _bids.end() && level--) {
it++;
}
if (it != _bids.end()) {
auto&& level = it->second;
return level.size;
}
return 0;
}
uint64_t order_book::ask_price(size_t level) const
{
auto it = _asks.begin();
while (it != _asks.end() && level--) {
it++;
}
if (it != _asks.end()) {
auto&& level = it->second;
return level.price;
}
return std::numeric_limits<uint64_t>::max();
}
uint64_t order_book::ask_size(size_t level) const
{
auto it = _asks.begin();
while (it != _asks.end() && level--) {
it++;
}
if (it != _asks.end()) {
auto&& level = it->second;
return level.size;
}
return 0;
}
uint64_t order_book::midprice(size_t level) const
{
auto bid = bid_price(level);
auto ask = ask_price(level);
return (bid + ask) / 2;
}
}
<commit_msg>Clean up namespace import in order_book.cc<commit_after>#include "helix/order_book.hh"
#include <boost/version.hpp>
#include <stdexcept>
#include <limits>
namespace helix {
execution::execution(uint64_t price, side_type side, uint64_t remaining)
: price{price}
, side{side}
, remaining{remaining}
{
}
order_book::order_book(std::string symbol, uint64_t timestamp, size_t max_orders)
: _symbol{std::move(symbol)}
, _timestamp{timestamp}
, _state{trading_state::unknown}
{
#if BOOST_VERSION >= 105600
_orders.reserve(max_orders);
#endif
}
void order_book::add(order order)
{
switch (order.side) {
case side_type::buy: {
auto&& level = lookup_or_create(_bids, order.price);
order.level = &level;
level.size += order.quantity;
break;
}
case side_type::sell: {
auto&& level = lookup_or_create(_asks, order.price);
order.level = &level;
level.size += order.quantity;
break;
}
default:
throw std::invalid_argument(std::string("invalid side: ") + static_cast<char>(order.side));
}
_orders.emplace(std::move(order));
}
void order_book::replace(uint64_t order_id, order order)
{
remove(order_id);
add(std::move(order));
}
void order_book::cancel(uint64_t order_id, uint64_t quantity)
{
auto it = _orders.find(order_id);
if (it == _orders.end()) {
throw std::invalid_argument(std::string("invalid order id: ") + std::to_string(order_id));
}
_orders.modify(it, [quantity](order& order) {
order.quantity -= quantity;
order.level->size -= quantity;
});
if (!it->quantity) {
remove(it);
}
}
execution order_book::execute(uint64_t order_id, uint64_t quantity)
{
auto it = _orders.find(order_id);
if (it == _orders.end()) {
throw std::invalid_argument(std::string("invalid order id: ") + std::to_string(order_id));
}
_orders.modify(it, [quantity](order& order) {
order.quantity -= quantity;
order.level->size -= quantity;
});
auto result = execution(it->price, it->side, it->level->size);
if (!it->quantity) {
remove(it);
}
return result;
}
void order_book::remove(uint64_t order_id)
{
auto it = _orders.find(order_id);
if (it == _orders.end()) {
throw std::invalid_argument(std::string("invalid order id: ") + std::to_string(order_id));
}
remove(it);
}
void order_book::remove(iterator& iter)
{
auto && order = *iter;
switch (order.side) {
case side_type::buy: {
remove(order, _bids);
break;
}
case side_type::sell: {
remove(order, _asks);
break;
}
default:
throw std::invalid_argument(std::string("invalid side: ") + static_cast<char>(order.side));
}
_orders.erase(iter);
}
template<typename T>
void order_book::remove(const order& o, T& levels)
{
auto it = levels.find(o.price);
if (it == levels.end()) {
throw std::invalid_argument(std::string("invalid price: ") + std::to_string(o.price));
}
auto&& level = it->second;
o.level->size -= o.quantity;
if (level.size == 0) {
levels.erase(it);
}
}
template<typename T>
price_level& order_book::lookup_or_create(T& levels, uint64_t price)
{
auto it = levels.find(price);
if (it != levels.end()) {
return it->second;
}
price_level level{price};
levels.emplace(price, level);
it = levels.find(price);
return it->second;
}
side_type order_book::side(uint64_t order_id) const
{
auto it = _orders.find(order_id);
if (it == _orders.end()) {
throw std::invalid_argument(std::string("invalid order id: ") + std::to_string(order_id));
}
return it->side;
}
size_t order_book::bid_levels() const
{
return _bids.size();
}
size_t order_book::ask_levels() const
{
return _asks.size();
}
size_t order_book::order_count() const
{
return _orders.size();
}
uint64_t order_book::bid_price(size_t level) const
{
auto it = _bids.begin();
while (it != _bids.end() && level--) {
it++;
}
if (it != _bids.end()) {
auto&& level = it->second;
return level.price;
}
return std::numeric_limits<uint64_t>::min();
}
uint64_t order_book::bid_size(size_t level) const
{
auto it = _bids.begin();
while (it != _bids.end() && level--) {
it++;
}
if (it != _bids.end()) {
auto&& level = it->second;
return level.size;
}
return 0;
}
uint64_t order_book::ask_price(size_t level) const
{
auto it = _asks.begin();
while (it != _asks.end() && level--) {
it++;
}
if (it != _asks.end()) {
auto&& level = it->second;
return level.price;
}
return std::numeric_limits<uint64_t>::max();
}
uint64_t order_book::ask_size(size_t level) const
{
auto it = _asks.begin();
while (it != _asks.end() && level--) {
it++;
}
if (it != _asks.end()) {
auto&& level = it->second;
return level.size;
}
return 0;
}
uint64_t order_book::midprice(size_t level) const
{
auto bid = bid_price(level);
auto ask = ask_price(level);
return (bid + ask) / 2;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/parse_url.hpp"
namespace libtorrent
{
// returns protocol, auth, hostname, port, path, error
boost::tuple<std::string, std::string, std::string, int, std::string, char const*>
parse_url_components(std::string url)
{
std::string hostname; // hostname only
std::string auth; // user:pass
std::string protocol; // http or https for instance
char const* error = 0;
int port = 80;
std::string::iterator at;
std::string::iterator colon;
std::string::iterator port_pos;
// PARSE URL
std::string::iterator start = url.begin();
// remove white spaces in front of the url
while (start != url.end() && (*start == ' ' || *start == '\t'))
++start;
std::string::iterator end
= std::find(url.begin(), url.end(), ':');
protocol.assign(start, end);
if (protocol == "https") port = 443;
if (end == url.end())
{
error = "no protocol in url";
goto exit;
}
++end;
if (end == url.end() || *end != '/')
{
error = "incomplete protocol";
goto exit;
}
++end;
if (end == url.end() || *end != '/')
{
error = "incomplete protocol";
goto exit;
}
++end;
start = end;
at = std::find(start, url.end(), '@');
colon = std::find(start, url.end(), ':');
end = std::find(start, url.end(), '/');
if (at != url.end()
&& colon != url.end()
&& colon < at
&& at < end)
{
auth.assign(start, at);
start = at;
++start;
}
// this is for IPv6 addresses
if (start != url.end() && *start == '[')
{
port_pos = std::find(start, url.end(), ']');
if (port_pos == url.end())
{
error = "expected closing ']' for address";
goto exit;
}
port_pos = std::find(port_pos, url.end(), ':');
}
else
{
port_pos = std::find(start, url.end(), ':');
}
if (port_pos < end)
{
hostname.assign(start, port_pos);
++port_pos;
port = atoi(std::string(port_pos, end).c_str());
}
else
{
hostname.assign(start, end);
}
start = end;
exit:
return boost::make_tuple(protocol, auth, hostname, port
, std::string(start, url.end()), error);
}
}
<commit_msg>added missing include<commit_after>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/parse_url.hpp"
#include <algorithm>
namespace libtorrent
{
// returns protocol, auth, hostname, port, path, error
boost::tuple<std::string, std::string, std::string, int, std::string, char const*>
parse_url_components(std::string url)
{
std::string hostname; // hostname only
std::string auth; // user:pass
std::string protocol; // http or https for instance
char const* error = 0;
int port = 80;
std::string::iterator at;
std::string::iterator colon;
std::string::iterator port_pos;
// PARSE URL
std::string::iterator start = url.begin();
// remove white spaces in front of the url
while (start != url.end() && (*start == ' ' || *start == '\t'))
++start;
std::string::iterator end
= std::find(url.begin(), url.end(), ':');
protocol.assign(start, end);
if (protocol == "https") port = 443;
if (end == url.end())
{
error = "no protocol in url";
goto exit;
}
++end;
if (end == url.end() || *end != '/')
{
error = "incomplete protocol";
goto exit;
}
++end;
if (end == url.end() || *end != '/')
{
error = "incomplete protocol";
goto exit;
}
++end;
start = end;
at = std::find(start, url.end(), '@');
colon = std::find(start, url.end(), ':');
end = std::find(start, url.end(), '/');
if (at != url.end()
&& colon != url.end()
&& colon < at
&& at < end)
{
auth.assign(start, at);
start = at;
++start;
}
// this is for IPv6 addresses
if (start != url.end() && *start == '[')
{
port_pos = std::find(start, url.end(), ']');
if (port_pos == url.end())
{
error = "expected closing ']' for address";
goto exit;
}
port_pos = std::find(port_pos, url.end(), ':');
}
else
{
port_pos = std::find(start, url.end(), ':');
}
if (port_pos < end)
{
hostname.assign(start, port_pos);
++port_pos;
port = atoi(std::string(port_pos, end).c_str());
}
else
{
hostname.assign(start, end);
}
start = end;
exit:
return boost::make_tuple(protocol, auth, hostname, port
, std::string(start, url.end()), error);
}
}
<|endoftext|> |
<commit_before>#include "propimage.h"
#include "proploader.h"
PropImage::PropImage()
: m_imageData(NULL)
{
}
PropImage::PropImage(uint8_t *imageData, int imageSize)
: m_imageData(NULL)
{
setImage(imageData, imageSize);
}
PropImage::~PropImage()
{
}
void PropImage::setImage(uint8_t *imageData, int imageSize)
{
m_imageData = imageData;
m_imageSize = imageSize;
}
uint32_t PropImage::clkFreq()
{
return getLong((uint8_t *)&((SpinHdr *)m_imageData)->clkfreq);
}
void PropImage::setClkFreq(uint32_t clkFreq)
{
setLong((uint8_t *)&((SpinHdr *)m_imageData)->clkfreq, clkFreq);
}
uint8_t PropImage::clkMode()
{
return *(uint8_t *)&((SpinHdr *)m_imageData)->clkfreq;
}
void PropImage::setClkMode(uint8_t clkMode)
{
*(uint8_t *)&((SpinHdr *)m_imageData)->clkfreq = clkMode;
}
int PropImage::validate()
{
// make sure the image is at least the size of a Spin header
if (m_imageSize < (int)sizeof(SpinHdr))
return IMAGE_TRUNCATED;
// verify the checksum
uint8_t *p = m_imageData;
uint8_t chksum = SPIN_STACK_FRAME_CHECKSUM;
for (int cnt = m_imageSize; --cnt >= 0; )
chksum += *p++;
if (chksum != 0)
return IMAGE_CORRUPTED;
// make sure there is no data after the code
SpinHdr *hdr = (SpinHdr *)m_imageData;
uint16_t idx = hdr->vbase;
while (idx < m_imageSize && idx < hdr->dbase && m_imageData[idx] == 0)
++idx;
if (idx < m_imageSize)
return IMAGE_CORRUPTED;
// image is okay
return 0;
}
int PropImage::validate(uint8_t *imageData, int imageSize)
{
PropImage image(imageData, imageSize);
return image.validate();
}
void PropImage::updateChecksum()
{
SpinHdr *spinHdr = (SpinHdr *)m_imageData;
uint8_t *p = m_imageData;
uint8_t chksum;
int cnt;
spinHdr->chksum = 0;
chksum = SPIN_STACK_FRAME_CHECKSUM;
for (cnt = m_imageSize; --cnt >= 0; )
chksum += *p++;
spinHdr->chksum = -chksum;
}
void PropImage::updateChecksum(uint8_t *imageData, int imageSize)
{
PropImage image(imageData, imageSize);
image.updateChecksum();
}
uint16_t PropImage::getWord(const uint8_t *buf)
{
return (buf[1] << 8) | buf[0];
}
void PropImage::setWord(uint8_t *buf, uint16_t value)
{
buf[1] = value >> 8;
buf[0] = value;
}
uint32_t PropImage::getLong(const uint8_t *buf)
{
return (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0];
}
void PropImage::setLong(uint8_t *buf, uint32_t value)
{
buf[3] = value >> 24;
buf[2] = value >> 16;
buf[1] = value >> 8;
buf[0] = value;
}
<commit_msg>Fix the image validation code.<commit_after>#include "propimage.h"
#include "proploader.h"
PropImage::PropImage()
: m_imageData(NULL)
{
}
PropImage::PropImage(uint8_t *imageData, int imageSize)
: m_imageData(NULL)
{
setImage(imageData, imageSize);
}
PropImage::~PropImage()
{
}
void PropImage::setImage(uint8_t *imageData, int imageSize)
{
m_imageData = imageData;
m_imageSize = imageSize;
}
uint32_t PropImage::clkFreq()
{
return getLong((uint8_t *)&((SpinHdr *)m_imageData)->clkfreq);
}
void PropImage::setClkFreq(uint32_t clkFreq)
{
setLong((uint8_t *)&((SpinHdr *)m_imageData)->clkfreq, clkFreq);
}
uint8_t PropImage::clkMode()
{
return *(uint8_t *)&((SpinHdr *)m_imageData)->clkfreq;
}
void PropImage::setClkMode(uint8_t clkMode)
{
*(uint8_t *)&((SpinHdr *)m_imageData)->clkfreq = clkMode;
}
int PropImage::validate()
{
// make sure the image is at least the size of a Spin header
if (m_imageSize <= (int)sizeof(SpinHdr))
return IMAGE_TRUNCATED;
// verify the checksum
uint8_t *p = m_imageData;
uint8_t chksum = SPIN_STACK_FRAME_CHECKSUM;
for (int cnt = m_imageSize; --cnt >= 0; )
chksum += *p++;
if (chksum != 0)
return IMAGE_CORRUPTED;
// make sure there is no data after the code
SpinHdr *hdr = (SpinHdr *)m_imageData;
uint16_t idx = hdr->vbase;
while (idx < m_imageSize && idx < hdr->dbase && m_imageData[idx] == 0)
++idx;
if (idx < m_imageSize)
return IMAGE_CORRUPTED;
// image is okay
return 0;
}
int PropImage::validate(uint8_t *imageData, int imageSize)
{
PropImage image(imageData, imageSize);
return image.validate();
}
void PropImage::updateChecksum()
{
SpinHdr *spinHdr = (SpinHdr *)m_imageData;
uint8_t *p = m_imageData;
uint8_t chksum;
int cnt;
spinHdr->chksum = 0;
chksum = SPIN_STACK_FRAME_CHECKSUM;
for (cnt = m_imageSize; --cnt >= 0; )
chksum += *p++;
spinHdr->chksum = -chksum;
}
void PropImage::updateChecksum(uint8_t *imageData, int imageSize)
{
PropImage image(imageData, imageSize);
image.updateChecksum();
}
uint16_t PropImage::getWord(const uint8_t *buf)
{
return (buf[1] << 8) | buf[0];
}
void PropImage::setWord(uint8_t *buf, uint16_t value)
{
buf[1] = value >> 8;
buf[0] = value;
}
uint32_t PropImage::getLong(const uint8_t *buf)
{
return (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0];
}
void PropImage::setLong(uint8_t *buf, uint32_t value)
{
buf[3] = value >> 24;
buf[2] = value >> 16;
buf[1] = value >> 8;
buf[0] = value;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.