text
stringlengths 54
60.6k
|
|---|
<commit_before>/****************************************************************************
** Copyright (C) 2001-2006 Klarälvdalens Datakonsult AB. All rights reserved.
**
** This file is part of the KD Gantt library.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid commercial KD Gantt licenses may use this file in
** accordance with the KD Gantt Commercial License Agreement provided with
** the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.kdab.net/kdgantt for
** information about KD Gantt Commercial License Agreements.
**
** Contact info@kdab.net if any conditions of this
** licensing are not clear to you.
**
**********************************************************************/
#include "kdganttdatetimegrid.h"
#include "kdganttdatetimegrid_p.h"
#include "kdganttabstractrowcontroller.h"
#include <QApplication>
#include <QDateTime>
#include <QPainter>
#include <QStyle>
#include <QStyleOptionHeader>
#include <QWidget>
#include <QDebug>
#include <cassert>
using namespace KDGantt;
/*!\class KDGantt::DateTimeGrid
* \ingroup KDGantt
*
* This implementation of AbstractGrid works with QDateTime
* and shows days and week numbers in the header
*
* \todo Extend to work with hours, minutes,... as units too.
*/
// TODO: I think maybe this class should be responsible
// for unit-transformation of the scene...
qreal DateTimeGrid::Private::dateTimeToChartX( const QDateTime& dt ) const
{
assert( startDateTime.isValid() );
qreal result = startDateTime.date().daysTo(dt.date())*24.*60.*60.;
result += startDateTime.time().msecsTo(dt.time())/1000.;
result *= dayWidth/( 24.*60.*60. );
return result;
}
QDateTime DateTimeGrid::Private::chartXtoDateTime( qreal x ) const
{
// TODO
assert( startDateTime.isValid() );
int days = static_cast<int>( x/dayWidth );
qreal secs = x*( 24.*60.*60. )/dayWidth;
QDateTime dt = startDateTime;
QDateTime result = dt.addDays( days ).addSecs( qRound(secs-(days*24.*60.*60.) ) );
return result;
}
#define d d_func()
DateTimeGrid::DateTimeGrid() : AbstractGrid( new Private )
{
}
DateTimeGrid::~DateTimeGrid()
{
}
QDateTime DateTimeGrid::startDateTime() const
{
return d->startDateTime;
}
void DateTimeGrid::setStartDateTime( const QDateTime& dt )
{
d->startDateTime = dt;
emit gridChanged();
}
qreal DateTimeGrid::dayWidth() const
{
return d->dayWidth;
}
void DateTimeGrid::setDayWidth( qreal w )
{
d->dayWidth = w;
emit gridChanged();
}
void DateTimeGrid::setScale( Scale s )
{
d->scale = s;
emit gridChanged();
}
DateTimeGrid::Scale DateTimeGrid::scale() const
{
return d->scale;
}
void DateTimeGrid::setWeekStart( Qt::DayOfWeek ws )
{
d->weekStart = ws;
emit gridChanged();
}
Qt::DayOfWeek DateTimeGrid::weekStart() const
{
return d->weekStart;
}
void DateTimeGrid::setFreeDays( const QSet<Qt::DayOfWeek>& fd )
{
d->freeDays = fd;
emit gridChanged();
}
QSet<Qt::DayOfWeek> DateTimeGrid::freeDays() const
{
return d->freeDays;
}
bool DateTimeGrid::rowSeparators() const
{
return d->rowSeparators;
}
void DateTimeGrid::setRowSeparators( bool enable )
{
d->rowSeparators = enable;
}
Span DateTimeGrid::mapToChart( const QModelIndex& idx ) const
{
assert( model() );
if ( !idx.isValid() ) return Span();
assert( idx.model()==model() );
const QVariant sv = model()->data( idx, StartTimeRole );
const QVariant ev = model()->data( idx, EndTimeRole );
if( qVariantCanConvert<QDateTime>(sv) &&
qVariantCanConvert<QDateTime>(ev) &&
!(sv.type() == QVariant::String && qVariantValue<QString>(sv).isEmpty()) &&
!(ev.type() == QVariant::String && qVariantValue<QString>(ev).isEmpty())
) {
QDateTime st = sv.toDateTime();
QDateTime et = ev.toDateTime();
if ( et.isValid() && st.isValid() ) {
qreal sx = d->dateTimeToChartX( st );
qreal ex = d->dateTimeToChartX( et )-sx;
return Span( sx, ex);
}
}
return Span();
}
static void debug_print_idx( const QModelIndex& idx )
{
if ( !idx.isValid() ) {
qDebug() << "[Invalid]";
return;
}
QDateTime st = idx.data( StartTimeRole ).toDateTime();
QDateTime et = idx.data( StartTimeRole ).toDateTime();
qDebug() << idx << "["<<st<<et<<"]";
}
bool DateTimeGrid::mapFromChart( const Span& span, const QModelIndex& idx,
const QList<Constraint>& constraints ) const
{
assert( model() );
if ( !idx.isValid() ) return false;
assert( idx.model()==model() );
QDateTime st = d->chartXtoDateTime(span.start());
QDateTime et = d->chartXtoDateTime(span.start()+span.length());
Q_FOREACH( const Constraint& c, constraints ) {
if ( c.type() != Constraint::TypeHard || !isSatisfiedConstraint( c )) continue;
if ( c.startIndex() == idx ) {
QDateTime tmpst = model()->data( c.endIndex(), StartTimeRole ).toDateTime();
//qDebug() << tmpst << "<" << et <<"?";
if ( tmpst<et ) return false;
} else if ( c.endIndex() == idx ) {
QDateTime tmpet = model()->data( c.startIndex(), EndTimeRole ).toDateTime();
//qDebug() << tmpet << ">" << st <<"?";
if ( tmpet>st ) return false;
}
}
return model()->setData( idx, qVariantFromValue(st), StartTimeRole )
&& model()->setData( idx, qVariantFromValue(et), EndTimeRole );
}
void DateTimeGrid::paintGrid( QPainter* painter,
const QRectF& sceneRect,
const QRectF& exposedRect,
AbstractRowController* rowController,
QWidget* widget )
{
// TODO: Support hours
QDateTime dt = d->chartXtoDateTime( exposedRect.left() );
dt.setTime( QTime( 0, 0, 0, 0 ) );
for ( qreal x = d->dateTimeToChartX( dt ); x < exposedRect.right();
dt = dt.addDays( 1 ),x=d->dateTimeToChartX( dt ) ) {
QPen pen = painter->pen();
pen.setBrush( QApplication::palette().dark() );
if ( dt.date().dayOfWeek() == d->weekStart ) {
pen.setStyle( Qt::SolidLine );
} else {
pen.setStyle( Qt::DashLine );
}
painter->setPen( pen );
if ( d->freeDays.contains( static_cast<Qt::DayOfWeek>( dt.date().dayOfWeek() ) ) ) {
painter->setBrush( widget?widget->palette().alternateBase()
:QApplication::palette().alternateBase() );
painter->fillRect( QRectF( x, exposedRect.top(), dayWidth(), exposedRect.height() ), painter->brush() );
}
painter->drawLine( QPointF( x, sceneRect.top() ), QPointF( x, sceneRect.bottom() ) );
}
if ( rowController && d->rowSeparators ) {
// First draw the rows
QPen pen = painter->pen();
pen.setBrush( QApplication::palette().dark() );
pen.setStyle( Qt::DashLine );
painter->setPen( pen );
QModelIndex idx = rowController->indexAt( qRound( exposedRect.top() ) );
qreal y = 0;
while ( y < exposedRect.bottom() && idx.isValid() ) {
const Span s = rowController->rowGeometry( idx );
y = s.start()+s.length();
painter->drawLine( QPointF( sceneRect.left(), y ),
QPointF( sceneRect.right(), y ) );
// Is alternating background better?
//if ( idx.row()%2 ) painter->fillRect( QRectF( exposedRect.x(), s.start(), exposedRect.width(), s.length() ), QApplication::palette().alternateBase() );
idx = rowController->indexBelow( idx );
}
}
}
void DateTimeGrid::paintHeader( QPainter* painter, const QRectF& headerRect, const QRectF& exposedRect,
qreal offset, QWidget* widget )
{
switch(scale()) {
case ScaleHour: paintHourScaleHeader(painter,headerRect,exposedRect,offset,widget); break;
case ScaleDay: paintDayScaleHeader(painter,headerRect,exposedRect,offset,widget); break;
case ScaleAuto:
if(dayWidth()>500) paintHourScaleHeader(painter,headerRect,exposedRect,offset,widget);
else paintDayScaleHeader(painter,headerRect,exposedRect,offset,widget);
break;
}
}
void DateTimeGrid::paintHourScaleHeader( QPainter* painter, const QRectF& headerRect, const QRectF& exposedRect,
qreal offset, QWidget* widget )
{
QStyle* style = widget?widget->style():QApplication::style();
// Paint a section for each hour
QDateTime dt = d->chartXtoDateTime( offset+exposedRect.left() );
dt.setTime( QTime( dt.time().hour(), 0, 0, 0 ) );
for ( qreal x = d->dateTimeToChartX( dt ); x < exposedRect.right()+offset;
dt = dt.addSecs( 60*60 /*1 hour*/ ),x=d->dateTimeToChartX( dt ) ) {
QStyleOptionHeader opt;
opt.init( widget );
opt.rect = QRectF( x-offset, headerRect.top()+headerRect.height()/2., dayWidth()/24., headerRect.height()/2. ).toRect();
opt.text = dt.time().toString( QString::fromAscii( "hh" ) );
opt.textAlignment = Qt::AlignCenter;
style->drawControl(QStyle::CE_Header, &opt, painter, widget);
}
dt = d->chartXtoDateTime( offset+exposedRect.left() );
dt.setTime( QTime( 0, 0, 0, 0 ) );
// Paint a section for each day
for ( qreal x2 = d->dateTimeToChartX( dt ); x2 < exposedRect.right()+offset;
dt = dt.addDays( 1 ),x2=d->dateTimeToChartX( dt ) ) {
QStyleOptionHeader opt;
opt.init( widget );
opt.rect = QRectF( x2-offset, headerRect.top(), dayWidth(), headerRect.height()/2. ).toRect();
opt.text = QString::number( dt.date().weekNumber() );
opt.textAlignment = Qt::AlignCenter;
style->drawControl(QStyle::CE_Header, &opt, painter, widget);
}
}
void DateTimeGrid::paintDayScaleHeader( QPainter* painter, const QRectF& headerRect, const QRectF& exposedRect,
qreal offset, QWidget* widget )
{
// For starters, support only the regular tab-per-day look
QStyle* style = widget?widget->style():QApplication::style();
// Paint a section for each day
QDateTime dt = d->chartXtoDateTime( offset+exposedRect.left() );
dt.setTime( QTime( 0, 0, 0, 0 ) );
for ( qreal x = d->dateTimeToChartX( dt ); x < exposedRect.right()+offset;
dt = dt.addDays( 1 ),x=d->dateTimeToChartX( dt ) ) {
QStyleOptionHeader opt;
opt.init( widget );
opt.rect = QRectF( x-offset, headerRect.top()+headerRect.height()/2., dayWidth(), headerRect.height()/2. ).toRect();
opt.text = dt.toString( QString::fromAscii( "ddd" ) ).left( 1 );
opt.textAlignment = Qt::AlignCenter;
style->drawControl(QStyle::CE_Header, &opt, painter, widget);
}
dt = d->chartXtoDateTime( offset+exposedRect.left() );
dt.setTime( QTime( 0, 0, 0, 0 ) );
// Go backwards until start of week
while ( dt.date().dayOfWeek() != d->weekStart ) dt = dt.addDays( -1 );
// Paint a section for each week
for ( qreal x2 = d->dateTimeToChartX( dt ); x2 < exposedRect.right()+offset;
dt = dt.addDays( 7 ),x2=d->dateTimeToChartX( dt ) ) {
QStyleOptionHeader opt;
opt.init( widget );
opt.rect = QRectF( x2-offset, headerRect.top(), dayWidth()*7., headerRect.height()/2. ).toRect();
opt.text = QString::number( dt.date().weekNumber() );
opt.textAlignment = Qt::AlignCenter;
style->drawControl(QStyle::CE_Header, &opt, painter, widget);
}
}
#undef d
#ifndef KDAB_NO_UNIT_TESTS
#include <QStandardItemModel>
#include "unittest/test.h"
namespace {
std::ostream& operator<<( std::ostream& os, const QDateTime& dt )
{
os << dt.toString().toStdString();
return os;
}
}
KDAB_SCOPED_UNITTEST_SIMPLE( KDGantt, DateTimeGrid, "test" ) {
QStandardItemModel model( 3, 2 );
DateTimeGrid grid;
QDateTime dt = QDateTime::currentDateTime();
grid.setModel( &model );
grid.setStartDateTime( dt.addDays( -10 ) );
model.setData( model.index( 0, 0 ), dt, StartTimeRole );
model.setData( model.index( 0, 0 ), dt.addDays( 17 ), EndTimeRole );
model.setData( model.index( 2, 0 ), dt.addDays( 18 ), StartTimeRole );
model.setData( model.index( 2, 0 ), dt.addDays( 19 ), EndTimeRole );
Span s = grid.mapToChart( model.index( 0, 0 ) );
qDebug() << "span="<<s;
assertTrue( s.start()>0 );
assertTrue( s.length()>0 );
grid.mapFromChart( s, model.index( 1, 0 ) );
QDateTime s1 = model.data( model.index( 0, 0 ), StartTimeRole ).toDateTime();
QDateTime e1 = model.data( model.index( 0, 0 ), EndTimeRole ).toDateTime();
QDateTime s2 = model.data( model.index( 1, 0 ), StartTimeRole ).toDateTime();
QDateTime e2 = model.data( model.index( 1, 0 ), EndTimeRole ).toDateTime();
assertTrue( s1.isValid() );
assertTrue( e1.isValid() );
assertTrue( s2.isValid() );
assertTrue( e2.isValid() );
assertEqual( s1, s2 );
assertEqual( e1, e2 );
assertTrue( grid.isSatisfiedConstraint( Constraint( model.index( 0, 0 ), model.index( 2, 0 ) ) ) );
assertFalse( grid.isSatisfiedConstraint( Constraint( model.index( 2, 0 ), model.index( 0, 0 ) ) ) );
}
#endif /* KDAB_NO_UNIT_TESTS */
#include "moc_kdganttdatetimegrid.cpp"
<commit_msg>can apparently never be NULL (CID 3537)<commit_after>/****************************************************************************
** Copyright (C) 2001-2006 Klarälvdalens Datakonsult AB. All rights reserved.
**
** This file is part of the KD Gantt library.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid commercial KD Gantt licenses may use this file in
** accordance with the KD Gantt Commercial License Agreement provided with
** the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.kdab.net/kdgantt for
** information about KD Gantt Commercial License Agreements.
**
** Contact info@kdab.net if any conditions of this
** licensing are not clear to you.
**
**********************************************************************/
#include "kdganttdatetimegrid.h"
#include "kdganttdatetimegrid_p.h"
#include "kdganttabstractrowcontroller.h"
#include <QApplication>
#include <QDateTime>
#include <QPainter>
#include <QStyle>
#include <QStyleOptionHeader>
#include <QWidget>
#include <QDebug>
#include <cassert>
using namespace KDGantt;
/*!\class KDGantt::DateTimeGrid
* \ingroup KDGantt
*
* This implementation of AbstractGrid works with QDateTime
* and shows days and week numbers in the header
*
* \todo Extend to work with hours, minutes,... as units too.
*/
// TODO: I think maybe this class should be responsible
// for unit-transformation of the scene...
qreal DateTimeGrid::Private::dateTimeToChartX( const QDateTime& dt ) const
{
assert( startDateTime.isValid() );
qreal result = startDateTime.date().daysTo(dt.date())*24.*60.*60.;
result += startDateTime.time().msecsTo(dt.time())/1000.;
result *= dayWidth/( 24.*60.*60. );
return result;
}
QDateTime DateTimeGrid::Private::chartXtoDateTime( qreal x ) const
{
// TODO
assert( startDateTime.isValid() );
int days = static_cast<int>( x/dayWidth );
qreal secs = x*( 24.*60.*60. )/dayWidth;
QDateTime dt = startDateTime;
QDateTime result = dt.addDays( days ).addSecs( qRound(secs-(days*24.*60.*60.) ) );
return result;
}
#define d d_func()
DateTimeGrid::DateTimeGrid() : AbstractGrid( new Private )
{
}
DateTimeGrid::~DateTimeGrid()
{
}
QDateTime DateTimeGrid::startDateTime() const
{
return d->startDateTime;
}
void DateTimeGrid::setStartDateTime( const QDateTime& dt )
{
d->startDateTime = dt;
emit gridChanged();
}
qreal DateTimeGrid::dayWidth() const
{
return d->dayWidth;
}
void DateTimeGrid::setDayWidth( qreal w )
{
d->dayWidth = w;
emit gridChanged();
}
void DateTimeGrid::setScale( Scale s )
{
d->scale = s;
emit gridChanged();
}
DateTimeGrid::Scale DateTimeGrid::scale() const
{
return d->scale;
}
void DateTimeGrid::setWeekStart( Qt::DayOfWeek ws )
{
d->weekStart = ws;
emit gridChanged();
}
Qt::DayOfWeek DateTimeGrid::weekStart() const
{
return d->weekStart;
}
void DateTimeGrid::setFreeDays( const QSet<Qt::DayOfWeek>& fd )
{
d->freeDays = fd;
emit gridChanged();
}
QSet<Qt::DayOfWeek> DateTimeGrid::freeDays() const
{
return d->freeDays;
}
bool DateTimeGrid::rowSeparators() const
{
return d->rowSeparators;
}
void DateTimeGrid::setRowSeparators( bool enable )
{
d->rowSeparators = enable;
}
Span DateTimeGrid::mapToChart( const QModelIndex& idx ) const
{
assert( model() );
if ( !idx.isValid() ) return Span();
assert( idx.model()==model() );
const QVariant sv = model()->data( idx, StartTimeRole );
const QVariant ev = model()->data( idx, EndTimeRole );
if( qVariantCanConvert<QDateTime>(sv) &&
qVariantCanConvert<QDateTime>(ev) &&
!(sv.type() == QVariant::String && qVariantValue<QString>(sv).isEmpty()) &&
!(ev.type() == QVariant::String && qVariantValue<QString>(ev).isEmpty())
) {
QDateTime st = sv.toDateTime();
QDateTime et = ev.toDateTime();
if ( et.isValid() && st.isValid() ) {
qreal sx = d->dateTimeToChartX( st );
qreal ex = d->dateTimeToChartX( et )-sx;
return Span( sx, ex);
}
}
return Span();
}
static void debug_print_idx( const QModelIndex& idx )
{
if ( !idx.isValid() ) {
qDebug() << "[Invalid]";
return;
}
QDateTime st = idx.data( StartTimeRole ).toDateTime();
QDateTime et = idx.data( StartTimeRole ).toDateTime();
qDebug() << idx << "["<<st<<et<<"]";
}
bool DateTimeGrid::mapFromChart( const Span& span, const QModelIndex& idx,
const QList<Constraint>& constraints ) const
{
assert( model() );
if ( !idx.isValid() ) return false;
assert( idx.model()==model() );
QDateTime st = d->chartXtoDateTime(span.start());
QDateTime et = d->chartXtoDateTime(span.start()+span.length());
Q_FOREACH( const Constraint& c, constraints ) {
if ( c.type() != Constraint::TypeHard || !isSatisfiedConstraint( c )) continue;
if ( c.startIndex() == idx ) {
QDateTime tmpst = model()->data( c.endIndex(), StartTimeRole ).toDateTime();
//qDebug() << tmpst << "<" << et <<"?";
if ( tmpst<et ) return false;
} else if ( c.endIndex() == idx ) {
QDateTime tmpet = model()->data( c.startIndex(), EndTimeRole ).toDateTime();
//qDebug() << tmpet << ">" << st <<"?";
if ( tmpet>st ) return false;
}
}
return model()->setData( idx, qVariantFromValue(st), StartTimeRole )
&& model()->setData( idx, qVariantFromValue(et), EndTimeRole );
}
void DateTimeGrid::paintGrid( QPainter* painter,
const QRectF& sceneRect,
const QRectF& exposedRect,
AbstractRowController* rowController,
QWidget* widget )
{
// TODO: Support hours
QDateTime dt = d->chartXtoDateTime( exposedRect.left() );
dt.setTime( QTime( 0, 0, 0, 0 ) );
for ( qreal x = d->dateTimeToChartX( dt ); x < exposedRect.right();
dt = dt.addDays( 1 ),x=d->dateTimeToChartX( dt ) ) {
QPen pen = painter->pen();
pen.setBrush( QApplication::palette().dark() );
if ( dt.date().dayOfWeek() == d->weekStart ) {
pen.setStyle( Qt::SolidLine );
} else {
pen.setStyle( Qt::DashLine );
}
painter->setPen( pen );
if ( d->freeDays.contains( static_cast<Qt::DayOfWeek>( dt.date().dayOfWeek() ) ) ) {
painter->setBrush( widget?widget->palette().alternateBase()
:QApplication::palette().alternateBase() );
painter->fillRect( QRectF( x, exposedRect.top(), dayWidth(), exposedRect.height() ), painter->brush() );
}
painter->drawLine( QPointF( x, sceneRect.top() ), QPointF( x, sceneRect.bottom() ) );
}
if ( rowController && d->rowSeparators ) {
// First draw the rows
QPen pen = painter->pen();
pen.setBrush( QApplication::palette().dark() );
pen.setStyle( Qt::DashLine );
painter->setPen( pen );
QModelIndex idx = rowController->indexAt( qRound( exposedRect.top() ) );
qreal y = 0;
while ( y < exposedRect.bottom() && idx.isValid() ) {
const Span s = rowController->rowGeometry( idx );
y = s.start()+s.length();
painter->drawLine( QPointF( sceneRect.left(), y ),
QPointF( sceneRect.right(), y ) );
// Is alternating background better?
//if ( idx.row()%2 ) painter->fillRect( QRectF( exposedRect.x(), s.start(), exposedRect.width(), s.length() ), QApplication::palette().alternateBase() );
idx = rowController->indexBelow( idx );
}
}
}
void DateTimeGrid::paintHeader( QPainter* painter, const QRectF& headerRect, const QRectF& exposedRect,
qreal offset, QWidget* widget )
{
switch(scale()) {
case ScaleHour: paintHourScaleHeader(painter,headerRect,exposedRect,offset,widget); break;
case ScaleDay: paintDayScaleHeader(painter,headerRect,exposedRect,offset,widget); break;
case ScaleAuto:
if(dayWidth()>500) paintHourScaleHeader(painter,headerRect,exposedRect,offset,widget);
else paintDayScaleHeader(painter,headerRect,exposedRect,offset,widget);
break;
}
}
void DateTimeGrid::paintHourScaleHeader( QPainter* painter, const QRectF& headerRect, const QRectF& exposedRect,
qreal offset, QWidget* widget )
{
QStyle* style = widget->style();
// Paint a section for each hour
QDateTime dt = d->chartXtoDateTime( offset+exposedRect.left() );
dt.setTime( QTime( dt.time().hour(), 0, 0, 0 ) );
for ( qreal x = d->dateTimeToChartX( dt ); x < exposedRect.right()+offset;
dt = dt.addSecs( 60*60 /*1 hour*/ ),x=d->dateTimeToChartX( dt ) ) {
QStyleOptionHeader opt;
opt.init( widget );
opt.rect = QRectF( x-offset, headerRect.top()+headerRect.height()/2., dayWidth()/24., headerRect.height()/2. ).toRect();
opt.text = dt.time().toString( QString::fromAscii( "hh" ) );
opt.textAlignment = Qt::AlignCenter;
style->drawControl(QStyle::CE_Header, &opt, painter, widget);
}
dt = d->chartXtoDateTime( offset+exposedRect.left() );
dt.setTime( QTime( 0, 0, 0, 0 ) );
// Paint a section for each day
for ( qreal x2 = d->dateTimeToChartX( dt ); x2 < exposedRect.right()+offset;
dt = dt.addDays( 1 ),x2=d->dateTimeToChartX( dt ) ) {
QStyleOptionHeader opt;
opt.init( widget );
opt.rect = QRectF( x2-offset, headerRect.top(), dayWidth(), headerRect.height()/2. ).toRect();
opt.text = QString::number( dt.date().weekNumber() );
opt.textAlignment = Qt::AlignCenter;
style->drawControl(QStyle::CE_Header, &opt, painter, widget);
}
}
void DateTimeGrid::paintDayScaleHeader( QPainter* painter, const QRectF& headerRect, const QRectF& exposedRect,
qreal offset, QWidget* widget )
{
// For starters, support only the regular tab-per-day look
QStyle* style = widget?widget->style():QApplication::style();
// Paint a section for each day
QDateTime dt = d->chartXtoDateTime( offset+exposedRect.left() );
dt.setTime( QTime( 0, 0, 0, 0 ) );
for ( qreal x = d->dateTimeToChartX( dt ); x < exposedRect.right()+offset;
dt = dt.addDays( 1 ),x=d->dateTimeToChartX( dt ) ) {
QStyleOptionHeader opt;
opt.init( widget );
opt.rect = QRectF( x-offset, headerRect.top()+headerRect.height()/2., dayWidth(), headerRect.height()/2. ).toRect();
opt.text = dt.toString( QString::fromAscii( "ddd" ) ).left( 1 );
opt.textAlignment = Qt::AlignCenter;
style->drawControl(QStyle::CE_Header, &opt, painter, widget);
}
dt = d->chartXtoDateTime( offset+exposedRect.left() );
dt.setTime( QTime( 0, 0, 0, 0 ) );
// Go backwards until start of week
while ( dt.date().dayOfWeek() != d->weekStart ) dt = dt.addDays( -1 );
// Paint a section for each week
for ( qreal x2 = d->dateTimeToChartX( dt ); x2 < exposedRect.right()+offset;
dt = dt.addDays( 7 ),x2=d->dateTimeToChartX( dt ) ) {
QStyleOptionHeader opt;
opt.init( widget );
opt.rect = QRectF( x2-offset, headerRect.top(), dayWidth()*7., headerRect.height()/2. ).toRect();
opt.text = QString::number( dt.date().weekNumber() );
opt.textAlignment = Qt::AlignCenter;
style->drawControl(QStyle::CE_Header, &opt, painter, widget);
}
}
#undef d
#ifndef KDAB_NO_UNIT_TESTS
#include <QStandardItemModel>
#include "unittest/test.h"
namespace {
std::ostream& operator<<( std::ostream& os, const QDateTime& dt )
{
os << dt.toString().toStdString();
return os;
}
}
KDAB_SCOPED_UNITTEST_SIMPLE( KDGantt, DateTimeGrid, "test" ) {
QStandardItemModel model( 3, 2 );
DateTimeGrid grid;
QDateTime dt = QDateTime::currentDateTime();
grid.setModel( &model );
grid.setStartDateTime( dt.addDays( -10 ) );
model.setData( model.index( 0, 0 ), dt, StartTimeRole );
model.setData( model.index( 0, 0 ), dt.addDays( 17 ), EndTimeRole );
model.setData( model.index( 2, 0 ), dt.addDays( 18 ), StartTimeRole );
model.setData( model.index( 2, 0 ), dt.addDays( 19 ), EndTimeRole );
Span s = grid.mapToChart( model.index( 0, 0 ) );
qDebug() << "span="<<s;
assertTrue( s.start()>0 );
assertTrue( s.length()>0 );
grid.mapFromChart( s, model.index( 1, 0 ) );
QDateTime s1 = model.data( model.index( 0, 0 ), StartTimeRole ).toDateTime();
QDateTime e1 = model.data( model.index( 0, 0 ), EndTimeRole ).toDateTime();
QDateTime s2 = model.data( model.index( 1, 0 ), StartTimeRole ).toDateTime();
QDateTime e2 = model.data( model.index( 1, 0 ), EndTimeRole ).toDateTime();
assertTrue( s1.isValid() );
assertTrue( e1.isValid() );
assertTrue( s2.isValid() );
assertTrue( e2.isValid() );
assertEqual( s1, s2 );
assertEqual( e1, e2 );
assertTrue( grid.isSatisfiedConstraint( Constraint( model.index( 0, 0 ), model.index( 2, 0 ) ) ) );
assertFalse( grid.isSatisfiedConstraint( Constraint( model.index( 2, 0 ), model.index( 0, 0 ) ) ) );
}
#endif /* KDAB_NO_UNIT_TESTS */
#include "moc_kdganttdatetimegrid.cpp"
<|endoftext|>
|
<commit_before>#include "mytablemodel.h"
int MyTableModel::rowCount(const QModelIndex &parent) const
{
return m_data.size();
}
int MyTableModel::columnCount(const QModelIndex &parent) const
{
return 2;
}
QVariant MyTableModel::data(const QModelIndex &index, int role) const
{
Record const& dataElem = m_data[index.row()];
if (index.column() == 0)
return QVariant(dataElem.label);
else
return QVariant(dataElem.number);
}
bool MyTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
return false;
}
Qt::ItemFlags MyTableModel::flags(const QModelIndex &index) const
{
return Qt::ItemFlags();
}
void MyTableModel::insertRow()
{
m_data.push_back({ "label", 0 });
emit layoutChanged();
}
<commit_msg>Fix bugs<commit_after>#include "mytablemodel.h"
int MyTableModel::rowCount(const QModelIndex &parent) const
{
return m_data.size();
}
int MyTableModel::columnCount(const QModelIndex &parent) const
{
return 2;
}
QVariant MyTableModel::data(const QModelIndex &index, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
Record const& dataElem = m_data[index.row()];
if (index.column() == 0)
return QVariant(dataElem.label);
else
return QVariant(dataElem.number);
}
bool MyTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
return false;
}
Qt::ItemFlags MyTableModel::flags(const QModelIndex &index) const
{
return QAbstractTableModel::flags(index);
}
void MyTableModel::insertRow()
{
m_data.push_back({ "label", 0 });
emit layoutChanged();
}
<|endoftext|>
|
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
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 <Interface/Modules/Render/ViewSceneUtility.h>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <sstream>
using namespace SCIRun::Render::Gui;
glm::quat ViewSceneUtility::stringToQuat(const std::string &s)
{
double w = 1.0;
double x, y, z = 0.0f;
if (!s.empty())
{
try
{
static boost::regex r("Quaternion\\((.+),(.+),(.+),(.+)\\)");
boost::smatch what;
regex_match(s, what, r);
w = boost::lexical_cast<double>(what[1]);
x = boost::lexical_cast<double>(what[2]);
y = boost::lexical_cast<double>(what[3]);
z = boost::lexical_cast<double>(what[4]);
}
catch (...)
{
// keeps as default view
}
}
return glm::normalize(glm::quat(w, x, y, z));
}
std::string ViewSceneUtility::quatToString(const glm::quat &q)
{
return "Quaternion(" + std::to_string((double)q.w) + ","
+ std::to_string((double)q.x) + ","
+ std::to_string((double)q.y) + ","
+ std::to_string((double)q.z) + ")";
}
<commit_msg>Small fix<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
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 <Interface/Modules/Render/ViewSceneUtility.h>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <sstream>
using namespace SCIRun::Render::Gui;
glm::quat ViewSceneUtility::stringToQuat(const std::string &s)
{
double w, x, y, z;
w = 1.0;
x = y = z = 0.0f;
if (!s.empty())
{
try
{
static boost::regex r("Quaternion\\((.+),(.+),(.+),(.+)\\)");
boost::smatch what;
regex_match(s, what, r);
w = boost::lexical_cast<double>(what[1]);
x = boost::lexical_cast<double>(what[2]);
y = boost::lexical_cast<double>(what[3]);
z = boost::lexical_cast<double>(what[4]);
}
catch (...)
{
// keeps as default view
}
}
return glm::normalize(glm::quat(w, x, y, z));
}
std::string ViewSceneUtility::quatToString(const glm::quat &q)
{
return "Quaternion(" + std::to_string((double)q.w) + ","
+ std::to_string((double)q.x) + ","
+ std::to_string((double)q.y) + ","
+ std::to_string((double)q.z) + ")";
}
<|endoftext|>
|
<commit_before>#ifndef GUARD_checked_arithmetic_hpp_7987160937854629
#define GUARD_checked_arithmetic_hpp_7987160937854629
/** \file checked_arithmetic.hpp
*
* \author Matthew Harvey
* \date 2012-06-09
*
* Copyright (c) 2012, Matthew Harvey. All rights reserved.
*
* \brief Provides functions that check the safety of arithmetic
* operations. In the case of signed arithmetic, we are checking
* for overflow; in the case of unsigned arithmetic, we are
* checking for wrap-around. In the case of division and remainder
* operations, we are also checking for divide-by-zero.
*
* The parameters to these functions must be of one of the supported types,
* and must be of the same type.
* Failure to provide the required types will result in compilation
* failure.
* Automatic conversion to the required types will \e never occur.
*
* Supported types are:\n
* <tt>
* int\n
* short\n
* long\n
* long long\n
* signed char\n
* unsigned int\n
* unsigned long\n
* unsigned long long\n
* unsigned short\n
* unsigned char\n
* </tt>
* @param x first number that would be added (or subtracted, or etc.).
* @param y second number that would be added (or subtracted, or etc.).
* @returns \c true if and only if it \e would be
* unsafe to add \c x and \c y (or subtract \c y from \c x, or multiply \c x
* by \c y, or divide \c x by \c y) otherwise returns false.
* The operation being tested is not actually performed.
*
* Exception safety: <em>nothrow guarantee</em> is offered by all compilable
* instantiations of the function templates in this header.
*
* @todo LOW PRIORITY Write functions to test the safety of unary minus,
* increment and decrement.
*/
#include <boost/cstdint.hpp>
#include "detail/checked_arithmetic_detail.hpp"
namespace jewel
{
// INTERFACE
/// \name Check addition, subtraction, multiplication and division
/// operations for or overflow other unsafe conditions.
//@{
/**
* @returns true if and only if it is unsafe to perform the
* operation <tt>x + y</tt>.
*/
template <typename T>
bool addition_is_unsafe(T x, T y);
/**
* @returns true if and only if it is unsafe to perform the operation
* <tt>x - y</tt>.
*/
template <typename T>
bool subtraction_is_unsafe(T x, T y);
/**
* @returns true if and only if it is unsafe to perform the operation
* <tt>x * y</tt>.
*/
template <typename T>
bool multiplication_is_unsafe(T x, T y);
/**
* @returns true if and only if is unsafe to perform the operation
* <tt>x / y</tt>.
*/
template <typename T>
bool division_is_unsafe(T x, T y);
/** See documentation for file checked_arithmetic.hpp.
*
* @returns \e true if and only if it is unsafe to perform
* the operation <tt>x % y</tt>.
*/
template <typename T>
bool remainder_is_unsafe(T x, T y);
//@}
//@cond
// IMPLEMENTATIONS
template <typename T>
inline
bool addition_is_unsafe(T x, T y)
{
return detail::CheckedArithmetic::addition_is_unsafe(x, y);
}
template <typename T>
inline
bool subtraction_is_unsafe(T x, T y)
{
return detail::CheckedArithmetic::subtraction_is_unsafe(x, y);
}
template <typename T>
inline
bool multiplication_is_unsafe(T x, T y)
{
return detail::CheckedArithmetic::multiplication_is_unsafe(x, y);
}
template <typename T>
inline
bool division_is_unsafe(T x, T y)
{
return detail::CheckedArithmetic::division_is_unsafe(x, y);
}
template <typename T>
inline
bool remainder_is_unsafe(T x, T y)
{
return detail::CheckedArithmetic::remainder_is_unsafe(x, y);
}
//@endcond
} // namespace jewel
#endif // GUARD_checked_arithmetic_hpp_7987160937854629
<commit_msg>Got rid of unused header #include from "checked_arithmetic.hpp".<commit_after>#ifndef GUARD_checked_arithmetic_hpp_7987160937854629
#define GUARD_checked_arithmetic_hpp_7987160937854629
/** \file checked_arithmetic.hpp
*
* \author Matthew Harvey
* \date 2012-06-09
*
* Copyright (c) 2012, Matthew Harvey. All rights reserved.
*
* \brief Provides functions that check the safety of arithmetic
* operations. In the case of signed arithmetic, we are checking
* for overflow; in the case of unsigned arithmetic, we are
* checking for wrap-around. In the case of division and remainder
* operations, we are also checking for divide-by-zero.
*
* The parameters to these functions must be of one of the supported types,
* and must be of the same type.
* Failure to provide the required types will result in compilation
* failure.
* Automatic conversion to the required types will \e never occur.
*
* Supported types are:\n
* <tt>
* int\n
* short\n
* long\n
* long long\n
* signed char\n
* unsigned int\n
* unsigned long\n
* unsigned long long\n
* unsigned short\n
* unsigned char\n
* </tt>
* @param x first number that would be added (or subtracted, or etc.).
* @param y second number that would be added (or subtracted, or etc.).
* @returns \c true if and only if it \e would be
* unsafe to add \c x and \c y (or subtract \c y from \c x, or multiply \c x
* by \c y, or divide \c x by \c y) otherwise returns false.
* The operation being tested is not actually performed.
*
* Exception safety: <em>nothrow guarantee</em> is offered by all compilable
* instantiations of the function templates in this header.
*
* @todo LOW PRIORITY Write functions to test the safety of unary minus,
* increment and decrement.
*/
#include "detail/checked_arithmetic_detail.hpp"
namespace jewel
{
// INTERFACE
/// \name Check addition, subtraction, multiplication and division
/// operations for or overflow other unsafe conditions.
//@{
/**
* @returns true if and only if it is unsafe to perform the
* operation <tt>x + y</tt>.
*/
template <typename T>
bool addition_is_unsafe(T x, T y);
/**
* @returns true if and only if it is unsafe to perform the operation
* <tt>x - y</tt>.
*/
template <typename T>
bool subtraction_is_unsafe(T x, T y);
/**
* @returns true if and only if it is unsafe to perform the operation
* <tt>x * y</tt>.
*/
template <typename T>
bool multiplication_is_unsafe(T x, T y);
/**
* @returns true if and only if is unsafe to perform the operation
* <tt>x / y</tt>.
*/
template <typename T>
bool division_is_unsafe(T x, T y);
/** See documentation for file checked_arithmetic.hpp.
*
* @returns \e true if and only if it is unsafe to perform
* the operation <tt>x % y</tt>.
*/
template <typename T>
bool remainder_is_unsafe(T x, T y);
//@}
//@cond
// IMPLEMENTATIONS
template <typename T>
inline
bool addition_is_unsafe(T x, T y)
{
return detail::CheckedArithmetic::addition_is_unsafe(x, y);
}
template <typename T>
inline
bool subtraction_is_unsafe(T x, T y)
{
return detail::CheckedArithmetic::subtraction_is_unsafe(x, y);
}
template <typename T>
inline
bool multiplication_is_unsafe(T x, T y)
{
return detail::CheckedArithmetic::multiplication_is_unsafe(x, y);
}
template <typename T>
inline
bool division_is_unsafe(T x, T y)
{
return detail::CheckedArithmetic::division_is_unsafe(x, y);
}
template <typename T>
inline
bool remainder_is_unsafe(T x, T y)
{
return detail::CheckedArithmetic::remainder_is_unsafe(x, y);
}
//@endcond
} // namespace jewel
#endif // GUARD_checked_arithmetic_hpp_7987160937854629
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libetonyek project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "PAGCollector.h"
#include <cassert>
#include <boost/make_shared.hpp>
#include "IWORKDocumentInterface.h"
#include "IWORKOutputElements.h"
#include "IWORKText.h"
#include "PAGProperties.h"
#include "PAGTypes.h"
namespace libetonyek
{
using librevenge::RVNGPropertyList;
using std::string;
namespace
{
typedef void (IWORKDocumentInterface::*OpenFunction)(const RVNGPropertyList &);
typedef void (IWORKDocumentInterface::*CloseFunction)();
typedef const std::string &(*PickFunction)(const PAGPageMaster &);
const std::string &pickHeader(const PAGPageMaster &pageMaster)
{
return pageMaster.m_header;
}
const std::string &pickFooter(const PAGPageMaster &pageMaster)
{
return pageMaster.m_footer;
}
void writeHeaderFooter(
IWORKDocumentInterface *const document, const IWORKHeaderFooterMap_t &hfMap,
const string &name, const string &occurence,
const OpenFunction open, const CloseFunction close)
{
assert(document);
const IWORKHeaderFooterMap_t::const_iterator it = hfMap.find(name);
RVNGPropertyList props;
props.insert("librevenge:occurence", occurence.c_str());
(document->*open)(props);
if (it != hfMap.end())
it->second.write(document);
(document->*close)();
}
void writeHeadersFooters(
IWORKDocumentInterface *const document, const IWORKStylePtr_t &style, const IWORKHeaderFooterMap_t &hfMap,
const PickFunction pick, const OpenFunction open, const CloseFunction close)
{
assert(bool(style));
using namespace property;
const string odd((style->has<OddPageMaster>()) ? pick(style->get<OddPageMaster>()) : "");
const string even((style->has<EvenPageMaster>()) ? pick(style->get<EvenPageMaster>()) : "");
if (odd == even)
{
writeHeaderFooter(document, hfMap, odd, "both", open, close);
}
else
{
writeHeaderFooter(document, hfMap, odd, "odd", open, close);
writeHeaderFooter(document, hfMap, even, "even", open, close);
}
}
}
PAGCollector::Section::Section()
: m_style()
, m_width()
, m_height()
, m_horizontalMargin()
, m_verticalMargin()
{
}
void PAGCollector::Section::clear()
{
m_style.reset();
m_width.reset();
m_height.reset();
m_horizontalMargin.reset();
m_verticalMargin.reset();
}
PAGCollector::PAGCollector(IWORKDocumentInterface *const document)
: IWORKCollector(document)
, m_currentSection()
, m_firstPageSpan(true)
{
}
void PAGCollector::collectPublicationInfo(const PAGPublicationInfo &/*pubInfo*/)
{
}
void PAGCollector::collectTextBody()
{
// It seems that this is never used, as Pages always inserts all text
// into a section. But better safe than sorry.
flushPageSpan(false);
}
void PAGCollector::collectAttachment(const IWORKOutputID_t &id)
{
assert(bool(m_currentText));
m_currentText->insertBlockContent(getOutputManager().get(id));
}
void PAGCollector::openSection(const std::string &style, const double width, const double height, const double horizontalMargin, const double verticalMargin)
{
m_currentSection.m_width = width;
m_currentSection.m_height = height;
m_currentSection.m_horizontalMargin = horizontalMargin;
m_currentSection.m_verticalMargin = verticalMargin;
if (!m_stylesheetStack.empty())
{
const IWORKStyleMap_t::iterator it = m_stylesheetStack.top()->m_styles.find(style);
if (it != m_stylesheetStack.top()->m_styles.end())
{
m_currentSection.m_style = it->second;
}
else
{
ETONYEK_DEBUG_MSG(("style '%s' not found\n", style.c_str()));
}
}
else
{
ETONYEK_DEBUG_MSG(("no stylesheet is available\n"));
}
}
void PAGCollector::closeSection()
{
flushPageSpan();
}
void PAGCollector::drawTable()
{
assert(!m_levelStack.empty());
librevenge::RVNGPropertyList props;
// TODO: I am not sure this is the default for Pages...
props.insert("table:align", "center");
const IWORKGeometryPtr_t geometry(m_levelStack.top().m_geometry);
if (geometry)
{
const glm::dvec3 dim(m_levelStack.top().m_trafo * glm::dvec3(geometry->m_naturalSize.m_width, 0, 0));
props.insert("style:width", pt2in(dim[0]));
}
m_currentTable.draw(props, m_outputManager.getCurrent());
}
void PAGCollector::flushPageSpan(const bool writeEmpty)
{
if (m_firstPageSpan)
{
RVNGPropertyList metadata;
fillMetadata(metadata);
m_document->setDocumentMetaData(metadata);
m_firstPageSpan = false;
}
librevenge::RVNGPropertyList props;
if (m_currentSection.m_width)
props.insert("fo:page-width", get(m_currentSection.m_width));
if (m_currentSection.m_height)
props.insert("fo:page-height", get(m_currentSection.m_height));
if (m_currentSection.m_horizontalMargin)
{
props.insert("fo:margin-left", get(m_currentSection.m_horizontalMargin));
props.insert("fo:margin-right", get(m_currentSection.m_horizontalMargin));
}
if (m_currentSection.m_verticalMargin)
{
props.insert("fo:margin-top", get(m_currentSection.m_verticalMargin));
props.insert("fo:margin-bottom", get(m_currentSection.m_verticalMargin));
}
IWORKOutputElements text;
if (bool(m_currentText))
{
m_currentText->draw(text);
m_currentText.reset();
}
if (!text.empty() || writeEmpty)
{
m_document->openPageSpan(props);
if (m_currentSection.m_style)
{
writeHeadersFooters(m_document, m_currentSection.m_style, m_headers, pickHeader,
&IWORKDocumentInterface::openHeader, &IWORKDocumentInterface::closeHeader);
writeHeadersFooters(m_document, m_currentSection.m_style, m_footers, pickFooter,
&IWORKDocumentInterface::openFooter, &IWORKDocumentInterface::closeFooter);
}
text.write(m_document);
m_document->closePageSpan();
}
m_currentSection.clear();
}
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>do not write header block if there is no header<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libetonyek project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "PAGCollector.h"
#include <cassert>
#include <boost/make_shared.hpp>
#include "IWORKDocumentInterface.h"
#include "IWORKOutputElements.h"
#include "IWORKText.h"
#include "PAGProperties.h"
#include "PAGTypes.h"
namespace libetonyek
{
using librevenge::RVNGPropertyList;
using std::string;
namespace
{
typedef void (IWORKDocumentInterface::*OpenFunction)(const RVNGPropertyList &);
typedef void (IWORKDocumentInterface::*CloseFunction)();
typedef const std::string &(*PickFunction)(const PAGPageMaster &);
const std::string &pickHeader(const PAGPageMaster &pageMaster)
{
return pageMaster.m_header;
}
const std::string &pickFooter(const PAGPageMaster &pageMaster)
{
return pageMaster.m_footer;
}
void writeHeaderFooter(
IWORKDocumentInterface *const document, const IWORKHeaderFooterMap_t &hfMap,
const string &name, const string &occurence,
const OpenFunction open, const CloseFunction close)
{
assert(document);
if (name.empty())
return;
const IWORKHeaderFooterMap_t::const_iterator it = hfMap.find(name);
if (it != hfMap.end())
{
RVNGPropertyList props;
props.insert("librevenge:occurence", occurence.c_str());
(document->*open)(props);
it->second.write(document);
(document->*close)();
}
}
void writeHeadersFooters(
IWORKDocumentInterface *const document, const IWORKStylePtr_t &style, const IWORKHeaderFooterMap_t &hfMap,
const PickFunction pick, const OpenFunction open, const CloseFunction close)
{
assert(bool(style));
using namespace property;
const string odd((style->has<OddPageMaster>()) ? pick(style->get<OddPageMaster>()) : "");
const string even((style->has<EvenPageMaster>()) ? pick(style->get<EvenPageMaster>()) : "");
if (odd == even)
{
writeHeaderFooter(document, hfMap, odd, "both", open, close);
}
else
{
writeHeaderFooter(document, hfMap, odd, "odd", open, close);
writeHeaderFooter(document, hfMap, even, "even", open, close);
}
}
}
PAGCollector::Section::Section()
: m_style()
, m_width()
, m_height()
, m_horizontalMargin()
, m_verticalMargin()
{
}
void PAGCollector::Section::clear()
{
m_style.reset();
m_width.reset();
m_height.reset();
m_horizontalMargin.reset();
m_verticalMargin.reset();
}
PAGCollector::PAGCollector(IWORKDocumentInterface *const document)
: IWORKCollector(document)
, m_currentSection()
, m_firstPageSpan(true)
{
}
void PAGCollector::collectPublicationInfo(const PAGPublicationInfo &/*pubInfo*/)
{
}
void PAGCollector::collectTextBody()
{
// It seems that this is never used, as Pages always inserts all text
// into a section. But better safe than sorry.
flushPageSpan(false);
}
void PAGCollector::collectAttachment(const IWORKOutputID_t &id)
{
assert(bool(m_currentText));
m_currentText->insertBlockContent(getOutputManager().get(id));
}
void PAGCollector::openSection(const std::string &style, const double width, const double height, const double horizontalMargin, const double verticalMargin)
{
m_currentSection.m_width = width;
m_currentSection.m_height = height;
m_currentSection.m_horizontalMargin = horizontalMargin;
m_currentSection.m_verticalMargin = verticalMargin;
if (!m_stylesheetStack.empty())
{
const IWORKStyleMap_t::iterator it = m_stylesheetStack.top()->m_styles.find(style);
if (it != m_stylesheetStack.top()->m_styles.end())
{
m_currentSection.m_style = it->second;
}
else
{
ETONYEK_DEBUG_MSG(("style '%s' not found\n", style.c_str()));
}
}
else
{
ETONYEK_DEBUG_MSG(("no stylesheet is available\n"));
}
}
void PAGCollector::closeSection()
{
flushPageSpan();
}
void PAGCollector::drawTable()
{
assert(!m_levelStack.empty());
librevenge::RVNGPropertyList props;
// TODO: I am not sure this is the default for Pages...
props.insert("table:align", "center");
const IWORKGeometryPtr_t geometry(m_levelStack.top().m_geometry);
if (geometry)
{
const glm::dvec3 dim(m_levelStack.top().m_trafo * glm::dvec3(geometry->m_naturalSize.m_width, 0, 0));
props.insert("style:width", pt2in(dim[0]));
}
m_currentTable.draw(props, m_outputManager.getCurrent());
}
void PAGCollector::flushPageSpan(const bool writeEmpty)
{
if (m_firstPageSpan)
{
RVNGPropertyList metadata;
fillMetadata(metadata);
m_document->setDocumentMetaData(metadata);
m_firstPageSpan = false;
}
librevenge::RVNGPropertyList props;
if (m_currentSection.m_width)
props.insert("fo:page-width", get(m_currentSection.m_width));
if (m_currentSection.m_height)
props.insert("fo:page-height", get(m_currentSection.m_height));
if (m_currentSection.m_horizontalMargin)
{
props.insert("fo:margin-left", get(m_currentSection.m_horizontalMargin));
props.insert("fo:margin-right", get(m_currentSection.m_horizontalMargin));
}
if (m_currentSection.m_verticalMargin)
{
props.insert("fo:margin-top", get(m_currentSection.m_verticalMargin));
props.insert("fo:margin-bottom", get(m_currentSection.m_verticalMargin));
}
IWORKOutputElements text;
if (bool(m_currentText))
{
m_currentText->draw(text);
m_currentText.reset();
}
if (!text.empty() || writeEmpty)
{
m_document->openPageSpan(props);
if (m_currentSection.m_style)
{
writeHeadersFooters(m_document, m_currentSection.m_style, m_headers, pickHeader,
&IWORKDocumentInterface::openHeader, &IWORKDocumentInterface::closeHeader);
writeHeadersFooters(m_document, m_currentSection.m_style, m_footers, pickFooter,
&IWORKDocumentInterface::openFooter, &IWORKDocumentInterface::closeFooter);
}
text.write(m_document);
m_document->closePageSpan();
}
m_currentSection.clear();
}
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|>
|
<commit_before>#include <possumwood_sdk/node_implementation.h>
#define EIGEN_STACK_ALLOCATION_LIMIT 0
#include <actions/traits.h>
#include <tbb/task_group.h>
#include <Eigen/Sparse>
#include <mutex>
#include <opencv2/opencv.hpp>
#include "frame.h"
namespace {
class Triplets;
class Row {
public:
Row() = default;
void addValue(int64_t row, int64_t col, double value) {
if(value != 0.0)
m_values[(row << 32) + col] += value;
}
private:
Row(const Row&) = delete;
Row& operator=(const Row&) = delete;
std::map<int64_t, double> m_values;
friend class Triplets;
};
class Triplets {
public:
Triplets(int rows, int cols) : m_rowCount(0), m_rows(rows), m_cols(cols) {
}
void addRow(const Row& r) {
for(auto& v : r.m_values) {
int32_t row = v.first >> 32;
int32_t col = v.first & 0xffffffff;
assert(row < m_rows);
assert(col < m_cols);
m_triplets.push_back(Eigen::Triplet<double>(m_rowCount, row * m_cols + col, v.second));
}
++m_rowCount;
}
std::size_t rows() const {
return m_rowCount;
}
const std::vector<Eigen::Triplet<double>>& triplets() const {
return m_triplets;
}
private:
std::vector<Eigen::Triplet<double>> m_triplets;
int m_rowCount, m_rows, m_cols;
friend class Row;
};
static const cv::Mat kernel = (cv::Mat_<double>(3, 3) << 0.0, -1.0, 0.0, -1.0, 4.0, -1.0, 0.0, -1.0, 0.0);
// static const cv::Mat kernel = (cv::Mat_<double>(3,3) <<
// -1.0, -1.0, -1.0,
// -1.0, 8.0, -1.0,
// -1.0, -1.0, -1.0
// );
// static const cv::Mat kernel = (cv::Mat_<double>(3,3) <<
// -1.0, -2.0, -1.0,
// -2.0, 12.0, -2.0,
// -1.0, -2.0, -1.0
// );
// static const cv::Mat kernel = (cv::Mat_<double>(5,5) <<
// 0.0, 0.0, 1.0, 0.0, 0.0,
// 0.0, 2.0, -8.0, 2.0, 0.0,
// 1.0, -8.0, 20.0, -8.0, 1.0,
// 0.0, 2.0, -8.0, 2.0, 0.0,
// 0.0, 0.0, 1.0, 0.0, 0.0
// );
float buildMatrices(const cv::Mat& image, const cv::Mat& mask, Eigen::SparseMatrix<double>& A, Eigen::VectorXd& b,
const cv::Rect2i& roi) {
Triplets triplets(roi.height, roi.width);
std::vector<double> values;
std::size_t validCtr = 0, interpolatedCtr = 0;
for(int y = roi.y; y < roi.y + roi.height; ++y)
for(int x = roi.x; x < roi.x + roi.width; ++x) {
Row row;
// masked and/or edge
if(mask.at<unsigned char>(y, x) > 128) {
values.push_back(0.0f);
// convolution
for(int yi = 0; yi < kernel.rows; ++yi)
for(int xi = 0; xi < kernel.cols; ++xi) {
int ypos = y + yi - kernel.rows / 2;
int xpos = x + xi - kernel.cols / 2;
// handling of edges - "clip" (or "mirror", commented out for now)
if(ypos < roi.y)
// ypos = -ypos;
ypos = roi.y;
if(ypos >= roi.y + roi.height)
// ypos = (image.rows-1) - (ypos-image.rows);
ypos = roi.y + roi.height - 1;
if(xpos < roi.x)
// xpos = -xpos;
xpos = roi.x;
if(xpos >= roi.x + roi.width)
// xpos = (image.cols-1) - (xpos-image.cols);
xpos = roi.x + roi.width - 1;
row.addValue(ypos - roi.y, xpos - roi.x, kernel.at<double>(yi, xi));
}
++interpolatedCtr;
}
// non-masked
if(mask.at<unsigned char>(y, x) <= 128) {
values.push_back(image.at<float>(y, x));
row.addValue(y - roi.y, x - roi.x, 1);
++validCtr;
}
triplets.addRow(row);
}
// initialise the sparse matrix
A = Eigen::SparseMatrix<double>(triplets.rows(), roi.height * roi.width);
A.setFromTriplets(triplets.triplets().begin(), triplets.triplets().end());
// and the "b" vector
assert(values.size() == triplets.rows());
b = Eigen::VectorXd(values.size());
for(std::size_t i = 0; i < values.size(); ++i)
b[i] = values[i];
return (float)validCtr / ((float)validCtr + (float)interpolatedCtr);
}
dependency_graph::InAttr<possumwood::opencv::Frame> a_inFrame, a_inMask;
dependency_graph::InAttr<unsigned> a_mosaic;
dependency_graph::OutAttr<possumwood::opencv::Frame> a_outFrame;
dependency_graph::State compute(dependency_graph::Values& data) {
dependency_graph::State state;
const cv::Mat& input = *data.get(a_inFrame);
const cv::Mat& mask = *data.get(a_inMask);
const unsigned mosaic = data.get(a_mosaic);
if(input.depth() != CV_32F)
throw std::runtime_error("Laplacian inpainting - input image type has to be CV_32F.");
if(mask.type() != CV_8UC1 && mask.type() != CV_8UC3)
throw std::runtime_error("Laplacian inpainting - mask image type has to be CV_8UC1 or CV_8UC3.");
if(input.empty() || mask.empty())
throw std::runtime_error("Laplacian inpainting - empty input image and/or mask.");
if(input.size != mask.size)
throw std::runtime_error("Laplacian inpainting - input and mask image size have to match.");
if(input.cols % mosaic != 0 || input.rows % mosaic != 0)
throw std::runtime_error(
"Laplacian inpainting - image size is not divisible by mosaic count - invalid mosaic?.");
std::vector<std::vector<float>> x(input.channels(), std::vector<float>(input.rows * input.cols, 0.0f));
tbb::task_group tasks;
std::mutex solve_mutex;
// split the inputs and masks per channel
std::vector<cv::Mat> inputs, masks;
cv::split(input, inputs);
cv::split(mask, masks);
assert((int)inputs.size() == input.channels());
assert((int)masks.size() == mask.channels());
const unsigned mosaic_rows = input.rows / mosaic;
const unsigned mosaic_cols = input.cols / mosaic;
for(unsigned yi = 0; yi < mosaic; ++yi) {
for(unsigned xi = 0; xi < mosaic; ++xi) {
cv::Rect2i roi;
roi.y = yi * mosaic_rows;
roi.x = xi * mosaic_cols;
roi.height = mosaic_rows;
roi.width = mosaic_cols;
for(int channel = 0; channel < input.channels(); ++channel) {
tasks.run([channel, &inputs, &masks, &x, &state, &solve_mutex, roi]() {
cv::Mat inTile = inputs[channel];
cv::Mat inMask;
if(masks.size() == 1)
inMask = masks[0];
else
inMask = masks[channel];
Eigen::SparseMatrix<double> A;
Eigen::VectorXd b, tmp;
const float ratio = buildMatrices(inTile, inMask, A, b, roi);
if(ratio > 0.003) {
const char* stage = "solver construction";
Eigen::SparseLU<Eigen::SparseMatrix<double> /*, Eigen::NaturalOrdering<int>*/> chol(A);
if(chol.info() == Eigen::Success) {
stage = "analyze pattern";
chol.analyzePattern(A);
if(chol.info() == Eigen::Success) {
stage = "factorize";
chol.factorize(A);
if(chol.info() == Eigen::Success) {
stage = "solve";
tmp = chol.solve(b);
assert(tmp.size() == roi.height * roi.width);
for(int i = 0; i < tmp.size(); ++i) {
const int row = i / roi.width;
const int col = i % roi.width;
const int index = (row + roi.y) * masks[0].cols + col + roi.x;
assert((std::size_t)index < x[channel].size());
x[channel][index] = tmp[i];
}
}
}
}
std::lock_guard<std::mutex> guard(solve_mutex);
if(chol.info() == Eigen::NumericalIssue)
state.addWarning("Decomposition failed - Eigen::NumericalIssue at stage " +
std::string(stage));
else if(chol.info() == Eigen::NoConvergence)
state.addWarning("Decomposition failed - Eigen::NoConvergence at stage " +
std::string(stage));
else if(chol.info() == Eigen::InvalidInput)
state.addWarning("Decomposition failed - Eigen::InvalidInput at stage " +
std::string(stage));
else if(chol.info() != Eigen::Success)
state.addWarning("Decomposition failed - unknown error at stage " + std::string(stage));
}
});
}
}
}
tasks.wait();
cv::Mat result = input.clone();
for(int yi = 0; yi < result.rows; ++yi)
for(int xi = 0; xi < result.cols; ++xi)
for(int c = 0; c < input.channels(); ++c)
result.ptr<float>(yi, xi)[c] = x[c][yi * result.cols + xi];
data.set(a_outFrame, possumwood::opencv::Frame(result));
return state;
}
void init(possumwood::Metadata& meta) {
meta.addAttribute(a_inFrame, "frame", possumwood::opencv::Frame(), possumwood::AttrFlags::kVertical);
meta.addAttribute(a_inMask, "mask", possumwood::opencv::Frame(), possumwood::AttrFlags::kVertical);
meta.addAttribute(a_mosaic, "mosaic", 1u);
meta.addAttribute(a_outFrame, "out_frame", possumwood::opencv::Frame(), possumwood::AttrFlags::kVertical);
meta.addInfluence(a_inFrame, a_outFrame);
meta.addInfluence(a_inMask, a_outFrame);
meta.addInfluence(a_mosaic, a_outFrame);
meta.setCompute(compute);
}
possumwood::NodeImplementation s_impl("opencv/inpaint_laplacian", init);
} // namespace
<commit_msg>Laplacian inpainting simplified by removing mozaic regions<commit_after>#include <possumwood_sdk/node_implementation.h>
#define EIGEN_STACK_ALLOCATION_LIMIT 0
#include <actions/traits.h>
#include <tbb/task_group.h>
#include <Eigen/Sparse>
#include <mutex>
#include <opencv2/opencv.hpp>
#include "frame.h"
namespace {
class Triplets;
class Row {
public:
Row() = default;
void addValue(int64_t row, int64_t col, double value) {
if(value != 0.0)
m_values[(row << 32) + col] += value;
}
private:
Row(const Row&) = delete;
Row& operator=(const Row&) = delete;
std::map<int64_t, double> m_values;
friend class Triplets;
};
class Triplets {
public:
Triplets(int rows, int cols) : m_rowCount(0), m_rows(rows), m_cols(cols) {
}
void addRow(const Row& r) {
for(auto& v : r.m_values) {
int32_t row = v.first >> 32;
int32_t col = v.first & 0xffffffff;
assert(row < m_rows);
assert(col < m_cols);
m_triplets.push_back(Eigen::Triplet<double>(m_rowCount, row * m_cols + col, v.second));
}
++m_rowCount;
}
std::size_t rows() const {
return m_rowCount;
}
const std::vector<Eigen::Triplet<double>>& triplets() const {
return m_triplets;
}
private:
std::vector<Eigen::Triplet<double>> m_triplets;
int m_rowCount, m_rows, m_cols;
friend class Row;
};
static const cv::Mat kernel = (cv::Mat_<double>(3, 3) << 0.0, -1.0, 0.0, -1.0, 4.0, -1.0, 0.0, -1.0, 0.0);
// static const cv::Mat kernel = (cv::Mat_<double>(3,3) <<
// -1.0, -1.0, -1.0,
// -1.0, 8.0, -1.0,
// -1.0, -1.0, -1.0
// );
// static const cv::Mat kernel = (cv::Mat_<double>(3,3) <<
// -1.0, -2.0, -1.0,
// -2.0, 12.0, -2.0,
// -1.0, -2.0, -1.0
// );
// static const cv::Mat kernel = (cv::Mat_<double>(5,5) <<
// 0.0, 0.0, 1.0, 0.0, 0.0,
// 0.0, 2.0, -8.0, 2.0, 0.0,
// 1.0, -8.0, 20.0, -8.0, 1.0,
// 0.0, 2.0, -8.0, 2.0, 0.0,
// 0.0, 0.0, 1.0, 0.0, 0.0
// );
float buildMatrices(const cv::Mat& image, const cv::Mat& mask, Eigen::SparseMatrix<double>& A, Eigen::VectorXd& b) {
Triplets triplets(image.rows, image.cols);
std::vector<double> values;
std::size_t validCtr = 0, interpolatedCtr = 0;
for(int y = 0; y < image.rows; ++y)
for(int x = 0; x < image.cols; ++x) {
Row row;
// masked and/or edge
if(mask.at<unsigned char>(y, x) > 128) {
values.push_back(0.0f);
// convolution
for(int yi = 0; yi < kernel.rows; ++yi)
for(int xi = 0; xi < kernel.cols; ++xi) {
int ypos = y + yi - kernel.rows / 2;
int xpos = x + xi - kernel.cols / 2;
// handling of edges - "clip" (or "mirror", commented out for now)
if(ypos < 0)
// ypos = -ypos;
ypos = 0;
if(ypos >= image.rows)
// ypos = (image.rows-1) - (ypos-image.rows);
ypos = image.rows - 1;
if(xpos < 0)
// xpos = -xpos;
xpos = 0;
if(xpos >= image.cols)
// xpos = (image.cols-1) - (xpos-image.cols);
xpos = image.cols - 1;
row.addValue(ypos, xpos, kernel.at<double>(yi, xi));
}
++interpolatedCtr;
}
// non-masked
if(mask.at<unsigned char>(y, x) <= 128) {
values.push_back(image.at<float>(y, x));
row.addValue(y, x, 1);
++validCtr;
}
triplets.addRow(row);
}
// initialise the sparse matrix
A = Eigen::SparseMatrix<double>(triplets.rows(), image.rows * image.cols);
A.setFromTriplets(triplets.triplets().begin(), triplets.triplets().end());
// and the "b" vector
assert(values.size() == triplets.rows());
b = Eigen::VectorXd(values.size());
for(std::size_t i = 0; i < values.size(); ++i)
b[i] = values[i];
return (float)validCtr / ((float)validCtr + (float)interpolatedCtr);
}
dependency_graph::InAttr<possumwood::opencv::Frame> a_inFrame, a_inMask;
dependency_graph::OutAttr<possumwood::opencv::Frame> a_outFrame;
dependency_graph::State compute(dependency_graph::Values& data) {
dependency_graph::State state;
const cv::Mat& input = *data.get(a_inFrame);
const cv::Mat& mask = *data.get(a_inMask);
if(input.depth() != CV_32F)
throw std::runtime_error("Laplacian inpainting - input image type has to be CV_32F.");
if(mask.type() != CV_8UC1 && mask.type() != CV_8UC3)
throw std::runtime_error("Laplacian inpainting - mask image type has to be CV_8UC1 or CV_8UC3.");
if(input.empty() || mask.empty())
throw std::runtime_error("Laplacian inpainting - empty input image and/or mask.");
if(input.size != mask.size)
throw std::runtime_error("Laplacian inpainting - input and mask image size have to match.");
std::vector<std::vector<float>> x(input.channels(), std::vector<float>(input.rows * input.cols, 0.0f));
tbb::task_group tasks;
std::mutex solve_mutex;
// split the inputs and masks per channel
std::vector<cv::Mat> inputs, masks;
cv::split(input, inputs);
cv::split(mask, masks);
assert((int)inputs.size() == input.channels());
assert((int)masks.size() == mask.channels());
for(int channel = 0; channel < input.channels(); ++channel) {
tasks.run([channel, &inputs, &masks, &x, &state, &solve_mutex]() {
cv::Mat inTile = inputs[channel];
cv::Mat inMask;
if(masks.size() == 1)
inMask = masks[0];
else
inMask = masks[channel];
Eigen::SparseMatrix<double> A;
Eigen::VectorXd b, tmp;
const float ratio = buildMatrices(inTile, inMask, A, b);
if(ratio > 0.003) {
const char* stage = "solver construction";
Eigen::SparseLU<Eigen::SparseMatrix<double> /*, Eigen::NaturalOrdering<int>*/> chol(A);
if(chol.info() == Eigen::Success) {
stage = "analyze pattern";
chol.analyzePattern(A);
if(chol.info() == Eigen::Success) {
stage = "factorize";
chol.factorize(A);
if(chol.info() == Eigen::Success) {
stage = "solve";
tmp = chol.solve(b);
assert(tmp.size() == inTile.rows * inTile.cols);
for(int i = 0; i < tmp.size(); ++i) {
const int row = i / inTile.cols;
const int col = i % inTile.cols;
const int index = row * masks[0].cols + col;
assert((std::size_t)index < x[channel].size());
x[channel][index] = tmp[i];
}
}
}
}
std::lock_guard<std::mutex> guard(solve_mutex);
if(chol.info() == Eigen::NumericalIssue)
state.addWarning("Decomposition failed - Eigen::NumericalIssue at stage " + std::string(stage));
else if(chol.info() == Eigen::NoConvergence)
state.addWarning("Decomposition failed - Eigen::NoConvergence at stage " + std::string(stage));
else if(chol.info() == Eigen::InvalidInput)
state.addWarning("Decomposition failed - Eigen::InvalidInput at stage " + std::string(stage));
else if(chol.info() != Eigen::Success)
state.addWarning("Decomposition failed - unknown error at stage " + std::string(stage));
}
});
}
tasks.wait();
cv::Mat result = input.clone();
for(int yi = 0; yi < result.rows; ++yi)
for(int xi = 0; xi < result.cols; ++xi)
for(int c = 0; c < input.channels(); ++c)
result.ptr<float>(yi, xi)[c] = x[c][yi * result.cols + xi];
data.set(a_outFrame, possumwood::opencv::Frame(result));
return state;
}
void init(possumwood::Metadata& meta) {
meta.addAttribute(a_inFrame, "frame", possumwood::opencv::Frame(), possumwood::AttrFlags::kVertical);
meta.addAttribute(a_inMask, "mask", possumwood::opencv::Frame(), possumwood::AttrFlags::kVertical);
meta.addAttribute(a_outFrame, "out_frame", possumwood::opencv::Frame(), possumwood::AttrFlags::kVertical);
meta.addInfluence(a_inFrame, a_outFrame);
meta.addInfluence(a_inMask, a_outFrame);
meta.setCompute(compute);
}
possumwood::NodeImplementation s_impl("opencv/inpaint_laplacian", init);
} // namespace
<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012 Dennis Nienhüser <earthwings@gentoo.org>
//
#include "MapQuestRunner.h"
#include "MarbleAbstractRunner.h"
#include "MarbleDebug.h"
#include "MarbleLocale.h"
#include "GeoDataDocument.h"
#include "GeoDataPlacemark.h"
#include "GeoDataExtendedData.h"
#include "TinyWebBrowser.h"
#include "routing/Maneuver.h"
#include <QtCore/QString>
#include <QtCore/QVector>
#include <QtCore/QUrl>
#include <QtCore/QTime>
#include <QtCore/QTimer>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtXml/QDomDocument>
namespace Marble
{
MapQuestRunner::MapQuestRunner( QObject *parent ) :
MarbleAbstractRunner( parent ),
m_networkAccessManager( new QNetworkAccessManager( this ) )
{
connect( m_networkAccessManager, SIGNAL( finished( QNetworkReply * ) ),
this, SLOT( retrieveData( QNetworkReply * ) ) );
}
MapQuestRunner::~MapQuestRunner()
{
// nothing to do
}
GeoDataFeature::GeoDataVisualCategory MapQuestRunner::category() const
{
return GeoDataFeature::OsmSite;
}
void MapQuestRunner::retrieveRoute( const RouteRequest *route )
{
if ( route->size() < 2 ) {
return;
}
QHash<QString, QVariant> settings = route->routingProfile().pluginSettings()["mapquest"];
QString url = "http://open.mapquestapi.com/directions/v0/route?callback=renderAdvancedNarrative&outFormat=xml&narrativeType=text&shapeFormat=raw&generalize=0";
GeoDataCoordinates::Unit const degree = GeoDataCoordinates::Degree;
append( &url, "from", QString::number( route->source().latitude( degree ), 'f', 6 ) + "," + QString::number( route->source().longitude( degree ), 'f', 6 ) );
for ( int i=1; i<route->size(); ++i ) {
append( &url, "to", QString::number( route->at( i ).latitude( degree ), 'f', 6 ) + "," + QString::number( route->at( i ).longitude( degree ), 'f', 6 ) );
}
QString const unit = MarbleGlobal::getInstance()->locale()->measurementSystem() == QLocale::MetricSystem ? "k" : "m";
append( &url, "units", unit );
if ( settings["noMotorways"].toInt() ) {
append( &url, "avoids", "Limited Access" );
}
if ( settings["noTollroads"].toInt() ) {
append( &url, "avoids", "Toll road" );
}
if ( settings["noFerries"].toInt() ) {
append( &url, "avoids", "Ferry" );
}
if ( !settings["preference"].toString().isEmpty() ) {
append( &url, "routeType", settings["preference"].toString() );
}
QNetworkReply *reply = m_networkAccessManager->get( QNetworkRequest( QUrl( url ) ) );
connect( reply, SIGNAL( error( QNetworkReply::NetworkError ) ),
this, SLOT( handleError( QNetworkReply::NetworkError ) ) );
QEventLoop eventLoop;
connect( this, SIGNAL( routeCalculated( GeoDataDocument* ) ),
&eventLoop, SLOT( quit() ) );
eventLoop.exec();
}
void MapQuestRunner::retrieveData( QNetworkReply *reply )
{
if ( reply->isFinished() ) {
QByteArray data = reply->readAll();
reply->deleteLater();
//mDebug() << "Download completed: " << data;
GeoDataDocument* document = parse( data );
if ( !document ) {
mDebug() << "Failed to parse the downloaded route data" << data;
}
emit routeCalculated( document );
}
}
void MapQuestRunner::handleError( QNetworkReply::NetworkError error )
{
mDebug() << " Error when retrieving mapquest.org route: " << error;
}
void MapQuestRunner::append(QString *input, const QString &key, const QString &value)
{
*input += "&" + key + "=" + value;
}
int MapQuestRunner::maneuverType( int mapQuestId ) const
{
/** @todo FIXME: review 10, 11 */
switch( mapQuestId ) {
case 0: return Maneuver::Straight ; // straight
case 1: return Maneuver::SlightRight ; // slight right
case 2: return Maneuver::Right ; // right
case 3: return Maneuver::SharpRight ; // sharp right
case 4: return Maneuver::TurnAround ; // reverse
case 5: return Maneuver::SharpLeft ; // sharp left
case 6: return Maneuver::Left ; // left
case 7: return Maneuver::SlightLeft ; // slight left
case 8: return Maneuver::TurnAround ; // right u-turn
case 9: return Maneuver::TurnAround ; // left u-turn
case 10: return Maneuver::Merge ; // right merge
case 11: return Maneuver::Merge ; // left merge
case 12: return Maneuver::Merge ; // right on ramp
case 13: return Maneuver::Merge ; // left on ramp
case 14: return Maneuver::ExitRight ; // right off ramp
case 15: return Maneuver::ExitLeft ; // left off ramp
case 16: return Maneuver::Right ; // right fork
case 17: return Maneuver::Left ; // left fork
case 18: return Maneuver::Continue ; // straight fork
}
return Maneuver::Unknown;
}
GeoDataDocument* MapQuestRunner::parse( const QByteArray &content ) const
{
QDomDocument xml;
if ( !xml.setContent( content ) ) {
mDebug() << "Cannot parse xml file with routing instructions.";
return 0;
}
// mDebug() << xml.toString(2);
QDomElement root = xml.documentElement();
GeoDataDocument* result = new GeoDataDocument();
result->setName( "MapQuest" );
GeoDataPlacemark* routePlacemark = new GeoDataPlacemark;
routePlacemark->setName( "Route" );
GeoDataLineString* routeWaypoints = new GeoDataLineString;
QDomNodeList shapePoints = root.elementsByTagName( "shapePoints" );
if ( shapePoints.size() == 1 ) {
QDomNodeList geometry = shapePoints.at( 0 ).toElement().elementsByTagName( "latLng" );
for ( int i=0; i<geometry.size(); ++i ) {
double const lat = geometry.item( i ).namedItem( "lat" ).toElement().text().toDouble();
double const lon = geometry.item( i ).namedItem( "lng" ).toElement().text().toDouble();
GeoDataCoordinates const position( lon, lat, 0.0, GeoDataCoordinates::Degree );
routeWaypoints->append( position );
}
}
routePlacemark->setGeometry( routeWaypoints );
QString name = "%1 %2 (MapQuest)";
QString unit = "m";
qreal length = routeWaypoints->length( EARTH_RADIUS );
if (length >= 1000) {
length /= 1000.0;
unit = "km";
}
result->setName( name.arg( length, 0, 'f', 1 ).arg( unit ) );
result->append( routePlacemark );
QMap<int,int> mapping;
QDomNodeList maneuvers = root.elementsByTagName( "maneuverIndexes" );
if ( maneuvers.size() == 1 ) {
maneuvers = maneuvers.at( 0 ).childNodes();
for ( int i=0; i<maneuvers.size(); ++i ) {
mapping[i] = maneuvers.at( i ).toElement().text().toInt();
if ( mapping[i] == routeWaypoints->size() ) {
--mapping[i];
}
}
}
QDomNodeList instructions = root.elementsByTagName( "maneuver" );
unsigned int const lastInstruction = instructions.length()-1; // ignore the last 'Welcome to xy' instruction
for ( unsigned int i = 0; i < lastInstruction; ++i ) {
QDomElement node = instructions.item( i ).toElement();
QDomNodeList maneuver = node.elementsByTagName( "turnType" );
QDomNodeList textNodes = node.elementsByTagName( "narrative" );
QDomNodeList points = node.elementsByTagName( "startPoint" );
QDomNodeList streets = node.elementsByTagName( "streets" );
Q_ASSERT( mapping.contains( i ) );
if ( textNodes.size() == 1 && maneuver.size() == 1 && points.size() == 1 && mapping.contains( i ) ) {
GeoDataPlacemark* instruction = new GeoDataPlacemark;
instruction->setName( textNodes.at( 0 ).toElement().text() );
GeoDataExtendedData extendedData;
GeoDataData turnType;
turnType.setName( "turnType" );
turnType.setValue( maneuverType( maneuver.at( 0 ).toElement().text().toInt() ) );
extendedData.addValue( turnType );
if ( streets.size() == 1 ) {
GeoDataData roadName;
roadName.setName( "roadName" );
roadName.setValue( streets.at( 0 ).toElement().text() );
extendedData.addValue( roadName );
}
instruction->setExtendedData( extendedData );
int const start = mapping[i];
int const end = mapping.contains(i+1) ? mapping[i+1] : routeWaypoints->size()-1;
if ( start >= 0 && start < routeWaypoints->size() && end < routeWaypoints->size() ) {
instruction->setName( textNodes.item( 0 ).toElement().text() );
GeoDataLineString *lineString = new GeoDataLineString;
for ( int j=start; j<=end; ++j ) {
*lineString << GeoDataCoordinates( routeWaypoints->at( j ).longitude(), routeWaypoints->at( j ).latitude() );
}
if ( !lineString->isEmpty() ) {
instruction->setGeometry( lineString );
result->append( instruction );
}
}
}
}
return result;
}
} // namespace Marble
#include "MapQuestRunner.moc"
<commit_msg>avoid underrun of variable "lastInstruction"<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012 Dennis Nienhüser <earthwings@gentoo.org>
//
#include "MapQuestRunner.h"
#include "MarbleAbstractRunner.h"
#include "MarbleDebug.h"
#include "MarbleLocale.h"
#include "GeoDataDocument.h"
#include "GeoDataPlacemark.h"
#include "GeoDataExtendedData.h"
#include "TinyWebBrowser.h"
#include "routing/Maneuver.h"
#include <QtCore/QString>
#include <QtCore/QVector>
#include <QtCore/QUrl>
#include <QtCore/QTime>
#include <QtCore/QTimer>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtXml/QDomDocument>
namespace Marble
{
MapQuestRunner::MapQuestRunner( QObject *parent ) :
MarbleAbstractRunner( parent ),
m_networkAccessManager( new QNetworkAccessManager( this ) )
{
connect( m_networkAccessManager, SIGNAL( finished( QNetworkReply * ) ),
this, SLOT( retrieveData( QNetworkReply * ) ) );
}
MapQuestRunner::~MapQuestRunner()
{
// nothing to do
}
GeoDataFeature::GeoDataVisualCategory MapQuestRunner::category() const
{
return GeoDataFeature::OsmSite;
}
void MapQuestRunner::retrieveRoute( const RouteRequest *route )
{
if ( route->size() < 2 ) {
return;
}
QHash<QString, QVariant> settings = route->routingProfile().pluginSettings()["mapquest"];
QString url = "http://open.mapquestapi.com/directions/v0/route?callback=renderAdvancedNarrative&outFormat=xml&narrativeType=text&shapeFormat=raw&generalize=0";
GeoDataCoordinates::Unit const degree = GeoDataCoordinates::Degree;
append( &url, "from", QString::number( route->source().latitude( degree ), 'f', 6 ) + "," + QString::number( route->source().longitude( degree ), 'f', 6 ) );
for ( int i=1; i<route->size(); ++i ) {
append( &url, "to", QString::number( route->at( i ).latitude( degree ), 'f', 6 ) + "," + QString::number( route->at( i ).longitude( degree ), 'f', 6 ) );
}
QString const unit = MarbleGlobal::getInstance()->locale()->measurementSystem() == QLocale::MetricSystem ? "k" : "m";
append( &url, "units", unit );
if ( settings["noMotorways"].toInt() ) {
append( &url, "avoids", "Limited Access" );
}
if ( settings["noTollroads"].toInt() ) {
append( &url, "avoids", "Toll road" );
}
if ( settings["noFerries"].toInt() ) {
append( &url, "avoids", "Ferry" );
}
if ( !settings["preference"].toString().isEmpty() ) {
append( &url, "routeType", settings["preference"].toString() );
}
QNetworkReply *reply = m_networkAccessManager->get( QNetworkRequest( QUrl( url ) ) );
connect( reply, SIGNAL( error( QNetworkReply::NetworkError ) ),
this, SLOT( handleError( QNetworkReply::NetworkError ) ) );
QEventLoop eventLoop;
connect( this, SIGNAL( routeCalculated( GeoDataDocument* ) ),
&eventLoop, SLOT( quit() ) );
eventLoop.exec();
}
void MapQuestRunner::retrieveData( QNetworkReply *reply )
{
if ( reply->isFinished() ) {
QByteArray data = reply->readAll();
reply->deleteLater();
//mDebug() << "Download completed: " << data;
GeoDataDocument* document = parse( data );
if ( !document ) {
mDebug() << "Failed to parse the downloaded route data" << data;
}
emit routeCalculated( document );
}
}
void MapQuestRunner::handleError( QNetworkReply::NetworkError error )
{
mDebug() << " Error when retrieving mapquest.org route: " << error;
}
void MapQuestRunner::append(QString *input, const QString &key, const QString &value)
{
*input += "&" + key + "=" + value;
}
int MapQuestRunner::maneuverType( int mapQuestId ) const
{
/** @todo FIXME: review 10, 11 */
switch( mapQuestId ) {
case 0: return Maneuver::Straight ; // straight
case 1: return Maneuver::SlightRight ; // slight right
case 2: return Maneuver::Right ; // right
case 3: return Maneuver::SharpRight ; // sharp right
case 4: return Maneuver::TurnAround ; // reverse
case 5: return Maneuver::SharpLeft ; // sharp left
case 6: return Maneuver::Left ; // left
case 7: return Maneuver::SlightLeft ; // slight left
case 8: return Maneuver::TurnAround ; // right u-turn
case 9: return Maneuver::TurnAround ; // left u-turn
case 10: return Maneuver::Merge ; // right merge
case 11: return Maneuver::Merge ; // left merge
case 12: return Maneuver::Merge ; // right on ramp
case 13: return Maneuver::Merge ; // left on ramp
case 14: return Maneuver::ExitRight ; // right off ramp
case 15: return Maneuver::ExitLeft ; // left off ramp
case 16: return Maneuver::Right ; // right fork
case 17: return Maneuver::Left ; // left fork
case 18: return Maneuver::Continue ; // straight fork
}
return Maneuver::Unknown;
}
GeoDataDocument* MapQuestRunner::parse( const QByteArray &content ) const
{
QDomDocument xml;
if ( !xml.setContent( content ) ) {
mDebug() << "Cannot parse xml file with routing instructions.";
return 0;
}
// mDebug() << xml.toString(2);
QDomElement root = xml.documentElement();
GeoDataDocument* result = new GeoDataDocument();
result->setName( "MapQuest" );
GeoDataPlacemark* routePlacemark = new GeoDataPlacemark;
routePlacemark->setName( "Route" );
GeoDataLineString* routeWaypoints = new GeoDataLineString;
QDomNodeList shapePoints = root.elementsByTagName( "shapePoints" );
if ( shapePoints.size() == 1 ) {
QDomNodeList geometry = shapePoints.at( 0 ).toElement().elementsByTagName( "latLng" );
for ( int i=0; i<geometry.size(); ++i ) {
double const lat = geometry.item( i ).namedItem( "lat" ).toElement().text().toDouble();
double const lon = geometry.item( i ).namedItem( "lng" ).toElement().text().toDouble();
GeoDataCoordinates const position( lon, lat, 0.0, GeoDataCoordinates::Degree );
routeWaypoints->append( position );
}
}
routePlacemark->setGeometry( routeWaypoints );
QString name = "%1 %2 (MapQuest)";
QString unit = "m";
qreal length = routeWaypoints->length( EARTH_RADIUS );
if (length >= 1000) {
length /= 1000.0;
unit = "km";
}
result->setName( name.arg( length, 0, 'f', 1 ).arg( unit ) );
result->append( routePlacemark );
QMap<int,int> mapping;
QDomNodeList maneuvers = root.elementsByTagName( "maneuverIndexes" );
if ( maneuvers.size() == 1 ) {
maneuvers = maneuvers.at( 0 ).childNodes();
for ( int i=0; i<maneuvers.size(); ++i ) {
mapping[i] = maneuvers.at( i ).toElement().text().toInt();
if ( mapping[i] == routeWaypoints->size() ) {
--mapping[i];
}
}
}
QDomNodeList instructions = root.elementsByTagName( "maneuver" );
unsigned int const lastInstruction = qMax<int>( 0, instructions.length()-1 ); // ignore the last 'Welcome to xy' instruction
for ( unsigned int i = 0; i < lastInstruction; ++i ) {
QDomElement node = instructions.item( i ).toElement();
QDomNodeList maneuver = node.elementsByTagName( "turnType" );
QDomNodeList textNodes = node.elementsByTagName( "narrative" );
QDomNodeList points = node.elementsByTagName( "startPoint" );
QDomNodeList streets = node.elementsByTagName( "streets" );
Q_ASSERT( mapping.contains( i ) );
if ( textNodes.size() == 1 && maneuver.size() == 1 && points.size() == 1 && mapping.contains( i ) ) {
GeoDataPlacemark* instruction = new GeoDataPlacemark;
instruction->setName( textNodes.at( 0 ).toElement().text() );
GeoDataExtendedData extendedData;
GeoDataData turnType;
turnType.setName( "turnType" );
turnType.setValue( maneuverType( maneuver.at( 0 ).toElement().text().toInt() ) );
extendedData.addValue( turnType );
if ( streets.size() == 1 ) {
GeoDataData roadName;
roadName.setName( "roadName" );
roadName.setValue( streets.at( 0 ).toElement().text() );
extendedData.addValue( roadName );
}
instruction->setExtendedData( extendedData );
int const start = mapping[i];
int const end = mapping.contains(i+1) ? mapping[i+1] : routeWaypoints->size()-1;
if ( start >= 0 && start < routeWaypoints->size() && end < routeWaypoints->size() ) {
instruction->setName( textNodes.item( 0 ).toElement().text() );
GeoDataLineString *lineString = new GeoDataLineString;
for ( int j=start; j<=end; ++j ) {
*lineString << GeoDataCoordinates( routeWaypoints->at( j ).longitude(), routeWaypoints->at( j ).latitude() );
}
if ( !lineString->isEmpty() ) {
instruction->setGeometry( lineString );
result->append( instruction );
}
}
}
}
return result;
}
} // namespace Marble
#include "MapQuestRunner.moc"
<|endoftext|>
|
<commit_before>/*
Testing out: Immediate Mode GUI approach
*/
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_image.h>
#include "../MasterHeader.h"
struct ui_state
{
//the id of the widget the mouse cursor is over on
int hoveredID;
//the id of the widget the mouse cursor has pressed
int pressedID;
} ui_global_state;
//draws the button relative to the game's window
//returns true if button is pressed, otherwise it returns false
bool drawButton(SDL_Renderer* render,int ui_id, const SDL_Rect* bounds, const SDL_Color& color,SDL_Texture* text)
{
ui_global_state.hoveredID = 0;
//changes the global state depending on these conditions
SDL_Point mousePos;
bool mousePressed = SDL_GetMouseState(&mousePos.x, &mousePos.y) & SDL_BUTTON(SDL_BUTTON_LEFT);
if (SDL_PointInRect(&mousePos, bounds))
{
ui_global_state.hoveredID = ui_id;
if (mousePressed)
{
ui_global_state.pressedID = ui_id;
}
}
//this updates how the button is drawn depending on what the global state is in
SDL_SetRenderDrawBlendMode(render, SDL_BLENDMODE_BLEND);
//is pressed
if (ui_global_state.pressedID == ui_id && ui_global_state.hoveredID == ui_id)
{
SDL_SetRenderDrawColor(render, color.r / 2, color.g / 2, color.b / 2, color.a);
SDL_RenderFillRect(render, bounds);
}
else if (ui_global_state.hoveredID == ui_id) // hovered over
{
SDL_SetRenderDrawColor(render, color.r, color.g, color.b, color.a);
SDL_RenderFillRect(render, bounds);
SDL_SetRenderDrawColor(render, 255, 0, 255, 255 / 2);
SDL_RenderFillRect(render, bounds);
}
else //inactive
{
SDL_SetRenderDrawColor(render, color.r, color.g, color.b, color.a);
SDL_RenderFillRect(render, bounds);
}
//render text
SDL_Rect textArea;
SDL_QueryTexture(text, NULL, NULL, &textArea.w,&textArea.h);
textArea.x = bounds->x + (bounds->w - textArea.w) / 2;
textArea.y = bounds->y + (bounds->h - textArea.h) / 2;
SDL_RenderCopy(render, text, NULL, &textArea);
//set color back to black after drawing
SDL_SetRenderDrawColor(render, 0, 0, 0, 0);
//evaluate if the button was pressed by checking to see if the button is released this frame
if (ui_global_state.pressedID == ui_id && ui_global_state.hoveredID == ui_id && !mousePressed)
{
ui_global_state.pressedID = 0;
return true;
}
//button was not pressed
return false;
}
int main(int argc, char* argv[])
{
Core core;
SDL_Renderer* render = core.getRenderer();
ImageStore store(render);
string mainPath(SDL_GetBasePath());
mainPath += string("resources\\");
string fontPath = mainPath + string("Rubik_Mono_One/RubikMonoOne-Regular.ttf");
TTF_Font* font = TTF_OpenFont(fontPath.c_str(), 16);
SDL_Color textColor{ 0,0,0 };
const char* const sampleText = "OK";
SDL_Surface* textSurface = TTF_RenderText_Blended(font, sampleText, textColor);
SDL_Texture* textTextureSolid = SDL_CreateTextureFromSurface(render, textSurface);
SDL_FreeSurface(textSurface);
SDL_Point mousePos{ 0,0 };
SDL_Point oldMousePos{ 0,0 };
bool mouseClicked = false;
//initial slider properties
SDL_Color scrollWheelColor = { 0,0,255,255 };
SDL_Rect scrollWheelRect;
scrollWheelRect.x = 100;
scrollWheelRect.y = 50;
scrollWheelRect.w = 20;
scrollWheelRect.h = 20;
SDL_Color scrollBarColor = { 255,255,255,255 };
SDL_Rect scrollBarRect;
scrollBarRect.x = 100;
scrollBarRect.y = 50;
scrollBarRect.w = 20;
scrollBarRect.h = 160;
//---------------- Game Loop ------------------//
//observedDeltaTime is measured in milliseconds
float observedDeltaTime = core.getTargetDeltaTime();
float deltaTime = observedDeltaTime / 1000.0f;//converts from milliseconds to seconds
//to avoid unnecessary context switches os might do (which I have no control over.. cache the target delta time)
float targetDeltaTime = core.getTargetDeltaTime();
Uint64 observedFPS = core.getTargetFPS();
float currentTime = 0.0f;
Uint64 performanceFrequency = SDL_GetPerformanceFrequency();
Uint64 startCount = SDL_GetPerformanceCounter();
Uint64 endCount;
bool running = true;
while (running)
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
running = false;
break;
case SDL_MOUSEMOTION:
mousePos.x = event.button.x;
mousePos.y = event.button.y;
break;
case SDL_MOUSEBUTTONDOWN:
mouseClicked = true;
break;
case SDL_MOUSEBUTTONUP:
mouseClicked = false;
break;
}
}
SDL_Rect buttonArea;
buttonArea.w = 100;
buttonArea.h = 20;
buttonArea.x = 85;
buttonArea.y = 230;
if (drawButton(render, 1, &buttonArea, SDL_Color{ 0,255,0,255 }, textTextureSolid))
{
puts("button pressed 1");
}
SDL_Rect buttonArea2;
buttonArea2.w = 100;
buttonArea2.h = 20;
buttonArea2.x = SCREEN_WIDTH / 2 - buttonArea2.w / 2;
buttonArea2.y = SCREEN_HEIGHT / 2 - buttonArea2.h / 2;
if (drawButton(render, 2, &buttonArea2, SDL_Color{ 255,255,0,255 },textTextureSolid))
{
//logic where button does something when clicked on
puts("button pressed 2");
}
//draw a slider
int slider_id = 3;
//check if mouse is on scrollbar
if (SDL_PointInRect(&mousePos, &scrollBarRect))
{
ui_global_state.hoveredID = slider_id;
if (mouseClicked && ui_global_state.pressedID == 0)
{
ui_global_state.pressedID = slider_id;
}
}
SDL_SetRenderDrawBlendMode(render, SDL_BLENDMODE_BLEND);
//draw scroll bar
SDL_SetRenderDrawColor(render, scrollBarColor.r, scrollBarColor.g, scrollBarColor.b, scrollBarColor.a);
SDL_RenderFillRect(render, &scrollBarRect);
//1st goal: keep scroll knob in place anywhere that it is clicked on(do not move the knob if mouse delta y == 0)
//2nd goal: move the scroll knob when mouse delta y != 0;
//is pressed
if (ui_global_state.pressedID == slider_id)
{
ui_global_state.pressedID = 0;
int deltaMousePos = mousePos.y - oldMousePos.y;
if (deltaMousePos != 0)
{
int projectedPos = scrollWheelRect.y + deltaMousePos;
//3rd goal: keep the scroll knob in place when it touches the top bounds
if (projectedPos < scrollBarRect.y)
scrollWheelRect.y = scrollBarRect.y;
//4th goal: keep the scroll knob in place when it touches the bottom bounds
else if (projectedPos + scrollWheelRect.h > scrollBarRect.y + scrollBarRect.h)
scrollWheelRect.y = (scrollBarRect.y + scrollBarRect.h) - scrollWheelRect.h;
else
scrollWheelRect.y = projectedPos;
}
//render scroll wheel
SDL_SetRenderDrawColor(render, scrollWheelColor.r / 2, scrollWheelColor.g / 2, scrollWheelColor.b / 2, scrollWheelColor.a);
SDL_RenderFillRect(render, &scrollWheelRect);
}
else //not pressed
{
//render scroll wheel
SDL_SetRenderDrawColor(render, scrollWheelColor.r, scrollWheelColor.g, scrollWheelColor.b, scrollWheelColor.a);
SDL_RenderFillRect(render, &scrollWheelRect);
}
oldMousePos.x = mousePos.x;
oldMousePos.y = mousePos.y;
SDL_RenderPresent(render);
SDL_SetRenderDrawColor(render, 0, 0, 0, 0);
SDL_RenderClear(render);
endCount = SDL_GetPerformanceCounter();
observedDeltaTime = (1000.0f * (endCount - startCount)) / performanceFrequency;//gives ms
observedFPS = performanceFrequency / (endCount - startCount);
//if the computer can process the update and draw functions faster than 60 fps...
//cap the frame-rate here to ensure that all computers play roughly around the same fps
float msDifference = targetDeltaTime - observedDeltaTime;
if (msDifference > 0)
{
SDL_Delay((Uint32)msDifference);
//Note: must re-record the times after the delay since the times before the delay maybe
//under 16.666 ms
endCount = SDL_GetPerformanceCounter();
observedDeltaTime = (1000.0f * (endCount - startCount)) / performanceFrequency;//gives ms
observedFPS = performanceFrequency / (endCount - startCount);
}
currentTime += observedDeltaTime;
deltaTime = observedDeltaTime / 1000.0f;
startCount = endCount;
//display fps text in title
std::string title("Beat Em Left");
title += std::string(" | FPS: ") + std::to_string(observedFPS);
SDL_SetWindowTitle(core.getWindow(), title.c_str());
}
SDL_DestroyTexture(textTextureSolid);
TTF_CloseFont(font);
font = NULL;
return 0;
}<commit_msg>Add 2 versions of drawVerticalSlider<commit_after>/*
Testing out: Immediate Mode GUI approach
Note: ids for each ui object is used to distinguish which ui is being hovered on or pressed on,
If only a single global state such as an enum was used to define the states of each button, all buttons would be affected by the change
*/
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_image.h>
#include "../MasterHeader.h"
struct ui_state
{
//the id of the widget the mouse cursor is over on
int hoveredID;
//the id of the widget the mouse cursor has pressed
int pressedID;
SDL_Point mousePos;
SDL_Point oldMousePos;
} ui_global_state;
//draws the button relative to the game's window
//returns true if button is pressed, otherwise it returns false
bool drawButton(SDL_Renderer* render,int ui_id, const SDL_Rect* bounds, const SDL_Color& color,SDL_Texture* text)
{
ui_global_state.hoveredID = 0;
//changes the global state depending on these conditions
SDL_Point mousePos;
bool mousePressed = SDL_GetMouseState(&mousePos.x, &mousePos.y) & SDL_BUTTON(SDL_BUTTON_LEFT);
if (SDL_PointInRect(&mousePos, bounds))
{
ui_global_state.hoveredID = ui_id;
if (mousePressed)
{
ui_global_state.pressedID = ui_id;
}
}
//this updates how the button is drawn depending on what the global state is in
SDL_SetRenderDrawBlendMode(render, SDL_BLENDMODE_BLEND);
//is pressed
if (ui_global_state.pressedID == ui_id && ui_global_state.hoveredID == ui_id)
{
SDL_SetRenderDrawColor(render, color.r / 2, color.g / 2, color.b / 2, color.a);
SDL_RenderFillRect(render, bounds);
}
else if (ui_global_state.hoveredID == ui_id) // hovered over
{
SDL_SetRenderDrawColor(render, color.r, color.g, color.b, color.a);
SDL_RenderFillRect(render, bounds);
SDL_SetRenderDrawColor(render, 255, 0, 255, 255 / 2);
SDL_RenderFillRect(render, bounds);
}
else //inactive
{
SDL_SetRenderDrawColor(render, color.r, color.g, color.b, color.a);
SDL_RenderFillRect(render, bounds);
}
//render text
SDL_Rect textArea;
SDL_QueryTexture(text, NULL, NULL, &textArea.w,&textArea.h);
textArea.x = bounds->x + (bounds->w - textArea.w) / 2;
textArea.y = bounds->y + (bounds->h - textArea.h) / 2;
SDL_RenderCopy(render, text, NULL, &textArea);
//set color back to black after drawing
SDL_SetRenderDrawColor(render, 0, 0, 0, 0);
//evaluate if the button was pressed by checking to see if the button is released this frame
if (ui_global_state.pressedID == ui_id && ui_global_state.hoveredID == ui_id && !mousePressed)
{
ui_global_state.pressedID = 0;
return true;
}
//button was not pressed
return false;
}
//1st version
void drawVerticalSlider(SDL_Renderer* render, int ui_id, const SDL_Color& knobColor, const SDL_Color& barColor, SDL_Rect* knobBounds, const SDL_Rect* barBounds, const SDL_Point* mousePos)
{
SDL_Point newMousePos;
bool mouseClicked = SDL_GetMouseState(&newMousePos.x, &newMousePos.y) & SDL_BUTTON(SDL_BUTTON_LEFT);
//determine if scroll bar is hovered on or pressed on
if(SDL_PointInRect(mousePos,barBounds))
{
ui_global_state.hoveredID = ui_id;
if (mouseClicked)
{
ui_global_state.pressedID = ui_id;
}
}
//1st goal: keep scroll knob in place anywhere that it is clicked on(do not move the knob if mouse delta y == 0)
//2nd goal: move the scroll knob when mouse delta y != 0;
if (ui_global_state.pressedID == ui_id)
{
int deltaMousePos = newMousePos.y - mousePos->y;
if (deltaMousePos != 0)
{
int projectedPos = knobBounds->y + deltaMousePos;
//3rd goal: keep the scroll knob in place when it touches the top bounds
if (projectedPos < barBounds->y)
knobBounds->y = barBounds->y;
//4th goal: keep the scroll knob in place when it touches the bottom bounds
else if (projectedPos + knobBounds->h > barBounds->y + barBounds->h)
knobBounds->y = (barBounds->y + barBounds->h) - knobBounds->h;
else
knobBounds->y = projectedPos;
}
}
SDL_SetRenderDrawBlendMode(render, SDL_BLENDMODE_BLEND);
//draw scroll bar
SDL_SetRenderDrawColor(render, barColor.r, barColor.g, barColor.b, barColor.a);
SDL_RenderFillRect(render, barBounds);
//render knob
if (ui_global_state.pressedID == ui_id)
{
ui_global_state.pressedID = 0;
SDL_SetRenderDrawColor(render, knobColor.r / 2, knobColor.g / 2, knobColor.b / 2, knobColor.a);
SDL_RenderFillRect(render, knobBounds);
}
else
{
SDL_SetRenderDrawColor(render, knobColor.r, knobColor.g, knobColor.b, knobColor.a);
SDL_RenderFillRect(render, knobBounds);
}
}
//returns the position of the knob as a floating point value mapped between a min and max float value.
//Note: initialValue must be a floating point value between 0.0f and 1.0f inclusive
//2nd version
float drawVerticalSlider(SDL_Renderer* render, int ui_id, const SDL_Rect* bounds, float initialValue)
{
//construct the knob bounds
float knobScale = 0.25f;
SDL_Rect knobBounds;
knobBounds.x = bounds->x;
knobBounds.w = bounds->w;
knobBounds.h = (int)(knobScale * bounds->h);
SDL_Color knobColor{ 160, 160,160,255 };
SDL_Color barColor{ 114, 99, 99, 255 };
SDL_Point newMousePos;
bool mouseClicked = SDL_GetMouseState(&newMousePos.x, &newMousePos.y) & SDL_BUTTON(SDL_BUTTON_LEFT);
//determine if scroll bar is hovered over or pressed on
if (SDL_PointInRect(&newMousePos, bounds))
{
ui_global_state.hoveredID = ui_id;
if (mouseClicked)
{
ui_global_state.pressedID = ui_id;
}
}
//keep the scroll knob in place anywhere that it is clicked on
//move the scroll knob by the amount the mouse position changes (delta mouse pos)
float minValue = 0.0f;
float maxValue = 1.0f;
float value = (initialValue < minValue) ? minValue : (initialValue > maxValue) ? maxValue : initialValue;
knobBounds.y = (int)(value * bounds->h) + bounds->y;
if (ui_global_state.pressedID == ui_id)
{
int deltaMousePos = newMousePos.y - ui_global_state.oldMousePos.y;
if (deltaMousePos != 0)
{
//deltaV ranges from -1 to 1 inclusive
float deltaV = (float)deltaMousePos / bounds->h;
value += deltaV;
value = (value > maxValue) ? maxValue : (value < minValue) ? minValue : value;
}
//printf("value: %f\n", value);
knobBounds.y = (int)(value * bounds->h) + bounds->y;
}
//since the knob has a height and its coordinates are measured from its top-left corner,
//its necessary to make sure the knob doesn't move past its scrollable area.
if (knobBounds.y + knobBounds.h > bounds->y + bounds->h)
knobBounds.y = (bounds->y + bounds->h) - knobBounds.h;
//rendering
SDL_SetRenderDrawBlendMode(render, SDL_BLENDMODE_BLEND);
//draw scroll bar
SDL_SetRenderDrawColor(render, barColor.r, barColor.g, barColor.b, barColor.a);
SDL_RenderFillRect(render, bounds);
//draw scroll knob
if (ui_global_state.pressedID == ui_id)
{
ui_global_state.pressedID = 0;
SDL_SetRenderDrawColor(render, knobColor.r / 2, knobColor.g / 2, knobColor.b / 2, knobColor.a);
SDL_RenderFillRect(render, &knobBounds);
}
else
{
SDL_SetRenderDrawColor(render, knobColor.r, knobColor.g, knobColor.b, knobColor.a);
SDL_RenderFillRect(render, &knobBounds);
}
return value;
}
int main(int argc, char* argv[])
{
Core core;
SDL_Renderer* render = core.getRenderer();
ImageStore store(render);
string mainPath(SDL_GetBasePath());
mainPath += string("resources\\");
string fontPath = mainPath + string("Rubik_Mono_One/RubikMonoOne-Regular.ttf");
TTF_Font* font = TTF_OpenFont(fontPath.c_str(), 16);
SDL_Color textColor{ 0,0,0 };
const char* const sampleText = "OK";
SDL_Surface* textSurface = TTF_RenderText_Blended(font, sampleText, textColor);
SDL_Texture* textTextureSolid = SDL_CreateTextureFromSurface(render, textSurface);
SDL_FreeSurface(textSurface);
SDL_Point mousePos{ 0,0 };
SDL_Point oldMousePos{ 0,0 };
bool mouseClicked = false;
//initial slider properties
float initialScrollValue = 0.0f;
SDL_Color scrollWheelColor = { 0,0,255,255 };
SDL_Rect scrollWheelRect;
scrollWheelRect.x = 100;
scrollWheelRect.y = 50;
scrollWheelRect.w = 20;
scrollWheelRect.h = 20;
SDL_Color scrollBarColor = { 255,255,255,255 };
SDL_Rect scrollBarRect;
scrollBarRect.x = 100;
scrollBarRect.y = 50;
scrollBarRect.w = 20;
scrollBarRect.h = 160;
//---------------- Game Loop ------------------//
//observedDeltaTime is measured in milliseconds
float observedDeltaTime = core.getTargetDeltaTime();
float deltaTime = observedDeltaTime / 1000.0f;//converts from milliseconds to seconds
//to avoid unnecessary context switches os might do (which I have no control over.. cache the target delta time)
float targetDeltaTime = core.getTargetDeltaTime();
Uint64 observedFPS = core.getTargetFPS();
float currentTime = 0.0f;
Uint64 performanceFrequency = SDL_GetPerformanceFrequency();
Uint64 startCount = SDL_GetPerformanceCounter();
Uint64 endCount;
bool running = true;
while (running)
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
running = false;
break;
case SDL_MOUSEMOTION:
mousePos.x = event.button.x;
mousePos.y = event.button.y;
ui_global_state.mousePos.x = event.button.x;
ui_global_state.mousePos.y = event.button.y;
break;
case SDL_MOUSEBUTTONDOWN:
mouseClicked = true;
printf("mousePos: (%d, %d)\n", mousePos.x, mousePos.y);
break;
case SDL_MOUSEBUTTONUP:
mouseClicked = false;
break;
}
}
SDL_Rect buttonArea;
buttonArea.w = 100;
buttonArea.h = 20;
buttonArea.x = 85;
buttonArea.y = 230;
if (drawButton(render, 1, &buttonArea, SDL_Color{ 0,255,0,255 }, textTextureSolid))
{
puts("button pressed 1");
}
SDL_Rect buttonArea2;
buttonArea2.w = 100;
buttonArea2.h = 20;
buttonArea2.x = SCREEN_WIDTH / 2 - buttonArea2.w / 2;
buttonArea2.y = SCREEN_HEIGHT / 2 - buttonArea2.h / 2;
if (drawButton(render, 2, &buttonArea2, SDL_Color{ 255,255,0,255 },textTextureSolid))
{
//logic where button does something when clicked on
puts("button pressed 2");
}
/*
Params needed to construct vertical slider:
SDL_Renderer,
int id,
const SDL_Color& knobColor,
const SDL_Color& barColor,
SDL_Rect* knobBounds,
const SDL_Rect* barBounds,
const SDL_Point* mousePos;
*/
//1st version
drawVerticalSlider(render, 3, scrollWheelColor, scrollBarColor, &scrollWheelRect, &scrollBarRect, &oldMousePos);
//2nd version
SDL_Rect bounds2;
bounds2.x = 300;
bounds2.y = 150;
bounds2.w = 20;
bounds2.h = 150;
initialScrollValue = drawVerticalSlider(render, 4, &bounds2, initialScrollValue);
printf("scrollValue: %f\n", initialScrollValue);
oldMousePos.x = mousePos.x;
oldMousePos.y = mousePos.y;
ui_global_state.oldMousePos.x = mousePos.x;
ui_global_state.oldMousePos.y = mousePos.y;
SDL_RenderPresent(render);
SDL_SetRenderDrawColor(render, 0, 0, 0, 0);
SDL_RenderClear(render);
endCount = SDL_GetPerformanceCounter();
observedDeltaTime = (1000.0f * (endCount - startCount)) / performanceFrequency;//gives ms
observedFPS = performanceFrequency / (endCount - startCount);
//if the computer can process the update and draw functions faster than 60 fps...
//cap the frame-rate here to ensure that all computers play roughly around the same fps
float msDifference = targetDeltaTime - observedDeltaTime;
if (msDifference > 0)
{
SDL_Delay((Uint32)msDifference);
//Note: must re-record the times after the delay since the times before the delay maybe
//under 16.666 ms
endCount = SDL_GetPerformanceCounter();
observedDeltaTime = (1000.0f * (endCount - startCount)) / performanceFrequency;//gives ms
observedFPS = performanceFrequency / (endCount - startCount);
}
currentTime += observedDeltaTime;
deltaTime = observedDeltaTime / 1000.0f;
startCount = endCount;
//display fps text in title
std::string title("Beat Em Left");
title += std::string(" | FPS: ") + std::to_string(observedFPS);
SDL_SetWindowTitle(core.getWindow(), title.c_str());
}
SDL_DestroyTexture(textTextureSolid);
TTF_CloseFont(font);
font = NULL;
return 0;
}<|endoftext|>
|
<commit_before>void lb_populate_function_pass_manager(LLVMPassManagerRef fpm, bool ignore_memcpy_pass, i32 optimization_level) {
// NOTE(bill): Treat -opt:3 as if it was -opt:2
// TODO(bill): Determine which opt definitions should exist in the first place
optimization_level = gb_clamp(optimization_level, 0, 2);
if (!ignore_memcpy_pass) {
LLVMAddMemCpyOptPass(fpm);
}
LLVMAddPromoteMemoryToRegisterPass(fpm);
LLVMAddMergedLoadStoreMotionPass(fpm);
LLVMAddEarlyCSEPass(fpm);
// LLVMAddEarlyCSEMemSSAPass(fpm);
LLVMAddConstantPropagationPass(fpm);
LLVMAddMergedLoadStoreMotionPass(fpm);
LLVMAddPromoteMemoryToRegisterPass(fpm);
LLVMAddCFGSimplificationPass(fpm);
// LLVMAddSLPVectorizePass(fpm);
// LLVMAddLoopVectorizePass(fpm);
// LLVMAddScalarizerPass(fpm);
// LLVMAddLoopIdiomPass(fpm);
if (optimization_level == 0) {
return;
}
#if 0
LLVMAddSCCPPass(fpm);
LLVMAddPromoteMemoryToRegisterPass(fpm);
LLVMAddUnifyFunctionExitNodesPass(fpm);
LLVMAddCFGSimplificationPass(fpm);
// LLVMAddScalarReplAggregatesPass(fpm);
LLVMAddEarlyCSEPass(fpm);
LLVMAddLowerExpectIntrinsicPass(fpm);
#endif
}
void lb_add_function_simplifcation_passes(LLVMPassManagerRef mpm, i32 optimization_level) {
// LLVMAddScalarReplAggregatesPass(mpm);
LLVMAddEarlyCSEMemSSAPass(mpm);
LLVMAddGVNPass(mpm);
LLVMAddCFGSimplificationPass(mpm);
LLVMAddJumpThreadingPass(mpm);
// if (optimization_level > 2) {
// LLVMAddAggressiveInstCombinerPass(mpm);
// }
LLVMAddInstructionCombiningPass(mpm);
LLVMAddSimplifyLibCallsPass(mpm);
LLVMAddTailCallEliminationPass(mpm);
LLVMAddCFGSimplificationPass(mpm);
LLVMAddReassociatePass(mpm);
LLVMAddLoopRotatePass(mpm);
LLVMAddLICMPass(mpm);
LLVMAddLoopUnswitchPass(mpm);
LLVMAddCFGSimplificationPass(mpm);
LLVMAddInstructionCombiningPass(mpm);
LLVMAddIndVarSimplifyPass(mpm);
LLVMAddLoopIdiomPass(mpm);
LLVMAddLoopDeletionPass(mpm);
LLVMAddLoopUnrollPass(mpm);
LLVMAddMergedLoadStoreMotionPass(mpm);
LLVMAddGVNPass(mpm);
LLVMAddMemCpyOptPass(mpm);
LLVMAddSCCPPass(mpm);
LLVMAddBitTrackingDCEPass(mpm);
LLVMAddInstructionCombiningPass(mpm);
LLVMAddJumpThreadingPass(mpm);
LLVMAddCorrelatedValuePropagationPass(mpm);
LLVMAddDeadStoreEliminationPass(mpm);
LLVMAddLICMPass(mpm);
LLVMAddLoopRerollPass(mpm);
LLVMAddAggressiveDCEPass(mpm);
LLVMAddCFGSimplificationPass(mpm);
LLVMAddInstructionCombiningPass(mpm);
}
void lb_populate_module_pass_manager(LLVMTargetMachineRef target_machine, LLVMPassManagerRef mpm, i32 optimization_level) {
// NOTE(bill): Treat -opt:3 as if it was -opt:2
// TODO(bill): Determine which opt definitions should exist in the first place
optimization_level = gb_clamp(optimization_level, 0, 2);
if (optimization_level >= 2) {
// NOTE(bill, 2021-03-29: use this causes invalid code generation)
// LLVMPassManagerBuilderRef pmb = LLVMPassManagerBuilderCreate();
// LLVMPassManagerBuilderPopulateModulePassManager(pmb, mpm);
// LLVMPassManagerBuilderPopulateLTOPassManager(pmb, mpm, false, true);
// LLVMPassManagerBuilderSetOptLevel(pmb, optimization_level);
// LLVMPassManagerBuilderSetSizeLevel(pmb, optimization_level);
}
LLVMAddAlwaysInlinerPass(mpm);
LLVMAddStripDeadPrototypesPass(mpm);
LLVMAddAnalysisPasses(target_machine, mpm);
LLVMAddPruneEHPass(mpm);
if (optimization_level == 0) {
return;
}
LLVMAddGlobalDCEPass(mpm);
LLVMAddIPSCCPPass(mpm);
LLVMAddCalledValuePropagationPass(mpm);
LLVMAddGlobalOptimizerPass(mpm);
LLVMAddDeadArgEliminationPass(mpm);
// LLVMAddConstantMergePass(mpm); // ???
LLVMAddInstructionCombiningPass(mpm);
LLVMAddCFGSimplificationPass(mpm);
LLVMAddPruneEHPass(mpm);
if (optimization_level < 2) {
return;
}
LLVMAddFunctionInliningPass(mpm);
lb_add_function_simplifcation_passes(mpm, optimization_level);
LLVMAddGlobalDCEPass(mpm);
LLVMAddGlobalOptimizerPass(mpm);
// LLVMAddLowerConstantIntrinsicsPass(mpm);
LLVMAddLoopRotatePass(mpm);
LLVMAddLoopVectorizePass(mpm);
LLVMAddInstructionCombiningPass(mpm);
if (optimization_level >= 2) {
LLVMAddEarlyCSEPass(mpm);
LLVMAddCorrelatedValuePropagationPass(mpm);
LLVMAddLICMPass(mpm);
LLVMAddLoopUnswitchPass(mpm);
LLVMAddCFGSimplificationPass(mpm);
LLVMAddInstructionCombiningPass(mpm);
}
LLVMAddCFGSimplificationPass(mpm);
LLVMAddSLPVectorizePass(mpm);
LLVMAddLICMPass(mpm);
LLVMAddAlignmentFromAssumptionsPass(mpm);
LLVMAddStripDeadPrototypesPass(mpm);
if (optimization_level >= 2) {
LLVMAddGlobalDCEPass(mpm);
LLVMAddConstantMergePass(mpm);
}
LLVMAddCFGSimplificationPass(mpm);
#if 0
#endif
}
<commit_msg>Remove dead code and comments<commit_after>void lb_populate_function_pass_manager(LLVMPassManagerRef fpm, bool ignore_memcpy_pass, i32 optimization_level) {
// NOTE(bill): Treat -opt:3 as if it was -opt:2
// TODO(bill): Determine which opt definitions should exist in the first place
optimization_level = gb_clamp(optimization_level, 0, 2);
if (!ignore_memcpy_pass) {
LLVMAddMemCpyOptPass(fpm);
}
LLVMAddPromoteMemoryToRegisterPass(fpm);
LLVMAddMergedLoadStoreMotionPass(fpm);
LLVMAddEarlyCSEPass(fpm);
// LLVMAddEarlyCSEMemSSAPass(fpm);
LLVMAddConstantPropagationPass(fpm);
LLVMAddMergedLoadStoreMotionPass(fpm);
LLVMAddPromoteMemoryToRegisterPass(fpm);
LLVMAddCFGSimplificationPass(fpm);
// LLVMAddSLPVectorizePass(fpm);
// LLVMAddLoopVectorizePass(fpm);
// LLVMAddScalarizerPass(fpm);
// LLVMAddLoopIdiomPass(fpm);
if (optimization_level == 0) {
return;
}
#if 1
LLVMAddSCCPPass(fpm);
LLVMAddPromoteMemoryToRegisterPass(fpm);
LLVMAddUnifyFunctionExitNodesPass(fpm);
LLVMAddCFGSimplificationPass(fpm);
LLVMAddEarlyCSEPass(fpm);
LLVMAddLowerExpectIntrinsicPass(fpm);
#endif
}
void lb_add_function_simplifcation_passes(LLVMPassManagerRef mpm, i32 optimization_level) {
LLVMAddEarlyCSEMemSSAPass(mpm);
LLVMAddGVNPass(mpm);
LLVMAddCFGSimplificationPass(mpm);
LLVMAddJumpThreadingPass(mpm);
// if (optimization_level > 2) {
// LLVMAddAggressiveInstCombinerPass(mpm);
// }
LLVMAddInstructionCombiningPass(mpm);
LLVMAddSimplifyLibCallsPass(mpm);
LLVMAddTailCallEliminationPass(mpm);
LLVMAddCFGSimplificationPass(mpm);
LLVMAddReassociatePass(mpm);
LLVMAddLoopRotatePass(mpm);
LLVMAddLICMPass(mpm);
LLVMAddLoopUnswitchPass(mpm);
LLVMAddCFGSimplificationPass(mpm);
LLVMAddInstructionCombiningPass(mpm);
LLVMAddIndVarSimplifyPass(mpm);
LLVMAddLoopIdiomPass(mpm);
LLVMAddLoopDeletionPass(mpm);
LLVMAddLoopUnrollPass(mpm);
LLVMAddMergedLoadStoreMotionPass(mpm);
LLVMAddGVNPass(mpm);
LLVMAddMemCpyOptPass(mpm);
LLVMAddSCCPPass(mpm);
LLVMAddBitTrackingDCEPass(mpm);
LLVMAddInstructionCombiningPass(mpm);
LLVMAddJumpThreadingPass(mpm);
LLVMAddCorrelatedValuePropagationPass(mpm);
LLVMAddDeadStoreEliminationPass(mpm);
LLVMAddLICMPass(mpm);
LLVMAddLoopRerollPass(mpm);
LLVMAddAggressiveDCEPass(mpm);
LLVMAddCFGSimplificationPass(mpm);
LLVMAddInstructionCombiningPass(mpm);
}
void lb_populate_module_pass_manager(LLVMTargetMachineRef target_machine, LLVMPassManagerRef mpm, i32 optimization_level) {
// NOTE(bill): Treat -opt:3 as if it was -opt:2
// TODO(bill): Determine which opt definitions should exist in the first place
optimization_level = gb_clamp(optimization_level, 0, 2);
if (optimization_level >= 2) {
// NOTE(bill, 2021-03-29: use this causes invalid code generation)
// LLVMPassManagerBuilderRef pmb = LLVMPassManagerBuilderCreate();
// LLVMPassManagerBuilderPopulateModulePassManager(pmb, mpm);
// LLVMPassManagerBuilderPopulateLTOPassManager(pmb, mpm, false, true);
// LLVMPassManagerBuilderSetOptLevel(pmb, optimization_level);
// LLVMPassManagerBuilderSetSizeLevel(pmb, optimization_level);
}
LLVMAddAlwaysInlinerPass(mpm);
LLVMAddStripDeadPrototypesPass(mpm);
LLVMAddAnalysisPasses(target_machine, mpm);
LLVMAddPruneEHPass(mpm);
if (optimization_level == 0) {
return;
}
LLVMAddGlobalDCEPass(mpm);
LLVMAddIPSCCPPass(mpm);
LLVMAddCalledValuePropagationPass(mpm);
LLVMAddGlobalOptimizerPass(mpm);
LLVMAddDeadArgEliminationPass(mpm);
// LLVMAddConstantMergePass(mpm); // ???
LLVMAddInstructionCombiningPass(mpm);
LLVMAddCFGSimplificationPass(mpm);
LLVMAddPruneEHPass(mpm);
if (optimization_level < 2) {
return;
}
LLVMAddFunctionInliningPass(mpm);
lb_add_function_simplifcation_passes(mpm, optimization_level);
LLVMAddGlobalDCEPass(mpm);
LLVMAddGlobalOptimizerPass(mpm);
// LLVMAddLowerConstantIntrinsicsPass(mpm);
LLVMAddLoopRotatePass(mpm);
LLVMAddLoopVectorizePass(mpm);
LLVMAddInstructionCombiningPass(mpm);
if (optimization_level >= 2) {
LLVMAddEarlyCSEPass(mpm);
LLVMAddCorrelatedValuePropagationPass(mpm);
LLVMAddLICMPass(mpm);
LLVMAddLoopUnswitchPass(mpm);
LLVMAddCFGSimplificationPass(mpm);
LLVMAddInstructionCombiningPass(mpm);
}
LLVMAddCFGSimplificationPass(mpm);
LLVMAddSLPVectorizePass(mpm);
LLVMAddLICMPass(mpm);
LLVMAddAlignmentFromAssumptionsPass(mpm);
LLVMAddStripDeadPrototypesPass(mpm);
if (optimization_level >= 2) {
LLVMAddGlobalDCEPass(mpm);
LLVMAddConstantMergePass(mpm);
}
LLVMAddCFGSimplificationPass(mpm);
}
<|endoftext|>
|
<commit_before><commit_msg>Need moon to rotate other way<commit_after><|endoftext|>
|
<commit_before>#include <iostream>
#include "Cutie.hpp"
//#include "Main.hpp"
enum Move {ROCK, PAPER, SCISSORS};
void getPlayerTurn(enum Move & temp)
{
int choice = 1;
std::cout << "Please enter your move!" << std::endl;
std::cout << "1: ROCK" << std::endl;
std::cout << "2: PAPER" << std::endl;
std::cout << "3: SCISSORS!" << std::endl;
std::cin >> choice;
if (choice == 1) {
temp = ROCK;
}
else if (choice == 2) {
temp = PAPER;
}
else {
temp = SCISSORS;
}
}
void outputScore()
{
std::cout << "YOU: " << myScore << std::endl;
std::cout << "OPPONENT: " << theirTurn << std:: endl;
}
void updateScore(bool winner)
{
if (winner) {
myScore++;
return;
}
theirScore++;
return;
}
// bool compareTurn(Move player){
// }
int main(int argc, char *argv[])
{
//cutie::connect();
//if(cutie::connect(address, timeout)) {
//bool gameStarted = gameInit(0,0);
bool gameActive = true;
if (gameStarted) {
int myScore = 0;
int theirScore = 0;
bool winner = false;
Move myTurn = 1;
Move theirTurn = 1;
while (gameActive) {
outputScore();
getPlayerTurn(myTurn);
theirTurn = doTurn(myTurn);
if (myTurn == theirTurn) {
winner = false;
}
else if (myTurn == ROCK) {
winner = (theirTurn == SCISSORS)? true : false;
}
else if (myTurn == PAPER) {
winner = (theirTurn == ROCK)? true : false;
}
else {
winner = (theirTurn == PAPER)? true : false;
}
updateScore(winner);
}
}
//}
return 0;
}
<commit_msg>Enum, game functions<commit_after>#include <iostream>
#include <string>
#include "Cutie.hpp"
//#include "Main.hpp"
enum Move {ROCK, PAPER, SCISSORS};
void getPlayerTurn(enum Move & temp)
{
int choice = 1;
std::cout << "Please enter your move!" << std::endl;
std::cout << "1: ROCK" << std::endl;
std::cout << "2: PAPER" << std::endl;
std::cout << "3: SCISSORS!" << std::endl;
std::cin >> choice;
if (choice == 1) {
temp = ROCK;
}
else if (choice == 2) {
temp = PAPER;
}
else {
temp = SCISSORS;
}
}
void outputScore()
{
std::cout << "YOU: " << myScore << std::endl;
std::cout << "OPPONENT: " << theirTurn << std:: endl;
}
void updateScore(bool winner)
{
if (winner) {
myScore++;
return;
}
theirScore++;
return;
}
// bool compareTurn(Move player){
// }
int main(int argc, char *argv[])
{
//cutie::connect();
//if(cutie::connect(address, timeout)) {
//bool gameStarted = gameInit(0,0);
bool gameActive = true;
if (gameStarted) {
int myScore = 0;
int theirScore = 0;
bool winner = false;
Move myTurn = 1;
Move theirTurn = 1;
while (gameActive) {
outputScore();
getPlayerTurn(myTurn);
theirTurn = doTurn(myTurn);
if (myTurn == theirTurn) {
winner = false;
}
else if (myTurn == ROCK) {
winner = (theirTurn == SCISSORS)? true : false;
}
else if (myTurn == PAPER) {
winner = (theirTurn == ROCK)? true : false;
}
else {
winner = (theirTurn == PAPER)? true : false;
}
updateScore(winner);
}
}
//}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/network_message_observer.h"
#include "ash/shell.h"
#include "ash/shell_delegate.h"
#include "ash/system/network/network_observer.h"
#include "ash/system/tray/system_tray.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/stl_util.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/notifications/balloon_view_host_chromeos.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/singleton_tabs.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/time_format.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
// Returns prefs::kShowPlanNotifications in the profile of the last active
// browser. If there is no active browser, returns true.
bool ShouldShowMobilePlanNotifications() {
Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord();
PrefService* prefs = profile->GetPrefs();
return prefs->GetBoolean(prefs::kShowPlanNotifications);
}
} // namespace
namespace chromeos {
class NetworkMessageNotification : public ash::NetworkTrayDelegate {
public:
NetworkMessageNotification(Profile* profile,
ash::NetworkObserver::MessageType error_type)
: error_type_(error_type) {
std::string id;
int icon_id = 0;
switch (error_type) {
case ash::NetworkObserver::ERROR_CONNECT_FAILED:
id = "network_connection.chromeos";
icon_id = IDR_NOTIFICATION_NETWORK_FAILED;
title_ = l10n_util::GetStringUTF16(IDS_NETWORK_CONNECTION_ERROR_TITLE);
break;
case ash::NetworkObserver::MESSAGE_DATA_LOW:
id = "network_low_data.chromeos";
icon_id = IDR_NOTIFICATION_BARS_CRITICAL;
title_ = l10n_util::GetStringUTF16(IDS_NETWORK_LOW_DATA_TITLE);
break;
case ash::NetworkObserver::MESSAGE_DATA_NONE:
id = "network_no_data.chromeos";
icon_id = IDR_NOTIFICATION_BARS_EMPTY;
title_ = l10n_util::GetStringUTF16(IDS_NETWORK_OUT_OF_DATA_TITLE);
break;
case ash::NetworkObserver::MESSAGE_DATA_PROMO:
NOTREACHED();
break;
}
DCHECK(!id.empty());
}
// Overridden from ash::NetworkTrayDelegate:
virtual void NotificationLinkClicked(size_t index) OVERRIDE {
base::ListValue empty_value;
if (!callback_.is_null())
callback_.Run(&empty_value);
}
void Hide() {
ash::Shell::GetInstance()->system_tray()->network_observer()->
ClearNetworkMessage(error_type_);
}
void SetTitle(const string16& title) {
title_ = title;
}
void Show(const string16& message,
const string16& link_text,
const BalloonViewHost::MessageCallback& callback,
bool urgent, bool sticky) {
callback_ = callback;
std::vector<string16> links;
links.push_back(link_text);
ash::Shell::GetInstance()->system_tray()->network_observer()->
SetNetworkMessage(this, error_type_, title_, message, links);
}
void ShowAlways(const string16& message,
const string16& link_text,
const BalloonViewHost::MessageCallback& callback,
bool urgent, bool sticky) {
Show(message, link_text, callback, urgent, sticky);
}
private:
string16 title_;
ash::NetworkObserver::MessageType error_type_;
BalloonViewHost::MessageCallback callback_;
};
NetworkMessageObserver::NetworkMessageObserver(Profile* profile) {
notification_connection_error_.reset(
new NetworkMessageNotification(
profile, ash::NetworkObserver::ERROR_CONNECT_FAILED));
notification_low_data_.reset(
new NetworkMessageNotification(
profile,
ash::NetworkObserver::MESSAGE_DATA_LOW));
notification_no_data_.reset(
new NetworkMessageNotification(
profile,
ash::NetworkObserver::MESSAGE_DATA_NONE));
NetworkLibrary* netlib = CrosLibrary::Get()->GetNetworkLibrary();
OnNetworkManagerChanged(netlib);
// Note that this gets added as a NetworkManagerObserver,
// CellularDataPlanObserver, and UserActionObserver in
// startup_browser_creator.cc
}
NetworkMessageObserver::~NetworkMessageObserver() {
NetworkLibrary* netlib = CrosLibrary::Get()->GetNetworkLibrary();
netlib->RemoveNetworkManagerObserver(this);
netlib->RemoveCellularDataPlanObserver(this);
netlib->RemoveUserActionObserver(this);
notification_connection_error_->Hide();
notification_low_data_->Hide();
notification_no_data_->Hide();
}
// static
bool NetworkMessageObserver::IsApplicableBackupPlan(
const CellularDataPlan* plan, const CellularDataPlan* other_plan) {
// By applicable plan, we mean that the other plan has data AND the timeframe
// will apply: (unlimited OR used bytes < max bytes) AND
// ((start time - 1 sec) <= end time of currently active plan).
// In other words, there is data available and there is no gap of more than a
// second in time between the old plan and the new plan.
bool has_data = other_plan->plan_type == CELLULAR_DATA_PLAN_UNLIMITED ||
other_plan->remaining_data() > 0;
bool will_apply =
(other_plan->plan_start_time - plan->plan_end_time).InSeconds() <= 1;
return has_data && will_apply;
}
void NetworkMessageObserver::OpenMobileSetupPage(
const std::string& service_path, const ListValue* args) {
ash::Shell::GetInstance()->delegate()->OpenMobileSetup(service_path);
}
void NetworkMessageObserver::OpenMoreInfoPage(const ListValue* args) {
Browser* browser = browser::FindOrCreateTabbedBrowser(
ProfileManager::GetDefaultProfileOrOffTheRecord());
chromeos::NetworkLibrary* lib =
chromeos::CrosLibrary::Get()->GetNetworkLibrary();
const chromeos::CellularNetwork* cellular = lib->cellular_network();
if (!cellular)
return;
chrome::ShowSingletonTab(browser, GURL(cellular->payment_url()));
}
void NetworkMessageObserver::InitNewPlan(const CellularDataPlan* plan) {
notification_low_data_->Hide();
notification_no_data_->Hide();
if (plan->plan_type == CELLULAR_DATA_PLAN_UNLIMITED) {
notification_no_data_->SetTitle(
l10n_util::GetStringFUTF16(IDS_NETWORK_DATA_EXPIRED_TITLE,
ASCIIToUTF16(plan->plan_name)));
notification_low_data_->SetTitle(
l10n_util::GetStringFUTF16(IDS_NETWORK_NEARING_EXPIRATION_TITLE,
ASCIIToUTF16(plan->plan_name)));
} else {
notification_no_data_->SetTitle(
l10n_util::GetStringFUTF16(IDS_NETWORK_OUT_OF_DATA_TITLE,
ASCIIToUTF16(plan->plan_name)));
notification_low_data_->SetTitle(
l10n_util::GetStringFUTF16(IDS_NETWORK_LOW_DATA_TITLE,
ASCIIToUTF16(plan->plan_name)));
}
}
void NetworkMessageObserver::ShowNeedsPlanNotification(
const CellularNetwork* cellular) {
notification_no_data_->SetTitle(
l10n_util::GetStringFUTF16(IDS_NETWORK_NO_DATA_PLAN_TITLE,
UTF8ToUTF16(cellular->name())));
notification_no_data_->Show(
l10n_util::GetStringFUTF16(
IDS_NETWORK_NO_DATA_PLAN_MESSAGE,
UTF8ToUTF16(cellular->name())),
l10n_util::GetStringUTF16(IDS_NETWORK_PURCHASE_MORE_MESSAGE),
base::Bind(&NetworkMessageObserver::OpenMobileSetupPage,
AsWeakPtr(),
cellular->service_path()),
false, false);
}
void NetworkMessageObserver::ShowNoDataNotification(
const CellularNetwork* cellular,
CellularDataPlanType plan_type) {
notification_low_data_->Hide(); // Hide previous low data notification.
string16 message = plan_type == CELLULAR_DATA_PLAN_UNLIMITED ?
TimeFormat::TimeRemaining(base::TimeDelta()) :
l10n_util::GetStringFUTF16(IDS_NETWORK_DATA_REMAINING_MESSAGE,
ASCIIToUTF16("0"));
notification_no_data_->Show(message,
l10n_util::GetStringUTF16(IDS_NETWORK_PURCHASE_MORE_MESSAGE),
base::Bind(&NetworkMessageObserver::OpenMobileSetupPage,
AsWeakPtr(),
cellular->service_path()),
false, false);
}
void NetworkMessageObserver::ShowLowDataNotification(
const CellularDataPlan* plan) {
string16 message;
if (plan->plan_type == CELLULAR_DATA_PLAN_UNLIMITED) {
message = plan->GetPlanExpiration();
} else {
int64 remaining_mbytes = plan->remaining_data() / (1024 * 1024);
message = l10n_util::GetStringFUTF16(IDS_NETWORK_DATA_REMAINING_MESSAGE,
UTF8ToUTF16(base::Int64ToString(remaining_mbytes)));
}
notification_low_data_->Show(message,
l10n_util::GetStringUTF16(IDS_NETWORK_MORE_INFO_MESSAGE),
base::Bind(&NetworkMessageObserver::OpenMoreInfoPage, AsWeakPtr()),
false, false);
}
void NetworkMessageObserver::OnNetworkManagerChanged(NetworkLibrary* cros) {
const Network* new_failed_network = NULL;
// Check to see if we have any newly failed networks.
for (WifiNetworkVector::const_iterator it = cros->wifi_networks().begin();
it != cros->wifi_networks().end(); it++) {
const WifiNetwork* net = *it;
if (net->notify_failure()) {
new_failed_network = net;
break; // There should only be one failed network.
}
}
if (!new_failed_network) {
for (WimaxNetworkVector::const_iterator it = cros->wimax_networks().begin();
it != cros->wimax_networks().end(); ++it) {
const WimaxNetwork* net = *it;
if (net->notify_failure()) {
new_failed_network = net;
break; // There should only be one failed network.
}
}
}
if (!new_failed_network) {
for (CellularNetworkVector::const_iterator it =
cros->cellular_networks().begin();
it != cros->cellular_networks().end(); it++) {
const CellularNetwork* net = *it;
if (net->notify_failure()) {
new_failed_network = net;
break; // There should only be one failed network.
}
}
}
if (!new_failed_network) {
for (VirtualNetworkVector::const_iterator it =
cros->virtual_networks().begin();
it != cros->virtual_networks().end(); it++) {
const VirtualNetwork* net = *it;
if (net->notify_failure()) {
new_failed_network = net;
break; // There should only be one failed network.
}
}
}
// Show connection error notification if necessary.
if (new_failed_network) {
notification_connection_error_->ShowAlways(
l10n_util::GetStringFUTF16(
IDS_NETWORK_CONNECTION_ERROR_MESSAGE_WITH_DETAILS,
UTF8ToUTF16(new_failed_network->name()),
UTF8ToUTF16(new_failed_network->GetErrorString())),
string16(), BalloonViewHost::MessageCallback(), false, false);
}
}
void NetworkMessageObserver::OnCellularDataPlanChanged(NetworkLibrary* cros) {
if (!ShouldShowMobilePlanNotifications())
return;
const CellularNetwork* cellular = cros->cellular_network();
if (!cellular || !cellular->SupportsDataPlan())
return;
const CellularDataPlanVector* plans =
cros->GetDataPlans(cellular->service_path());
// If no plans available, check to see if we need a new plan.
if (!plans || plans->empty()) {
// If previously, we had low data, we know that a plan was near expiring.
// In that case, because the plan disappeared, we assume that it expired.
if (cellular_data_left_ == CellularNetwork::DATA_LOW) {
ShowNoDataNotification(cellular, cellular_data_plan_type_);
} else if (cellular->needs_new_plan()) {
ShowNeedsPlanNotification(cellular);
}
SaveLastCellularInfo(cellular, NULL);
return;
}
CellularDataPlanVector::const_iterator iter = plans->begin();
const CellularDataPlan* current_plan = *iter;
// If current plan is not the last plan (there is another backup plan),
// then we do not show notifications for this plan.
// For example, if there is another data plan available when this runs out.
for (++iter; iter != plans->end(); ++iter) {
if (IsApplicableBackupPlan(current_plan, *iter)) {
SaveLastCellularInfo(cellular, current_plan);
return;
}
}
// If connected cellular network changed, or data plan is different, then
// it's a new network. Then hide all previous notifications.
bool new_plan = cellular->service_path() != cellular_service_path_ ||
current_plan->GetUniqueIdentifier() != cellular_data_plan_unique_id_;
if (new_plan) {
InitNewPlan(current_plan);
}
if (cellular->data_left() == CellularNetwork::DATA_NONE) {
ShowNoDataNotification(cellular, current_plan->plan_type);
} else if (cellular->data_left() == CellularNetwork::DATA_VERY_LOW) {
// Only show low data notification if we transition to very low data
// and we are on the same plan. This is so that users don't get a
// notification whenever they connect to a low data 3g network.
if (!new_plan && (cellular_data_left_ != CellularNetwork::DATA_VERY_LOW))
ShowLowDataNotification(current_plan);
}
SaveLastCellularInfo(cellular, current_plan);
}
void NetworkMessageObserver::OnConnectionInitiated(NetworkLibrary* cros,
const Network* network) {
// If user initiated any network connection, we hide the error notification.
notification_connection_error_->Hide();
}
void NetworkMessageObserver::SaveLastCellularInfo(
const CellularNetwork* cellular, const CellularDataPlan* plan) {
DCHECK(cellular);
cellular_service_path_ = cellular->service_path();
cellular_data_left_ = cellular->data_left();
if (plan) {
cellular_data_plan_unique_id_ = plan->GetUniqueIdentifier();
cellular_data_plan_type_ = plan->plan_type;
} else {
cellular_data_plan_unique_id_ = std::string();
cellular_data_plan_type_ = CELLULAR_DATA_PLAN_UNKNOWN;
}
}
} // namespace chromeos
<commit_msg>Remove unused code in network_message_observer<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/network_message_observer.h"
#include "ash/shell.h"
#include "ash/shell_delegate.h"
#include "ash/system/network/network_observer.h"
#include "ash/system/tray/system_tray.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/stl_util.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/notifications/balloon_view_host_chromeos.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/singleton_tabs.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/time_format.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
// Returns prefs::kShowPlanNotifications in the profile of the last active
// browser. If there is no active browser, returns true.
bool ShouldShowMobilePlanNotifications() {
Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord();
PrefService* prefs = profile->GetPrefs();
return prefs->GetBoolean(prefs::kShowPlanNotifications);
}
} // namespace
namespace chromeos {
class NetworkMessageNotification : public ash::NetworkTrayDelegate {
public:
NetworkMessageNotification(Profile* profile,
ash::NetworkObserver::MessageType error_type)
: error_type_(error_type) {
switch (error_type) {
case ash::NetworkObserver::ERROR_CONNECT_FAILED:
title_ = l10n_util::GetStringUTF16(IDS_NETWORK_CONNECTION_ERROR_TITLE);
break;
case ash::NetworkObserver::MESSAGE_DATA_LOW:
title_ = l10n_util::GetStringUTF16(IDS_NETWORK_LOW_DATA_TITLE);
break;
case ash::NetworkObserver::MESSAGE_DATA_NONE:
title_ = l10n_util::GetStringUTF16(IDS_NETWORK_OUT_OF_DATA_TITLE);
break;
case ash::NetworkObserver::MESSAGE_DATA_PROMO:
NOTREACHED();
break;
}
}
// Overridden from ash::NetworkTrayDelegate:
virtual void NotificationLinkClicked(size_t index) OVERRIDE {
base::ListValue empty_value;
if (!callback_.is_null())
callback_.Run(&empty_value);
}
void Hide() {
ash::Shell::GetInstance()->system_tray()->network_observer()->
ClearNetworkMessage(error_type_);
}
void SetTitle(const string16& title) {
title_ = title;
}
void Show(const string16& message,
const string16& link_text,
const BalloonViewHost::MessageCallback& callback,
bool urgent, bool sticky) {
callback_ = callback;
std::vector<string16> links;
links.push_back(link_text);
ash::Shell::GetInstance()->system_tray()->network_observer()->
SetNetworkMessage(this, error_type_, title_, message, links);
}
void ShowAlways(const string16& message,
const string16& link_text,
const BalloonViewHost::MessageCallback& callback,
bool urgent, bool sticky) {
Show(message, link_text, callback, urgent, sticky);
}
private:
string16 title_;
ash::NetworkObserver::MessageType error_type_;
BalloonViewHost::MessageCallback callback_;
};
NetworkMessageObserver::NetworkMessageObserver(Profile* profile) {
notification_connection_error_.reset(
new NetworkMessageNotification(
profile, ash::NetworkObserver::ERROR_CONNECT_FAILED));
notification_low_data_.reset(
new NetworkMessageNotification(
profile,
ash::NetworkObserver::MESSAGE_DATA_LOW));
notification_no_data_.reset(
new NetworkMessageNotification(
profile,
ash::NetworkObserver::MESSAGE_DATA_NONE));
NetworkLibrary* netlib = CrosLibrary::Get()->GetNetworkLibrary();
OnNetworkManagerChanged(netlib);
// Note that this gets added as a NetworkManagerObserver,
// CellularDataPlanObserver, and UserActionObserver in
// startup_browser_creator.cc
}
NetworkMessageObserver::~NetworkMessageObserver() {
NetworkLibrary* netlib = CrosLibrary::Get()->GetNetworkLibrary();
netlib->RemoveNetworkManagerObserver(this);
netlib->RemoveCellularDataPlanObserver(this);
netlib->RemoveUserActionObserver(this);
notification_connection_error_->Hide();
notification_low_data_->Hide();
notification_no_data_->Hide();
}
// static
bool NetworkMessageObserver::IsApplicableBackupPlan(
const CellularDataPlan* plan, const CellularDataPlan* other_plan) {
// By applicable plan, we mean that the other plan has data AND the timeframe
// will apply: (unlimited OR used bytes < max bytes) AND
// ((start time - 1 sec) <= end time of currently active plan).
// In other words, there is data available and there is no gap of more than a
// second in time between the old plan and the new plan.
bool has_data = other_plan->plan_type == CELLULAR_DATA_PLAN_UNLIMITED ||
other_plan->remaining_data() > 0;
bool will_apply =
(other_plan->plan_start_time - plan->plan_end_time).InSeconds() <= 1;
return has_data && will_apply;
}
void NetworkMessageObserver::OpenMobileSetupPage(
const std::string& service_path, const ListValue* args) {
ash::Shell::GetInstance()->delegate()->OpenMobileSetup(service_path);
}
void NetworkMessageObserver::OpenMoreInfoPage(const ListValue* args) {
Browser* browser = browser::FindOrCreateTabbedBrowser(
ProfileManager::GetDefaultProfileOrOffTheRecord());
chromeos::NetworkLibrary* lib =
chromeos::CrosLibrary::Get()->GetNetworkLibrary();
const chromeos::CellularNetwork* cellular = lib->cellular_network();
if (!cellular)
return;
chrome::ShowSingletonTab(browser, GURL(cellular->payment_url()));
}
void NetworkMessageObserver::InitNewPlan(const CellularDataPlan* plan) {
notification_low_data_->Hide();
notification_no_data_->Hide();
if (plan->plan_type == CELLULAR_DATA_PLAN_UNLIMITED) {
notification_no_data_->SetTitle(
l10n_util::GetStringFUTF16(IDS_NETWORK_DATA_EXPIRED_TITLE,
ASCIIToUTF16(plan->plan_name)));
notification_low_data_->SetTitle(
l10n_util::GetStringFUTF16(IDS_NETWORK_NEARING_EXPIRATION_TITLE,
ASCIIToUTF16(plan->plan_name)));
} else {
notification_no_data_->SetTitle(
l10n_util::GetStringFUTF16(IDS_NETWORK_OUT_OF_DATA_TITLE,
ASCIIToUTF16(plan->plan_name)));
notification_low_data_->SetTitle(
l10n_util::GetStringFUTF16(IDS_NETWORK_LOW_DATA_TITLE,
ASCIIToUTF16(plan->plan_name)));
}
}
void NetworkMessageObserver::ShowNeedsPlanNotification(
const CellularNetwork* cellular) {
notification_no_data_->SetTitle(
l10n_util::GetStringFUTF16(IDS_NETWORK_NO_DATA_PLAN_TITLE,
UTF8ToUTF16(cellular->name())));
notification_no_data_->Show(
l10n_util::GetStringFUTF16(
IDS_NETWORK_NO_DATA_PLAN_MESSAGE,
UTF8ToUTF16(cellular->name())),
l10n_util::GetStringUTF16(IDS_NETWORK_PURCHASE_MORE_MESSAGE),
base::Bind(&NetworkMessageObserver::OpenMobileSetupPage,
AsWeakPtr(),
cellular->service_path()),
false, false);
}
void NetworkMessageObserver::ShowNoDataNotification(
const CellularNetwork* cellular,
CellularDataPlanType plan_type) {
notification_low_data_->Hide(); // Hide previous low data notification.
string16 message = plan_type == CELLULAR_DATA_PLAN_UNLIMITED ?
TimeFormat::TimeRemaining(base::TimeDelta()) :
l10n_util::GetStringFUTF16(IDS_NETWORK_DATA_REMAINING_MESSAGE,
ASCIIToUTF16("0"));
notification_no_data_->Show(message,
l10n_util::GetStringUTF16(IDS_NETWORK_PURCHASE_MORE_MESSAGE),
base::Bind(&NetworkMessageObserver::OpenMobileSetupPage,
AsWeakPtr(),
cellular->service_path()),
false, false);
}
void NetworkMessageObserver::ShowLowDataNotification(
const CellularDataPlan* plan) {
string16 message;
if (plan->plan_type == CELLULAR_DATA_PLAN_UNLIMITED) {
message = plan->GetPlanExpiration();
} else {
int64 remaining_mbytes = plan->remaining_data() / (1024 * 1024);
message = l10n_util::GetStringFUTF16(IDS_NETWORK_DATA_REMAINING_MESSAGE,
UTF8ToUTF16(base::Int64ToString(remaining_mbytes)));
}
notification_low_data_->Show(message,
l10n_util::GetStringUTF16(IDS_NETWORK_MORE_INFO_MESSAGE),
base::Bind(&NetworkMessageObserver::OpenMoreInfoPage, AsWeakPtr()),
false, false);
}
void NetworkMessageObserver::OnNetworkManagerChanged(NetworkLibrary* cros) {
const Network* new_failed_network = NULL;
// Check to see if we have any newly failed networks.
for (WifiNetworkVector::const_iterator it = cros->wifi_networks().begin();
it != cros->wifi_networks().end(); it++) {
const WifiNetwork* net = *it;
if (net->notify_failure()) {
new_failed_network = net;
break; // There should only be one failed network.
}
}
if (!new_failed_network) {
for (WimaxNetworkVector::const_iterator it = cros->wimax_networks().begin();
it != cros->wimax_networks().end(); ++it) {
const WimaxNetwork* net = *it;
if (net->notify_failure()) {
new_failed_network = net;
break; // There should only be one failed network.
}
}
}
if (!new_failed_network) {
for (CellularNetworkVector::const_iterator it =
cros->cellular_networks().begin();
it != cros->cellular_networks().end(); it++) {
const CellularNetwork* net = *it;
if (net->notify_failure()) {
new_failed_network = net;
break; // There should only be one failed network.
}
}
}
if (!new_failed_network) {
for (VirtualNetworkVector::const_iterator it =
cros->virtual_networks().begin();
it != cros->virtual_networks().end(); it++) {
const VirtualNetwork* net = *it;
if (net->notify_failure()) {
new_failed_network = net;
break; // There should only be one failed network.
}
}
}
// Show connection error notification if necessary.
if (new_failed_network) {
notification_connection_error_->ShowAlways(
l10n_util::GetStringFUTF16(
IDS_NETWORK_CONNECTION_ERROR_MESSAGE_WITH_DETAILS,
UTF8ToUTF16(new_failed_network->name()),
UTF8ToUTF16(new_failed_network->GetErrorString())),
string16(), BalloonViewHost::MessageCallback(), false, false);
}
}
void NetworkMessageObserver::OnCellularDataPlanChanged(NetworkLibrary* cros) {
if (!ShouldShowMobilePlanNotifications())
return;
const CellularNetwork* cellular = cros->cellular_network();
if (!cellular || !cellular->SupportsDataPlan())
return;
const CellularDataPlanVector* plans =
cros->GetDataPlans(cellular->service_path());
// If no plans available, check to see if we need a new plan.
if (!plans || plans->empty()) {
// If previously, we had low data, we know that a plan was near expiring.
// In that case, because the plan disappeared, we assume that it expired.
if (cellular_data_left_ == CellularNetwork::DATA_LOW) {
ShowNoDataNotification(cellular, cellular_data_plan_type_);
} else if (cellular->needs_new_plan()) {
ShowNeedsPlanNotification(cellular);
}
SaveLastCellularInfo(cellular, NULL);
return;
}
CellularDataPlanVector::const_iterator iter = plans->begin();
const CellularDataPlan* current_plan = *iter;
// If current plan is not the last plan (there is another backup plan),
// then we do not show notifications for this plan.
// For example, if there is another data plan available when this runs out.
for (++iter; iter != plans->end(); ++iter) {
if (IsApplicableBackupPlan(current_plan, *iter)) {
SaveLastCellularInfo(cellular, current_plan);
return;
}
}
// If connected cellular network changed, or data plan is different, then
// it's a new network. Then hide all previous notifications.
bool new_plan = cellular->service_path() != cellular_service_path_ ||
current_plan->GetUniqueIdentifier() != cellular_data_plan_unique_id_;
if (new_plan) {
InitNewPlan(current_plan);
}
if (cellular->data_left() == CellularNetwork::DATA_NONE) {
ShowNoDataNotification(cellular, current_plan->plan_type);
} else if (cellular->data_left() == CellularNetwork::DATA_VERY_LOW) {
// Only show low data notification if we transition to very low data
// and we are on the same plan. This is so that users don't get a
// notification whenever they connect to a low data 3g network.
if (!new_plan && (cellular_data_left_ != CellularNetwork::DATA_VERY_LOW))
ShowLowDataNotification(current_plan);
}
SaveLastCellularInfo(cellular, current_plan);
}
void NetworkMessageObserver::OnConnectionInitiated(NetworkLibrary* cros,
const Network* network) {
// If user initiated any network connection, we hide the error notification.
notification_connection_error_->Hide();
}
void NetworkMessageObserver::SaveLastCellularInfo(
const CellularNetwork* cellular, const CellularDataPlan* plan) {
DCHECK(cellular);
cellular_service_path_ = cellular->service_path();
cellular_data_left_ = cellular->data_left();
if (plan) {
cellular_data_plan_unique_id_ = plan->GetUniqueIdentifier();
cellular_data_plan_type_ = plan->plan_type;
} else {
cellular_data_plan_unique_id_ = std::string();
cellular_data_plan_type_ = CELLULAR_DATA_PLAN_UNKNOWN;
}
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/status/clock_menu_button.h"
#include "base/i18n/time_formatting.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/status/status_area_host.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "content/common/notification_details.h"
#include "content/common/notification_source.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/font.h"
#include "views/widget/widget.h"
#include "unicode/datefmt.h"
namespace {
// views::MenuItemView item ids
enum {
CLOCK_DISPLAY_ITEM,
CLOCK_OPEN_OPTIONS_ITEM
};
} // namespace
namespace chromeos {
// Amount of slop to add into the timer to make sure we're into the next minute
// when the timer goes off.
const int kTimerSlopSeconds = 1;
ClockMenuButton::ClockMenuButton(StatusAreaHost* host)
: StatusAreaButton(host, this) {
// Add as SystemAccess observer. We update the clock if timezone changes.
SystemAccess::GetInstance()->AddObserver(this);
CrosLibrary::Get()->GetPowerLibrary()->AddObserver(this);
// Start monitoring the kUse24HourClock preference.
if (host->GetProfile()) { // This can be NULL in the login screen.
registrar_.Init(host->GetProfile()->GetPrefs());
registrar_.Add(prefs::kUse24HourClock, this);
}
UpdateTextAndSetNextTimer();
}
ClockMenuButton::~ClockMenuButton() {
CrosLibrary::Get()->GetPowerLibrary()->RemoveObserver(this);
SystemAccess::GetInstance()->RemoveObserver(this);
}
void ClockMenuButton::UpdateTextAndSetNextTimer() {
UpdateText();
// Try to set the timer to go off at the next change of the minute. We don't
// want to have the timer go off more than necessary since that will cause
// the CPU to wake up and consume power.
base::Time now = base::Time::Now();
base::Time::Exploded exploded;
now.LocalExplode(&exploded);
// Often this will be called at minute boundaries, and we'll actually want
// 60 seconds from now.
int seconds_left = 60 - exploded.second;
if (seconds_left == 0)
seconds_left = 60;
// Make sure that the timer fires on the next minute. Without this, if it is
// called just a teeny bit early, then it will skip the next minute.
seconds_left += kTimerSlopSeconds;
timer_.Start(base::TimeDelta::FromSeconds(seconds_left), this,
&ClockMenuButton::UpdateTextAndSetNextTimer);
}
void ClockMenuButton::UpdateText() {
base::Time time(base::Time::Now());
// If the profie is present, check the use 24-hour clock preference.
const bool use_24hour_clock =
host_->GetProfile() &&
host_->GetProfile()->GetPrefs()->GetBoolean(prefs::kUse24HourClock);
SetText(UTF16ToWide(base::TimeFormatTimeOfDayWithHourClockType(
time,
use_24hour_clock ? base::k24HourClock : base::k12HourClock,
base::kDropAmPm)));
SetTooltipText(UTF16ToWide(base::TimeFormatShortDate(time)));
SetAccessibleName(base::TimeFormatFriendlyDateAndTime(time));
SchedulePaint();
}
// ClockMenuButton, NotificationObserver implementation:
void ClockMenuButton::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::PREF_CHANGED) {
std::string* pref_name = Details<std::string>(details).ptr();
if (*pref_name == prefs::kUse24HourClock) {
UpdateText();
}
}
}
// ClockMenuButton, views::MenuDelegate implementation:
std::wstring ClockMenuButton::GetLabel(int id) const {
DCHECK_EQ(CLOCK_DISPLAY_ITEM, id);
const string16 label = base::TimeFormatFriendlyDate(base::Time::Now());
return UTF16ToWide(label);
}
bool ClockMenuButton::IsCommandEnabled(int id) const {
DCHECK(id == CLOCK_DISPLAY_ITEM || id == CLOCK_OPEN_OPTIONS_ITEM);
return id == CLOCK_OPEN_OPTIONS_ITEM;
}
void ClockMenuButton::ExecuteCommand(int id) {
DCHECK_EQ(CLOCK_OPEN_OPTIONS_ITEM, id);
host_->OpenButtonOptions(this);
}
// ClockMenuButton, PowerLibrary::Observer implementation:
void ClockMenuButton::SystemResumed() {
UpdateText();
}
// ClockMenuButton, SystemLibrary::Observer implementation:
void ClockMenuButton::TimezoneChanged(const icu::TimeZone& timezone) {
UpdateText();
}
int ClockMenuButton::horizontal_padding() {
return 3;
}
// ClockMenuButton, views::ViewMenuDelegate implementation:
void ClockMenuButton::RunMenu(views::View* source, const gfx::Point& pt) {
// View passed in must be a views::MenuButton, i.e. the ClockMenuButton.
DCHECK_EQ(source, this);
EnsureMenu();
// TODO(rhashimoto): Remove this workaround when WebUI provides a
// top-level widget on the ChromeOS login screen that is a window.
// The current BackgroundView class for the ChromeOS login screen
// creates a owning Widget that has a native GtkWindow but is not a
// Window. This makes it impossible to get the NativeWindow via
// the views API. This workaround casts the top-level NativeWidget
// to a NativeWindow that we can pass to MenuItemView::RunMenuAt().
gfx::NativeWindow window = GTK_WINDOW(source->GetWidget()->GetNativeView());
gfx::Point screen_loc;
views::View::ConvertPointToScreen(source, &screen_loc);
gfx::Rect bounds(screen_loc, source->size());
menu_->RunMenuAt(
window,
this,
bounds,
views::MenuItemView::TOPRIGHT,
true);
}
// ClockMenuButton, views::View implementation:
void ClockMenuButton::OnLocaleChanged() {
UpdateText();
}
void ClockMenuButton::EnsureMenu() {
if (!menu_.get()) {
menu_.reset(new views::MenuItemView(this));
// Text for this item will be set by GetLabel().
menu_->AppendDelegateMenuItem(CLOCK_DISPLAY_ITEM);
// If options dialog is unavailable, don't show a separator and configure
// menu item.
if (host_->ShouldOpenButtonOptions(this)) {
menu_->AppendSeparator();
const string16 clock_open_options_label =
l10n_util::GetStringUTF16(IDS_STATUSBAR_CLOCK_OPEN_OPTIONS_DIALOG);
menu_->AppendMenuItemWithLabel(
CLOCK_OPEN_OPTIONS_ITEM,
UTF16ToWide(clock_open_options_label));
}
}
}
} // namespace chromeos
<commit_msg>Bugfix for date hover format.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/status/clock_menu_button.h"
#include "base/i18n/time_formatting.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/status/status_area_host.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "content/common/notification_details.h"
#include "content/common/notification_source.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/font.h"
#include "views/widget/widget.h"
#include "unicode/datefmt.h"
namespace {
// views::MenuItemView item ids
enum {
CLOCK_DISPLAY_ITEM,
CLOCK_OPEN_OPTIONS_ITEM
};
} // namespace
namespace chromeos {
// Amount of slop to add into the timer to make sure we're into the next minute
// when the timer goes off.
const int kTimerSlopSeconds = 1;
ClockMenuButton::ClockMenuButton(StatusAreaHost* host)
: StatusAreaButton(host, this) {
// Add as SystemAccess observer. We update the clock if timezone changes.
SystemAccess::GetInstance()->AddObserver(this);
CrosLibrary::Get()->GetPowerLibrary()->AddObserver(this);
// Start monitoring the kUse24HourClock preference.
if (host->GetProfile()) { // This can be NULL in the login screen.
registrar_.Init(host->GetProfile()->GetPrefs());
registrar_.Add(prefs::kUse24HourClock, this);
}
UpdateTextAndSetNextTimer();
}
ClockMenuButton::~ClockMenuButton() {
CrosLibrary::Get()->GetPowerLibrary()->RemoveObserver(this);
SystemAccess::GetInstance()->RemoveObserver(this);
}
void ClockMenuButton::UpdateTextAndSetNextTimer() {
UpdateText();
// Try to set the timer to go off at the next change of the minute. We don't
// want to have the timer go off more than necessary since that will cause
// the CPU to wake up and consume power.
base::Time now = base::Time::Now();
base::Time::Exploded exploded;
now.LocalExplode(&exploded);
// Often this will be called at minute boundaries, and we'll actually want
// 60 seconds from now.
int seconds_left = 60 - exploded.second;
if (seconds_left == 0)
seconds_left = 60;
// Make sure that the timer fires on the next minute. Without this, if it is
// called just a teeny bit early, then it will skip the next minute.
seconds_left += kTimerSlopSeconds;
timer_.Start(base::TimeDelta::FromSeconds(seconds_left), this,
&ClockMenuButton::UpdateTextAndSetNextTimer);
}
void ClockMenuButton::UpdateText() {
base::Time time(base::Time::Now());
// If the profie is present, check the use 24-hour clock preference.
const bool use_24hour_clock =
host_->GetProfile() &&
host_->GetProfile()->GetPrefs()->GetBoolean(prefs::kUse24HourClock);
SetText(UTF16ToWide(base::TimeFormatTimeOfDayWithHourClockType(
time,
use_24hour_clock ? base::k24HourClock : base::k12HourClock,
base::kDropAmPm)));
SetTooltipText(UTF16ToWide(base::TimeFormatFriendlyDateAndTime(time)));
SetAccessibleName(base::TimeFormatFriendlyDateAndTime(time));
SchedulePaint();
}
// ClockMenuButton, NotificationObserver implementation:
void ClockMenuButton::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::PREF_CHANGED) {
std::string* pref_name = Details<std::string>(details).ptr();
if (*pref_name == prefs::kUse24HourClock) {
UpdateText();
}
}
}
// ClockMenuButton, views::MenuDelegate implementation:
std::wstring ClockMenuButton::GetLabel(int id) const {
DCHECK_EQ(CLOCK_DISPLAY_ITEM, id);
const string16 label = base::TimeFormatFriendlyDate(base::Time::Now());
return UTF16ToWide(label);
}
bool ClockMenuButton::IsCommandEnabled(int id) const {
DCHECK(id == CLOCK_DISPLAY_ITEM || id == CLOCK_OPEN_OPTIONS_ITEM);
return id == CLOCK_OPEN_OPTIONS_ITEM;
}
void ClockMenuButton::ExecuteCommand(int id) {
DCHECK_EQ(CLOCK_OPEN_OPTIONS_ITEM, id);
host_->OpenButtonOptions(this);
}
// ClockMenuButton, PowerLibrary::Observer implementation:
void ClockMenuButton::SystemResumed() {
UpdateText();
}
// ClockMenuButton, SystemLibrary::Observer implementation:
void ClockMenuButton::TimezoneChanged(const icu::TimeZone& timezone) {
UpdateText();
}
int ClockMenuButton::horizontal_padding() {
return 3;
}
// ClockMenuButton, views::ViewMenuDelegate implementation:
void ClockMenuButton::RunMenu(views::View* source, const gfx::Point& pt) {
// View passed in must be a views::MenuButton, i.e. the ClockMenuButton.
DCHECK_EQ(source, this);
EnsureMenu();
// TODO(rhashimoto): Remove this workaround when WebUI provides a
// top-level widget on the ChromeOS login screen that is a window.
// The current BackgroundView class for the ChromeOS login screen
// creates a owning Widget that has a native GtkWindow but is not a
// Window. This makes it impossible to get the NativeWindow via
// the views API. This workaround casts the top-level NativeWidget
// to a NativeWindow that we can pass to MenuItemView::RunMenuAt().
gfx::NativeWindow window = GTK_WINDOW(source->GetWidget()->GetNativeView());
gfx::Point screen_loc;
views::View::ConvertPointToScreen(source, &screen_loc);
gfx::Rect bounds(screen_loc, source->size());
menu_->RunMenuAt(
window,
this,
bounds,
views::MenuItemView::TOPRIGHT,
true);
}
// ClockMenuButton, views::View implementation:
void ClockMenuButton::OnLocaleChanged() {
UpdateText();
}
void ClockMenuButton::EnsureMenu() {
if (!menu_.get()) {
menu_.reset(new views::MenuItemView(this));
// Text for this item will be set by GetLabel().
menu_->AppendDelegateMenuItem(CLOCK_DISPLAY_ITEM);
// If options dialog is unavailable, don't show a separator and configure
// menu item.
if (host_->ShouldOpenButtonOptions(this)) {
menu_->AppendSeparator();
const string16 clock_open_options_label =
l10n_util::GetStringUTF16(IDS_STATUSBAR_CLOCK_OPEN_OPTIONS_DIALOG);
menu_->AppendMenuItemWithLabel(
CLOCK_OPEN_OPTIONS_ITEM,
UTF16ToWide(clock_open_options_label));
}
}
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/pref_names.h"
#include "net/base/mock_host_resolver.h"
// Possible race in ChromeURLDataManager. http://crbug.com/59198
#if defined(OS_MACOSX) || defined(OS_LINUX)
#define MAYBE_TabOnRemoved DISABLED_TabOnRemoved
#else
#define MAYBE_TabOnRemoved TabOnRemoved
#endif
// Crashes on linux views. http://crbug.com/61592
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
#define MAYBE_Tabs DISABLED_Tabs
#else
#define MAYBE_Tabs Tabs
#endif
// Window resizes are not completed by the time the callback happens,
// so these tests fail on linux. http://crbug.com/72369
#if defined(OS_LINUX)
#define MAYBE_FocusWindowDoesNotExitFullscreen \
DISABLED_FocusWindowDoesNotExitFullscreen
#define MAYBE_UpdateWindowSizeExitsFullscreen \
DISABLED_UpdateWindowSizeExitsFullscreen
#else
#define MAYBE_FocusWindowDoesNotExitFullscreen FocusWindowDoesNotExitFullscreen
#define MAYBE_UpdateWindowSizeExitsFullscreen UpdateWindowSizeExitsFullscreen
#endif
// Times out on Mac (especially Leopard). http://crbug.com/80212
#if defined(OS_MACOSX)
#define MAYBE_CaptureVisibleTabRace DISABLED_CaptureVisibleTabRace
#else
#define MAYBE_CaptureVisibleTabRace CaptureVisibleTabRace
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
ASSERT_TRUE(StartTestServer());
// The test creates a tab and checks that the URL of the new tab
// is that of the new tab page. Make sure the pref that controls
// this is set.
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kHomePageIsNewTabPage, true);
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabPinned) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "pinned.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabMove) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "move.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabEvents) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "events.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabRelativeURLs) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "relative_urls.html"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCrashBrowser) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crash.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_;
}
// Test is timing out on linux and cros and flaky on others.
// See http://crbug.com/83876
#if defined(OS_LINUX)
#define MAYBE_CaptureVisibleTabJpeg DISABLED_CaptureVisibleTabJpeg
#else
#define MAYBE_CaptureVisibleTabJpeg FLAKY_CaptureVisibleTabJpeg
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabJpeg) {
host_resolver()->AddRule("a.com", "127.0.0.1");
host_resolver()->AddRule("b.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_jpeg.html")) << message_;
}
// Test is timing out on cros and flaky on others. See http://crbug.com/83876
#if defined(OS_CHROMEOS)
#define MAYBE_CaptureVisibleTabPng DISABLED_CaptureVisibleTabPng
#else
#define MAYBE_CaptureVisibleTabPng FLAKY_CaptureVisibleTabPng
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabPng) {
host_resolver()->AddRule("a.com", "127.0.0.1");
host_resolver()->AddRule("b.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_png.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabRace) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_race.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
MAYBE_FocusWindowDoesNotExitFullscreen) {
browser()->window()->SetFullscreen(true);
bool is_fullscreen = browser()->window()->IsFullscreen();
ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_;
ASSERT_EQ(is_fullscreen, browser()->window()->IsFullscreen());
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
MAYBE_UpdateWindowSizeExitsFullscreen) {
browser()->window()->SetFullscreen(true);
ASSERT_TRUE(RunExtensionTest("window_update/sizing")) << message_;
ASSERT_FALSE(browser()->window()->IsFullscreen());
}
#if defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FocusWindowDoesNotUnmaximize) {
gfx::NativeWindow window = browser()->window()->GetNativeHandle();
::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_;
ASSERT_TRUE(::IsZoomed(window));
}
#endif // OS_WIN
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabledByPref) {
ASSERT_TRUE(StartTestServer());
browser()->profile()->GetPrefs()->SetBoolean(prefs::kIncognitoEnabled, false);
// This makes sure that creating an incognito window fails due to pref
// (policy) being set.
ASSERT_TRUE(RunExtensionTest("tabs/incognito_disabled")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViewsOfCreatedPopup) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_popup.html"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViewsOfCreatedWindow) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_window.html"))
<< message_;
}
<commit_msg>OS_CHROMEOS isn't defined on the Linux views bot.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/pref_names.h"
#include "net/base/mock_host_resolver.h"
// Possible race in ChromeURLDataManager. http://crbug.com/59198
#if defined(OS_MACOSX) || defined(OS_LINUX)
#define MAYBE_TabOnRemoved DISABLED_TabOnRemoved
#else
#define MAYBE_TabOnRemoved TabOnRemoved
#endif
// Crashes on linux views. http://crbug.com/61592
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
#define MAYBE_Tabs DISABLED_Tabs
#else
#define MAYBE_Tabs Tabs
#endif
// Window resizes are not completed by the time the callback happens,
// so these tests fail on linux. http://crbug.com/72369
#if defined(OS_LINUX)
#define MAYBE_FocusWindowDoesNotExitFullscreen \
DISABLED_FocusWindowDoesNotExitFullscreen
#define MAYBE_UpdateWindowSizeExitsFullscreen \
DISABLED_UpdateWindowSizeExitsFullscreen
#else
#define MAYBE_FocusWindowDoesNotExitFullscreen FocusWindowDoesNotExitFullscreen
#define MAYBE_UpdateWindowSizeExitsFullscreen UpdateWindowSizeExitsFullscreen
#endif
// Times out on Mac (especially Leopard). http://crbug.com/80212
#if defined(OS_MACOSX)
#define MAYBE_CaptureVisibleTabRace DISABLED_CaptureVisibleTabRace
#else
#define MAYBE_CaptureVisibleTabRace CaptureVisibleTabRace
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
ASSERT_TRUE(StartTestServer());
// The test creates a tab and checks that the URL of the new tab
// is that of the new tab page. Make sure the pref that controls
// this is set.
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kHomePageIsNewTabPage, true);
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabPinned) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "pinned.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabMove) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "move.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabEvents) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "events.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabRelativeURLs) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "relative_urls.html"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCrashBrowser) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crash.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_;
}
// Test is timing out on linux and cros and flaky on others.
// See http://crbug.com/83876
#if defined(OS_LINUX)
#define MAYBE_CaptureVisibleTabJpeg DISABLED_CaptureVisibleTabJpeg
#else
#define MAYBE_CaptureVisibleTabJpeg FLAKY_CaptureVisibleTabJpeg
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabJpeg) {
host_resolver()->AddRule("a.com", "127.0.0.1");
host_resolver()->AddRule("b.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_jpeg.html")) << message_;
}
// Test is timing out on cros and flaky on others. See http://crbug.com/83876
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
#define MAYBE_CaptureVisibleTabPng DISABLED_CaptureVisibleTabPng
#else
#define MAYBE_CaptureVisibleTabPng FLAKY_CaptureVisibleTabPng
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabPng) {
host_resolver()->AddRule("a.com", "127.0.0.1");
host_resolver()->AddRule("b.com", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_png.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabRace) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_race.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
MAYBE_FocusWindowDoesNotExitFullscreen) {
browser()->window()->SetFullscreen(true);
bool is_fullscreen = browser()->window()->IsFullscreen();
ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_;
ASSERT_EQ(is_fullscreen, browser()->window()->IsFullscreen());
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
MAYBE_UpdateWindowSizeExitsFullscreen) {
browser()->window()->SetFullscreen(true);
ASSERT_TRUE(RunExtensionTest("window_update/sizing")) << message_;
ASSERT_FALSE(browser()->window()->IsFullscreen());
}
#if defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FocusWindowDoesNotUnmaximize) {
gfx::NativeWindow window = browser()->window()->GetNativeHandle();
::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_;
ASSERT_TRUE(::IsZoomed(window));
}
#endif // OS_WIN
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabledByPref) {
ASSERT_TRUE(StartTestServer());
browser()->profile()->GetPrefs()->SetBoolean(prefs::kIncognitoEnabled, false);
// This makes sure that creating an incognito window fails due to pref
// (policy) being set.
ASSERT_TRUE(RunExtensionTest("tabs/incognito_disabled")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViewsOfCreatedPopup) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_popup.html"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, GetViewsOfCreatedWindow) {
ASSERT_TRUE(StartTestServer());
ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_window.html"))
<< message_;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#if defined(OS_MACOSX)
// Tabs appears to timeout, or maybe crash on mac.
// http://crbug.com/53779
#define MAYBE_Tabs FAILS_Tabs
#else
#define MAYBE_Tabs Tabs
#endif
// TabOnRemoved is flaky on chromeos and linux views debug build.
// http://crbug.com/49258
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG)
#define MAYBE_TabOnRemoved FLAKY_TabOnRemoved
#else
#define MAYBE_TabOnRemoved TabOnRemoved
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
ASSERT_TRUE(test_server()->Start());
// The test creates a tab and checks that the URL of the new tab
// is that of the new tab page. Make sure the pref that controls
// this is set.
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kHomePageIsNewTabPage, true);
ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_jpeg.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_png.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_;
}
<commit_msg>Mark ExtensionApiTest.Tabs flaky on win and linux.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#if defined(OS_MACOSX)
// Tabs appears to timeout, or maybe crash on mac.
// http://crbug.com/53779
#define MAYBE_Tabs FAILS_Tabs
#else
// It's flaky on win and linux.
// http://crbug.com/58269
#define MAYBE_Tabs FLAKY_Tabs
#endif
// TabOnRemoved is flaky on chromeos and linux views debug build.
// http://crbug.com/49258
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG)
#define MAYBE_TabOnRemoved FLAKY_TabOnRemoved
#else
#define MAYBE_TabOnRemoved TabOnRemoved
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
ASSERT_TRUE(test_server()->Start());
// The test creates a tab and checks that the URL of the new tab
// is that of the new tab page. Make sure the pref that controls
// this is set.
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kHomePageIsNewTabPage, true);
ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_jpeg.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_png.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/page_action_controller.h"
#include "chrome/browser/extensions/browser_event_router.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/extensions/tab_helper.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/sessions/session_id.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension_set.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/invalidate_type.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/web_contents.h"
namespace extensions {
PageActionController::PageActionController(TabContents* tab_contents)
: content::WebContentsObserver(tab_contents->web_contents()),
tab_contents_(tab_contents) {}
PageActionController::~PageActionController() {}
std::vector<ExtensionAction*> PageActionController::GetCurrentActions() const {
ExtensionService* service = GetExtensionService();
if (!service)
return std::vector<ExtensionAction*>();
std::vector<ExtensionAction*> current_actions;
for (ExtensionSet::const_iterator i = service->extensions()->begin();
i != service->extensions()->end(); ++i) {
ExtensionAction* action = (*i)->page_action();
if (action)
current_actions.push_back(action);
}
return current_actions;
}
LocationBarController::Action PageActionController::OnClicked(
const std::string& extension_id, int mouse_button) {
ExtensionService* service = GetExtensionService();
if (!service)
return ACTION_NONE;
const Extension* extension = service->extensions()->GetByID(extension_id);
CHECK(extension);
ExtensionAction* page_action = extension->page_action();
CHECK(page_action);
int tab_id = ExtensionTabUtil::GetTabId(tab_contents_->web_contents());
tab_contents_->extension_tab_helper()->active_tab_permission_manager()->
GrantIfRequested(extension);
switch (mouse_button) {
case 1: // left
case 2: // middle
if (page_action->HasPopup(tab_id))
return ACTION_SHOW_POPUP;
GetExtensionService()->browser_event_router()->PageActionExecuted(
tab_contents_->profile(),
*page_action,
tab_id,
tab_contents_->web_contents()->GetURL().spec(),
mouse_button);
return ACTION_NONE;
case 3: // right
return extension->ShowConfigureContextMenus() ?
ACTION_SHOW_CONTEXT_MENU : ACTION_NONE;
}
return ACTION_NONE;
}
void PageActionController::NotifyChange() {
tab_contents_->web_contents()->NotifyNavigationStateChanged(
content::INVALIDATE_TYPE_PAGE_ACTIONS);
}
void PageActionController::DidNavigateMainFrame(
const content::LoadCommittedDetails& details,
const content::FrameNavigateParams& params) {
const std::vector<ExtensionAction*> current_actions = GetCurrentActions();
if (current_actions.empty())
return;
for (size_t i = 0; i < current_actions.size(); ++i) {
current_actions[i]->ClearAllValuesForTab(
SessionID::IdForTab(tab_contents_));
}
NotifyChange();
}
ExtensionService* PageActionController::GetExtensionService() const {
return ExtensionSystem::Get(tab_contents_->profile())->extension_service();
}
} // namespace extensions
<commit_msg>Copy the !details.is_in_page restriction from TabHelper to PageActionController::DidNavigateMainFrame<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/page_action_controller.h"
#include "chrome/browser/extensions/browser_event_router.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/extensions/tab_helper.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/sessions/session_id.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension_set.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/invalidate_type.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/web_contents.h"
namespace extensions {
PageActionController::PageActionController(TabContents* tab_contents)
: content::WebContentsObserver(tab_contents->web_contents()),
tab_contents_(tab_contents) {}
PageActionController::~PageActionController() {}
std::vector<ExtensionAction*> PageActionController::GetCurrentActions() const {
ExtensionService* service = GetExtensionService();
if (!service)
return std::vector<ExtensionAction*>();
std::vector<ExtensionAction*> current_actions;
for (ExtensionSet::const_iterator i = service->extensions()->begin();
i != service->extensions()->end(); ++i) {
ExtensionAction* action = (*i)->page_action();
if (action)
current_actions.push_back(action);
}
return current_actions;
}
LocationBarController::Action PageActionController::OnClicked(
const std::string& extension_id, int mouse_button) {
ExtensionService* service = GetExtensionService();
if (!service)
return ACTION_NONE;
const Extension* extension = service->extensions()->GetByID(extension_id);
CHECK(extension);
ExtensionAction* page_action = extension->page_action();
CHECK(page_action);
int tab_id = ExtensionTabUtil::GetTabId(tab_contents_->web_contents());
tab_contents_->extension_tab_helper()->active_tab_permission_manager()->
GrantIfRequested(extension);
switch (mouse_button) {
case 1: // left
case 2: // middle
if (page_action->HasPopup(tab_id))
return ACTION_SHOW_POPUP;
GetExtensionService()->browser_event_router()->PageActionExecuted(
tab_contents_->profile(),
*page_action,
tab_id,
tab_contents_->web_contents()->GetURL().spec(),
mouse_button);
return ACTION_NONE;
case 3: // right
return extension->ShowConfigureContextMenus() ?
ACTION_SHOW_CONTEXT_MENU : ACTION_NONE;
}
return ACTION_NONE;
}
void PageActionController::NotifyChange() {
tab_contents_->web_contents()->NotifyNavigationStateChanged(
content::INVALIDATE_TYPE_PAGE_ACTIONS);
}
void PageActionController::DidNavigateMainFrame(
const content::LoadCommittedDetails& details,
const content::FrameNavigateParams& params) {
if (details.is_in_page)
return;
const std::vector<ExtensionAction*> current_actions = GetCurrentActions();
if (current_actions.empty())
return;
for (size_t i = 0; i < current_actions.size(); ++i) {
current_actions[i]->ClearAllValuesForTab(
SessionID::IdForTab(tab_contents_));
}
NotifyChange();
}
ExtensionService* PageActionController::GetExtensionService() const {
return ExtensionSystem::Get(tab_contents_->profile())->extension_service();
}
} // namespace extensions
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gtk/options/advanced_contents_gtk.h"
#include "app/l10n_util.h"
#include "base/basictypes.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/gtk/options/options_layout_gtk.h"
#include "chrome/browser/options_page_base.h"
#include "chrome/browser/profile.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/installer/util/google_update_settings.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
///////////////////////////////////////////////////////////////////////////////
// DownloadSection
class DownloadSection : public OptionsPageBase {
public:
explicit DownloadSection(Profile* profile);
virtual ~DownloadSection() {}
GtkWidget* get_page_widget() const {
return page_;
}
private:
// The widget containing the options for this section.
GtkWidget* page_;
DISALLOW_COPY_AND_ASSIGN(DownloadSection);
};
DownloadSection::DownloadSection(Profile* profile)
: OptionsPageBase(profile) {
page_ = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
gtk_box_pack_start(GTK_BOX(page_), gtk_label_new("TODO download options"),
FALSE, FALSE, 0);
}
///////////////////////////////////////////////////////////////////////////////
// NetworkSection
class NetworkSection : public OptionsPageBase {
public:
explicit NetworkSection(Profile* profile);
virtual ~NetworkSection() {}
GtkWidget* get_page_widget() const {
return page_;
}
private:
// The widget containing the options for this section.
GtkWidget* page_;
DISALLOW_COPY_AND_ASSIGN(NetworkSection);
};
NetworkSection::NetworkSection(Profile* profile)
: OptionsPageBase(profile) {
page_ = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
gtk_box_pack_start(GTK_BOX(page_), gtk_label_new("TODO network options"),
FALSE, FALSE, 0);
}
///////////////////////////////////////////////////////////////////////////////
// PrivacySection
class PrivacySection : public OptionsPageBase {
public:
explicit PrivacySection(Profile* profile);
virtual ~PrivacySection() {}
GtkWidget* get_page_widget() const {
return page_;
}
private:
// This is the callback function for Stats reporting checkbox.
static void OnLoggingChange(GtkWidget* widget,
PrivacySection* options_window);
// This function gets called when stats reporting option is changed.
void LoggingChanged(GtkWidget* widget);
// The widget containing the options for this section.
GtkWidget* page_;
DISALLOW_COPY_AND_ASSIGN(PrivacySection);
};
PrivacySection::PrivacySection(Profile* profile) : OptionsPageBase(profile) {
page_ = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
GtkWidget* metrics = gtk_check_button_new();
GtkWidget* metrics_label = gtk_label_new(
l10n_util::GetStringUTF8(IDS_OPTIONS_ENABLE_LOGGING).c_str());
gtk_label_set_line_wrap(GTK_LABEL(metrics_label), TRUE);
// TODO(evanm): make the label wrap at the appropriate width.
gtk_widget_set_size_request(metrics_label, 475, -1);
gtk_container_add(GTK_CONTAINER(metrics), metrics_label);
gtk_box_pack_start(GTK_BOX(page_), metrics, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(page_),
gtk_label_new("TODO rest of the privacy options"),
FALSE, FALSE, 0);
bool logging = g_browser_process->local_state()->GetBoolean(
prefs::kMetricsReportingEnabled);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(metrics), logging);
g_signal_connect(metrics, "clicked", G_CALLBACK(OnLoggingChange), this);
}
// static
void PrivacySection::OnLoggingChange(GtkWidget* widget,
PrivacySection* privacy_section) {
privacy_section->LoggingChanged(widget);
}
void PrivacySection::LoggingChanged(GtkWidget* metrics) {
bool logging = (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(metrics)) ==
TRUE);
g_browser_process->local_state()->SetBoolean(prefs::kMetricsReportingEnabled,
logging);
GoogleUpdateSettings::SetCollectStatsConsent(logging);
}
///////////////////////////////////////////////////////////////////////////////
// SecuritySection
class SecuritySection : public OptionsPageBase {
public:
explicit SecuritySection(Profile* profile);
virtual ~SecuritySection() {}
GtkWidget* get_page_widget() const {
return page_;
}
private:
// The widget containing the options for this section.
GtkWidget* page_;
DISALLOW_COPY_AND_ASSIGN(SecuritySection);
};
SecuritySection::SecuritySection(Profile* profile)
: OptionsPageBase(profile) {
page_ = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
gtk_box_pack_start(GTK_BOX(page_), gtk_label_new("TODO security options"),
FALSE, FALSE, 0);
}
///////////////////////////////////////////////////////////////////////////////
// WebContentSection
class WebContentSection : public OptionsPageBase {
public:
explicit WebContentSection(Profile* profile);
virtual ~WebContentSection() {}
GtkWidget* get_page_widget() const {
return page_;
}
private:
// The widget containing the options for this section.
GtkWidget* page_;
DISALLOW_COPY_AND_ASSIGN(WebContentSection);
};
WebContentSection::WebContentSection(Profile* profile)
: OptionsPageBase(profile) {
page_ = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
gtk_box_pack_start(GTK_BOX(page_), gtk_label_new("TODO web content options"),
FALSE, FALSE, 0);
}
///////////////////////////////////////////////////////////////////////////////
// AdvancedContentsGtk
AdvancedContentsGtk::AdvancedContentsGtk(Profile* profile)
: profile_(profile) {
Init();
}
AdvancedContentsGtk::~AdvancedContentsGtk() {
}
void AdvancedContentsGtk::Init() {
OptionsLayoutBuilderGtk options_builder;
network_section_.reset(new NetworkSection(profile_));
options_builder.AddOptionGroup(
l10n_util::GetStringUTF8(IDS_OPTIONS_ADVANCED_SECTION_TITLE_NETWORK),
network_section_->get_page_widget(), false);
privacy_section_.reset(new PrivacySection(profile_));
options_builder.AddOptionGroup(
l10n_util::GetStringUTF8(IDS_OPTIONS_ADVANCED_SECTION_TITLE_PRIVACY),
privacy_section_->get_page_widget(), false);
download_section_.reset(new DownloadSection(profile_));
options_builder.AddOptionGroup(
l10n_util::GetStringUTF8(IDS_OPTIONS_DOWNLOADLOCATION_GROUP_NAME),
download_section_->get_page_widget(), false);
web_content_section_.reset(new WebContentSection(profile_));
options_builder.AddOptionGroup(
l10n_util::GetStringUTF8(IDS_OPTIONS_ADVANCED_SECTION_TITLE_CONTENT),
web_content_section_->get_page_widget(), false);
security_section_.reset(new SecuritySection(profile_));
options_builder.AddOptionGroup(
l10n_util::GetStringUTF8(IDS_OPTIONS_ADVANCED_SECTION_TITLE_SECURITY),
security_section_->get_page_widget(), false);
page_ = options_builder.get_page_widget();
}
<commit_msg>Add more privacy prefs<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gtk/options/advanced_contents_gtk.h"
#include "app/l10n_util.h"
#include "base/basictypes.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/gtk/options/options_layout_gtk.h"
#include "chrome/browser/net/dns_global.h"
#include "chrome/browser/options_page_base.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/pref_member.h"
#include "chrome/common/pref_names.h"
#include "chrome/installer/util/google_update_settings.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
namespace {
// The pixel width we wrap labels at.
// TODO(evanm): make the labels wrap at the appropriate width.
const int kWrapWidth = 475;
GtkWidget* CreateWrappedLabel(int string_id) {
GtkWidget* label = gtk_label_new(
l10n_util::GetStringUTF8(string_id).c_str());
gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
gtk_widget_set_size_request(label, kWrapWidth, -1);
return label;
}
GtkWidget* CreateCheckButtonWithWrappedLabel(int string_id) {
GtkWidget* checkbox = gtk_check_button_new();
gtk_container_add(GTK_CONTAINER(checkbox),
CreateWrappedLabel(string_id));
return checkbox;
}
} // anonymous namespace
///////////////////////////////////////////////////////////////////////////////
// DownloadSection
class DownloadSection : public OptionsPageBase {
public:
explicit DownloadSection(Profile* profile);
virtual ~DownloadSection() {}
GtkWidget* get_page_widget() const {
return page_;
}
private:
// The widget containing the options for this section.
GtkWidget* page_;
DISALLOW_COPY_AND_ASSIGN(DownloadSection);
};
DownloadSection::DownloadSection(Profile* profile)
: OptionsPageBase(profile) {
page_ = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
gtk_box_pack_start(GTK_BOX(page_), gtk_label_new("TODO download options"),
FALSE, FALSE, 0);
}
///////////////////////////////////////////////////////////////////////////////
// NetworkSection
class NetworkSection : public OptionsPageBase {
public:
explicit NetworkSection(Profile* profile);
virtual ~NetworkSection() {}
GtkWidget* get_page_widget() const {
return page_;
}
private:
// The widget containing the options for this section.
GtkWidget* page_;
DISALLOW_COPY_AND_ASSIGN(NetworkSection);
};
NetworkSection::NetworkSection(Profile* profile)
: OptionsPageBase(profile) {
page_ = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
gtk_box_pack_start(GTK_BOX(page_), gtk_label_new("TODO network options"),
FALSE, FALSE, 0);
}
///////////////////////////////////////////////////////////////////////////////
// PrivacySection
class PrivacySection : public OptionsPageBase {
public:
explicit PrivacySection(Profile* profile);
virtual ~PrivacySection() {}
GtkWidget* get_page_widget() const {
return page_;
}
private:
// Overridden from OptionsPageBase.
virtual void NotifyPrefChanged(const std::wstring* pref_name);
// The callback functions for the options widgets.
static void OnEnableLinkDoctorChange(GtkWidget* widget,
PrivacySection* options_window);
static void OnEnableSuggestChange(GtkWidget* widget,
PrivacySection* options_window);
static void OnDNSPrefetchingChange(GtkWidget* widget,
PrivacySection* options_window);
static void OnSafeBrowsingChange(GtkWidget* widget,
PrivacySection* options_window);
static void OnLoggingChange(GtkWidget* widget,
PrivacySection* options_window);
// The widget containing the options for this section.
GtkWidget* page_;
// The widgets for the privacy options.
GtkWidget* enable_link_doctor_checkbox_;
GtkWidget* enable_suggest_checkbox_;
GtkWidget* enable_dns_prefetching_checkbox_;
GtkWidget* enable_safe_browsing_checkbox_;
GtkWidget* reporting_enabled_checkbox_;
// Preferences for this section:
BooleanPrefMember alternate_error_pages_;
BooleanPrefMember use_suggest_;
BooleanPrefMember dns_prefetch_enabled_;
BooleanPrefMember safe_browsing_;
BooleanPrefMember enable_metrics_recording_;
IntegerPrefMember cookie_behavior_;
// Flag to ignore gtk callbacks while we are loading prefs, to avoid
// then turning around and saving them again.
bool initializing_;
DISALLOW_COPY_AND_ASSIGN(PrivacySection);
};
PrivacySection::PrivacySection(Profile* profile)
: OptionsPageBase(profile),
initializing_(true) {
page_ = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
GtkWidget* section_description_label = CreateWrappedLabel(
IDS_OPTIONS_DISABLE_SERVICES);
gtk_misc_set_alignment(GTK_MISC(section_description_label), 0, 0);
gtk_box_pack_start(GTK_BOX(page_), section_description_label,
FALSE, FALSE, 0);
// TODO(mattm): Learn more link
enable_link_doctor_checkbox_ = CreateCheckButtonWithWrappedLabel(
IDS_OPTIONS_LINKDOCTOR_PREF);
gtk_box_pack_start(GTK_BOX(page_), enable_link_doctor_checkbox_,
FALSE, FALSE, 0);
g_signal_connect(enable_link_doctor_checkbox_, "clicked",
G_CALLBACK(OnEnableLinkDoctorChange), this);
enable_suggest_checkbox_ = CreateCheckButtonWithWrappedLabel(
IDS_OPTIONS_SUGGEST_PREF);
gtk_box_pack_start(GTK_BOX(page_), enable_suggest_checkbox_,
FALSE, FALSE, 0);
g_signal_connect(enable_suggest_checkbox_, "clicked",
G_CALLBACK(OnEnableSuggestChange), this);
enable_dns_prefetching_checkbox_ = CreateCheckButtonWithWrappedLabel(
IDS_NETWORK_DNS_PREFETCH_ENABLED_DESCRIPTION);
gtk_box_pack_start(GTK_BOX(page_), enable_dns_prefetching_checkbox_,
FALSE, FALSE, 0);
g_signal_connect(enable_dns_prefetching_checkbox_, "clicked",
G_CALLBACK(OnDNSPrefetchingChange), this);
enable_safe_browsing_checkbox_ = CreateCheckButtonWithWrappedLabel(
IDS_OPTIONS_SAFEBROWSING_ENABLEPROTECTION);
gtk_box_pack_start(GTK_BOX(page_), enable_safe_browsing_checkbox_,
FALSE, FALSE, 0);
g_signal_connect(enable_safe_browsing_checkbox_, "clicked",
G_CALLBACK(OnSafeBrowsingChange), this);
reporting_enabled_checkbox_ = CreateCheckButtonWithWrappedLabel(
IDS_OPTIONS_ENABLE_LOGGING);
gtk_box_pack_start(GTK_BOX(page_), reporting_enabled_checkbox_,
FALSE, FALSE, 0);
g_signal_connect(reporting_enabled_checkbox_, "clicked",
G_CALLBACK(OnLoggingChange), this);
// TODO(mattm): cookie combobox and button
gtk_box_pack_start(GTK_BOX(page_),
gtk_label_new("TODO rest of the privacy options"),
FALSE, FALSE, 0);
// Init member prefs so we can update the controls if prefs change.
alternate_error_pages_.Init(prefs::kAlternateErrorPagesEnabled,
profile->GetPrefs(), this);
use_suggest_.Init(prefs::kSearchSuggestEnabled,
profile->GetPrefs(), this);
dns_prefetch_enabled_.Init(prefs::kDnsPrefetchingEnabled,
profile->GetPrefs(), this);
safe_browsing_.Init(prefs::kSafeBrowsingEnabled, profile->GetPrefs(), this);
enable_metrics_recording_.Init(prefs::kMetricsReportingEnabled,
g_browser_process->local_state(), this);
cookie_behavior_.Init(prefs::kCookieBehavior, profile->GetPrefs(), this);
NotifyPrefChanged(NULL);
}
// static
void PrivacySection::OnEnableLinkDoctorChange(GtkWidget* widget,
PrivacySection* privacy_section) {
if (privacy_section->initializing_)
return;
bool enabled = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
privacy_section->UserMetricsRecordAction(
enabled ?
L"Options_LinkDoctorCheckbox_Enable" :
L"Options_LinkDoctorCheckbox_Disable",
privacy_section->profile()->GetPrefs());
privacy_section->alternate_error_pages_.SetValue(enabled);
}
// static
void PrivacySection::OnEnableSuggestChange(GtkWidget* widget,
PrivacySection* privacy_section) {
if (privacy_section->initializing_)
return;
bool enabled = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
privacy_section->UserMetricsRecordAction(
enabled ?
L"Options_UseSuggestCheckbox_Enable" :
L"Options_UseSuggestCheckbox_Disable",
privacy_section->profile()->GetPrefs());
privacy_section->use_suggest_.SetValue(enabled);
}
// static
void PrivacySection::OnDNSPrefetchingChange(GtkWidget* widget,
PrivacySection* privacy_section) {
if (privacy_section->initializing_)
return;
bool enabled = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
privacy_section->UserMetricsRecordAction(
enabled ?
L"Options_DnsPrefetchCheckbox_Enable" :
L"Options_DnsPrefetchCheckbox_Disable",
privacy_section->profile()->GetPrefs());
privacy_section->dns_prefetch_enabled_.SetValue(enabled);
chrome_browser_net::EnableDnsPrefetch(enabled);
}
// static
void PrivacySection::OnSafeBrowsingChange(GtkWidget* widget,
PrivacySection* privacy_section) {
if (privacy_section->initializing_)
return;
bool enabled = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
privacy_section->UserMetricsRecordAction(
enabled ?
L"Options_SafeBrowsingCheckbox_Enable" :
L"Options_SafeBrowsingCheckbox_Disable",
privacy_section->profile()->GetPrefs());
privacy_section->safe_browsing_.SetValue(enabled);
SafeBrowsingService* safe_browsing_service =
g_browser_process->resource_dispatcher_host()->safe_browsing_service();
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
safe_browsing_service, &SafeBrowsingService::OnEnable, enabled));
}
// static
void PrivacySection::OnLoggingChange(GtkWidget* widget,
PrivacySection* privacy_section) {
if (privacy_section->initializing_)
return;
bool enabled = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
privacy_section->UserMetricsRecordAction(
enabled ?
L"Options_MetricsReportingCheckbox_Enable" :
L"Options_MetricsReportingCheckbox_Disable",
privacy_section->profile()->GetPrefs());
// TODO(mattm): ResolveMetricsReportingEnabled?
// TODO(mattm): show browser must be restarted message?
privacy_section->enable_metrics_recording_.SetValue(enabled);
GoogleUpdateSettings::SetCollectStatsConsent(enabled);
}
void PrivacySection::NotifyPrefChanged(const std::wstring* pref_name) {
initializing_ = true;
if (!pref_name || *pref_name == prefs::kAlternateErrorPagesEnabled) {
gtk_toggle_button_set_active(
GTK_TOGGLE_BUTTON(enable_link_doctor_checkbox_),
alternate_error_pages_.GetValue());
}
if (!pref_name || *pref_name == prefs::kSearchSuggestEnabled) {
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(enable_suggest_checkbox_),
use_suggest_.GetValue());
}
if (!pref_name || *pref_name == prefs::kDnsPrefetchingEnabled) {
bool enabled = dns_prefetch_enabled_.GetValue();
gtk_toggle_button_set_active(
GTK_TOGGLE_BUTTON(enable_dns_prefetching_checkbox_), enabled);
chrome_browser_net::EnableDnsPrefetch(enabled);
}
if (!pref_name || *pref_name == prefs::kSafeBrowsingEnabled) {
gtk_toggle_button_set_active(
GTK_TOGGLE_BUTTON(enable_safe_browsing_checkbox_),
safe_browsing_.GetValue());
}
if (!pref_name || *pref_name == prefs::kMetricsReportingEnabled) {
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(reporting_enabled_checkbox_),
enable_metrics_recording_.GetValue());
// TODO(mattm): ResolveMetricsReportingEnabled()?
}
if (!pref_name || *pref_name == prefs::kCookieBehavior) {
// TODO(mattm): set cookie combobox state
}
initializing_ = false;
}
///////////////////////////////////////////////////////////////////////////////
// SecuritySection
class SecuritySection : public OptionsPageBase {
public:
explicit SecuritySection(Profile* profile);
virtual ~SecuritySection() {}
GtkWidget* get_page_widget() const {
return page_;
}
private:
// The widget containing the options for this section.
GtkWidget* page_;
DISALLOW_COPY_AND_ASSIGN(SecuritySection);
};
SecuritySection::SecuritySection(Profile* profile)
: OptionsPageBase(profile) {
page_ = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
gtk_box_pack_start(GTK_BOX(page_), gtk_label_new("TODO security options"),
FALSE, FALSE, 0);
}
///////////////////////////////////////////////////////////////////////////////
// WebContentSection
class WebContentSection : public OptionsPageBase {
public:
explicit WebContentSection(Profile* profile);
virtual ~WebContentSection() {}
GtkWidget* get_page_widget() const {
return page_;
}
private:
// The widget containing the options for this section.
GtkWidget* page_;
DISALLOW_COPY_AND_ASSIGN(WebContentSection);
};
WebContentSection::WebContentSection(Profile* profile)
: OptionsPageBase(profile) {
page_ = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
gtk_box_pack_start(GTK_BOX(page_), gtk_label_new("TODO web content options"),
FALSE, FALSE, 0);
}
///////////////////////////////////////////////////////////////////////////////
// AdvancedContentsGtk
AdvancedContentsGtk::AdvancedContentsGtk(Profile* profile)
: profile_(profile) {
Init();
}
AdvancedContentsGtk::~AdvancedContentsGtk() {
}
void AdvancedContentsGtk::Init() {
OptionsLayoutBuilderGtk options_builder;
network_section_.reset(new NetworkSection(profile_));
options_builder.AddOptionGroup(
l10n_util::GetStringUTF8(IDS_OPTIONS_ADVANCED_SECTION_TITLE_NETWORK),
network_section_->get_page_widget(), false);
privacy_section_.reset(new PrivacySection(profile_));
options_builder.AddOptionGroup(
l10n_util::GetStringUTF8(IDS_OPTIONS_ADVANCED_SECTION_TITLE_PRIVACY),
privacy_section_->get_page_widget(), false);
download_section_.reset(new DownloadSection(profile_));
options_builder.AddOptionGroup(
l10n_util::GetStringUTF8(IDS_OPTIONS_DOWNLOADLOCATION_GROUP_NAME),
download_section_->get_page_widget(), false);
web_content_section_.reset(new WebContentSection(profile_));
options_builder.AddOptionGroup(
l10n_util::GetStringUTF8(IDS_OPTIONS_ADVANCED_SECTION_TITLE_CONTENT),
web_content_section_->get_page_widget(), false);
security_section_.reset(new SecuritySection(profile_));
options_builder.AddOptionGroup(
l10n_util::GetStringUTF8(IDS_OPTIONS_ADVANCED_SECTION_TITLE_SECURITY),
security_section_->get_page_widget(), false);
page_ = options_builder.get_page_widget();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/startup/session_crashed_prompt.h"
#include "chrome/browser/infobars/infobar_tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/session_restore.h"
#include "chrome/browser/tab_contents/confirm_infobar_delegate.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/web_contents.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "grit/theme_resources_standard.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
namespace {
// A delegate for the InfoBar shown when the previous session has crashed.
class SessionCrashedInfoBarDelegate : public ConfirmInfoBarDelegate {
public:
SessionCrashedInfoBarDelegate(Profile* profile,
InfoBarTabHelper* infobar_helper);
private:
virtual ~SessionCrashedInfoBarDelegate();
// ConfirmInfoBarDelegate:
virtual gfx::Image* GetIcon() const OVERRIDE;
virtual string16 GetMessageText() const OVERRIDE;
virtual int GetButtons() const OVERRIDE;
virtual string16 GetButtonLabel(InfoBarButton button) const OVERRIDE;
virtual bool Accept() OVERRIDE;
// The Profile that we restore sessions from.
Profile* profile_;
DISALLOW_COPY_AND_ASSIGN(SessionCrashedInfoBarDelegate);
};
SessionCrashedInfoBarDelegate::SessionCrashedInfoBarDelegate(
Profile* profile,
InfoBarTabHelper* infobar_helper)
: ConfirmInfoBarDelegate(infobar_helper),
profile_(profile) {
}
SessionCrashedInfoBarDelegate::~SessionCrashedInfoBarDelegate() {
}
gfx::Image* SessionCrashedInfoBarDelegate::GetIcon() const {
return &ResourceBundle::GetSharedInstance().GetNativeImageNamed(
IDR_INFOBAR_RESTORE_SESSION);
}
string16 SessionCrashedInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringUTF16(IDS_SESSION_CRASHED_VIEW_MESSAGE);
}
int SessionCrashedInfoBarDelegate::GetButtons() const {
return BUTTON_OK;
}
string16 SessionCrashedInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
DCHECK_EQ(BUTTON_OK, button);
return l10n_util::GetStringUTF16(IDS_SESSION_CRASHED_VIEW_RESTORE_BUTTON);
}
bool SessionCrashedInfoBarDelegate::Accept() {
uint32 behavior = 0;
Browser* browser = browser::FindLastActiveWithProfile(profile_);
if (browser && browser->tab_count() == 1
&& browser->GetWebContentsAt(0)->GetURL() ==
GURL(chrome::kChromeUINewTabURL)) {
// There is only one tab and its the new tab page, make session restore
// clobber it.
behavior = SessionRestore::CLOBBER_CURRENT_TAB;
}
SessionRestore::RestoreSession(
profile_, browser, behavior, std::vector<GURL>());
return true;
}
} // namespace
namespace browser {
void ShowSessionCrashedPrompt(Browser* browser) {
// Assume that if the user is launching incognito they were previously
// running incognito so that we have nothing to restore from.
if (browser->profile()->IsOffTheRecord())
return;
// In ChromeBot tests, there might be a race. This line appears to get
// called during shutdown and |tab| can be NULL.
TabContents* tab = browser->GetActiveTabContents();
if (!tab)
return;
// Don't show the info-bar if there are already info-bars showing.
if (tab->infobar_tab_helper()->infobar_count() > 0)
return;
tab->infobar_tab_helper()->AddInfoBar(
new SessionCrashedInfoBarDelegate(browser->profile(),
tab->infobar_tab_helper()));
}
} // namespace browser
<commit_msg>Get rid of browser::FindLastActiveWithProfile call session restore code. The infobar delegate can get to its current Browser through the tab.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/startup/session_crashed_prompt.h"
#include "chrome/browser/infobars/infobar_tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/session_restore.h"
#include "chrome/browser/tab_contents/confirm_infobar_delegate.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/web_contents.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "grit/theme_resources_standard.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
namespace {
// A delegate for the InfoBar shown when the previous session has crashed.
class SessionCrashedInfoBarDelegate : public ConfirmInfoBarDelegate {
public:
explicit SessionCrashedInfoBarDelegate(InfoBarTabHelper* infobar_helper);
private:
virtual ~SessionCrashedInfoBarDelegate();
// ConfirmInfoBarDelegate:
virtual gfx::Image* GetIcon() const OVERRIDE;
virtual string16 GetMessageText() const OVERRIDE;
virtual int GetButtons() const OVERRIDE;
virtual string16 GetButtonLabel(InfoBarButton button) const OVERRIDE;
virtual bool Accept() OVERRIDE;
DISALLOW_COPY_AND_ASSIGN(SessionCrashedInfoBarDelegate);
};
SessionCrashedInfoBarDelegate::SessionCrashedInfoBarDelegate(
InfoBarTabHelper* infobar_helper)
: ConfirmInfoBarDelegate(infobar_helper) {
}
SessionCrashedInfoBarDelegate::~SessionCrashedInfoBarDelegate() {
}
gfx::Image* SessionCrashedInfoBarDelegate::GetIcon() const {
return &ResourceBundle::GetSharedInstance().GetNativeImageNamed(
IDR_INFOBAR_RESTORE_SESSION);
}
string16 SessionCrashedInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringUTF16(IDS_SESSION_CRASHED_VIEW_MESSAGE);
}
int SessionCrashedInfoBarDelegate::GetButtons() const {
return BUTTON_OK;
}
string16 SessionCrashedInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
DCHECK_EQ(BUTTON_OK, button);
return l10n_util::GetStringUTF16(IDS_SESSION_CRASHED_VIEW_RESTORE_BUTTON);
}
bool SessionCrashedInfoBarDelegate::Accept() {
uint32 behavior = 0;
Browser* browser =
browser::FindBrowserWithWebContents(owner()->web_contents());
if (browser && browser->tab_count() == 1 &&
browser->GetWebContentsAt(0)->GetURL() ==
GURL(chrome::kChromeUINewTabURL)) {
// There is only one tab and its the new tab page, make session restore
// clobber it.
behavior = SessionRestore::CLOBBER_CURRENT_TAB;
}
SessionRestore::RestoreSession(
browser->profile(), browser, behavior, std::vector<GURL>());
return true;
}
} // namespace
namespace browser {
void ShowSessionCrashedPrompt(Browser* browser) {
// Assume that if the user is launching incognito they were previously
// running incognito so that we have nothing to restore from.
if (browser->profile()->IsOffTheRecord())
return;
// In ChromeBot tests, there might be a race. This line appears to get
// called during shutdown and |tab| can be NULL.
TabContents* tab = browser->GetActiveTabContents();
if (!tab)
return;
// Don't show the info-bar if there are already info-bars showing.
if (tab->infobar_tab_helper()->infobar_count() > 0)
return;
tab->infobar_tab_helper()->AddInfoBar(
new SessionCrashedInfoBarDelegate(tab->infobar_tab_helper()));
}
} // namespace browser
<|endoftext|>
|
<commit_before>// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/frame/contents_container.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "grit/theme_resources.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/image_skia.h"
// static
const char ContentsContainer::kViewClassName[] =
"browser/ui/views/frame/ContentsContainer";
namespace {
int OverlayHeightInPixels(int parent_height, int overlay_height,
InstantSizeUnits overlay_height_units) {
overlay_height = std::max(0, overlay_height);
switch (overlay_height_units) {
case INSTANT_SIZE_PERCENT:
return std::min(parent_height, (parent_height * overlay_height) / 100);
case INSTANT_SIZE_PIXELS:
return std::min(parent_height, overlay_height);
}
NOTREACHED() << "unknown units: " << overlay_height_units;
return 0;
}
// This class draws the drop shadow below the overlay when the non-NTP overlay
// doesn't fill up the entire content page.
// This class is owned by ContentsContainer, which:
// - adds it as child when shadow is needed
// - removes it as child when shadow is not needed or when overlay is nuked or
// when overlay is removed as child
// - always makes sure it's the 3rd child in the view hierarchy i.e. after
// active and overlay.
class ShadowView : public views::View {
public:
ShadowView() {
drop_shadow_ = *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
IDR_OVERLAY_DROP_SHADOW);
SetPaintToLayer(true);
SetFillsBoundsOpaquely(false);
set_owned_by_client();
}
virtual ~ShadowView() {}
virtual gfx::Size GetPreferredSize() OVERRIDE {
// Only height really matters, since images will be stretched horizontally
// across.
return drop_shadow_.size();
}
protected:
virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
// Stretch drop shadow horizontally across.
canvas->DrawImageInt(
drop_shadow_,
0, 0, drop_shadow_.width(), drop_shadow_.height(),
0, 0, width(), drop_shadow_.height(),
true);
}
private:
gfx::ImageSkia drop_shadow_;
DISALLOW_COPY_AND_ASSIGN(ShadowView);
};
} // namespace
ContentsContainer::ContentsContainer(views::WebView* active)
: active_(active),
overlay_(NULL),
overlay_web_contents_(NULL),
draw_drop_shadow_(false),
active_top_margin_(0),
overlay_height_(100),
overlay_height_units_(INSTANT_SIZE_PERCENT) {
AddChildView(active_);
}
ContentsContainer::~ContentsContainer() {
}
void ContentsContainer::MakeOverlayContentsActiveContents() {
DCHECK(overlay_);
active_ = overlay_;
overlay_ = NULL;
overlay_web_contents_ = NULL;
// Since |overlay_| has been nuked, shadow view is not needed anymore.
// Note that the previous |active_| will be deleted by caller (see
// BrowserView::ActiveTabChanged()) after this call, hence removing the old
// |active_| as a child, and making the new |active_| (which is the previous
// |overlay_|) the first child.
shadow_view_.reset();
Layout();
}
void ContentsContainer::SetOverlay(views::WebView* overlay,
content::WebContents* overlay_web_contents,
int height,
InstantSizeUnits units,
bool draw_drop_shadow) {
// If drawing drop shadow, clip the bottom 1-px-thick separator out of
// overlay.
// TODO(kuan): remove this when GWS gives chrome the height without the
// separator.
#if !defined(OS_WIN)
if (draw_drop_shadow)
--height;
#endif // !defined(OS_WIN)
if (overlay_ == overlay && overlay_web_contents_ == overlay_web_contents &&
overlay_height_ == height && overlay_height_units_ == units &&
draw_drop_shadow_ == draw_drop_shadow) {
return;
}
if (overlay_ != overlay) {
if (overlay_) {
// Order of children is important: always |active_| first, then
// |overlay_|, then shadow view if necessary. To make sure the next view
// is added in the right order, remove shadow view every time |overlay_|
// is removed. Don't nuke the shadow view now in case it's needed below
// when we handle |draw_drop_shadow|.
if (shadow_view_.get())
RemoveChildView(shadow_view_.get());
RemoveChildView(overlay_);
}
overlay_ = overlay;
if (overlay_)
AddChildView(overlay_);
}
if (overlay_web_contents_ != overlay_web_contents) {
#if !defined(OS_WIN)
// Unregister from previous overlay web contents' render view host.
if (overlay_web_contents_)
registrar_.RemoveAll();
#endif // !defined(OS_WIN)
overlay_web_contents_ = overlay_web_contents;
#if !defined(OS_WIN)
// Register to new overlay web contents' render view host.
if (overlay_web_contents_) {
content::RenderViewHost* rvh = overlay_web_contents_->GetRenderViewHost();
DCHECK(rvh);
content::NotificationSource source =
content::Source<content::RenderWidgetHost>(rvh);
registrar_.Add(this,
content::NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
source);
}
#endif // !defined(OS_WIN)
}
overlay_height_ = height;
overlay_height_units_ = units;
draw_drop_shadow_ = draw_drop_shadow;
// Add shadow view if there's overlay and drop shadow is needed.
// Remove shadow view if there's no overlay.
// If there's overlay and drop shadow is not needed, that means the partial-
// height overlay is going to be full-height. Don't remove the shadow view
// yet because its view will disappear noticeably faster than the webview-ed
// overlay is repainted at the full height - when resizing web contents page,
// RenderWidgetHostViewAura locks the compositor until texture is updated or
// timeout occurs. This out-of-sync refresh results in a split second where
// there's no separator between the overlay and active contents, making the
// overlay contents erroneously appear to be part of active contents.
// When the overlay is repainted at the full height, we'll be notified via
// NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKGING_STORE, at which time
// the shadow view will be removed.
if (overlay_ && draw_drop_shadow_) {
#if !defined(OS_WIN)
if (!shadow_view_.get()) // Shadow view has not been created.
shadow_view_.reset(new ShadowView());
if (!shadow_view_->parent()) // Shadow view has not been added.
AddChildView(shadow_view_.get());
#endif // !defined(OS_WIN)
} else if (!overlay_) {
shadow_view_.reset();
}
Layout();
}
void ContentsContainer::MaybeStackOverlayAtTop() {
if (!overlay_)
return;
// To force |overlay_| to the topmost in the z-order, remove it, then add it
// back.
// See comments in SetOverlay() for why shadow view is removed.
bool removed_shadow = false;
if (shadow_view_.get()) {
RemoveChildView(shadow_view_.get());
removed_shadow = true;
}
RemoveChildView(overlay_);
AddChildView(overlay_);
if (removed_shadow) // Add back shadow view if it was removed.
AddChildView(shadow_view_.get());
Layout();
}
void ContentsContainer::SetActiveTopMargin(int margin) {
if (active_top_margin_ == margin)
return;
active_top_margin_ = margin;
// Make sure we layout next time around. We need this in case our bounds
// haven't changed.
InvalidateLayout();
}
gfx::Rect ContentsContainer::GetOverlayBounds() const {
gfx::Point screen_loc;
ConvertPointToScreen(this, &screen_loc);
return gfx::Rect(screen_loc, size());
}
bool ContentsContainer::IsOverlayFullHeight(
int overlay_height,
InstantSizeUnits overlay_height_units) const {
int height_in_pixels = OverlayHeightInPixels(height(), overlay_height,
overlay_height_units);
return height_in_pixels == height();
}
void ContentsContainer::Layout() {
int content_y = active_top_margin_;
int content_height = std::max(0, height() - content_y);
active_->SetBounds(0, content_y, width(), content_height);
if (overlay_) {
overlay_->SetBounds(0, 0, width(),
OverlayHeightInPixels(height(), overlay_height_,
overlay_height_units_));
if (draw_drop_shadow_) {
#if !defined(OS_WIN)
DCHECK(shadow_view_.get() && shadow_view_->parent());
shadow_view_->SetBounds(0, overlay_->bounds().height(), width(),
shadow_view_->GetPreferredSize().height());
#endif // !defined(OS_WIN)
}
}
// Need to invoke views::View in case any views whose bounds didn't change
// still need a layout.
views::View::Layout();
}
std::string ContentsContainer::GetClassName() const {
return kViewClassName;
}
void ContentsContainer::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK_EQ(content::NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
type);
// Remove shadow view if it's not needed.
if (overlay_ && !draw_drop_shadow_)
shadow_view_.reset();
}
<commit_msg>alternate ntp: fix crash in ContentsContainer destructor<commit_after>// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/frame/contents_container.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "grit/theme_resources.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/image_skia.h"
// static
const char ContentsContainer::kViewClassName[] =
"browser/ui/views/frame/ContentsContainer";
namespace {
int OverlayHeightInPixels(int parent_height, int overlay_height,
InstantSizeUnits overlay_height_units) {
overlay_height = std::max(0, overlay_height);
switch (overlay_height_units) {
case INSTANT_SIZE_PERCENT:
return std::min(parent_height, (parent_height * overlay_height) / 100);
case INSTANT_SIZE_PIXELS:
return std::min(parent_height, overlay_height);
}
NOTREACHED() << "unknown units: " << overlay_height_units;
return 0;
}
// This class draws the drop shadow below the overlay when the non-NTP overlay
// doesn't fill up the entire content page.
// This class is owned by ContentsContainer, which:
// - adds it as child when shadow is needed
// - removes it as child when shadow is not needed or when overlay is nuked or
// when overlay is removed as child
// - always makes sure it's the 3rd child in the view hierarchy i.e. after
// active and overlay.
class ShadowView : public views::View {
public:
ShadowView() {
drop_shadow_ = *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
IDR_OVERLAY_DROP_SHADOW);
SetPaintToLayer(true);
SetFillsBoundsOpaquely(false);
set_owned_by_client();
}
virtual ~ShadowView() {}
virtual gfx::Size GetPreferredSize() OVERRIDE {
// Only height really matters, since images will be stretched horizontally
// across.
return drop_shadow_.size();
}
protected:
virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {
// Stretch drop shadow horizontally across.
canvas->DrawImageInt(
drop_shadow_,
0, 0, drop_shadow_.width(), drop_shadow_.height(),
0, 0, width(), drop_shadow_.height(),
true);
}
private:
gfx::ImageSkia drop_shadow_;
DISALLOW_COPY_AND_ASSIGN(ShadowView);
};
} // namespace
ContentsContainer::ContentsContainer(views::WebView* active)
: active_(active),
overlay_(NULL),
overlay_web_contents_(NULL),
draw_drop_shadow_(false),
active_top_margin_(0),
overlay_height_(100),
overlay_height_units_(INSTANT_SIZE_PERCENT) {
AddChildView(active_);
}
ContentsContainer::~ContentsContainer() {
}
void ContentsContainer::MakeOverlayContentsActiveContents() {
DCHECK(overlay_);
active_ = overlay_;
overlay_ = NULL;
overlay_web_contents_ = NULL;
// Unregister from observing previous |overlay_web_contents_|.
registrar_.RemoveAll();
// Since |overlay_| has been nuked, shadow view is not needed anymore.
// Note that the previous |active_| will be deleted by caller (see
// BrowserView::ActiveTabChanged()) after this call, hence removing the old
// |active_| as a child, and making the new |active_| (which is the previous
// |overlay_|) the first child.
shadow_view_.reset();
Layout();
}
void ContentsContainer::SetOverlay(views::WebView* overlay,
content::WebContents* overlay_web_contents,
int height,
InstantSizeUnits units,
bool draw_drop_shadow) {
// If drawing drop shadow, clip the bottom 1-px-thick separator out of
// overlay.
// TODO(kuan): remove this when GWS gives chrome the height without the
// separator.
#if !defined(OS_WIN)
if (draw_drop_shadow)
--height;
#endif // !defined(OS_WIN)
if (overlay_ == overlay && overlay_web_contents_ == overlay_web_contents &&
overlay_height_ == height && overlay_height_units_ == units &&
draw_drop_shadow_ == draw_drop_shadow) {
return;
}
if (overlay_ != overlay) {
if (overlay_) {
// Order of children is important: always |active_| first, then
// |overlay_|, then shadow view if necessary. To make sure the next view
// is added in the right order, remove shadow view every time |overlay_|
// is removed. Don't nuke the shadow view now in case it's needed below
// when we handle |draw_drop_shadow|.
if (shadow_view_.get())
RemoveChildView(shadow_view_.get());
RemoveChildView(overlay_);
}
overlay_ = overlay;
if (overlay_)
AddChildView(overlay_);
}
if (overlay_web_contents_ != overlay_web_contents) {
#if !defined(OS_WIN)
// Unregister from observing previous |overlay_web_contents_|.
registrar_.RemoveAll();
#endif // !defined(OS_WIN)
overlay_web_contents_ = overlay_web_contents;
#if !defined(OS_WIN)
// Register to new overlay web contents' render view host.
if (overlay_web_contents_) {
content::RenderViewHost* rvh = overlay_web_contents_->GetRenderViewHost();
DCHECK(rvh);
if (rvh) {
content::NotificationSource source =
content::Source<content::RenderWidgetHost>(rvh);
registrar_.Add(this,
content::NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
source);
}
}
#endif // !defined(OS_WIN)
}
overlay_height_ = height;
overlay_height_units_ = units;
draw_drop_shadow_ = draw_drop_shadow;
// Add shadow view if there's overlay and drop shadow is needed.
// Remove shadow view if there's no overlay.
// If there's overlay and drop shadow is not needed, that means the partial-
// height overlay is going to be full-height. Don't remove the shadow view
// yet because its view will disappear noticeably faster than the webview-ed
// overlay is repainted at the full height - when resizing web contents page,
// RenderWidgetHostViewAura locks the compositor until texture is updated or
// timeout occurs. This out-of-sync refresh results in a split second where
// there's no separator between the overlay and active contents, making the
// overlay contents erroneously appear to be part of active contents.
// When the overlay is repainted at the full height, we'll be notified via
// NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKGING_STORE, at which time
// the shadow view will be removed.
if (overlay_ && draw_drop_shadow_) {
#if !defined(OS_WIN)
if (!shadow_view_.get()) // Shadow view has not been created.
shadow_view_.reset(new ShadowView());
if (!shadow_view_->parent()) // Shadow view has not been added.
AddChildView(shadow_view_.get());
#endif // !defined(OS_WIN)
} else if (!overlay_) {
shadow_view_.reset();
}
Layout();
}
void ContentsContainer::MaybeStackOverlayAtTop() {
if (!overlay_)
return;
// To force |overlay_| to the topmost in the z-order, remove it, then add it
// back.
// See comments in SetOverlay() for why shadow view is removed.
bool removed_shadow = false;
if (shadow_view_.get()) {
RemoveChildView(shadow_view_.get());
removed_shadow = true;
}
RemoveChildView(overlay_);
AddChildView(overlay_);
if (removed_shadow) // Add back shadow view if it was removed.
AddChildView(shadow_view_.get());
Layout();
}
void ContentsContainer::SetActiveTopMargin(int margin) {
if (active_top_margin_ == margin)
return;
active_top_margin_ = margin;
// Make sure we layout next time around. We need this in case our bounds
// haven't changed.
InvalidateLayout();
}
gfx::Rect ContentsContainer::GetOverlayBounds() const {
gfx::Point screen_loc;
ConvertPointToScreen(this, &screen_loc);
return gfx::Rect(screen_loc, size());
}
bool ContentsContainer::IsOverlayFullHeight(
int overlay_height,
InstantSizeUnits overlay_height_units) const {
int height_in_pixels = OverlayHeightInPixels(height(), overlay_height,
overlay_height_units);
return height_in_pixels == height();
}
void ContentsContainer::Layout() {
int content_y = active_top_margin_;
int content_height = std::max(0, height() - content_y);
active_->SetBounds(0, content_y, width(), content_height);
if (overlay_) {
overlay_->SetBounds(0, 0, width(),
OverlayHeightInPixels(height(), overlay_height_,
overlay_height_units_));
if (draw_drop_shadow_) {
#if !defined(OS_WIN)
DCHECK(shadow_view_.get() && shadow_view_->parent());
shadow_view_->SetBounds(0, overlay_->bounds().height(), width(),
shadow_view_->GetPreferredSize().height());
#endif // !defined(OS_WIN)
}
}
// Need to invoke views::View in case any views whose bounds didn't change
// still need a layout.
views::View::Layout();
}
std::string ContentsContainer::GetClassName() const {
return kViewClassName;
}
void ContentsContainer::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK_EQ(content::NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
type);
// Remove shadow view if it's not needed.
if (overlay_ && !draw_drop_shadow_) {
DCHECK(overlay_web_contents_);
DCHECK_EQ(overlay_web_contents_->GetRenderViewHost(),
(content::Source<content::RenderWidgetHost>(source)).ptr());
shadow_view_.reset();
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/chromeos/mobile_setup_ui.h"
#include <algorithm>
#include <map>
#include <string>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/file_util.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/memory/ref_counted_memory.h"
#include "base/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/mobile/mobile_activator.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/webui/chrome_url_data_manager.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_view_host_observer.h"
#include "content/public/browser/url_data_source_delegate.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "googleurl/src/gurl.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
using chromeos::CellularNetwork;
using chromeos::CrosLibrary;
using chromeos::MobileActivator;
using content::BrowserThread;
using content::RenderViewHost;
using content::WebContents;
using content::WebUIMessageHandler;
namespace {
// Host page JS API function names.
const char kJsApiStartActivation[] = "startActivation";
const char kJsApiSetTransactionStatus[] = "setTransactionStatus";
const char kJsApiPaymentPortalLoad[] = "paymentPortalLoad";
const char kJsApiResultOK[] = "ok";
const char kJsDeviceStatusChangedCallback[] =
"mobile.MobileSetup.deviceStateChanged";
const char kJsPortalFrameLoadFailedCallback[] =
"mobile.MobileSetup.portalFrameLoadError";
const char kJsPortalFrameLoadCompletedCallback[] =
"mobile.MobileSetup.portalFrameLoadCompleted";
} // namespace
// Observes IPC messages from the rederer and notifies JS if frame loading error
// appears.
class PortalFrameLoadObserver : public content::RenderViewHostObserver {
public:
PortalFrameLoadObserver(const base::WeakPtr<MobileSetupUI>& parent,
RenderViewHost* host)
: content::RenderViewHostObserver(host), parent_(parent) {
Send(new ChromeViewMsg_StartFrameSniffer(routing_id(),
UTF8ToUTF16("paymentForm")));
}
// IPC::Listener implementation.
virtual bool OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(PortalFrameLoadObserver, message)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FrameLoadingError, OnFrameLoadError)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FrameLoadingCompleted,
OnFrameLoadCompleted)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
private:
void OnFrameLoadError(int error) {
if (!parent_.get())
return;
base::FundamentalValue result_value(error);
parent_->web_ui()->CallJavascriptFunction(kJsPortalFrameLoadFailedCallback,
result_value);
}
void OnFrameLoadCompleted() {
if (!parent_.get())
return;
parent_->web_ui()->CallJavascriptFunction(
kJsPortalFrameLoadCompletedCallback);
}
base::WeakPtr<MobileSetupUI> parent_;
DISALLOW_COPY_AND_ASSIGN(PortalFrameLoadObserver);
};
class MobileSetupUIHTMLSource : public content::URLDataSourceDelegate {
public:
MobileSetupUIHTMLSource();
// content::URLDataSourceDelegate implementation.
virtual std::string GetSource() OVERRIDE;
virtual void StartDataRequest(const std::string& path,
bool is_incognito,
int request_id);
virtual std::string GetMimeType(const std::string&) const {
return "text/html";
}
private:
virtual ~MobileSetupUIHTMLSource() {}
DISALLOW_COPY_AND_ASSIGN(MobileSetupUIHTMLSource);
};
// The handler for Javascript messages related to the "register" view.
class MobileSetupHandler
: public WebUIMessageHandler,
public MobileActivator::Observer,
public base::SupportsWeakPtr<MobileSetupHandler> {
public:
MobileSetupHandler();
virtual ~MobileSetupHandler();
// WebUIMessageHandler implementation.
virtual void RegisterMessages() OVERRIDE;
private:
// Changes internal state.
void OnActivationStateChanged(CellularNetwork* network,
MobileActivator::PlanActivationState new_state,
const std::string& error_description);
// Handlers for JS WebUI messages.
void HandleSetTransactionStatus(const ListValue* args);
void HandleStartActivation(const ListValue* args);
void HandlePaymentPortalLoad(const ListValue* args);
// Sends message to host registration page with system/user info data.
void SendDeviceInfo();
// Converts the currently active CellularNetwork device into a JS object.
static void GetDeviceInfo(CellularNetwork* network,
DictionaryValue* value);
DISALLOW_COPY_AND_ASSIGN(MobileSetupHandler);
};
////////////////////////////////////////////////////////////////////////////////
//
// MobileSetupUIHTMLSource
//
////////////////////////////////////////////////////////////////////////////////
MobileSetupUIHTMLSource::MobileSetupUIHTMLSource() {
}
std::string MobileSetupUIHTMLSource::GetSource() OVERRIDE {
return chrome::kChromeUIMobileSetupHost;
}
void MobileSetupUIHTMLSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
CellularNetwork* network = !path.size() ? NULL :
CrosLibrary::Get()->
GetNetworkLibrary()->FindCellularNetworkByPath(path);
if (!network || !network->SupportsActivation()) {
LOG(WARNING) << "Can't find device to activate for service path " << path;
scoped_refptr<base::RefCountedBytes> html_bytes(new base::RefCountedBytes);
url_data_source()->SendResponse(request_id, html_bytes);
return;
}
LOG(WARNING) << "Activating mobile service " << path;
DictionaryValue strings;
strings.SetString("title", l10n_util::GetStringUTF16(IDS_MOBILE_SETUP_TITLE));
strings.SetString("connecting_header",
l10n_util::GetStringFUTF16(IDS_MOBILE_CONNECTING_HEADER,
network ? UTF8ToUTF16(network->name()) : string16()));
strings.SetString("error_header",
l10n_util::GetStringUTF16(IDS_MOBILE_ERROR_HEADER));
strings.SetString("activating_header",
l10n_util::GetStringUTF16(IDS_MOBILE_ACTIVATING_HEADER));
strings.SetString("completed_header",
l10n_util::GetStringUTF16(IDS_MOBILE_COMPLETED_HEADER));
strings.SetString("please_wait",
l10n_util::GetStringUTF16(IDS_MOBILE_PLEASE_WAIT));
strings.SetString("completed_text",
l10n_util::GetStringUTF16(IDS_MOBILE_COMPLETED_TEXT));
strings.SetString("close_button",
l10n_util::GetStringUTF16(IDS_CLOSE));
strings.SetString("cancel_button",
l10n_util::GetStringUTF16(IDS_CANCEL));
strings.SetString("ok_button",
l10n_util::GetStringUTF16(IDS_OK));
URLDataSource::SetFontAndTextDirection(&strings);
static const base::StringPiece html(
ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_MOBILE_SETUP_PAGE_HTML));
std::string full_html = jstemplate_builder::GetI18nTemplateHtml(html,
&strings);
url_data_source()->SendResponse(
request_id, base::RefCountedString::TakeString(&full_html));
}
////////////////////////////////////////////////////////////////////////////////
//
// MobileSetupHandler
//
////////////////////////////////////////////////////////////////////////////////
MobileSetupHandler::MobileSetupHandler() {
MobileActivator::GetInstance()->AddObserver(this);
}
MobileSetupHandler::~MobileSetupHandler() {
MobileActivator::GetInstance()->RemoveObserver(this);
MobileActivator::GetInstance()->TerminateActivation();
}
void MobileSetupHandler::OnActivationStateChanged(
CellularNetwork* network,
MobileActivator::PlanActivationState state,
const std::string& error_description) {
if (!web_ui())
return;
DictionaryValue device_dict;
if (network)
GetDeviceInfo(network, &device_dict);
device_dict.SetInteger("state", state);
if (error_description.length())
device_dict.SetString("error", error_description);
web_ui()->CallJavascriptFunction(
kJsDeviceStatusChangedCallback, device_dict);
}
void MobileSetupHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback(kJsApiStartActivation,
base::Bind(&MobileSetupHandler::HandleStartActivation,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kJsApiSetTransactionStatus,
base::Bind(&MobileSetupHandler::HandleSetTransactionStatus,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kJsApiPaymentPortalLoad,
base::Bind(&MobileSetupHandler::HandlePaymentPortalLoad,
base::Unretained(this)));
}
void MobileSetupHandler::HandleStartActivation(const ListValue* args) {
if (!web_ui())
return;
std::string path = web_ui()->GetWebContents()->GetURL().path();
if (!path.size())
return;
LOG(WARNING) << "Starting activation for service " << path;
MobileActivator::GetInstance()->InitiateActivation(path.substr(1));
}
void MobileSetupHandler::HandleSetTransactionStatus(const ListValue* args) {
const size_t kSetTransactionStatusParamCount = 1;
if (args->GetSize() != kSetTransactionStatusParamCount)
return;
// Get change callback function name.
std::string status;
if (!args->GetString(0, &status))
return;
MobileActivator::GetInstance()->OnSetTransactionStatus(
LowerCaseEqualsASCII(status, kJsApiResultOK));
}
void MobileSetupHandler::HandlePaymentPortalLoad(const ListValue* args) {
const size_t kPaymentPortalLoadParamCount = 1;
if (args->GetSize() != kPaymentPortalLoadParamCount)
return;
// Get change callback function name.
std::string result;
if (!args->GetString(0, &result))
return;
MobileActivator::GetInstance()->OnPortalLoaded(
LowerCaseEqualsASCII(result, kJsApiResultOK));
}
void MobileSetupHandler::GetDeviceInfo(CellularNetwork* network,
DictionaryValue* value) {
DCHECK(network);
chromeos::NetworkLibrary* cros =
chromeos::CrosLibrary::Get()->GetNetworkLibrary();
if (!cros)
return;
value->SetString("carrier", network->name());
value->SetString("payment_url", network->payment_url());
if (network->using_post() && network->post_data().length())
value->SetString("post_data", network->post_data());
const chromeos::NetworkDevice* device =
cros->FindNetworkDeviceByPath(network->device_path());
if (device) {
value->SetString("MEID", device->meid());
value->SetString("IMEI", device->imei());
value->SetString("MDN", device->mdn());
}
}
////////////////////////////////////////////////////////////////////////////////
//
// MobileSetupUI
//
////////////////////////////////////////////////////////////////////////////////
MobileSetupUI::MobileSetupUI(content::WebUI* web_ui)
: WebUIController(web_ui) {
web_ui->AddMessageHandler(new MobileSetupHandler());
MobileSetupUIHTMLSource* html_source = new MobileSetupUIHTMLSource();
// Set up the chrome://mobilesetup/ source.
Profile* profile = Profile::FromWebUI(web_ui);
ChromeURLDataManager::AddDataSource(profile, html_source);
}
void MobileSetupUI::RenderViewCreated(RenderViewHost* host) {
// Destroyed by the corresponding RenderViewHost
new PortalFrameLoadObserver(AsWeakPtr(), host);
}
<commit_msg>Fix linux asan build from previous change<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/chromeos/mobile_setup_ui.h"
#include <algorithm>
#include <map>
#include <string>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/file_util.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/memory/ref_counted_memory.h"
#include "base/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/mobile/mobile_activator.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/webui/chrome_url_data_manager.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_view_host_observer.h"
#include "content/public/browser/url_data_source_delegate.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "googleurl/src/gurl.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
using chromeos::CellularNetwork;
using chromeos::CrosLibrary;
using chromeos::MobileActivator;
using content::BrowserThread;
using content::RenderViewHost;
using content::WebContents;
using content::WebUIMessageHandler;
namespace {
// Host page JS API function names.
const char kJsApiStartActivation[] = "startActivation";
const char kJsApiSetTransactionStatus[] = "setTransactionStatus";
const char kJsApiPaymentPortalLoad[] = "paymentPortalLoad";
const char kJsApiResultOK[] = "ok";
const char kJsDeviceStatusChangedCallback[] =
"mobile.MobileSetup.deviceStateChanged";
const char kJsPortalFrameLoadFailedCallback[] =
"mobile.MobileSetup.portalFrameLoadError";
const char kJsPortalFrameLoadCompletedCallback[] =
"mobile.MobileSetup.portalFrameLoadCompleted";
} // namespace
// Observes IPC messages from the rederer and notifies JS if frame loading error
// appears.
class PortalFrameLoadObserver : public content::RenderViewHostObserver {
public:
PortalFrameLoadObserver(const base::WeakPtr<MobileSetupUI>& parent,
RenderViewHost* host)
: content::RenderViewHostObserver(host), parent_(parent) {
Send(new ChromeViewMsg_StartFrameSniffer(routing_id(),
UTF8ToUTF16("paymentForm")));
}
// IPC::Listener implementation.
virtual bool OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(PortalFrameLoadObserver, message)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FrameLoadingError, OnFrameLoadError)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FrameLoadingCompleted,
OnFrameLoadCompleted)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
private:
void OnFrameLoadError(int error) {
if (!parent_.get())
return;
base::FundamentalValue result_value(error);
parent_->web_ui()->CallJavascriptFunction(kJsPortalFrameLoadFailedCallback,
result_value);
}
void OnFrameLoadCompleted() {
if (!parent_.get())
return;
parent_->web_ui()->CallJavascriptFunction(
kJsPortalFrameLoadCompletedCallback);
}
base::WeakPtr<MobileSetupUI> parent_;
DISALLOW_COPY_AND_ASSIGN(PortalFrameLoadObserver);
};
class MobileSetupUIHTMLSource : public content::URLDataSourceDelegate {
public:
MobileSetupUIHTMLSource();
// content::URLDataSourceDelegate implementation.
virtual std::string GetSource() OVERRIDE;
virtual void StartDataRequest(const std::string& path,
bool is_incognito,
int request_id);
virtual std::string GetMimeType(const std::string&) const {
return "text/html";
}
private:
virtual ~MobileSetupUIHTMLSource() {}
DISALLOW_COPY_AND_ASSIGN(MobileSetupUIHTMLSource);
};
// The handler for Javascript messages related to the "register" view.
class MobileSetupHandler
: public WebUIMessageHandler,
public MobileActivator::Observer,
public base::SupportsWeakPtr<MobileSetupHandler> {
public:
MobileSetupHandler();
virtual ~MobileSetupHandler();
// WebUIMessageHandler implementation.
virtual void RegisterMessages() OVERRIDE;
private:
// Changes internal state.
void OnActivationStateChanged(CellularNetwork* network,
MobileActivator::PlanActivationState new_state,
const std::string& error_description);
// Handlers for JS WebUI messages.
void HandleSetTransactionStatus(const ListValue* args);
void HandleStartActivation(const ListValue* args);
void HandlePaymentPortalLoad(const ListValue* args);
// Sends message to host registration page with system/user info data.
void SendDeviceInfo();
// Converts the currently active CellularNetwork device into a JS object.
static void GetDeviceInfo(CellularNetwork* network,
DictionaryValue* value);
DISALLOW_COPY_AND_ASSIGN(MobileSetupHandler);
};
////////////////////////////////////////////////////////////////////////////////
//
// MobileSetupUIHTMLSource
//
////////////////////////////////////////////////////////////////////////////////
MobileSetupUIHTMLSource::MobileSetupUIHTMLSource() {
}
std::string MobileSetupUIHTMLSource::GetSource() {
return chrome::kChromeUIMobileSetupHost;
}
void MobileSetupUIHTMLSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
CellularNetwork* network = !path.size() ? NULL :
CrosLibrary::Get()->
GetNetworkLibrary()->FindCellularNetworkByPath(path);
if (!network || !network->SupportsActivation()) {
LOG(WARNING) << "Can't find device to activate for service path " << path;
scoped_refptr<base::RefCountedBytes> html_bytes(new base::RefCountedBytes);
url_data_source()->SendResponse(request_id, html_bytes);
return;
}
LOG(WARNING) << "Activating mobile service " << path;
DictionaryValue strings;
strings.SetString("title", l10n_util::GetStringUTF16(IDS_MOBILE_SETUP_TITLE));
strings.SetString("connecting_header",
l10n_util::GetStringFUTF16(IDS_MOBILE_CONNECTING_HEADER,
network ? UTF8ToUTF16(network->name()) : string16()));
strings.SetString("error_header",
l10n_util::GetStringUTF16(IDS_MOBILE_ERROR_HEADER));
strings.SetString("activating_header",
l10n_util::GetStringUTF16(IDS_MOBILE_ACTIVATING_HEADER));
strings.SetString("completed_header",
l10n_util::GetStringUTF16(IDS_MOBILE_COMPLETED_HEADER));
strings.SetString("please_wait",
l10n_util::GetStringUTF16(IDS_MOBILE_PLEASE_WAIT));
strings.SetString("completed_text",
l10n_util::GetStringUTF16(IDS_MOBILE_COMPLETED_TEXT));
strings.SetString("close_button",
l10n_util::GetStringUTF16(IDS_CLOSE));
strings.SetString("cancel_button",
l10n_util::GetStringUTF16(IDS_CANCEL));
strings.SetString("ok_button",
l10n_util::GetStringUTF16(IDS_OK));
URLDataSource::SetFontAndTextDirection(&strings);
static const base::StringPiece html(
ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_MOBILE_SETUP_PAGE_HTML));
std::string full_html = jstemplate_builder::GetI18nTemplateHtml(html,
&strings);
url_data_source()->SendResponse(
request_id, base::RefCountedString::TakeString(&full_html));
}
////////////////////////////////////////////////////////////////////////////////
//
// MobileSetupHandler
//
////////////////////////////////////////////////////////////////////////////////
MobileSetupHandler::MobileSetupHandler() {
MobileActivator::GetInstance()->AddObserver(this);
}
MobileSetupHandler::~MobileSetupHandler() {
MobileActivator::GetInstance()->RemoveObserver(this);
MobileActivator::GetInstance()->TerminateActivation();
}
void MobileSetupHandler::OnActivationStateChanged(
CellularNetwork* network,
MobileActivator::PlanActivationState state,
const std::string& error_description) {
if (!web_ui())
return;
DictionaryValue device_dict;
if (network)
GetDeviceInfo(network, &device_dict);
device_dict.SetInteger("state", state);
if (error_description.length())
device_dict.SetString("error", error_description);
web_ui()->CallJavascriptFunction(
kJsDeviceStatusChangedCallback, device_dict);
}
void MobileSetupHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback(kJsApiStartActivation,
base::Bind(&MobileSetupHandler::HandleStartActivation,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kJsApiSetTransactionStatus,
base::Bind(&MobileSetupHandler::HandleSetTransactionStatus,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(kJsApiPaymentPortalLoad,
base::Bind(&MobileSetupHandler::HandlePaymentPortalLoad,
base::Unretained(this)));
}
void MobileSetupHandler::HandleStartActivation(const ListValue* args) {
if (!web_ui())
return;
std::string path = web_ui()->GetWebContents()->GetURL().path();
if (!path.size())
return;
LOG(WARNING) << "Starting activation for service " << path;
MobileActivator::GetInstance()->InitiateActivation(path.substr(1));
}
void MobileSetupHandler::HandleSetTransactionStatus(const ListValue* args) {
const size_t kSetTransactionStatusParamCount = 1;
if (args->GetSize() != kSetTransactionStatusParamCount)
return;
// Get change callback function name.
std::string status;
if (!args->GetString(0, &status))
return;
MobileActivator::GetInstance()->OnSetTransactionStatus(
LowerCaseEqualsASCII(status, kJsApiResultOK));
}
void MobileSetupHandler::HandlePaymentPortalLoad(const ListValue* args) {
const size_t kPaymentPortalLoadParamCount = 1;
if (args->GetSize() != kPaymentPortalLoadParamCount)
return;
// Get change callback function name.
std::string result;
if (!args->GetString(0, &result))
return;
MobileActivator::GetInstance()->OnPortalLoaded(
LowerCaseEqualsASCII(result, kJsApiResultOK));
}
void MobileSetupHandler::GetDeviceInfo(CellularNetwork* network,
DictionaryValue* value) {
DCHECK(network);
chromeos::NetworkLibrary* cros =
chromeos::CrosLibrary::Get()->GetNetworkLibrary();
if (!cros)
return;
value->SetString("carrier", network->name());
value->SetString("payment_url", network->payment_url());
if (network->using_post() && network->post_data().length())
value->SetString("post_data", network->post_data());
const chromeos::NetworkDevice* device =
cros->FindNetworkDeviceByPath(network->device_path());
if (device) {
value->SetString("MEID", device->meid());
value->SetString("IMEI", device->imei());
value->SetString("MDN", device->mdn());
}
}
////////////////////////////////////////////////////////////////////////////////
//
// MobileSetupUI
//
////////////////////////////////////////////////////////////////////////////////
MobileSetupUI::MobileSetupUI(content::WebUI* web_ui)
: WebUIController(web_ui) {
web_ui->AddMessageHandler(new MobileSetupHandler());
MobileSetupUIHTMLSource* html_source = new MobileSetupUIHTMLSource();
// Set up the chrome://mobilesetup/ source.
Profile* profile = Profile::FromWebUI(web_ui);
ChromeURLDataManager::AddDataSource(profile, html_source);
}
void MobileSetupUI::RenderViewCreated(RenderViewHost* host) {
// Destroyed by the corresponding RenderViewHost
new PortalFrameLoadObserver(AsWeakPtr(), host);
}
<|endoftext|>
|
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/ntp/ntp_user_data_logger.h"
#include "base/metrics/histogram.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/after_startup_task_utils.h"
#include "chrome/browser/search/most_visited_iframe_source.h"
#include "chrome/browser/search/search.h"
#include "chrome/common/search_urls.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
// Macro to log UMA statistics related to the 8 tiles shown on the NTP.
#define UMA_HISTOGRAM_NTP_TILES(name, sample) \
UMA_HISTOGRAM_CUSTOM_COUNTS(name, sample, 0, 8, 9)
namespace {
// Used to track if suggestions were issued by the client or the server.
enum SuggestionsType {
CLIENT_SIDE = 0,
SERVER_SIDE = 1,
SUGGESTIONS_TYPE_COUNT = 2
};
// Number of Most Visited elements on the NTP for logging purposes.
const int kNumMostVisited = 8;
// Name of the histogram keeping track of Most Visited impressions.
const char kMostVisitedImpressionHistogramName[] =
"NewTabPage.SuggestionsImpression";
// Format string to generate the name for the histogram keeping track of
// suggestion impressions.
const char kMostVisitedImpressionHistogramWithProvider[] =
"NewTabPage.SuggestionsImpression.%s";
// Name of the histogram keeping track of Most Visited navigations.
const char kMostVisitedNavigationHistogramName[] =
"NewTabPage.MostVisited";
// Format string to generate the name for the histogram keeping track of
// suggestion navigations.
const char kMostVisitedNavigationHistogramWithProvider[] =
"NewTabPage.MostVisited.%s";
} // namespace
DEFINE_WEB_CONTENTS_USER_DATA_KEY(NTPUserDataLogger);
// Log a time event for a given |histogram| at a given |value|. This
// routine exists because regular histogram macros are cached thus can't be used
// if the name of the histogram will change at a given call site.
void logLoadTimeHistogram(const std::string& histogram, base::TimeDelta value) {
base::HistogramBase* counter = base::LinearHistogram::FactoryTimeGet(
histogram,
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromSeconds(60), 100,
base::Histogram::kUmaTargetedHistogramFlag);
if (counter)
counter->AddTime(value);
}
NTPUserDataLogger::~NTPUserDataLogger() {}
// static
NTPUserDataLogger* NTPUserDataLogger::GetOrCreateFromWebContents(
content::WebContents* content) {
// Calling CreateForWebContents when an instance is already attached has no
// effect, so we can do this.
NTPUserDataLogger::CreateForWebContents(content);
NTPUserDataLogger* logger = NTPUserDataLogger::FromWebContents(content);
// We record the URL of this NTP in order to identify navigations that
// originate from it. We use the NavigationController's URL since it might
// differ from the WebContents URL which is usually chrome://newtab/.
const content::NavigationEntry* entry =
content->GetController().GetVisibleEntry();
if (entry)
logger->ntp_url_ = entry->GetURL();
return logger;
}
// static
std::string NTPUserDataLogger::GetMostVisitedImpressionHistogramNameForProvider(
const std::string& provider) {
return base::StringPrintf(kMostVisitedImpressionHistogramWithProvider,
provider.c_str());
}
// static
std::string NTPUserDataLogger::GetMostVisitedNavigationHistogramNameForProvider(
const std::string& provider) {
return base::StringPrintf(kMostVisitedNavigationHistogramWithProvider,
provider.c_str());
}
void NTPUserDataLogger::EmitNtpStatistics() {
UMA_HISTOGRAM_COUNTS("NewTabPage.NumberOfMouseOvers", number_of_mouseovers_);
number_of_mouseovers_ = 0;
// We only send statistics once per page.
// And we don't send if there are no tiles recorded.
if (has_emitted_ || !number_of_tiles_)
return;
// LoadTime only gets update once per page, so we don't have it on reloads.
if (load_time_ > base::TimeDelta::FromMilliseconds(0)) {
logLoadTimeHistogram("NewTabPage.LoadTime", load_time_);
// Split between ML and MV.
std::string type = has_server_side_suggestions_ ?
"MostLikely" : "MostVisited";
logLoadTimeHistogram("NewTabPage.LoadTime." + type, load_time_);
// Split between Web and Local.
std::string source = ntp_url_.SchemeIsHTTPOrHTTPS() ? "Web" : "LocalNTP";
logLoadTimeHistogram("NewTabPage.LoadTime." + source, load_time_);
// Split between Startup and non-startup.
std::string status = during_startup_ ? "Startup" : "Newtab";
logLoadTimeHistogram("NewTabPage.LoadTime." + status, load_time_);
load_time_ = base::TimeDelta::FromMilliseconds(0);
}
UMA_HISTOGRAM_ENUMERATION(
"NewTabPage.SuggestionsType",
has_server_side_suggestions_ ? SERVER_SIDE : CLIENT_SIDE,
SUGGESTIONS_TYPE_COUNT);
has_server_side_suggestions_ = false;
has_client_side_suggestions_ = false;
UMA_HISTOGRAM_NTP_TILES("NewTabPage.NumberOfTiles", number_of_tiles_);
number_of_tiles_ = 0;
UMA_HISTOGRAM_NTP_TILES("NewTabPage.NumberOfThumbnailTiles",
number_of_thumbnail_tiles_);
number_of_thumbnail_tiles_ = 0;
UMA_HISTOGRAM_NTP_TILES("NewTabPage.NumberOfGrayTiles",
number_of_gray_tiles_);
number_of_gray_tiles_ = 0;
UMA_HISTOGRAM_NTP_TILES("NewTabPage.NumberOfExternalTiles",
number_of_external_tiles_);
number_of_external_tiles_ = 0;
UMA_HISTOGRAM_NTP_TILES("NewTabPage.NumberOfThumbnailErrors",
number_of_thumbnail_errors_);
number_of_thumbnail_errors_ = 0;
UMA_HISTOGRAM_NTP_TILES("NewTabPage.NumberOfGrayTileFallbacks",
number_of_gray_tile_fallbacks_);
number_of_gray_tile_fallbacks_ = 0;
UMA_HISTOGRAM_NTP_TILES("NewTabPage.NumberOfExternalTileFallbacks",
number_of_external_tile_fallbacks_);
number_of_external_tile_fallbacks_ = 0;
has_emitted_ = true;
during_startup_ = false;
}
void NTPUserDataLogger::LogEvent(NTPLoggingEventType event,
base::TimeDelta time) {
switch (event) {
// It is possible that our page gets update with a different set of
// suggestions if the NTP is left open enough time.
// In either case, we want to flush our stats before recounting again.
case NTP_SERVER_SIDE_SUGGESTION:
if (has_client_side_suggestions_)
EmitNtpStatistics();
has_server_side_suggestions_ = true;
break;
case NTP_CLIENT_SIDE_SUGGESTION:
if (has_server_side_suggestions_)
EmitNtpStatistics();
has_client_side_suggestions_ = true;
break;
case NTP_TILE:
number_of_tiles_++;
break;
case NTP_THUMBNAIL_TILE:
number_of_thumbnail_tiles_++;
break;
case NTP_GRAY_TILE:
number_of_gray_tiles_++;
break;
case NTP_EXTERNAL_TILE:
number_of_external_tiles_++;
break;
case NTP_THUMBNAIL_ERROR:
number_of_thumbnail_errors_++;
break;
case NTP_GRAY_TILE_FALLBACK:
number_of_gray_tile_fallbacks_++;
break;
case NTP_EXTERNAL_TILE_FALLBACK:
number_of_external_tile_fallbacks_++;
break;
case NTP_MOUSEOVER:
number_of_mouseovers_++;
break;
case NTP_TILE_LOADED:
// The time at which the last tile has loaded (title, thumbnail or single)
// is a good proxy for the total load time of the NTP, therefore we keep
// the max as the load time.
load_time_ = std::max(load_time_, time);
break;
default:
NOTREACHED();
}
}
void NTPUserDataLogger::LogMostVisitedImpression(
int position, const base::string16& provider) {
// Log the Most Visited navigation for navigations that have providers and
// those that dont.
UMA_HISTOGRAM_ENUMERATION(kMostVisitedImpressionHistogramName, position,
kNumMostVisited);
// If a provider is specified, log the metric specific to it.
if (!provider.empty()) {
// Cannot rely on UMA histograms macro because the name of the histogram is
// generated dynamically.
base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
GetMostVisitedImpressionHistogramNameForProvider(
base::UTF16ToUTF8(provider)),
1,
kNumMostVisited,
kNumMostVisited + 1,
base::Histogram::kUmaTargetedHistogramFlag);
counter->Add(position);
}
}
void NTPUserDataLogger::LogMostVisitedNavigation(
int position, const base::string16& provider) {
// Log the Most Visited navigation for navigations that have providers and
// those that dont.
UMA_HISTOGRAM_ENUMERATION(kMostVisitedNavigationHistogramName, position,
kNumMostVisited);
// If a provider is specified, log the metric specific to it.
if (!provider.empty()) {
// Cannot rely on UMA histograms macro because the name of the histogram is
// generated dynamically.
base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
GetMostVisitedNavigationHistogramNameForProvider(
base::UTF16ToUTF8(provider)),
1,
kNumMostVisited,
kNumMostVisited + 1,
base::Histogram::kUmaTargetedHistogramFlag);
counter->Add(position);
}
// Records the action. This will be available as a time-stamped stream
// server-side and can be used to compute time-to-long-dwell.
content::RecordAction(base::UserMetricsAction("MostVisited_Clicked"));
}
// content::WebContentsObserver override
void NTPUserDataLogger::NavigationEntryCommitted(
const content::LoadCommittedDetails& load_details) {
if (!load_details.previous_url.is_valid())
return;
if (search::MatchesOriginAndPath(ntp_url_, load_details.previous_url)) {
EmitNtpStatistics();
}
}
NTPUserDataLogger::NTPUserDataLogger(content::WebContents* contents)
: content::WebContentsObserver(contents),
has_server_side_suggestions_(false),
has_client_side_suggestions_(false),
number_of_tiles_(0),
number_of_thumbnail_tiles_(0),
number_of_gray_tiles_(0),
number_of_external_tiles_(0),
number_of_thumbnail_errors_(0),
number_of_gray_tile_fallbacks_(0),
number_of_external_tile_fallbacks_(0),
number_of_mouseovers_(0),
has_emitted_(false),
during_startup_(false) {
during_startup_ = !AfterStartupTaskUtils::IsBrowserStartupComplete();
}
<commit_msg>Fix typo on NTP histogram name<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/ntp/ntp_user_data_logger.h"
#include "base/metrics/histogram.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/after_startup_task_utils.h"
#include "chrome/browser/search/most_visited_iframe_source.h"
#include "chrome/browser/search/search.h"
#include "chrome/common/search_urls.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
// Macro to log UMA statistics related to the 8 tiles shown on the NTP.
#define UMA_HISTOGRAM_NTP_TILES(name, sample) \
UMA_HISTOGRAM_CUSTOM_COUNTS(name, sample, 0, 8, 9)
namespace {
// Used to track if suggestions were issued by the client or the server.
enum SuggestionsType {
CLIENT_SIDE = 0,
SERVER_SIDE = 1,
SUGGESTIONS_TYPE_COUNT = 2
};
// Number of Most Visited elements on the NTP for logging purposes.
const int kNumMostVisited = 8;
// Name of the histogram keeping track of Most Visited impressions.
const char kMostVisitedImpressionHistogramName[] =
"NewTabPage.SuggestionsImpression";
// Format string to generate the name for the histogram keeping track of
// suggestion impressions.
const char kMostVisitedImpressionHistogramWithProvider[] =
"NewTabPage.SuggestionsImpression.%s";
// Name of the histogram keeping track of Most Visited navigations.
const char kMostVisitedNavigationHistogramName[] =
"NewTabPage.MostVisited";
// Format string to generate the name for the histogram keeping track of
// suggestion navigations.
const char kMostVisitedNavigationHistogramWithProvider[] =
"NewTabPage.MostVisited.%s";
} // namespace
DEFINE_WEB_CONTENTS_USER_DATA_KEY(NTPUserDataLogger);
// Log a time event for a given |histogram| at a given |value|. This
// routine exists because regular histogram macros are cached thus can't be used
// if the name of the histogram will change at a given call site.
void logLoadTimeHistogram(const std::string& histogram, base::TimeDelta value) {
base::HistogramBase* counter = base::LinearHistogram::FactoryTimeGet(
histogram,
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromSeconds(60), 100,
base::Histogram::kUmaTargetedHistogramFlag);
if (counter)
counter->AddTime(value);
}
NTPUserDataLogger::~NTPUserDataLogger() {}
// static
NTPUserDataLogger* NTPUserDataLogger::GetOrCreateFromWebContents(
content::WebContents* content) {
// Calling CreateForWebContents when an instance is already attached has no
// effect, so we can do this.
NTPUserDataLogger::CreateForWebContents(content);
NTPUserDataLogger* logger = NTPUserDataLogger::FromWebContents(content);
// We record the URL of this NTP in order to identify navigations that
// originate from it. We use the NavigationController's URL since it might
// differ from the WebContents URL which is usually chrome://newtab/.
const content::NavigationEntry* entry =
content->GetController().GetVisibleEntry();
if (entry)
logger->ntp_url_ = entry->GetURL();
return logger;
}
// static
std::string NTPUserDataLogger::GetMostVisitedImpressionHistogramNameForProvider(
const std::string& provider) {
return base::StringPrintf(kMostVisitedImpressionHistogramWithProvider,
provider.c_str());
}
// static
std::string NTPUserDataLogger::GetMostVisitedNavigationHistogramNameForProvider(
const std::string& provider) {
return base::StringPrintf(kMostVisitedNavigationHistogramWithProvider,
provider.c_str());
}
void NTPUserDataLogger::EmitNtpStatistics() {
UMA_HISTOGRAM_COUNTS("NewTabPage.NumberOfMouseOvers", number_of_mouseovers_);
number_of_mouseovers_ = 0;
// We only send statistics once per page.
// And we don't send if there are no tiles recorded.
if (has_emitted_ || !number_of_tiles_)
return;
// LoadTime only gets update once per page, so we don't have it on reloads.
if (load_time_ > base::TimeDelta::FromMilliseconds(0)) {
logLoadTimeHistogram("NewTabPage.LoadTime", load_time_);
// Split between ML and MV.
std::string type = has_server_side_suggestions_ ?
"MostLikely" : "MostVisited";
logLoadTimeHistogram("NewTabPage.LoadTime." + type, load_time_);
// Split between Web and Local.
std::string source = ntp_url_.SchemeIsHTTPOrHTTPS() ? "Web" : "LocalNTP";
logLoadTimeHistogram("NewTabPage.LoadTime." + source, load_time_);
// Split between Startup and non-startup.
std::string status = during_startup_ ? "Startup" : "NewTab";
logLoadTimeHistogram("NewTabPage.LoadTime." + status, load_time_);
load_time_ = base::TimeDelta::FromMilliseconds(0);
}
UMA_HISTOGRAM_ENUMERATION(
"NewTabPage.SuggestionsType",
has_server_side_suggestions_ ? SERVER_SIDE : CLIENT_SIDE,
SUGGESTIONS_TYPE_COUNT);
has_server_side_suggestions_ = false;
has_client_side_suggestions_ = false;
UMA_HISTOGRAM_NTP_TILES("NewTabPage.NumberOfTiles", number_of_tiles_);
number_of_tiles_ = 0;
UMA_HISTOGRAM_NTP_TILES("NewTabPage.NumberOfThumbnailTiles",
number_of_thumbnail_tiles_);
number_of_thumbnail_tiles_ = 0;
UMA_HISTOGRAM_NTP_TILES("NewTabPage.NumberOfGrayTiles",
number_of_gray_tiles_);
number_of_gray_tiles_ = 0;
UMA_HISTOGRAM_NTP_TILES("NewTabPage.NumberOfExternalTiles",
number_of_external_tiles_);
number_of_external_tiles_ = 0;
UMA_HISTOGRAM_NTP_TILES("NewTabPage.NumberOfThumbnailErrors",
number_of_thumbnail_errors_);
number_of_thumbnail_errors_ = 0;
UMA_HISTOGRAM_NTP_TILES("NewTabPage.NumberOfGrayTileFallbacks",
number_of_gray_tile_fallbacks_);
number_of_gray_tile_fallbacks_ = 0;
UMA_HISTOGRAM_NTP_TILES("NewTabPage.NumberOfExternalTileFallbacks",
number_of_external_tile_fallbacks_);
number_of_external_tile_fallbacks_ = 0;
has_emitted_ = true;
during_startup_ = false;
}
void NTPUserDataLogger::LogEvent(NTPLoggingEventType event,
base::TimeDelta time) {
switch (event) {
// It is possible that our page gets update with a different set of
// suggestions if the NTP is left open enough time.
// In either case, we want to flush our stats before recounting again.
case NTP_SERVER_SIDE_SUGGESTION:
if (has_client_side_suggestions_)
EmitNtpStatistics();
has_server_side_suggestions_ = true;
break;
case NTP_CLIENT_SIDE_SUGGESTION:
if (has_server_side_suggestions_)
EmitNtpStatistics();
has_client_side_suggestions_ = true;
break;
case NTP_TILE:
number_of_tiles_++;
break;
case NTP_THUMBNAIL_TILE:
number_of_thumbnail_tiles_++;
break;
case NTP_GRAY_TILE:
number_of_gray_tiles_++;
break;
case NTP_EXTERNAL_TILE:
number_of_external_tiles_++;
break;
case NTP_THUMBNAIL_ERROR:
number_of_thumbnail_errors_++;
break;
case NTP_GRAY_TILE_FALLBACK:
number_of_gray_tile_fallbacks_++;
break;
case NTP_EXTERNAL_TILE_FALLBACK:
number_of_external_tile_fallbacks_++;
break;
case NTP_MOUSEOVER:
number_of_mouseovers_++;
break;
case NTP_TILE_LOADED:
// The time at which the last tile has loaded (title, thumbnail or single)
// is a good proxy for the total load time of the NTP, therefore we keep
// the max as the load time.
load_time_ = std::max(load_time_, time);
break;
default:
NOTREACHED();
}
}
void NTPUserDataLogger::LogMostVisitedImpression(
int position, const base::string16& provider) {
// Log the Most Visited navigation for navigations that have providers and
// those that dont.
UMA_HISTOGRAM_ENUMERATION(kMostVisitedImpressionHistogramName, position,
kNumMostVisited);
// If a provider is specified, log the metric specific to it.
if (!provider.empty()) {
// Cannot rely on UMA histograms macro because the name of the histogram is
// generated dynamically.
base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
GetMostVisitedImpressionHistogramNameForProvider(
base::UTF16ToUTF8(provider)),
1,
kNumMostVisited,
kNumMostVisited + 1,
base::Histogram::kUmaTargetedHistogramFlag);
counter->Add(position);
}
}
void NTPUserDataLogger::LogMostVisitedNavigation(
int position, const base::string16& provider) {
// Log the Most Visited navigation for navigations that have providers and
// those that dont.
UMA_HISTOGRAM_ENUMERATION(kMostVisitedNavigationHistogramName, position,
kNumMostVisited);
// If a provider is specified, log the metric specific to it.
if (!provider.empty()) {
// Cannot rely on UMA histograms macro because the name of the histogram is
// generated dynamically.
base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
GetMostVisitedNavigationHistogramNameForProvider(
base::UTF16ToUTF8(provider)),
1,
kNumMostVisited,
kNumMostVisited + 1,
base::Histogram::kUmaTargetedHistogramFlag);
counter->Add(position);
}
// Records the action. This will be available as a time-stamped stream
// server-side and can be used to compute time-to-long-dwell.
content::RecordAction(base::UserMetricsAction("MostVisited_Clicked"));
}
// content::WebContentsObserver override
void NTPUserDataLogger::NavigationEntryCommitted(
const content::LoadCommittedDetails& load_details) {
if (!load_details.previous_url.is_valid())
return;
if (search::MatchesOriginAndPath(ntp_url_, load_details.previous_url)) {
EmitNtpStatistics();
}
}
NTPUserDataLogger::NTPUserDataLogger(content::WebContents* contents)
: content::WebContentsObserver(contents),
has_server_side_suggestions_(false),
has_client_side_suggestions_(false),
number_of_tiles_(0),
number_of_thumbnail_tiles_(0),
number_of_gray_tiles_(0),
number_of_external_tiles_(0),
number_of_thumbnail_errors_(0),
number_of_gray_tile_fallbacks_(0),
number_of_external_tile_fallbacks_(0),
number_of_mouseovers_(0),
has_emitted_(false),
during_startup_(false) {
during_startup_ = !AfterStartupTaskUtils::IsBrowserStartupComplete();
}
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (Apache License)
*
* Copyright (c) 2014, Southwest Research Institute
*
* 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 <industrial_extrinsic_cal/ros_transform_interface.h>
#include <iostream>
#include <fstream>
int main(int argc, char **argv)
{
ros::init(argc, argv, "manual_calt_adjuster");
ros::NodeHandle nh, pnh("~");
ros::ServiceClient get_client; /**< a client for calling the service to get the joint values associated with the transform */
ros::ServiceClient set_client; /**< a client for calling the service to set the joint values associated with the transform */
ros::ServiceClient store_client; /**< a client for calling the service to store the joint values associated with the transform */
industrial_extrinsic_cal::get_mutable_joint_states::Request get_request; /**< request when transform is part of a mutable set */
industrial_extrinsic_cal::get_mutable_joint_states::Response get_response; /**< response when transform is part of a mutable set */
industrial_extrinsic_cal::set_mutable_joint_states::Request set_request; /**< request when transform is part of a mutable set */
industrial_extrinsic_cal::set_mutable_joint_states::Response set_response; /**< response when transform is part of a mutable set */
industrial_extrinsic_cal::store_mutable_joint_states::Request store_request; /**< request to store when part of a mutable set */
industrial_extrinsic_cal::store_mutable_joint_states::Response store_response;/**< response to store when part of a mutable set */
get_client = nh.serviceClient<industrial_extrinsic_cal::get_mutable_joint_states>("get_mutable_joint_states");
set_client = nh.serviceClient<industrial_extrinsic_cal::set_mutable_joint_states>("set_mutable_joint_states");
store_client = nh.serviceClient<industrial_extrinsic_cal::store_mutable_joint_states>("store_mutable_joint_states");
std::string base_name;
double delta_t, delta_d;
std::vector<double> joint_values;
if(argc == 4){
base_name = argv[1];
sscanf(argv[2],"%lf", &delta_t);
sscanf(argv[3],"%lf", &delta_d);
}
else{
ROS_ERROR(" usage manual_calt_adjuster base_name delta_theta delta_distance ");
exit(0);
}
get_request.joint_names.push_back(base_name+"_x_joint");
get_request.joint_names.push_back(base_name+"_y_joint");
get_request.joint_names.push_back(base_name+"_z_joint");
get_request.joint_names.push_back(base_name+"_yaw_joint");
get_request.joint_names.push_back(base_name+"_pitch_joint");
get_request.joint_names.push_back(base_name+"_roll_joint");
while(!get_client.call(get_request,get_response)){
sleep(1);
ROS_INFO("Waiting for mutable joint state publisher to come up");
}
if(get_response.joint_values.size() < 6){
ROS_ERROR("could not get the requested joint values from the mutable joint state publisher base_name: %s",base_name.c_str());
}
for(int i=0;i<(int) get_response.joint_values.size();i++){
joint_values.push_back(get_response.joint_values[i]);
}
set_request.joint_names.push_back(base_name+"_x_joint");
set_request.joint_names.push_back(base_name+"_y_joint");
set_request.joint_names.push_back(base_name+"_z_joint");
set_request.joint_names.push_back(base_name+"_yaw_joint");
set_request.joint_names.push_back(base_name+"_pitch_joint");
set_request.joint_names.push_back(base_name+"_roll_joint");
system ("/bin/stty raw");
ros::Rate loop_rate(10);
char c;
while(ros::ok() && c !='q'){
c = 'n';
c = getc(stdin);
set_request.joint_values.clear();
set_request.joint_names.clear();
switch (c)
{
case 'x':
joint_values[0] -= delta_d;
set_request.joint_values.push_back(joint_values[0]);
set_request.joint_names.push_back(base_name+"_x_joint");
set_client.call(set_request,set_response);
break;
case 'X':
joint_values[0] += delta_d;
set_request.joint_names.push_back(base_name+"_x_joint");
set_request.joint_values.push_back(joint_values[0]);
set_client.call(set_request,set_response);
break;
case 'y':
joint_values[1] -= delta_d;
set_request.joint_names.push_back(base_name+"_y_joint");
set_request.joint_values.push_back(joint_values[1]);
set_client.call(set_request,set_response);
break;
case 'Y':
joint_values[1] += delta_d;
set_request.joint_names.push_back(base_name+"_y_joint");
set_request.joint_values.push_back(joint_values[1]);
set_client.call(set_request,set_response);
break;
case 'z':
joint_values[2] -= delta_d;
set_request.joint_names.push_back(base_name+"_z_joint");
set_request.joint_values.push_back(joint_values[2]);
set_client.call(set_request,set_response);
break;
case 'Z':
joint_values[2] += delta_d;
set_request.joint_names.push_back(base_name+"_z_joint");
set_request.joint_values.push_back(joint_values[2]);
set_client.call(set_request,set_response);
break;
case 'r':
joint_values[3] -= delta_t;
set_request.joint_names.push_back(base_name+"_roll_joint");
set_request.joint_values.push_back(joint_values[3]);
set_client.call(set_request,set_response);
break;
case 'R':
joint_values[3] += delta_t;
set_request.joint_names.push_back(base_name+"_roll_joint");
set_request.joint_values.push_back(joint_values[3]);
set_client.call(set_request,set_response);
break;
case 'p':
joint_values[4] -= delta_t;
set_request.joint_names.push_back(base_name+"_pitch_joint");
set_request.joint_values.push_back(joint_values[4]);
set_client.call(set_request,set_response);
break;
case 'P':
joint_values[4] += delta_t;
set_request.joint_names.push_back(base_name+"_pitch_joint");
set_request.joint_values.push_back(joint_values[4]);
set_client.call(set_request,set_response);
break;
case 'w':
joint_values[5] -= delta_t;
set_request.joint_names.push_back(base_name+"_yaw_joint");
set_request.joint_values.push_back(joint_values[5]);
set_client.call(set_request,set_response);
break;
case 'W':
joint_values[5] += delta_t;
set_request.joint_names.push_back(base_name+"_yaw_joint");
set_request.joint_values.push_back(joint_values[5]);
set_client.call(set_request,set_response);
break;
case '-':
delta_d = delta_d*.95;
delta_t = delta_t*.95;
break;
case '+':
delta_d = delta_d*1.05;
delta_t = delta_t*1.05;
break;
case 's':
store_client.call(store_request, store_response);
break;
default:
break;
} // end switch
ros::spinOnce();
loop_rate.sleep();
}// end while ok
system ("/bin/stty cooked");
}
<commit_msg>fixed error in variable order for rotation updates<commit_after>/*
* Software License Agreement (Apache License)
*
* Copyright (c) 2014, Southwest Research Institute
*
* 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 <industrial_extrinsic_cal/ros_transform_interface.h>
#include <iostream>
#include <fstream>
int main(int argc, char **argv)
{
ros::init(argc, argv, "manual_calt_adjuster");
ros::NodeHandle nh, pnh("~");
ros::ServiceClient get_client; /**< a client for calling the service to get the joint values associated with the transform */
ros::ServiceClient set_client; /**< a client for calling the service to set the joint values associated with the transform */
ros::ServiceClient store_client; /**< a client for calling the service to store the joint values associated with the transform */
industrial_extrinsic_cal::get_mutable_joint_states::Request get_request; /**< request when transform is part of a mutable set */
industrial_extrinsic_cal::get_mutable_joint_states::Response get_response; /**< response when transform is part of a mutable set */
industrial_extrinsic_cal::set_mutable_joint_states::Request set_request; /**< request when transform is part of a mutable set */
industrial_extrinsic_cal::set_mutable_joint_states::Response set_response; /**< response when transform is part of a mutable set */
industrial_extrinsic_cal::store_mutable_joint_states::Request store_request; /**< request to store when part of a mutable set */
industrial_extrinsic_cal::store_mutable_joint_states::Response store_response;/**< response to store when part of a mutable set */
get_client = nh.serviceClient<industrial_extrinsic_cal::get_mutable_joint_states>("get_mutable_joint_states");
set_client = nh.serviceClient<industrial_extrinsic_cal::set_mutable_joint_states>("set_mutable_joint_states");
store_client = nh.serviceClient<industrial_extrinsic_cal::store_mutable_joint_states>("store_mutable_joint_states");
std::string base_name;
double delta_t, delta_d;
std::vector<double> joint_values;
if(argc == 4){
base_name = argv[1];
sscanf(argv[2],"%lf", &delta_t);
sscanf(argv[3],"%lf", &delta_d);
}
else{
ROS_ERROR(" usage manual_calt_adjuster base_name delta_theta delta_distance ");
exit(0);
}
get_request.joint_names.push_back(base_name+"_x_joint");
get_request.joint_names.push_back(base_name+"_y_joint");
get_request.joint_names.push_back(base_name+"_z_joint");
get_request.joint_names.push_back(base_name+"_yaw_joint");
get_request.joint_names.push_back(base_name+"_pitch_joint");
get_request.joint_names.push_back(base_name+"_roll_joint");
while(!get_client.call(get_request,get_response)){
sleep(1);
ROS_INFO("Waiting for mutable joint state publisher to come up");
}
if(get_response.joint_values.size() < 6){
ROS_ERROR("could not get the requested joint values from the mutable joint state publisher base_name: %s",base_name.c_str());
}
for(int i=0;i<(int) get_response.joint_values.size();i++){
joint_values.push_back(get_response.joint_values[i]);
}
set_request.joint_names.push_back(base_name+"_x_joint");
set_request.joint_names.push_back(base_name+"_y_joint");
set_request.joint_names.push_back(base_name+"_z_joint");
set_request.joint_names.push_back(base_name+"_yaw_joint");
set_request.joint_names.push_back(base_name+"_pitch_joint");
set_request.joint_names.push_back(base_name+"_roll_joint");
system ("/bin/stty raw");
ros::Rate loop_rate(10);
char c;
while(ros::ok() && c !='q'){
c = 'n';
c = getc(stdin);
set_request.joint_values.clear();
set_request.joint_names.clear();
switch (c)
{
case 'x':
joint_values[0] -= delta_d;
set_request.joint_values.push_back(joint_values[0]);
set_request.joint_names.push_back(base_name+"_x_joint");
set_client.call(set_request,set_response);
break;
case 'X':
joint_values[0] += delta_d;
set_request.joint_names.push_back(base_name+"_x_joint");
set_request.joint_values.push_back(joint_values[0]);
set_client.call(set_request,set_response);
break;
case 'y':
joint_values[1] -= delta_d;
set_request.joint_names.push_back(base_name+"_y_joint");
set_request.joint_values.push_back(joint_values[1]);
set_client.call(set_request,set_response);
break;
case 'Y':
joint_values[1] += delta_d;
set_request.joint_names.push_back(base_name+"_y_joint");
set_request.joint_values.push_back(joint_values[1]);
set_client.call(set_request,set_response);
break;
case 'z':
joint_values[2] -= delta_d;
set_request.joint_names.push_back(base_name+"_z_joint");
set_request.joint_values.push_back(joint_values[2]);
set_client.call(set_request,set_response);
break;
case 'Z':
joint_values[2] += delta_d;
set_request.joint_names.push_back(base_name+"_z_joint");
set_request.joint_values.push_back(joint_values[2]);
set_client.call(set_request,set_response);
break;
case 'w':
joint_values[3] -= delta_t;
set_request.joint_names.push_back(base_name+"_yaw_joint");
set_request.joint_values.push_back(joint_values[3]);
set_client.call(set_request,set_response);
break;
case 'W':
joint_values[3] += delta_t;
set_request.joint_names.push_back(base_name+"_yaw_joint");
set_request.joint_values.push_back(joint_values[3]);
set_client.call(set_request,set_response);
break;
case 'p':
joint_values[4] -= delta_t;
set_request.joint_names.push_back(base_name+"_pitch_joint");
set_request.joint_values.push_back(joint_values[4]);
set_client.call(set_request,set_response);
break;
case 'P':
joint_values[4] += delta_t;
set_request.joint_names.push_back(base_name+"_pitch_joint");
set_request.joint_values.push_back(joint_values[4]);
set_client.call(set_request,set_response);
break;
case 'r':
joint_values[5] -= delta_t;
set_request.joint_names.push_back(base_name+"_roll_joint");
set_request.joint_values.push_back(joint_values[5]);
set_client.call(set_request,set_response);
break;
case 'R':
joint_values[5] += delta_t;
set_request.joint_names.push_back(base_name+"_roll_joint");
set_request.joint_values.push_back(joint_values[5]);
set_client.call(set_request,set_response);
break;
case '-':
delta_d = delta_d*.95;
delta_t = delta_t*.95;
break;
case '+':
delta_d = delta_d*1.05;
delta_t = delta_t*1.05;
break;
case 's':
store_client.call(store_request, store_response);
break;
default:
break;
} // end switch
ros::spinOnce();
loop_rate.sleep();
}// end while ok
system ("/bin/stty cooked");
}
<|endoftext|>
|
<commit_before>// Copyright 2020 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/compiler/Dialect/HAL/Target/LLVM/LLVMTargetOptions.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Host.h"
#include "llvm/Target/TargetOptions.h"
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace HAL {
LLVMTargetOptions getDefaultLLVMTargetOptions() {
LLVMTargetOptions targetOptions;
// Host target triple.
targetOptions.targetTriple = llvm::sys::getDefaultTargetTriple();
targetOptions.targetCPU = llvm::sys::getHostCPUName().str();
{
llvm::SubtargetFeatures features;
llvm::StringMap<bool> hostFeatures;
if (llvm::sys::getHostCPUFeatures(hostFeatures)) {
for (auto &feature : hostFeatures) {
features.AddFeature(feature.first(), feature.second);
}
}
targetOptions.targetCPUFeatures = features.getString();
}
// LLVM loop optimization options.
targetOptions.pipelineTuningOptions.LoopInterleaving = true;
targetOptions.pipelineTuningOptions.LoopVectorization = true;
targetOptions.pipelineTuningOptions.LoopUnrolling = true;
// LLVM SLP Auto vectorizer.
targetOptions.pipelineTuningOptions.SLPVectorization = true;
// LLVM -O3.
// TODO(benvanik): add an option for this.
targetOptions.optLevel = llvm::PassBuilder::OptimizationLevel::O3;
targetOptions.options.FloatABIType = llvm::FloatABI::Hard;
return targetOptions;
}
LLVMTargetOptions getLLVMTargetOptionsFromFlags() {
auto llvmTargetOptions = getDefaultLLVMTargetOptions();
static llvm::cl::opt<std::string> clTargetTriple(
"iree-llvm-target-triple", llvm::cl::desc("LLVM target machine triple"),
llvm::cl::init(llvmTargetOptions.targetTriple));
static llvm::cl::opt<std::string> clTargetCPU(
"iree-llvm-target-cpu",
llvm::cl::desc(
"LLVM target machine CPU; use 'host' for your host native CPU"),
llvm::cl::init("generic"));
static llvm::cl::opt<std::string> clTargetCPUFeatures(
"iree-llvm-target-cpu-features",
llvm::cl::desc("LLVM target machine CPU features; use 'host' for your "
"host native CPU"),
llvm::cl::init(""));
static llvm::cl::opt<bool> llvmLoopInterleaving(
"iree-llvm-loop-interleaving", llvm::cl::init(false),
llvm::cl::desc("Enable LLVM loop interleaving opt"));
static llvm::cl::opt<bool> llvmLoopVectorization(
"iree-llvm-loop-vectorization", llvm::cl::init(true),
llvm::cl::desc("Enable LLVM loop vectorization opt"));
static llvm::cl::opt<bool> llvmLoopUnrolling(
"iree-llvm-loop-unrolling", llvm::cl::init(false),
llvm::cl::desc("Enable LLVM loop unrolling opt"));
static llvm::cl::opt<bool> llvmSLPVectorization(
"iree-llvm-slp-vectorization", llvm::cl::init(false),
llvm::cl::desc("Enable LLVM SLP Vectorization opt"));
llvmTargetOptions.targetTriple = clTargetTriple;
if (clTargetCPU != "host") {
llvmTargetOptions.targetCPU = clTargetCPU;
}
if (clTargetCPUFeatures != "host") {
llvmTargetOptions.targetCPUFeatures = clTargetCPUFeatures;
}
// LLVM opt options.
llvmTargetOptions.pipelineTuningOptions.LoopInterleaving =
llvmLoopInterleaving;
llvmTargetOptions.pipelineTuningOptions.LoopVectorization =
llvmLoopVectorization;
llvmTargetOptions.pipelineTuningOptions.LoopUnrolling = llvmLoopUnrolling;
llvmTargetOptions.pipelineTuningOptions.SLPVectorization =
llvmSLPVectorization;
static llvm::cl::opt<SanitizerKind> clSanitizerKind(
"iree-llvm-sanitize", llvm::cl::desc("Apply LLVM sanitize feature"),
llvm::cl::init(SanitizerKind::kNone),
llvm::cl::values(clEnumValN(SanitizerKind::kAddress, "address",
"Address sanitizer support")));
llvmTargetOptions.sanitizerKind = clSanitizerKind;
static llvm::cl::opt<std::string> clTargetABI(
"iree-llvm-target-abi",
llvm::cl::desc("LLVM target machine ABI; specify for -mabi"),
llvm::cl::init(""));
llvmTargetOptions.options.MCOptions.ABIName = clTargetABI;
static llvm::cl::opt<llvm::FloatABI::ABIType> clTargetFloatABI(
"iree-llvm-target-float-abi",
llvm::cl::desc("LLVM target codegen enables soft float abi e.g "
"-mfloat-abi=softfp"),
llvm::cl::init(llvmTargetOptions.options.FloatABIType),
llvm::cl::values(
clEnumValN(llvm::FloatABI::Default, "default", "Default (softfp)"),
clEnumValN(llvm::FloatABI::Soft, "soft",
"Software floating-point emulation"),
clEnumValN(llvm::FloatABI::Hard, "hard",
"Hardware floating-point instructions")));
llvmTargetOptions.options.FloatABIType = clTargetFloatABI;
static llvm::cl::opt<bool> clDebugSymbols(
"iree-llvm-debug-symbols",
llvm::cl::desc("Generate and embed debug information (DWARF, PDB, etc)"),
llvm::cl::init(llvmTargetOptions.debugSymbols));
llvmTargetOptions.debugSymbols = clDebugSymbols;
static llvm::cl::opt<std::string> clLinkerPath(
"iree-llvm-linker-path",
llvm::cl::desc("Tool used to link shared libraries produced by IREE."),
llvm::cl::init(""));
llvmTargetOptions.linkerPath = clLinkerPath;
static llvm::cl::opt<std::string> clEmbeddedLinkerPath(
"iree-llvm-embedded-linker-path",
llvm::cl::desc("Tool used to link embedded ELFs produced by IREE (for "
"-iree-llvm-link-embedded)."),
llvm::cl::init("ld.lld"));
llvmTargetOptions.embeddedLinkerPath = clEmbeddedLinkerPath;
static llvm::cl::opt<bool> clLinkEmbedded(
"iree-llvm-link-embedded",
llvm::cl::desc("Links binaries into a platform-agnostic ELF to be loaded "
"by the embedded IREE ELF loader"),
llvm::cl::init(llvmTargetOptions.linkEmbedded));
llvmTargetOptions.linkEmbedded = clLinkEmbedded;
static llvm::cl::opt<bool> clLinkStatic(
"iree-llvm-link-static",
llvm::cl::desc(
"Links system libraries into binaries statically to isolate them "
"from platform dependencies needed at runtime"),
llvm::cl::init(llvmTargetOptions.linkStatic));
llvmTargetOptions.linkStatic = clLinkStatic;
static llvm::cl::opt<bool> clKeepLinkerArtifacts(
"iree-llvm-keep-linker-artifacts",
llvm::cl::desc("Keep LLVM linker target artifacts (.so/.dll/etc)"),
llvm::cl::init(llvmTargetOptions.keepLinkerArtifacts));
llvmTargetOptions.keepLinkerArtifacts = clKeepLinkerArtifacts;
static llvm::cl::opt<std::string> clStaticLibraryOutputPath(
"iree-llvm-static-library-output-path",
llvm::cl::desc(
"Path to output static object (EX: '/path/to/static-library.o'). "
"This will produce the static library at the specified path along "
"with a similarly named '.h' file for static linking."),
llvm::cl::init(llvmTargetOptions.staticLibraryOutput));
llvmTargetOptions.staticLibraryOutput = clStaticLibraryOutputPath;
return llvmTargetOptions;
}
} // namespace HAL
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
<commit_msg>Adding -iree-llvm-list-targets to list registered targets. (#6286)<commit_after>// Copyright 2020 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/compiler/Dialect/HAL/Target/LLVM/LLVMTargetOptions.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Target/TargetOptions.h"
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace HAL {
LLVMTargetOptions getDefaultLLVMTargetOptions() {
LLVMTargetOptions targetOptions;
// Host target triple.
targetOptions.targetTriple = llvm::sys::getDefaultTargetTriple();
targetOptions.targetCPU = llvm::sys::getHostCPUName().str();
{
llvm::SubtargetFeatures features;
llvm::StringMap<bool> hostFeatures;
if (llvm::sys::getHostCPUFeatures(hostFeatures)) {
for (auto &feature : hostFeatures) {
features.AddFeature(feature.first(), feature.second);
}
}
targetOptions.targetCPUFeatures = features.getString();
}
// LLVM loop optimization options.
targetOptions.pipelineTuningOptions.LoopInterleaving = true;
targetOptions.pipelineTuningOptions.LoopVectorization = true;
targetOptions.pipelineTuningOptions.LoopUnrolling = true;
// LLVM SLP Auto vectorizer.
targetOptions.pipelineTuningOptions.SLPVectorization = true;
// LLVM -O3.
// TODO(benvanik): add an option for this.
targetOptions.optLevel = llvm::PassBuilder::OptimizationLevel::O3;
targetOptions.options.FloatABIType = llvm::FloatABI::Hard;
return targetOptions;
}
LLVMTargetOptions getLLVMTargetOptionsFromFlags() {
auto llvmTargetOptions = getDefaultLLVMTargetOptions();
static llvm::cl::opt<std::string> clTargetTriple(
"iree-llvm-target-triple", llvm::cl::desc("LLVM target machine triple"),
llvm::cl::init(llvmTargetOptions.targetTriple));
static llvm::cl::opt<std::string> clTargetCPU(
"iree-llvm-target-cpu",
llvm::cl::desc(
"LLVM target machine CPU; use 'host' for your host native CPU"),
llvm::cl::init("generic"));
static llvm::cl::opt<std::string> clTargetCPUFeatures(
"iree-llvm-target-cpu-features",
llvm::cl::desc("LLVM target machine CPU features; use 'host' for your "
"host native CPU"),
llvm::cl::init(""));
static llvm::cl::opt<bool> llvmLoopInterleaving(
"iree-llvm-loop-interleaving", llvm::cl::init(false),
llvm::cl::desc("Enable LLVM loop interleaving opt"));
static llvm::cl::opt<bool> llvmLoopVectorization(
"iree-llvm-loop-vectorization", llvm::cl::init(true),
llvm::cl::desc("Enable LLVM loop vectorization opt"));
static llvm::cl::opt<bool> llvmLoopUnrolling(
"iree-llvm-loop-unrolling", llvm::cl::init(false),
llvm::cl::desc("Enable LLVM loop unrolling opt"));
static llvm::cl::opt<bool> llvmSLPVectorization(
"iree-llvm-slp-vectorization", llvm::cl::init(false),
llvm::cl::desc("Enable LLVM SLP Vectorization opt"));
llvmTargetOptions.targetTriple = clTargetTriple;
if (clTargetCPU != "host") {
llvmTargetOptions.targetCPU = clTargetCPU;
}
if (clTargetCPUFeatures != "host") {
llvmTargetOptions.targetCPUFeatures = clTargetCPUFeatures;
}
// LLVM opt options.
llvmTargetOptions.pipelineTuningOptions.LoopInterleaving =
llvmLoopInterleaving;
llvmTargetOptions.pipelineTuningOptions.LoopVectorization =
llvmLoopVectorization;
llvmTargetOptions.pipelineTuningOptions.LoopUnrolling = llvmLoopUnrolling;
llvmTargetOptions.pipelineTuningOptions.SLPVectorization =
llvmSLPVectorization;
static llvm::cl::opt<SanitizerKind> clSanitizerKind(
"iree-llvm-sanitize", llvm::cl::desc("Apply LLVM sanitize feature"),
llvm::cl::init(SanitizerKind::kNone),
llvm::cl::values(clEnumValN(SanitizerKind::kAddress, "address",
"Address sanitizer support")));
llvmTargetOptions.sanitizerKind = clSanitizerKind;
static llvm::cl::opt<std::string> clTargetABI(
"iree-llvm-target-abi",
llvm::cl::desc("LLVM target machine ABI; specify for -mabi"),
llvm::cl::init(""));
llvmTargetOptions.options.MCOptions.ABIName = clTargetABI;
static llvm::cl::opt<llvm::FloatABI::ABIType> clTargetFloatABI(
"iree-llvm-target-float-abi",
llvm::cl::desc("LLVM target codegen enables soft float abi e.g "
"-mfloat-abi=softfp"),
llvm::cl::init(llvmTargetOptions.options.FloatABIType),
llvm::cl::values(
clEnumValN(llvm::FloatABI::Default, "default", "Default (softfp)"),
clEnumValN(llvm::FloatABI::Soft, "soft",
"Software floating-point emulation"),
clEnumValN(llvm::FloatABI::Hard, "hard",
"Hardware floating-point instructions")));
llvmTargetOptions.options.FloatABIType = clTargetFloatABI;
static llvm::cl::opt<bool> clDebugSymbols(
"iree-llvm-debug-symbols",
llvm::cl::desc("Generate and embed debug information (DWARF, PDB, etc)"),
llvm::cl::init(llvmTargetOptions.debugSymbols));
llvmTargetOptions.debugSymbols = clDebugSymbols;
static llvm::cl::opt<std::string> clLinkerPath(
"iree-llvm-linker-path",
llvm::cl::desc("Tool used to link shared libraries produced by IREE."),
llvm::cl::init(""));
llvmTargetOptions.linkerPath = clLinkerPath;
static llvm::cl::opt<std::string> clEmbeddedLinkerPath(
"iree-llvm-embedded-linker-path",
llvm::cl::desc("Tool used to link embedded ELFs produced by IREE (for "
"-iree-llvm-link-embedded)."),
llvm::cl::init("ld.lld"));
llvmTargetOptions.embeddedLinkerPath = clEmbeddedLinkerPath;
static llvm::cl::opt<bool> clLinkEmbedded(
"iree-llvm-link-embedded",
llvm::cl::desc("Links binaries into a platform-agnostic ELF to be loaded "
"by the embedded IREE ELF loader"),
llvm::cl::init(llvmTargetOptions.linkEmbedded));
llvmTargetOptions.linkEmbedded = clLinkEmbedded;
static llvm::cl::opt<bool> clLinkStatic(
"iree-llvm-link-static",
llvm::cl::desc(
"Links system libraries into binaries statically to isolate them "
"from platform dependencies needed at runtime"),
llvm::cl::init(llvmTargetOptions.linkStatic));
llvmTargetOptions.linkStatic = clLinkStatic;
static llvm::cl::opt<bool> clKeepLinkerArtifacts(
"iree-llvm-keep-linker-artifacts",
llvm::cl::desc("Keep LLVM linker target artifacts (.so/.dll/etc)"),
llvm::cl::init(llvmTargetOptions.keepLinkerArtifacts));
llvmTargetOptions.keepLinkerArtifacts = clKeepLinkerArtifacts;
static llvm::cl::opt<std::string> clStaticLibraryOutputPath(
"iree-llvm-static-library-output-path",
llvm::cl::desc(
"Path to output static object (EX: '/path/to/static-library.o'). "
"This will produce the static library at the specified path along "
"with a similarly named '.h' file for static linking."),
llvm::cl::init(llvmTargetOptions.staticLibraryOutput));
llvmTargetOptions.staticLibraryOutput = clStaticLibraryOutputPath;
static llvm::cl::opt<bool> clListTargets(
"iree-llvm-list-targets",
llvm::cl::desc("Lists all registered targets that the LLVM backend can "
"generate code for."),
llvm::cl::init(false));
if (clListTargets) {
llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
exit(0);
}
return llvmTargetOptions;
}
} // namespace HAL
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
<|endoftext|>
|
<commit_before><commit_msg>Output time of ICC creation<commit_after><|endoftext|>
|
<commit_before>// coding: utf-8
/* Copyright (c) 2014, Roboterclub Aachen e. V.
* All Rights Reserved.
*
* The file is part of the xpcc library and is released under the 3-clause BSD
* license. See the file `LICENSE` for the full license governing this code.
*/
// ----------------------------------------------------------------------------
#ifndef XPCC__NRF24_PHY_HPP
# error "Don't include this file directly, use 'nrf24_phy.hpp' instead!"
#endif
#include "nrf24_phy.hpp"
#include "nrf24_definitions.hpp"
template <typename Spi, typename Csn, typename Ce>
uint8_t xpcc::Nrf24Phy<Spi, Csn, Ce>::status;
template <typename Spi, typename Csn, typename Ce>
uint8_t xpcc::Nrf24Phy<Spi, Csn, Ce>::payload_len;
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::writeCommandNoData(Command_t cmd)
{
Csn::reset();
status = Spi::transferBlocking(cmd.value);
Csn::set();
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
uint8_t
xpcc::Nrf24Phy<Spi, Csn, Ce>::writeCommandSingleData(Command_t cmd, uint8_t data)
{
Csn::reset();
status = Spi::transferBlocking(cmd.value);
uint8_t ret = Spi::transferBlocking(data);
Csn::set();
return ret;
}
// --------------------------------------------------------------------------------------------------------------------
/*
* TODO: maybe optimize this
*/
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::writeCommandMultiData(Command_t cmd, uint8_t* argv, uint8_t* retv, uint8_t argc)
{
Csn::reset();
status = Spi::transferBlocking(cmd.value);
uint8_t i;
for(i = 0; i < argc; i++)
{
uint8_t data;
uint8_t arg = 0;
if(argv != nullptr)
{
arg = argv[i];
}
data = Spi::transferBlocking(arg);
if(retv != nullptr)
{
retv[i] = data;
}
}
Csn::set();
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
uint8_t
xpcc::Nrf24Phy<Spi, Csn, Ce>::readRegister(NrfRegister_t reg)
{
Command_t cmd = Command::R_REGISTER;
cmd.value |= reg.value;
return writeCommandSingleData(cmd, 0x00);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::writeRegister(NrfRegister_t reg, uint8_t data)
{
Command_t cmd = Command::W_REGISTER;
cmd.value |= reg.value;
writeCommandSingleData(cmd, data);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::setBits(NrfRegister_t reg, Flags_t flags)
{
uint8_t old = readRegister(reg);
writeRegister(reg, old | flags.value);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::clearBits(NrfRegister_t reg, Flags_t flags)
{
uint8_t old = readRegister(reg);
writeRegister(reg, old & ~flags.value);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::flushTxFifo()
{
writeCommandNoData(Command::FLUSH_TX);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::flushRxFifo()
{
writeCommandNoData(Command::FLUSH_RX);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
uint8_t
xpcc::Nrf24Phy<Spi, Csn, Ce>::readRxPayloadWidth()
{
return writeCommandSingleData(Command::R_RX_PL_WID, 0x00);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
uint8_t
xpcc::Nrf24Phy<Spi, Csn, Ce>::readRxPayload(uint8_t* buffer)
{
uint8_t cur_pl_len = payload_len;
// cope with dynamic payload
if(cur_pl_len == 0)
{
cur_pl_len = readRxPayloadWidth();
}
writeCommandMultiData(Command::R_RX_PAYLOAD, nullptr, buffer, cur_pl_len);
return cur_pl_len;
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::writeTxPayload(uint8_t* buffer, uint8_t len)
{
if(len > payload_len)
return;
writeCommandMultiData(Command::W_TX_PAYLOAD, buffer, nullptr, len);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::writeTxPayloadNoAck(uint8_t* buffer, uint8_t len)
{
if(len > payload_len)
return;
writeCommandMultiData(Command::W_TX_PAYLOAD_NOACK, buffer, nullptr, len);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::writeAckPayload(Pipe_t pipe, uint8_t* buffer, uint8_t len)
{
if(len > payload_len)
return;
Command_t cmd = Command::W_ACK_PAYLOAD;
cmd.value |= pipe.value;
writeCommandMultiData(cmd, buffer, nullptr, len);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::reuseTxPayload()
{
writeCommandNoData(Command::REUSE_TX_PL);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
uint8_t
xpcc::Nrf24Phy<Spi, Csn, Ce>::readStatus()
{
writeCommandNoData(Command::NOP);
return status;
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
uint8_t
xpcc::Nrf24Phy<Spi, Csn, Ce>::readFifoStatus()
{
return readRegister(NrfRegister::FIFO_STATUS);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::setRxAddress(Pipe_t pipe, uint64_t address)
{
Command_t cmd = Command::W_REGISTER;
cmd.value |= static_cast<uint8_t>(NrfRegister::RX_ADDR_P0);
// add pipe value so register will be RX_ADDR_Px if pipe is 'x'
cmd.value += pipe.value;
if(pipe.value <= 1)
{
/* register RX_ADDR_P0|1 are 40 bit wide */
uint8_t addr[address_size];
/* assemble address */
for(uint8_t i = 0; i < address_size; i++)
{
addr[i] = address & 0xff;
address >>= 8;
}
writeCommandMultiData(cmd, addr, nullptr, address_size);
} else if(pipe.value < rx_pipe_count)
{
NrfRegister_t reg = NrfRegister::RX_ADDR_P0;
reg.value += pipe.value;
/* register RX_ADDR_P2-5 are just 8 bit wide */
writeRegister(reg, static_cast<uint8_t>(address & 0xff));
}
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::setTxAddress(uint64_t address)
{
uint8_t addr[address_size];
for(uint8_t i = 0; i < address_size; i++)
{
addr[i] = address & 0xff;
address >>= 8;
}
Command_t cmd = Command::W_REGISTER;
cmd.value |= static_cast<uint8_t>(NrfRegister::TX_ADDR);
writeCommandMultiData(cmd, addr, nullptr, address_size);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
uint64_t
xpcc::Nrf24Phy<Spi, Csn, Ce>::getRxAddress(Pipe_t pipe)
{
if(pipe.value <= 1)
{
/* register RX_ADDR_P0|1 are 40 bit wide, so they need special treatment */
Command_t cmd = Command::R_REGISTER;
cmd.value |= static_cast<uint8_t>(NrfRegister::RX_ADDR_P0);
// add pipe value so register will be RX_ADDR_Px if pipe is 'x'
cmd.value += pipe.value;
uint8_t addr[address_size];
uint64_t address = 0;
writeCommandMultiData(cmd, nullptr, addr, address_size);
uint8_t i = address_size;
do
{
i--;
address <<= 8;
address |= addr[i];
} while(i != 0);
return address;
} else if(pipe.value <= address_size)
{
NrfRegister_t reg = NrfRegister::RX_ADDR_P0;
reg.value += pipe.value;
/* register RX_ADDR_P2-5 are just 8 bit wide */
return readRegister(reg);
}
/* Returning 0 as error indicator is totally okay because this address is not allowed by the datasheet anyway */
return 0;
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
uint64_t
xpcc::Nrf24Phy<Spi, Csn, Ce>::getTxAddress()
{
uint8_t addr[address_size];
uint64_t address = 0;
Command_t cmd = Command::R_REGISTER;
cmd.value |= static_cast<uint8_t>(NrfRegister::TX_ADDR);
writeCommandMultiData(cmd, nullptr, addr, address_size);
uint8_t i = address_size;
do
{
i--;
address <<= 8;
address |= addr[i];
} while(i != 0);
return address;
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::pulseCe()
{
Ce::set();
xpcc::delayMicroseconds(10);
Ce::reset();
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::setCe()
{
Ce::set();
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::resetCe()
{
Ce::reset();
}
<commit_msg>nrf24-phy: change implementation of pulseCe() to higher delay and Ce::toggle()<commit_after>// coding: utf-8
/* Copyright (c) 2014, Roboterclub Aachen e. V.
* All Rights Reserved.
*
* The file is part of the xpcc library and is released under the 3-clause BSD
* license. See the file `LICENSE` for the full license governing this code.
*/
// ----------------------------------------------------------------------------
#ifndef XPCC__NRF24_PHY_HPP
# error "Don't include this file directly, use 'nrf24_phy.hpp' instead!"
#endif
#include "nrf24_phy.hpp"
#include "nrf24_definitions.hpp"
template <typename Spi, typename Csn, typename Ce>
uint8_t xpcc::Nrf24Phy<Spi, Csn, Ce>::status;
template <typename Spi, typename Csn, typename Ce>
uint8_t xpcc::Nrf24Phy<Spi, Csn, Ce>::payload_len;
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::writeCommandNoData(Command_t cmd)
{
Csn::reset();
status = Spi::transferBlocking(cmd.value);
Csn::set();
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
uint8_t
xpcc::Nrf24Phy<Spi, Csn, Ce>::writeCommandSingleData(Command_t cmd, uint8_t data)
{
Csn::reset();
status = Spi::transferBlocking(cmd.value);
uint8_t ret = Spi::transferBlocking(data);
Csn::set();
return ret;
}
// --------------------------------------------------------------------------------------------------------------------
/*
* TODO: maybe optimize this
*/
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::writeCommandMultiData(Command_t cmd, uint8_t* argv, uint8_t* retv, uint8_t argc)
{
Csn::reset();
status = Spi::transferBlocking(cmd.value);
uint8_t i;
for(i = 0; i < argc; i++)
{
uint8_t data;
uint8_t arg = 0;
if(argv != nullptr)
{
arg = argv[i];
}
data = Spi::transferBlocking(arg);
if(retv != nullptr)
{
retv[i] = data;
}
}
Csn::set();
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
uint8_t
xpcc::Nrf24Phy<Spi, Csn, Ce>::readRegister(NrfRegister_t reg)
{
Command_t cmd = Command::R_REGISTER;
cmd.value |= reg.value;
return writeCommandSingleData(cmd, 0x00);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::writeRegister(NrfRegister_t reg, uint8_t data)
{
Command_t cmd = Command::W_REGISTER;
cmd.value |= reg.value;
writeCommandSingleData(cmd, data);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::setBits(NrfRegister_t reg, Flags_t flags)
{
uint8_t old = readRegister(reg);
writeRegister(reg, old | flags.value);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::clearBits(NrfRegister_t reg, Flags_t flags)
{
uint8_t old = readRegister(reg);
writeRegister(reg, old & ~flags.value);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::flushTxFifo()
{
writeCommandNoData(Command::FLUSH_TX);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::flushRxFifo()
{
writeCommandNoData(Command::FLUSH_RX);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
uint8_t
xpcc::Nrf24Phy<Spi, Csn, Ce>::readRxPayloadWidth()
{
return writeCommandSingleData(Command::R_RX_PL_WID, 0x00);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
uint8_t
xpcc::Nrf24Phy<Spi, Csn, Ce>::readRxPayload(uint8_t* buffer)
{
uint8_t cur_pl_len = payload_len;
// cope with dynamic payload
if(cur_pl_len == 0)
{
cur_pl_len = readRxPayloadWidth();
}
writeCommandMultiData(Command::R_RX_PAYLOAD, nullptr, buffer, cur_pl_len);
return cur_pl_len;
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::writeTxPayload(uint8_t* buffer, uint8_t len)
{
if(len > payload_len)
return;
writeCommandMultiData(Command::W_TX_PAYLOAD, buffer, nullptr, len);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::writeTxPayloadNoAck(uint8_t* buffer, uint8_t len)
{
if(len > payload_len)
return;
writeCommandMultiData(Command::W_TX_PAYLOAD_NOACK, buffer, nullptr, len);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::writeAckPayload(Pipe_t pipe, uint8_t* buffer, uint8_t len)
{
if(len > payload_len)
return;
Command_t cmd = Command::W_ACK_PAYLOAD;
cmd.value |= pipe.value;
writeCommandMultiData(cmd, buffer, nullptr, len);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::reuseTxPayload()
{
writeCommandNoData(Command::REUSE_TX_PL);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
uint8_t
xpcc::Nrf24Phy<Spi, Csn, Ce>::readStatus()
{
writeCommandNoData(Command::NOP);
return status;
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
uint8_t
xpcc::Nrf24Phy<Spi, Csn, Ce>::readFifoStatus()
{
return readRegister(NrfRegister::FIFO_STATUS);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::setRxAddress(Pipe_t pipe, uint64_t address)
{
Command_t cmd = Command::W_REGISTER;
cmd.value |= static_cast<uint8_t>(NrfRegister::RX_ADDR_P0);
// add pipe value so register will be RX_ADDR_Px if pipe is 'x'
cmd.value += pipe.value;
if(pipe.value <= 1)
{
/* register RX_ADDR_P0|1 are 40 bit wide */
uint8_t addr[address_size];
/* assemble address */
for(uint8_t i = 0; i < address_size; i++)
{
addr[i] = address & 0xff;
address >>= 8;
}
writeCommandMultiData(cmd, addr, nullptr, address_size);
} else if(pipe.value < rx_pipe_count)
{
NrfRegister_t reg = NrfRegister::RX_ADDR_P0;
reg.value += pipe.value;
/* register RX_ADDR_P2-5 are just 8 bit wide */
writeRegister(reg, static_cast<uint8_t>(address & 0xff));
}
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::setTxAddress(uint64_t address)
{
uint8_t addr[address_size];
for(uint8_t i = 0; i < address_size; i++)
{
addr[i] = address & 0xff;
address >>= 8;
}
Command_t cmd = Command::W_REGISTER;
cmd.value |= static_cast<uint8_t>(NrfRegister::TX_ADDR);
writeCommandMultiData(cmd, addr, nullptr, address_size);
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
uint64_t
xpcc::Nrf24Phy<Spi, Csn, Ce>::getRxAddress(Pipe_t pipe)
{
if(pipe.value <= 1)
{
/* register RX_ADDR_P0|1 are 40 bit wide, so they need special treatment */
Command_t cmd = Command::R_REGISTER;
cmd.value |= static_cast<uint8_t>(NrfRegister::RX_ADDR_P0);
// add pipe value so register will be RX_ADDR_Px if pipe is 'x'
cmd.value += pipe.value;
uint8_t addr[address_size];
uint64_t address = 0;
writeCommandMultiData(cmd, nullptr, addr, address_size);
uint8_t i = address_size;
do
{
i--;
address <<= 8;
address |= addr[i];
} while(i != 0);
return address;
} else if(pipe.value <= address_size)
{
NrfRegister_t reg = NrfRegister::RX_ADDR_P0;
reg.value += pipe.value;
/* register RX_ADDR_P2-5 are just 8 bit wide */
return readRegister(reg);
}
/* Returning 0 as error indicator is totally okay because this address is not allowed by the datasheet anyway */
return 0;
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
uint64_t
xpcc::Nrf24Phy<Spi, Csn, Ce>::getTxAddress()
{
uint8_t addr[address_size];
uint64_t address = 0;
Command_t cmd = Command::R_REGISTER;
cmd.value |= static_cast<uint8_t>(NrfRegister::TX_ADDR);
writeCommandMultiData(cmd, nullptr, addr, address_size);
uint8_t i = address_size;
do
{
i--;
address <<= 8;
address |= addr[i];
} while(i != 0);
return address;
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::pulseCe()
{
Ce::toggle();
// delay might not be precise enough
xpcc::delayMicroseconds(15);
Ce::toggle();
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::setCe()
{
Ce::set();
}
// --------------------------------------------------------------------------------------------------------------------
template<typename Spi, typename Csn, typename Ce>
void
xpcc::Nrf24Phy<Spi, Csn, Ce>::resetCe()
{
Ce::reset();
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2007-2020 CM4all GmbH
* 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.
*/
#include "TempListener.hxx"
#include "net/UniqueSocketDescriptor.hxx"
#include "system/Error.hxx"
#include <sys/stat.h>
static void
make_child_socket_path(struct sockaddr_un *address)
{
strcpy(address->sun_path, "/tmp/cm4all-beng-proxy-socket-XXXXXX");
if (*mktemp(address->sun_path) == 0)
throw MakeErrno("mktemp() failed");
address->sun_family = AF_LOCAL;
}
TempListener::~TempListener() noexcept
{
if (IsDefined())
unlink(address.sun_path);
}
UniqueSocketDescriptor
TempListener::Create(int socket_type, int backlog)
{
make_child_socket_path(&address);
unlink(address.sun_path);
UniqueSocketDescriptor fd;
if (!fd.Create(AF_LOCAL, socket_type, 0))
throw MakeErrno("failed to create local socket");
/* allow only beng-proxy to connect to it */
fchmod(fd.Get(), 0600);
if (!fd.Bind(GetAddress()))
throw MakeErrno("failed to bind local socket");
if (!fd.Listen(backlog))
throw MakeErrno("failed to listen on local socket");
return fd;
}
UniqueSocketDescriptor
TempListener::Connect() const
{
UniqueSocketDescriptor fd;
if (!fd.CreateNonBlock(AF_LOCAL, SOCK_STREAM, 0))
throw MakeErrno("Failed to create socket");
if (!fd.Connect(GetAddress())) {
int e = errno;
fd.Close();
throw MakeErrno(e, "Failed to connect");
}
return fd;
}
<commit_msg>net/TempListener: use RUNTIME_DIRECTORY<commit_after>/*
* Copyright 2007-2020 CM4all GmbH
* 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.
*/
#include "TempListener.hxx"
#include "net/UniqueSocketDescriptor.hxx"
#include "system/Error.hxx"
#include <stdlib.h>
#include <sys/stat.h>
static void
make_child_socket_path(struct sockaddr_un *address)
{
const char *runtime_directory = getenv("RUNTIME_DIRECTORY");
if (runtime_directory != nullptr)
sprintf(address->sun_path, "%s/temp-socket-XXXXXX",
runtime_directory);
else
strcpy(address->sun_path, "/tmp/cm4all-beng-proxy-socket-XXXXXX");
if (*mktemp(address->sun_path) == 0)
throw MakeErrno("mktemp() failed");
address->sun_family = AF_LOCAL;
}
TempListener::~TempListener() noexcept
{
if (IsDefined())
unlink(address.sun_path);
}
UniqueSocketDescriptor
TempListener::Create(int socket_type, int backlog)
{
make_child_socket_path(&address);
unlink(address.sun_path);
UniqueSocketDescriptor fd;
if (!fd.Create(AF_LOCAL, socket_type, 0))
throw MakeErrno("failed to create local socket");
/* allow only beng-proxy to connect to it */
fchmod(fd.Get(), 0600);
if (!fd.Bind(GetAddress()))
throw MakeErrno("failed to bind local socket");
if (!fd.Listen(backlog))
throw MakeErrno("failed to listen on local socket");
return fd;
}
UniqueSocketDescriptor
TempListener::Connect() const
{
UniqueSocketDescriptor fd;
if (!fd.CreateNonBlock(AF_LOCAL, SOCK_STREAM, 0))
throw MakeErrno("Failed to create socket");
if (!fd.Connect(GetAddress())) {
int e = errno;
fd.Close();
throw MakeErrno(e, "Failed to connect");
}
return fd;
}
<|endoftext|>
|
<commit_before>//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include "ngraph/op/gather.hpp"
#include "ngraph/op/constant.hpp"
#include "ngraph/runtime/host_tensor.hpp"
#include "ngraph/runtime/reference/gather.hpp"
#include "ngraph/shape.hpp"
#include <limits>
using namespace std;
using namespace ngraph;
static const int PARAMS = 0;
static const int INDICES = 1;
static const int AXIS = 2;
constexpr NodeTypeInfo op::v0::Gather::type_info;
op::v0::Gather::Gather(const Output<Node>& params, const Output<Node>& indices, size_t axis)
: Op({params, indices})
, m_axis(axis)
{
constructor_validate_and_infer_types();
}
shared_ptr<Node> op::v0::Gather::clone_with_new_inputs(const OutputVector& new_args) const
{
check_new_args_count(this, new_args);
return make_shared<v0::Gather>(new_args.at(PARAMS), new_args.at(INDICES), m_axis);
}
void op::v0::Gather::validate_and_infer_types()
{
element::Type result_et = get_input_element_type(PARAMS);
element::Type indices_et = get_input_element_type(INDICES);
const PartialShape& params_shape = get_input_partial_shape(PARAMS);
const PartialShape& indices_shape = get_input_partial_shape(INDICES);
NODE_VALIDATION_CHECK(this,
indices_et == element::i32 || indices_et == element::i64,
"Indices element type must be i64 or i32");
// params rank must be at least (axis + 1)
// indices value must be in range [0, params.shape[axis]).
// output rank is rank(params) + rank(indices) - 1
NODE_VALIDATION_CHECK(this,
params_shape.rank().is_dynamic() ||
params_shape.rank().get_length() > static_cast<size_t>(m_axis),
"params rank is expected to be at least axis + 1");
PartialShape result_shape;
if (params_shape.rank().is_static() && indices_shape.rank().is_static())
{
std::vector<Dimension> result_dims(params_shape.rank().get_length() +
indices_shape.rank().get_length() - 1);
size_t i = 0;
for (; i < static_cast<size_t>(m_axis); i++)
{
result_dims[i] = params_shape[i];
}
for (size_t j = 0; j < indices_shape.rank().get_length(); i++, j++)
{
result_dims[i] = indices_shape[j];
}
for (size_t j = static_cast<size_t>(m_axis) + 1; j < params_shape.rank().get_length();
i++, j++)
{
result_dims[i] = params_shape[j];
}
result_shape = PartialShape(result_dims);
}
else
{
result_shape = PartialShape::dynamic();
}
set_output_type(0, result_et, result_shape);
}
void op::v0::Gather::generate_adjoints(autodiff::Adjoints& /* adjoints */,
const OutputVector& /* deltas */)
{
throw ngraph_error("Not yet implemented");
}
constexpr NodeTypeInfo op::v1::Gather::type_info;
const int64_t op::v1::Gather::AXIS_NOT_SET_VALUE;
op::v1::Gather::Gather(const Output<Node>& params,
const Output<Node>& indices,
const Output<Node>& axes)
: Op({params, indices, axes})
{
constructor_validate_and_infer_types();
}
bool ngraph::op::v1::Gather::visit_attributes(AttributeVisitor& visitor)
{
return true;
}
void op::v1::Gather::validate_and_infer_types()
{
const auto& input_rank = get_input_partial_shape(PARAMS).rank();
const auto& axis_shape = get_input_partial_shape(AXIS);
const auto& axis_rank = axis_shape.rank();
if (axis_rank.is_static() && axis_shape.is_static())
{
const auto axis_is_scalar = axis_rank.get_length() == 0;
const auto axis_has_one_elem =
axis_rank.get_length() == 1 && axis_shape[0].get_length() == 1;
NODE_VALIDATION_CHECK(this,
axis_is_scalar || axis_has_one_elem,
"Axes input must be scalar or have 1 element (shape: ",
axis_shape,
").");
}
int64_t axis = get_axis();
if (input_rank.is_static() && axis != AXIS_NOT_SET_VALUE)
{
NODE_VALIDATION_CHECK(this,
axis < input_rank.get_length(),
"The axis must => 0 and <= input_rank (axis: ",
axis,
").");
}
element::Type result_et = get_input_element_type(PARAMS);
element::Type indices_et = get_input_element_type(INDICES);
const PartialShape& params_shape = get_input_partial_shape(PARAMS);
const PartialShape& indices_shape = get_input_partial_shape(INDICES);
PartialShape result_shape;
if (params_shape.rank().is_static() && indices_shape.rank().is_static() &&
axis != AXIS_NOT_SET_VALUE)
{
std::vector<Dimension> result_dims(params_shape.rank().get_length() +
indices_shape.rank().get_length() - 1);
uint64_t i = 0;
for (; i < axis; i++)
{
result_dims[i] = params_shape[i];
}
for (uint64_t j = 0; j < indices_shape.rank().get_length(); i++, j++)
{
result_dims[i] = indices_shape[j];
}
for (uint64_t j = axis + 1; j < params_shape.rank().get_length(); i++, j++)
{
result_dims[i] = params_shape[j];
}
result_shape = PartialShape(result_dims);
}
else
{
result_shape = PartialShape::dynamic();
}
set_output_type(0, result_et, result_shape);
}
int64_t op::v1::Gather::get_axis() const
{
int64_t axis = AXIS_NOT_SET_VALUE;
auto axes_input_node = input_value(AXIS).get_node_shared_ptr();
if (auto const_op = as_type_ptr<op::Constant>(axes_input_node))
{
axis = const_op->cast_vector<int64_t>()[0];
}
if (axis < 0)
{
const auto& input_rank = get_input_partial_shape(PARAMS).rank();
if (input_rank.is_static())
{
axis += input_rank.get_length();
}
}
return axis;
}
void op::v1::Gather::generate_adjoints(autodiff::Adjoints& /* adjoints */,
const OutputVector& /* deltas */)
{
throw ngraph_error("Not yet implemented");
}
shared_ptr<Node> op::v1::Gather::clone_with_new_inputs(const OutputVector& new_args) const
{
check_new_args_count(this, new_args);
return make_shared<v1::Gather>(new_args.at(PARAMS), new_args.at(INDICES), new_args.at(AXIS));
}
namespace
{
template <element::Type_t ET>
bool evaluate(const HostTensorPtr& arg0,
const HostTensorPtr& arg1,
const HostTensorPtr& out,
size_t axis)
{
using T = typename element_type_traits<ET>::value_type;
Shape params_shape = arg0->get_shape();
Shape indices_shape = arg1->get_shape();
Shape out_shape(params_shape.size() + indices_shape.size() - 1);
uint64_t i = 0;
for (; i < axis; i++)
{
out_shape[i] = params_shape[i];
}
for (uint64_t j = 0; j < indices_shape.size(); i++, j++)
{
out_shape[i] = indices_shape[j];
}
for (uint64_t j = axis + 1; j < params_shape.size(); i++, j++)
{
out_shape[i] = params_shape[j];
}
out->set_shape(out_shape);
if (arg1->get_element_type() == element::i64)
{
runtime::reference::gather<T, int64_t>(arg0->get_data_ptr<ET>(),
arg1->get_data_ptr<int64_t>(),
out->get_data_ptr<ET>(),
arg0->get_shape(),
arg1->get_shape(),
out->get_shape(),
axis);
}
else if (arg1->get_element_type() == element::i32)
{
runtime::reference::gather<T, int32_t>(arg0->get_data_ptr<ET>(),
arg1->get_data_ptr<int32_t>(),
out->get_data_ptr<ET>(),
arg0->get_shape(),
arg1->get_shape(),
out->get_shape(),
axis);
}
else
{
throw ngraph_error("Unexpected type");
}
return true;
}
bool evaluate_gather(const HostTensorPtr& arg0,
const HostTensorPtr& arg1,
const HostTensorPtr& out,
size_t axis)
{
bool rc = true;
switch (out->get_element_type())
{
TYPE_CASE(i8)(arg0, arg1, out, axis);
break;
TYPE_CASE(i16)(arg0, arg1, out, axis);
break;
TYPE_CASE(i32)(arg0, arg1, out, axis);
break;
TYPE_CASE(i64)(arg0, arg1, out, axis);
break;
TYPE_CASE(u8)(arg0, arg1, out, axis);
break;
TYPE_CASE(u16)(arg0, arg1, out, axis);
break;
TYPE_CASE(u32)(arg0, arg1, out, axis);
break;
TYPE_CASE(u64)(arg0, arg1, out, axis);
break;
TYPE_CASE(f32)(arg0, arg1, out, axis);
break;
TYPE_CASE(f64)(arg0, arg1, out, axis);
break;
default: rc = false; break;
}
return rc;
}
}
bool op::v0::Gather::evaluate(const HostTensorVector& outputs, const HostTensorVector& inputs)
{
return evaluate_gather(inputs[0], inputs[1], outputs[0], get_axis());
}
bool op::v1::Gather::evaluate(const HostTensorVector& outputs, const HostTensorVector& inputs)
{
auto axis = 0;
switch (inputs[2]->get_element_type())
{
case element::Type_t::i8: axis = inputs[2]->get_data_ptr<element::Type_t::i8>()[0]; break;
case element::Type_t::i16: axis = inputs[2]->get_data_ptr<element::Type_t::i16>()[0]; break;
case element::Type_t::i32: axis = inputs[2]->get_data_ptr<element::Type_t::i32>()[0]; break;
case element::Type_t::i64: axis = inputs[2]->get_data_ptr<element::Type_t::i64>()[0]; break;
case element::Type_t::u8: axis = inputs[2]->get_data_ptr<element::Type_t::u8>()[0]; break;
case element::Type_t::u16: axis = inputs[2]->get_data_ptr<element::Type_t::u16>()[0]; break;
case element::Type_t::u32: axis = inputs[2]->get_data_ptr<element::Type_t::u32>()[0]; break;
case element::Type_t::u64: axis = inputs[2]->get_data_ptr<element::Type_t::u64>()[0]; break;
default: throw ngraph_error("axis element type is not integral data type");
}
if (axis < 0)
{
const auto& input_rank = get_input_partial_shape(PARAMS).rank();
if (input_rank.is_static())
{
axis += input_rank.get_length();
}
}
return evaluate_gather(inputs[0], inputs[1], outputs[0], axis);
}
<commit_msg>Change to i64<commit_after>//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include "ngraph/op/gather.hpp"
#include "ngraph/op/constant.hpp"
#include "ngraph/runtime/host_tensor.hpp"
#include "ngraph/runtime/reference/gather.hpp"
#include "ngraph/shape.hpp"
#include <limits>
using namespace std;
using namespace ngraph;
static const int PARAMS = 0;
static const int INDICES = 1;
static const int AXIS = 2;
constexpr NodeTypeInfo op::v0::Gather::type_info;
op::v0::Gather::Gather(const Output<Node>& params, const Output<Node>& indices, size_t axis)
: Op({params, indices})
, m_axis(axis)
{
constructor_validate_and_infer_types();
}
shared_ptr<Node> op::v0::Gather::clone_with_new_inputs(const OutputVector& new_args) const
{
check_new_args_count(this, new_args);
return make_shared<v0::Gather>(new_args.at(PARAMS), new_args.at(INDICES), m_axis);
}
void op::v0::Gather::validate_and_infer_types()
{
element::Type result_et = get_input_element_type(PARAMS);
element::Type indices_et = get_input_element_type(INDICES);
const PartialShape& params_shape = get_input_partial_shape(PARAMS);
const PartialShape& indices_shape = get_input_partial_shape(INDICES);
NODE_VALIDATION_CHECK(this,
indices_et == element::i32 || indices_et == element::i64,
"Indices element type must be i64 or i32");
// params rank must be at least (axis + 1)
// indices value must be in range [0, params.shape[axis]).
// output rank is rank(params) + rank(indices) - 1
NODE_VALIDATION_CHECK(this,
params_shape.rank().is_dynamic() ||
params_shape.rank().get_length() > static_cast<size_t>(m_axis),
"params rank is expected to be at least axis + 1");
PartialShape result_shape;
if (params_shape.rank().is_static() && indices_shape.rank().is_static())
{
std::vector<Dimension> result_dims(params_shape.rank().get_length() +
indices_shape.rank().get_length() - 1);
size_t i = 0;
for (; i < static_cast<size_t>(m_axis); i++)
{
result_dims[i] = params_shape[i];
}
for (size_t j = 0; j < indices_shape.rank().get_length(); i++, j++)
{
result_dims[i] = indices_shape[j];
}
for (size_t j = static_cast<size_t>(m_axis) + 1; j < params_shape.rank().get_length();
i++, j++)
{
result_dims[i] = params_shape[j];
}
result_shape = PartialShape(result_dims);
}
else
{
result_shape = PartialShape::dynamic();
}
set_output_type(0, result_et, result_shape);
}
void op::v0::Gather::generate_adjoints(autodiff::Adjoints& /* adjoints */,
const OutputVector& /* deltas */)
{
throw ngraph_error("Not yet implemented");
}
constexpr NodeTypeInfo op::v1::Gather::type_info;
const int64_t op::v1::Gather::AXIS_NOT_SET_VALUE;
op::v1::Gather::Gather(const Output<Node>& params,
const Output<Node>& indices,
const Output<Node>& axes)
: Op({params, indices, axes})
{
constructor_validate_and_infer_types();
}
bool ngraph::op::v1::Gather::visit_attributes(AttributeVisitor& visitor)
{
return true;
}
void op::v1::Gather::validate_and_infer_types()
{
const auto& input_rank = get_input_partial_shape(PARAMS).rank();
const auto& axis_shape = get_input_partial_shape(AXIS);
const auto& axis_rank = axis_shape.rank();
if (axis_rank.is_static() && axis_shape.is_static())
{
const auto axis_is_scalar = axis_rank.get_length() == 0;
const auto axis_has_one_elem =
axis_rank.get_length() == 1 && axis_shape[0].get_length() == 1;
NODE_VALIDATION_CHECK(this,
axis_is_scalar || axis_has_one_elem,
"Axes input must be scalar or have 1 element (shape: ",
axis_shape,
").");
}
int64_t axis = get_axis();
if (input_rank.is_static() && axis != AXIS_NOT_SET_VALUE)
{
NODE_VALIDATION_CHECK(this,
axis < input_rank.get_length(),
"The axis must => 0 and <= input_rank (axis: ",
axis,
").");
}
element::Type result_et = get_input_element_type(PARAMS);
element::Type indices_et = get_input_element_type(INDICES);
const PartialShape& params_shape = get_input_partial_shape(PARAMS);
const PartialShape& indices_shape = get_input_partial_shape(INDICES);
PartialShape result_shape;
if (params_shape.rank().is_static() && indices_shape.rank().is_static() &&
axis != AXIS_NOT_SET_VALUE)
{
std::vector<Dimension> result_dims(params_shape.rank().get_length() +
indices_shape.rank().get_length() - 1);
uint64_t i = 0;
for (; i < axis; i++)
{
result_dims[i] = params_shape[i];
}
for (uint64_t j = 0; j < indices_shape.rank().get_length(); i++, j++)
{
result_dims[i] = indices_shape[j];
}
for (uint64_t j = axis + 1; j < params_shape.rank().get_length(); i++, j++)
{
result_dims[i] = params_shape[j];
}
result_shape = PartialShape(result_dims);
}
else
{
result_shape = PartialShape::dynamic();
}
set_output_type(0, result_et, result_shape);
}
int64_t op::v1::Gather::get_axis() const
{
int64_t axis = AXIS_NOT_SET_VALUE;
auto axes_input_node = input_value(AXIS).get_node_shared_ptr();
if (auto const_op = as_type_ptr<op::Constant>(axes_input_node))
{
axis = const_op->cast_vector<int64_t>()[0];
}
if (axis < 0)
{
const auto& input_rank = get_input_partial_shape(PARAMS).rank();
if (input_rank.is_static())
{
axis += input_rank.get_length();
}
}
return axis;
}
void op::v1::Gather::generate_adjoints(autodiff::Adjoints& /* adjoints */,
const OutputVector& /* deltas */)
{
throw ngraph_error("Not yet implemented");
}
shared_ptr<Node> op::v1::Gather::clone_with_new_inputs(const OutputVector& new_args) const
{
check_new_args_count(this, new_args);
return make_shared<v1::Gather>(new_args.at(PARAMS), new_args.at(INDICES), new_args.at(AXIS));
}
namespace
{
template <element::Type_t ET>
bool evaluate(const HostTensorPtr& arg0,
const HostTensorPtr& arg1,
const HostTensorPtr& out,
size_t axis)
{
using T = typename element_type_traits<ET>::value_type;
Shape params_shape = arg0->get_shape();
Shape indices_shape = arg1->get_shape();
Shape out_shape(params_shape.size() + indices_shape.size() - 1);
uint64_t i = 0;
for (; i < axis; i++)
{
out_shape[i] = params_shape[i];
}
for (uint64_t j = 0; j < indices_shape.size(); i++, j++)
{
out_shape[i] = indices_shape[j];
}
for (uint64_t j = axis + 1; j < params_shape.size(); i++, j++)
{
out_shape[i] = params_shape[j];
}
out->set_shape(out_shape);
if (arg1->get_element_type() == element::i64)
{
runtime::reference::gather<T, int64_t>(arg0->get_data_ptr<ET>(),
arg1->get_data_ptr<int64_t>(),
out->get_data_ptr<ET>(),
arg0->get_shape(),
arg1->get_shape(),
out->get_shape(),
axis);
}
else if (arg1->get_element_type() == element::i32)
{
runtime::reference::gather<T, int32_t>(arg0->get_data_ptr<ET>(),
arg1->get_data_ptr<int32_t>(),
out->get_data_ptr<ET>(),
arg0->get_shape(),
arg1->get_shape(),
out->get_shape(),
axis);
}
else
{
throw ngraph_error("Unexpected type");
}
return true;
}
bool evaluate_gather(const HostTensorPtr& arg0,
const HostTensorPtr& arg1,
const HostTensorPtr& out,
size_t axis)
{
bool rc = true;
switch (out->get_element_type())
{
TYPE_CASE(i8)(arg0, arg1, out, axis);
break;
TYPE_CASE(i16)(arg0, arg1, out, axis);
break;
TYPE_CASE(i32)(arg0, arg1, out, axis);
break;
TYPE_CASE(i64)(arg0, arg1, out, axis);
break;
TYPE_CASE(u8)(arg0, arg1, out, axis);
break;
TYPE_CASE(u16)(arg0, arg1, out, axis);
break;
TYPE_CASE(u32)(arg0, arg1, out, axis);
break;
TYPE_CASE(u64)(arg0, arg1, out, axis);
break;
TYPE_CASE(f32)(arg0, arg1, out, axis);
break;
TYPE_CASE(f64)(arg0, arg1, out, axis);
break;
default: rc = false; break;
}
return rc;
}
}
bool op::v0::Gather::evaluate(const HostTensorVector& outputs, const HostTensorVector& inputs)
{
return evaluate_gather(inputs[0], inputs[1], outputs[0], get_axis());
}
bool op::v1::Gather::evaluate(const HostTensorVector& outputs, const HostTensorVector& inputs)
{
int64_t axis = 0;
switch (inputs[2]->get_element_type())
{
case element::Type_t::i8: axis = inputs[2]->get_data_ptr<element::Type_t::i8>()[0]; break;
case element::Type_t::i16: axis = inputs[2]->get_data_ptr<element::Type_t::i16>()[0]; break;
case element::Type_t::i32: axis = inputs[2]->get_data_ptr<element::Type_t::i32>()[0]; break;
case element::Type_t::i64: axis = inputs[2]->get_data_ptr<element::Type_t::i64>()[0]; break;
case element::Type_t::u8: axis = inputs[2]->get_data_ptr<element::Type_t::u8>()[0]; break;
case element::Type_t::u16: axis = inputs[2]->get_data_ptr<element::Type_t::u16>()[0]; break;
case element::Type_t::u32: axis = inputs[2]->get_data_ptr<element::Type_t::u32>()[0]; break;
case element::Type_t::u64: axis = inputs[2]->get_data_ptr<element::Type_t::u64>()[0]; break;
default: throw ngraph_error("axis element type is not integral data type");
}
if (axis < 0)
{
const auto& input_rank = get_input_partial_shape(PARAMS).rank();
if (input_rank.is_static())
{
axis += input_rank.get_length();
}
}
return evaluate_gather(inputs[0], inputs[1], outputs[0], axis);
}
<|endoftext|>
|
<commit_before>/* * This file is part of Maliit framework *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* Contact: maliit-discuss@lists.maliit.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "minputmethodhost.h"
#include "minputcontextconnection.h"
#include "mimpluginmanager.h"
#include <maliit/plugins/abstractinputmethod.h>
#include "windowgroup.h"
#include <maliit/namespace.h>
MInputMethodHost::MInputMethodHost(const QSharedPointer<MInputContextConnection> &inputContextConnection,
MIMPluginManager *pluginManager,
const QSharedPointer<Maliit::WindowGroup> &windowGroup,
const QString &plugin,
const QString &description)
: MAbstractInputMethodHost(),
connection(inputContextConnection),
pluginManager(pluginManager),
inputMethod(0),
enabled(false),
pluginId(plugin),
pluginDescription(description),
mWindowGroup(windowGroup)
{
// nothing
}
MInputMethodHost::~MInputMethodHost()
{
// nothing
}
void MInputMethodHost::setEnabled(bool enabled)
{
this->enabled = enabled;
}
void MInputMethodHost::setInputMethod(MAbstractInputMethod *inputMethod)
{
this->inputMethod = inputMethod;
}
int MInputMethodHost::contentType(bool &valid)
{
return connection->contentType(valid);
}
bool MInputMethodHost::correctionEnabled(bool &valid)
{
return connection->correctionEnabled(valid);
}
bool MInputMethodHost::predictionEnabled(bool &valid)
{
return connection->predictionEnabled(valid);
}
bool MInputMethodHost::autoCapitalizationEnabled(bool &valid)
{
return connection->autoCapitalizationEnabled(valid);
}
bool MInputMethodHost::surroundingText(QString &text, int &cursorPosition)
{
return connection->surroundingText(text, cursorPosition);
}
bool MInputMethodHost::hasSelection(bool &valid)
{
return connection->hasSelection(valid);
}
QString MInputMethodHost::selection(bool &valid)
{
return connection->selection(valid);
}
void MInputMethodHost::registerWindow (QWindow *window,
Maliit::Position position)
{
mWindowGroup->setupWindow(window, position);
}
int MInputMethodHost::preeditClickPos(bool &valid) const
{
return connection->preeditClickPos(valid);
}
int MInputMethodHost::inputMethodMode(bool &valid)
{
return connection->inputMethodMode(valid);
}
QRect MInputMethodHost::preeditRectangle(bool &valid)
{
return connection->preeditRectangle(valid);
}
QRect MInputMethodHost::cursorRectangle(bool &valid)
{
return connection->cursorRectangle(valid);
}
bool MInputMethodHost::hiddenText(bool &valid)
{
return connection->hiddenText(valid);
}
void MInputMethodHost::sendPreeditString(const QString &string,
const QList<Maliit::PreeditTextFormat> &preeditFormats,
int replacementStart, int replacementLength,
int cursorPos)
{
if (enabled) {
connection->sendPreeditString(string, preeditFormats, replacementStart, replacementLength, cursorPos);
}
}
void MInputMethodHost::sendCommitString(const QString &string, int replaceStart,
int replaceLength, int cursorPos)
{
if (enabled) {
connection->sendCommitString(string, replaceStart, replaceLength, cursorPos);
}
}
void MInputMethodHost::sendKeyEvent(const QKeyEvent &keyEvent,
Maliit::EventRequestType requestType)
{
if (enabled) {
connection->sendKeyEvent(keyEvent, requestType);
}
}
void MInputMethodHost::notifyImInitiatedHiding()
{
if (enabled) {
connection->notifyImInitiatedHiding();
}
}
void MInputMethodHost::invokeAction(const QString &action,
const QKeySequence &sequence)
{
if (enabled) {
connection->invokeAction(action, sequence);
}
}
void MInputMethodHost::setRedirectKeys(bool redirectEnabled)
{
if (enabled) {
connection->setRedirectKeys(redirectEnabled);
}
}
void MInputMethodHost::setDetectableAutoRepeat(bool autoRepeatEnabled)
{
if (enabled) {
connection->setDetectableAutoRepeat(autoRepeatEnabled);
}
}
void MInputMethodHost::setGlobalCorrectionEnabled(bool correctionEnabled)
{
if (enabled) {
connection->setGlobalCorrectionEnabled(correctionEnabled);
}
}
void MInputMethodHost::switchPlugin(Maliit::SwitchDirection direction)
{
if (enabled) {
pluginManager->switchPlugin(direction, inputMethod);
}
}
void MInputMethodHost::switchPlugin(const QString &pluginName)
{
if (enabled) {
pluginManager->switchPlugin(pluginName, inputMethod);
}
}
void MInputMethodHost::setScreenRegion(const QRegion ®ion)
{
if (enabled) {
pluginManager->updateRegion(region);
}
}
void MInputMethodHost::setInputMethodArea(const QRegion &)
{
// TODO: remove function since it is handled by surfaces now
}
void MInputMethodHost::setSelection(int start, int length)
{
if (enabled) {
connection->setSelection(start, length);
}
}
QList<MImPluginDescription> MInputMethodHost::pluginDescriptions(Maliit::HandlerState state) const
{
return pluginManager->pluginDescriptions(state);
}
QList<MImSubViewDescription>
MInputMethodHost::surroundingSubViewDescriptions(Maliit::HandlerState state) const
{
return pluginManager->surroundingSubViewDescriptions(state);
}
void MInputMethodHost::setLanguage(const QString &language)
{
if (enabled) {
connection->setLanguage(language);
}
}
void MInputMethodHost::setOrientationAngleLocked(bool)
{
// NOT implemented.
}
int MInputMethodHost::anchorPosition(bool &valid)
{
return connection->anchorPosition(valid);
}
AbstractPluginSetting *MInputMethodHost::registerPluginSetting(const QString &key,
const QString &description,
Maliit::SettingEntryType type,
const QVariantMap &attributes)
{
return pluginManager->registerPluginSetting(pluginId, pluginDescription, key, description, type, attributes);
}
<commit_msg>Temporarily allow plugin to set input method<commit_after>/* * This file is part of Maliit framework *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* Contact: maliit-discuss@lists.maliit.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "minputmethodhost.h"
#include "minputcontextconnection.h"
#include "mimpluginmanager.h"
#include <maliit/plugins/abstractinputmethod.h>
#include "windowgroup.h"
#include <maliit/namespace.h>
MInputMethodHost::MInputMethodHost(const QSharedPointer<MInputContextConnection> &inputContextConnection,
MIMPluginManager *pluginManager,
const QSharedPointer<Maliit::WindowGroup> &windowGroup,
const QString &plugin,
const QString &description)
: MAbstractInputMethodHost(),
connection(inputContextConnection),
pluginManager(pluginManager),
inputMethod(0),
enabled(false),
pluginId(plugin),
pluginDescription(description),
mWindowGroup(windowGroup)
{
// nothing
}
MInputMethodHost::~MInputMethodHost()
{
// nothing
}
void MInputMethodHost::setEnabled(bool enabled)
{
this->enabled = enabled;
}
void MInputMethodHost::setInputMethod(MAbstractInputMethod *inputMethod)
{
this->inputMethod = inputMethod;
}
int MInputMethodHost::contentType(bool &valid)
{
return connection->contentType(valid);
}
bool MInputMethodHost::correctionEnabled(bool &valid)
{
return connection->correctionEnabled(valid);
}
bool MInputMethodHost::predictionEnabled(bool &valid)
{
return connection->predictionEnabled(valid);
}
bool MInputMethodHost::autoCapitalizationEnabled(bool &valid)
{
return connection->autoCapitalizationEnabled(valid);
}
bool MInputMethodHost::surroundingText(QString &text, int &cursorPosition)
{
return connection->surroundingText(text, cursorPosition);
}
bool MInputMethodHost::hasSelection(bool &valid)
{
return connection->hasSelection(valid);
}
QString MInputMethodHost::selection(bool &valid)
{
return connection->selection(valid);
}
void MInputMethodHost::registerWindow (QWindow *window,
Maliit::Position position)
{
mWindowGroup->setupWindow(window, position);
}
int MInputMethodHost::preeditClickPos(bool &valid) const
{
return connection->preeditClickPos(valid);
}
int MInputMethodHost::inputMethodMode(bool &valid)
{
return connection->inputMethodMode(valid);
}
QRect MInputMethodHost::preeditRectangle(bool &valid)
{
return connection->preeditRectangle(valid);
}
QRect MInputMethodHost::cursorRectangle(bool &valid)
{
return connection->cursorRectangle(valid);
}
bool MInputMethodHost::hiddenText(bool &valid)
{
return connection->hiddenText(valid);
}
void MInputMethodHost::sendPreeditString(const QString &string,
const QList<Maliit::PreeditTextFormat> &preeditFormats,
int replacementStart, int replacementLength,
int cursorPos)
{
if (enabled) {
connection->sendPreeditString(string, preeditFormats, replacementStart, replacementLength, cursorPos);
}
}
void MInputMethodHost::sendCommitString(const QString &string, int replaceStart,
int replaceLength, int cursorPos)
{
if (enabled) {
connection->sendCommitString(string, replaceStart, replaceLength, cursorPos);
}
}
void MInputMethodHost::sendKeyEvent(const QKeyEvent &keyEvent,
Maliit::EventRequestType requestType)
{
if (enabled) {
connection->sendKeyEvent(keyEvent, requestType);
}
}
void MInputMethodHost::notifyImInitiatedHiding()
{
if (enabled) {
connection->notifyImInitiatedHiding();
}
}
void MInputMethodHost::invokeAction(const QString &action,
const QKeySequence &sequence)
{
if (enabled) {
connection->invokeAction(action, sequence);
}
}
void MInputMethodHost::setRedirectKeys(bool redirectEnabled)
{
if (enabled) {
connection->setRedirectKeys(redirectEnabled);
}
}
void MInputMethodHost::setDetectableAutoRepeat(bool autoRepeatEnabled)
{
if (enabled) {
connection->setDetectableAutoRepeat(autoRepeatEnabled);
}
}
void MInputMethodHost::setGlobalCorrectionEnabled(bool correctionEnabled)
{
if (enabled) {
connection->setGlobalCorrectionEnabled(correctionEnabled);
}
}
void MInputMethodHost::switchPlugin(Maliit::SwitchDirection direction)
{
if (enabled) {
pluginManager->switchPlugin(direction, inputMethod);
}
}
void MInputMethodHost::switchPlugin(const QString &pluginName)
{
if (enabled) {
pluginManager->switchPlugin(pluginName, inputMethod);
}
}
void MInputMethodHost::setScreenRegion(const QRegion ®ion)
{
if (enabled) {
pluginManager->updateRegion(region);
}
}
void MInputMethodHost::setInputMethodArea(const QRegion ®ion)
{
// FIXME: this currently fights with window group on who is allowed to set the area.
if (enabled) {
connection->updateInputMethodArea(region);
}
}
void MInputMethodHost::setSelection(int start, int length)
{
if (enabled) {
connection->setSelection(start, length);
}
}
QList<MImPluginDescription> MInputMethodHost::pluginDescriptions(Maliit::HandlerState state) const
{
return pluginManager->pluginDescriptions(state);
}
QList<MImSubViewDescription>
MInputMethodHost::surroundingSubViewDescriptions(Maliit::HandlerState state) const
{
return pluginManager->surroundingSubViewDescriptions(state);
}
void MInputMethodHost::setLanguage(const QString &language)
{
if (enabled) {
connection->setLanguage(language);
}
}
void MInputMethodHost::setOrientationAngleLocked(bool)
{
// NOT implemented.
}
int MInputMethodHost::anchorPosition(bool &valid)
{
return connection->anchorPosition(valid);
}
AbstractPluginSetting *MInputMethodHost::registerPluginSetting(const QString &key,
const QString &description,
Maliit::SettingEntryType type,
const QVariantMap &attributes)
{
return pluginManager->registerPluginSetting(pluginId, pluginDescription, key, description, type, attributes);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2018 Nagisa Sekiguchi
*
* 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 YDSH_LOGGER_BASE_HPP
#define YDSH_LOGGER_BASE_HPP
#include <unistd.h>
#include <cstring>
#include <string>
#include <ctime>
#include <cstdarg>
#include <mutex>
#include "resource.hpp"
#include "util.hpp"
#include "fatal.h"
namespace ydsh {
enum class LogLevel : unsigned int {
INFO, WARNING, ERROR, FATAL, NONE
};
inline const char *toString(LogLevel level) {
const char *str[] = {
"info", "warning", "error", "fatal", "none"
};
return str[static_cast<unsigned int>(level)];
}
namespace __detail_logger {
template<bool T>
class LoggerBase {
protected:
static_assert(T, "not allowed instantiation");
std::string prefix;
FilePtr filePtr;
LogLevel severity{LogLevel::FATAL};
std::mutex outMutex;
/**
* if prefix is mepty string, treat as null logger
* @param prefix
*/
explicit LoggerBase(const char *prefix) : prefix(prefix) {
this->syncSetting([&]{
this->syncSeverityWithEnv();
this->syncAppenderWithEnv();
});
}
~LoggerBase() = default;
void log(LogLevel level, const char *fmt, va_list list);
public:
// helper method for logger setting.
template <typename Func>
void syncSetting(Func func) {
std::lock_guard<std::mutex> guard(this->outMutex);
func();
}
void operator()(LogLevel level, const char *fmt, ...) __attribute__ ((format(printf, 3, 4))) {
va_list arg;
va_start(arg, fmt);
this->log(level, fmt, arg);
va_end(arg);
}
bool enabled(LogLevel level) const {
return static_cast<unsigned int>(level) < static_cast<unsigned int>(LogLevel::NONE) &&
static_cast<unsigned int>(level) >= static_cast<unsigned int>(this->severity);
}
// not-thread safe api.
void syncSeverityWithEnv();
void setSeverity(LogLevel level) {
this->severity = level;
}
void syncAppenderWithEnv();
void setAppender(FilePtr &&file) {
this->filePtr = std::move(file);
}
const FilePtr &getAppender() const {
return this->filePtr;
}
};
template <bool T>
void LoggerBase<T>::log(LogLevel level, const char *fmt, va_list list) {
if(!this->enabled(level)) {
return;
}
// create body
char *str = nullptr;
if(vasprintf(&str, fmt, list) == -1) {
fatal_perror("");
}
// create header
char header[128];
header[0] = '\0';
time_t timer = time(nullptr);
struct tm local{};
tzset();
if(localtime_r(&timer, &local)) {
char buf[32];
strftime(buf, arraySize(buf), "%F %T", &local);
snprintf(header, arraySize(header), "%s <%s> [%d] ", buf, toString(level), getpid());
}
// print body
fprintf(this->filePtr.get(), "%s%s\n", header, str);
fflush(this->filePtr.get());
free(str);
if(level == LogLevel::FATAL) {
abort();
}
}
template <bool T>
void LoggerBase<T>::syncSeverityWithEnv() {
if(this->prefix.empty()) {
this->setSeverity(LogLevel::NONE);
return;
}
std::string key = this->prefix;
key += "_LEVEL";
const char *level = getenv(key.c_str());
if(level != nullptr) {
for(auto i = static_cast<unsigned int>(LogLevel::INFO);
i < static_cast<unsigned int>(LogLevel::NONE) + 1; i++) {
auto s = static_cast<LogLevel>(i);
if(strcasecmp(toString(s), level) == 0) {
this->setSeverity(s);
return;
}
}
}
}
template <bool T>
void LoggerBase<T>::syncAppenderWithEnv() {
std::string key = this->prefix;
key += "_APPENDER";
const char *appender = getenv(key.c_str());
FilePtr file;
if(appender && *appender != '\0') {
file = createFilePtr(fopen, appender, "w");
}
if(!file) {
file = createFilePtr(fdopen, dup(STDERR_FILENO), "w");
}
this->setAppender(std::move(file));
}
} // namespace __detail_logger
using LoggerBase = __detail_logger::LoggerBase<true>;
struct NullLogger : public LoggerBase {
NullLogger() : LoggerBase("") {}
};
template <typename T>
class SingletonLogger : public LoggerBase, public Singleton<T> {
protected:
explicit SingletonLogger(const char *prefix) : LoggerBase(prefix) {}
public:
static void Info(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))) {
va_list arg;
va_start(arg, fmt);
Singleton<T>::instance().log(LogLevel::INFO, fmt, arg);
va_end(arg);
}
static void Warning(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))) {
va_list arg;
va_start(arg, fmt);
Singleton<T>::instance().log(LogLevel::WARNING, fmt, arg);
va_end(arg);
}
static void Error(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))) {
va_list arg;
va_start(arg, fmt);
Singleton<T>::instance().log(LogLevel::ERROR, fmt, arg);
va_end(arg);
}
static void Fatal(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))) {
va_list arg;
va_start(arg, fmt);
Singleton<T>::instance().log(LogLevel::FATAL, fmt, arg);
va_end(arg);
}
static bool Enabled(LogLevel level) {
return Singleton<T>::instance().enabled(level);
}
};
} // namespace ydsh
#endif //YDSH_LOGGER_BASE_HPP
<commit_msg>fix build error in gcc<commit_after>/*
* Copyright (C) 2018 Nagisa Sekiguchi
*
* 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 YDSH_LOGGER_BASE_HPP
#define YDSH_LOGGER_BASE_HPP
#include <unistd.h>
#include <cstring>
#include <string>
#include <ctime>
#include <cstdarg>
#include <mutex>
#include "resource.hpp"
#include "util.hpp"
#include "fatal.h"
namespace ydsh {
enum class LogLevel : unsigned int {
INFO, WARNING, ERROR, FATAL, NONE
};
inline const char *toString(LogLevel level) {
const char *str[] = {
"info", "warning", "error", "fatal", "none"
};
return str[static_cast<unsigned int>(level)];
}
namespace __detail_logger {
template<bool T>
class LoggerBase {
protected:
static_assert(T, "not allowed instantiation");
std::string prefix;
FilePtr filePtr;
LogLevel severity{LogLevel::FATAL};
std::mutex outMutex;
/**
* if prefix is mepty string, treat as null logger
* @param prefix
*/
explicit LoggerBase(const char *prefix) : prefix(prefix) {
this->syncSetting([&]{
this->syncSeverityWithEnv();
this->syncAppenderWithEnv();
});
}
~LoggerBase() = default;
void log(LogLevel level, const char *fmt, va_list list);
public:
// helper method for logger setting.
template <typename Func>
void syncSetting(Func func) {
std::lock_guard<std::mutex> guard(this->outMutex);
func();
}
void operator()(LogLevel level, const char *fmt, ...) __attribute__ ((format(printf, 3, 4))) {
va_list arg;
va_start(arg, fmt);
this->log(level, fmt, arg);
va_end(arg);
}
bool enabled(LogLevel level) const {
return static_cast<unsigned int>(level) < static_cast<unsigned int>(LogLevel::NONE) &&
static_cast<unsigned int>(level) >= static_cast<unsigned int>(this->severity);
}
// not-thread safe api.
void syncSeverityWithEnv();
void setSeverity(LogLevel level) {
this->severity = level;
}
void syncAppenderWithEnv();
void setAppender(FilePtr &&file) {
this->filePtr = std::move(file);
}
const FilePtr &getAppender() const {
return this->filePtr;
}
};
template <bool T>
void LoggerBase<T>::log(LogLevel level, const char *fmt, va_list list) {
if(!this->enabled(level)) {
return;
}
// create body
char *str = nullptr;
if(vasprintf(&str, fmt, list) == -1) {
fatal_perror("");
}
// create header
char header[128];
header[0] = '\0';
time_t timer = time(nullptr);
struct tm local{};
tzset();
if(localtime_r(&timer, &local)) {
char buf[32];
strftime(buf, arraySize(buf), "%F %T", &local);
snprintf(header, arraySize(header), "%s <%s> [%d] ", buf, toString(level), getpid());
}
// print body
fprintf(this->filePtr.get(), "%s%s\n", header, str);
fflush(this->filePtr.get());
free(str);
if(level == LogLevel::FATAL) {
abort();
}
}
template <bool T>
void LoggerBase<T>::syncSeverityWithEnv() {
if(this->prefix.empty()) {
this->setSeverity(LogLevel::NONE);
return;
}
std::string key = this->prefix;
key += "_LEVEL";
const char *level = getenv(key.c_str());
if(level != nullptr) {
for(auto i = static_cast<unsigned int>(LogLevel::INFO);
i < static_cast<unsigned int>(LogLevel::NONE) + 1; i++) {
auto s = static_cast<LogLevel>(i);
if(strcasecmp(toString(s), level) == 0) {
this->setSeverity(s);
return;
}
}
}
}
template <bool T>
void LoggerBase<T>::syncAppenderWithEnv() {
std::string key = this->prefix;
key += "_APPENDER";
const char *appender = getenv(key.c_str());
FilePtr file;
if(appender && *appender != '\0') {
file = createFilePtr(fopen, appender, "w");
}
if(!static_cast<bool>(file)) { // workaround for gcc
file = createFilePtr(fdopen, dup(STDERR_FILENO), "w");
}
this->setAppender(std::move(file));
}
} // namespace __detail_logger
using LoggerBase = __detail_logger::LoggerBase<true>;
struct NullLogger : public LoggerBase {
NullLogger() : LoggerBase("") {}
};
template <typename T>
class SingletonLogger : public LoggerBase, public Singleton<T> {
protected:
explicit SingletonLogger(const char *prefix) : LoggerBase(prefix) {}
public:
static void Info(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))) {
va_list arg;
va_start(arg, fmt);
Singleton<T>::instance().log(LogLevel::INFO, fmt, arg);
va_end(arg);
}
static void Warning(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))) {
va_list arg;
va_start(arg, fmt);
Singleton<T>::instance().log(LogLevel::WARNING, fmt, arg);
va_end(arg);
}
static void Error(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))) {
va_list arg;
va_start(arg, fmt);
Singleton<T>::instance().log(LogLevel::ERROR, fmt, arg);
va_end(arg);
}
static void Fatal(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))) {
va_list arg;
va_start(arg, fmt);
Singleton<T>::instance().log(LogLevel::FATAL, fmt, arg);
va_end(arg);
}
static bool Enabled(LogLevel level) {
return Singleton<T>::instance().enabled(level);
}
};
} // namespace ydsh
#endif //YDSH_LOGGER_BASE_HPP
<|endoftext|>
|
<commit_before>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#include "CompressRGB.h"
#include "CompressionOptions.h"
#include "OutputOptions.h"
#include <nvimage/Image.h>
#include <nvimage/FloatImage.h>
#include <nvimage/PixelFormat.h>
#include <nvmath/Color.h>
#include <nvmath/half.h>
#include <nvcore/Debug.h>
using namespace nv;
using namespace nvtt;
namespace
{
inline uint computePitch(uint w, uint bitsize)
{
uint p = w * ((bitsize + 7) / 8);
// Align to 32 bits.
return ((p + 3) / 4) * 4;
}
inline void convert_to_a8r8g8b8(const void * src, void * dst, uint w)
{
memcpy(dst, src, 4 * w);
}
inline void convert_to_x8r8g8b8(const void * src, void * dst, uint w)
{
memcpy(dst, src, 4 * w);
}
} // namespace
// Pixel format converter.
void nv::compressRGB(const Image * image, const OutputOptions::Private & outputOptions, const CompressionOptions::Private & compressionOptions)
{
nvCheck(image != NULL);
const uint w = image->width();
const uint h = image->height();
uint bitCount;
uint rmask, rshift, rsize;
uint gmask, gshift, gsize;
uint bmask, bshift, bsize;
uint amask, ashift, asize;
if (compressionOptions.bitcount != 0)
{
bitCount = compressionOptions.bitcount;
nvCheck(bitCount == 8 || bitCount == 16 || bitCount == 24 || bitCount == 32);
rmask = compressionOptions.rmask;
gmask = compressionOptions.gmask;
bmask = compressionOptions.bmask;
amask = compressionOptions.amask;
PixelFormat::maskShiftAndSize(rmask, &rshift, &rsize);
PixelFormat::maskShiftAndSize(gmask, &gshift, &gsize);
PixelFormat::maskShiftAndSize(bmask, &bshift, &bsize);
PixelFormat::maskShiftAndSize(amask, &ashift, &asize);
}
else
{
rsize = compressionOptions.rsize;
gsize = compressionOptions.gsize;
bsize = compressionOptions.bsize;
asize = compressionOptions.asize;
bitCount = rsize + gsize + bsize + asize;
nvCheck(bitCount <= 32);
ashift = 0;
bshift = ashift + asize;
gshift = bshift + bsize;
rshift = gshift + gsize;
rmask = ((1 << rsize) - 1) << rshift;
gmask = ((1 << gsize) - 1) << gshift;
bmask = ((1 << bsize) - 1) << bshift;
amask = ((1 << asize) - 1) << ashift;
}
const uint byteCount = bitCount / 8;
// Determine pitch.
uint pitch = computePitch(w, bitCount);
uint8 * dst = (uint8 *)mem::malloc(pitch + 4);
for (uint y = 0; y < h; y++)
{
const Color32 * src = image->scanline(y);
if (bitCount == 32 && rmask == 0xFF0000 && gmask == 0xFF00 && bmask == 0xFF && amask == 0xFF000000)
{
convert_to_a8r8g8b8(src, dst, w);
}
else if (bitCount == 32 && rmask == 0xFF0000 && gmask == 0xFF00 && bmask == 0xFF && amask == 0)
{
convert_to_x8r8g8b8(src, dst, w);
}
else
{
// Generic pixel format conversion.
for (uint x = 0; x < w; x++)
{
uint c = 0;
c |= PixelFormat::convert(src[x].r, 8, rsize) << rshift;
c |= PixelFormat::convert(src[x].g, 8, gsize) << gshift;
c |= PixelFormat::convert(src[x].b, 8, bsize) << bshift;
c |= PixelFormat::convert(src[x].a, 8, asize) << ashift;
// Output one byte at a time.
for (uint i = 0; i < byteCount; i++)
{
*(dst + x * byteCount + i) = (c >> (i * 8)) & 0xFF;
}
}
// Zero padding.
for (uint x = w; x < pitch; x++)
{
*(dst + x) = 0;
}
}
if (outputOptions.outputHandler != NULL)
{
outputOptions.outputHandler->writeData(dst, pitch);
}
}
mem::free(dst);
}
void nv::compressRGB(const FloatImage * image, const OutputOptions::Private & outputOptions, const CompressionOptions::Private & compressionOptions)
{
nvCheck(image != NULL);
const uint w = image->width();
const uint h = image->height();
const uint rsize = compressionOptions.rsize;
const uint gsize = compressionOptions.gsize;
const uint bsize = compressionOptions.bsize;
const uint asize = compressionOptions.asize;
nvCheck(rsize == 0 || rsize == 16 || rsize == 32);
nvCheck(gsize == 0 || gsize == 16 || gsize == 32);
nvCheck(bsize == 0 || bsize == 16 || bsize == 32);
nvCheck(asize == 0 || asize == 16 || asize == 32);
const uint bitCount = rsize + gsize + bsize + asize;
const uint byteCount = bitCount / 8;
const uint pitch = w * byteCount;
uint8 * dst = (uint8 *)mem::malloc(pitch);
for (uint y = 0; y < h; y++)
{
const float * rchannel = image->scanline(y, 0);
const float * gchannel = image->scanline(y, 1);
const float * bchannel = image->scanline(y, 2);
const float * achannel = image->scanline(y, 3);
union FLOAT
{
float f;
uint32 u;
};
uint8 * ptr = dst;
for (uint x = 0; x < w; x++)
{
FLOAT r, g, b, a;
r.f = rchannel[x];
g.f = gchannel[x];
b.f = bchannel[x];
a.f = achannel[x];
if (rsize == 32) *((uint32 *)ptr) = r.u;
else if (rsize == 16) *((uint16 *)ptr) = half_from_float(r.u);
ptr += rsize / 8;
if (gsize == 32) *((uint32 *)ptr) = g.u;
else if (gsize == 16) *((uint16 *)ptr) = half_from_float(g.u);
ptr += gsize / 8;
if (bsize == 32) *((uint32 *)ptr) = b.u;
else if (bsize == 16) *((uint16 *)ptr) = half_from_float(b.u);
ptr += bsize / 8;
if (asize == 32) *((uint32 *)ptr) = a.u;
else if (asize == 16) *((uint16 *)ptr) = half_from_float(a.u);
ptr += asize / 8;
}
if (outputOptions.outputHandler != NULL)
{
outputOptions.outputHandler->writeData(dst, pitch);
}
}
mem::free(dst);
}
<commit_msg>Fix linux includes.<commit_after>// Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#include "CompressRGB.h"
#include "CompressionOptions.h"
#include "OutputOptions.h"
#include <nvimage/Image.h>
#include <nvimage/FloatImage.h>
#include <nvimage/PixelFormat.h>
#include <nvmath/Color.h>
#include <nvmath/Half.h>
#include <nvcore/Debug.h>
using namespace nv;
using namespace nvtt;
namespace
{
inline uint computePitch(uint w, uint bitsize)
{
uint p = w * ((bitsize + 7) / 8);
// Align to 32 bits.
return ((p + 3) / 4) * 4;
}
inline void convert_to_a8r8g8b8(const void * src, void * dst, uint w)
{
memcpy(dst, src, 4 * w);
}
inline void convert_to_x8r8g8b8(const void * src, void * dst, uint w)
{
memcpy(dst, src, 4 * w);
}
} // namespace
// Pixel format converter.
void nv::compressRGB(const Image * image, const OutputOptions::Private & outputOptions, const CompressionOptions::Private & compressionOptions)
{
nvCheck(image != NULL);
const uint w = image->width();
const uint h = image->height();
uint bitCount;
uint rmask, rshift, rsize;
uint gmask, gshift, gsize;
uint bmask, bshift, bsize;
uint amask, ashift, asize;
if (compressionOptions.bitcount != 0)
{
bitCount = compressionOptions.bitcount;
nvCheck(bitCount == 8 || bitCount == 16 || bitCount == 24 || bitCount == 32);
rmask = compressionOptions.rmask;
gmask = compressionOptions.gmask;
bmask = compressionOptions.bmask;
amask = compressionOptions.amask;
PixelFormat::maskShiftAndSize(rmask, &rshift, &rsize);
PixelFormat::maskShiftAndSize(gmask, &gshift, &gsize);
PixelFormat::maskShiftAndSize(bmask, &bshift, &bsize);
PixelFormat::maskShiftAndSize(amask, &ashift, &asize);
}
else
{
rsize = compressionOptions.rsize;
gsize = compressionOptions.gsize;
bsize = compressionOptions.bsize;
asize = compressionOptions.asize;
bitCount = rsize + gsize + bsize + asize;
nvCheck(bitCount <= 32);
ashift = 0;
bshift = ashift + asize;
gshift = bshift + bsize;
rshift = gshift + gsize;
rmask = ((1 << rsize) - 1) << rshift;
gmask = ((1 << gsize) - 1) << gshift;
bmask = ((1 << bsize) - 1) << bshift;
amask = ((1 << asize) - 1) << ashift;
}
const uint byteCount = bitCount / 8;
// Determine pitch.
uint pitch = computePitch(w, bitCount);
uint8 * dst = (uint8 *)mem::malloc(pitch + 4);
for (uint y = 0; y < h; y++)
{
const Color32 * src = image->scanline(y);
if (bitCount == 32 && rmask == 0xFF0000 && gmask == 0xFF00 && bmask == 0xFF && amask == 0xFF000000)
{
convert_to_a8r8g8b8(src, dst, w);
}
else if (bitCount == 32 && rmask == 0xFF0000 && gmask == 0xFF00 && bmask == 0xFF && amask == 0)
{
convert_to_x8r8g8b8(src, dst, w);
}
else
{
// Generic pixel format conversion.
for (uint x = 0; x < w; x++)
{
uint c = 0;
c |= PixelFormat::convert(src[x].r, 8, rsize) << rshift;
c |= PixelFormat::convert(src[x].g, 8, gsize) << gshift;
c |= PixelFormat::convert(src[x].b, 8, bsize) << bshift;
c |= PixelFormat::convert(src[x].a, 8, asize) << ashift;
// Output one byte at a time.
for (uint i = 0; i < byteCount; i++)
{
*(dst + x * byteCount + i) = (c >> (i * 8)) & 0xFF;
}
}
// Zero padding.
for (uint x = w; x < pitch; x++)
{
*(dst + x) = 0;
}
}
if (outputOptions.outputHandler != NULL)
{
outputOptions.outputHandler->writeData(dst, pitch);
}
}
mem::free(dst);
}
void nv::compressRGB(const FloatImage * image, const OutputOptions::Private & outputOptions, const CompressionOptions::Private & compressionOptions)
{
nvCheck(image != NULL);
const uint w = image->width();
const uint h = image->height();
const uint rsize = compressionOptions.rsize;
const uint gsize = compressionOptions.gsize;
const uint bsize = compressionOptions.bsize;
const uint asize = compressionOptions.asize;
nvCheck(rsize == 0 || rsize == 16 || rsize == 32);
nvCheck(gsize == 0 || gsize == 16 || gsize == 32);
nvCheck(bsize == 0 || bsize == 16 || bsize == 32);
nvCheck(asize == 0 || asize == 16 || asize == 32);
const uint bitCount = rsize + gsize + bsize + asize;
const uint byteCount = bitCount / 8;
const uint pitch = w * byteCount;
uint8 * dst = (uint8 *)mem::malloc(pitch);
for (uint y = 0; y < h; y++)
{
const float * rchannel = image->scanline(y, 0);
const float * gchannel = image->scanline(y, 1);
const float * bchannel = image->scanline(y, 2);
const float * achannel = image->scanline(y, 3);
union FLOAT
{
float f;
uint32 u;
};
uint8 * ptr = dst;
for (uint x = 0; x < w; x++)
{
FLOAT r, g, b, a;
r.f = rchannel[x];
g.f = gchannel[x];
b.f = bchannel[x];
a.f = achannel[x];
if (rsize == 32) *((uint32 *)ptr) = r.u;
else if (rsize == 16) *((uint16 *)ptr) = half_from_float(r.u);
ptr += rsize / 8;
if (gsize == 32) *((uint32 *)ptr) = g.u;
else if (gsize == 16) *((uint16 *)ptr) = half_from_float(g.u);
ptr += gsize / 8;
if (bsize == 32) *((uint32 *)ptr) = b.u;
else if (bsize == 16) *((uint16 *)ptr) = half_from_float(b.u);
ptr += bsize / 8;
if (asize == 32) *((uint32 *)ptr) = a.u;
else if (asize == 16) *((uint16 *)ptr) = half_from_float(a.u);
ptr += asize / 8;
}
if (outputOptions.outputHandler != NULL)
{
outputOptions.outputHandler->writeData(dst, pitch);
}
}
mem::free(dst);
}
<|endoftext|>
|
<commit_before>#include "facepreprocessor.h"
#include <vector>
#include <algorithm>
#include <limits>
#include <cstdint>
#include <cmath>
#include <opencv2/imgproc/imgproc.hpp>
#include <QDebug>
static const double PI = std::atan(1.0) * 4;
using namespace cv;
static const bool MARK_FOUND_FEATURES = false;
FacePreprocessor::FacePreprocessor(FaceClassifiers classifiers, const Mat& input) throw(std::invalid_argument)
: input(input),
result(Mat(input.rows, input.cols, CV_8UC1)),
classifiers(classifiers)
{
if (classifiers.face.get() == nullptr)
throw std::invalid_argument("face classifier");
else if (classifiers.face->empty())
throw std::invalid_argument("face classifier");
else if (classifiers.eye.get() == nullptr)
throw std::invalid_argument("eye classifier");
else if (classifiers.eye->empty())
throw std::invalid_argument("eye classifier");
else if (classifiers.eyePair.get() == nullptr)
throw std::invalid_argument("eyepair classifier");
else if (classifiers.eyePair->empty())
throw std::invalid_argument("eyepair classifier");
else if (classifiers.eyeLeft.get() == nullptr)
throw std::invalid_argument("left eye classifier");
else if (classifiers.eyeLeft->empty())
throw std::invalid_argument("left eye classifier");
else if (classifiers.eyeRight.get() == nullptr)
throw std::invalid_argument("right eye classifier");
else if (classifiers.eyeRight->empty())
throw std::invalid_argument("right eye classifier");
else if (input.empty())
throw std::invalid_argument("input");
}
unsigned int FacePreprocessor::GetMinSize() const
{
int minDim = std::min(input.rows, input.cols);
return static_cast<unsigned int>(minDim / 5.0);
}
Rect FacePreprocessor::LargestRect(const std::vector<Rect>& rects)
{
if(rects.empty())
return Rect();
Rect largest = *std::max_element(rects.begin(), rects.end(), [](const Rect& a, const Rect& b)
{
return a.area() < b.area();
}
);
return largest;
}
const double FacePreprocessor::MAX_ROTATE_ANGLE = 25.0;
double FacePreprocessor::GetRotation(cv::Rect left, cv::Rect right)
{
Point direction;
direction.x = right.x - left.x;
direction.y = right.y - left.y;
double angle = std::atan2(direction.y, direction.x) * 180.0 / PI;
return angle;
}
std::vector<Rect> FacePreprocessor::GetEyesAlternateMethod()
{
static std::vector<Rect> empty;
std::vector<Rect> eyes;
eyes.reserve(2);
classifiers.eyePair->detectMultiScale(result, eyes, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT);
if(eyes.empty())
return empty;
qDebug() << "eye pair was found";
if (MARK_FOUND_FEATURES)
rectangle(result, eyes.front(), 1);
std::vector<Rect> lefts;
std::vector<Rect> rights;
Rect cRect = eyes.front();
cRect.width /= 2;
classifiers.eyeLeft->detectMultiScale(result(cRect), lefts, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT);
if(lefts.empty())
{
qDebug () << "left wasnt found";
return empty;
}
cRect.x += cRect.width;
classifiers.eyeLeft->detectMultiScale(result(cRect), rights, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT);
if(rights.empty())
{
qDebug () << "right wasnt found";
return empty;
}
rights.front().x += cRect.width;
gotEyes = true;
lefts.front().x += eyes.front().x;
lefts.front().y += eyes.front().y;
rights.front().x += eyes.front().x;
rights.front().y += eyes.front().y;
if (MARK_FOUND_FEATURES)
{
rectangle(result, lefts.front(), 1);
rectangle(result, rights.front(), 1);
}
eyes.clear();
eyes.push_back(lefts.front());
eyes.push_back(rights.front());
return eyes;
}
std::vector<Rect> FacePreprocessor::GetEyes()
{
const Rect upperHalfOfFace(face.width / 12, face.height / 5, face.width - (face.width / 6), static_cast<int>(face.height / 2.2));
const int maxSize = static_cast<int>(std::ceil(std::max(upperHalfOfFace.width, upperHalfOfFace.height) / 5.0));
const int minSize = std::max(static_cast<int>(std::floor(std::min(upperHalfOfFace.width, upperHalfOfFace.height) / 20.0)), 3);
std::vector<Rect> eyes;
std::vector<Rect> eyePairR;
//classifiers.eyePair->detectMultiScale(result(upperHalfOfFace), eyePairR, 1.1, 3, CV_HAAR_FIND_BIGGEST_OBJECT);
if(eyePairR.empty())
{
classifiers.eye->detectMultiScale(result(upperHalfOfFace), eyes, 1.05, 6, 0, Size(minSize, minSize), Size(maxSize, maxSize));
}
else
{
classifiers.eye->detectMultiScale(result(eyePairR.front()), eyes, 1.1, 6, 0, Size(minSize, minSize), Size(maxSize, maxSize));
if (MARK_FOUND_FEATURES)
rectangle(result, eyePairR.front(), 255);
}
for (auto eye : eyes)
{
if(!eyePairR.empty())
{
eye.x += eyePairR.front().x;
eye.y += eyePairR.front().y;
}
else
{
eye.x += upperHalfOfFace.x;
eye.y += upperHalfOfFace.y;
}
if (MARK_FOUND_FEATURES)
rectangle(result, eye, 1);
}
// removing intersecting objects
for(uint8_t i = 0; i < eyes.size(); i++)
{
for(uint8_t j = 0; j < eyes.size(); j++)
{
if (i != j)
{
Rect intersection = eyes[i] & eyes[j];
if (intersection.area() > 0)
{
eyes.erase(eyes.begin() + j);
if (i > j)
i--;
j--;
}
}
}
}
if(eyes.size() < 2)
{
qDebug() << "only" << eyes.size() << "eyes were found";
eyes.clear();
return eyes;
}
gotEyes = true;
if(eyes.size() > 2)
{
// finding the pair with lowest angle
std::vector<std::pair<uint16_t, uint16_t>> helper;
helper.reserve(eyes.size() * eyes.size() - eyes.size());
for(auto i = eyes.begin(); i != eyes.end(); i++)
{
for(auto j = eyes.begin(); j != eyes.end(); j++)
{
if (i != j)
helper.push_back(std::make_pair(std::distance(eyes.begin(), i), std::distance(eyes.begin(), j)));
}
}
std::sort(helper.begin(), helper.end(), [&eyes](const std::pair<uint16_t, uint16_t>& a, const std::pair<uint16_t, uint16_t>& b)
{
double angleA = std::abs(GetRotation(eyes[a.first], eyes[a.second]));
double angleB = std::abs(GetRotation(eyes[b.first], eyes[b.second]));
return angleA < angleB;
});
assert(helper.front().first != helper.front().second);
std::swap(eyes[0], eyes[helper.front().first]);
std::swap(eyes[1], eyes[helper.front().second]);
}
std::sort(eyes.begin(), eyes.begin() + 2, [](const Rect& a, const Rect& b) { return a.x < b.x; });
eyes.resize(2);
return eyes;
}
void FacePreprocessor::RotateFace()
{
std::vector<Rect> eyes = GetEyes();
if(eyes.size() < 2)
{
return;
}
double angle = GetRotation(eyes[0], eyes[1]);
angle = std::round(angle * 10.0) / 10.0;
qDebug() << "rotation angle: " << angle;
if (std::abs(angle) < std::numeric_limits<double>::epsilon() * 3 || std::abs(angle) > MAX_ROTATE_ANGLE)
return;
int size = std::max(result.cols, result.rows);
int fullSize = std::max(normalized.cols, normalized.rows);
Point2f pt(size/2.0f + face.x, size/2.0f + face.y);
Mat r = getRotationMatrix2D(pt, angle, 1.0);
warpAffine(normalized, rotated, r, Size(fullSize, fullSize), CV_INTER_LANCZOS4);
result = rotated(face);
}
void FacePreprocessor::ScaleFace()
{
Rect aspected = face;
if(face.width < face.height)
{
aspected.width = face.height;
}
else
{
aspected.height = face.width;
}
Mat scaled = result.clone();
copyMakeBorder(scaled, scaled, 0, aspected.height, 0, aspected.width, BORDER_REPLICATE);
aspected.x = 0;
aspected.y = 0;
result = scaled(aspected);
resize(result, result, Size(512, 512), 0.0, 0.0, CV_INTER_LANCZOS4);
}
bool FacePreprocessor::IsFaceFound() const
{
return face.width > 0 && face.height > 0;
}
bool FacePreprocessor::AreEyesFound() const
{
return gotEyes;
}
bool FacePreprocessor::IsRotated() const
{
return !rotated.empty();
}
double FacePreprocessor::GetAccuracy() const
{
double accuracy = 0.0;
if(IsFaceFound())
accuracy += 0.5;
if(AreEyesFound())
accuracy += 0.25;
if(IsRotated())
accuracy += 0.25;
return accuracy;
}
Mat FacePreprocessor::Preprocess() throw (NoFaceFoundException)
{
if(input.type() == CV_8UC3)
cvtColor(input, result, CV_BGR2GRAY);
else
result = input;
equalizeHist(result, normalized);
result = normalized;
std::vector<Rect> faces;
Size minSize(GetMinSize(), GetMinSize());
classifiers.face->detectMultiScale(result, faces, 1.1, 3, CV_HAAR_FIND_BIGGEST_OBJECT | CV_HAAR_DO_CANNY_PRUNING, minSize);
if (!faces.empty())
{
face = LargestRect(faces);
result = result(face);
}
else
{
throw NoFaceFoundException();
}
RotateFace();
ScaleFace();
return result;
}
<commit_msg>improved performance by not rotating the whole image<commit_after>#include "facepreprocessor.h"
#include <vector>
#include <algorithm>
#include <limits>
#include <cstdint>
#include <cmath>
#include <opencv2/imgproc/imgproc.hpp>
#include <QDebug>
static const double PI = std::atan(1.0) * 4;
using namespace cv;
static const bool MARK_FOUND_FEATURES = false;
FacePreprocessor::FacePreprocessor(FaceClassifiers classifiers, const Mat& input) throw(std::invalid_argument)
: input(input),
result(Mat(input.rows, input.cols, CV_8UC1)),
classifiers(classifiers)
{
if (classifiers.face.get() == nullptr)
throw std::invalid_argument("face classifier");
else if (classifiers.face->empty())
throw std::invalid_argument("face classifier");
else if (classifiers.eye.get() == nullptr)
throw std::invalid_argument("eye classifier");
else if (classifiers.eye->empty())
throw std::invalid_argument("eye classifier");
else if (classifiers.eyePair.get() == nullptr)
throw std::invalid_argument("eyepair classifier");
else if (classifiers.eyePair->empty())
throw std::invalid_argument("eyepair classifier");
else if (classifiers.eyeLeft.get() == nullptr)
throw std::invalid_argument("left eye classifier");
else if (classifiers.eyeLeft->empty())
throw std::invalid_argument("left eye classifier");
else if (classifiers.eyeRight.get() == nullptr)
throw std::invalid_argument("right eye classifier");
else if (classifiers.eyeRight->empty())
throw std::invalid_argument("right eye classifier");
else if (input.empty())
throw std::invalid_argument("input");
}
unsigned int FacePreprocessor::GetMinSize() const
{
int minDim = std::min(input.rows, input.cols);
return static_cast<unsigned int>(minDim / 5.0);
}
Rect FacePreprocessor::LargestRect(const std::vector<Rect>& rects)
{
if(rects.empty())
return Rect();
Rect largest = *std::max_element(rects.begin(), rects.end(), [](const Rect& a, const Rect& b)
{
return a.area() < b.area();
}
);
return largest;
}
const double FacePreprocessor::MAX_ROTATE_ANGLE = 25.0;
double FacePreprocessor::GetRotation(cv::Rect left, cv::Rect right)
{
Point direction;
direction.x = right.x - left.x;
direction.y = right.y - left.y;
double angle = std::atan2(direction.y, direction.x) * 180.0 / PI;
return angle;
}
std::vector<Rect> FacePreprocessor::GetEyesAlternateMethod()
{
static std::vector<Rect> empty;
std::vector<Rect> eyes;
eyes.reserve(2);
classifiers.eyePair->detectMultiScale(result, eyes, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT);
if(eyes.empty())
return empty;
qDebug() << "eye pair was found";
if (MARK_FOUND_FEATURES)
rectangle(result, eyes.front(), 1);
std::vector<Rect> lefts;
std::vector<Rect> rights;
Rect cRect = eyes.front();
cRect.width /= 2;
classifiers.eyeLeft->detectMultiScale(result(cRect), lefts, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT);
if(lefts.empty())
{
qDebug () << "left wasnt found";
return empty;
}
cRect.x += cRect.width;
classifiers.eyeLeft->detectMultiScale(result(cRect), rights, 1.1, 4, CV_HAAR_FIND_BIGGEST_OBJECT);
if(rights.empty())
{
qDebug () << "right wasnt found";
return empty;
}
rights.front().x += cRect.width;
gotEyes = true;
lefts.front().x += eyes.front().x;
lefts.front().y += eyes.front().y;
rights.front().x += eyes.front().x;
rights.front().y += eyes.front().y;
if (MARK_FOUND_FEATURES)
{
rectangle(result, lefts.front(), 1);
rectangle(result, rights.front(), 1);
}
eyes.clear();
eyes.push_back(lefts.front());
eyes.push_back(rights.front());
return eyes;
}
std::vector<Rect> FacePreprocessor::GetEyes()
{
const Rect upperHalfOfFace(face.width / 12, face.height / 5, face.width - (face.width / 6), static_cast<int>(face.height / 2.2));
const int maxSize = static_cast<int>(std::ceil(std::max(upperHalfOfFace.width, upperHalfOfFace.height) / 5.0));
const int minSize = std::max(static_cast<int>(std::floor(std::min(upperHalfOfFace.width, upperHalfOfFace.height) / 20.0)), 3);
std::vector<Rect> eyes;
std::vector<Rect> eyePairR;
//classifiers.eyePair->detectMultiScale(result(upperHalfOfFace), eyePairR, 1.1, 3, CV_HAAR_FIND_BIGGEST_OBJECT);
if(eyePairR.empty())
{
classifiers.eye->detectMultiScale(result(upperHalfOfFace), eyes, 1.05, 6, 0, Size(minSize, minSize), Size(maxSize, maxSize));
}
else
{
classifiers.eye->detectMultiScale(result(eyePairR.front()), eyes, 1.1, 6, 0, Size(minSize, minSize), Size(maxSize, maxSize));
if (MARK_FOUND_FEATURES)
rectangle(result, eyePairR.front(), 255);
}
for (auto eye : eyes)
{
if(!eyePairR.empty())
{
eye.x += eyePairR.front().x;
eye.y += eyePairR.front().y;
}
else
{
eye.x += upperHalfOfFace.x;
eye.y += upperHalfOfFace.y;
}
if (MARK_FOUND_FEATURES)
rectangle(result, eye, 1);
}
// removing intersecting objects
for(uint8_t i = 0; i < eyes.size(); i++)
{
for(uint8_t j = 0; j < eyes.size(); j++)
{
if (i != j)
{
Rect intersection = eyes[i] & eyes[j];
if (intersection.area() > 0)
{
eyes.erase(eyes.begin() + j);
if (i > j)
i--;
j--;
}
}
}
}
if(eyes.size() < 2)
{
qDebug() << "only" << eyes.size() << "eyes were found";
eyes.clear();
return eyes;
}
gotEyes = true;
if(eyes.size() > 2)
{
// finding the pair with lowest angle
std::vector<std::pair<uint16_t, uint16_t>> helper;
helper.reserve(eyes.size() * eyes.size() - eyes.size());
for(auto i = eyes.begin(); i != eyes.end(); i++)
{
for(auto j = eyes.begin(); j != eyes.end(); j++)
{
if (i != j)
helper.push_back(std::make_pair(std::distance(eyes.begin(), i), std::distance(eyes.begin(), j)));
}
}
std::sort(helper.begin(), helper.end(), [&eyes](const std::pair<uint16_t, uint16_t>& a, const std::pair<uint16_t, uint16_t>& b)
{
double angleA = std::abs(GetRotation(eyes[a.first], eyes[a.second]));
double angleB = std::abs(GetRotation(eyes[b.first], eyes[b.second]));
return angleA < angleB;
});
assert(helper.front().first != helper.front().second);
std::swap(eyes[0], eyes[helper.front().first]);
std::swap(eyes[1], eyes[helper.front().second]);
}
std::sort(eyes.begin(), eyes.begin() + 2, [](const Rect& a, const Rect& b) { return a.x < b.x; });
eyes.resize(2);
return eyes;
}
void FacePreprocessor::RotateFace()
{
std::vector<Rect> eyes = GetEyes();
if(eyes.size() < 2)
{
return;
}
double angle = GetRotation(eyes[0], eyes[1]);
angle = std::round(angle * 10.0) / 10.0;
qDebug() << "rotation angle: " << angle;
if (std::abs(angle) < std::numeric_limits<double>::epsilon() * 3 || std::abs(angle) > MAX_ROTATE_ANGLE)
return;
Point2f ptOnFullFrame(face.width / 2.0f + face.x, face.height / 2.0f + face.y);
//Mat r = getRotationMatrix2D(ptOnFullFrame, angle, 1.0);
RotatedRect rr(ptOnFullFrame, Size2f(face.width, face.height), angle);
Rect boundingBox = rr.boundingRect();
// create border
{
int top = -std::min(0, boundingBox.y);
int bottom = std::max(0, std::max(0, boundingBox.y) + boundingBox.height - normalized.rows);
int left = -std::min(0, boundingBox.x);
int right = std::max(0, std::max(0, boundingBox.x) + boundingBox.width - normalized.cols);
qDebug () << top << bottom << left << right;
copyMakeBorder(normalized, normalized, top, bottom, left, right, BORDER_REPLICATE);
boundingBox.x += left;
boundingBox.y += right;
}
//copyMakeBorder(normalized, normalized, boundingBox.height, boundingBox.height, boundingBox.width, boundingBox.width, BORDER_REPLICATE);
//warpAffine(normalized, rotated, r, Size(fullSize, fullSize), CV_INTER_LANCZOS4);
rotated = normalized(boundingBox);
Mat rotationMatrix = getRotationMatrix2D(Point2f(boundingBox.width / 2.0f, boundingBox.height / 2.0f), angle, 1.0);
warpAffine(rotated, rotated, rotationMatrix, boundingBox.size(), CV_INTER_LANCZOS4);
Rect faceTmp = face;
faceTmp.x = (boundingBox.width - face.width) / 2;
faceTmp.y = (boundingBox.height - face.height) / 2;
result = rotated(faceTmp);
}
void FacePreprocessor::ScaleFace()
{
Rect aspected = face;
if(face.width < face.height)
{
aspected.width = face.height;
}
else
{
aspected.height = face.width;
}
Mat scaled = result.clone();
copyMakeBorder(scaled, scaled, 0, aspected.height, 0, aspected.width, BORDER_REPLICATE);
aspected.x = 0;
aspected.y = 0;
result = scaled(aspected);
resize(result, result, Size(512, 512), 0.0, 0.0, CV_INTER_LANCZOS4);
}
bool FacePreprocessor::IsFaceFound() const
{
return face.width > 0 && face.height > 0;
}
bool FacePreprocessor::AreEyesFound() const
{
return gotEyes;
}
bool FacePreprocessor::IsRotated() const
{
return !rotated.empty();
}
double FacePreprocessor::GetAccuracy() const
{
double accuracy = 0.0;
if(IsFaceFound())
accuracy += 0.5;
if(AreEyesFound())
accuracy += 0.25;
if(IsRotated())
accuracy += 0.25;
return accuracy;
}
Mat FacePreprocessor::Preprocess() throw (NoFaceFoundException)
{
if(input.type() == CV_8UC3)
cvtColor(input, result, CV_BGR2GRAY);
else
result = input;
equalizeHist(result, normalized);
result = normalized;
std::vector<Rect> faces;
Size minSize(GetMinSize(), GetMinSize());
classifiers.face->detectMultiScale(result, faces, 1.1, 3, CV_HAAR_FIND_BIGGEST_OBJECT | CV_HAAR_DO_CANNY_PRUNING, minSize);
if (!faces.empty())
{
face = LargestRect(faces);
result = result(face);
}
else
{
throw NoFaceFoundException();
}
RotateFace();
ScaleFace();
return result;
}
<|endoftext|>
|
<commit_before>/** \copyright
* Copyright (c) 2017, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file CDIUtils.hxx
*
* Utility library for interpreting CDI XML files.
*
* @author Balazs Racz
* @date 31 Aug 2017
*/
#ifndef _OPENLCB_CDIUTILS_HXX_
#define _OPENLCB_CDIUTILS_HXX_
#include "sxmlc.h"
namespace openlcb
{
class CDIUtils
{
public:
/// Helper class for unique_ptr to delete an XML document correctly.
struct XMLDocDeleter
{
/// Deletion operator. @param doc the object to be freed.
void operator()(XMLDoc *doc)
{
if (!doc)
return;
cleanup_doc(doc);
XMLDoc_free(doc);
delete doc;
}
};
/// Smart pointer class for holding XML documents.
typedef std::unique_ptr<XMLDoc, XMLDocDeleter> xmldoc_ptr_t;
/// Helper class for deleting sxml strings.
struct SXmlStringDeleter
{
/// Deletion operator. @param data the SXML string to be freed.
void operator()(const SXML_CHAR *data)
{
free(const_cast<SXML_CHAR *>(data));
}
};
/// Smart pointer class for holding C strings from sxml. Appropriately
/// frees the string upon going out of scope.
typedef std::unique_ptr<const SXML_CHAR, SXmlStringDeleter> xmlstring_t;
/// Searches the list of children for the first child with a specific tag.
/// @param parent is the node whose children to search.
/// @param tag is which child to look for.
/// @return nullptr if not found, else the first occurrence of tag in the
/// children.
static XMLNode *find_child_or_null(const XMLNode *parent, const char *tag)
{
auto count = XMLNode_get_children_count(parent);
for (int i = 0; i < count; ++i)
{
auto *c = XMLNode_get_child(parent, i);
if (strcmp(tag, c->tag) == 0)
return c;
}
return nullptr;
}
/// Finds the name of a CDI element.
///
/// @param node is a CDI element (segment, group, or config element).
/// @param def is the default to return if no <name> element exists or if
/// it has no text.
/// @return finds a child tag <name> and returns its contents. Returns
/// empty string if no <name> was found.
static string find_node_name(const XMLNode *node, const char *def)
{
auto *n = find_child_or_null(node, "name");
if (n == nullptr || n->text == nullptr)
return def;
return n->text;
}
/// Find the description of a CDI element.
///
/// @param node is a CDI element (segment, group, or config element).
/// @return finds a child tag <description> and returns its
/// contents. Returns empty string if no <description> was found.
static string find_node_description(const XMLNode *node)
{
auto *n = find_child_or_null(node, "description");
if (n == nullptr || n->text == nullptr)
return "";
return n->text;
}
/// Clears out al luserinfo structure pointers. This is necessary to use
/// the new_userinfo call below. Call this after the XML has been
/// successfully parsed.
/// @param doc document to prepare up.
static void prepare_doc(XMLDoc *doc)
{
auto *node = XMLDoc_root(doc);
while (node)
{
node->user = nullptr;
node = XMLNode_next(node);
}
}
/// Deletes all userinfo structures allocated in a doc.
/// @param doc document to clean up.
static void cleanup_doc(XMLDoc *doc)
{
auto *node = XMLDoc_root(doc);
while (node)
{
free(node->user);
node->user = nullptr;
node = XMLNode_next(node);
}
}
/// Allocates a new object of type T for the node as userinfo; calls T's
/// constructor with args..., stores the resulting pointer in the userinfo
/// pointer of node.
/// @param info output argument for the userinfo structure pointer.
/// @param node which XML node the userinfo should point at.
/// @param args... forwarded as the constructor arguments for T (can be
/// empty).
template <class T, typename... Args>
static void new_userinfo(T **info, XMLNode *node, Args &&... args)
{
HASSERT(node->user == nullptr);
static_assert(std::is_trivially_destructible<T>::value == true,
"Userdata attached to nodes must be trivially destructible");
*info = static_cast<T *>(malloc(sizeof(T)));
new (*info) T(std::forward<Args>(args)...);
node->user = *info;
}
/// Retrieve the userinfo structure from an XML node.
/// @param info will be set to the userinfo structure using an unchecked
/// cast to T. This variable must be of the same (or compatible) type as
/// what the userinfo has been allocated to.
/// @param node is the XML element node whose userinfo we are trying to
/// fetch
template <class T> static void get_userinfo(T **info, const XMLNode *node)
{
HASSERT(node);
*info = static_cast<T *>(node->user);
}
/// Allocation data we hold about a Data Element in its userinfo structure.
struct NodeInfo
{
/// Offset of the address of this element from the address of the
/// parent group element. This is the sum of size values of the
/// preceding elements within the given group. Inside a repeated group
/// these offsets are counted from the current repetition start offset.
int offset_from_parent = 0;
/// Total number of bytes that this element occupies. This includes all
/// repetitions for a repeated group.
int size = 0;
};
/// Helper function to find and convert an attribute to a number.
/// @param node is the XML node of the element whose attribute we're looking
/// for
/// @param attr_name is a C-string for the attribute name we're looking for
/// @param def is the default value that will be returned if the attribute
/// is not found.
/// @return attribute value, or `def` if not found, or zero if the
/// attribute is found but the value is not convertible to an integer.
static int get_numeric_attribute(
const XMLNode *node, const char *attr_name, int def = 0)
{
const SXML_CHAR *attr_value;
XMLNode_get_attribute_with_default(
const_cast<XMLNode *>(node), attr_name, &attr_value, nullptr);
xmlstring_t d(attr_value);
if ((!attr_value) || (attr_value[0] == 0))
{
return def;
}
return atoi(attr_value);
}
/// Used to classify elements.
enum class DataType {
UNKNOWN = 0,
GROUP,
INT,
FLOAT,
STRING,
EVENTID
};
/// Classifies XML elements to node types.
/// @param child is an XML element under a group.
/// @return node type or UNKNOWN
static DataType get_type_from_node(XMLNode *child)
{
if (strcmp(child->tag, "group") == 0)
{
return DataType::GROUP;
}
if (strcmp(child->tag, "int") == 0)
{
return DataType::INT;
}
if (strcmp(child->tag, "eventid") == 0)
{
return DataType::EVENTID;
}
if (strcmp(child->tag, "string") == 0)
{
return DataType::STRING;
}
if (strcmp(child->tag, "float") == 0)
{
return DataType::FLOAT;
}
return DataType::UNKNOWN;
};
/// Allocates all userinfo structures within a segment and performs the
/// offset layout algorithm.
/// @param segment is the XML node of the <segment> element.
static void layout_segment(XMLNode *segment)
{
HASSERT(strcmp(segment->tag, "segment") == 0);
unsigned current_offset = get_numeric_attribute(segment, "origin");
NodeInfo *info;
new_userinfo(&info, segment);
info->offset_from_parent = current_offset;
if (XMLNode_get_children_count(segment) == 0)
return;
XMLNode *current_parent = segment;
XMLNode *current_child = XMLNode_get_child(segment, 0);
NodeInfo *parent_info = info;
while (true)
{
if (strcmp(current_child->tag, "name") == 0 ||
strcmp(current_child->tag, "description") == 0 ||
strcmp(current_child->tag, "repname") == 0)
{
// Do nothing, not a data element
}
else
{
new_userinfo(&info, current_child);
parent_info->size +=
get_numeric_attribute(current_child, "offset", 0);
info->offset_from_parent = parent_info->size;
auto type = get_type_from_node(current_child);
switch (type)
{
case DataType::UNKNOWN:
// Probably should not get here.
break;
case DataType::EVENTID:
info->size = 8;
break;
case DataType::STRING:
case DataType::INT:
case DataType::FLOAT:
info->size =
get_numeric_attribute(current_child, "size", 1);
break;
case DataType::GROUP:
if (XMLNode_get_children_count(current_child) > 0)
{
current_parent = current_child;
current_child =
XMLNode_get_child(current_parent, 0);
get_userinfo(&parent_info, current_parent);
continue;
}
// an empty group has size == 0 and we don't need to do
// anything here.
break;
}
parent_info->size += info->size;
}
// Move to next child.
while ((current_child = XMLNode_next_sibling(current_child)) ==
nullptr)
{
// End of children; must go up.
if (current_parent == segment)
{
// nowhere to go up
break;
}
current_child = current_parent;
current_parent = current_child->father;
// handle groups with repetitions
get_userinfo(&info, current_child);
get_userinfo(&parent_info, current_parent);
int repcount = get_replication(current_child);
info->size *= repcount;
parent_info->size += info->size;
}
if (current_parent == segment && current_child == nullptr)
{
// end of iteration
break;
}
}
}
/// @return the number of replicas a group has, if it is a repeated group,
/// or 1 if it is a non-repeated group.
/// @param group is the XML node of the <group> element to query.
static int get_replication(const XMLNode *group)
{
HASSERT(strcmp(group->tag, "group") == 0);
return get_numeric_attribute(group, "replication", 1);
}
struct CDINodeRep
{
/// Element in the XML where we are. This is a segment or a group node.
const XMLNode *node_;
/// address in the current space of the beginning of the current
/// node. For segments, this is the origin; for groups this is the
/// address of the virtual zero-length data element at the beginning of
/// the group. For repeated groups this is meaningful only with a given
/// repetition of a group.
unsigned address_;
/// Default constructor. Probably should not be used; maybe only for
/// the root of the CDI which is not inside any segment.
CDINodeRep()
: node_(nullptr)
, address_(0)
{
}
/// Initializes a group rep from an arbitrary XML element (e.g. the cdi
/// root). Tihs does not allow child computations.
/// @param node is the XML element.
CDINodeRep(const XMLNode *node, std::nullptr_t)
: node_(node)
, address_(0)
{
}
/// Initializes a group rep from a segment root.
/// @param segment is the XML element representing the segment root.
CDINodeRep(const XMLNode *segment)
{
NodeInfo *info;
get_userinfo(&info, segment);
HASSERT(info);
node_ = segment;
address_ = info->offset_from_parent;
}
/// Initializes a group rep which has no replication.
/// @param parent is the Node representation of the parent group or
/// segment.
/// @param group is the XML element for the current (child) group. it
/// must have no replication.
CDINodeRep(const CDINodeRep *parent, const XMLNode *group)
{
HASSERT(group->father == parent->node_);
node_ = group;
HASSERT(get_replication(group) == 1);
address_ = parent->get_child_address(group);
}
/// Initializes a group rep for a given replica.
/// @param parent is the Node representation of the parent group or
/// segment.
/// @param group is the XML element for the current (child) group. it
/// must have replication.
/// @param replica is the number of the replication (zero to
/// replication - 1).
CDINodeRep(const CDINodeRep *parent, const XMLNode *group, unsigned replica)
{
HASSERT(group->father == parent->node_);
node_ = group;
int replication = get_replication(group);
HASSERT(replication > 1);
NodeInfo *info;
get_userinfo(&info, group);
HASSERT(info);
unsigned base_address = parent->get_child_address(group);
unsigned stride = info->size / replication;
address_ = base_address + stride * replica;
}
/// Resets the current representation. Use any constructor argument
/// set.
template <typename... Args> void reset(Args &&... args)
{
new (this) CDINodeRep(std::forward<Args>(args)...);
}
/// Gets the absolute address of a given child in the current segment.
/// @param child an element which is a child of node_
/// @return the absolute address within the CDI segment of child.
unsigned get_child_address(const XMLNode *child) const
{
HASSERT(child->father == node_);
NodeInfo *info;
get_userinfo(&info, child);
HASSERT(info);
return address_ + info->offset_from_parent;
}
/// Gets the size of a child (number of bytes occupied).
unsigned get_child_size(const XMLNode *child) const
{
HASSERT(child->father == node_);
NodeInfo *info;
get_userinfo(&info, child);
HASSERT(info);
return info->size;
}
};
private:
/// Static class; never instantiated.
CDIUtils();
};
} // namespace openlcb
#endif // _OPENLCB_CDIUTILS_HXX_
<commit_msg>Updates CDINodeRep constructor to be able to deal with creating a rep for a single individual variable.<commit_after>/** \copyright
* Copyright (c) 2017, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file CDIUtils.hxx
*
* Utility library for interpreting CDI XML files.
*
* @author Balazs Racz
* @date 31 Aug 2017
*/
#ifndef _OPENLCB_CDIUTILS_HXX_
#define _OPENLCB_CDIUTILS_HXX_
#include "sxmlc.h"
namespace openlcb
{
class CDIUtils
{
public:
/// Helper class for unique_ptr to delete an XML document correctly.
struct XMLDocDeleter
{
/// Deletion operator. @param doc the object to be freed.
void operator()(XMLDoc *doc)
{
if (!doc)
return;
cleanup_doc(doc);
XMLDoc_free(doc);
delete doc;
}
};
/// Smart pointer class for holding XML documents.
typedef std::unique_ptr<XMLDoc, XMLDocDeleter> xmldoc_ptr_t;
/// Helper class for deleting sxml strings.
struct SXmlStringDeleter
{
/// Deletion operator. @param data the SXML string to be freed.
void operator()(const SXML_CHAR *data)
{
free(const_cast<SXML_CHAR *>(data));
}
};
/// Smart pointer class for holding C strings from sxml. Appropriately
/// frees the string upon going out of scope.
typedef std::unique_ptr<const SXML_CHAR, SXmlStringDeleter> xmlstring_t;
/// Searches the list of children for the first child with a specific tag.
/// @param parent is the node whose children to search.
/// @param tag is which child to look for.
/// @return nullptr if not found, else the first occurrence of tag in the
/// children.
static XMLNode *find_child_or_null(const XMLNode *parent, const char *tag)
{
auto count = XMLNode_get_children_count(parent);
for (int i = 0; i < count; ++i)
{
auto *c = XMLNode_get_child(parent, i);
if (strcmp(tag, c->tag) == 0)
return c;
}
return nullptr;
}
/// Finds the name of a CDI element.
///
/// @param node is a CDI element (segment, group, or config element).
/// @param def is the default to return if no <name> element exists or if
/// it has no text.
/// @return finds a child tag <name> and returns its contents. Returns
/// empty string if no <name> was found.
static string find_node_name(const XMLNode *node, const char *def)
{
auto *n = find_child_or_null(node, "name");
if (n == nullptr || n->text == nullptr)
return def;
return n->text;
}
/// Find the description of a CDI element.
///
/// @param node is a CDI element (segment, group, or config element).
/// @return finds a child tag <description> and returns its
/// contents. Returns empty string if no <description> was found.
static string find_node_description(const XMLNode *node)
{
auto *n = find_child_or_null(node, "description");
if (n == nullptr || n->text == nullptr)
return "";
return n->text;
}
/// Clears out al luserinfo structure pointers. This is necessary to use
/// the new_userinfo call below. Call this after the XML has been
/// successfully parsed.
/// @param doc document to prepare up.
static void prepare_doc(XMLDoc *doc)
{
auto *node = XMLDoc_root(doc);
while (node)
{
node->user = nullptr;
node = XMLNode_next(node);
}
}
/// Deletes all userinfo structures allocated in a doc.
/// @param doc document to clean up.
static void cleanup_doc(XMLDoc *doc)
{
auto *node = XMLDoc_root(doc);
while (node)
{
free(node->user);
node->user = nullptr;
node = XMLNode_next(node);
}
}
/// Allocates a new object of type T for the node as userinfo; calls T's
/// constructor with args..., stores the resulting pointer in the userinfo
/// pointer of node.
/// @param info output argument for the userinfo structure pointer.
/// @param node which XML node the userinfo should point at.
/// @param args... forwarded as the constructor arguments for T (can be
/// empty).
template <class T, typename... Args>
static void new_userinfo(T **info, XMLNode *node, Args &&... args)
{
HASSERT(node->user == nullptr);
static_assert(std::is_trivially_destructible<T>::value == true,
"Userdata attached to nodes must be trivially destructible");
*info = static_cast<T *>(malloc(sizeof(T)));
new (*info) T(std::forward<Args>(args)...);
node->user = *info;
}
/// Retrieve the userinfo structure from an XML node.
/// @param info will be set to the userinfo structure using an unchecked
/// cast to T. This variable must be of the same (or compatible) type as
/// what the userinfo has been allocated to.
/// @param node is the XML element node whose userinfo we are trying to
/// fetch
template <class T> static void get_userinfo(T **info, const XMLNode *node)
{
HASSERT(node);
*info = static_cast<T *>(node->user);
}
/// Allocation data we hold about a Data Element in its userinfo structure.
struct NodeInfo
{
/// Offset of the address of this element from the address of the
/// parent group element. This is the sum of size values of the
/// preceding elements within the given group. Inside a repeated group
/// these offsets are counted from the current repetition start offset.
int offset_from_parent = 0;
/// Total number of bytes that this element occupies. This includes all
/// repetitions for a repeated group.
int size = 0;
};
/// Helper function to find and convert an attribute to a number.
/// @param node is the XML node of the element whose attribute we're looking
/// for
/// @param attr_name is a C-string for the attribute name we're looking for
/// @param def is the default value that will be returned if the attribute
/// is not found.
/// @return attribute value, or `def` if not found, or zero if the
/// attribute is found but the value is not convertible to an integer.
static int get_numeric_attribute(
const XMLNode *node, const char *attr_name, int def = 0)
{
const SXML_CHAR *attr_value;
XMLNode_get_attribute_with_default(
const_cast<XMLNode *>(node), attr_name, &attr_value, nullptr);
xmlstring_t d(attr_value);
if ((!attr_value) || (attr_value[0] == 0))
{
return def;
}
return atoi(attr_value);
}
/// Used to classify elements.
enum class DataType {
UNKNOWN = 0,
GROUP,
INT,
FLOAT,
STRING,
EVENTID
};
/// Classifies XML elements to node types.
/// @param child is an XML element under a group.
/// @return node type or UNKNOWN
static DataType get_type_from_node(XMLNode *child)
{
if (strcmp(child->tag, "group") == 0)
{
return DataType::GROUP;
}
if (strcmp(child->tag, "int") == 0)
{
return DataType::INT;
}
if (strcmp(child->tag, "eventid") == 0)
{
return DataType::EVENTID;
}
if (strcmp(child->tag, "string") == 0)
{
return DataType::STRING;
}
if (strcmp(child->tag, "float") == 0)
{
return DataType::FLOAT;
}
return DataType::UNKNOWN;
};
/// Allocates all userinfo structures within a segment and performs the
/// offset layout algorithm.
/// @param segment is the XML node of the <segment> element.
static void layout_segment(XMLNode *segment)
{
HASSERT(strcmp(segment->tag, "segment") == 0);
unsigned current_offset = get_numeric_attribute(segment, "origin");
NodeInfo *info;
new_userinfo(&info, segment);
info->offset_from_parent = current_offset;
if (XMLNode_get_children_count(segment) == 0)
return;
XMLNode *current_parent = segment;
XMLNode *current_child = XMLNode_get_child(segment, 0);
NodeInfo *parent_info = info;
while (true)
{
if (strcmp(current_child->tag, "name") == 0 ||
strcmp(current_child->tag, "description") == 0 ||
strcmp(current_child->tag, "repname") == 0)
{
// Do nothing, not a data element
}
else
{
new_userinfo(&info, current_child);
parent_info->size +=
get_numeric_attribute(current_child, "offset", 0);
info->offset_from_parent = parent_info->size;
auto type = get_type_from_node(current_child);
switch (type)
{
case DataType::UNKNOWN:
// Probably should not get here.
break;
case DataType::EVENTID:
info->size = 8;
break;
case DataType::STRING:
case DataType::INT:
case DataType::FLOAT:
info->size =
get_numeric_attribute(current_child, "size", 1);
break;
case DataType::GROUP:
if (XMLNode_get_children_count(current_child) > 0)
{
current_parent = current_child;
current_child =
XMLNode_get_child(current_parent, 0);
get_userinfo(&parent_info, current_parent);
continue;
}
// an empty group has size == 0 and we don't need to do
// anything here.
break;
}
parent_info->size += info->size;
}
// Move to next child.
while ((current_child = XMLNode_next_sibling(current_child)) ==
nullptr)
{
// End of children; must go up.
if (current_parent == segment)
{
// nowhere to go up
break;
}
current_child = current_parent;
current_parent = current_child->father;
// handle groups with repetitions
get_userinfo(&info, current_child);
get_userinfo(&parent_info, current_parent);
int repcount = get_replication(current_child);
info->size *= repcount;
parent_info->size += info->size;
}
if (current_parent == segment && current_child == nullptr)
{
// end of iteration
break;
}
}
}
/// @return the number of replicas a group has, if it is a repeated group,
/// or 1 if it is a non-repeated group.
/// @param group is the XML node of the <group> element to query.
static int get_replication(const XMLNode *group)
{
HASSERT(strcmp(group->tag, "group") == 0);
return get_numeric_attribute(group, "replication", 1);
}
struct CDINodeRep
{
/// Element in the XML where we are. This is a segment or a group node.
const XMLNode *node_;
/// address in the current space of the beginning of the current
/// node. For segments, this is the origin; for groups this is the
/// address of the virtual zero-length data element at the beginning of
/// the group. For repeated groups this is meaningful only with a given
/// repetition of a group.
unsigned address_;
/// Default constructor. Probably should not be used; maybe only for
/// the root of the CDI which is not inside any segment.
CDINodeRep()
: node_(nullptr)
, address_(0)
{
}
/// Initializes a group rep from an arbitrary XML element (e.g. the cdi
/// root). Tihs does not allow child computations.
/// @param node is the XML element.
CDINodeRep(const XMLNode *node, std::nullptr_t)
: node_(node)
, address_(0)
{
}
/// Initializes a group rep from a segment root.
/// @param segment is the XML element representing the segment root.
CDINodeRep(const XMLNode *segment)
{
NodeInfo *info;
get_userinfo(&info, segment);
HASSERT(info);
node_ = segment;
address_ = info->offset_from_parent;
}
/// Initializes a group rep which has no replication or an entry rep.
/// @param parent is the Node representation of the parent group or
/// segment.
/// @param child is the XML element for the current (child). If it is a
/// group, it must have no replication.
CDINodeRep(const CDINodeRep *parent, const XMLNode *child)
{
HASSERT(child->father == parent->node_);
node_ = child;
if (strcmp(child->tag, "group") == 0)
{
HASSERT(get_replication(child) == 1);
}
address_ = parent->get_child_address(child);
}
/// Initializes a group rep for a given replica.
/// @param parent is the Node representation of the parent group or
/// segment.
/// @param group is the XML element for the current (child) group. it
/// must have replication.
/// @param replica is the number of the replication (zero to
/// replication - 1).
CDINodeRep(const CDINodeRep *parent, const XMLNode *group, unsigned replica)
{
HASSERT(group->father == parent->node_);
node_ = group;
int replication = get_replication(group);
HASSERT(replication > 1);
NodeInfo *info;
get_userinfo(&info, group);
HASSERT(info);
unsigned base_address = parent->get_child_address(group);
unsigned stride = info->size / replication;
address_ = base_address + stride * replica;
}
/// Resets the current representation. Use any constructor argument
/// set.
template <typename... Args> void reset(Args &&... args)
{
new (this) CDINodeRep(std::forward<Args>(args)...);
}
/// Gets the absolute address of a given child in the current segment.
/// @param child an element which is a child of node_
/// @return the absolute address within the CDI segment of child.
unsigned get_child_address(const XMLNode *child) const
{
HASSERT(child->father == node_);
NodeInfo *info;
get_userinfo(&info, child);
HASSERT(info);
return address_ + info->offset_from_parent;
}
/// Gets the size of a child (number of bytes occupied).
unsigned get_child_size(const XMLNode *child) const
{
HASSERT(child->father == node_);
NodeInfo *info;
get_userinfo(&info, child);
HASSERT(info);
return info->size;
}
};
private:
/// Static class; never instantiated.
CDIUtils();
};
} // namespace openlcb
#endif // _OPENLCB_CDIUTILS_HXX_
<|endoftext|>
|
<commit_before><commit_msg>170. Two Sum III - Data structure design<commit_after><|endoftext|>
|
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgText/FadeText>
#include <osg/Notify>
#include <osg/io_utils>
#include <OpenThreads/Mutex>
#include <OpenThreads/ScopedLock>
using namespace osgText;
struct FadeTextData : public osg::Referenced
{
FadeTextData(FadeText* fadeText=0):
_fadeText(fadeText),
_visible(true) {}
bool operator < (const FadeTextData& rhs) const
{
return _fadeText < rhs._fadeText;
}
double getNearestZ() const
{
double nearestZ = _vertices[0].z();
if (nearestZ < _vertices[1].z()) nearestZ = _vertices[1].z();
if (nearestZ < _vertices[2].z()) nearestZ = _vertices[2].z();
if (nearestZ < _vertices[3].z()) nearestZ = _vertices[3].z();
// OSG_NOTICE<<"getNearestZ()="<<_fadeText->getText().createUTF8EncodedString()<<" "<<nearestZ<<std::endl;
return nearestZ;
}
FadeText* _fadeText;
osg::Vec3d _vertices[4];
bool _visible;
};
struct FadeTextPolytopeData : public FadeTextData, public osg::Polytope
{
FadeTextPolytopeData(FadeTextData& fadeTextData):
FadeTextData(fadeTextData)
{
_referenceVertexList.push_back(_vertices[0]);
_referenceVertexList.push_back(_vertices[1]);
_referenceVertexList.push_back(_vertices[2]);
_referenceVertexList.push_back(_vertices[3]);
}
void addEdgePlane(const osg::Vec3& corner, const osg::Vec3& edge)
{
osg::Vec3 normal( edge.y(), -edge.x(), 0.0f);
normal.normalize();
add(osg::Plane(normal, corner));
}
void buildPolytope()
{
osg::Vec3d edge01 = _vertices[1] - _vertices[0];
osg::Vec3d edge12 = _vertices[2] - _vertices[1];
osg::Vec3d normalFrontFace = edge01 ^ edge12;
bool needToFlip = normalFrontFace.z()>0.0f;
normalFrontFace.normalize();
add(osg::Plane(normalFrontFace, _vertices[0]));
add(osg::Plane( osg::Vec3d(0.0f,0.0f,0.0f), _vertices[0], _vertices[1]));
add(osg::Plane( osg::Vec3d(0.0f,0.0f,0.0f), _vertices[1], _vertices[2]));
add(osg::Plane( osg::Vec3d(0.0f,0.0f,0.0f), _vertices[2], _vertices[3]));
add(osg::Plane( osg::Vec3d(0.0f,0.0f,0.0f), _vertices[3], _vertices[0]));
#if 0
OSG_NOTICE<<" normalFrontFace = "<<normalFrontFace<<std::endl;
OSG_NOTICE<<" edge01 = "<<edge01<<std::endl;
OSG_NOTICE<<" edge12 = "<<edge12<<std::endl;
OSG_NOTICE<<" _vertices[0]= "<<_vertices[0]<<std::endl;
OSG_NOTICE<<" _vertices[1]= "<<_vertices[1]<<std::endl;
OSG_NOTICE<<" _vertices[2]= "<<_vertices[2]<<std::endl;
OSG_NOTICE<<" _vertices[3]= "<<_vertices[3]<<std::endl;
#endif
if (needToFlip) flip();
#if 0
OSG_NOTICE<<" plane 0 "<< _planeList[0]<<std::endl;
OSG_NOTICE<<" plane 1 "<< _planeList[1]<<std::endl;
OSG_NOTICE<<" plane 2 "<< _planeList[2]<<std::endl;
OSG_NOTICE<<" plane 3 "<< _planeList[3]<<std::endl;
OSG_NOTICE<<" plane 4 "<< _planeList[4]<<std::endl;
#endif
}
inline bool contains(const std::vector<osg::Vec3>& vertices)
{
for(std::vector<osg::Vec3>::const_iterator itr = vertices.begin();
itr != vertices.end();
++itr)
{
if (osg::Polytope::contains(*itr))
{
return true;
}
}
return false;
}
};
struct FadeTextUserData : public osg::Referenced
{
FadeTextUserData():
_frameNumber(0) {}
typedef std::list<FadeTextData> FadeTextList;
unsigned int _frameNumber;
FadeTextList _fadeTextInView;
};
struct GlobalFadeText : public osg::Referenced
{
typedef std::set< osg::ref_ptr<FadeTextUserData> > UserDataSet;
typedef std::set<FadeText*> FadeTextSet;
typedef std::multimap<double, osg::ref_ptr<FadeTextPolytopeData> > FadeTextPolytopeMap;
typedef std::map<osg::View*, UserDataSet> ViewUserDataMap;
typedef std::map<osg::View*, FadeTextSet > ViewFadeTextMap;
GlobalFadeText():
_frameNumber(0xffffffff)
{
}
FadeTextUserData* createNewFadeTextUserData(osg::View* view)
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
FadeTextUserData* userData = new FadeTextUserData;
if (!userData)
{
OSG_NOTICE<<"Memory error, unable to create FadeTextUserData."<<std::endl;
return 0;
}
_viewMap[view].insert(userData);
return userData;
}
void update(unsigned int frameNumber)
{
_frameNumber = frameNumber;
for(GlobalFadeText::ViewUserDataMap::iterator vitr = _viewMap.begin();
vitr != _viewMap.end();
++vitr)
{
osg::View* view = vitr->first;
FadeTextSet& fadeTextSet = _viewFadeTextMap[view];
fadeTextSet.clear();
FadeTextPolytopeMap fadeTextPolytopeMap;
for(GlobalFadeText::UserDataSet::iterator uitr = vitr->second.begin();
uitr != vitr->second.end();
++uitr)
{
FadeTextUserData* userData = uitr->get();
int frameDelta = frameNumber - userData->_frameNumber;
if (frameDelta<=1)
{
for(FadeTextUserData::FadeTextList::iterator fitr = userData->_fadeTextInView.begin();
fitr != userData->_fadeTextInView.end();
++fitr)
{
FadeTextData& fadeTextData = *fitr;
if (fadeTextSet.count(fadeTextData._fadeText)==0)
{
fadeTextSet.insert(fadeTextData._fadeText);
fadeTextPolytopeMap.insert(FadeTextPolytopeMap::value_type(
-fadeTextData.getNearestZ(), new FadeTextPolytopeData(fadeTextData)));
}
}
}
}
// for each FadeTexPoltopeData
// create polytopes
// test against all FTPD's later in the list
// test all control points on FTPD against each plane of the current polytope
// if all control points removed or outside then discard FTPD and make FT visible = false;
FadeTextPolytopeMap::iterator outer_itr = fadeTextPolytopeMap.begin();
while (outer_itr != fadeTextPolytopeMap.end())
{
FadeTextPolytopeMap::iterator inner_itr = outer_itr;
++inner_itr;
if (inner_itr == fadeTextPolytopeMap.end()) break;
FadeTextPolytopeData& outer_ftpm = *(outer_itr->second);
outer_ftpm.buildPolytope();
// OSG_NOTICE<<"Outer z "<<outer_ftpm.getNearestZ()<<std::endl;
while(inner_itr != fadeTextPolytopeMap.end())
{
FadeTextPolytopeData& inner_ftpm = *(inner_itr->second);
// OSG_NOTICE<<"Inner z "<<inner_ftpm.getNearestZ()<<std::endl;
if (outer_ftpm.contains(inner_ftpm.getReferenceVertexList()))
{
FadeTextPolytopeMap::iterator erase_itr = inner_itr;
// move to next ftpm
++inner_itr;
fadeTextSet.erase(inner_ftpm._fadeText);
// need to remove inner_ftpm as its occluded.
fadeTextPolytopeMap.erase(erase_itr);
}
else
{
// move to next ftpm
++inner_itr;
}
}
++outer_itr;
}
}
}
inline void updateIfRequired(unsigned int frameNumber)
{
if (_frameNumber!=frameNumber) update(frameNumber);
}
unsigned int _frameNumber;
OpenThreads::Mutex _mutex;
ViewUserDataMap _viewMap;
ViewFadeTextMap _viewFadeTextMap;
};
GlobalFadeText* getGlobalFadeText()
{
static osg::ref_ptr<GlobalFadeText> s_globalFadeText = new GlobalFadeText;
return s_globalFadeText.get();
}
struct FadeText::FadeTextUpdateCallback : public osg::DrawableUpdateCallback
{
FadeTextData _ftd;
virtual void update(osg::NodeVisitor* nv, osg::Drawable* drawable)
{
osgText::FadeText* fadeText = dynamic_cast<osgText::FadeText*>(drawable);
if (!fadeText) return;
unsigned int frameNumber = nv->getFrameStamp()->getFrameNumber();
GlobalFadeText* gft = getGlobalFadeText();
gft->updateIfRequired(frameNumber);
osgText::FadeText::ViewBlendColourMap& vbcm = fadeText->getViewBlendColourMap();
_ftd._fadeText = fadeText;
float fadeSpeed = fadeText->getFadeSpeed();
GlobalFadeText::ViewFadeTextMap& vftm = gft->_viewFadeTextMap;
for(GlobalFadeText::ViewFadeTextMap::iterator itr = vftm.begin();
itr != vftm.end();
++itr)
{
osg::View* view = itr->first;
GlobalFadeText::FadeTextSet& fadeTextSet = itr->second;
bool visible = fadeTextSet.count(fadeText)!=0;
osg::Vec4& tec = vbcm[view];
tec[0] = 1.0f;
tec[1] = 1.0f;
tec[2] = 1.0f;
if (visible)
{
if (tec[3]<1.0f)
{
tec[3] += fadeSpeed;
if (tec[3]>1.0f) tec[3] = 1.0f;
}
}
else
{
if (tec[3]>0.0f)
{
tec[3] -= fadeSpeed;
if (tec[3]<0.0f) tec[3] = 0.0f;
}
}
}
}
};
FadeText::FadeText()
{
init();
}
FadeText::FadeText(const Text& text,const osg::CopyOp& copyop):
Text(text,copyop)
{
init();
}
void FadeText::init()
{
setDataVariance(osg::Object::DYNAMIC);
_fadeSpeed = 0.01f;
setUpdateCallback(new FadeTextUpdateCallback());
}
void FadeText::drawImplementation(osg::RenderInfo& renderInfo) const
{
osg::State& state = *renderInfo.getState();
ViewBlendColourMap::iterator itr = _viewBlendColourMap.find(renderInfo.getView());
if (itr != _viewBlendColourMap.end())
{
Text::drawImplementation(*renderInfo.getState(), itr->second );
}
else
{
Text::drawImplementation(*renderInfo.getState(), osg::Vec4(1.0f,1.0f,1.0f,1.0f) );
}
// now pass on new details
FadeTextUserData* userData = dynamic_cast<FadeTextUserData*>(renderInfo.getUserData());
if (!userData)
{
if (renderInfo.getUserData())
{
OSG_NOTICE<<"Warning user data not of supported type."<<std::endl;
return;
}
userData = getGlobalFadeText()->createNewFadeTextUserData(renderInfo.getView());
if (!userData)
{
OSG_NOTICE<<"Memory error, unable to create FadeTextUserData."<<std::endl;
return;
}
renderInfo.setUserData(userData);
}
unsigned int frameNumber = renderInfo.getState()->getFrameStamp()->getFrameNumber();
if (frameNumber != userData->_frameNumber)
{
// new frame so must reset UserData structure.
userData->_frameNumber = frameNumber;
userData->_fadeTextInView.clear();
}
osgText::Text::AutoTransformCache& atc = _autoTransformCache[renderInfo.getContextID()];
osg::Matrix lmv = atc._matrix;
lmv.postMult(state.getModelViewMatrix());
if (renderInfo.getView() && renderInfo.getView()->getCamera())
{
// move from camera into the view space.
lmv.postMult(state.getInitialInverseViewMatrix());
lmv.postMult(renderInfo.getView()->getCamera()->getViewMatrix());
}
FadeTextData ftd(const_cast<osgText::FadeText*>(this));
ftd._vertices[0].set(osg::Vec3d(_textBB.xMin(),_textBB.yMin(),_textBB.zMin())*lmv);
ftd._vertices[1].set(osg::Vec3d(_textBB.xMax(),_textBB.yMin(),_textBB.zMin())*lmv);
ftd._vertices[2].set(osg::Vec3d(_textBB.xMax(),_textBB.yMax(),_textBB.zMin())*lmv);
ftd._vertices[3].set(osg::Vec3d(_textBB.xMin(),_textBB.yMax(),_textBB.zMin())*lmv);
userData->_fadeTextInView.push_back(ftd);
}
<commit_msg>Fixed FadeText when using NEW_APPROACH<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgText/FadeText>
#include <osg/Notify>
#include <osg/io_utils>
#include <OpenThreads/Mutex>
#include <OpenThreads/ScopedLock>
using namespace osgText;
struct FadeTextData : public osg::Referenced
{
FadeTextData(FadeText* fadeText=0):
_fadeText(fadeText),
_visible(true) {}
bool operator < (const FadeTextData& rhs) const
{
return _fadeText < rhs._fadeText;
}
double getNearestZ() const
{
double nearestZ = _vertices[0].z();
if (nearestZ < _vertices[1].z()) nearestZ = _vertices[1].z();
if (nearestZ < _vertices[2].z()) nearestZ = _vertices[2].z();
if (nearestZ < _vertices[3].z()) nearestZ = _vertices[3].z();
// OSG_NOTICE<<"getNearestZ()="<<_fadeText->getText().createUTF8EncodedString()<<" "<<nearestZ<<std::endl;
return nearestZ;
}
FadeText* _fadeText;
osg::Vec3d _vertices[4];
bool _visible;
};
struct FadeTextPolytopeData : public FadeTextData, public osg::Polytope
{
FadeTextPolytopeData(FadeTextData& fadeTextData):
FadeTextData(fadeTextData)
{
_referenceVertexList.push_back(_vertices[0]);
_referenceVertexList.push_back(_vertices[1]);
_referenceVertexList.push_back(_vertices[2]);
_referenceVertexList.push_back(_vertices[3]);
}
void addEdgePlane(const osg::Vec3& corner, const osg::Vec3& edge)
{
osg::Vec3 normal( edge.y(), -edge.x(), 0.0f);
normal.normalize();
add(osg::Plane(normal, corner));
}
void buildPolytope()
{
osg::Vec3d edge01 = _vertices[1] - _vertices[0];
osg::Vec3d edge12 = _vertices[2] - _vertices[1];
osg::Vec3d normalFrontFace = edge01 ^ edge12;
bool needToFlip = normalFrontFace.z()>0.0f;
normalFrontFace.normalize();
add(osg::Plane(normalFrontFace, _vertices[0]));
add(osg::Plane( osg::Vec3d(0.0f,0.0f,0.0f), _vertices[0], _vertices[1]));
add(osg::Plane( osg::Vec3d(0.0f,0.0f,0.0f), _vertices[1], _vertices[2]));
add(osg::Plane( osg::Vec3d(0.0f,0.0f,0.0f), _vertices[2], _vertices[3]));
add(osg::Plane( osg::Vec3d(0.0f,0.0f,0.0f), _vertices[3], _vertices[0]));
#if 0
OSG_NOTICE<<" normalFrontFace = "<<normalFrontFace<<std::endl;
OSG_NOTICE<<" edge01 = "<<edge01<<std::endl;
OSG_NOTICE<<" edge12 = "<<edge12<<std::endl;
OSG_NOTICE<<" _vertices[0]= "<<_vertices[0]<<std::endl;
OSG_NOTICE<<" _vertices[1]= "<<_vertices[1]<<std::endl;
OSG_NOTICE<<" _vertices[2]= "<<_vertices[2]<<std::endl;
OSG_NOTICE<<" _vertices[3]= "<<_vertices[3]<<std::endl;
#endif
if (needToFlip) flip();
#if 0
OSG_NOTICE<<" plane 0 "<< _planeList[0]<<std::endl;
OSG_NOTICE<<" plane 1 "<< _planeList[1]<<std::endl;
OSG_NOTICE<<" plane 2 "<< _planeList[2]<<std::endl;
OSG_NOTICE<<" plane 3 "<< _planeList[3]<<std::endl;
OSG_NOTICE<<" plane 4 "<< _planeList[4]<<std::endl;
#endif
}
inline bool contains(const std::vector<osg::Vec3>& vertices)
{
for(std::vector<osg::Vec3>::const_iterator itr = vertices.begin();
itr != vertices.end();
++itr)
{
if (osg::Polytope::contains(*itr))
{
return true;
}
}
return false;
}
};
struct FadeTextUserData : public osg::Referenced
{
FadeTextUserData():
_frameNumber(0) {}
typedef std::list<FadeTextData> FadeTextList;
unsigned int _frameNumber;
FadeTextList _fadeTextInView;
};
struct GlobalFadeText : public osg::Referenced
{
typedef std::set< osg::ref_ptr<FadeTextUserData> > UserDataSet;
typedef std::set<FadeText*> FadeTextSet;
typedef std::multimap<double, osg::ref_ptr<FadeTextPolytopeData> > FadeTextPolytopeMap;
typedef std::map<osg::View*, UserDataSet> ViewUserDataMap;
typedef std::map<osg::View*, FadeTextSet > ViewFadeTextMap;
GlobalFadeText():
_frameNumber(0xffffffff)
{
}
FadeTextUserData* createNewFadeTextUserData(osg::View* view)
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
FadeTextUserData* userData = new FadeTextUserData;
if (!userData)
{
OSG_NOTICE<<"Memory error, unable to create FadeTextUserData."<<std::endl;
return 0;
}
_viewMap[view].insert(userData);
return userData;
}
void update(unsigned int frameNumber)
{
_frameNumber = frameNumber;
for(GlobalFadeText::ViewUserDataMap::iterator vitr = _viewMap.begin();
vitr != _viewMap.end();
++vitr)
{
osg::View* view = vitr->first;
FadeTextSet& fadeTextSet = _viewFadeTextMap[view];
fadeTextSet.clear();
FadeTextPolytopeMap fadeTextPolytopeMap;
for(GlobalFadeText::UserDataSet::iterator uitr = vitr->second.begin();
uitr != vitr->second.end();
++uitr)
{
FadeTextUserData* userData = uitr->get();
int frameDelta = frameNumber - userData->_frameNumber;
if (frameDelta<=1)
{
for(FadeTextUserData::FadeTextList::iterator fitr = userData->_fadeTextInView.begin();
fitr != userData->_fadeTextInView.end();
++fitr)
{
FadeTextData& fadeTextData = *fitr;
if (fadeTextSet.count(fadeTextData._fadeText)==0)
{
fadeTextSet.insert(fadeTextData._fadeText);
fadeTextPolytopeMap.insert(FadeTextPolytopeMap::value_type(
-fadeTextData.getNearestZ(), new FadeTextPolytopeData(fadeTextData)));
}
}
}
}
// for each FadeTexPoltopeData
// create polytopes
// test against all FTPD's later in the list
// test all control points on FTPD against each plane of the current polytope
// if all control points removed or outside then discard FTPD and make FT visible = false;
FadeTextPolytopeMap::iterator outer_itr = fadeTextPolytopeMap.begin();
while (outer_itr != fadeTextPolytopeMap.end())
{
FadeTextPolytopeMap::iterator inner_itr = outer_itr;
++inner_itr;
if (inner_itr == fadeTextPolytopeMap.end()) break;
FadeTextPolytopeData& outer_ftpm = *(outer_itr->second);
outer_ftpm.buildPolytope();
// OSG_NOTICE<<"Outer z "<<outer_ftpm.getNearestZ()<<std::endl;
while(inner_itr != fadeTextPolytopeMap.end())
{
FadeTextPolytopeData& inner_ftpm = *(inner_itr->second);
// OSG_NOTICE<<"Inner z "<<inner_ftpm.getNearestZ()<<std::endl;
if (outer_ftpm.contains(inner_ftpm.getReferenceVertexList()))
{
FadeTextPolytopeMap::iterator erase_itr = inner_itr;
// move to next ftpm
++inner_itr;
fadeTextSet.erase(inner_ftpm._fadeText);
// need to remove inner_ftpm as its occluded.
fadeTextPolytopeMap.erase(erase_itr);
}
else
{
// move to next ftpm
++inner_itr;
}
}
++outer_itr;
}
}
}
inline void updateIfRequired(unsigned int frameNumber)
{
if (_frameNumber!=frameNumber) update(frameNumber);
}
unsigned int _frameNumber;
OpenThreads::Mutex _mutex;
ViewUserDataMap _viewMap;
ViewFadeTextMap _viewFadeTextMap;
};
GlobalFadeText* getGlobalFadeText()
{
static osg::ref_ptr<GlobalFadeText> s_globalFadeText = new GlobalFadeText;
return s_globalFadeText.get();
}
struct FadeText::FadeTextUpdateCallback : public osg::DrawableUpdateCallback
{
FadeTextData _ftd;
virtual void update(osg::NodeVisitor* nv, osg::Drawable* drawable)
{
osgText::FadeText* fadeText = dynamic_cast<osgText::FadeText*>(drawable);
if (!fadeText) return;
unsigned int frameNumber = nv->getFrameStamp()->getFrameNumber();
GlobalFadeText* gft = getGlobalFadeText();
gft->updateIfRequired(frameNumber);
osgText::FadeText::ViewBlendColourMap& vbcm = fadeText->getViewBlendColourMap();
_ftd._fadeText = fadeText;
float fadeSpeed = fadeText->getFadeSpeed();
GlobalFadeText::ViewFadeTextMap& vftm = gft->_viewFadeTextMap;
for(GlobalFadeText::ViewFadeTextMap::iterator itr = vftm.begin();
itr != vftm.end();
++itr)
{
osg::View* view = itr->first;
GlobalFadeText::FadeTextSet& fadeTextSet = itr->second;
bool visible = fadeTextSet.count(fadeText)!=0;
osg::Vec4& tec = vbcm[view];
tec[0] = 1.0f;
tec[1] = 1.0f;
tec[2] = 1.0f;
if (visible)
{
if (tec[3]<1.0f)
{
tec[3] += fadeSpeed;
if (tec[3]>1.0f) tec[3] = 1.0f;
}
}
else
{
if (tec[3]>0.0f)
{
tec[3] -= fadeSpeed;
if (tec[3]<0.0f) tec[3] = 0.0f;
}
}
}
}
};
FadeText::FadeText()
{
init();
}
FadeText::FadeText(const Text& text,const osg::CopyOp& copyop):
Text(text,copyop)
{
init();
}
void FadeText::init()
{
setDataVariance(osg::Object::DYNAMIC);
_fadeSpeed = 0.01f;
setUpdateCallback(new FadeTextUpdateCallback());
}
void FadeText::drawImplementation(osg::RenderInfo& renderInfo) const
{
osg::State& state = *renderInfo.getState();
ViewBlendColourMap::iterator itr = _viewBlendColourMap.find(renderInfo.getView());
if (itr != _viewBlendColourMap.end())
{
Text::drawImplementation(*renderInfo.getState(), itr->second );
}
else
{
Text::drawImplementation(*renderInfo.getState(), osg::Vec4(1.0f,1.0f,1.0f,1.0f) );
}
// now pass on new details
FadeTextUserData* userData = dynamic_cast<FadeTextUserData*>(renderInfo.getUserData());
if (!userData)
{
if (renderInfo.getUserData())
{
OSG_NOTICE<<"Warning user data not of supported type."<<std::endl;
return;
}
userData = getGlobalFadeText()->createNewFadeTextUserData(renderInfo.getView());
if (!userData)
{
OSG_NOTICE<<"Memory error, unable to create FadeTextUserData."<<std::endl;
return;
}
renderInfo.setUserData(userData);
}
unsigned int frameNumber = renderInfo.getState()->getFrameStamp()->getFrameNumber();
if (frameNumber != userData->_frameNumber)
{
// new frame so must reset UserData structure.
userData->_frameNumber = frameNumber;
userData->_fadeTextInView.clear();
}
#ifdef NEW_APPROACH
osg::Matrix lmv = state.getModelViewMatrix();
computeMatrix(state, lmv);
lmv.postMult(state.getModelViewMatrix());
#else
osgText::Text::AutoTransformCache& atc = _autoTransformCache[renderInfo.getContextID()];
osg::Matrix lmv = atc._matrix;
lmv.postMult(state.getModelViewMatrix());
#endif
if (renderInfo.getView() && renderInfo.getView()->getCamera())
{
// move from camera into the view space.
lmv.postMult(state.getInitialInverseViewMatrix());
lmv.postMult(renderInfo.getView()->getCamera()->getViewMatrix());
}
FadeTextData ftd(const_cast<osgText::FadeText*>(this));
ftd._vertices[0].set(osg::Vec3d(_textBB.xMin(),_textBB.yMin(),_textBB.zMin())*lmv);
ftd._vertices[1].set(osg::Vec3d(_textBB.xMax(),_textBB.yMin(),_textBB.zMin())*lmv);
ftd._vertices[2].set(osg::Vec3d(_textBB.xMax(),_textBB.yMax(),_textBB.zMin())*lmv);
ftd._vertices[3].set(osg::Vec3d(_textBB.xMin(),_textBB.yMax(),_textBB.zMin())*lmv);
userData->_fadeTextInView.push_back(ftd);
}
<|endoftext|>
|
<commit_before>//===- lib/Tooling/AllTUsExecution.cpp - Execute actions on all TUs. ------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "clang/Tooling/AllTUsExecution.h"
#include "clang/Tooling/ToolExecutorPluginRegistry.h"
#include "llvm/Support/ThreadPool.h"
namespace clang {
namespace tooling {
const char *AllTUsToolExecutor::ExecutorName = "AllTUsToolExecutor";
namespace {
llvm::Error make_string_error(const llvm::Twine &Message) {
return llvm::make_error<llvm::StringError>(Message,
llvm::inconvertibleErrorCode());
}
ArgumentsAdjuster getDefaultArgumentsAdjusters() {
return combineAdjusters(
getClangStripOutputAdjuster(),
combineAdjusters(getClangSyntaxOnlyAdjuster(),
getClangStripDependencyFileAdjuster()));
}
class ThreadSafeToolResults : public ToolResults {
public:
void addResult(StringRef Key, StringRef Value) override {
std::unique_lock<std::mutex> LockGuard(Mutex);
Results.addResult(Key, Value);
}
std::vector<std::pair<llvm::StringRef, llvm::StringRef>>
AllKVResults() override {
return Results.AllKVResults();
}
void forEachResult(llvm::function_ref<void(StringRef Key, StringRef Value)>
Callback) override {
Results.forEachResult(Callback);
}
private:
InMemoryToolResults Results;
std::mutex Mutex;
};
} // namespace
llvm::cl::opt<std::string>
Filter("filter",
llvm::cl::desc("Only process files that match this filter. "
"This flag only applies to all-TUs."),
llvm::cl::init(".*"));
AllTUsToolExecutor::AllTUsToolExecutor(
const CompilationDatabase &Compilations, unsigned ThreadCount,
std::shared_ptr<PCHContainerOperations> PCHContainerOps)
: Compilations(Compilations), Results(new ThreadSafeToolResults),
Context(Results.get()), ThreadCount(ThreadCount) {}
AllTUsToolExecutor::AllTUsToolExecutor(
CommonOptionsParser Options, unsigned ThreadCount,
std::shared_ptr<PCHContainerOperations> PCHContainerOps)
: OptionsParser(std::move(Options)),
Compilations(OptionsParser->getCompilations()),
Results(new ThreadSafeToolResults), Context(Results.get()),
ThreadCount(ThreadCount) {}
llvm::Error AllTUsToolExecutor::execute(
llvm::ArrayRef<
std::pair<std::unique_ptr<FrontendActionFactory>, ArgumentsAdjuster>>
Actions) {
if (Actions.empty())
return make_string_error("No action to execute.");
if (Actions.size() != 1)
return make_string_error(
"Only support executing exactly 1 action at this point.");
std::string ErrorMsg;
std::mutex TUMutex;
auto AppendError = [&](llvm::Twine Err) {
std::unique_lock<std::mutex> LockGuard(TUMutex);
ErrorMsg += Err.str();
};
auto Log = [&](llvm::Twine Msg) {
std::unique_lock<std::mutex> LockGuard(TUMutex);
llvm::errs() << Msg.str() << "\n";
};
std::vector<std::string> Files;
llvm::Regex RegexFilter(Filter);
for (const auto& File : Compilations.getAllFiles()) {
if (RegexFilter.match(File))
Files.push_back(File);
}
// Add a counter to track the progress.
const std::string TotalNumStr = std::to_string(Files.size());
unsigned Counter = 0;
auto Count = [&]() {
std::unique_lock<std::mutex> LockGuard(TUMutex);
return ++Counter;
};
auto &Action = Actions.front();
{
llvm::ThreadPool Pool(ThreadCount == 0 ? llvm::hardware_concurrency()
: ThreadCount);
llvm::SmallString<128> InitialWorkingDir;
if (auto EC = llvm::sys::fs::current_path(InitialWorkingDir)) {
InitialWorkingDir = "";
llvm::errs() << "Error while getting current working directory: "
<< EC.message() << "\n";
}
for (std::string File : Files) {
Pool.async(
[&](std::string Path) {
Log("[" + std::to_string(Count()) + "/" + TotalNumStr +
"] Processing file " + Path);
ClangTool Tool(Compilations, {Path});
Tool.appendArgumentsAdjuster(Action.second);
Tool.appendArgumentsAdjuster(getDefaultArgumentsAdjusters());
for (const auto &FileAndContent : OverlayFiles)
Tool.mapVirtualFile(FileAndContent.first(),
FileAndContent.second);
// Do not restore working dir from multiple threads to avoid races.
Tool.setRestoreWorkingDir(false);
if (Tool.run(Action.first.get()))
AppendError(llvm::Twine("Failed to run action on ") + Path +
"\n");
},
File);
}
// Make sure all tasks have finished before resetting the working directory.
Pool.wait();
if (!InitialWorkingDir.empty()) {
if (auto EC = llvm::sys::fs::set_current_path(InitialWorkingDir))
llvm::errs() << "Error while restoring working directory: "
<< EC.message() << "\n";
}
}
if (!ErrorMsg.empty())
return make_string_error(ErrorMsg);
return llvm::Error::success();
}
static llvm::cl::opt<unsigned> ExecutorConcurrency(
"execute-concurrency",
llvm::cl::desc("The number of threads used to process all files in "
"parallel. Set to 0 for hardware concurrency. "
"This flag only applies to all-TUs."),
llvm::cl::init(0));
class AllTUsToolExecutorPlugin : public ToolExecutorPlugin {
public:
llvm::Expected<std::unique_ptr<ToolExecutor>>
create(CommonOptionsParser &OptionsParser) override {
if (OptionsParser.getSourcePathList().empty())
return make_string_error(
"[AllTUsToolExecutorPlugin] Please provide a directory/file path in "
"the compilation database.");
return llvm::make_unique<AllTUsToolExecutor>(std::move(OptionsParser),
ExecutorConcurrency);
}
};
static ToolExecutorPluginRegistry::Add<AllTUsToolExecutorPlugin>
X("all-TUs", "Runs FrontendActions on all TUs in the compilation database. "
"Tool results are stored in memory.");
// This anchor is used to force the linker to link in the generated object file
// and thus register the plugin.
volatile int AllTUsToolExecutorAnchorSource = 0;
} // end namespace tooling
} // end namespace clang
<commit_msg>[Tooling] Avoid working-dir races in AllTUsToolExecutor<commit_after>//===- lib/Tooling/AllTUsExecution.cpp - Execute actions on all TUs. ------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "clang/Tooling/AllTUsExecution.h"
#include "clang/Tooling/ToolExecutorPluginRegistry.h"
#include "llvm/Support/ThreadPool.h"
#include "llvm/Support/VirtualFileSystem.h"
namespace clang {
namespace tooling {
const char *AllTUsToolExecutor::ExecutorName = "AllTUsToolExecutor";
namespace {
llvm::Error make_string_error(const llvm::Twine &Message) {
return llvm::make_error<llvm::StringError>(Message,
llvm::inconvertibleErrorCode());
}
ArgumentsAdjuster getDefaultArgumentsAdjusters() {
return combineAdjusters(
getClangStripOutputAdjuster(),
combineAdjusters(getClangSyntaxOnlyAdjuster(),
getClangStripDependencyFileAdjuster()));
}
class ThreadSafeToolResults : public ToolResults {
public:
void addResult(StringRef Key, StringRef Value) override {
std::unique_lock<std::mutex> LockGuard(Mutex);
Results.addResult(Key, Value);
}
std::vector<std::pair<llvm::StringRef, llvm::StringRef>>
AllKVResults() override {
return Results.AllKVResults();
}
void forEachResult(llvm::function_ref<void(StringRef Key, StringRef Value)>
Callback) override {
Results.forEachResult(Callback);
}
private:
InMemoryToolResults Results;
std::mutex Mutex;
};
} // namespace
llvm::cl::opt<std::string>
Filter("filter",
llvm::cl::desc("Only process files that match this filter. "
"This flag only applies to all-TUs."),
llvm::cl::init(".*"));
AllTUsToolExecutor::AllTUsToolExecutor(
const CompilationDatabase &Compilations, unsigned ThreadCount,
std::shared_ptr<PCHContainerOperations> PCHContainerOps)
: Compilations(Compilations), Results(new ThreadSafeToolResults),
Context(Results.get()), ThreadCount(ThreadCount) {}
AllTUsToolExecutor::AllTUsToolExecutor(
CommonOptionsParser Options, unsigned ThreadCount,
std::shared_ptr<PCHContainerOperations> PCHContainerOps)
: OptionsParser(std::move(Options)),
Compilations(OptionsParser->getCompilations()),
Results(new ThreadSafeToolResults), Context(Results.get()),
ThreadCount(ThreadCount) {}
llvm::Error AllTUsToolExecutor::execute(
llvm::ArrayRef<
std::pair<std::unique_ptr<FrontendActionFactory>, ArgumentsAdjuster>>
Actions) {
if (Actions.empty())
return make_string_error("No action to execute.");
if (Actions.size() != 1)
return make_string_error(
"Only support executing exactly 1 action at this point.");
std::string ErrorMsg;
std::mutex TUMutex;
auto AppendError = [&](llvm::Twine Err) {
std::unique_lock<std::mutex> LockGuard(TUMutex);
ErrorMsg += Err.str();
};
auto Log = [&](llvm::Twine Msg) {
std::unique_lock<std::mutex> LockGuard(TUMutex);
llvm::errs() << Msg.str() << "\n";
};
std::vector<std::string> Files;
llvm::Regex RegexFilter(Filter);
for (const auto& File : Compilations.getAllFiles()) {
if (RegexFilter.match(File))
Files.push_back(File);
}
// Add a counter to track the progress.
const std::string TotalNumStr = std::to_string(Files.size());
unsigned Counter = 0;
auto Count = [&]() {
std::unique_lock<std::mutex> LockGuard(TUMutex);
return ++Counter;
};
auto &Action = Actions.front();
{
llvm::ThreadPool Pool(ThreadCount == 0 ? llvm::hardware_concurrency()
: ThreadCount);
for (std::string File : Files) {
Pool.async(
[&](std::string Path) {
Log("[" + std::to_string(Count()) + "/" + TotalNumStr +
"] Processing file " + Path);
// Each thread gets an indepent copy of a VFS to allow different
// concurrent working directories.
IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS =
llvm::vfs::createPhysicalFileSystem().release();
ClangTool Tool(Compilations, {Path},
std::make_shared<PCHContainerOperations>(), FS);
Tool.appendArgumentsAdjuster(Action.second);
Tool.appendArgumentsAdjuster(getDefaultArgumentsAdjusters());
for (const auto &FileAndContent : OverlayFiles)
Tool.mapVirtualFile(FileAndContent.first(),
FileAndContent.second);
if (Tool.run(Action.first.get()))
AppendError(llvm::Twine("Failed to run action on ") + Path +
"\n");
},
File);
}
// Make sure all tasks have finished before resetting the working directory.
Pool.wait();
}
if (!ErrorMsg.empty())
return make_string_error(ErrorMsg);
return llvm::Error::success();
}
static llvm::cl::opt<unsigned> ExecutorConcurrency(
"execute-concurrency",
llvm::cl::desc("The number of threads used to process all files in "
"parallel. Set to 0 for hardware concurrency. "
"This flag only applies to all-TUs."),
llvm::cl::init(0));
class AllTUsToolExecutorPlugin : public ToolExecutorPlugin {
public:
llvm::Expected<std::unique_ptr<ToolExecutor>>
create(CommonOptionsParser &OptionsParser) override {
if (OptionsParser.getSourcePathList().empty())
return make_string_error(
"[AllTUsToolExecutorPlugin] Please provide a directory/file path in "
"the compilation database.");
return llvm::make_unique<AllTUsToolExecutor>(std::move(OptionsParser),
ExecutorConcurrency);
}
};
static ToolExecutorPluginRegistry::Add<AllTUsToolExecutorPlugin>
X("all-TUs", "Runs FrontendActions on all TUs in the compilation database. "
"Tool results are stored in memory.");
// This anchor is used to force the linker to link in the generated object file
// and thus register the plugin.
volatile int AllTUsToolExecutorAnchorSource = 0;
} // end namespace tooling
} // end namespace clang
<|endoftext|>
|
<commit_before>/* -*- Mode: c++; tab-width: 2; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/* vim:set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Dirk Holz <dirk.holz _at_ ieee.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT 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 <pcl/io/vtk_lib_io.h>
#include <pcl/console/print.h>
int main(int argc, char** argv)
{
if (argc != 3)
{
PCL_ERROR("USAGE: %s [input mesh] [output mesh]\n", argv[0]);
exit(EXIT_FAILURE);
}
std::string input(argv[1]), output(argv[2]);
PCL_DEBUG("Converting %s to %s.\n", input.c_str(), output.c_str());
pcl::PolygonMesh mesh;
if (pcl::io::loadPolygonFile(input, mesh) <= 0)
{
PCL_ERROR("Error reading from %s", input.c_str());
exit(EXIT_FAILURE);
}
if (pcl::io::savePolygonFile(output, mesh) <= 0)
{
PCL_ERROR("Error writing to %s", input.c_str());
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
<commit_msg>added scaling<commit_after>/* -*- Mode: c++; tab-width: 2; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/* vim:set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Dirk Holz <dirk.holz _at_ ieee.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT 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 <pcl/io/vtk_lib_io.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
int main(int argc, char** argv)
{
if (argc < 3)
{
PCL_ERROR("USAGE: %s [input mesh] [output mesh] [OPT: options...]\n", argv[0]);
exit(EXIT_FAILURE);
}
std::string input(argv[1]), output(argv[2]);
PCL_DEBUG("Converting %s to %s.\n", input.c_str(), output.c_str());
pcl::PolygonMesh mesh;
if (pcl::io::loadPolygonFile(input, mesh) <= 0)
{
PCL_ERROR("Error reading from %s", input.c_str());
exit(EXIT_FAILURE);
}
// Scaling
const float INVALID_SCALING_FACTOR = 0.0f;
float scaling_factor = INVALID_SCALING_FACTOR;
pcl::console::parse_argument(argc, argv, "-scale", scaling_factor);
if (scaling_factor != INVALID_SCALING_FACTOR)
{
PCL_INFO("Scaling input mesh by a factor of %0.4f\n", scaling_factor);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::fromPCLPointCloud2(mesh.cloud, *cloud);
for (size_t i = 0; i < cloud->points.size(); ++i)
{
cloud->points[i].x *= scaling_factor;
cloud->points[i].y *= scaling_factor;
cloud->points[i].z *= scaling_factor;
}
pcl::toPCLPointCloud2(*cloud, mesh.cloud);
}
if (pcl::io::savePolygonFile(output, mesh) <= 0)
{
PCL_ERROR("Error writing to %s", input.c_str());
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "process.h"
#include <stdlib.h>
#include <algorithm>
#include <boost/predef.h>
#include <boost/filesystem.hpp>
#include <boost/assert.hpp>
#if( BOOST_OS_WINDOWS )
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <unistd.h>
#endif
namespace platform {
namespace process {
#if( BOOST_OS_WINDOWS )
namespace {
std::wstring wcstr( std::string const& str )
{
size_t len = mbstowcs( NULL, str.c_str(), 0 );
std::wstring wstr( len + 1, '\0' );
mbstowcs( &wstr[0], str.c_str(), wstr.size() );
return wstr;
}
}
bool Start( std::string const& command, std::vector<std::string> const& arguments )
{
std::vector<std::wstring> args;
std::transform( arguments.begin(), arguments.end(), std::back_inserter( args ), &wcstr );
return Start( wcstr( command ), args );
}
bool Start( std::wstring const& command, std::vector<std::wstring> const& arguments )
{
std::wstring commandline = std::accumulate( arguments.begin(), arguments.end(), command, []( std::wstring const& accu, std::wstring const& elem ){ return accu + " " + elem; } );
PROCESS_INFORMATION pi;
STARTUPINFOW si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
wchar_t dir[1024];
GetCurrentDirectoryW(sizeof(dir), dir);
if (!CreateProcessW(NULL, commandline.c_str(), NULL, NULL, FALSE, 0, NULL, dir, &si, &pi))
{
return false;
}
CloseHandle(pi.hThread);
return true;
}
#else
namespace buffers {
char* GetPath()
{
static std::string pathstr;
if( pathstr.empty() )
{
pathstr = "PATH=";
pathstr += getenv("PATH");
pathstr += ":";
pathstr += boost::filesystem::current_path().string();
}
return const_cast<char*>( pathstr.c_str() );
}
char* Env[] = { GetPath(), NULL };
}
bool Start( std::string const& command, std::vector<std::string> const& arguments )
{
size_t ctr = 0;
std::vector<char*> args( 1, const_cast<char*>( command.c_str() ) );
std::transform( arguments.begin(), arguments.end(), std::back_inserter( args ), []( std::string const& a ){ return const_cast<char*>( a.c_str() ); } );
args.push_back( NULL );
pid_t pid = fork();
if (pid == -1)
{
return false;
}
else if (pid == 0) {
(void) execvpe( command.c_str(),
&args[0], buffers::Env );
exit(1);
}
return true;
}
namespace {
std::string mbstr( std::wstring const& wstr )
{
size_t len = wcstombs( NULL, wstr.c_str(), 0 );
std::string str( len + 1, '\0' );
wcstombs( &str[0], wstr.c_str(), str.size() );
return str;
}
}
bool Start( std::wstring const& command, std::vector<std::wstring> const& arguments )
{
std::vector<std::string> args;
std::transform( arguments.begin(), arguments.end(), std::back_inserter( args ), &mbstr );
return Start( mbstr( command ), args );
}
#endif
}
}
<commit_msg>B: mingw compile fix<commit_after>#include "process.h"
#include <stdlib.h>
#include <algorithm>
#include <boost/predef.h>
#include <boost/filesystem.hpp>
#include <boost/assert.hpp>
#if( BOOST_OS_WINDOWS )
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <unistd.h>
#endif
namespace platform {
namespace process {
#if( BOOST_OS_WINDOWS )
namespace {
std::wstring wcstr( std::string const& str )
{
size_t len = mbstowcs( NULL, str.c_str(), 0 );
std::wstring wstr( len + 1, '\0' );
mbstowcs( &wstr[0], str.c_str(), wstr.size() );
return wstr;
}
}
bool Start( std::string const& command, std::vector<std::string> const& arguments )
{
std::vector<std::wstring> args;
std::transform( arguments.begin(), arguments.end(), std::back_inserter( args ), &wcstr );
return Start( wcstr( command ), args );
}
bool Start( std::wstring const& command, std::vector<std::wstring> const& arguments )
{
std::wstring commandline = std::accumulate( arguments.begin(), arguments.end(), command, []( std::wstring const& accu, std::wstring const& elem ){ return accu + L" " + elem; } );
PROCESS_INFORMATION pi;
STARTUPINFOW si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
wchar_t dir[1024];
GetCurrentDirectoryW(sizeof(dir), dir);
if (!CreateProcessW(NULL, const_cast<wchar_t*>( commandline.c_str() ), NULL, NULL, FALSE, 0, NULL, dir, &si, &pi))
{
return false;
}
CloseHandle(pi.hThread);
return true;
}
#else
namespace buffers {
char* GetPath()
{
static std::string pathstr;
if( pathstr.empty() )
{
pathstr = "PATH=";
pathstr += getenv("PATH");
pathstr += ":";
pathstr += boost::filesystem::current_path().string();
}
return const_cast<char*>( pathstr.c_str() );
}
char* Env[] = { GetPath(), NULL };
}
bool Start( std::string const& command, std::vector<std::string> const& arguments )
{
size_t ctr = 0;
std::vector<char*> args( 1, const_cast<char*>( command.c_str() ) );
std::transform( arguments.begin(), arguments.end(), std::back_inserter( args ), []( std::string const& a ){ return const_cast<char*>( a.c_str() ); } );
args.push_back( NULL );
pid_t pid = fork();
if (pid == -1)
{
return false;
}
else if (pid == 0) {
(void) execvpe( command.c_str(),
&args[0], buffers::Env );
exit(1);
}
return true;
}
namespace {
std::string mbstr( std::wstring const& wstr )
{
size_t len = wcstombs( NULL, wstr.c_str(), 0 );
std::string str( len + 1, '\0' );
wcstombs( &str[0], wstr.c_str(), str.size() );
return str;
}
}
bool Start( std::wstring const& command, std::vector<std::wstring> const& arguments )
{
std::vector<std::string> args;
std::transform( arguments.begin(), arguments.end(), std::back_inserter( args ), &mbstr );
return Start( mbstr( command ), args );
}
#endif
}
}
<|endoftext|>
|
<commit_before><commit_msg>ppl: check if there is enough positions for constraints<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <primitives/block.h>
#include <globaltoken/hardfork.h>
#include <hash.h>
#include <tinyformat.h>
#include <utilstrencodings.h>
#include <crypto/common.h>
#include <crypto/algos/hashlib/multihash.h>
#include <crypto/algos/neoscrypt/neoscrypt.h>
#include <crypto/algos/scrypt/scrypt.h>
#include <crypto/algos/yescrypt/yescrypt.h>
uint256 CBlockHeader::GetHash() const
{
int version;
if (IsHardForkActivated(nHeight)) {
version = PROTOCOL_VERSION;
} else {
version = PROTOCOL_VERSION | SERIALIZE_BLOCK_LEGACY;
}
CHashWriter writer(SER_GETHASH, version);
::Serialize(writer, *this);
return writer.GetHash();
}
int CBlockHeader::GetAlgo() const
{
return nAlgo;
}
uint256 CBlockHeader::GetPoWHash(int algo) const
{
switch (algo)
{
case ALGO_SHA256D:
return GetHash();
case ALGO_SCRYPT:
{
uint256 thash;
scrypt_1024_1_1_256(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_X11
{
uint32_t default_nonce = (uint32_t)nNonce.GetUint64(0);
return HashX11(BEGIN(nVersion), END(default_nonce));
}
case ALGO_NEOSCRYPT:
{
unsigned int profile = 0x0;
uint256 thash;
neoscrypt((unsigned char *) &nVersion, (unsigned char *) &thash, profile);
return thash;
}
case ALGO_EQUIHASH:
return GetHash();
case ALGO_YESCRYPT:
{
uint256 thash;
yescrypt_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_HMQ1725
{
uint32_t default_nonce = (uint32_t)nNonce.GetUint64(0);
return HMQ1725(BEGIN(nVersion), END(default_nonce));
}
}
return GetHash();
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=0x%08x, powalgo=%u, powalgoname=%s, powhash=%s, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%s, vtx=%u)\n",
GetHash().ToString(),
nVersion,
GetAlgo(),
GetAlgoName(GetAlgo()),
GetPoWHash(GetAlgo()).ToString(),
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce.GetHex(),
vtx.size());
for (const auto& tx : vtx) {
s << " " << tx->ToString() << "\n";
}
return s.str();
}
std::string GetAlgoName(int Algo)
{
switch (Algo)
{
case ALGO_SHA256D:
return std::string("sha256d");
case ALGO_SCRYPT:
return std::string("scrypt");
case ALGO_X11:
return std::string("x11");
case ALGO_NEOSCRYPT:
return std::string("neoscrypt");
case ALGO_YESCRYPT:
return std::string("yescrypt");
case ALGO_EQUIHASH:
return std::string("equihash");
case ALGO_HMQ1725:
return std::string("hmq1725");
}
return std::string("unknown");
}
<commit_msg>Missing ":"<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <primitives/block.h>
#include <globaltoken/hardfork.h>
#include <hash.h>
#include <tinyformat.h>
#include <utilstrencodings.h>
#include <crypto/common.h>
#include <crypto/algos/hashlib/multihash.h>
#include <crypto/algos/neoscrypt/neoscrypt.h>
#include <crypto/algos/scrypt/scrypt.h>
#include <crypto/algos/yescrypt/yescrypt.h>
uint256 CBlockHeader::GetHash() const
{
int version;
if (IsHardForkActivated(nHeight)) {
version = PROTOCOL_VERSION;
} else {
version = PROTOCOL_VERSION | SERIALIZE_BLOCK_LEGACY;
}
CHashWriter writer(SER_GETHASH, version);
::Serialize(writer, *this);
return writer.GetHash();
}
int CBlockHeader::GetAlgo() const
{
return nAlgo;
}
uint256 CBlockHeader::GetPoWHash(int algo) const
{
switch (algo)
{
case ALGO_SHA256D:
return GetHash();
case ALGO_SCRYPT:
{
uint256 thash;
scrypt_1024_1_1_256(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_X11:
{
uint32_t default_nonce = (uint32_t)nNonce.GetUint64(0);
return HashX11(BEGIN(nVersion), END(default_nonce));
}
case ALGO_NEOSCRYPT:
{
unsigned int profile = 0x0;
uint256 thash;
neoscrypt((unsigned char *) &nVersion, (unsigned char *) &thash, profile);
return thash;
}
case ALGO_EQUIHASH:
return GetHash();
case ALGO_YESCRYPT:
{
uint256 thash;
yescrypt_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_HMQ1725
{
uint32_t default_nonce = (uint32_t)nNonce.GetUint64(0);
return HMQ1725(BEGIN(nVersion), END(default_nonce));
}
}
return GetHash();
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=0x%08x, powalgo=%u, powalgoname=%s, powhash=%s, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%s, vtx=%u)\n",
GetHash().ToString(),
nVersion,
GetAlgo(),
GetAlgoName(GetAlgo()),
GetPoWHash(GetAlgo()).ToString(),
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce.GetHex(),
vtx.size());
for (const auto& tx : vtx) {
s << " " << tx->ToString() << "\n";
}
return s.str();
}
std::string GetAlgoName(int Algo)
{
switch (Algo)
{
case ALGO_SHA256D:
return std::string("sha256d");
case ALGO_SCRYPT:
return std::string("scrypt");
case ALGO_X11:
return std::string("x11");
case ALGO_NEOSCRYPT:
return std::string("neoscrypt");
case ALGO_YESCRYPT:
return std::string("yescrypt");
case ALGO_EQUIHASH:
return std::string("equihash");
case ALGO_HMQ1725:
return std::string("hmq1725");
}
return std::string("unknown");
}
<|endoftext|>
|
<commit_before>/*
This file is part of VROOM.
Copyright (c) 2015-2021, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include "problems/tsp/tsp.h"
#include "problems/tsp/heuristics/christofides.h"
#include "problems/tsp/heuristics/local_search.h"
#include "utils/helpers.h"
namespace vroom {
TSP::TSP(const Input& input, std::vector<Index> job_ranks, Index vehicle_rank)
: VRP(input),
_vehicle_rank(vehicle_rank),
_job_ranks(std::move(job_ranks)),
_is_symmetric(true),
_has_start(_input.vehicles[_vehicle_rank].has_start()),
_has_end(_input.vehicles[_vehicle_rank].has_end()) {
assert(!_job_ranks.empty());
// Pick ranks to select from input matrix.
std::vector<Index> matrix_ranks;
std::transform(_job_ranks.cbegin(),
_job_ranks.cend(),
std::back_inserter(matrix_ranks),
[&](const auto& r) { return _input.jobs[r].index(); });
if (_has_start) {
// Add start and remember rank in _matrix.
_start = matrix_ranks.size();
matrix_ranks.push_back(
_input.vehicles[_vehicle_rank].start.value().index());
}
if (_has_end) {
// Add end and remember rank in _matrix.
if (_has_start and (_input.vehicles[_vehicle_rank].start.value().index() ==
_input.vehicles[_vehicle_rank].end.value().index())) {
// Avoiding duplicate for identical ranks.
_end = _start;
} else {
_end = matrix_ranks.size();
matrix_ranks.push_back(
_input.vehicles[_vehicle_rank].end.value().index());
}
}
// Populate TSP-solving matrix.
_matrix = Matrix<Cost>(matrix_ranks.size());
const auto& v = _input.vehicles[vehicle_rank];
for (Index i = 0; i < matrix_ranks.size(); ++i) {
for (Index j = 0; j < matrix_ranks.size(); ++j) {
_matrix[i][j] = v.cost(matrix_ranks[i], matrix_ranks[j]);
}
}
// Distances on the diagonal are never used except in the minimum
// weight perfect matching (munkres call during the heuristic). This
// makes sure no node will be matched with itself at that time.
for (Index i = 0; i < _matrix.size(); ++i) {
_matrix[i][i] = INFINITE_COST;
}
_round_trip = _has_start and _has_end and (_start == _end);
if (!_round_trip) {
// Dealing with open tour cases. Exactly one of the following
// happens.
if (_has_start and !_has_end) {
// Forcing first location as start, end location decided during
// optimization.
for (Index i = 0; i < _matrix.size(); ++i) {
if (i != _start) {
_matrix[i][_start] = 0;
}
}
}
if (!_has_start and _has_end) {
// Forcing last location as end, start location decided during
// optimization.
for (Index j = 0; j < _matrix.size(); ++j) {
if (j != _end) {
_matrix[_end][j] = 0;
}
}
}
if (_has_start and _has_end) {
// Forcing first location as start, last location as end to
// produce an open tour.
assert(_start != _end);
_matrix[_end][_start] = 0;
for (Index j = 0; j < _matrix.size(); ++j) {
if ((j != _start) and (j != _end)) {
_matrix[_end][j] = INFINITE_COST;
}
}
}
}
// Compute symmetrized matrix and update _is_symmetric flag.
_symmetrized_matrix = Matrix<Cost>(_matrix.size());
const Cost& (*sym_f)(const Cost&, const Cost&) = std::min<Cost>;
if ((_has_start and !_has_end) or (!_has_start and _has_end)) {
// Using symmetrization with max as when only start or only end is
// forced, the matrix has a line or a column filled with zeros.
sym_f = std::max<Cost>;
}
for (Index i = 0; i < _matrix.size(); ++i) {
_symmetrized_matrix[i][i] = _matrix[i][i];
for (Index j = i + 1; j < _matrix.size(); ++j) {
_is_symmetric = _is_symmetric && (_matrix[i][j] == _matrix[j][i]);
Cost val = sym_f(_matrix[i][j], _matrix[j][i]);
_symmetrized_matrix[i][j] = val;
_symmetrized_matrix[j][i] = val;
}
}
}
Cost TSP::cost(const std::list<Index>& tour) const {
Cost cost = 0;
Index init_step = 0; // Initialization actually never used.
auto step = tour.cbegin();
if (tour.size() > 0) {
init_step = *step;
}
Index previous_step = init_step;
++step;
for (; step != tour.cend(); ++step) {
cost += _matrix[previous_step][*step];
previous_step = *step;
}
if (tour.size() > 0) {
cost += _matrix[previous_step][init_step];
}
return cost;
}
Cost TSP::symmetrized_cost(const std::list<Index>& tour) const {
Cost cost = 0;
Index init_step = 0; // Initialization actually never used.
auto step = tour.cbegin();
if (tour.size() > 0) {
init_step = *step;
}
Index previous_step = init_step;
++step;
for (; step != tour.cend(); ++step) {
cost += _symmetrized_matrix[previous_step][*step];
previous_step = *step;
}
if (tour.size() > 0) {
cost += _symmetrized_matrix[previous_step][init_step];
}
return cost;
}
std::vector<Index> TSP::raw_solve(unsigned nb_threads,
const Timeout& timeout) const {
// Applying heuristic.
std::list<Index> christo_sol = tsp::christofides(_symmetrized_matrix);
// Local search on symmetric problem.
// Applying deterministic, fast local search to improve the current
// solution in a small amount of time. All possible moves for the
// different neighbourhoods are performed, stopping when reaching a
// local minima.
tsp::LocalSearch sym_ls(_symmetrized_matrix,
std::make_pair(!_round_trip and _has_start and
_has_end,
_start),
christo_sol,
nb_threads);
Cost sym_two_opt_gain = 0;
Cost sym_relocate_gain = 0;
Cost sym_or_opt_gain = 0;
do {
// All possible 2-opt moves.
sym_two_opt_gain = sym_ls.perform_all_two_opt_steps();
// All relocate moves.
sym_relocate_gain = sym_ls.perform_all_relocate_steps();
// All or-opt moves.
sym_or_opt_gain = sym_ls.perform_all_or_opt_steps();
} while ((sym_two_opt_gain > 0) or (sym_relocate_gain > 0) or
(sym_or_opt_gain > 0));
Index first_loc_index;
if (_has_start) {
// Use start value set in constructor from vehicle input.
first_loc_index = _start;
} else {
assert(_has_end);
// Requiring the tour to be described from the "forced" end
// location.
first_loc_index = _end;
}
std::list<Index> current_sol = sym_ls.get_tour(first_loc_index);
if (!_is_symmetric) {
// Back to the asymmetric problem, picking the best way.
std::list<Index> reverse_current_sol(current_sol);
reverse_current_sol.reverse();
Cost direct_cost = this->cost(current_sol);
Cost reverse_cost = this->cost(reverse_current_sol);
// Local search on asymmetric problem.
tsp::LocalSearch
asym_ls(_matrix,
std::make_pair(!_round_trip and _has_start and _has_end, _start),
(direct_cost <= reverse_cost) ? current_sol : reverse_current_sol,
nb_threads);
Cost asym_two_opt_gain = 0;
Cost asym_relocate_gain = 0;
Cost asym_or_opt_gain = 0;
Cost asym_avoid_loops_gain = 0;
do {
// All avoid-loops moves.
asym_avoid_loops_gain = asym_ls.perform_all_avoid_loop_steps();
// All possible 2-opt moves.
asym_two_opt_gain = asym_ls.perform_all_asym_two_opt_steps();
// All relocate moves.
asym_relocate_gain = asym_ls.perform_all_relocate_steps();
// All or-opt moves.
asym_or_opt_gain = asym_ls.perform_all_or_opt_steps();
} while ((asym_two_opt_gain > 0) or (asym_relocate_gain > 0) or
(asym_or_opt_gain > 0) or (asym_avoid_loops_gain > 0));
current_sol = asym_ls.get_tour(first_loc_index);
}
// Deal with open tour cases requiring adaptation.
if (!_has_start and _has_end) {
// The tour has been listed starting with the "forced" end. This
// index has to be popped and put back, the next element being the
// chosen start resulting from the optimization.
current_sol.push_back(current_sol.front());
current_sol.pop_front();
}
// Handle start and end removal as output list should only contain
// jobs.
if (_has_start) {
// Jobs start further away in the list.
current_sol.pop_front();
}
if (!_round_trip and _has_end) {
current_sol.pop_back();
}
// Back to ranks in input::_jobs.
std::vector<Index> init_ranks_sol;
std::transform(current_sol.cbegin(),
current_sol.cend(),
std::back_inserter(init_ranks_sol),
[&](const auto& i) { return _job_ranks[i]; });
return init_ranks_sol;
}
Solution TSP::solve(unsigned,
unsigned nb_threads,
const Timeout& timeout,
const std::vector<HeuristicParameters>&) const {
RawRoute r(_input, 0);
r.set_route(_input, raw_solve(nb_threads, timeout));
return utils::format_solution(_input, {r});
}
} // namespace vroom
<commit_msg>Splitting logic of available time for TSP local search.<commit_after>/*
This file is part of VROOM.
Copyright (c) 2015-2021, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include "problems/tsp/tsp.h"
#include "problems/tsp/heuristics/christofides.h"
#include "problems/tsp/heuristics/local_search.h"
#include "utils/helpers.h"
namespace vroom {
TSP::TSP(const Input& input, std::vector<Index> job_ranks, Index vehicle_rank)
: VRP(input),
_vehicle_rank(vehicle_rank),
_job_ranks(std::move(job_ranks)),
_is_symmetric(true),
_has_start(_input.vehicles[_vehicle_rank].has_start()),
_has_end(_input.vehicles[_vehicle_rank].has_end()) {
assert(!_job_ranks.empty());
// Pick ranks to select from input matrix.
std::vector<Index> matrix_ranks;
std::transform(_job_ranks.cbegin(),
_job_ranks.cend(),
std::back_inserter(matrix_ranks),
[&](const auto& r) { return _input.jobs[r].index(); });
if (_has_start) {
// Add start and remember rank in _matrix.
_start = matrix_ranks.size();
matrix_ranks.push_back(
_input.vehicles[_vehicle_rank].start.value().index());
}
if (_has_end) {
// Add end and remember rank in _matrix.
if (_has_start and (_input.vehicles[_vehicle_rank].start.value().index() ==
_input.vehicles[_vehicle_rank].end.value().index())) {
// Avoiding duplicate for identical ranks.
_end = _start;
} else {
_end = matrix_ranks.size();
matrix_ranks.push_back(
_input.vehicles[_vehicle_rank].end.value().index());
}
}
// Populate TSP-solving matrix.
_matrix = Matrix<Cost>(matrix_ranks.size());
const auto& v = _input.vehicles[vehicle_rank];
for (Index i = 0; i < matrix_ranks.size(); ++i) {
for (Index j = 0; j < matrix_ranks.size(); ++j) {
_matrix[i][j] = v.cost(matrix_ranks[i], matrix_ranks[j]);
}
}
// Distances on the diagonal are never used except in the minimum
// weight perfect matching (munkres call during the heuristic). This
// makes sure no node will be matched with itself at that time.
for (Index i = 0; i < _matrix.size(); ++i) {
_matrix[i][i] = INFINITE_COST;
}
_round_trip = _has_start and _has_end and (_start == _end);
if (!_round_trip) {
// Dealing with open tour cases. Exactly one of the following
// happens.
if (_has_start and !_has_end) {
// Forcing first location as start, end location decided during
// optimization.
for (Index i = 0; i < _matrix.size(); ++i) {
if (i != _start) {
_matrix[i][_start] = 0;
}
}
}
if (!_has_start and _has_end) {
// Forcing last location as end, start location decided during
// optimization.
for (Index j = 0; j < _matrix.size(); ++j) {
if (j != _end) {
_matrix[_end][j] = 0;
}
}
}
if (_has_start and _has_end) {
// Forcing first location as start, last location as end to
// produce an open tour.
assert(_start != _end);
_matrix[_end][_start] = 0;
for (Index j = 0; j < _matrix.size(); ++j) {
if ((j != _start) and (j != _end)) {
_matrix[_end][j] = INFINITE_COST;
}
}
}
}
// Compute symmetrized matrix and update _is_symmetric flag.
_symmetrized_matrix = Matrix<Cost>(_matrix.size());
const Cost& (*sym_f)(const Cost&, const Cost&) = std::min<Cost>;
if ((_has_start and !_has_end) or (!_has_start and _has_end)) {
// Using symmetrization with max as when only start or only end is
// forced, the matrix has a line or a column filled with zeros.
sym_f = std::max<Cost>;
}
for (Index i = 0; i < _matrix.size(); ++i) {
_symmetrized_matrix[i][i] = _matrix[i][i];
for (Index j = i + 1; j < _matrix.size(); ++j) {
_is_symmetric = _is_symmetric && (_matrix[i][j] == _matrix[j][i]);
Cost val = sym_f(_matrix[i][j], _matrix[j][i]);
_symmetrized_matrix[i][j] = val;
_symmetrized_matrix[j][i] = val;
}
}
}
Cost TSP::cost(const std::list<Index>& tour) const {
Cost cost = 0;
Index init_step = 0; // Initialization actually never used.
auto step = tour.cbegin();
if (tour.size() > 0) {
init_step = *step;
}
Index previous_step = init_step;
++step;
for (; step != tour.cend(); ++step) {
cost += _matrix[previous_step][*step];
previous_step = *step;
}
if (tour.size() > 0) {
cost += _matrix[previous_step][init_step];
}
return cost;
}
Cost TSP::symmetrized_cost(const std::list<Index>& tour) const {
Cost cost = 0;
Index init_step = 0; // Initialization actually never used.
auto step = tour.cbegin();
if (tour.size() > 0) {
init_step = *step;
}
Index previous_step = init_step;
++step;
for (; step != tour.cend(); ++step) {
cost += _symmetrized_matrix[previous_step][*step];
previous_step = *step;
}
if (tour.size() > 0) {
cost += _symmetrized_matrix[previous_step][init_step];
}
return cost;
}
std::vector<Index> TSP::raw_solve(unsigned nb_threads,
const Timeout& timeout) const {
// Compute deadline including heuristic computing time.
const Deadline deadline =
timeout.has_value()
? utils::now() + std::chrono::milliseconds(timeout.value())
: Deadline();
// Applying heuristic.
std::list<Index> christo_sol = tsp::christofides(_symmetrized_matrix);
Deadline sym_deadline = deadline;
if (deadline.has_value() and !_is_symmetric) {
// Rule of thumb if problem is asymmetric: dedicate 70% of the
// remaining available solving time to the symmetric local search,
// then the rest to the asymmetric version.
const auto after_heuristic = utils::now();
const auto remaining_ms =
(after_heuristic < deadline.value())
? std::chrono::duration_cast<std::chrono::milliseconds>(
deadline.value() - after_heuristic)
.count()
: 0;
sym_deadline =
after_heuristic +
std::chrono::milliseconds(static_cast<unsigned>(0.7 * remaining_ms));
}
// Local search on symmetric problem.
// Applying deterministic, fast local search to improve the current
// solution in a small amount of time. All possible moves for the
// different neighbourhoods are performed, stopping when reaching a
// local minima.
tsp::LocalSearch sym_ls(_symmetrized_matrix,
std::make_pair(!_round_trip and _has_start and
_has_end,
_start),
christo_sol,
nb_threads);
Cost sym_two_opt_gain = 0;
Cost sym_relocate_gain = 0;
Cost sym_or_opt_gain = 0;
do {
// All possible 2-opt moves.
sym_two_opt_gain = sym_ls.perform_all_two_opt_steps(sym_deadline);
// All relocate moves.
sym_relocate_gain = sym_ls.perform_all_relocate_steps(sym_deadline);
// All or-opt moves.
sym_or_opt_gain = sym_ls.perform_all_or_opt_steps(sym_deadline);
} while ((sym_two_opt_gain > 0) or (sym_relocate_gain > 0) or
(sym_or_opt_gain > 0));
Index first_loc_index;
if (_has_start) {
// Use start value set in constructor from vehicle input.
first_loc_index = _start;
} else {
assert(_has_end);
// Requiring the tour to be described from the "forced" end
// location.
first_loc_index = _end;
}
std::list<Index> current_sol = sym_ls.get_tour(first_loc_index);
if (!_is_symmetric) {
// Back to the asymmetric problem, picking the best way.
std::list<Index> reverse_current_sol(current_sol);
reverse_current_sol.reverse();
Cost direct_cost = this->cost(current_sol);
Cost reverse_cost = this->cost(reverse_current_sol);
// Local search on asymmetric problem.
tsp::LocalSearch
asym_ls(_matrix,
std::make_pair(!_round_trip and _has_start and _has_end, _start),
(direct_cost <= reverse_cost) ? current_sol : reverse_current_sol,
nb_threads);
Cost asym_two_opt_gain = 0;
Cost asym_relocate_gain = 0;
Cost asym_or_opt_gain = 0;
Cost asym_avoid_loops_gain = 0;
do {
// All avoid-loops moves.
asym_avoid_loops_gain = asym_ls.perform_all_avoid_loop_steps(deadline);
// All possible 2-opt moves.
asym_two_opt_gain = asym_ls.perform_all_asym_two_opt_steps(deadline);
// All relocate moves.
asym_relocate_gain = asym_ls.perform_all_relocate_steps(deadline);
// All or-opt moves.
asym_or_opt_gain = asym_ls.perform_all_or_opt_steps(deadline);
} while ((asym_two_opt_gain > 0) or (asym_relocate_gain > 0) or
(asym_or_opt_gain > 0) or (asym_avoid_loops_gain > 0));
current_sol = asym_ls.get_tour(first_loc_index);
}
// Deal with open tour cases requiring adaptation.
if (!_has_start and _has_end) {
// The tour has been listed starting with the "forced" end. This
// index has to be popped and put back, the next element being the
// chosen start resulting from the optimization.
current_sol.push_back(current_sol.front());
current_sol.pop_front();
}
// Handle start and end removal as output list should only contain
// jobs.
if (_has_start) {
// Jobs start further away in the list.
current_sol.pop_front();
}
if (!_round_trip and _has_end) {
current_sol.pop_back();
}
// Back to ranks in input::_jobs.
std::vector<Index> init_ranks_sol;
std::transform(current_sol.cbegin(),
current_sol.cend(),
std::back_inserter(init_ranks_sol),
[&](const auto& i) { return _job_ranks[i]; });
return init_ranks_sol;
}
Solution TSP::solve(unsigned,
unsigned nb_threads,
const Timeout& timeout,
const std::vector<HeuristicParameters>&) const {
RawRoute r(_input, 0);
r.set_route(_input, raw_solve(nb_threads, timeout));
return utils::format_solution(_input, {r});
}
} // namespace vroom
<|endoftext|>
|
<commit_before>#include <GL/glut.h>
#include <cstdlib>
GLubyte space[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
GLubyte letters[][13] = {
{0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xc3, 0xff, 0xc3, 0xc3, 0xc3, 0x66, 0x3c, 0x18}, //A
{0x00, 0x00, 0xfe, 0xc7, 0xc3, 0xc3, 0xc7, 0xfe, 0xc7, 0xc3, 0xc3, 0xc7, 0xfe}, //B
{0x00, 0x00, 0x7e, 0xe7, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xe7, 0x7e}, //C
{0x00, 0x00, 0xfc, 0xce, 0xc7, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc7, 0xce, 0xfc}, //D
{0x00, 0x00, 0xff, 0xc0, 0xc0, 0xc0, 0xc0, 0xfc, 0xc0, 0xc0, 0xc0, 0xc0, 0xff}, //E
{0x00, 0x00, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xfc, 0xc0, 0xc0, 0xc0, 0xff}, //F
{0x00, 0x00, 0x7e, 0xe7, 0xc3, 0xc3, 0xcf, 0xc0, 0xc0, 0xc0, 0xc0, 0xe7, 0x7e}, //G
{0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xff, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3}, //H
{0x00, 0x00, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7e}, //I
{0x00, 0x00, 0x7c, 0xee, 0xc6, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06}, //J
{0x00, 0x00, 0xc3, 0xc6, 0xcc, 0xd8, 0xf0, 0xe0, 0xf0, 0xd8, 0xcc, 0xc6, 0xc3}, //K
{0x00, 0x00, 0xff, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0}, //L
{0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xdb, 0xff, 0xff, 0xe7, 0xc3}, //M
{0x00, 0x00, 0xc7, 0xc7, 0xcf, 0xcf, 0xdf, 0xdb, 0xfb, 0xf3, 0xf3, 0xe3, 0xe3}, //N
{0x00, 0x00, 0x7e, 0xe7, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xe7, 0x7e}, //O
{0x00, 0x00, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xfe, 0xc7, 0xc3, 0xc3, 0xc7, 0xfe}, //P
{0x00, 0x00, 0x3f, 0x6e, 0xdf, 0xdb, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0x66, 0x3c}, //Q
{0x00, 0x00, 0xc3, 0xc6, 0xcc, 0xd8, 0xf0, 0xfe, 0xc7, 0xc3, 0xc3, 0xc7, 0xfe}, //R
{0x00, 0x00, 0x7e, 0xe7, 0x03, 0x03, 0x07, 0x7e, 0xe0, 0xc0, 0xc0, 0xe7, 0x7e}, //S
{0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xff}, //T
{0x00, 0x00, 0x7e, 0xe7, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3}, //U
{0x00, 0x00, 0x18, 0x3c, 0x3c, 0x66, 0x66, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3}, //V
{0x00, 0x00, 0xc3, 0xe7, 0xff, 0xff, 0xdb, 0xdb, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3}, //W
{0x00, 0x00, 0xc3, 0x66, 0x66, 0x3c, 0x3c, 0x18, 0x3c, 0x3c, 0x66, 0x66, 0xc3}, //X
{0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x3c, 0x66, 0x66, 0xc3}, //Y
{0x00, 0x00, 0xff, 0xc0, 0xc0, 0x60, 0x30, 0x7e, 0x0c, 0x06, 0x03, 0x03, 0xff} //Z
};
void init(void)
{
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glClearColor(0.0, 0.0, 0.0, 0.0);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 1.0, 1.0);
//first name
glRasterPos2i(15, 55);
glBitmap(8, 13, 0.0, 2.0, 10.0, 0.0, letters[12]); //M
glBitmap(8, 13, 0.0, 2.0, 10.0, 0.0, letters[8]); //I
glBitmap(8, 13, 0.0, 2.0, 10.0, 0.0, letters[2]); //C
glBitmap(8, 13, 0.0, 2.0, 10.0, 0.0, letters[7]); //H
glBitmap(8, 13, 0.0, 2.0, 10.0, 0.0, letters[0]); //A
glBitmap(8, 13, 0.0, 2.0, 10.0, 0.0, letters[4]); //E
glBitmap(8, 13, 0.0, 2.0, 10.0, 0.0, letters[11]); //L
//last name
glRasterPos2i(15, 35);
glBitmap(8, 13, 0.0, 2.0, 10.0, 0.0, letters[25]); //Z
glBitmap(8, 13, 0.0, 2.0, 10.0, 0.0, letters[17]); //R
glBitmap(8, 13, 0.0, 2.0, 10.0, 0.0, letters[8]); //I
glBitmap(8, 13, 0.0, 2.0, 10.0, 0.0, letters[12]); //M
glBitmap(8, 13, 0.0, 2.0, 10.0, 0.0, letters[18]); //S
glBitmap(8, 13, 0.0, 2.0, 10.0, 0.0, letters[4]); //E
glBitmap(8, 13, 0.0, 2.0, 10.0, 0.0, letters[10]); //K
glFlush();
}
void reshape(int width, int height)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, (GLfloat) width, 0.0, (GLfloat) height);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glMatrixMode(GL_PROJECTION);
glutInitWindowSize(100, 100);
glutInitWindowPosition(100, 100);
glutCreateWindow("Name");
init();
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutMainLoop();
return 0;
}<commit_msg>refactor rendering letters<commit_after>#include <GL/glut.h>
#include <cstdlib>
GLubyte space[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
GLubyte letters[][13] = {
{0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xc3, 0xff, 0xc3, 0xc3, 0xc3, 0x66, 0x3c, 0x18}, //A
{0x00, 0x00, 0xfe, 0xc7, 0xc3, 0xc3, 0xc7, 0xfe, 0xc7, 0xc3, 0xc3, 0xc7, 0xfe}, //B
{0x00, 0x00, 0x7e, 0xe7, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xe7, 0x7e}, //C
{0x00, 0x00, 0xfc, 0xce, 0xc7, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc7, 0xce, 0xfc}, //D
{0x00, 0x00, 0xff, 0xc0, 0xc0, 0xc0, 0xc0, 0xfc, 0xc0, 0xc0, 0xc0, 0xc0, 0xff}, //E
{0x00, 0x00, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xfc, 0xc0, 0xc0, 0xc0, 0xff}, //F
{0x00, 0x00, 0x7e, 0xe7, 0xc3, 0xc3, 0xcf, 0xc0, 0xc0, 0xc0, 0xc0, 0xe7, 0x7e}, //G
{0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xff, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3}, //H
{0x00, 0x00, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7e}, //I
{0x00, 0x00, 0x7c, 0xee, 0xc6, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06}, //J
{0x00, 0x00, 0xc3, 0xc6, 0xcc, 0xd8, 0xf0, 0xe0, 0xf0, 0xd8, 0xcc, 0xc6, 0xc3}, //K
{0x00, 0x00, 0xff, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0}, //L
{0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xdb, 0xff, 0xff, 0xe7, 0xc3}, //M
{0x00, 0x00, 0xc7, 0xc7, 0xcf, 0xcf, 0xdf, 0xdb, 0xfb, 0xf3, 0xf3, 0xe3, 0xe3}, //N
{0x00, 0x00, 0x7e, 0xe7, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xe7, 0x7e}, //O
{0x00, 0x00, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xfe, 0xc7, 0xc3, 0xc3, 0xc7, 0xfe}, //P
{0x00, 0x00, 0x3f, 0x6e, 0xdf, 0xdb, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0x66, 0x3c}, //Q
{0x00, 0x00, 0xc3, 0xc6, 0xcc, 0xd8, 0xf0, 0xfe, 0xc7, 0xc3, 0xc3, 0xc7, 0xfe}, //R
{0x00, 0x00, 0x7e, 0xe7, 0x03, 0x03, 0x07, 0x7e, 0xe0, 0xc0, 0xc0, 0xe7, 0x7e}, //S
{0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xff}, //T
{0x00, 0x00, 0x7e, 0xe7, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3}, //U
{0x00, 0x00, 0x18, 0x3c, 0x3c, 0x66, 0x66, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3}, //V
{0x00, 0x00, 0xc3, 0xe7, 0xff, 0xff, 0xdb, 0xdb, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3}, //W
{0x00, 0x00, 0xc3, 0x66, 0x66, 0x3c, 0x3c, 0x18, 0x3c, 0x3c, 0x66, 0x66, 0xc3}, //X
{0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x3c, 0x66, 0x66, 0xc3}, //Y
{0x00, 0x00, 0xff, 0xc0, 0xc0, 0x60, 0x30, 0x7e, 0x0c, 0x06, 0x03, 0x03, 0xff} //Z
};
void init(void)
{
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glClearColor(0.0, 0.0, 0.0, 0.0);
}
void renderLetter(int index)
{
glBitmap(8, 13, 0.0, 2.0, 10.0, 0.0, letters[index]);
}
void renderFirstName()
{
renderLetter(12); //M
renderLetter(8); //I
renderLetter(2); //C
renderLetter(7); //H
renderLetter(0); //A
renderLetter(4); //E
renderLetter(11); //L
}
void renderLastName()
{
renderLetter(25); //Z
renderLetter(17); //R
renderLetter(8); //I
renderLetter(12); //M
renderLetter(18); //S
renderLetter(4); //E
renderLetter(10); //K
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 1.0, 1.0);
glRasterPos2i(15, 55);
renderFirstName();
glRasterPos2i(15, 35);
renderLastName();
glFlush();
}
void reshape(int width, int height)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, (GLfloat) width, 0.0, (GLfloat) height);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glMatrixMode(GL_PROJECTION);
glutInitWindowSize(100, 100);
glutInitWindowPosition(100, 100);
glutCreateWindow("Name");
init();
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutMainLoop();
return 0;
}<|endoftext|>
|
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// 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
//
// Current versions can be found at www.libavg.de
//
#include "CurveNode.h"
#include "NodeDefinition.h"
#include "../graphics/VertexArray.h"
#include "../base/Exception.h"
#include "../base/MathHelper.h"
#include "../base/CubicSpline.h"
#include <iostream>
#include <sstream>
using namespace std;
namespace avg {
NodeDefinition CurveNode::createDefinition()
{
return NodeDefinition("curve", Node::buildNode<CurveNode>)
.extendDefinition(VectorNode::createDefinition())
.addArg(Arg<double>("x1", 0, true, offsetof(CurveNode, m_P1.x)))
.addArg(Arg<double>("y1", 0, true, offsetof(CurveNode, m_P1.y)))
.addArg(Arg<double>("x2", 0, true, offsetof(CurveNode, m_P2.x)))
.addArg(Arg<double>("y2", 0, true, offsetof(CurveNode, m_P2.y)))
.addArg(Arg<double>("x3", 0, true, offsetof(CurveNode, m_P3.x)))
.addArg(Arg<double>("y3", 0, true, offsetof(CurveNode, m_P3.y)))
.addArg(Arg<double>("x4", 0, true, offsetof(CurveNode, m_P4.x)))
.addArg(Arg<double>("y4", 0, true, offsetof(CurveNode, m_P4.y)));
}
CurveNode::CurveNode(const ArgList& Args, bool bFromXML)
: VectorNode(Args)
{
Args.setMembers(this);
}
CurveNode::~CurveNode()
{
}
void CurveNode::setRenderingEngines(DisplayEngine * pDisplayEngine,
AudioEngine * pAudioEngine)
{
setDrawNeeded(true);
VectorNode::setRenderingEngines(pDisplayEngine, pAudioEngine);
}
double CurveNode::getX1() const
{
return m_P1.x;
}
void CurveNode::setX1(double x)
{
m_P1.x = x;
setDrawNeeded(true);
}
double CurveNode::getY1() const
{
return m_P1.y;
}
void CurveNode::setY1(double y)
{
m_P1.y = y;
setDrawNeeded(true);
}
const DPoint& CurveNode::getPos1() const
{
return m_P1;
}
void CurveNode::setPos1(const DPoint& pt)
{
m_P1 = pt;
setDrawNeeded(true);
}
double CurveNode::getX2() const
{
return m_P2.x;
}
void CurveNode::setX2(double x)
{
m_P2.x = x;
setDrawNeeded(true);
}
double CurveNode::getY2() const
{
return m_P2.y;
}
void CurveNode::setY2(double y)
{
m_P2.y = y;
setDrawNeeded(true);
}
const DPoint& CurveNode::getPos2() const
{
return m_P2;
}
void CurveNode::setPos2(const DPoint& pt)
{
m_P2 = pt;
setDrawNeeded(true);
}
double CurveNode::getX3() const
{
return m_P3.x;
}
void CurveNode::setX3(double x)
{
m_P3.x = x;
setDrawNeeded(true);
}
double CurveNode::getY3() const
{
return m_P3.y;
}
void CurveNode::setY3(double y)
{
m_P3.y = y;
setDrawNeeded(true);
}
const DPoint& CurveNode::getPos3() const
{
return m_P3;
}
void CurveNode::setPos3(const DPoint& pt)
{
m_P3 = pt;
setDrawNeeded(true);
}
double CurveNode::getX4() const
{
return m_P4.x;
}
void CurveNode::setX4(double x)
{
m_P4.x = x;
setDrawNeeded(true);
}
double CurveNode::getY4() const
{
return m_P4.y;
}
void CurveNode::setY4(double y)
{
m_P4.y = y;
setDrawNeeded(true);
}
const DPoint& CurveNode::getPos4() const
{
return m_P4;
}
void CurveNode::setPos4(const DPoint& pt)
{
m_P4 = pt;
setDrawNeeded(true);
}
int CurveNode::getNumTriangles()
{
return (getCurveLen())*2;
}
void CurveNode::updateData(VertexArrayPtr pVertexArray, int triIndex, double opacity,
bool bParentDrawNeeded)
{
if (isDrawNeeded() || bParentDrawNeeded) {
updateLines();
double curOpacity = opacity*getOpacity();
Pixel32 color = getColorVal();
color.setA(unsigned char(curOpacity*255));
for (unsigned i=0; i<m_LeftCurve.size()-1; ++i) {
const DPoint& p1 = m_LeftCurve[i];
const DPoint& p2 = m_LeftCurve[i+1];
const DPoint& p3 = m_RightCurve[i+1];
const DPoint& p4 = m_RightCurve[i];
pVertexArray->setPos(triIndex+i*2, 0, p1, DPoint(0,0), color);
pVertexArray->setPos(triIndex+i*2, 1, p2, DPoint(0,0), color);
pVertexArray->setPos(triIndex+i*2, 2, p3, DPoint(0,0), color);
pVertexArray->setPos(triIndex+i*2+1, 0, p1, DPoint(0,0), color);
pVertexArray->setPos(triIndex+i*2+1, 1, p3, DPoint(0,0), color);
pVertexArray->setPos(triIndex+i*2+1, 2, p4, DPoint(0,0), color);
}
}
setDrawNeeded(false);
}
int CurveNode::getCurveLen()
{
// Calc. upper bound for spline length.
return int(calcDist(m_P2,m_P1)+calcDist(m_P3,m_P2)+calcDist(m_P4,m_P3));
}
void CurveNode::updateLines()
{
// Generate control points the way CubicSpline.cpp wants.
static double ControlPoints[] = {-1, 0, 1, 2};
double xPoints[] = {2*m_P1.x-m_P2.x, m_P1.x, m_P4.x, 2*m_P4.x-m_P3.x};
double yPoints[] = {2*m_P1.y-m_P2.y, m_P1.y, m_P4.y, 2*m_P4.y-m_P3.y};
vector<double> splineControl = vectorFromCArray(4, ControlPoints);
vector<double> splineX = vectorFromCArray(4, xPoints);
CubicSpline xSpline(splineControl, splineX);
vector<double> splineY = vectorFromCArray(4, yPoints);
CubicSpline ySpline(splineControl, splineY);
// Calc. upper bound for spline length.
double len = getCurveLen();
vector<DPoint> centerCurve;
for (int i=0; i<len; ++i) {
DPoint curPt(xSpline.interpolate(i/len), ySpline.interpolate(i/len));
centerCurve.push_back(curPt);
}
centerCurve.push_back(m_P4);
m_LeftCurve.clear();
m_RightCurve.clear();
addLRCurvePoint(centerCurve[0], centerCurve[1]-centerCurve[0]);
for (unsigned i=1; i<centerCurve.size()-1; ++i) {
addLRCurvePoint(centerCurve[i], centerCurve[i-1]-centerCurve[i+1]);
}
unsigned l = centerCurve.size();
addLRCurvePoint(centerCurve[l-1], centerCurve[l-2]-centerCurve[l-1]);
}
void CurveNode::addLRCurvePoint(const DPoint& pos, const DPoint& delta)
{
// TODO: Use correct derivative of the curve.
DPoint m(delta);
m.normalize();
DPoint w = DPoint(m.y, -m.x)*getStrokeWidth()/2;
m_LeftCurve.push_back(pos-w);
m_RightCurve.push_back(pos+w);
}
}
<commit_msg>Fixed mac os x compile.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// 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
//
// Current versions can be found at www.libavg.de
//
#include "CurveNode.h"
#include "NodeDefinition.h"
#include "../graphics/VertexArray.h"
#include "../base/Exception.h"
#include "../base/MathHelper.h"
#include "../base/CubicSpline.h"
#include <iostream>
#include <sstream>
using namespace std;
namespace avg {
NodeDefinition CurveNode::createDefinition()
{
return NodeDefinition("curve", Node::buildNode<CurveNode>)
.extendDefinition(VectorNode::createDefinition())
.addArg(Arg<double>("x1", 0, true, offsetof(CurveNode, m_P1.x)))
.addArg(Arg<double>("y1", 0, true, offsetof(CurveNode, m_P1.y)))
.addArg(Arg<double>("x2", 0, true, offsetof(CurveNode, m_P2.x)))
.addArg(Arg<double>("y2", 0, true, offsetof(CurveNode, m_P2.y)))
.addArg(Arg<double>("x3", 0, true, offsetof(CurveNode, m_P3.x)))
.addArg(Arg<double>("y3", 0, true, offsetof(CurveNode, m_P3.y)))
.addArg(Arg<double>("x4", 0, true, offsetof(CurveNode, m_P4.x)))
.addArg(Arg<double>("y4", 0, true, offsetof(CurveNode, m_P4.y)));
}
CurveNode::CurveNode(const ArgList& Args, bool bFromXML)
: VectorNode(Args)
{
Args.setMembers(this);
}
CurveNode::~CurveNode()
{
}
void CurveNode::setRenderingEngines(DisplayEngine * pDisplayEngine,
AudioEngine * pAudioEngine)
{
setDrawNeeded(true);
VectorNode::setRenderingEngines(pDisplayEngine, pAudioEngine);
}
double CurveNode::getX1() const
{
return m_P1.x;
}
void CurveNode::setX1(double x)
{
m_P1.x = x;
setDrawNeeded(true);
}
double CurveNode::getY1() const
{
return m_P1.y;
}
void CurveNode::setY1(double y)
{
m_P1.y = y;
setDrawNeeded(true);
}
const DPoint& CurveNode::getPos1() const
{
return m_P1;
}
void CurveNode::setPos1(const DPoint& pt)
{
m_P1 = pt;
setDrawNeeded(true);
}
double CurveNode::getX2() const
{
return m_P2.x;
}
void CurveNode::setX2(double x)
{
m_P2.x = x;
setDrawNeeded(true);
}
double CurveNode::getY2() const
{
return m_P2.y;
}
void CurveNode::setY2(double y)
{
m_P2.y = y;
setDrawNeeded(true);
}
const DPoint& CurveNode::getPos2() const
{
return m_P2;
}
void CurveNode::setPos2(const DPoint& pt)
{
m_P2 = pt;
setDrawNeeded(true);
}
double CurveNode::getX3() const
{
return m_P3.x;
}
void CurveNode::setX3(double x)
{
m_P3.x = x;
setDrawNeeded(true);
}
double CurveNode::getY3() const
{
return m_P3.y;
}
void CurveNode::setY3(double y)
{
m_P3.y = y;
setDrawNeeded(true);
}
const DPoint& CurveNode::getPos3() const
{
return m_P3;
}
void CurveNode::setPos3(const DPoint& pt)
{
m_P3 = pt;
setDrawNeeded(true);
}
double CurveNode::getX4() const
{
return m_P4.x;
}
void CurveNode::setX4(double x)
{
m_P4.x = x;
setDrawNeeded(true);
}
double CurveNode::getY4() const
{
return m_P4.y;
}
void CurveNode::setY4(double y)
{
m_P4.y = y;
setDrawNeeded(true);
}
const DPoint& CurveNode::getPos4() const
{
return m_P4;
}
void CurveNode::setPos4(const DPoint& pt)
{
m_P4 = pt;
setDrawNeeded(true);
}
int CurveNode::getNumTriangles()
{
return (getCurveLen())*2;
}
void CurveNode::updateData(VertexArrayPtr pVertexArray, int triIndex, double opacity,
bool bParentDrawNeeded)
{
if (isDrawNeeded() || bParentDrawNeeded) {
updateLines();
double curOpacity = opacity*getOpacity();
Pixel32 color = getColorVal();
color.setA((unsigned char)(curOpacity*255));
for (unsigned i=0; i<m_LeftCurve.size()-1; ++i) {
const DPoint& p1 = m_LeftCurve[i];
const DPoint& p2 = m_LeftCurve[i+1];
const DPoint& p3 = m_RightCurve[i+1];
const DPoint& p4 = m_RightCurve[i];
pVertexArray->setPos(triIndex+i*2, 0, p1, DPoint(0,0), color);
pVertexArray->setPos(triIndex+i*2, 1, p2, DPoint(0,0), color);
pVertexArray->setPos(triIndex+i*2, 2, p3, DPoint(0,0), color);
pVertexArray->setPos(triIndex+i*2+1, 0, p1, DPoint(0,0), color);
pVertexArray->setPos(triIndex+i*2+1, 1, p3, DPoint(0,0), color);
pVertexArray->setPos(triIndex+i*2+1, 2, p4, DPoint(0,0), color);
}
}
setDrawNeeded(false);
}
int CurveNode::getCurveLen()
{
// Calc. upper bound for spline length.
return int(calcDist(m_P2,m_P1)+calcDist(m_P3,m_P2)+calcDist(m_P4,m_P3));
}
void CurveNode::updateLines()
{
// Generate control points the way CubicSpline.cpp wants.
static double ControlPoints[] = {-1, 0, 1, 2};
double xPoints[] = {2*m_P1.x-m_P2.x, m_P1.x, m_P4.x, 2*m_P4.x-m_P3.x};
double yPoints[] = {2*m_P1.y-m_P2.y, m_P1.y, m_P4.y, 2*m_P4.y-m_P3.y};
vector<double> splineControl = vectorFromCArray(4, ControlPoints);
vector<double> splineX = vectorFromCArray(4, xPoints);
CubicSpline xSpline(splineControl, splineX);
vector<double> splineY = vectorFromCArray(4, yPoints);
CubicSpline ySpline(splineControl, splineY);
// Calc. upper bound for spline length.
double len = getCurveLen();
vector<DPoint> centerCurve;
for (int i=0; i<len; ++i) {
DPoint curPt(xSpline.interpolate(i/len), ySpline.interpolate(i/len));
centerCurve.push_back(curPt);
}
centerCurve.push_back(m_P4);
m_LeftCurve.clear();
m_RightCurve.clear();
addLRCurvePoint(centerCurve[0], centerCurve[1]-centerCurve[0]);
for (unsigned i=1; i<centerCurve.size()-1; ++i) {
addLRCurvePoint(centerCurve[i], centerCurve[i-1]-centerCurve[i+1]);
}
unsigned l = centerCurve.size();
addLRCurvePoint(centerCurve[l-1], centerCurve[l-2]-centerCurve[l-1]);
}
void CurveNode::addLRCurvePoint(const DPoint& pos, const DPoint& delta)
{
// TODO: Use correct derivative of the curve.
DPoint m(delta);
m.normalize();
DPoint w = DPoint(m.y, -m.x)*getStrokeWidth()/2;
m_LeftCurve.push_back(pos-w);
m_RightCurve.push_back(pos+w);
}
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 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
*
*****************************************************************************/
//$Id$
// mapnik
#include <mapnik/point_symbolizer.hpp>
#include <mapnik/image_data.hpp>
#include <mapnik/image_reader.hpp>
// boost
#include <boost/scoped_ptr.hpp>
// stl
#include <iostream>
namespace mapnik
{
point_symbolizer::point_symbolizer()
: symbolizer_with_image(boost::shared_ptr<ImageData32>(new ImageData32(4,4))),
overlap_(false),
opacity_(1.0)
{
//default point symbol is black 4x4px square
image_->set(0xff000000);
}
point_symbolizer::point_symbolizer(std::string const& file,
std::string const& type,
unsigned width,unsigned height)
: symbolizer_with_image(file, type, width, height),
overlap_(false),
opacity_(1.0)
{ }
point_symbolizer::point_symbolizer(point_symbolizer const& rhs)
: symbolizer_with_image(rhs),
overlap_(rhs.overlap_),
opacity_(rhs.opacity_)
{}
void point_symbolizer::set_allow_overlap(bool overlap)
{
overlap_ = overlap;
}
bool point_symbolizer::get_allow_overlap() const
{
return overlap_;
}
}
<commit_msg>+ corrected init order <commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 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
*
*****************************************************************************/
//$Id$
// mapnik
#include <mapnik/point_symbolizer.hpp>
#include <mapnik/image_data.hpp>
#include <mapnik/image_reader.hpp>
// boost
#include <boost/scoped_ptr.hpp>
// stl
#include <iostream>
namespace mapnik
{
point_symbolizer::point_symbolizer()
: symbolizer_with_image(boost::shared_ptr<ImageData32>(new ImageData32(4,4))),
opacity_(1.0),
overlap_(false)
{
//default point symbol is black 4x4px square
image_->set(0xff000000);
}
point_symbolizer::point_symbolizer(std::string const& file,
std::string const& type,
unsigned width,unsigned height)
: symbolizer_with_image(file, type, width, height),
opacity_(1.0),
overlap_(false)
{ }
point_symbolizer::point_symbolizer(point_symbolizer const& rhs)
: symbolizer_with_image(rhs),
opacity_(rhs.opacity_),
overlap_(rhs.overlap_)
{}
void point_symbolizer::set_allow_overlap(bool overlap)
{
overlap_ = overlap;
}
bool point_symbolizer::get_allow_overlap() const
{
return overlap_;
}
}
<|endoftext|>
|
<commit_before>/**
* pretty_print_msg.cpp
*
* @author Nathan Campos
*/
#include <cstdio>
#include <cstdlib>
#include <cstdlib>
#include <sstream>
#include "channels.h"
#include "color.h"
#include "irc_reply_codes.h"
#include "message.h"
#include "pretty_print_msg.h"
using namespace std;
/**
* Constructor for the class.
*
* \param _buffer Message string.
*/
Pretty_Print_Message::Pretty_Print_Message(const char *_buffer) {
buffer = _buffer;
echo = true;
}
/**
* Create a color string based on the string's letters.
*
* \param nickname Nickname to be colorized.
* \param include_msg Include the whole message with it.
* \return Colorized string.
*/
string Pretty_Print_Message::color_string(string nickname, bool include_msg) {
// Generate a color for the nick based on its letters.
string chars = " abcdefghijklmnopqrstuvwxyz1234567890_-";
int color = 0;
char color_chr[2];
for (size_t i = 0; i < nickname.size(); i++) {
// Get the characted position in our dictionary.
size_t pos = chars.find(nickname.at(i));
// If we couldn't find it just default it to 10.
if (pos == string::npos) {
pos = 10;
}
color += pos;
}
// Build the string.
color = (color % 7) + 1;
sprintf(color_chr, "%d", color);
if (!include_msg) {
return "\033[1m\033[3" + string(color_chr) + "m";
} else {
return "\033[1m\033[3" + string(color_chr) + "m" + nickname + RESET;
}
}
/**
* Generate the pretty formatted string based on the message.
*
* \param message Pointer to a Message class.
* \param channels Pointer to a Channels class.
* \return Prettyfied string.
*/
string Pretty_Print_Message::generate(Message &message, Channels &channels) {
// Parse and return a better and more human-readable message.
string str_buffer(buffer);
vector<string> arguments = message.get_command_args();
if (message.get_command() == "PRIVMSG") {
if (arguments.at(0).at(0) == '#') {
// Channel message.
if (arguments.at(0) != "#" + channels.list.at(channels.current)) {
echo = false;
}
// A normal message.
string nickname = message.get_nickname();
str_buffer = color_string(nickname, false) + "<" + nickname + "> " + string(RESET) + arguments.at(1) + "\r\n";
if (arguments.at(1).size() > 6) {
if (arguments.at(1).substr(0, 7) == "\001ACTION") {
// This is a ACTION message.
str_buffer = string(BOLDMAGENTA) + "\u2022 " + message.get_nickname() + " " + arguments.at(1).substr(8) + string(RESET) + "\r\n";
}
}
}
} else if (message.get_command() == "JOIN") {
// Someone joined the channel.
// TODO: Check if this isn't adding more than one time when another user joins the channel.
// If it is move this to the repl loop and create an eval return for it.
if (!arguments.empty()) {
channels.add(arguments.at(0).substr(1, arguments.at(0).find(":") - 1));
}
str_buffer = string(BOLDGREEN) + "> " + string(RESET) + message.get_nickname() + " joined " + arguments.at(0) + "\r\n";
} else if (message.get_command() == "PART") {
// Someone left the channel.
str_buffer = string(BOLDRED) + "< " + string(RESET) + message.get_nickname() + " left\r\n";
} else if (message.get_command() == "KICK") {
// Someone got kicked.
str_buffer = string(BOLDRED) + "<< " + message.get_nickname() + " got kicked from " + arguments.at(0) + " (" + arguments.at(2) + ")" + string(RESET) + "\r\n";
} else if (message.get_command() == "MODE") {
// Changing modes.
str_buffer = string(BOLDBLUE) + "* " + string(RESET) + message.get_nickname() + " set mode ";
for (unsigned int i = 0; i < arguments.size(); i++) {
str_buffer += arguments.at(i) + " ";
}
str_buffer += "\r\n";
} else if (message.get_command() == "QUIT") {
// Quitting.
str_buffer = string(BOLDRED) + "<< " + string(RESET) + message.get_nickname() + " quit (" + arguments.at(0) + ")\r\n";
} else if (message.get_command() == "ERROR") {
// Oh noes! Error!
str_buffer = string(BOLDRED) + "Error: " + arguments.at(0) + string(RESET) + "\r\n";
} else if (message.get_command() == "NICK") {
// Someone is chaning the nick.
str_buffer = string(BOLDBLUE) + "* " + color_string(message.get_nickname(), true) + " is now known as " + color_string(arguments.at(0), true) + "\r\n";
} else {
// Might be a server message, so let's check for the reply code.
int reply_code = message.get_reply_code();
ostringstream stream;
switch (reply_code) {
case RPL_TOPIC:
// Got a topic.
str_buffer = string(BOLDWHITE) + "Topic: " + "\"" + arguments.at(2) + "\"" + string(RESET) + "\r\n";
break;
case RPL_TOPICWHOTIME:
// Got who set the topic.
str_buffer = "Topic set by " + arguments.at(2).substr(0, arguments.at(2).find('!')) + "\r\n";
break;
case RPL_NAMREPLY:
// Got a list of the people online.
stream << "Users: ";
str_buffer = arguments.at(3);
while (str_buffer.find(" ") != string::npos) {
size_t pos = str_buffer.find(" ");
stream << color_string(str_buffer.substr(0, pos), true) << " ";
str_buffer.erase(0, pos + 1);
}
if (!str_buffer.empty()) {
stream << color_string(str_buffer, true);
}
stream << "\r\n";
str_buffer = stream.str();
break;
case RPL_ENDOFNAMES:
// (Ignored) Got the end of the online names list
str_buffer = "";
break;
default:
// Got some other kind of message that we haven't covered.
str_buffer = "";
for (size_t i = 1; i < arguments.size(); i++) {
str_buffer += arguments.at(i) + " ";
}
str_buffer += "\r\n";
break;
}
}
if (arguments.at(0).at(0) == '#') {
channels.cache(arguments.at(0).substr(1), str_buffer);
}
return str_buffer;
}
/**
* Check if the message should be echoed.
*
* \return true if the message should be echoed.
*/
bool Pretty_Print_Message::echo_message() {
return echo;
}
<commit_msg>Fixed a typo in a #include<commit_after>/**
* pretty_print_msg.cpp
*
* @author Nathan Campos
*/
#include <cstdio>
#include <cstdlib>
#include <sstream>
#include "channels.h"
#include "color.h"
#include "irc_reply_codes.h"
#include "message.h"
#include "pretty_print_msg.h"
using namespace std;
/**
* Constructor for the class.
*
* \param _buffer Message string.
*/
Pretty_Print_Message::Pretty_Print_Message(const char *_buffer) {
buffer = _buffer;
echo = true;
}
/**
* Create a color string based on the string's letters.
*
* \param nickname Nickname to be colorized.
* \param include_msg Include the whole message with it.
* \return Colorized string.
*/
string Pretty_Print_Message::color_string(string nickname, bool include_msg) {
// Generate a color for the nick based on its letters.
string chars = " abcdefghijklmnopqrstuvwxyz1234567890_-";
int color = 0;
char color_chr[2];
for (size_t i = 0; i < nickname.size(); i++) {
// Get the characted position in our dictionary.
size_t pos = chars.find(nickname.at(i));
// If we couldn't find it just default it to 10.
if (pos == string::npos) {
pos = 10;
}
color += pos;
}
// Build the string.
color = (color % 7) + 1;
sprintf(color_chr, "%d", color);
if (!include_msg) {
return "\033[1m\033[3" + string(color_chr) + "m";
} else {
return "\033[1m\033[3" + string(color_chr) + "m" + nickname + RESET;
}
}
/**
* Generate the pretty formatted string based on the message.
*
* \param message Pointer to a Message class.
* \param channels Pointer to a Channels class.
* \return Prettyfied string.
*/
string Pretty_Print_Message::generate(Message &message, Channels &channels) {
// Parse and return a better and more human-readable message.
string str_buffer(buffer);
vector<string> arguments = message.get_command_args();
if (message.get_command() == "PRIVMSG") {
if (arguments.at(0).at(0) == '#') {
// Channel message.
if (arguments.at(0) != "#" + channels.list.at(channels.current)) {
echo = false;
}
// A normal message.
string nickname = message.get_nickname();
str_buffer = color_string(nickname, false) + "<" + nickname + "> " + string(RESET) + arguments.at(1) + "\r\n";
if (arguments.at(1).size() > 6) {
if (arguments.at(1).substr(0, 7) == "\001ACTION") {
// This is a ACTION message.
str_buffer = string(BOLDMAGENTA) + "\u2022 " + message.get_nickname() + " " + arguments.at(1).substr(8) + string(RESET) + "\r\n";
}
}
}
} else if (message.get_command() == "JOIN") {
// Someone joined the channel.
// TODO: Check if this isn't adding more than one time when another user joins the channel.
// If it is move this to the repl loop and create an eval return for it.
if (!arguments.empty()) {
channels.add(arguments.at(0).substr(1, arguments.at(0).find(":") - 1));
}
str_buffer = string(BOLDGREEN) + "> " + string(RESET) + message.get_nickname() + " joined " + arguments.at(0) + "\r\n";
} else if (message.get_command() == "PART") {
// Someone left the channel.
str_buffer = string(BOLDRED) + "< " + string(RESET) + message.get_nickname() + " left\r\n";
} else if (message.get_command() == "KICK") {
// Someone got kicked.
str_buffer = string(BOLDRED) + "<< " + message.get_nickname() + " got kicked from " + arguments.at(0) + " (" + arguments.at(2) + ")" + string(RESET) + "\r\n";
} else if (message.get_command() == "MODE") {
// Changing modes.
str_buffer = string(BOLDBLUE) + "* " + string(RESET) + message.get_nickname() + " set mode ";
for (unsigned int i = 0; i < arguments.size(); i++) {
str_buffer += arguments.at(i) + " ";
}
str_buffer += "\r\n";
} else if (message.get_command() == "QUIT") {
// Quitting.
str_buffer = string(BOLDRED) + "<< " + string(RESET) + message.get_nickname() + " quit (" + arguments.at(0) + ")\r\n";
} else if (message.get_command() == "ERROR") {
// Oh noes! Error!
str_buffer = string(BOLDRED) + "Error: " + arguments.at(0) + string(RESET) + "\r\n";
} else if (message.get_command() == "NICK") {
// Someone is chaning the nick.
str_buffer = string(BOLDBLUE) + "* " + color_string(message.get_nickname(), true) + " is now known as " + color_string(arguments.at(0), true) + "\r\n";
} else {
// Might be a server message, so let's check for the reply code.
int reply_code = message.get_reply_code();
ostringstream stream;
switch (reply_code) {
case RPL_TOPIC:
// Got a topic.
str_buffer = string(BOLDWHITE) + "Topic: " + "\"" + arguments.at(2) + "\"" + string(RESET) + "\r\n";
break;
case RPL_TOPICWHOTIME:
// Got who set the topic.
str_buffer = "Topic set by " + arguments.at(2).substr(0, arguments.at(2).find('!')) + "\r\n";
break;
case RPL_NAMREPLY:
// Got a list of the people online.
stream << "Users: ";
str_buffer = arguments.at(3);
while (str_buffer.find(" ") != string::npos) {
size_t pos = str_buffer.find(" ");
stream << color_string(str_buffer.substr(0, pos), true) << " ";
str_buffer.erase(0, pos + 1);
}
if (!str_buffer.empty()) {
stream << color_string(str_buffer, true);
}
stream << "\r\n";
str_buffer = stream.str();
break;
case RPL_ENDOFNAMES:
// (Ignored) Got the end of the online names list
str_buffer = "";
break;
default:
// Got some other kind of message that we haven't covered.
str_buffer = "";
for (size_t i = 1; i < arguments.size(); i++) {
str_buffer += arguments.at(i) + " ";
}
str_buffer += "\r\n";
break;
}
}
if (arguments.at(0).at(0) == '#') {
channels.cache(arguments.at(0).substr(1), str_buffer);
}
return str_buffer;
}
/**
* Check if the message should be echoed.
*
* \return true if the message should be echoed.
*/
bool Pretty_Print_Message::echo_message() {
return echo;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/test/uritests.h>
#include <qt/guiutil.h>
#include <qt/walletmodel.h>
#include <QUrl>
void URITests::uriTests()
{
SendCoinsRecipient rv;
QUrl uri;
uri.setUrl(QString("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?req-dontexist="));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?dontexist="));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 0);
uri.setUrl(QString("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?label=Wikipedia Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString("Wikipedia Example Address"));
QVERIFY(rv.amount == 0);
uri.setUrl(QString("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=0.001"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100000);
uri.setUrl(QString("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=1.001"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100100000);
uri.setUrl(QString("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=100&label=Wikipedia Example"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.amount == 10000000000LL);
QVERIFY(rv.label == QString("Wikipedia Example"));
uri.setUrl(QString("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?message=Wikipedia Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString());
QVERIFY(GUIUtil::parseBitcoinURI("bitcoin://175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?message=Wikipedia Example Address", &rv));
QVERIFY(rv.address == QString("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"));
QVERIFY(rv.label == QString());
uri.setUrl(QString("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?req-message=Wikipedia Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=1,000&label=Wikipedia Example"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=1,000.0&label=Wikipedia Example"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
}
<commit_msg>Viacoin: uritests<commit_after>// Copyright (c) 2009-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/test/uritests.h>
#include <qt/guiutil.h>
#include <qt/walletmodel.h>
#include <QUrl>
void URITests::uriTests()
{
SendCoinsRecipient rv;
QUrl uri;
uri.setUrl(QString("viacoin:Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn?req-dontexist="));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("viacoin:Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn?dontexist="));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 0);
uri.setUrl(QString("viacoin:Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn?label=Wikipedia Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn"));
QVERIFY(rv.label == QString("Wikipedia Example Address"));
QVERIFY(rv.amount == 0);
uri.setUrl(QString("viacoin:Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn?amount=0.001"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100000);
uri.setUrl(QString("viacoin:Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn?amount=1.001"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100100000);
uri.setUrl(QString("viacoin:Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn?amount=100&label=Wikipedia Example"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn"));
QVERIFY(rv.amount == 10000000000LL);
QVERIFY(rv.label == QString("Wikipedia Example"));
uri.setUrl(QString("viacoin:Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn?message=Wikipedia Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn"));
QVERIFY(rv.label == QString());
QVERIFY(GUIUtil::parseBitcoinURI("viacoin://Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn?message=Wikipedia Example Address", &rv));
QVERIFY(rv.address == QString("Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn"));
QVERIFY(rv.label == QString());
uri.setUrl(QString("viacoin:Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn?req-message=Wikipedia Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("viacoin:Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn?amount=1,000&label=Wikipedia Example"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("viacoin:Vg5iRXkaipLKSYBDJjkV5qa1CE9b1djeHn?amount=1,000.0&label=Wikipedia Example"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
}
<|endoftext|>
|
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_ENV_HPP_
#define RDB_PROTOCOL_ENV_HPP_
#include <map>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include "concurrency/one_per_thread.hpp"
#include "containers/counted.hpp"
#include "extproc/js_runner.hpp"
#include "rdb_protocol/error.hpp"
#include "rdb_protocol/protocol.hpp"
#include "rdb_protocol/datum_stream.hpp"
#include "rdb_protocol/val.hpp"
class extproc_pool_t;
namespace ql {
class datum_t;
class term_t;
/* If and optarg with the given key is present and is of type DATUM it will be
* returned. Otherwise an empty counted_t<const datum_t> will be returned. */
counted_t<const datum_t> static_optarg(const std::string &key, protob_t<Query> q);
std::map<std::string, wire_func_t> global_optargs(protob_t<Query> q);
class global_optargs_t {
public:
global_optargs_t();
explicit global_optargs_t(std::map<std::string, wire_func_t> optargs);
void init_optargs(const std::map<std::string, wire_func_t> &_optargs);
// returns NULL if no entry
counted_t<val_t> get_optarg(env_t *env, const std::string &key);
const std::map<std::string, wire_func_t> &get_all_optargs();
private:
std::map<std::string, wire_func_t> optargs;
};
class cluster_access_t {
public:
cluster_access_t(
base_namespace_repo_t *_ns_repo,
clone_ptr_t<watchable_t<cow_ptr_t<namespaces_semilattice_metadata_t> > >
_namespaces_semilattice_metadata,
clone_ptr_t<watchable_t<databases_semilattice_metadata_t> >
_databases_semilattice_metadata,
boost::shared_ptr<semilattice_readwrite_view_t<cluster_semilattice_metadata_t> >
_semilattice_metadata,
directory_read_manager_t<cluster_directory_metadata_t> *_directory_read_manager,
uuid_u _this_machine);
base_namespace_repo_t *ns_repo;
clone_ptr_t<watchable_t<cow_ptr_t<namespaces_semilattice_metadata_t > > >
namespaces_semilattice_metadata;
clone_ptr_t<watchable_t<databases_semilattice_metadata_t> >
databases_semilattice_metadata;
// This is a read-WRITE view because of things like table_create_term_t,
// db_create_term_t, etc. Its home thread might be different from ours.
boost::shared_ptr<semilattice_readwrite_view_t<cluster_semilattice_metadata_t> >
semilattice_metadata;
// This field can be NULL. Importantly, this field is NULL everywhere except in
// the parser's env_t. This is because you "cannot nest meta operations inside
// queries." RSI: What does that even mean?
directory_read_manager_t<cluster_directory_metadata_t> *directory_read_manager;
// Semilattice modification functions
void join_and_wait_to_propagate(
const cluster_semilattice_metadata_t &metadata_to_join,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
const uuid_u this_machine;
};
namespace changefeed {
class client_t;
} // namespace changefeed
profile_bool_t profile_bool_optarg(const protob_t<Query> &query);
class env_t : public home_thread_mixin_t {
public:
env_t(
extproc_pool_t *_extproc_pool,
changefeed::client_t *_changefeed_client,
const std::string &_reql_http_proxy,
base_namespace_repo_t *_ns_repo,
clone_ptr_t<watchable_t<cow_ptr_t<namespaces_semilattice_metadata_t> > >
_namespaces_semilattice_metadata,
clone_ptr_t<watchable_t<databases_semilattice_metadata_t> >
_databases_semilattice_metadata,
boost::shared_ptr<semilattice_readwrite_view_t<cluster_semilattice_metadata_t> >
_semilattice_metadata,
directory_read_manager_t<cluster_directory_metadata_t> *_directory_read_manager,
signal_t *_interruptor,
uuid_u _this_machine,
std::map<std::string, wire_func_t> optargs);
env_t(
extproc_pool_t *_extproc_pool,
changefeed::client_t *_changefeed_client,
const std::string &_reql_http_proxy,
base_namespace_repo_t *_ns_repo,
clone_ptr_t<watchable_t<cow_ptr_t<namespaces_semilattice_metadata_t> > >
_namespaces_semilattice_metadata,
clone_ptr_t<watchable_t<databases_semilattice_metadata_t> >
_databases_semilattice_metadata,
boost::shared_ptr<semilattice_readwrite_view_t<cluster_semilattice_metadata_t> >
_semilattice_metadata,
signal_t *_interruptor,
uuid_u _this_machine);
env_t(rdb_context_t *ctx, signal_t *interruptor);
explicit env_t(signal_t *interruptor);
~env_t();
static const uint32_t EVALS_BEFORE_YIELD = 256;
uint32_t evals_since_yield;
// Will yield after EVALS_BEFORE_YIELD calls
void maybe_yield();
// Returns js_runner, but first calls js_runner->begin() if it hasn't
// already been called.
js_runner_t *get_js_runner();
// This is a callback used in unittests to control things during a query
class eval_callback_t {
public:
virtual ~eval_callback_t() { }
virtual void eval_callback() = 0;
};
void set_eval_callback(eval_callback_t *callback);
void do_eval_callback();
// The global optargs values passed to .run(...) in the Python, Ruby, and JS
// drivers.
global_optargs_t global_optargs;
// A pool used for running external JS jobs. Inexplicably this isn't inside of
// js_runner_t.
extproc_pool_t *const extproc_pool;
// Holds a bunch of mailboxes and maps them to streams.
changefeed::client_t *changefeed_client;
// HTTP proxy to use when running `r.http(...)` queries
const std::string reql_http_proxy;
// Access to the cluster, for talking over the cluster or about the cluster.
cluster_access_t cluster_access;
// The interruptor signal while a query evaluates.
signal_t *const interruptor;
// This is _always_ empty, because profiling is not supported in this release.
// (Unfortunately, all the profiling code expects this field to exist! Letting
// this field be empty is the quickest way to disable profiling support in the
// 1.13 release. When reintroducing profiling support, please make sure that
// every env_t constructor contains a profile parameter -- rdb_read_visitor_t in
// particular no longer passes its profile parameter along.
const scoped_ptr_t<profile::trace_t> trace;
// Always returns profile_bool_t::DONT_PROFILE for now, because trace is empty,
// because we don't support profiling in this release.
profile_bool_t profile() const;
private:
js_runner_t js_runner;
eval_callback_t *eval_callback;
DISABLE_COPYING(env_t);
};
// An environment in which expressions are compiled. Since compilation doesn't
// evaluate anything, it doesn't need an env_t *.
class compile_env_t {
public:
explicit compile_env_t(var_visibility_t &&_visibility)
: visibility(std::move(_visibility)) { }
var_visibility_t visibility;
};
// This is an environment for evaluating things that use variables in scope. It
// supplies the variables along with the "global" evaluation environment.
class scope_env_t {
public:
scope_env_t(env_t *_env, var_scope_t &&_scope)
: env(_env), scope(std::move(_scope)) { }
env_t *const env;
const var_scope_t scope;
DISABLE_COPYING(scope_env_t);
};
scoped_ptr_t<env_t> make_complete_env(rdb_context_t *ctx,
signal_t *interruptor,
std::map<std::string, wire_func_t> optargs);
} // namespace ql
#endif // RDB_PROTOCOL_ENV_HPP_
<commit_msg>Updated RSI comment.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_ENV_HPP_
#define RDB_PROTOCOL_ENV_HPP_
#include <map>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include "concurrency/one_per_thread.hpp"
#include "containers/counted.hpp"
#include "extproc/js_runner.hpp"
#include "rdb_protocol/error.hpp"
#include "rdb_protocol/protocol.hpp"
#include "rdb_protocol/datum_stream.hpp"
#include "rdb_protocol/val.hpp"
class extproc_pool_t;
namespace ql {
class datum_t;
class term_t;
/* If and optarg with the given key is present and is of type DATUM it will be
* returned. Otherwise an empty counted_t<const datum_t> will be returned. */
counted_t<const datum_t> static_optarg(const std::string &key, protob_t<Query> q);
std::map<std::string, wire_func_t> global_optargs(protob_t<Query> q);
class global_optargs_t {
public:
global_optargs_t();
explicit global_optargs_t(std::map<std::string, wire_func_t> optargs);
void init_optargs(const std::map<std::string, wire_func_t> &_optargs);
// returns NULL if no entry
counted_t<val_t> get_optarg(env_t *env, const std::string &key);
const std::map<std::string, wire_func_t> &get_all_optargs();
private:
std::map<std::string, wire_func_t> optargs;
};
class cluster_access_t {
public:
cluster_access_t(
base_namespace_repo_t *_ns_repo,
clone_ptr_t<watchable_t<cow_ptr_t<namespaces_semilattice_metadata_t> > >
_namespaces_semilattice_metadata,
clone_ptr_t<watchable_t<databases_semilattice_metadata_t> >
_databases_semilattice_metadata,
boost::shared_ptr<semilattice_readwrite_view_t<cluster_semilattice_metadata_t> >
_semilattice_metadata,
directory_read_manager_t<cluster_directory_metadata_t> *_directory_read_manager,
uuid_u _this_machine);
base_namespace_repo_t *ns_repo;
clone_ptr_t<watchable_t<cow_ptr_t<namespaces_semilattice_metadata_t > > >
namespaces_semilattice_metadata;
clone_ptr_t<watchable_t<databases_semilattice_metadata_t> >
databases_semilattice_metadata;
// This is a read-WRITE view because of things like table_create_term_t,
// db_create_term_t, etc. Its home thread might be different from ours.
boost::shared_ptr<semilattice_readwrite_view_t<cluster_semilattice_metadata_t> >
semilattice_metadata;
// This field can be NULL. Importantly, this field is NULL everywhere except in
// the parser's env_t. This is because you "cannot nest meta operations inside
// queries" -- as meta_write_op_t will complain. However, term_walker.cc is what
// actually enforces this property. RSI: Make this field always be non-NULL, and
// rely on term_walker.cc's enforcement.
directory_read_manager_t<cluster_directory_metadata_t> *directory_read_manager;
// Semilattice modification functions
void join_and_wait_to_propagate(
const cluster_semilattice_metadata_t &metadata_to_join,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t);
const uuid_u this_machine;
};
namespace changefeed {
class client_t;
} // namespace changefeed
profile_bool_t profile_bool_optarg(const protob_t<Query> &query);
class env_t : public home_thread_mixin_t {
public:
env_t(
extproc_pool_t *_extproc_pool,
changefeed::client_t *_changefeed_client,
const std::string &_reql_http_proxy,
base_namespace_repo_t *_ns_repo,
clone_ptr_t<watchable_t<cow_ptr_t<namespaces_semilattice_metadata_t> > >
_namespaces_semilattice_metadata,
clone_ptr_t<watchable_t<databases_semilattice_metadata_t> >
_databases_semilattice_metadata,
boost::shared_ptr<semilattice_readwrite_view_t<cluster_semilattice_metadata_t> >
_semilattice_metadata,
directory_read_manager_t<cluster_directory_metadata_t> *_directory_read_manager,
signal_t *_interruptor,
uuid_u _this_machine,
std::map<std::string, wire_func_t> optargs);
env_t(
extproc_pool_t *_extproc_pool,
changefeed::client_t *_changefeed_client,
const std::string &_reql_http_proxy,
base_namespace_repo_t *_ns_repo,
clone_ptr_t<watchable_t<cow_ptr_t<namespaces_semilattice_metadata_t> > >
_namespaces_semilattice_metadata,
clone_ptr_t<watchable_t<databases_semilattice_metadata_t> >
_databases_semilattice_metadata,
boost::shared_ptr<semilattice_readwrite_view_t<cluster_semilattice_metadata_t> >
_semilattice_metadata,
signal_t *_interruptor,
uuid_u _this_machine);
env_t(rdb_context_t *ctx, signal_t *interruptor);
explicit env_t(signal_t *interruptor);
~env_t();
static const uint32_t EVALS_BEFORE_YIELD = 256;
uint32_t evals_since_yield;
// Will yield after EVALS_BEFORE_YIELD calls
void maybe_yield();
// Returns js_runner, but first calls js_runner->begin() if it hasn't
// already been called.
js_runner_t *get_js_runner();
// This is a callback used in unittests to control things during a query
class eval_callback_t {
public:
virtual ~eval_callback_t() { }
virtual void eval_callback() = 0;
};
void set_eval_callback(eval_callback_t *callback);
void do_eval_callback();
// The global optargs values passed to .run(...) in the Python, Ruby, and JS
// drivers.
global_optargs_t global_optargs;
// A pool used for running external JS jobs. Inexplicably this isn't inside of
// js_runner_t.
extproc_pool_t *const extproc_pool;
// Holds a bunch of mailboxes and maps them to streams.
changefeed::client_t *changefeed_client;
// HTTP proxy to use when running `r.http(...)` queries
const std::string reql_http_proxy;
// Access to the cluster, for talking over the cluster or about the cluster.
cluster_access_t cluster_access;
// The interruptor signal while a query evaluates.
signal_t *const interruptor;
// This is _always_ empty, because profiling is not supported in this release.
// (Unfortunately, all the profiling code expects this field to exist! Letting
// this field be empty is the quickest way to disable profiling support in the
// 1.13 release. When reintroducing profiling support, please make sure that
// every env_t constructor contains a profile parameter -- rdb_read_visitor_t in
// particular no longer passes its profile parameter along.
const scoped_ptr_t<profile::trace_t> trace;
// Always returns profile_bool_t::DONT_PROFILE for now, because trace is empty,
// because we don't support profiling in this release.
profile_bool_t profile() const;
private:
js_runner_t js_runner;
eval_callback_t *eval_callback;
DISABLE_COPYING(env_t);
};
// An environment in which expressions are compiled. Since compilation doesn't
// evaluate anything, it doesn't need an env_t *.
class compile_env_t {
public:
explicit compile_env_t(var_visibility_t &&_visibility)
: visibility(std::move(_visibility)) { }
var_visibility_t visibility;
};
// This is an environment for evaluating things that use variables in scope. It
// supplies the variables along with the "global" evaluation environment.
class scope_env_t {
public:
scope_env_t(env_t *_env, var_scope_t &&_scope)
: env(_env), scope(std::move(_scope)) { }
env_t *const env;
const var_scope_t scope;
DISABLE_COPYING(scope_env_t);
};
scoped_ptr_t<env_t> make_complete_env(rdb_context_t *ctx,
signal_t *interruptor,
std::map<std::string, wire_func_t> optargs);
} // namespace ql
#endif // RDB_PROTOCOL_ENV_HPP_
<|endoftext|>
|
<commit_before>// Copyright (c) 2015-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/platformstyle.h>
#include <qt/guiconstants.h>
#include <QApplication>
#include <QColor>
#include <QImage>
#include <QPalette>
static const struct {
const char *platformId;
/** Show images on push buttons */
const bool imagesOnButtons;
/** Colorize single-color icons */
const bool colorizeIcons;
/** Extra padding/spacing in transactionview */
const bool useExtraSpacing;
} platform_styles[] = {
{"macosx", false, false, true},
{"windows", true, false, false},
/* Other: linux, unix, ... */
{"other", true, true, false}
};
static const unsigned platform_styles_count = sizeof(platform_styles)/sizeof(*platform_styles);
namespace {
/* Local functions for colorizing single-color images */
void MakeSingleColorImage(QImage& img, const QColor& colorbase)
{
img = img.convertToFormat(QImage::Format_ARGB32);
for (int x = img.width(); x--; )
{
for (int y = img.height(); y--; )
{
const QRgb rgb = img.pixel(x, y);
img.setPixel(x, y, qRgba(colorbase.red(), colorbase.green(), colorbase.blue(), qAlpha(rgb)));
}
}
}
QIcon ColorizeIcon(const QIcon& ico, const QColor& colorbase)
{
QIcon new_ico;
for (const QSize sz : ico.availableSizes())
{
QImage img(ico.pixmap(sz).toImage());
MakeSingleColorImage(img, colorbase);
new_ico.addPixmap(QPixmap::fromImage(img));
}
return new_ico;
}
QImage ColorizeImage(const QString& filename, const QColor& colorbase)
{
QImage img(filename);
MakeSingleColorImage(img, colorbase);
return img;
}
QIcon ColorizeIcon(const QString& filename, const QColor& colorbase)
{
return QIcon(QPixmap::fromImage(ColorizeImage(filename, colorbase)));
}
}
PlatformStyle::PlatformStyle(const QString &_name, bool _imagesOnButtons, bool _colorizeIcons, bool _useExtraSpacing):
name(_name),
imagesOnButtons(_imagesOnButtons),
colorizeIcons(_colorizeIcons),
useExtraSpacing(_useExtraSpacing),
singleColor(0,0,0),
textColor(0,0,0)
{
// Determine icon highlighting color
if (colorizeIcons) {
const QColor colorHighlightBg(QApplication::palette().color(QPalette::Highlight));
const QColor colorHighlightFg(QApplication::palette().color(QPalette::HighlightedText));
const QColor colorText(QApplication::palette().color(QPalette::WindowText));
const int colorTextLightness = colorText.lightness();
QColor colorbase;
if (abs(colorHighlightBg.lightness() - colorTextLightness) < abs(colorHighlightFg.lightness() - colorTextLightness))
colorbase = colorHighlightBg;
else
colorbase = colorHighlightFg;
singleColor = colorbase;
}
// Determine text color
textColor = QColor(QApplication::palette().color(QPalette::WindowText));
}
QImage PlatformStyle::SingleColorImage(const QString& filename) const
{
if (!colorizeIcons)
return QImage(filename);
return ColorizeImage(filename, SingleColor());
}
QIcon PlatformStyle::SingleColorIcon(const QString& filename) const
{
if (!colorizeIcons)
return QIcon(filename);
return ColorizeIcon(filename, SingleColor());
}
QIcon PlatformStyle::SingleColorIcon(const QIcon& icon) const
{
if (!colorizeIcons)
return icon;
return ColorizeIcon(icon, SingleColor());
}
QIcon PlatformStyle::TextColorIcon(const QString& filename) const
{
return ColorizeIcon(filename, TextColor());
}
QIcon PlatformStyle::TextColorIcon(const QIcon& icon) const
{
return ColorizeIcon(icon, TextColor());
}
const PlatformStyle *PlatformStyle::instantiate(const QString &platformId)
{
for (unsigned x=0; x<platform_styles_count; ++x)
{
if (platformId == platform_styles[x].platformId)
{
return new PlatformStyle(
platform_styles[x].platformId,
platform_styles[x].imagesOnButtons,
platform_styles[x].colorizeIcons,
platform_styles[x].useExtraSpacing);
}
}
return 0;
}
<commit_msg>Use grs menu colour<commit_after>// Copyright (c) 2015-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/platformstyle.h>
#include <qt/guiconstants.h>
#include <QApplication>
#include <QColor>
#include <QImage>
#include <QPalette>
static const struct {
const char *platformId;
/** Show images on push buttons */
const bool imagesOnButtons;
/** Colorize single-color icons */
const bool colorizeIcons;
/** Extra padding/spacing in transactionview */
const bool useExtraSpacing;
} platform_styles[] = {
{"macosx", false, false, true},
{"windows", true, false, false},
/* Other: linux, unix, ... */
{"other", true, false, false}
};
static const unsigned platform_styles_count = sizeof(platform_styles)/sizeof(*platform_styles);
namespace {
/* Local functions for colorizing single-color images */
void MakeSingleColorImage(QImage& img, const QColor& colorbase)
{
img = img.convertToFormat(QImage::Format_ARGB32);
for (int x = img.width(); x--; )
{
for (int y = img.height(); y--; )
{
const QRgb rgb = img.pixel(x, y);
img.setPixel(x, y, qRgba(colorbase.red(), colorbase.green(), colorbase.blue(), qAlpha(rgb)));
}
}
}
QIcon ColorizeIcon(const QIcon& ico, const QColor& colorbase)
{
QIcon new_ico;
for (const QSize sz : ico.availableSizes())
{
QImage img(ico.pixmap(sz).toImage());
MakeSingleColorImage(img, colorbase);
new_ico.addPixmap(QPixmap::fromImage(img));
}
return new_ico;
}
QImage ColorizeImage(const QString& filename, const QColor& colorbase)
{
QImage img(filename);
MakeSingleColorImage(img, colorbase);
return img;
}
QIcon ColorizeIcon(const QString& filename, const QColor& colorbase)
{
return QIcon(QPixmap::fromImage(ColorizeImage(filename, colorbase)));
}
}
PlatformStyle::PlatformStyle(const QString &_name, bool _imagesOnButtons, bool _colorizeIcons, bool _useExtraSpacing):
name(_name),
imagesOnButtons(_imagesOnButtons),
colorizeIcons(_colorizeIcons),
useExtraSpacing(_useExtraSpacing),
singleColor(0,0,0),
textColor(0,0,0)
{
// Determine icon highlighting color
if (colorizeIcons) {
const QColor colorHighlightBg(QApplication::palette().color(QPalette::Highlight));
const QColor colorHighlightFg(QApplication::palette().color(QPalette::HighlightedText));
const QColor colorText(QApplication::palette().color(QPalette::WindowText));
const int colorTextLightness = colorText.lightness();
QColor colorbase;
if (abs(colorHighlightBg.lightness() - colorTextLightness) < abs(colorHighlightFg.lightness() - colorTextLightness))
colorbase = colorHighlightBg;
else
colorbase = colorHighlightFg;
singleColor = colorbase;
}
// Determine text color
textColor = QColor(QApplication::palette().color(QPalette::WindowText));
}
QImage PlatformStyle::SingleColorImage(const QString& filename) const
{
if (!colorizeIcons)
return QImage(filename);
return ColorizeImage(filename, SingleColor());
}
QIcon PlatformStyle::SingleColorIcon(const QString& filename) const
{
if (!colorizeIcons)
return QIcon(filename);
return ColorizeIcon(filename, SingleColor());
}
QIcon PlatformStyle::SingleColorIcon(const QIcon& icon) const
{
if (!colorizeIcons)
return icon;
return ColorizeIcon(icon, SingleColor());
}
QIcon PlatformStyle::TextColorIcon(const QString& filename) const
{
if (!colorizeIcons)
return QIcon(filename);
return ColorizeIcon(filename, TextColor());
}
QIcon PlatformStyle::TextColorIcon(const QIcon& icon) const
{
if (!colorizeIcons)
return icon;
return ColorizeIcon(icon, TextColor());
}
const PlatformStyle *PlatformStyle::instantiate(const QString &platformId)
{
for (unsigned x=0; x<platform_styles_count; ++x)
{
if (platformId == platform_styles[x].platformId)
{
return new PlatformStyle(
platform_styles[x].platformId,
platform_styles[x].imagesOnButtons,
platform_styles[x].colorizeIcons,
platform_styles[x].useExtraSpacing);
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include "qwt_analog_clock.h"
#include "qwt_round_scale_draw.h"
#include <qmath.h>
class QwtAnalogClockScaleDraw: public QwtRoundScaleDraw
{
public:
QwtAnalogClockScaleDraw()
{
setSpacing( 8 );
enableComponent( QwtAbstractScaleDraw::Backbone, false );
setTickLength( QwtScaleDiv::MinorTick, 2 );
setTickLength( QwtScaleDiv::MediumTick, 4 );
setTickLength( QwtScaleDiv::MajorTick, 8 );
setPenWidth( 1 );
}
virtual QwtText label( double value ) const
{
if ( qFuzzyCompare( value + 1.0, 1.0 ) )
value = 60.0 * 60.0 * 12.0;
return QLocale().toString( qRound( value / ( 60.0 * 60.0 ) ) );
}
};
/*!
Constructor
\param parent Parent widget
*/
QwtAnalogClock::QwtAnalogClock( QWidget *parent ):
QwtDial( parent )
{
setWrapping( true );
setReadOnly( true );
setOrigin( 270.0 );
setScaleDraw( new QwtAnalogClockScaleDraw() );
const int secondsPerHour = 60.0 * 60.0;
QList<double> majorTicks;
QList<double> minorTicks;
for ( int i = 0; i < 12; i++ )
{
majorTicks += i * secondsPerHour;
for ( int j = 1; j < 5; j++ )
minorTicks += i * secondsPerHour + j * secondsPerHour / 5.0;
}
QwtScaleDiv scaleDiv;
scaleDiv.setInterval( 0.0, 12.0 * secondsPerHour );
scaleDiv.setTicks( QwtScaleDiv::MajorTick, majorTicks );
scaleDiv.setTicks( QwtScaleDiv::MinorTick, minorTicks );
setScale( scaleDiv );
QColor knobColor = palette().color( QPalette::Active, QPalette::Text );
knobColor = knobColor.dark( 120 );
QColor handColor;
int width;
for ( int i = 0; i < NHands; i++ )
{
if ( i == SecondHand )
{
width = 2;
handColor = knobColor.dark( 120 );
}
else
{
width = 8;
handColor = knobColor;
}
QwtDialSimpleNeedle *hand = new QwtDialSimpleNeedle(
QwtDialSimpleNeedle::Arrow, true, handColor, knobColor );
hand->setWidth( width );
d_hand[i] = NULL;
setHand( static_cast<Hand>( i ), hand );
}
}
//! Destructor
QwtAnalogClock::~QwtAnalogClock()
{
for ( int i = 0; i < NHands; i++ )
delete d_hand[i];
}
/*!
Nop method, use setHand instead
\sa setHand()
*/
void QwtAnalogClock::setNeedle( QwtDialNeedle * )
{
// no op
return;
}
/*!
Set a clockhand
\param hand Specifies the type of hand
\param needle Hand
\sa hand()
*/
void QwtAnalogClock::setHand( Hand hand, QwtDialNeedle *needle )
{
if ( hand >= 0 || hand < NHands )
{
delete d_hand[hand];
d_hand[hand] = needle;
}
}
/*!
\return Clock hand
\param hd Specifies the type of hand
\sa setHand()
*/
QwtDialNeedle *QwtAnalogClock::hand( Hand hd )
{
if ( hd < 0 || hd >= NHands )
return NULL;
return d_hand[hd];
}
/*!
\return Clock hand
\param hd Specifies the type of hand
\sa setHand()
*/
const QwtDialNeedle *QwtAnalogClock::hand( Hand hd ) const
{
return const_cast<QwtAnalogClock *>( this )->hand( hd );
}
/*!
\brief Set the current time
This is the same as QwtAnalogClock::setTime(), but Qt < 3.0
can't handle default parameters for slots.
*/
void QwtAnalogClock::setCurrentTime()
{
setTime( QTime::currentTime() );
}
/*!
Set a time
\param time Time to display
*/
void QwtAnalogClock::setTime( const QTime &time )
{
if ( time.isValid() )
{
setValue( ( time.hour() % 12 ) * 60.0 * 60.0
+ time.minute() * 60.0 + time.second() );
}
else
setValid( false );
}
/*!
\brief Draw the needle
A clock has no single needle but three hands instead. drawNeedle
translates value() into directions for the hands and calls
drawHand().
\param painter Painter
\param center Center of the clock
\param radius Maximum length for the hands
\param dir Dummy, not used.
\param colorGroup ColorGroup
\sa drawHand()
*/
void QwtAnalogClock::drawNeedle( QPainter *painter, const QPointF ¢er,
double radius, double dir, QPalette::ColorGroup colorGroup ) const
{
Q_UNUSED( dir );
if ( isValid() )
{
const double hours = value() / ( 60.0 * 60.0 );
const double minutes =
( value() - qFloor(hours) * 60.0 * 60.0 ) / 60.0;
const double seconds = value() - qFloor(hours) * 60.0 * 60.0
- qFloor(minutes) * 60.0;
double angle[NHands];
angle[HourHand] = 360.0 * hours / 12.0;
angle[MinuteHand] = 360.0 * minutes / 60.0;
angle[SecondHand] = 360.0 * seconds / 60.0;
for ( int hand = 0; hand < NHands; hand++ )
{
const double d = 360.0 - angle[hand] - origin();
drawHand( painter, static_cast<Hand>( hand ),
center, radius, d, colorGroup );
}
}
}
/*!
Draw a clock hand
\param painter Painter
\param hd Specify the type of hand
\param center Center of the clock
\param radius Maximum length for the hands
\param direction Direction of the hand in degrees, counter clockwise
\param cg ColorGroup
*/
void QwtAnalogClock::drawHand( QPainter *painter, Hand hd,
const QPointF ¢er, double radius, double direction,
QPalette::ColorGroup cg ) const
{
const QwtDialNeedle *needle = hand( hd );
if ( needle )
{
if ( hd == HourHand )
radius = qRound( 0.8 * radius );
needle->draw( painter, center, radius, direction, cg );
}
}
<commit_msg>bad defensive check fixed<commit_after>/* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include "qwt_analog_clock.h"
#include "qwt_round_scale_draw.h"
#include <qmath.h>
class QwtAnalogClockScaleDraw: public QwtRoundScaleDraw
{
public:
QwtAnalogClockScaleDraw()
{
setSpacing( 8 );
enableComponent( QwtAbstractScaleDraw::Backbone, false );
setTickLength( QwtScaleDiv::MinorTick, 2 );
setTickLength( QwtScaleDiv::MediumTick, 4 );
setTickLength( QwtScaleDiv::MajorTick, 8 );
setPenWidth( 1 );
}
virtual QwtText label( double value ) const
{
if ( qFuzzyCompare( value + 1.0, 1.0 ) )
value = 60.0 * 60.0 * 12.0;
return QLocale().toString( qRound( value / ( 60.0 * 60.0 ) ) );
}
};
/*!
Constructor
\param parent Parent widget
*/
QwtAnalogClock::QwtAnalogClock( QWidget *parent ):
QwtDial( parent )
{
setWrapping( true );
setReadOnly( true );
setOrigin( 270.0 );
setScaleDraw( new QwtAnalogClockScaleDraw() );
const int secondsPerHour = 60.0 * 60.0;
QList<double> majorTicks;
QList<double> minorTicks;
for ( int i = 0; i < 12; i++ )
{
majorTicks += i * secondsPerHour;
for ( int j = 1; j < 5; j++ )
minorTicks += i * secondsPerHour + j * secondsPerHour / 5.0;
}
QwtScaleDiv scaleDiv;
scaleDiv.setInterval( 0.0, 12.0 * secondsPerHour );
scaleDiv.setTicks( QwtScaleDiv::MajorTick, majorTicks );
scaleDiv.setTicks( QwtScaleDiv::MinorTick, minorTicks );
setScale( scaleDiv );
QColor knobColor = palette().color( QPalette::Active, QPalette::Text );
knobColor = knobColor.dark( 120 );
QColor handColor;
int width;
for ( int i = 0; i < NHands; i++ )
{
if ( i == SecondHand )
{
width = 2;
handColor = knobColor.dark( 120 );
}
else
{
width = 8;
handColor = knobColor;
}
QwtDialSimpleNeedle *hand = new QwtDialSimpleNeedle(
QwtDialSimpleNeedle::Arrow, true, handColor, knobColor );
hand->setWidth( width );
d_hand[i] = NULL;
setHand( static_cast<Hand>( i ), hand );
}
}
//! Destructor
QwtAnalogClock::~QwtAnalogClock()
{
for ( int i = 0; i < NHands; i++ )
delete d_hand[i];
}
/*!
Nop method, use setHand instead
\sa setHand()
*/
void QwtAnalogClock::setNeedle( QwtDialNeedle * )
{
// no op
return;
}
/*!
Set a clockhand
\param hand Specifies the type of hand
\param needle Hand
\sa hand()
*/
void QwtAnalogClock::setHand( Hand hand, QwtDialNeedle *needle )
{
if ( hand >= 0 && hand < NHands )
{
delete d_hand[hand];
d_hand[hand] = needle;
}
}
/*!
\return Clock hand
\param hd Specifies the type of hand
\sa setHand()
*/
QwtDialNeedle *QwtAnalogClock::hand( Hand hd )
{
if ( hd < 0 || hd >= NHands )
return NULL;
return d_hand[hd];
}
/*!
\return Clock hand
\param hd Specifies the type of hand
\sa setHand()
*/
const QwtDialNeedle *QwtAnalogClock::hand( Hand hd ) const
{
return const_cast<QwtAnalogClock *>( this )->hand( hd );
}
/*!
\brief Set the current time
This is the same as QwtAnalogClock::setTime(), but Qt < 3.0
can't handle default parameters for slots.
*/
void QwtAnalogClock::setCurrentTime()
{
setTime( QTime::currentTime() );
}
/*!
Set a time
\param time Time to display
*/
void QwtAnalogClock::setTime( const QTime &time )
{
if ( time.isValid() )
{
setValue( ( time.hour() % 12 ) * 60.0 * 60.0
+ time.minute() * 60.0 + time.second() );
}
else
setValid( false );
}
/*!
\brief Draw the needle
A clock has no single needle but three hands instead. drawNeedle
translates value() into directions for the hands and calls
drawHand().
\param painter Painter
\param center Center of the clock
\param radius Maximum length for the hands
\param dir Dummy, not used.
\param colorGroup ColorGroup
\sa drawHand()
*/
void QwtAnalogClock::drawNeedle( QPainter *painter, const QPointF ¢er,
double radius, double dir, QPalette::ColorGroup colorGroup ) const
{
Q_UNUSED( dir );
if ( isValid() )
{
const double hours = value() / ( 60.0 * 60.0 );
const double minutes =
( value() - qFloor(hours) * 60.0 * 60.0 ) / 60.0;
const double seconds = value() - qFloor(hours) * 60.0 * 60.0
- qFloor(minutes) * 60.0;
double angle[NHands];
angle[HourHand] = 360.0 * hours / 12.0;
angle[MinuteHand] = 360.0 * minutes / 60.0;
angle[SecondHand] = 360.0 * seconds / 60.0;
for ( int hand = 0; hand < NHands; hand++ )
{
const double d = 360.0 - angle[hand] - origin();
drawHand( painter, static_cast<Hand>( hand ),
center, radius, d, colorGroup );
}
}
}
/*!
Draw a clock hand
\param painter Painter
\param hd Specify the type of hand
\param center Center of the clock
\param radius Maximum length for the hands
\param direction Direction of the hand in degrees, counter clockwise
\param cg ColorGroup
*/
void QwtAnalogClock::drawHand( QPainter *painter, Hand hd,
const QPointF ¢er, double radius, double direction,
QPalette::ColorGroup cg ) const
{
const QwtDialNeedle *needle = hand( hd );
if ( needle )
{
if ( hd == HourHand )
radius = qRound( 0.8 * radius );
needle->draw( painter, center, radius, direction, cg );
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include "core/posix.hh"
#include "core/vla.hh"
#include "core/reactor.hh"
#include "core/future-util.hh"
#include "core/stream.hh"
#include "core/circular_buffer.hh"
#include "core/align.hh"
#include <atomic>
#include <list>
#include <queue>
#include <fcntl.h>
#include <linux/if_tun.h>
#include "ip.hh"
#include <xen/xen.h>
#include <xen/memory.h>
#include <xen/sys/gntalloc.h>
#include "core/xen/xenstore.hh"
#include "core/xen/evtchn.hh"
#include "xenfront.hh"
#include <unordered_set>
using namespace net;
namespace xen {
using phys = uint64_t;
class xenfront_net_device : public net::device {
private:
bool _userspace;
stream<packet> _rx_stream;
net::hw_features _hw_features;
std::string _device_str;
xenstore* _xenstore = xenstore::instance();
unsigned _otherend;
std::string _backend;
gntalloc *_gntalloc;
evtchn *_evtchn;
port _tx_evtchn;
port _rx_evtchn;
front_ring<tx> _tx_ring;
front_ring<rx> _rx_ring;
grant_head *_tx_refs;
grant_head *_rx_refs;
std::unordered_map<std::string, int> _features;
static std::unordered_map<std::string, std::string> _supported_features;
ethernet_address _hw_address;
port bind_tx_evtchn(bool split);
port bind_rx_evtchn(bool split);
future<> alloc_rx_references();
future<> handle_tx_completions();
future<> queue_rx_packet();
void alloc_one_rx_reference(unsigned id);
std::string path(std::string s) { return _device_str + "/" + s; }
public:
explicit xenfront_net_device(boost::program_options::variables_map opts, bool userspace);
~xenfront_net_device();
virtual subscription<packet> receive(std::function<future<> (packet)> next) override;
virtual future<> send(packet p) override;
ethernet_address hw_address();
net::hw_features hw_features();
};
std::unordered_map<std::string, std::string>
xenfront_net_device::_supported_features = {
{ "feature-split-event-channels", "feature-split-event-channels" },
{ "feature-rx-copy", "request-rx-copy" }
};
subscription<packet>
xenfront_net_device::receive(std::function<future<> (packet)> next) {
auto sub = _rx_stream.listen(std::move(next));
keep_doing([this] {
return _rx_evtchn.pending().then([this] {
return queue_rx_packet();
});
});
return std::move(sub);
}
future<>
xenfront_net_device::send(packet _p) {
uint32_t frag = 0;
// There doesn't seem to be a way to tell xen, when using the userspace
// drivers, to map a particular page. Therefore, the only alternative
// here is to copy. All pages shared must come from the gntalloc mmap.
//
// A better solution could be to change the packet allocation path to
// use a pre-determined page for data.
//
// In-kernel should be fine
// FIXME: negotiate and use scatter/gather
_p.linearize();
return _tx_ring.entries.has_room().then([this, p = std::move(_p), frag] () mutable {
auto req_prod = _tx_ring._sring->req_prod;
auto f = p.frag(frag);
auto ref = _tx_refs->new_ref(f.base, f.size);
unsigned idx = _tx_ring.entries.get_index();
assert(!_tx_ring.entries[idx]);
_tx_ring.entries[idx] = ref;
auto req = &_tx_ring._sring->_ring[idx].req;
req->gref = ref.xen_id;
req->offset = 0;
req->flags = {};
if (p.offload_info().protocol != ip_protocol_num::unused) {
req->flags.csum_blank = true;
req->flags.data_validated = true;
} else {
req->flags.data_validated = true;
}
req->id = idx;
req->size = f.size;
_tx_ring.req_prod_pvt = idx;
_tx_ring._sring->req_prod = req_prod + 1;
_tx_ring._sring->req_event++;
if ((frag + 1) == p.nr_frags()) {
_tx_evtchn.notify();
return make_ready_future<>();
} else {
return make_ready_future<>();
}
});
// FIXME: Don't forget to clear all grant refs when frontend closes. Or is it automatic?
}
#define rmb() asm volatile("lfence":::"memory");
#define wmb() asm volatile("":::"memory");
template <typename T>
future<> front_ring<T>::entries::has_room() {
return _available.wait();
}
template <typename T>
void front_ring<T>::entries::free_index(unsigned id) {
_available.signal();
}
template <typename T>
unsigned front_ring<T>::entries::get_index() {
return front_ring<T>::idx(_next_idx++);
}
template <typename T>
future<> front_ring<T>::process_ring(std::function<bool (gntref &entry, T& el)> func, grant_head *refs)
{
auto prod = _sring->rsp_prod;
rmb();
for (unsigned i = rsp_cons; i != prod; i++) {
auto el = _sring->_ring[idx(i)];
if (el.rsp.status < 0) {
dump("Packet error", el.rsp);
continue;
}
auto& entry = entries[i];
if (!func(entry, el)) {
continue;
}
assert(entry.xen_id >= 0);
refs->free_ref(entry);
entries.free_index(i);
prod = _sring->rsp_prod;
}
rsp_cons = prod;
_sring->rsp_event = prod + 1;
return make_ready_future<>();
}
future<> xenfront_net_device::queue_rx_packet()
{
return _rx_ring.process_ring([this] (gntref &entry, rx &rx) {
packet p(static_cast<char *>(entry.page) + rx.rsp.offset, rx.rsp.status);
_rx_stream.produce(std::move(p));
return true;
}, _rx_refs);
}
void xenfront_net_device::alloc_one_rx_reference(unsigned index) {
_rx_ring.entries[index] = _rx_refs->new_ref();
// This is how the backend knows where to put data.
auto req = &_rx_ring._sring->_ring[index].req;
req->id = index;
req->gref = _rx_ring.entries[index].xen_id;
}
future<> xenfront_net_device::alloc_rx_references() {
return _rx_ring.entries.has_room().then([this] () {
unsigned i = _rx_ring.entries.get_index();
auto req_prod = _rx_ring.req_prod_pvt;
alloc_one_rx_reference(i);
++req_prod;
_rx_ring.req_prod_pvt = req_prod;
wmb();
_rx_ring._sring->req_prod = req_prod;
/* ready */
_rx_evtchn.notify();
});
}
future<> xenfront_net_device::handle_tx_completions() {
return _tx_ring.process_ring([this] (gntref &entry, tx &tx) {
if (tx.rsp.status == 1) {
return false;
}
if (tx.rsp.status != 0) {
_tx_ring.dump("TX positive packet error", tx.rsp);
return false;
}
return true;
}, _tx_refs);
}
ethernet_address xenfront_net_device::hw_address() {
return _hw_address;
}
net::hw_features xenfront_net_device::hw_features() {
return _hw_features;
}
port xenfront_net_device::bind_tx_evtchn(bool split) {
return _evtchn->bind();
}
port xenfront_net_device::bind_rx_evtchn(bool split) {
if (split) {
return _evtchn->bind();
}
return _evtchn->bind(_tx_evtchn.number());
}
xenfront_net_device::xenfront_net_device(boost::program_options::variables_map opts, bool userspace)
: _userspace(userspace)
, _rx_stream()
, _device_str("device/vif/" + std::to_string(opts["vif"].as<unsigned>()))
, _otherend(_xenstore->read<int>(path("backend-id")))
, _backend(_xenstore->read(path("backend")))
, _gntalloc(gntalloc::instance(_userspace, _otherend))
, _evtchn(evtchn::instance(_userspace, _otherend))
, _tx_ring(_gntalloc->alloc_ref())
, _rx_ring(_gntalloc->alloc_ref())
, _tx_refs(_gntalloc->alloc_ref(front_ring<tx>::nr_ents))
, _rx_refs(_gntalloc->alloc_ref(front_ring<rx>::nr_ents))
, _hw_address(net::parse_ethernet_address(_xenstore->read(path("mac")))) {
_rx_stream.started();
auto all_features = _xenstore->ls(_backend);
for (auto&& feat : all_features) {
if (feat.compare(0, 8, "feature-") == 0) {
auto val = _xenstore->read<int>(_backend + "/" + feat);
try {
auto key = _supported_features.at(feat);
_features[key] = val;
} catch (const std::out_of_range& oor) {
_features[feat] = 0;
}
}
}
if (!opts["split-event-channels"].as<bool>()) {
_features["feature-split-event-channels"] = 0;
}
bool split = _features["feature-split-event-channel"];
_hw_features.rx_csum_offload = true;
_hw_features.tx_csum_offload = true;
_tx_evtchn = bind_tx_evtchn(split);
_rx_evtchn = bind_rx_evtchn(split);
{
auto t = xenstore::xenstore_transaction();
for (auto&& f: _features) {
_xenstore->write(path(f.first), f.second, t);
}
if (split) {
_xenstore->write<int>(path("event-channel-tx"), _tx_evtchn.number(), t);
_xenstore->write<int>(path("event-channel-rx"), _rx_evtchn.number(), t);
} else {
_xenstore->write<int>(path("event-channel"), _rx_evtchn.number(), t);
}
_xenstore->write<int>(path("tx-ring-ref"), _tx_ring.ref, t);
_xenstore->write<int>(path("rx-ring-ref"), _rx_ring.ref, t);
_xenstore->write<int>(path("state"), 4, t);
}
keep_doing([this] {
return alloc_rx_references();
});
_rx_evtchn.umask();
keep_doing([this] () {
return _tx_evtchn.pending().then([this] {
handle_tx_completions();
});
});
_tx_evtchn.umask();
}
xenfront_net_device::~xenfront_net_device() {
{
auto t = xenstore::xenstore_transaction();
for (auto& f: _features) {
_xenstore->remove(path(f.first), t);
}
_xenstore->remove(path("event-channel-tx"), t);
_xenstore->remove(path("event-channel-rx"), t);
_xenstore->remove(path("event-channel"), t);
_xenstore->remove(path("tx-ring-ref"), t);
_xenstore->remove(path("rx-ring-ref"), t);
_xenstore->write<int>(path("state"), 6, t);
}
_xenstore->write<int>(path("state"), 1);
}
boost::program_options::options_description
get_xenfront_net_options_description() {
boost::program_options::options_description opts(
"xenfront net options");
opts.add_options()
("vif",
boost::program_options::value<unsigned>()->default_value(0),
"vif number to hijack")
("split-event-channels",
boost::program_options::value<bool>()->default_value(true),
"Split event channel support")
;
return opts;
}
std::unique_ptr<net::device> create_xenfront_net_device(boost::program_options::variables_map opts, bool userspace) {
auto ptr = std::make_unique<xenfront_net_device>(opts, userspace);
// This assumes only one device per cpu. Will need to be fixed when
// this assumption will no longer hold.
dev = ptr.get();
return std::move(ptr);
}
}
<commit_msg>xen: fix typo in event channel detection<commit_after>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include "core/posix.hh"
#include "core/vla.hh"
#include "core/reactor.hh"
#include "core/future-util.hh"
#include "core/stream.hh"
#include "core/circular_buffer.hh"
#include "core/align.hh"
#include <atomic>
#include <list>
#include <queue>
#include <fcntl.h>
#include <linux/if_tun.h>
#include "ip.hh"
#include <xen/xen.h>
#include <xen/memory.h>
#include <xen/sys/gntalloc.h>
#include "core/xen/xenstore.hh"
#include "core/xen/evtchn.hh"
#include "xenfront.hh"
#include <unordered_set>
using namespace net;
namespace xen {
using phys = uint64_t;
class xenfront_net_device : public net::device {
private:
bool _userspace;
stream<packet> _rx_stream;
net::hw_features _hw_features;
std::string _device_str;
xenstore* _xenstore = xenstore::instance();
unsigned _otherend;
std::string _backend;
gntalloc *_gntalloc;
evtchn *_evtchn;
port _tx_evtchn;
port _rx_evtchn;
front_ring<tx> _tx_ring;
front_ring<rx> _rx_ring;
grant_head *_tx_refs;
grant_head *_rx_refs;
std::unordered_map<std::string, int> _features;
static std::unordered_map<std::string, std::string> _supported_features;
ethernet_address _hw_address;
port bind_tx_evtchn(bool split);
port bind_rx_evtchn(bool split);
future<> alloc_rx_references();
future<> handle_tx_completions();
future<> queue_rx_packet();
void alloc_one_rx_reference(unsigned id);
std::string path(std::string s) { return _device_str + "/" + s; }
public:
explicit xenfront_net_device(boost::program_options::variables_map opts, bool userspace);
~xenfront_net_device();
virtual subscription<packet> receive(std::function<future<> (packet)> next) override;
virtual future<> send(packet p) override;
ethernet_address hw_address();
net::hw_features hw_features();
};
std::unordered_map<std::string, std::string>
xenfront_net_device::_supported_features = {
{ "feature-split-event-channels", "feature-split-event-channels" },
{ "feature-rx-copy", "request-rx-copy" }
};
subscription<packet>
xenfront_net_device::receive(std::function<future<> (packet)> next) {
auto sub = _rx_stream.listen(std::move(next));
keep_doing([this] {
return _rx_evtchn.pending().then([this] {
return queue_rx_packet();
});
});
return std::move(sub);
}
future<>
xenfront_net_device::send(packet _p) {
uint32_t frag = 0;
// There doesn't seem to be a way to tell xen, when using the userspace
// drivers, to map a particular page. Therefore, the only alternative
// here is to copy. All pages shared must come from the gntalloc mmap.
//
// A better solution could be to change the packet allocation path to
// use a pre-determined page for data.
//
// In-kernel should be fine
// FIXME: negotiate and use scatter/gather
_p.linearize();
return _tx_ring.entries.has_room().then([this, p = std::move(_p), frag] () mutable {
auto req_prod = _tx_ring._sring->req_prod;
auto f = p.frag(frag);
auto ref = _tx_refs->new_ref(f.base, f.size);
unsigned idx = _tx_ring.entries.get_index();
assert(!_tx_ring.entries[idx]);
_tx_ring.entries[idx] = ref;
auto req = &_tx_ring._sring->_ring[idx].req;
req->gref = ref.xen_id;
req->offset = 0;
req->flags = {};
if (p.offload_info().protocol != ip_protocol_num::unused) {
req->flags.csum_blank = true;
req->flags.data_validated = true;
} else {
req->flags.data_validated = true;
}
req->id = idx;
req->size = f.size;
_tx_ring.req_prod_pvt = idx;
_tx_ring._sring->req_prod = req_prod + 1;
_tx_ring._sring->req_event++;
if ((frag + 1) == p.nr_frags()) {
_tx_evtchn.notify();
return make_ready_future<>();
} else {
return make_ready_future<>();
}
});
// FIXME: Don't forget to clear all grant refs when frontend closes. Or is it automatic?
}
#define rmb() asm volatile("lfence":::"memory");
#define wmb() asm volatile("":::"memory");
template <typename T>
future<> front_ring<T>::entries::has_room() {
return _available.wait();
}
template <typename T>
void front_ring<T>::entries::free_index(unsigned id) {
_available.signal();
}
template <typename T>
unsigned front_ring<T>::entries::get_index() {
return front_ring<T>::idx(_next_idx++);
}
template <typename T>
future<> front_ring<T>::process_ring(std::function<bool (gntref &entry, T& el)> func, grant_head *refs)
{
auto prod = _sring->rsp_prod;
rmb();
for (unsigned i = rsp_cons; i != prod; i++) {
auto el = _sring->_ring[idx(i)];
if (el.rsp.status < 0) {
dump("Packet error", el.rsp);
continue;
}
auto& entry = entries[i];
if (!func(entry, el)) {
continue;
}
assert(entry.xen_id >= 0);
refs->free_ref(entry);
entries.free_index(i);
prod = _sring->rsp_prod;
}
rsp_cons = prod;
_sring->rsp_event = prod + 1;
return make_ready_future<>();
}
future<> xenfront_net_device::queue_rx_packet()
{
return _rx_ring.process_ring([this] (gntref &entry, rx &rx) {
packet p(static_cast<char *>(entry.page) + rx.rsp.offset, rx.rsp.status);
_rx_stream.produce(std::move(p));
return true;
}, _rx_refs);
}
void xenfront_net_device::alloc_one_rx_reference(unsigned index) {
_rx_ring.entries[index] = _rx_refs->new_ref();
// This is how the backend knows where to put data.
auto req = &_rx_ring._sring->_ring[index].req;
req->id = index;
req->gref = _rx_ring.entries[index].xen_id;
}
future<> xenfront_net_device::alloc_rx_references() {
return _rx_ring.entries.has_room().then([this] () {
unsigned i = _rx_ring.entries.get_index();
auto req_prod = _rx_ring.req_prod_pvt;
alloc_one_rx_reference(i);
++req_prod;
_rx_ring.req_prod_pvt = req_prod;
wmb();
_rx_ring._sring->req_prod = req_prod;
/* ready */
_rx_evtchn.notify();
});
}
future<> xenfront_net_device::handle_tx_completions() {
return _tx_ring.process_ring([this] (gntref &entry, tx &tx) {
if (tx.rsp.status == 1) {
return false;
}
if (tx.rsp.status != 0) {
_tx_ring.dump("TX positive packet error", tx.rsp);
return false;
}
return true;
}, _tx_refs);
}
ethernet_address xenfront_net_device::hw_address() {
return _hw_address;
}
net::hw_features xenfront_net_device::hw_features() {
return _hw_features;
}
port xenfront_net_device::bind_tx_evtchn(bool split) {
return _evtchn->bind();
}
port xenfront_net_device::bind_rx_evtchn(bool split) {
if (split) {
return _evtchn->bind();
}
return _evtchn->bind(_tx_evtchn.number());
}
xenfront_net_device::xenfront_net_device(boost::program_options::variables_map opts, bool userspace)
: _userspace(userspace)
, _rx_stream()
, _device_str("device/vif/" + std::to_string(opts["vif"].as<unsigned>()))
, _otherend(_xenstore->read<int>(path("backend-id")))
, _backend(_xenstore->read(path("backend")))
, _gntalloc(gntalloc::instance(_userspace, _otherend))
, _evtchn(evtchn::instance(_userspace, _otherend))
, _tx_ring(_gntalloc->alloc_ref())
, _rx_ring(_gntalloc->alloc_ref())
, _tx_refs(_gntalloc->alloc_ref(front_ring<tx>::nr_ents))
, _rx_refs(_gntalloc->alloc_ref(front_ring<rx>::nr_ents))
, _hw_address(net::parse_ethernet_address(_xenstore->read(path("mac")))) {
_rx_stream.started();
auto all_features = _xenstore->ls(_backend);
for (auto&& feat : all_features) {
if (feat.compare(0, 8, "feature-") == 0) {
auto val = _xenstore->read<int>(_backend + "/" + feat);
try {
auto key = _supported_features.at(feat);
_features[key] = val;
} catch (const std::out_of_range& oor) {
_features[feat] = 0;
}
}
}
if (!opts["split-event-channels"].as<bool>()) {
_features["feature-split-event-channels"] = 0;
}
bool split = _features["feature-split-event-channels"];
_hw_features.rx_csum_offload = true;
_hw_features.tx_csum_offload = true;
_tx_evtchn = bind_tx_evtchn(split);
_rx_evtchn = bind_rx_evtchn(split);
{
auto t = xenstore::xenstore_transaction();
for (auto&& f: _features) {
_xenstore->write(path(f.first), f.second, t);
}
if (split) {
_xenstore->write<int>(path("event-channel-tx"), _tx_evtchn.number(), t);
_xenstore->write<int>(path("event-channel-rx"), _rx_evtchn.number(), t);
} else {
_xenstore->write<int>(path("event-channel"), _rx_evtchn.number(), t);
}
_xenstore->write<int>(path("tx-ring-ref"), _tx_ring.ref, t);
_xenstore->write<int>(path("rx-ring-ref"), _rx_ring.ref, t);
_xenstore->write<int>(path("state"), 4, t);
}
keep_doing([this] {
return alloc_rx_references();
});
_rx_evtchn.umask();
keep_doing([this] () {
return _tx_evtchn.pending().then([this] {
handle_tx_completions();
});
});
_tx_evtchn.umask();
}
xenfront_net_device::~xenfront_net_device() {
{
auto t = xenstore::xenstore_transaction();
for (auto& f: _features) {
_xenstore->remove(path(f.first), t);
}
_xenstore->remove(path("event-channel-tx"), t);
_xenstore->remove(path("event-channel-rx"), t);
_xenstore->remove(path("event-channel"), t);
_xenstore->remove(path("tx-ring-ref"), t);
_xenstore->remove(path("rx-ring-ref"), t);
_xenstore->write<int>(path("state"), 6, t);
}
_xenstore->write<int>(path("state"), 1);
}
boost::program_options::options_description
get_xenfront_net_options_description() {
boost::program_options::options_description opts(
"xenfront net options");
opts.add_options()
("vif",
boost::program_options::value<unsigned>()->default_value(0),
"vif number to hijack")
("split-event-channels",
boost::program_options::value<bool>()->default_value(true),
"Split event channel support")
;
return opts;
}
std::unique_ptr<net::device> create_xenfront_net_device(boost::program_options::variables_map opts, bool userspace) {
auto ptr = std::make_unique<xenfront_net_device>(opts, userspace);
// This assumes only one device per cpu. Will need to be fixed when
// this assumption will no longer hold.
dev = ptr.get();
return std::move(ptr);
}
}
<|endoftext|>
|
<commit_before>#include "schema_functions.h"
#include <algorithm>
template <typename T>
struct name_is {
const string &name;
name_is(const string &name): name(name) {}
bool operator()(const T& obj) const {
return (obj.name == name);
}
};
void report_schema_mismatch(const string &error) {
// FUTURE: can we implement some kind of non-fatal mismatch handling?
throw schema_mismatch(error);
}
void check_column_match(const Table &table, const Column &from_column, const Column &to_column) {
// FUTURE: check collation etc.
if (from_column.column_type != to_column.column_type) {
report_schema_mismatch("Column " + from_column.name + " on table " + table.name + " should be " + from_column.column_type + " but was " + to_column.column_type);
}
if (from_column.size != to_column.size) {
report_schema_mismatch("Column " + from_column.name + " on table " + table.name + " should have size " + to_string(from_column.size) + " but was " + to_string(to_column.size));
}
if (from_column.nullable != to_column.nullable) {
report_schema_mismatch("Column " + from_column.name + " on table " + table.name + " should be " + (from_column.nullable ? "nullable" : "not nullable") + " but was " + (to_column.nullable ? "nullable" : "not nullable"));
}
}
void check_columns_match(const Table &table, const Columns &from_columns, const Columns &to_columns) {
Columns::const_iterator to_column = to_columns.begin();
for (Columns::const_iterator from_column = from_columns.begin(); from_column != from_columns.end(); ++from_column) {
if (to_column != to_columns.end() && to_column->name == from_column->name) {
check_column_match(table, *from_column, *to_column);
++to_column;
} else if (find_if(to_column, to_columns.end(), name_is<Column>(from_column->name)) == to_columns.end()) {
report_schema_mismatch("Missing column " + from_column->name + " on table " + table.name);
} else if (find_if(from_column, from_columns.end(), name_is<Column>(to_column->name)) == from_columns.end()) {
report_schema_mismatch("Extra column " + to_column->name + " on table " + table.name);
} else {
report_schema_mismatch("Misordered column " + from_column->name + " on table " + table.name + ", should have " + to_column->name + " first");
}
}
if (to_column != to_columns.end()) {
report_schema_mismatch("Extra column " + to_column->name + " on table " + table.name);
}
}
string column_names(const Columns &columns, const ColumnIndices &column_indices) {
if (column_indices.empty()) {
return "(NULL)";
}
string result("(");
result.append(columns[*column_indices.begin()].name);
for (ColumnIndices::const_iterator column_index = column_indices.begin() + 1; column_index != column_indices.end(); ++column_index) {
result.append(", ");
result.append(columns[*column_index].name);
}
result.append(")");
return result;
}
void check_primary_key_matches(const Table &table, const ColumnIndices &from_primary_key_columns, const ColumnIndices &to_primary_key_columns) {
if (from_primary_key_columns != to_primary_key_columns) {
report_schema_mismatch("Mismatching primary key " + column_names(table.columns, to_primary_key_columns) + " on table " + table.name + ", should have " + column_names(table.columns, from_primary_key_columns));
}
}
void check_key_match(const Table &table, const Key &from_key, const Key &to_key) {
if (from_key.unique != to_key.unique) {
report_schema_mismatch("Mismatching unique flag on table " + table.name + " key " + from_key.name);
}
if (from_key.columns != to_key.columns) {
report_schema_mismatch("Mismatching columns " + column_names(table.columns, to_key.columns) + " on table " + table.name + " key " + from_key.name + ", should have " + column_names(table.columns, from_key.columns));
}
}
void check_keys_match(const Table &table, Keys from_keys, Keys to_keys) {
// the keys should already be given in a consistent sorted order, but our algorithm requires it, so we quickly enforce it here
sort(from_keys.begin(), from_keys.end());
sort( to_keys.begin(), to_keys.end());
Keys::const_iterator to_key = to_keys.begin();
for (Keys::const_iterator from_key = from_keys.begin(); from_key != from_keys.end(); ++from_key) {
if (to_key == to_keys.end() || to_key->name > from_key->name) {
report_schema_mismatch("Missing key " + from_key->name + " on table " + table.name);
} else if (to_key->name < from_key->name) {
report_schema_mismatch("Extra key " + to_key->name + " on table " + table.name);
} else {
check_key_match(table, *from_key, *to_key);
++to_key;
}
}
if (to_key != to_keys.end()) {
report_schema_mismatch("Extra key " + to_key->name + " on table " + table.name);
}
}
void check_table_match(const Table &from_table, const Table &to_table) {
check_columns_match(from_table, from_table.columns, to_table.columns);
check_primary_key_matches(from_table, from_table.primary_key_columns, to_table.primary_key_columns);
check_keys_match(from_table, from_table.keys, to_table.keys);
// FUTURE: check collation etc.
}
void check_tables_match(Tables from_tables, Tables to_tables) {
// databases typically return the tables in sorted order, but our algorithm requires it, so we quickly enforce it here
sort(from_tables.begin(), from_tables.end());
sort( to_tables.begin(), to_tables.end());
Tables::const_iterator to_table = to_tables.begin();
for (Tables::const_iterator from_table = from_tables.begin(); from_table != from_tables.end(); ++from_table) {
if (to_table == to_tables.end() || to_table->name > from_table->name) {
report_schema_mismatch("Missing table " + from_table->name);
} else if (to_table->name < from_table->name) {
report_schema_mismatch("Extra table " + to_table->name);
} else {
check_table_match(*from_table, *to_table);
++to_table;
}
}
if (to_table != to_tables.end()) {
report_schema_mismatch("Extra table " + to_table->name);
}
}
void match_schemas(const Database &from_database, const Database &to_database) {
// currently we only pay attention to tables, but in the future we might support other schema items
check_tables_match(from_database.tables, to_database.tables);
}
<commit_msg>rename a function for clarity, is only used for error messages and shouldn't be used in SQL<commit_after>#include "schema_functions.h"
#include <algorithm>
template <typename T>
struct name_is {
const string &name;
name_is(const string &name): name(name) {}
bool operator()(const T& obj) const {
return (obj.name == name);
}
};
void report_schema_mismatch(const string &error) {
// FUTURE: can we implement some kind of non-fatal mismatch handling?
throw schema_mismatch(error);
}
void check_column_match(const Table &table, const Column &from_column, const Column &to_column) {
// FUTURE: check collation etc.
if (from_column.column_type != to_column.column_type) {
report_schema_mismatch("Column " + from_column.name + " on table " + table.name + " should be " + from_column.column_type + " but was " + to_column.column_type);
}
if (from_column.size != to_column.size) {
report_schema_mismatch("Column " + from_column.name + " on table " + table.name + " should have size " + to_string(from_column.size) + " but was " + to_string(to_column.size));
}
if (from_column.nullable != to_column.nullable) {
report_schema_mismatch("Column " + from_column.name + " on table " + table.name + " should be " + (from_column.nullable ? "nullable" : "not nullable") + " but was " + (to_column.nullable ? "nullable" : "not nullable"));
}
}
void check_columns_match(const Table &table, const Columns &from_columns, const Columns &to_columns) {
Columns::const_iterator to_column = to_columns.begin();
for (Columns::const_iterator from_column = from_columns.begin(); from_column != from_columns.end(); ++from_column) {
if (to_column != to_columns.end() && to_column->name == from_column->name) {
check_column_match(table, *from_column, *to_column);
++to_column;
} else if (find_if(to_column, to_columns.end(), name_is<Column>(from_column->name)) == to_columns.end()) {
report_schema_mismatch("Missing column " + from_column->name + " on table " + table.name);
} else if (find_if(from_column, from_columns.end(), name_is<Column>(to_column->name)) == from_columns.end()) {
report_schema_mismatch("Extra column " + to_column->name + " on table " + table.name);
} else {
report_schema_mismatch("Misordered column " + from_column->name + " on table " + table.name + ", should have " + to_column->name + " first");
}
}
if (to_column != to_columns.end()) {
report_schema_mismatch("Extra column " + to_column->name + " on table " + table.name);
}
}
string unquoted_column_names_list(const Columns &columns, const ColumnIndices &column_indices) {
if (column_indices.empty()) {
return "(NULL)";
}
string result("(");
result.append(columns[*column_indices.begin()].name);
for (ColumnIndices::const_iterator column_index = column_indices.begin() + 1; column_index != column_indices.end(); ++column_index) {
result.append(", ");
result.append(columns[*column_index].name);
}
result.append(")");
return result;
}
void check_primary_key_matches(const Table &table, const ColumnIndices &from_primary_key_columns, const ColumnIndices &to_primary_key_columns) {
if (from_primary_key_columns != to_primary_key_columns) {
report_schema_mismatch("Mismatching primary key " + unquoted_column_names_list(table.columns, to_primary_key_columns) + " on table " + table.name + ", should have " + unquoted_column_names_list(table.columns, from_primary_key_columns));
}
}
void check_key_match(const Table &table, const Key &from_key, const Key &to_key) {
if (from_key.unique != to_key.unique) {
report_schema_mismatch("Mismatching unique flag on table " + table.name + " key " + from_key.name);
}
if (from_key.columns != to_key.columns) {
report_schema_mismatch("Mismatching columns " + unquoted_column_names_list(table.columns, to_key.columns) + " on table " + table.name + " key " + from_key.name + ", should have " + unquoted_column_names_list(table.columns, from_key.columns));
}
}
void check_keys_match(const Table &table, Keys from_keys, Keys to_keys) {
// the keys should already be given in a consistent sorted order, but our algorithm requires it, so we quickly enforce it here
sort(from_keys.begin(), from_keys.end());
sort( to_keys.begin(), to_keys.end());
Keys::const_iterator to_key = to_keys.begin();
for (Keys::const_iterator from_key = from_keys.begin(); from_key != from_keys.end(); ++from_key) {
if (to_key == to_keys.end() || to_key->name > from_key->name) {
report_schema_mismatch("Missing key " + from_key->name + " on table " + table.name);
} else if (to_key->name < from_key->name) {
report_schema_mismatch("Extra key " + to_key->name + " on table " + table.name);
} else {
check_key_match(table, *from_key, *to_key);
++to_key;
}
}
if (to_key != to_keys.end()) {
report_schema_mismatch("Extra key " + to_key->name + " on table " + table.name);
}
}
void check_table_match(const Table &from_table, const Table &to_table) {
check_columns_match(from_table, from_table.columns, to_table.columns);
check_primary_key_matches(from_table, from_table.primary_key_columns, to_table.primary_key_columns);
check_keys_match(from_table, from_table.keys, to_table.keys);
// FUTURE: check collation etc.
}
void check_tables_match(Tables from_tables, Tables to_tables) {
// databases typically return the tables in sorted order, but our algorithm requires it, so we quickly enforce it here
sort(from_tables.begin(), from_tables.end());
sort( to_tables.begin(), to_tables.end());
Tables::const_iterator to_table = to_tables.begin();
for (Tables::const_iterator from_table = from_tables.begin(); from_table != from_tables.end(); ++from_table) {
if (to_table == to_tables.end() || to_table->name > from_table->name) {
report_schema_mismatch("Missing table " + from_table->name);
} else if (to_table->name < from_table->name) {
report_schema_mismatch("Extra table " + to_table->name);
} else {
check_table_match(*from_table, *to_table);
++to_table;
}
}
if (to_table != to_tables.end()) {
report_schema_mismatch("Extra table " + to_table->name);
}
}
void match_schemas(const Database &from_database, const Database &to_database) {
// currently we only pay attention to tables, but in the future we might support other schema items
check_tables_match(from_database.tables, to_database.tables);
}
<|endoftext|>
|
<commit_before>#ifndef RIAK_RIAK_HPP_
#define RIAK_RIAK_HPP_
#include "errors.hpp"
#include <boost/tokenizer.hpp>
// #include <boost/fusion/include/adapt_struct.hpp>
// #include <boost/fusion/include/io.hpp>
#include "http/http.hpp"
#include "riak/riak_interface.hpp"
#include "riak/store_manager.hpp"
#include "spirit/boost_parser.hpp"
namespace riak {
struct link_t;
template <typename Iterator>
struct link_parser_t: qi::grammar<Iterator, std::vector<link_t>()> {
link_parser_t() : link_parser_t::base_type(start) {
using qi::lit;
using qi::_val;
using ascii::char_;
using ascii::space;
using qi::_1;
using qi::repeat;
namespace labels = qi::labels;
using boost::phoenix::at_c;
using boost::phoenix::bind;
link %= lit("</riak/") >> +(char_ - "/") >> "/" >> +(char_ - ">") >>
lit(">; riaktag=\"") >> +(char_ - "\"") >> "\"";
start %= (link % lit(", "));
}
qi::rule<Iterator, link_t()> link;
qi::rule<Iterator, std::vector<link_t>()> start;
};
class riak_http_app_t : public http_app_t {
public:
explicit riak_http_app_t(store_manager_t<std::list<std::string> > *);
private:
http_res_t handle(const http_req_t &);
private:
riak_interface_t riak_interface;
private:
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
typedef tokenizer::iterator tok_iterator;
//handlers for specific commands, really just to break up the code
private:
http_res_t list_buckets(const http_req_t &);
http_res_t get_bucket(const http_req_t &);
http_res_t set_bucket(const http_req_t &);
http_res_t fetch_object(const http_req_t &);
http_res_t store_object(const http_req_t &);
http_res_t delete_object(const http_req_t &);
http_res_t link_walk(const http_req_t &);
http_res_t mapreduce(const http_req_t &);
http_res_t luwak_info(const http_req_t &);
//http_res_t luwak_keys(const http_req_t &);
http_res_t luwak_fetch(const http_req_t &);
http_res_t luwak_store(const http_req_t &);
http_res_t luwak_delete(const http_req_t &);
http_res_t ping(const http_req_t &);
http_res_t status(const http_req_t &);
http_res_t list_resources(const http_req_t &);
};
}; //namespace riak
#endif
<commit_msg>Actually removed lines of code instead of commenting them out.<commit_after>#ifndef RIAK_RIAK_HPP_
#define RIAK_RIAK_HPP_
#include "errors.hpp"
#include <boost/tokenizer.hpp>
#include "http/http.hpp"
#include "riak/riak_interface.hpp"
#include "riak/store_manager.hpp"
#include "spirit/boost_parser.hpp"
namespace riak {
struct link_t;
template <typename Iterator>
struct link_parser_t: qi::grammar<Iterator, std::vector<link_t>()> {
link_parser_t() : link_parser_t::base_type(start) {
using qi::lit;
using qi::_val;
using ascii::char_;
using ascii::space;
using qi::_1;
using qi::repeat;
namespace labels = qi::labels;
using boost::phoenix::at_c;
using boost::phoenix::bind;
link %= lit("</riak/") >> +(char_ - "/") >> "/" >> +(char_ - ">") >>
lit(">; riaktag=\"") >> +(char_ - "\"") >> "\"";
start %= (link % lit(", "));
}
qi::rule<Iterator, link_t()> link;
qi::rule<Iterator, std::vector<link_t>()> start;
};
class riak_http_app_t : public http_app_t {
public:
explicit riak_http_app_t(store_manager_t<std::list<std::string> > *);
private:
http_res_t handle(const http_req_t &);
private:
riak_interface_t riak_interface;
private:
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
typedef tokenizer::iterator tok_iterator;
//handlers for specific commands, really just to break up the code
private:
http_res_t list_buckets(const http_req_t &);
http_res_t get_bucket(const http_req_t &);
http_res_t set_bucket(const http_req_t &);
http_res_t fetch_object(const http_req_t &);
http_res_t store_object(const http_req_t &);
http_res_t delete_object(const http_req_t &);
http_res_t link_walk(const http_req_t &);
http_res_t mapreduce(const http_req_t &);
http_res_t luwak_info(const http_req_t &);
//http_res_t luwak_keys(const http_req_t &);
http_res_t luwak_fetch(const http_req_t &);
http_res_t luwak_store(const http_req_t &);
http_res_t luwak_delete(const http_req_t &);
http_res_t ping(const http_req_t &);
http_res_t status(const http_req_t &);
http_res_t list_resources(const http_req_t &);
};
}; //namespace riak
#endif
<|endoftext|>
|
<commit_before>#include "gtest/gtest.h"
#include "world/ComponentManager.h"
#include "world/system_setup.h"
#include "config/Config.h"
#include "iocontroller/IOController.h"
class ConfigTest : public ::testing::Test {
protected:
Susi::IOController io;
virtual void SetUp() override {
io.makeDir("./configtest/");
}
virtual void TearDown() override {
io.deletePath("./configtest/");
}
};
TEST_F(ConfigTest, Contruct) {
Susi::Util::Any cfg = Susi::Util::Any::Object{
{"foo","bar"}
};
// Test valid json
io.writeFile("./configtest/config.cfg",cfg.toString());
EXPECT_NO_THROW({
auto config = std::make_shared<Susi::Config>("./configtest/config.cfg");
});
}
TEST_F(ConfigTest, ContructInvalidJson) {
io.writeFile("./configtest/config.cfg","{\"foo\",\"bar\", 22");
EXPECT_THROW({
auto config = std::make_shared<Susi::Config>("./configtest/config.cfg");
},std::runtime_error);
}
TEST_F(ConfigTest, ContructWrongFormatJson) {
// Test valid json which is no object;
io.writeFile("./configtest/config.cfg","\"wrongformat\"");
EXPECT_THROW({
auto config = std::make_shared<Susi::Config>("./configtest/config.cfg");
},std::runtime_error);
}
TEST_F(ConfigTest, ContructConfigMissing) {
// Test nonexistent file;
EXPECT_THROW({
auto config = std::make_shared<Susi::Config>("./configtest/wrongname.cfg");
},std::runtime_error);
}
TEST_F(ConfigTest, Get){
using Susi::Util::Any;
Any cfg = Any::Object{{"foo",Any::Object{{"bar", Any::Object{{"baz",123}}}}}};
io.writeFile("./configtest/config.cfg",cfg.toString());
EXPECT_NO_THROW({
auto config = std::make_shared<Susi::Config>("./configtest/config.cfg");
Any value1 = config->get("");
EXPECT_EQ(cfg,value1);
Any value2 = config->get("foo");
EXPECT_EQ(cfg["foo"],value2);
Any value3 = config->get("foo.bar");
EXPECT_EQ(cfg["foo"]["bar"],value3);
Any value4 = config->get("foo.bar.baz");
EXPECT_EQ(cfg["foo"]["bar"]["baz"],value4);
});
EXPECT_THROW({
auto config = std::make_shared<Susi::Config>("./configtest/config.cfg");
config->get("bla");
},std::runtime_error);
EXPECT_THROW({
auto config = std::make_shared<Susi::Config>("./configtest/config.cfg");
config->get("bla.blub");
},std::runtime_error);
}
TEST_F(ConfigTest,CommandLine){
using Susi::Util::Any;
Any cfg = Any::Object{{"foo",Any::Object{{"bar", Any::Object{{"baz",123}}}}}};
io.writeFile("./configtest/config.cfg",cfg.toString());
std::vector<std::string> cmdLine_1 = {"prognameIsAllwaysFirstParam","-baz","321"};
std::vector<std::string> cmdLine_2 = {"prognameIsAllwaysFirstParam","-baz","321.123"};
std::vector<std::string> cmdLine_3 = {"prognameIsAllwaysFirstParam","-baz","this is it"};
EXPECT_NO_THROW({
auto config = std::make_shared<Susi::Config>("./configtest/config.cfg");
config->registerCommandLineOption("baz","foo.bar.baz");
config->parseCommandLine(cmdLine_1);
EXPECT_EQ(Any{321}.toString(),config->get("foo.bar.baz").toString());
config->parseCommandLine(cmdLine_2);
EXPECT_EQ(Any{321.123}.toString(),config->get("foo.bar.baz").toString());
config->parseCommandLine(cmdLine_3);
EXPECT_EQ(Any{"this is it"}.toString(),config->get("foo.bar.baz").toString());
});
}
TEST_F(ConfigTest,CommandLineOneDashNoArg){
Susi::Config cfg;
std::vector<std::string> cmdline = {"prognameIsAllwaysFirstParam","-foo"};
cfg.parseCommandLine(cmdline);
EXPECT_TRUE(cfg.get("foo").isObject());
}
TEST_F(ConfigTest,CommandLineOneDashOneArg){
Susi::Config cfg;
std::vector<std::string> cmdline = {"prognameIsAllwaysFirstParam","-foo","bla"};
cfg.parseCommandLine(cmdline);
EXPECT_TRUE(cfg.get("foo").isString());
EXPECT_EQ("\"bla\"",cfg.get("foo").toString());
}
TEST_F(ConfigTest,CommandLineOneDashOneArg2){
Susi::Config cfg;
std::vector<std::string> cmdline = {"prognameIsAllwaysFirstParam","-foo=bla"};
cfg.parseCommandLine(cmdline);
EXPECT_TRUE(cfg.get("foo").isString());
EXPECT_EQ("\"bla\"",cfg.get("foo").toString());
}
TEST_F(ConfigTest,CommandLineTwoDashNoArg){
Susi::Config cfg;
std::vector<std::string> cmdline = {"prognameIsAllwaysFirstParam","--foo"};
cfg.parseCommandLine(cmdline);
EXPECT_TRUE(cfg.get("foo").isObject());
}
TEST_F(ConfigTest,CommandLineTwoDashOneArg){
Susi::Config cfg;
std::vector<std::string> cmdline = {"prognameIsAllwaysFirstParam","--foo","bla"};
cfg.parseCommandLine(cmdline);
EXPECT_TRUE(cfg.get("foo").isString());
EXPECT_EQ("\"bla\"",cfg.get("foo").toString());
}
TEST_F(ConfigTest,CommandLineTwoDashOneArg2){
Susi::Config cfg;
std::vector<std::string> cmdline = {"prognameIsAllwaysFirstParam","--foo=bla"};
cfg.parseCommandLine(cmdline);
EXPECT_TRUE(cfg.get("foo").isString());
EXPECT_EQ("\"bla\"",cfg.get("foo").toString());
}
TEST_F(ConfigTest,MultipleArguments){
Susi::Config cfg;
std::vector<std::string> cmdline = {
"prognameIsAllwaysFirstParam",
"--foo=bla",
"-bar","bla",
"-bla",
"--baz","bla"};
cfg.parseCommandLine(cmdline);
EXPECT_EQ("\"bla\"",cfg.get("foo").toString());
EXPECT_EQ("\"bla\"",cfg.get("bar").toString());
EXPECT_TRUE(cfg.get("bla").isObject());
EXPECT_EQ("\"bla\"",cfg.get("baz").toString());
}
TEST_F(ConfigTest,MultiLevelArguments){
Susi::Config cfg;
std::vector<std::string> cmdline = {"prognameIsAllwaysFirstParam","--foo.bar.baz=bla"};
cfg.parseCommandLine(cmdline);
EXPECT_TRUE(cfg.get("foo.bar.baz").isString());
EXPECT_EQ("\"bla\"",cfg.get("foo.bar.baz").toString());
}
TEST_F(ConfigTest,MultiConfigSupport){
Susi::Util::Any cfg_1 = Susi::Util::Any::Object{
{"foo","bar"},
{"data", "test1"}
};
// Test valid json
io.writeFile("./configtest/config_1.cfg",cfg_1.toString());
Susi::Util::Any cfg_2 = Susi::Util::Any::Object{
{"john","doe"},
{"data", "test2"}
};
io.writeFile("./configtest/config_2.cfg",cfg_2.toString());
Susi::Config cfg;
cfg.loadConfig("./configtest/config_1.cfg");
cfg.loadConfig("./configtest/config_2.cfg");
Susi::Util::Any conf = cfg.getConfig();
EXPECT_TRUE(cfg.get("foo").isString());
EXPECT_EQ("\"bar\"",cfg.get("foo").toString());
EXPECT_TRUE(cfg.get("john").isString());
EXPECT_EQ("\"doe\"",cfg.get("john").toString());
// test override
EXPECT_TRUE(cfg.get("data").isString());
EXPECT_EQ("\"test2\"",cfg.get("data").toString());
}
TEST_F(ConfigTest, LoadAllStartStop){
// make test independed from config file
/*
class C1 : public Component {};
class C2 : public Component {};
class C3 : public Component {};
mgr->registerComponent("c1",[](){return std::make_shared<C1>();});
mgr->registerComponent("c2",[](){return std::make_shared<C2>();});
mgr->registerComponent("c3",[](){return std::make_shared<C3>();});
cfg {"c1",{}}{"c2",{}}
*/
Susi::Config cfg{};
cfg.loadConfig("config.json");
std::shared_ptr<Susi::System::ComponentManager> componentManager = Susi::System::createSusiComponentManager(cfg.getConfig());
bool start = componentManager->startAll();
bool stop = componentManager->stopAll();
EXPECT_TRUE(start);
EXPECT_TRUE(stop);
}<commit_msg>[ConfigTest] make LoadAllStartStop Test independed from config file;<commit_after>#include "gtest/gtest.h"
#include "world/ComponentManager.h"
#include "world/system_setup.h"
#include "config/Config.h"
#include "iocontroller/IOController.h"
class ConfigTest : public ::testing::Test {
protected:
Susi::IOController io;
virtual void SetUp() override {
io.makeDir("./configtest/");
}
virtual void TearDown() override {
io.deletePath("./configtest/");
}
};
TEST_F(ConfigTest, Contruct) {
Susi::Util::Any cfg = Susi::Util::Any::Object{
{"foo","bar"}
};
// Test valid json
io.writeFile("./configtest/config.cfg",cfg.toString());
EXPECT_NO_THROW({
auto config = std::make_shared<Susi::Config>("./configtest/config.cfg");
});
}
TEST_F(ConfigTest, ContructInvalidJson) {
io.writeFile("./configtest/config.cfg","{\"foo\",\"bar\", 22");
EXPECT_THROW({
auto config = std::make_shared<Susi::Config>("./configtest/config.cfg");
},std::runtime_error);
}
TEST_F(ConfigTest, ContructWrongFormatJson) {
// Test valid json which is no object;
io.writeFile("./configtest/config.cfg","\"wrongformat\"");
EXPECT_THROW({
auto config = std::make_shared<Susi::Config>("./configtest/config.cfg");
},std::runtime_error);
}
TEST_F(ConfigTest, ContructConfigMissing) {
// Test nonexistent file;
EXPECT_THROW({
auto config = std::make_shared<Susi::Config>("./configtest/wrongname.cfg");
},std::runtime_error);
}
TEST_F(ConfigTest, Get){
using Susi::Util::Any;
Any cfg = Any::Object{{"foo",Any::Object{{"bar", Any::Object{{"baz",123}}}}}};
io.writeFile("./configtest/config.cfg",cfg.toString());
EXPECT_NO_THROW({
auto config = std::make_shared<Susi::Config>("./configtest/config.cfg");
Any value1 = config->get("");
EXPECT_EQ(cfg,value1);
Any value2 = config->get("foo");
EXPECT_EQ(cfg["foo"],value2);
Any value3 = config->get("foo.bar");
EXPECT_EQ(cfg["foo"]["bar"],value3);
Any value4 = config->get("foo.bar.baz");
EXPECT_EQ(cfg["foo"]["bar"]["baz"],value4);
});
EXPECT_THROW({
auto config = std::make_shared<Susi::Config>("./configtest/config.cfg");
config->get("bla");
},std::runtime_error);
EXPECT_THROW({
auto config = std::make_shared<Susi::Config>("./configtest/config.cfg");
config->get("bla.blub");
},std::runtime_error);
}
TEST_F(ConfigTest,CommandLine){
using Susi::Util::Any;
Any cfg = Any::Object{{"foo",Any::Object{{"bar", Any::Object{{"baz",123}}}}}};
io.writeFile("./configtest/config.cfg",cfg.toString());
std::vector<std::string> cmdLine_1 = {"prognameIsAllwaysFirstParam","-baz","321"};
std::vector<std::string> cmdLine_2 = {"prognameIsAllwaysFirstParam","-baz","321.123"};
std::vector<std::string> cmdLine_3 = {"prognameIsAllwaysFirstParam","-baz","this is it"};
EXPECT_NO_THROW({
auto config = std::make_shared<Susi::Config>("./configtest/config.cfg");
config->registerCommandLineOption("baz","foo.bar.baz");
config->parseCommandLine(cmdLine_1);
EXPECT_EQ(Any{321}.toString(),config->get("foo.bar.baz").toString());
config->parseCommandLine(cmdLine_2);
EXPECT_EQ(Any{321.123}.toString(),config->get("foo.bar.baz").toString());
config->parseCommandLine(cmdLine_3);
EXPECT_EQ(Any{"this is it"}.toString(),config->get("foo.bar.baz").toString());
});
}
TEST_F(ConfigTest,CommandLineOneDashNoArg){
Susi::Config cfg;
std::vector<std::string> cmdline = {"prognameIsAllwaysFirstParam","-foo"};
cfg.parseCommandLine(cmdline);
EXPECT_TRUE(cfg.get("foo").isObject());
}
TEST_F(ConfigTest,CommandLineOneDashOneArg){
Susi::Config cfg;
std::vector<std::string> cmdline = {"prognameIsAllwaysFirstParam","-foo","bla"};
cfg.parseCommandLine(cmdline);
EXPECT_TRUE(cfg.get("foo").isString());
EXPECT_EQ("\"bla\"",cfg.get("foo").toString());
}
TEST_F(ConfigTest,CommandLineOneDashOneArg2){
Susi::Config cfg;
std::vector<std::string> cmdline = {"prognameIsAllwaysFirstParam","-foo=bla"};
cfg.parseCommandLine(cmdline);
EXPECT_TRUE(cfg.get("foo").isString());
EXPECT_EQ("\"bla\"",cfg.get("foo").toString());
}
TEST_F(ConfigTest,CommandLineTwoDashNoArg){
Susi::Config cfg;
std::vector<std::string> cmdline = {"prognameIsAllwaysFirstParam","--foo"};
cfg.parseCommandLine(cmdline);
EXPECT_TRUE(cfg.get("foo").isObject());
}
TEST_F(ConfigTest,CommandLineTwoDashOneArg){
Susi::Config cfg;
std::vector<std::string> cmdline = {"prognameIsAllwaysFirstParam","--foo","bla"};
cfg.parseCommandLine(cmdline);
EXPECT_TRUE(cfg.get("foo").isString());
EXPECT_EQ("\"bla\"",cfg.get("foo").toString());
}
TEST_F(ConfigTest,CommandLineTwoDashOneArg2){
Susi::Config cfg;
std::vector<std::string> cmdline = {"prognameIsAllwaysFirstParam","--foo=bla"};
cfg.parseCommandLine(cmdline);
EXPECT_TRUE(cfg.get("foo").isString());
EXPECT_EQ("\"bla\"",cfg.get("foo").toString());
}
TEST_F(ConfigTest,MultipleArguments){
Susi::Config cfg;
std::vector<std::string> cmdline = {
"prognameIsAllwaysFirstParam",
"--foo=bla",
"-bar","bla",
"-bla",
"--baz","bla"};
cfg.parseCommandLine(cmdline);
EXPECT_EQ("\"bla\"",cfg.get("foo").toString());
EXPECT_EQ("\"bla\"",cfg.get("bar").toString());
EXPECT_TRUE(cfg.get("bla").isObject());
EXPECT_EQ("\"bla\"",cfg.get("baz").toString());
}
TEST_F(ConfigTest,MultiLevelArguments){
Susi::Config cfg;
std::vector<std::string> cmdline = {"prognameIsAllwaysFirstParam","--foo.bar.baz=bla"};
cfg.parseCommandLine(cmdline);
EXPECT_TRUE(cfg.get("foo.bar.baz").isString());
EXPECT_EQ("\"bla\"",cfg.get("foo.bar.baz").toString());
}
TEST_F(ConfigTest,MultiConfigSupport){
Susi::Util::Any cfg_1 = Susi::Util::Any::Object{
{"foo","bar"},
{"data", "test1"}
};
// Test valid json
io.writeFile("./configtest/config_1.cfg",cfg_1.toString());
Susi::Util::Any cfg_2 = Susi::Util::Any::Object{
{"john","doe"},
{"data", "test2"}
};
io.writeFile("./configtest/config_2.cfg",cfg_2.toString());
Susi::Config cfg;
cfg.loadConfig("./configtest/config_1.cfg");
cfg.loadConfig("./configtest/config_2.cfg");
Susi::Util::Any conf = cfg.getConfig();
EXPECT_TRUE(cfg.get("foo").isString());
EXPECT_EQ("\"bar\"",cfg.get("foo").toString());
EXPECT_TRUE(cfg.get("john").isString());
EXPECT_EQ("\"doe\"",cfg.get("john").toString());
// test override
EXPECT_TRUE(cfg.get("data").isString());
EXPECT_EQ("\"test2\"",cfg.get("data").toString());
}
TEST_F(ConfigTest, LoadAllStartStop){
// make test independed from config file
class C1 : public Susi::System::Component {
public:
virtual void start() override {}
virtual void stop() override {}
};
class C2 : public C1 {};
class C3 : public C1 {};
std::string test_config = "{"
" \"c1\" : {},"
" \"c2\" : {},"
" \"c3\" : {}"
" }";
Susi::Util::Any::Object config = Susi::Util::Any::fromString(test_config);
auto manager = std::make_shared<Susi::System::ComponentManager>(config);
manager->registerComponent("c1",[](Susi::System::ComponentManager * mgr, Susi::Util::Any & config){ return std::shared_ptr<Susi::System::Component>{new C1{}};});
manager->registerComponent("c2",[](Susi::System::ComponentManager * mgr, Susi::Util::Any & config){ return std::shared_ptr<Susi::System::Component>{new C2{}};});
manager->registerComponent("c3",[](Susi::System::ComponentManager * mgr, Susi::Util::Any & config){ return std::shared_ptr<Susi::System::Component>{new C3{}};});
bool start = manager->startAll();
bool stop = manager->stopAll();
EXPECT_TRUE(start);
EXPECT_TRUE(stop);
/*
Susi::Config cfg{};
cfg.loadConfig("config.json");
std::shared_ptr<Susi::System::ComponentManager> componentManager = Susi::System::createSusiComponentManager(cfg.getConfig());
bool start = componentManager->startAll();
bool stop = componentManager->stopAll();
EXPECT_TRUE(start);
EXPECT_TRUE(stop);
*/
}<|endoftext|>
|
<commit_before>
/*
* MIT License
*
* Copyright (c) 2017 Susanow
* Copyright (c) 2017 Hiroki SHIROKURA
*
* 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 <assert.h>
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <slankdev/string.h>
#include <slankdev/exception.h>
#include <slankdev/util.h>
#include <exception>
#include <ssn_port_stat.h>
#include <ssn_ma_port.h>
#include <ssn_ma_ring.h>
#include <ssn_thread.h>
#include <ssn_cpu.h>
#include <ssn_port.h>
#include <ssn_common.h>
#include <ssn_log.h>
#include <dpdk/dpdk.h>
#include <slankdev/vector.h>
#include <ssn_vnf_port.h>
#include <ssn_vnf_vcore.h>
#include <ssn_vnf_block.h>
#include <ssn_vnf.h>
size_t ssn_vnf::n_ports() const { return ports.size(); }
size_t ssn_vnf::n_blocks() const { return blocks.size(); }
const ssn_vnf_block* ssn_vnf::get_block(size_t bid) const { return blocks.at(bid); }
const ssn_vnf_port* ssn_vnf::get_port(size_t pid) const { return ports.at(pid); }
void ssn_vnf::configre_acc()
{
size_t n_ports = ports.size();
for (size_t i=0; i<n_ports; i++) {
ports.at(i)->config_acc();
}
}
bool ssn_vnf::deployable() const
{
/*
* Condition
* - port is attached
* - all coremask is set
*/
/*
* check ports
*/
size_t n_port = ports.size();
for (size_t i=0; i<n_port; i++) {
if (ports[i] == nullptr) return false;
}
/*
* check coremask
*/
size_t n_block = n_blocks();
for (size_t i=0; i<n_block; i++) {
if (blocks[i]->get_coremask() == 0) return false;
}
return true;
}
int ssn_vnf::reset()
{
/*
* Reset coremask
*/
const size_t n_ele = blocks.size();
for (size_t i=0; i<n_ele; i++) {
blocks.at(i)->reset();
set_coremask(i, 0x00);
}
/*
* Reset all port accessor
*/
const size_t n_port = ports.size();
for (size_t i=0; i<n_port; i++) {
if (!ports.at(i)) return -1;
}
for (size_t i=0; i<n_port; i++) {
ports.at(i)->reset_acc();
}
return 0;
}
ssn_vnf::ssn_vnf(size_t nport, const char* n) : ports(nport), name(n)
{
const size_t n_ele = ports.size();
for (size_t i=0; i<n_ele; i++) {
ports.at(i) = nullptr;
}
}
uint32_t ssn_vnf::get_coremask(size_t bid) const
{
return blocks.at(bid)->get_coremask();
}
uint32_t ssn_vnf::get_coremask() const
{
uint32_t coremask = 0;
const size_t n_ele = n_blocks();
for (size_t i=0; i<n_ele; i++) {
coremask |= blocks.at(i)->get_coremask();
}
return coremask;
}
int ssn_vnf::set_coremask(size_t block_id, uint32_t cmask)
{
const size_t n_port = ports.size();
for (size_t i=0; i<n_port; i++) {
if (!ports.at(i)) return -1;
}
blocks.at(block_id)->set_coremask(cmask);
return 0;
}
bool ssn_vnf::is_deletable() const
{
const size_t n_ele = ports.size();
for (size_t i=0; i<n_ele; i++) {
if (ports.at(i) != nullptr) {
return false;
}
}
return true;
}
void ssn_vnf::debug_dump(FILE* fp) const
{
using std::string;
fprintf(fp, "\r\n");
fprintf(fp, " + name: \"%s\" \r\n", name.c_str());
fprintf(fp, " + ports\r\n");
size_t n = ports.size();
for (size_t i=0; i<n; i++) {
auto* port = ports.at(i);
if (port) {
string name = port->name;
size_t orx = port->get_outer_rx_perf();
size_t irx = port->get_inner_rx_perf();
double r = port->get_perf_reduction();
printf(" port[%zd]: name=%s orx=%zd irx=%zd red=%lf\n",
i, name.c_str(), orx, irx, r);
} else {
printf(" port[%zd]: null\n", i);
}
}
fprintf(fp, "\r\n");
}
int ssn_vnf::deploy()
{
const size_t n_port = ports.size();
for (size_t i=0; i<n_port; i++) {
if (!ports.at(i)) {
// TODO: return with Error Code
// printf("port not attached pid=%zd\n", i);
return -1;
}
if (!ports.at(i)->deployable()) return -1;
}
configre_acc();
auto n_impl = blocks.size();
for (size_t i=0; i<n_impl; i++) {
int ret = this->blocks.at(i)->deploy();
if (ret < 0) {
// TODO: return with Error Code
// printf("block deploy miss bid=%zd\n", i);
return -1;
}
}
return 0;
}
void ssn_vnf::undeploy()
{
auto n_impl = blocks.size();
for (size_t i=0; i<n_impl; i++) {
this->blocks.at(i)->undeploy();
}
}
void ssn_vnf::update_stats()
{
auto np = ports.size();
for (size_t i=0; i<np; i++) {
this->ports.at(i)->stats_update_per1sec();
}
}
bool ssn_vnf::is_running() const
{
auto nb = n_blocks();
for (size_t i=0; i<nb; i++) {
if (!blocks.at(i)->is_running()) return false;
}
return true;
}
int ssn_vnf::attach_port(size_t pid, ssn_vnf_port* port)
{
if (ports.at(pid)) {
/* my-port was already attached */
return -1;
}
if (port->is_attached_vnf()) {
/* port has attached vnf */
return -1;
}
ports.at(pid) = port;
port->attach_vnf(this);
auto n = blocks.size();
for (size_t i=0; i<n; i++) {
blocks.at(i)->attach_port(pid, port);
}
return 0;
}
int ssn_vnf::dettach_port(size_t pid)
{
if (!ports.at(pid)) {
/* unattached port yet */
return -1;
}
ports.at(pid)->dettach_vnf();
ports.at(pid) = nullptr;
auto n = blocks.size();
for (size_t i=0; i<n; i++) {
blocks.at(i)->dettach_port(pid);
}
return 0;
}
double ssn_vnf::get_perf_reduction() const
{
double pr = 0.0;
const size_t n_port = ports.size();
for (size_t i=0; i<n_port; i++) {
if (ports.at(i) == nullptr) {
return 1.0;
}
pr += ports.at(i)->get_perf_reduction();
}
return pr/n_port;
}
size_t ssn_vnf::get_rx_rate() const
{
size_t sum = 0;
const size_t n_port = ports.size();
for (size_t i=0; i<n_port; i++) {
if (!ports.at(i)) return 0;
sum += ports.at(i)->get_outer_rx_perf();
}
return sum;
}
<commit_msg>2017.12.13-07:27<commit_after>
/*
* MIT License
*
* Copyright (c) 2017 Susanow
* Copyright (c) 2017 Hiroki SHIROKURA
*
* 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 <assert.h>
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <slankdev/string.h>
#include <slankdev/exception.h>
#include <slankdev/util.h>
#include <exception>
#include <ssn_port_stat.h>
#include <ssn_ma_port.h>
#include <ssn_ma_ring.h>
#include <ssn_thread.h>
#include <ssn_cpu.h>
#include <ssn_port.h>
#include <ssn_common.h>
#include <ssn_log.h>
#include <dpdk/dpdk.h>
#include <slankdev/vector.h>
#include <ssn_vnf_port.h>
#include <ssn_vnf_vcore.h>
#include <ssn_vnf_block.h>
#include <ssn_vnf.h>
size_t ssn_vnf::n_ports() const { return ports.size(); }
size_t ssn_vnf::n_blocks() const { return blocks.size(); }
const ssn_vnf_block* ssn_vnf::get_block(size_t bid) const { return blocks.at(bid); }
const ssn_vnf_port* ssn_vnf::get_port(size_t pid) const { return ports.at(pid); }
void ssn_vnf::configre_acc()
{
size_t n_ports = ports.size();
for (size_t i=0; i<n_ports; i++) {
ports.at(i)->config_acc();
}
}
bool ssn_vnf::deployable() const
{
/*
* Condition
* - port is attached
* - all coremask is set
*/
/*
* check ports
*/
size_t n_port = ports.size();
for (size_t i=0; i<n_port; i++) {
if (ports[i] == nullptr) return false;
}
/*
* check coremask
*/
size_t n_block = n_blocks();
for (size_t i=0; i<n_block; i++) {
if (blocks[i]->get_coremask() == 0) return false;
}
return true;
}
int ssn_vnf::reset()
{
/*
* Reset coremask
*/
const size_t n_ele = blocks.size();
for (size_t i=0; i<n_ele; i++) {
blocks.at(i)->reset();
set_coremask(i, 0x00);
}
/*
* Reset all port accessor
*/
const size_t n_port = ports.size();
for (size_t i=0; i<n_port; i++) {
if (!ports.at(i)) return -1;
}
for (size_t i=0; i<n_port; i++) {
ports.at(i)->reset_acc();
}
return 0;
}
ssn_vnf::ssn_vnf(size_t nport, const char* n) : ports(nport), name(n)
{
const size_t n_ele = ports.size();
for (size_t i=0; i<n_ele; i++) {
ports.at(i) = nullptr;
}
}
uint32_t ssn_vnf::get_coremask(size_t bid) const
{
return blocks.at(bid)->get_coremask();
}
uint32_t ssn_vnf::get_coremask() const
{
uint32_t coremask = 0;
const size_t n_ele = n_blocks();
for (size_t i=0; i<n_ele; i++) {
coremask |= blocks.at(i)->get_coremask();
}
return coremask;
}
int ssn_vnf::set_coremask(size_t block_id, uint32_t cmask)
{
const size_t n_port = ports.size();
for (size_t i=0; i<n_port; i++) {
if (!ports.at(i)) return -1;
}
blocks.at(block_id)->set_coremask(cmask);
return 0;
}
bool ssn_vnf::is_deletable() const
{
const size_t n_ele = ports.size();
for (size_t i=0; i<n_ele; i++) {
if (ports.at(i) != nullptr) {
return false;
}
}
return true;
}
void ssn_vnf::debug_dump(FILE* fp) const
{
using std::string;
fprintf(fp, "\r\n");
fprintf(fp, " + name: \"%s\" \r\n", name.c_str());
fprintf(fp, " + ports\r\n");
size_t n = ports.size();
for (size_t i=0; i<n; i++) {
auto* port = ports.at(i);
if (port) {
string name = port->name;
size_t orx = port->get_outer_rx_perf();
size_t irx = port->get_inner_rx_perf();
double r = port->get_perf_reduction();
printf(" port[%zd]: name=%s orx=%zd irx=%zd red=%lf\n",
i, name.c_str(), orx, irx, r);
} else {
printf(" port[%zd]: null\n", i);
}
}
fprintf(fp, "\r\n");
}
int ssn_vnf::deploy()
{
const size_t n_port = ports.size();
for (size_t i=0; i<n_port; i++) {
if (!ports.at(i)) {
// TODO: return with Error Code
// printf("port not attached pid=%zd\n", i);
return -1;
}
if (!ports.at(i)->deployable()) return -1;
}
configre_acc();
auto n_impl = blocks.size();
for (size_t i=0; i<n_impl; i++) {
int ret = this->blocks.at(i)->deploy();
if (ret < 0) {
// TODO: return with Error Code
// printf("block deploy miss bid=%zd\n", i);
return -1;
}
}
return 0;
}
void ssn_vnf::undeploy()
{
auto n_impl = blocks.size();
for (size_t i=0; i<n_impl; i++) {
this->blocks.at(i)->undeploy();
}
}
void ssn_vnf::update_stats()
{
auto np = ports.size();
for (size_t i=0; i<np; i++) {
this->ports.at(i)->stats_update_per1sec();
}
}
bool ssn_vnf::is_running() const
{
auto nb = n_blocks();
for (size_t i=0; i<nb; i++) {
if (!blocks.at(i)->is_running()) return false;
}
return true;
}
int ssn_vnf::attach_port(size_t pid, ssn_vnf_port* port)
{
if (ports.at(pid)) {
/* my-port was already attached */
return -1;
}
if (port->is_attached_vnf()) {
/* port has attached vnf */
return -1;
}
ports.at(pid) = port;
port->attach_vnf(this);
auto n = blocks.size();
for (size_t i=0; i<n; i++) {
blocks.at(i)->attach_port(pid, port);
}
return 0;
}
int ssn_vnf::dettach_port(size_t pid)
{
if (!ports.at(pid)) {
/* unattached port yet */
return -1;
}
ports.at(pid)->dettach_vnf();
ports.at(pid) = nullptr;
auto n = blocks.size();
for (size_t i=0; i<n; i++) {
blocks.at(i)->dettach_port(pid);
}
return 0;
}
double ssn_vnf::get_perf_reduction() const
{
double pr = 0.0;
const size_t n_port = ports.size();
for (size_t i=0; i<n_port; i++) {
if (ports.at(i) == nullptr) {
return 1.0;
}
pr += ports.at(i)->get_perf_reduction();
}
double ret = pr/n_port;
if (ret > 1) ret = 1;
return ret;
}
size_t ssn_vnf::get_rx_rate() const
{
size_t sum = 0;
const size_t n_port = ports.size();
for (size_t i=0; i<n_port; i++) {
if (!ports.at(i)) return 0;
sum += ports.at(i)->get_outer_rx_perf();
}
return sum;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2010 Aldo J. Nunez
Licensed under the Apache License, Version 2.0.
See the LICENSE text file for details.
*/
#include "Common.h"
#include "Config.h"
#include "MagoNatDE_i.h"
#include "../MagoNatEE/Common.h"
#define MAGO_SUBKEY L"SOFTWARE\\MagoDebugger"
// {B9D303A5-4EC7-4444-A7F8-6BFA4C7977EF}
static const GUID gGuidDLang =
{ 0xb9d303a5, 0x4ec7, 0x4444, { 0xa7, 0xf8, 0x6b, 0xfa, 0x4c, 0x79, 0x77, 0xef } };
// {3B476D35-A401-11D2-AAD4-00C04F990171}
static const GUID gGuidWin32ExceptionType =
{ 0x3B476D35, 0xA401, 0x11D2, { 0xAA, 0xD4, 0x00, 0xC0, 0x4F, 0x99, 0x01, 0x71 } };
static const wchar_t* gStrings[] =
{
NULL,
L"No symbols have been loaded for this document.",
L"No executable code is associated with this line.",
L"This is an invalid address.",
L"CPU",
L"CPU Segments",
L"Floating Point",
L"Flags",
L"MMX",
L"SSE",
L"SSE2",
L"Line",
L"bytes",
L"%1$s has triggered a breakpoint.",
L"First-chance exception: %1$s",
L"Unhandled exception: %1$s",
};
const GUID& GetEngineId()
{
return __uuidof( MagoNativeEngine );
}
const wchar_t* GetEngineName()
{
return L"Mago Native";
}
const GUID& GetDLanguageId()
{
return gGuidDLang;
}
const GUID& GetDExceptionType()
{
// we use the engine ID as the guid type for D exceptions
return __uuidof( MagoNativeEngine );
}
const GUID& GetWin32ExceptionType()
{
return gGuidWin32ExceptionType;
}
const wchar_t* GetRootDExceptionName()
{
return L"D Exceptions";
}
const wchar_t* GetRootWin32ExceptionName()
{
return L"Win32 Exceptions";
}
const wchar_t* GetString( DWORD strId )
{
if ( strId >= _countof( gStrings ) )
return NULL;
return gStrings[strId];
}
bool GetString( DWORD strId, CString& str )
{
const wchar_t* s = GetString( strId );
if ( s == NULL )
return false;
str = s;
return true;
}
LSTATUS OpenRootRegKey( bool user, bool readWrite, HKEY& hKey )
{
REGSAM samDesired = readWrite ? (KEY_READ | KEY_WRITE) : KEY_READ;
HKEY hive = user ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE;
return RegOpenKeyEx( hive, MAGO_SUBKEY, 0, samDesired, &hKey );
}
LSTATUS GetRegString( HKEY hKey, const wchar_t* valueName, wchar_t* charBuf, int& charLen )
{
if ( charBuf == NULL || charLen < 0 )
return ERROR_INVALID_PARAMETER;
DWORD regType = 0;
DWORD bufLen = charLen * sizeof( wchar_t );
DWORD bytesRead= bufLen;
LSTATUS ret = 0;
ret = RegQueryValueEx(
hKey,
valueName,
NULL,
®Type,
(BYTE*) charBuf,
&bytesRead );
if ( ret != ERROR_SUCCESS )
return ret;
if ( regType != REG_SZ || (bytesRead % sizeof( wchar_t )) != 0 )
return ERROR_UNSUPPORTED_TYPE;
int charsRead = bytesRead / sizeof( wchar_t );
if ( charsRead == 0 || charBuf[charsRead - 1] != L'\0' )
{
// there's no more room to add a null
if ( charsRead == charLen )
return ERROR_MORE_DATA;
charBuf[charsRead] = L'\0';
charLen = charsRead + 1;
}
else
{
// the string we read already ends in null
charLen = charsRead;
}
return ERROR_SUCCESS;
}
LSTATUS GetRegValue( HKEY hKey, const wchar_t* valueName, DWORD* pValue )
{
if ( pValue == NULL )
return ERROR_INVALID_PARAMETER;
DWORD regType = 0;
DWORD bytesRead = sizeof( *pValue );
LSTATUS ret = 0;
ret = RegQueryValueEx(
hKey,
valueName,
NULL,
®Type,
(BYTE*) pValue,
&bytesRead );
if ( ret != ERROR_SUCCESS )
return ret;
if ( regType != REG_DWORD )
return ERROR_UNSUPPORTED_TYPE;
return ERROR_SUCCESS;
}
MagoOptions gOptions;
bool readMagoOptions()
{
HKEY hKey;
LSTATUS hr = OpenRootRegKey( true, false, hKey );
if( hr != S_OK )
return false;
DWORD val;
if ( GetRegValue( hKey, L"hideInternalNames", &val ) == S_OK )
gOptions.hideInternalNames = val != 0;
else
gOptions.hideInternalNames = false;
if ( GetRegValue( hKey, L"showStaticsInAggr", &val ) == S_OK )
gOptions.showStaticsInAggr = val != 0;
else
gOptions.showStaticsInAggr = false;
if ( GetRegValue( hKey, L"showVTable", &val ) == S_OK )
gOptions.showVTable = val != 0;
else
gOptions.showVTable = true;
if ( GetRegValue( hKey, L"flatClassFields", &val ) == S_OK )
gOptions.flatClassFields = val != 0;
else
gOptions.flatClassFields = false;
if ( GetRegValue( hKey, L"expandableStrings", &val ) == S_OK )
gOptions.expandableStrings = val != 0;
else
gOptions.expandableStrings = false;
if ( GetRegValue( hKey, L"hideReferencePointers", &val ) == S_OK )
gOptions.hideReferencePointers = val != 0;
else
gOptions.hideReferencePointers = true;
if ( GetRegValue( hKey, L"removeLeadingHexZeroes", &val ) == S_OK )
gOptions.removeLeadingHexZeroes = val != 0;
else
gOptions.removeLeadingHexZeroes = false;
if ( GetRegValue( hKey, L"recombineTuples", &val ) == S_OK )
gOptions.recombineTuples = val != 0;
else
gOptions.recombineTuples = true;
if (GetRegValue(hKey, L"maxArrayElements", &val) == S_OK)
gOptions.maxArrayElements = val;
else
gOptions.maxArrayElements = 1000;
if (GetRegValue(hKey, L"showDArrayLengthInType", &val) == S_OK)
gOptions.showDArrayLengthInType = val != 0;
else
gOptions.showDArrayLengthInType = false;
if (GetRegValue(hKey, L"callDebuggerFunctions", &val) == S_OK)
gOptions.callDebuggerFunctions = val != 0;
else
gOptions.callDebuggerFunctions = true;
if (GetRegValue(hKey, L"callDebuggerRanges", &val) == S_OK)
gOptions.callDebuggerRanges = val != 0;
else
gOptions.callDebuggerRanges = true;
if (GetRegValue(hKey, L"callDebuggerUseMagoGC", &val) == S_OK)
gOptions.callDebuggerUseMagoGC = val != 0;
else
gOptions.callDebuggerUseMagoGC = true;
MagoEE::gShowVTable = gOptions.showVTable;
MagoEE::gMaxArrayLength = gOptions.maxArrayElements;
MagoEE::gHideReferencePointers = gOptions.hideReferencePointers;
MagoEE::gRemoveLeadingHexZeroes = gOptions.removeLeadingHexZeroes;
MagoEE::gRecombineTuples = gOptions.recombineTuples;
MagoEE::gShowDArrayLengthInType = gOptions.showDArrayLengthInType;
MagoEE::gCallDebuggerFunctions = gOptions.callDebuggerFunctions;
MagoEE::gCallDebuggerRanges = gOptions.callDebuggerRanges;
MagoEE::gCallDebuggerUseMagoGC = gOptions.callDebuggerUseMagoGC;
RegCloseKey( hKey );
return true;
}
static bool initMagoOption = readMagoOptions();
<commit_msg>change default to evaluate ranges to "off"<commit_after>/*
Copyright (c) 2010 Aldo J. Nunez
Licensed under the Apache License, Version 2.0.
See the LICENSE text file for details.
*/
#include "Common.h"
#include "Config.h"
#include "MagoNatDE_i.h"
#include "../MagoNatEE/Common.h"
#define MAGO_SUBKEY L"SOFTWARE\\MagoDebugger"
// {B9D303A5-4EC7-4444-A7F8-6BFA4C7977EF}
static const GUID gGuidDLang =
{ 0xb9d303a5, 0x4ec7, 0x4444, { 0xa7, 0xf8, 0x6b, 0xfa, 0x4c, 0x79, 0x77, 0xef } };
// {3B476D35-A401-11D2-AAD4-00C04F990171}
static const GUID gGuidWin32ExceptionType =
{ 0x3B476D35, 0xA401, 0x11D2, { 0xAA, 0xD4, 0x00, 0xC0, 0x4F, 0x99, 0x01, 0x71 } };
static const wchar_t* gStrings[] =
{
NULL,
L"No symbols have been loaded for this document.",
L"No executable code is associated with this line.",
L"This is an invalid address.",
L"CPU",
L"CPU Segments",
L"Floating Point",
L"Flags",
L"MMX",
L"SSE",
L"SSE2",
L"Line",
L"bytes",
L"%1$s has triggered a breakpoint.",
L"First-chance exception: %1$s",
L"Unhandled exception: %1$s",
};
const GUID& GetEngineId()
{
return __uuidof( MagoNativeEngine );
}
const wchar_t* GetEngineName()
{
return L"Mago Native";
}
const GUID& GetDLanguageId()
{
return gGuidDLang;
}
const GUID& GetDExceptionType()
{
// we use the engine ID as the guid type for D exceptions
return __uuidof( MagoNativeEngine );
}
const GUID& GetWin32ExceptionType()
{
return gGuidWin32ExceptionType;
}
const wchar_t* GetRootDExceptionName()
{
return L"D Exceptions";
}
const wchar_t* GetRootWin32ExceptionName()
{
return L"Win32 Exceptions";
}
const wchar_t* GetString( DWORD strId )
{
if ( strId >= _countof( gStrings ) )
return NULL;
return gStrings[strId];
}
bool GetString( DWORD strId, CString& str )
{
const wchar_t* s = GetString( strId );
if ( s == NULL )
return false;
str = s;
return true;
}
LSTATUS OpenRootRegKey( bool user, bool readWrite, HKEY& hKey )
{
REGSAM samDesired = readWrite ? (KEY_READ | KEY_WRITE) : KEY_READ;
HKEY hive = user ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE;
return RegOpenKeyEx( hive, MAGO_SUBKEY, 0, samDesired, &hKey );
}
LSTATUS GetRegString( HKEY hKey, const wchar_t* valueName, wchar_t* charBuf, int& charLen )
{
if ( charBuf == NULL || charLen < 0 )
return ERROR_INVALID_PARAMETER;
DWORD regType = 0;
DWORD bufLen = charLen * sizeof( wchar_t );
DWORD bytesRead= bufLen;
LSTATUS ret = 0;
ret = RegQueryValueEx(
hKey,
valueName,
NULL,
®Type,
(BYTE*) charBuf,
&bytesRead );
if ( ret != ERROR_SUCCESS )
return ret;
if ( regType != REG_SZ || (bytesRead % sizeof( wchar_t )) != 0 )
return ERROR_UNSUPPORTED_TYPE;
int charsRead = bytesRead / sizeof( wchar_t );
if ( charsRead == 0 || charBuf[charsRead - 1] != L'\0' )
{
// there's no more room to add a null
if ( charsRead == charLen )
return ERROR_MORE_DATA;
charBuf[charsRead] = L'\0';
charLen = charsRead + 1;
}
else
{
// the string we read already ends in null
charLen = charsRead;
}
return ERROR_SUCCESS;
}
LSTATUS GetRegValue( HKEY hKey, const wchar_t* valueName, DWORD* pValue )
{
if ( pValue == NULL )
return ERROR_INVALID_PARAMETER;
DWORD regType = 0;
DWORD bytesRead = sizeof( *pValue );
LSTATUS ret = 0;
ret = RegQueryValueEx(
hKey,
valueName,
NULL,
®Type,
(BYTE*) pValue,
&bytesRead );
if ( ret != ERROR_SUCCESS )
return ret;
if ( regType != REG_DWORD )
return ERROR_UNSUPPORTED_TYPE;
return ERROR_SUCCESS;
}
MagoOptions gOptions;
bool readMagoOptions()
{
HKEY hKey;
LSTATUS hr = OpenRootRegKey( true, false, hKey );
if( hr != S_OK )
return false;
DWORD val;
if ( GetRegValue( hKey, L"hideInternalNames", &val ) == S_OK )
gOptions.hideInternalNames = val != 0;
else
gOptions.hideInternalNames = false;
if ( GetRegValue( hKey, L"showStaticsInAggr", &val ) == S_OK )
gOptions.showStaticsInAggr = val != 0;
else
gOptions.showStaticsInAggr = false;
if ( GetRegValue( hKey, L"showVTable", &val ) == S_OK )
gOptions.showVTable = val != 0;
else
gOptions.showVTable = true;
if ( GetRegValue( hKey, L"flatClassFields", &val ) == S_OK )
gOptions.flatClassFields = val != 0;
else
gOptions.flatClassFields = false;
if ( GetRegValue( hKey, L"expandableStrings", &val ) == S_OK )
gOptions.expandableStrings = val != 0;
else
gOptions.expandableStrings = false;
if ( GetRegValue( hKey, L"hideReferencePointers", &val ) == S_OK )
gOptions.hideReferencePointers = val != 0;
else
gOptions.hideReferencePointers = true;
if ( GetRegValue( hKey, L"removeLeadingHexZeroes", &val ) == S_OK )
gOptions.removeLeadingHexZeroes = val != 0;
else
gOptions.removeLeadingHexZeroes = false;
if ( GetRegValue( hKey, L"recombineTuples", &val ) == S_OK )
gOptions.recombineTuples = val != 0;
else
gOptions.recombineTuples = true;
if (GetRegValue(hKey, L"maxArrayElements", &val) == S_OK)
gOptions.maxArrayElements = val;
else
gOptions.maxArrayElements = 1000;
if (GetRegValue(hKey, L"showDArrayLengthInType", &val) == S_OK)
gOptions.showDArrayLengthInType = val != 0;
else
gOptions.showDArrayLengthInType = false;
if (GetRegValue(hKey, L"callDebuggerFunctions", &val) == S_OK)
gOptions.callDebuggerFunctions = val != 0;
else
gOptions.callDebuggerFunctions = true;
if (GetRegValue(hKey, L"callDebuggerRanges", &val) == S_OK)
gOptions.callDebuggerRanges = val != 0;
else
gOptions.callDebuggerRanges = false;
if (GetRegValue(hKey, L"callDebuggerUseMagoGC", &val) == S_OK)
gOptions.callDebuggerUseMagoGC = val != 0;
else
gOptions.callDebuggerUseMagoGC = true;
MagoEE::gShowVTable = gOptions.showVTable;
MagoEE::gMaxArrayLength = gOptions.maxArrayElements;
MagoEE::gHideReferencePointers = gOptions.hideReferencePointers;
MagoEE::gRemoveLeadingHexZeroes = gOptions.removeLeadingHexZeroes;
MagoEE::gRecombineTuples = gOptions.recombineTuples;
MagoEE::gShowDArrayLengthInType = gOptions.showDArrayLengthInType;
MagoEE::gCallDebuggerFunctions = gOptions.callDebuggerFunctions;
MagoEE::gCallDebuggerRanges = gOptions.callDebuggerRanges;
MagoEE::gCallDebuggerUseMagoGC = gOptions.callDebuggerUseMagoGC;
RegCloseKey( hKey );
return true;
}
static bool initMagoOption = readMagoOptions();
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
// -------------------- OpenMesh
#include <OpenMesh/Core/IO/MeshIO.hh>
#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>
#ifndef DOXY_IGNORE_THIS
struct MyTraits : public OpenMesh::DefaultTraits
{
// store barycenter of neighbors in this member
VertexTraits
{
private:
Point cog_;
public:
VertexT() : cog_( Point(0.0f, 0.0f, 0.0f ) ) { }
const Point& cog() const { return cog_; }
void set_cog(const Point& _p) { cog_ = _p; }
};
};
#endif
typedef OpenMesh::TriMesh_ArrayKernelT<MyTraits> MyMesh;
typedef OpenMesh::TriMesh_ArrayKernelT<> MyMesh2;
// ---------------------------------------------------------------------------
#define SIZEOF( entity,b ) \
std::cout << _prefix << "size of " << #entity << ": " \
<< sizeof( entity ) << std::endl; \
b += sizeof( entity )
template <typename Mesh>
void print_size(const std::string& _prefix = "")
{
size_t total=0;
SIZEOF(Mesh::Vertex, total);
SIZEOF(Mesh::Halfedge, total);
SIZEOF(Mesh::Edge, total);
SIZEOF(Mesh::Face, total);
std::cout << _prefix << "total: " << total << std::endl;
}
#undef SIZEOF
// ---------------------------------------------------------------------------
int main(int argc, char **argv)
{
MyMesh mesh;
// check command line options
if (argc < 4 || argc > 5)
{
std::cerr << "Usage: " << argv[0] << " [-s] #iterations infile outfile\n";
exit(1);
}
int idx=2;
// display size of entities of the enhanced and the default mesh type
// when commandline option '-s' has been used.
if (argc == 5)
{
if (std::string("-s")==argv[idx-1])
{
std::cout << "Enhanced mesh size statistics\n";
print_size<MyMesh>(" ");
std::cout << "Default mesh size statistics\n";
print_size<MyMesh2>(" ");
}
// else ignore!
++idx;
}
// read mesh from stdin
std::cout<< " Input mesh: " << argv[idx] << std::endl;
if ( ! OpenMesh::IO::read_mesh(mesh, argv[idx]) )
{
std::cerr << "Error: Cannot read mesh from " << argv[idx] << std::endl;
return 0;
}
// smoothing mesh argv[1] times
MyMesh::VertexIter v_it, v_end(mesh.vertices_end());
MyMesh::VertexVertexIter vv_it;
MyMesh::Point cog;
MyMesh::Scalar valence;
unsigned int i, N(atoi(argv[idx-1]));
std::cout<< "Smooth mesh " << N << " times\n";
for (i=0; i < N; ++i)
{
for (v_it=mesh.vertices_begin(); v_it!=v_end; ++v_it)
{
cog[0] = cog[1] = cog[2] = valence = 0.0;
for (vv_it=mesh.vv_iter(v_it.handle()); vv_it; ++vv_it)
{
cog += mesh.point( vv_it.handle() );
++valence;
}
v_it->set_cog(cog / valence);
}
for (v_it=mesh.vertices_begin(); v_it!=v_end; ++v_it)
if (!mesh.is_boundary(v_it.handle()))
mesh.set_point( v_it.handle(), v_it->cog());
}
// write mesh to stdout
std::cout<< "Output mesh: " << argv[idx+1] << std::endl;
if ( ! OpenMesh::IO::write_mesh(mesh, argv[idx+1]) )
{
std::cerr << "Error: cannot write mesh to " << argv[idx+1] << std::endl;
return 0;
}
return 1;
}
<commit_msg>Updated tutorial 07 on traits.<commit_after>#include <iostream>
#include <vector>
// -------------------- OpenMesh
#include <OpenMesh/Core/IO/MeshIO.hh>
#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>
#include <OpenMesh/Core/Mesh/Traits.hh>
struct MyTraits : public OpenMesh::DefaultTraits
{
// store barycenter of neighbors in this member
VertexTraits
{
private:
Point cog_;
public:
VertexT() : cog_( Point(0.0f, 0.0f, 0.0f ) ) { }
const Point& cog() const { return cog_; }
void set_cog(const Point& _p) { cog_ = _p; }
};
};
typedef OpenMesh::TriMesh_ArrayKernelT<MyTraits> MyMesh;
typedef OpenMesh::TriMesh_ArrayKernelT<> MyMesh2;
// ---------------------------------------------------------------------------
#define SIZEOF( entity,b ) \
std::cout << _prefix << "size of " << #entity << ": " \
<< sizeof( entity ) << std::endl; \
b += sizeof( entity )
template <typename Mesh>
void print_size(const std::string& _prefix = "")
{
size_t total=0;
SIZEOF(typename Mesh::Vertex, total);
SIZEOF(typename Mesh::Halfedge, total);
SIZEOF(typename Mesh::Edge, total);
SIZEOF(typename Mesh::Face, total);
std::cout << _prefix << "total: " << total << std::endl;
}
#undef SIZEOF
// ---------------------------------------------------------------------------
int main(int argc, char **argv)
{
MyMesh mesh;
// check command line options
if (argc < 4 || argc > 5)
{
std::cerr << "Usage: " << argv[0] << " [-s] #iterations infile outfile\n";
exit(1);
}
int idx=2;
// display size of entities of the enhanced and the default mesh type
// when commandline option '-s' has been used.
if (argc == 5)
{
if (std::string("-s")==argv[idx-1])
{
std::cout << "Enhanced mesh size statistics\n";
print_size<MyMesh>(" ");
std::cout << "Default mesh size statistics\n";
print_size<MyMesh2>(" ");
}
// else ignore!
++idx;
}
// read mesh from stdin
std::cout<< " Input mesh: " << argv[idx] << std::endl;
if ( ! OpenMesh::IO::read_mesh(mesh, argv[idx]) )
{
std::cerr << "Error: Cannot read mesh from " << argv[idx] << std::endl;
return 0;
}
// smoothing mesh argv[1] times
MyMesh::VertexIter v_it, v_end(mesh.vertices_end());
MyMesh::VertexVertexIter vv_it;
MyMesh::Point cog;
MyMesh::Scalar valence;
unsigned int i, N(atoi(argv[idx-1]));
std::cout<< "Smooth mesh " << N << " times\n";
for (i=0; i < N; ++i)
{
for (v_it=mesh.vertices_begin(); v_it!=v_end; ++v_it)
{
cog[0] = cog[1] = cog[2] = valence = 0.0;
for (vv_it=mesh.vv_iter(v_it.handle()); vv_it; ++vv_it)
{
cog += mesh.point( vv_it.handle() );
++valence;
}
mesh.data(v_it).set_cog(cog / valence);
}
for (v_it=mesh.vertices_begin(); v_it!=v_end; ++v_it)
if (!mesh.is_boundary(v_it.handle()))
mesh.set_point( v_it.handle(), mesh.data(v_it).cog());
}
// write mesh to stdout
std::cout<< "Output mesh: " << argv[idx+1] << std::endl;
if ( ! OpenMesh::IO::write_mesh(mesh, argv[idx+1]) )
{
std::cerr << "Error: cannot write mesh to " << argv[idx+1] << std::endl;
return 0;
}
return 1;
}
<|endoftext|>
|
<commit_before>#include "selectformaction.h"
#include <cassert>
#include <sstream>
#include "config.h"
#include "fmtstrformatter.h"
#include "listformatter.h"
#include "strprintf.h"
#include "utils.h"
#include "view.h"
namespace newsboat {
/*
* The SelectFormAction is used both for the "select tag" dialog
* and the "select filter", as they do practically the same. That's
* why there is the decision between SELECTTAG and SELECTFILTER on
* a few places.
*/
SelectFormAction::SelectFormAction(View* vv,
std::string formstr,
ConfigContainer* cfg)
: FormAction(vv, formstr, cfg)
, quit(false)
, type(SelectionType::TAG)
{
}
SelectFormAction::~SelectFormAction() {}
void SelectFormAction::handle_cmdline(const std::string& cmd)
{
unsigned int idx = 0;
if (1 == sscanf(cmd.c_str(), "%u", &idx)) {
if (idx > 0 &&
idx <= ((type == SelectionType::TAG)
? tags.size()
: filters.size())) {
f->set("tagpos", std::to_string(idx - 1));
}
} else {
FormAction::handle_cmdline(cmd);
}
}
void SelectFormAction::process_operation(Operation op,
bool /* automatic */,
std::vector<std::string>* /* args */)
{
bool hardquit = false;
switch (op) {
case OP_QUIT:
value = "";
quit = true;
break;
case OP_HARDQUIT:
value = "";
hardquit = true;
break;
case OP_OPEN: {
std::string tagposname = f->get("tagposname");
unsigned int pos = utils::to_u(tagposname);
if (tagposname.length() > 0) {
switch (type) {
case SelectionType::TAG: {
if (pos < tags.size()) {
value = tags[pos];
quit = true;
}
} break;
case SelectionType::FILTER: {
if (pos < filters.size()) {
value = filters[pos].second;
quit = true;
}
} break;
default:
assert(0); // should never happen
}
}
} break;
default:
break;
}
if (hardquit) {
while (v->formaction_stack_size() > 0) {
v->pop_current_formaction();
}
} else if (quit) {
v->pop_current_formaction();
}
}
void SelectFormAction::prepare()
{
if (do_redraw) {
ListFormatter listfmt;
unsigned int i = 0;
std::string selecttag_format = cfg->get_configvalue("selecttag-format");
unsigned int width = utils::to_u(f->get("tags:w")); // Already defined?
switch (type) {
case SelectionType::TAG:
for (const auto& tag : tags) {
listfmt.add_line(format_line(selecttag_format,
tag,
i + 1,
width),
i);
i++;
}
break;
case SelectionType::FILTER:
for (const auto& filter : filters) {
std::string tagstr = strprintf::fmt(
"%4u %s", i + 1, filter.first);
listfmt.add_line(tagstr, i);
i++;
}
break;
default:
assert(0);
}
f->modify("taglist", "replace_inner", listfmt.format_list());
do_redraw = false;
}
}
void SelectFormAction::init()
{
std::string title;
do_redraw = true;
quit = false;
value = "";
std::string viewwidth = f->get("taglist:w");
unsigned int width = utils::to_u(viewwidth, 80);
set_keymap_hints();
FmtStrFormatter fmt;
fmt.register_fmt('N', PROGRAM_NAME);
fmt.register_fmt('V', utils::program_version());
switch (type) {
case SelectionType::TAG:
title = fmt.do_format(
cfg->get_configvalue("selecttag-title-format"), width);
break;
case SelectionType::FILTER:
title = fmt.do_format(
cfg->get_configvalue("selectfilter-title-format"),
width);
break;
default:
assert(0); // should never happen
}
f->set("head", title);
}
std::string SelectFormAction::format_line(const std::string& selecttag_format, // Referenced "FeedListFormAction::format_line".
std::string tag, // Reference used: "std::shared_ptr<RssFeed> feed".
unsigned int pos,
unsigned int width) // Defined in SelectFormAction::init() above?
{
FmtStrFormatter fmt;
/* Used names and format from "/src/reloader.cpp". */
const auto unread_feeds2 =
v->get_ctrl()->get_feedcontainer()->get_unread_feed_count_per_tag(tag);
const auto unread_articles2 =
v->get_ctrl()->get_feedcontainer()->get_unread_item_count_per_tag(tag);
fmt.register_fmt('i', strprintf::fmt("%u", pos + 1));
fmt.register_fmt('T', tag);
/* New identifiers correspond with pre-existing "notify-format" identifiers: */
fmt.register_fmt('f', std::to_string(unread_feeds2));
fmt.register_fmt('n', std::to_string(unread_articles2));
auto formattedLine = fmt.do_format(selecttag_format, width);
return formattedLine;
}
KeyMapHintEntry* SelectFormAction::get_keymap_hint()
{
static KeyMapHintEntry hints_tag[] = {{OP_QUIT, _("Cancel")},
{OP_OPEN, _("Select Tag")},
{OP_NIL, nullptr}};
static KeyMapHintEntry hints_filter[] = {{OP_QUIT, _("Cancel")},
{OP_OPEN, _("Select Filter")},
{OP_NIL, nullptr}};
switch (type) {
case SelectionType::TAG:
return hints_tag;
case SelectionType::FILTER:
return hints_filter;
}
return nullptr;
}
std::string SelectFormAction::title()
{
switch (type) {
case SelectionType::TAG:
return _("Select Tag");
case SelectionType::FILTER:
return _("Select Filter");
default:
return "";
}
}
} // namespace newsboat
<commit_msg>Remove debug comments<commit_after>#include "selectformaction.h"
#include <cassert>
#include <sstream>
#include "config.h"
#include "fmtstrformatter.h"
#include "listformatter.h"
#include "strprintf.h"
#include "utils.h"
#include "view.h"
namespace newsboat {
/*
* The SelectFormAction is used both for the "select tag" dialog
* and the "select filter", as they do practically the same. That's
* why there is the decision between SELECTTAG and SELECTFILTER on
* a few places.
*/
SelectFormAction::SelectFormAction(View* vv,
std::string formstr,
ConfigContainer* cfg)
: FormAction(vv, formstr, cfg)
, quit(false)
, type(SelectionType::TAG)
{
}
SelectFormAction::~SelectFormAction() {}
void SelectFormAction::handle_cmdline(const std::string& cmd)
{
unsigned int idx = 0;
if (1 == sscanf(cmd.c_str(), "%u", &idx)) {
if (idx > 0 &&
idx <= ((type == SelectionType::TAG)
? tags.size()
: filters.size())) {
f->set("tagpos", std::to_string(idx - 1));
}
} else {
FormAction::handle_cmdline(cmd);
}
}
void SelectFormAction::process_operation(Operation op,
bool /* automatic */,
std::vector<std::string>* /* args */)
{
bool hardquit = false;
switch (op) {
case OP_QUIT:
value = "";
quit = true;
break;
case OP_HARDQUIT:
value = "";
hardquit = true;
break;
case OP_OPEN: {
std::string tagposname = f->get("tagposname");
unsigned int pos = utils::to_u(tagposname);
if (tagposname.length() > 0) {
switch (type) {
case SelectionType::TAG: {
if (pos < tags.size()) {
value = tags[pos];
quit = true;
}
} break;
case SelectionType::FILTER: {
if (pos < filters.size()) {
value = filters[pos].second;
quit = true;
}
} break;
default:
assert(0); // should never happen
}
}
} break;
default:
break;
}
if (hardquit) {
while (v->formaction_stack_size() > 0) {
v->pop_current_formaction();
}
} else if (quit) {
v->pop_current_formaction();
}
}
void SelectFormAction::prepare()
{
if (do_redraw) {
ListFormatter listfmt;
unsigned int i = 0;
std::string selecttag_format = cfg->get_configvalue("selecttag-format");
unsigned int width = utils::to_u(f->get("tags:w"));
switch (type) {
case SelectionType::TAG:
for (const auto& tag : tags) {
listfmt.add_line(format_line(selecttag_format,
tag,
i + 1,
width),
i);
i++;
}
break;
case SelectionType::FILTER:
for (const auto& filter : filters) {
std::string tagstr = strprintf::fmt(
"%4u %s", i + 1, filter.first);
listfmt.add_line(tagstr, i);
i++;
}
break;
default:
assert(0);
}
f->modify("taglist", "replace_inner", listfmt.format_list());
do_redraw = false;
}
}
void SelectFormAction::init()
{
std::string title;
do_redraw = true;
quit = false;
value = "";
std::string viewwidth = f->get("taglist:w");
unsigned int width = utils::to_u(viewwidth, 80);
set_keymap_hints();
FmtStrFormatter fmt;
fmt.register_fmt('N', PROGRAM_NAME);
fmt.register_fmt('V', utils::program_version());
switch (type) {
case SelectionType::TAG:
title = fmt.do_format(
cfg->get_configvalue("selecttag-title-format"), width);
break;
case SelectionType::FILTER:
title = fmt.do_format(
cfg->get_configvalue("selectfilter-title-format"),
width);
break;
default:
assert(0); // should never happen
}
f->set("head", title);
}
std::string SelectFormAction::format_line(const std::string& selecttag_format,
std::string tag,
unsigned int pos,
unsigned int width)
{
FmtStrFormatter fmt;
/* Used names and format from "/src/reloader.cpp". */
const auto unread_feeds2 =
v->get_ctrl()->get_feedcontainer()->get_unread_feed_count_per_tag(tag);
const auto unread_articles2 =
v->get_ctrl()->get_feedcontainer()->get_unread_item_count_per_tag(tag);
fmt.register_fmt('i', strprintf::fmt("%u", pos + 1));
fmt.register_fmt('T', tag);
/* New identifiers correspond with pre-existing "notify-format" identifiers: */
fmt.register_fmt('f', std::to_string(unread_feeds2));
fmt.register_fmt('n', std::to_string(unread_articles2));
auto formattedLine = fmt.do_format(selecttag_format, width);
return formattedLine;
}
KeyMapHintEntry* SelectFormAction::get_keymap_hint()
{
static KeyMapHintEntry hints_tag[] = {{OP_QUIT, _("Cancel")},
{OP_OPEN, _("Select Tag")},
{OP_NIL, nullptr}};
static KeyMapHintEntry hints_filter[] = {{OP_QUIT, _("Cancel")},
{OP_OPEN, _("Select Filter")},
{OP_NIL, nullptr}};
switch (type) {
case SelectionType::TAG:
return hints_tag;
case SelectionType::FILTER:
return hints_filter;
}
return nullptr;
}
std::string SelectFormAction::title()
{
switch (type) {
case SelectionType::TAG:
return _("Select Tag");
case SelectionType::FILTER:
return _("Select Filter");
default:
return "";
}
}
} // namespace newsboat
<|endoftext|>
|
<commit_before>
#include "EthStratumClient.h"
#include <libdevcore/Log.h>
using boost::asio::ip::tcp;
EthStratumClient::EthStratumClient(GenericFarm<EthashProofOfWork> * f, MinerType m, string const & host, string const & port, string const & user, string const & pass, int const & retries, int const & worktimeout, bool const & precompute)
: m_socket(m_io_service)
{
m_minerType = m;
m_primary.host = host;
m_primary.port = port;
m_primary.user = user;
m_primary.pass = pass;
p_active = &m_primary;
m_authorized = false;
m_connected = false;
m_precompute = precompute;
m_pending = 0;
m_maxRetries = retries;
m_worktimeout = worktimeout;
p_farm = f;
p_worktimer = nullptr;
connect();
}
EthStratumClient::~EthStratumClient()
{
}
void EthStratumClient::setFailover(string const & host, string const & port)
{
setFailover(host, port, p_active->user, p_active->pass);
}
void EthStratumClient::setFailover(string const & host, string const & port, string const & user, string const & pass)
{
m_failover.host = host;
m_failover.port = port;
m_failover.user = user;
m_failover.pass = pass;
}
void EthStratumClient::connect()
{
tcp::resolver r(m_io_service);
tcp::resolver::query q(p_active->host, p_active->port);
r.async_resolve(q, boost::bind(&EthStratumClient::resolve_handler,
this, boost::asio::placeholders::error,
boost::asio::placeholders::iterator));
cnote << "Connecting to stratum server " << p_active->host + ":" + p_active->port;
boost::thread t(boost::bind(&boost::asio::io_service::run, &m_io_service));
}
#define BOOST_ASIO_ENABLE_CANCELIO
void EthStratumClient::reconnect()
{
/*
if (p_farm->isMining())
{
cnote << "Stopping farm";
p_farm->stop();
}
*/
if (p_worktimer) {
p_worktimer->cancel();
p_worktimer = nullptr;
}
m_io_service.reset();
m_socket.close();
m_authorized = false;
m_connected = false;
if (!m_failover.host.empty())
{
m_retries++;
if (m_retries > m_maxRetries)
{
if (m_failover.host == "exit") {
disconnect();
return;
}
else if (p_active == &m_primary)
{
p_active = &m_failover;
}
else {
p_active = &m_primary;
}
m_retries = 0;
}
}
cnote << "Reconnecting in 3 seconds...";
boost::asio::deadline_timer timer(m_io_service, boost::posix_time::seconds(3));
timer.wait();
connect();
}
void EthStratumClient::disconnect()
{
cnote << "Disconnecting";
m_connected = false;
m_running = false;
if (p_farm->isMining())
{
cnote << "Stopping farm";
p_farm->stop();
}
m_socket.close();
m_io_service.stop();
}
void EthStratumClient::resolve_handler(const boost::system::error_code& ec, tcp::resolver::iterator i)
{
if (!ec)
{
async_connect(m_socket, i, boost::bind(&EthStratumClient::connect_handler,
this, boost::asio::placeholders::error,
boost::asio::placeholders::iterator));
}
else
{
cerr << "Could not resolve host" << p_active->host + ":" + p_active->port + ", " << ec.message();
reconnect();
}
}
void EthStratumClient::connect_handler(const boost::system::error_code& ec, tcp::resolver::iterator i)
{
dev::setThreadName("stratum");
if (!ec)
{
m_connected = true;
cnote << "Connected to stratum server " << i->host_name() << ":" << p_active->port;
if (!p_farm->isMining())
{
cnote << "Starting farm";
if (m_minerType == MinerType::CPU)
p_farm->start("cpu");
else if (m_minerType == MinerType::CL)
p_farm->start("opencl");
else if (m_minerType == MinerType::CUDA)
p_farm->start("cuda");
}
std::ostream os(&m_requestBuffer);
os << "{\"id\": 1, \"method\": \"mining.subscribe\", \"params\": []}\n";
async_write(m_socket, m_requestBuffer,
boost::bind(&EthStratumClient::handleResponse, this,
boost::asio::placeholders::error));
}
else
{
cwarn << "Could not connect to stratum server " << p_active->host << ":" << p_active->port << ", " << ec.message();
reconnect();
}
}
void EthStratumClient::readline() {
x_pending.lock();
if (m_pending == 0) {
async_read_until(m_socket, m_responseBuffer, "\n",
boost::bind(&EthStratumClient::readResponse, this,
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
m_pending++;
}
x_pending.unlock();
}
void EthStratumClient::handleResponse(const boost::system::error_code& ec) {
if (!ec)
{
readline();
}
else
{
dev::setThreadName("stratum");
cwarn << "Handle response failed: " << ec.message();
}
}
void EthStratumClient::readResponse(const boost::system::error_code& ec, std::size_t bytes_transferred)
{
dev::setThreadName("stratum");
x_pending.lock();
m_pending = m_pending > 0 ? m_pending - 1 : 0;
x_pending.unlock();
if (!ec && bytes_transferred)
{
std::istream is(&m_responseBuffer);
std::string response;
getline(is, response);
if (response.front() == '{' && response.back() == '}')
{
Json::Value responseObject;
Json::Reader reader;
if (reader.parse(response.c_str(), responseObject))
{
processReponse(responseObject);
m_response = response;
}
else
{
cwarn << "Parse response failed: " << reader.getFormattedErrorMessages();
}
}
else
{
cwarn << "Discarding incomplete response";
}
if (m_connected)
readline();
}
else
{
cwarn << "Read response failed: " << ec.message();
if (m_connected)
reconnect();
}
}
void EthStratumClient::processReponse(Json::Value& responseObject)
{
Json::Value error = responseObject.get("error", new Json::Value);
if (error.isArray())
{
string msg = error.get(1, "Unknown error").asString();
cnote << msg;
}
std::ostream os(&m_requestBuffer);
Json::Value params;
int id = responseObject.get("id", Json::Value::null).asInt();
switch (id)
{
case 1:
cnote << "Subscribed to stratum server";
os << "{\"id\": 2, \"method\": \"mining.authorize\", \"params\": [\"" << p_active->user << "\",\"" << p_active->pass << "\"]}\n";
async_write(m_socket, m_requestBuffer,
boost::bind(&EthStratumClient::handleResponse, this,
boost::asio::placeholders::error));
break;
case 2:
m_authorized = responseObject.get("result", Json::Value::null).asBool();
if (!m_authorized)
{
cnote << "Worker not authorized:" << p_active->user;
disconnect();
return;
}
cnote << "Authorized worker " << p_active->user;
break;
case 4:
if (responseObject.get("result", false).asBool()) {
cnote << "B-) Submitted and accepted.";
p_farm->acceptedSolution(m_stale);
}
else {
cwarn << ":-( Not accepted.";
p_farm->rejectedSolution(m_stale);
}
break;
default:
string method = responseObject.get("method", "").asString();
if (method == "mining.notify")
{
params = responseObject.get("params", Json::Value::null);
if (params.isArray())
{
string job = params.get((Json::Value::ArrayIndex)0, "").asString();
string sHeaderHash = params.get((Json::Value::ArrayIndex)1, "").asString();
string sSeedHash = params.get((Json::Value::ArrayIndex)2, "").asString();
string sShareTarget = params.get((Json::Value::ArrayIndex)3, "").asString();
//bool cleanJobs = params.get((Json::Value::ArrayIndex)4, "").asBool();
// coinmine.pl fix
int l = sShareTarget.length();
if (l < 66)
sShareTarget = "0x" + string(66 - l, '0') + sShareTarget.substr(2);
if (sHeaderHash != "" && sSeedHash != "" && sShareTarget != "")
{
cnote << "Received new job #" + job.substr(0,8);
//cnote << "Header hash: " + sHeaderHash;
//cnote << "Seed hash: " + sSeedHash;
//cnote << "Share target: " + sShareTarget;
h256 seedHash = h256(sSeedHash);
h256 headerHash = h256(sHeaderHash);
EthashAux::FullType dag;
if (seedHash != m_current.seedHash)
{
cnote << "Grabbing DAG for" << seedHash;
}
if (!(dag = EthashAux::full(seedHash, true, [&](unsigned _pc){ m_waitState = _pc < 100 ? MINER_WAIT_STATE_DAG : MINER_WAIT_STATE_WORK; cnote << "Creating DAG. " << _pc << "% done..."; return 0; })))
{
BOOST_THROW_EXCEPTION(DAGCreationFailure());
}
if (m_precompute)
{
EthashAux::computeFull(sha3(seedHash), true);
}
if (headerHash != m_current.headerHash)
{
//x_current.lock();
if (p_worktimer)
p_worktimer->cancel();
m_previous.headerHash = m_current.headerHash;
m_previous.seedHash = m_current.seedHash;
m_previous.boundary = m_current.boundary;
m_previousJob = m_job;
m_current.headerHash = h256(sHeaderHash);
m_current.seedHash = seedHash;
m_current.boundary = h256(sShareTarget);// , h256::AlignRight);
m_job = job;
p_farm->setWork(m_current);
//x_current.unlock();
p_worktimer = new boost::asio::deadline_timer(m_io_service, boost::posix_time::seconds(m_worktimeout));
p_worktimer->async_wait(boost::bind(&EthStratumClient::work_timeout_handler, this, boost::asio::placeholders::error));
}
}
}
}
else if (method == "mining.set_difficulty")
{
}
else if (method == "client.get_version")
{
os << "{\"error\": null, \"id\" : " << id << ", \"result\" : \"" << ETH_PROJECT_VERSION << "\"}\n";
async_write(m_socket, m_requestBuffer,
boost::bind(&EthStratumClient::handleResponse, this,
boost::asio::placeholders::error));
}
break;
}
}
void EthStratumClient::work_timeout_handler(const boost::system::error_code& ec) {
if (!ec) {
cnote << "No new work received in" << m_worktimeout << "seconds.";
reconnect();
}
}
bool EthStratumClient::submit(EthashProofOfWork::Solution solution) {
x_current.lock();
EthashProofOfWork::WorkPackage tempWork(m_current);
string temp_job = m_job;
EthashProofOfWork::WorkPackage tempPreviousWork(m_previous);
string temp_previous_job = m_previousJob;
x_current.unlock();
cnote << "Solution found; Submitting to" << p_active->host << "...";
cnote << " Nonce:" << "0x" + solution.nonce.hex();
if (EthashAux::eval(tempWork.seedHash, tempWork.headerHash, solution.nonce).value < tempWork.boundary)
{
string json = "{\"id\": 4, \"method\": \"mining.submit\", \"params\": [\"" + p_active->user + "\",\"" + temp_job + "\",\"0x" + solution.nonce.hex() + "\",\"0x" + tempWork.headerHash.hex() + "\",\"0x" + solution.mixHash.hex() + "\"]}\n";
std::ostream os(&m_requestBuffer);
os << json;
m_stale = false;
async_write(m_socket, m_requestBuffer,
boost::bind(&EthStratumClient::handleResponse, this,
boost::asio::placeholders::error));
return true;
}
else if (EthashAux::eval(tempPreviousWork.seedHash, tempPreviousWork.headerHash, solution.nonce).value < tempPreviousWork.boundary)
{
string json = "{\"id\": 4, \"method\": \"mining.submit\", \"params\": [\"" + p_active->user + "\",\"" + temp_previous_job + "\",\"0x" + solution.nonce.hex() + "\",\"0x" + tempPreviousWork.headerHash.hex() + "\",\"0x" + solution.mixHash.hex() + "\"]}\n";
std::ostream os(&m_requestBuffer);
os << json;
m_stale = true;
cwarn << "Submitting stale solution.";
async_write(m_socket, m_requestBuffer,
boost::bind(&EthStratumClient::handleResponse, this,
boost::asio::placeholders::error));
return true;
}
else {
m_stale = false;
cwarn << "FAILURE: GPU gave incorrect result!";
p_farm->failedSolution();
}
return false;
}
<commit_msg>fix linux crash. re eanble lock<commit_after>
#include "EthStratumClient.h"
#include <libdevcore/Log.h>
using boost::asio::ip::tcp;
EthStratumClient::EthStratumClient(GenericFarm<EthashProofOfWork> * f, MinerType m, string const & host, string const & port, string const & user, string const & pass, int const & retries, int const & worktimeout, bool const & precompute)
: m_socket(m_io_service)
{
m_minerType = m;
m_primary.host = host;
m_primary.port = port;
m_primary.user = user;
m_primary.pass = pass;
p_active = &m_primary;
m_authorized = false;
m_connected = false;
m_precompute = precompute;
m_pending = 0;
m_maxRetries = retries;
m_worktimeout = worktimeout;
p_farm = f;
p_worktimer = nullptr;
connect();
}
EthStratumClient::~EthStratumClient()
{
}
void EthStratumClient::setFailover(string const & host, string const & port)
{
setFailover(host, port, p_active->user, p_active->pass);
}
void EthStratumClient::setFailover(string const & host, string const & port, string const & user, string const & pass)
{
m_failover.host = host;
m_failover.port = port;
m_failover.user = user;
m_failover.pass = pass;
}
void EthStratumClient::connect()
{
tcp::resolver r(m_io_service);
tcp::resolver::query q(p_active->host, p_active->port);
r.async_resolve(q, boost::bind(&EthStratumClient::resolve_handler,
this, boost::asio::placeholders::error,
boost::asio::placeholders::iterator));
cnote << "Connecting to stratum server " << p_active->host + ":" + p_active->port;
boost::thread t(boost::bind(&boost::asio::io_service::run, &m_io_service));
}
#define BOOST_ASIO_ENABLE_CANCELIO
void EthStratumClient::reconnect()
{
if (p_worktimer) {
p_worktimer->cancel();
p_worktimer = nullptr;
}
m_io_service.reset();
//m_socket.close(); // leads to crashes on Linux
m_authorized = false;
m_connected = false;
if (!m_failover.host.empty())
{
m_retries++;
if (m_retries > m_maxRetries)
{
if (m_failover.host == "exit") {
disconnect();
return;
}
else if (p_active == &m_primary)
{
p_active = &m_failover;
}
else {
p_active = &m_primary;
}
m_retries = 0;
}
}
cnote << "Reconnecting in 3 seconds...";
boost::asio::deadline_timer timer(m_io_service, boost::posix_time::seconds(3));
timer.wait();
connect();
}
void EthStratumClient::disconnect()
{
cnote << "Disconnecting";
m_connected = false;
m_running = false;
if (p_farm->isMining())
{
cnote << "Stopping farm";
p_farm->stop();
}
m_socket.close();
m_io_service.stop();
}
void EthStratumClient::resolve_handler(const boost::system::error_code& ec, tcp::resolver::iterator i)
{
if (!ec)
{
async_connect(m_socket, i, boost::bind(&EthStratumClient::connect_handler,
this, boost::asio::placeholders::error,
boost::asio::placeholders::iterator));
}
else
{
cerr << "Could not resolve host" << p_active->host + ":" + p_active->port + ", " << ec.message();
reconnect();
}
}
void EthStratumClient::connect_handler(const boost::system::error_code& ec, tcp::resolver::iterator i)
{
dev::setThreadName("stratum");
if (!ec)
{
m_connected = true;
cnote << "Connected to stratum server " << i->host_name() << ":" << p_active->port;
if (!p_farm->isMining())
{
cnote << "Starting farm";
if (m_minerType == MinerType::CPU)
p_farm->start("cpu");
else if (m_minerType == MinerType::CL)
p_farm->start("opencl");
else if (m_minerType == MinerType::CUDA)
p_farm->start("cuda");
}
std::ostream os(&m_requestBuffer);
os << "{\"id\": 1, \"method\": \"mining.subscribe\", \"params\": []}\n";
async_write(m_socket, m_requestBuffer,
boost::bind(&EthStratumClient::handleResponse, this,
boost::asio::placeholders::error));
}
else
{
cwarn << "Could not connect to stratum server " << p_active->host << ":" << p_active->port << ", " << ec.message();
reconnect();
}
}
void EthStratumClient::readline() {
x_pending.lock();
if (m_pending == 0) {
async_read_until(m_socket, m_responseBuffer, "\n",
boost::bind(&EthStratumClient::readResponse, this,
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
m_pending++;
}
x_pending.unlock();
}
void EthStratumClient::handleResponse(const boost::system::error_code& ec) {
if (!ec)
{
readline();
}
else
{
dev::setThreadName("stratum");
cwarn << "Handle response failed: " << ec.message();
}
}
void EthStratumClient::readResponse(const boost::system::error_code& ec, std::size_t bytes_transferred)
{
dev::setThreadName("stratum");
x_pending.lock();
m_pending = m_pending > 0 ? m_pending - 1 : 0;
x_pending.unlock();
if (!ec && bytes_transferred)
{
std::istream is(&m_responseBuffer);
std::string response;
getline(is, response);
if (response.front() == '{' && response.back() == '}')
{
Json::Value responseObject;
Json::Reader reader;
if (reader.parse(response.c_str(), responseObject))
{
processReponse(responseObject);
m_response = response;
}
else
{
cwarn << "Parse response failed: " << reader.getFormattedErrorMessages();
}
}
else
{
cwarn << "Discarding incomplete response";
}
if (m_connected)
readline();
}
else
{
cwarn << "Read response failed: " << ec.message();
if (m_connected)
reconnect();
}
}
void EthStratumClient::processReponse(Json::Value& responseObject)
{
Json::Value error = responseObject.get("error", new Json::Value);
if (error.isArray())
{
string msg = error.get(1, "Unknown error").asString();
cnote << msg;
}
std::ostream os(&m_requestBuffer);
Json::Value params;
int id = responseObject.get("id", Json::Value::null).asInt();
switch (id)
{
case 1:
cnote << "Subscribed to stratum server";
os << "{\"id\": 2, \"method\": \"mining.authorize\", \"params\": [\"" << p_active->user << "\",\"" << p_active->pass << "\"]}\n";
async_write(m_socket, m_requestBuffer,
boost::bind(&EthStratumClient::handleResponse, this,
boost::asio::placeholders::error));
break;
case 2:
m_authorized = responseObject.get("result", Json::Value::null).asBool();
if (!m_authorized)
{
cnote << "Worker not authorized:" << p_active->user;
disconnect();
return;
}
cnote << "Authorized worker " << p_active->user;
break;
case 4:
if (responseObject.get("result", false).asBool()) {
cnote << "B-) Submitted and accepted.";
p_farm->acceptedSolution(m_stale);
}
else {
cwarn << ":-( Not accepted.";
p_farm->rejectedSolution(m_stale);
}
break;
default:
string method = responseObject.get("method", "").asString();
if (method == "mining.notify")
{
params = responseObject.get("params", Json::Value::null);
if (params.isArray())
{
string job = params.get((Json::Value::ArrayIndex)0, "").asString();
string sHeaderHash = params.get((Json::Value::ArrayIndex)1, "").asString();
string sSeedHash = params.get((Json::Value::ArrayIndex)2, "").asString();
string sShareTarget = params.get((Json::Value::ArrayIndex)3, "").asString();
//bool cleanJobs = params.get((Json::Value::ArrayIndex)4, "").asBool();
// coinmine.pl fix
int l = sShareTarget.length();
if (l < 66)
sShareTarget = "0x" + string(66 - l, '0') + sShareTarget.substr(2);
if (sHeaderHash != "" && sSeedHash != "" && sShareTarget != "")
{
cnote << "Received new job #" + job.substr(0,8);
//cnote << "Header hash: " + sHeaderHash;
//cnote << "Seed hash: " + sSeedHash;
//cnote << "Share target: " + sShareTarget;
h256 seedHash = h256(sSeedHash);
h256 headerHash = h256(sHeaderHash);
EthashAux::FullType dag;
if (seedHash != m_current.seedHash)
{
cnote << "Grabbing DAG for" << seedHash;
}
if (!(dag = EthashAux::full(seedHash, true, [&](unsigned _pc){ m_waitState = _pc < 100 ? MINER_WAIT_STATE_DAG : MINER_WAIT_STATE_WORK; cnote << "Creating DAG. " << _pc << "% done..."; return 0; })))
{
BOOST_THROW_EXCEPTION(DAGCreationFailure());
}
if (m_precompute)
{
EthashAux::computeFull(sha3(seedHash), true);
}
if (headerHash != m_current.headerHash)
{
x_current.lock();
if (p_worktimer)
p_worktimer->cancel();
m_previous.headerHash = m_current.headerHash;
m_previous.seedHash = m_current.seedHash;
m_previous.boundary = m_current.boundary;
m_previousJob = m_job;
m_current.headerHash = h256(sHeaderHash);
m_current.seedHash = seedHash;
m_current.boundary = h256(sShareTarget);// , h256::AlignRight);
m_job = job;
p_farm->setWork(m_current);
x_current.unlock();
p_worktimer = new boost::asio::deadline_timer(m_io_service, boost::posix_time::seconds(m_worktimeout));
p_worktimer->async_wait(boost::bind(&EthStratumClient::work_timeout_handler, this, boost::asio::placeholders::error));
}
}
}
}
else if (method == "mining.set_difficulty")
{
}
else if (method == "client.get_version")
{
os << "{\"error\": null, \"id\" : " << id << ", \"result\" : \"" << ETH_PROJECT_VERSION << "\"}\n";
async_write(m_socket, m_requestBuffer,
boost::bind(&EthStratumClient::handleResponse, this,
boost::asio::placeholders::error));
}
break;
}
}
void EthStratumClient::work_timeout_handler(const boost::system::error_code& ec) {
if (!ec) {
cnote << "No new work received in" << m_worktimeout << "seconds.";
reconnect();
}
}
bool EthStratumClient::submit(EthashProofOfWork::Solution solution) {
x_current.lock();
EthashProofOfWork::WorkPackage tempWork(m_current);
string temp_job = m_job;
EthashProofOfWork::WorkPackage tempPreviousWork(m_previous);
string temp_previous_job = m_previousJob;
x_current.unlock();
cnote << "Solution found; Submitting to" << p_active->host << "...";
cnote << " Nonce:" << "0x" + solution.nonce.hex();
if (EthashAux::eval(tempWork.seedHash, tempWork.headerHash, solution.nonce).value < tempWork.boundary)
{
string json = "{\"id\": 4, \"method\": \"mining.submit\", \"params\": [\"" + p_active->user + "\",\"" + temp_job + "\",\"0x" + solution.nonce.hex() + "\",\"0x" + tempWork.headerHash.hex() + "\",\"0x" + solution.mixHash.hex() + "\"]}\n";
std::ostream os(&m_requestBuffer);
os << json;
m_stale = false;
async_write(m_socket, m_requestBuffer,
boost::bind(&EthStratumClient::handleResponse, this,
boost::asio::placeholders::error));
return true;
}
else if (EthashAux::eval(tempPreviousWork.seedHash, tempPreviousWork.headerHash, solution.nonce).value < tempPreviousWork.boundary)
{
string json = "{\"id\": 4, \"method\": \"mining.submit\", \"params\": [\"" + p_active->user + "\",\"" + temp_previous_job + "\",\"0x" + solution.nonce.hex() + "\",\"0x" + tempPreviousWork.headerHash.hex() + "\",\"0x" + solution.mixHash.hex() + "\"]}\n";
std::ostream os(&m_requestBuffer);
os << json;
m_stale = true;
cwarn << "Submitting stale solution.";
async_write(m_socket, m_requestBuffer,
boost::bind(&EthStratumClient::handleResponse, this,
boost::asio::placeholders::error));
return true;
}
else {
m_stale = false;
cwarn << "FAILURE: GPU gave incorrect result!";
p_farm->failedSolution();
}
return false;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: lngsvcmgr.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: tl $ $Date: 2001-06-29 13:50:15 $
*
* 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 _LINGUISTIC_LNGSVCMGR_HXX_
#define _LINGUISTIC_LNGSVCMGR_HXX_
#include <uno/lbnames.h> // CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type
#include <cppuhelper/implbase4.hxx> // helper for implementations
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h> //OMultiTypeInterfaceContainerHelper
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LINGUISTIC2_XLINGUSERVICEMANAGER_HPP_
#include <com/sun/star/linguistic2/XLinguServiceManager.hpp>
#endif
#ifndef _COM_SUN_STAR_LINGUISTIC2_XAVAILABLELOCALES_HPP_
#include <com/sun/star/linguistic2/XAvailableLocales.hpp>
#endif
#include <vcl/timer.hxx>
#include "misc.hxx"
#include "defs.hxx"
class SpellCheckerDispatcher;
class HyphenatorDispatcher;
class ThesaurusDispatcher;
class SvcInfoArray;
class LngSvcMgrListenerHelper;
namespace com { namespace sun { namespace star { namespace linguistic2 {
class XLinguServiceEventBroadcaster;
class XSpellChecker;
class XHyphenator;
class XThesaurus;
} } } }
///////////////////////////////////////////////////////////////////////////
class LngSvcMgr :
public cppu::WeakImplHelper4
<
com::sun::star::linguistic2::XLinguServiceManager,
com::sun::star::linguistic2::XAvailableLocales,
com::sun::star::lang::XComponent,
com::sun::star::lang::XServiceInfo
>
{
::cppu::OInterfaceContainerHelper aEvtListeners;
com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XSpellChecker > xSpellDsp;
com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XHyphenator > xHyphDsp;
com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XThesaurus > xThesDsp;
com::sun::star::uno::Reference<
::com::sun::star::lang::XEventListener > xListenerHelper;
com::sun::star::uno::Sequence<
com::sun::star::lang::Locale > aAvailSpellLocales;
com::sun::star::uno::Sequence<
com::sun::star::lang::Locale > aAvailHyphLocales;
com::sun::star::uno::Sequence<
com::sun::star::lang::Locale > aAvailThesLocales;
SpellCheckerDispatcher * pSpellDsp;
HyphenatorDispatcher * pHyphDsp;
ThesaurusDispatcher * pThesDsp;
LngSvcMgrListenerHelper * pListenerHelper;
SvcInfoArray * pAvailSpellSvcs;
SvcInfoArray * pAvailHyphSvcs;
SvcInfoArray * pAvailThesSvcs;
BOOL bDisposing;
BOOL bHasAvailSpellLocales;
BOOL bHasAvailHyphLocales;
BOOL bHasAvailThesLocales;
// disallow copy-constructor and assignment-operator for now
LngSvcMgr(const LngSvcMgr &);
LngSvcMgr & operator = (const LngSvcMgr &);
void GetAvailableSpellSvcs_Impl();
void GetAvailableHyphSvcs_Impl();
void GetAvailableThesSvcs_Impl();
void GetListenerHelper_Impl();
void GetSpellCheckerDsp_Impl();
void GetHyphenatorDsp_Impl();
void GetThesaurusDsp_Impl();
void SetCfgServiceLists( SpellCheckerDispatcher &rSpellDsp );
void SetCfgServiceLists( HyphenatorDispatcher &rHyphDsp );
void SetCfgServiceLists( ThesaurusDispatcher &rThesDsp );
BOOL SaveCfgSvcs( const String &rServiceName );
public:
LngSvcMgr();
virtual ~LngSvcMgr();
// XLinguServiceManager
virtual ::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XSpellChecker > SAL_CALL
getSpellChecker()
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XHyphenator > SAL_CALL
getHyphenator()
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XThesaurus > SAL_CALL
getThesaurus()
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL
addLinguServiceManagerListener(
const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XEventListener >& xListener )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL
removeLinguServiceManagerListener(
const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XEventListener >& xListener )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
getAvailableServices(
const ::rtl::OUString& rServiceName,
const ::com::sun::star::lang::Locale& rLocale )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
setConfiguredServices(
const ::rtl::OUString& rServiceName,
const ::com::sun::star::lang::Locale& rLocale,
const ::com::sun::star::uno::Sequence<
::rtl::OUString >& rServiceImplNames )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
getConfiguredServices(
const ::rtl::OUString& rServiceName,
const ::com::sun::star::lang::Locale& rLocale )
throw(::com::sun::star::uno::RuntimeException);
// XAvailableLocales
virtual ::com::sun::star::uno::Sequence<
::com::sun::star::lang::Locale > SAL_CALL
getAvailableLocales(
const ::rtl::OUString& rServiceName )
throw(::com::sun::star::uno::RuntimeException);
// XComponent
virtual void SAL_CALL
dispose()
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
addEventListener(
const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XEventListener >& xListener )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
removeEventListener(
const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XEventListener >& xListener )
throw(::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL
getImplementationName()
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL
supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
getSupportedServiceNames()
throw(::com::sun::star::uno::RuntimeException);
static inline ::rtl::OUString
getImplementationName_Static();
static ::com::sun::star::uno::Sequence< ::rtl::OUString >
getSupportedServiceNames_Static() throw();
BOOL AddLngSvcEvtBroadcaster(
const ::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XLinguServiceEventBroadcaster > &rxBroadcaster );
BOOL RemoveLngSvcEvtBroadcaster(
const ::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XLinguServiceEventBroadcaster > &rxBroadcaster );
};
inline ::rtl::OUString LngSvcMgr::getImplementationName_Static()
{
return A2OU( "com.sun.star.lingu2.LngSvcMgr" );
}
///////////////////////////////////////////////////////////////////////////
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.194); FILE MERGED 2005/09/05 17:29:40 rt 1.7.194.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: lngsvcmgr.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:54:07 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _LINGUISTIC_LNGSVCMGR_HXX_
#define _LINGUISTIC_LNGSVCMGR_HXX_
#include <uno/lbnames.h> // CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type
#include <cppuhelper/implbase4.hxx> // helper for implementations
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h> //OMultiTypeInterfaceContainerHelper
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LINGUISTIC2_XLINGUSERVICEMANAGER_HPP_
#include <com/sun/star/linguistic2/XLinguServiceManager.hpp>
#endif
#ifndef _COM_SUN_STAR_LINGUISTIC2_XAVAILABLELOCALES_HPP_
#include <com/sun/star/linguistic2/XAvailableLocales.hpp>
#endif
#include <vcl/timer.hxx>
#include "misc.hxx"
#include "defs.hxx"
class SpellCheckerDispatcher;
class HyphenatorDispatcher;
class ThesaurusDispatcher;
class SvcInfoArray;
class LngSvcMgrListenerHelper;
namespace com { namespace sun { namespace star { namespace linguistic2 {
class XLinguServiceEventBroadcaster;
class XSpellChecker;
class XHyphenator;
class XThesaurus;
} } } }
///////////////////////////////////////////////////////////////////////////
class LngSvcMgr :
public cppu::WeakImplHelper4
<
com::sun::star::linguistic2::XLinguServiceManager,
com::sun::star::linguistic2::XAvailableLocales,
com::sun::star::lang::XComponent,
com::sun::star::lang::XServiceInfo
>
{
::cppu::OInterfaceContainerHelper aEvtListeners;
com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XSpellChecker > xSpellDsp;
com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XHyphenator > xHyphDsp;
com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XThesaurus > xThesDsp;
com::sun::star::uno::Reference<
::com::sun::star::lang::XEventListener > xListenerHelper;
com::sun::star::uno::Sequence<
com::sun::star::lang::Locale > aAvailSpellLocales;
com::sun::star::uno::Sequence<
com::sun::star::lang::Locale > aAvailHyphLocales;
com::sun::star::uno::Sequence<
com::sun::star::lang::Locale > aAvailThesLocales;
SpellCheckerDispatcher * pSpellDsp;
HyphenatorDispatcher * pHyphDsp;
ThesaurusDispatcher * pThesDsp;
LngSvcMgrListenerHelper * pListenerHelper;
SvcInfoArray * pAvailSpellSvcs;
SvcInfoArray * pAvailHyphSvcs;
SvcInfoArray * pAvailThesSvcs;
BOOL bDisposing;
BOOL bHasAvailSpellLocales;
BOOL bHasAvailHyphLocales;
BOOL bHasAvailThesLocales;
// disallow copy-constructor and assignment-operator for now
LngSvcMgr(const LngSvcMgr &);
LngSvcMgr & operator = (const LngSvcMgr &);
void GetAvailableSpellSvcs_Impl();
void GetAvailableHyphSvcs_Impl();
void GetAvailableThesSvcs_Impl();
void GetListenerHelper_Impl();
void GetSpellCheckerDsp_Impl();
void GetHyphenatorDsp_Impl();
void GetThesaurusDsp_Impl();
void SetCfgServiceLists( SpellCheckerDispatcher &rSpellDsp );
void SetCfgServiceLists( HyphenatorDispatcher &rHyphDsp );
void SetCfgServiceLists( ThesaurusDispatcher &rThesDsp );
BOOL SaveCfgSvcs( const String &rServiceName );
public:
LngSvcMgr();
virtual ~LngSvcMgr();
// XLinguServiceManager
virtual ::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XSpellChecker > SAL_CALL
getSpellChecker()
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XHyphenator > SAL_CALL
getHyphenator()
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XThesaurus > SAL_CALL
getThesaurus()
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL
addLinguServiceManagerListener(
const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XEventListener >& xListener )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL
removeLinguServiceManagerListener(
const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XEventListener >& xListener )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
getAvailableServices(
const ::rtl::OUString& rServiceName,
const ::com::sun::star::lang::Locale& rLocale )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
setConfiguredServices(
const ::rtl::OUString& rServiceName,
const ::com::sun::star::lang::Locale& rLocale,
const ::com::sun::star::uno::Sequence<
::rtl::OUString >& rServiceImplNames )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
getConfiguredServices(
const ::rtl::OUString& rServiceName,
const ::com::sun::star::lang::Locale& rLocale )
throw(::com::sun::star::uno::RuntimeException);
// XAvailableLocales
virtual ::com::sun::star::uno::Sequence<
::com::sun::star::lang::Locale > SAL_CALL
getAvailableLocales(
const ::rtl::OUString& rServiceName )
throw(::com::sun::star::uno::RuntimeException);
// XComponent
virtual void SAL_CALL
dispose()
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
addEventListener(
const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XEventListener >& xListener )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
removeEventListener(
const ::com::sun::star::uno::Reference<
::com::sun::star::lang::XEventListener >& xListener )
throw(::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL
getImplementationName()
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL
supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
getSupportedServiceNames()
throw(::com::sun::star::uno::RuntimeException);
static inline ::rtl::OUString
getImplementationName_Static();
static ::com::sun::star::uno::Sequence< ::rtl::OUString >
getSupportedServiceNames_Static() throw();
BOOL AddLngSvcEvtBroadcaster(
const ::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XLinguServiceEventBroadcaster > &rxBroadcaster );
BOOL RemoveLngSvcEvtBroadcaster(
const ::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XLinguServiceEventBroadcaster > &rxBroadcaster );
};
inline ::rtl::OUString LngSvcMgr::getImplementationName_Static()
{
return A2OU( "com.sun.star.lingu2.LngSvcMgr" );
}
///////////////////////////////////////////////////////////////////////////
#endif
<|endoftext|>
|
<commit_before>#pragma once
#include "boost_defs.hpp"
#include <array>
#include <boost/optional.hpp>
#include <climits>
#include <fstream>
#include <string>
#include <sys/stat.h>
namespace krbn {
class filesystem final {
public:
static bool exists(const std::string& path) {
struct stat s;
return (stat(path.c_str(), &s) == 0);
}
static bool create_directory_with_intermediate_directories(const std::string& path, mode_t mode) {
std::vector<std::string> parents;
auto directory = path;
while (!exists(directory)) {
parents.push_back(directory);
directory = dirname(directory);
}
for (auto it = std::rbegin(parents); it != std::rend(parents); std::advance(it, 1)) {
if (mkdir(it->c_str(), mode) != 0) {
return false;
}
}
if (!is_directory(path)) {
return false;
}
chmod(path.c_str(), mode);
return true;
}
static void copy(const std::string& from_file_path,
const std::string& to_file_path) {
std::ifstream ifstream(from_file_path);
if (!ifstream) {
return;
}
std::ofstream ofstream(to_file_path);
if (!ofstream) {
return;
}
ofstream << ifstream.rdbuf();
}
static boost::optional<mode_t> file_access_permissions(const std::string& path) {
struct stat s;
if (stat(path.c_str(), &s) != 0) {
return boost::none;
}
return s.st_mode & ACCESSPERMS;
}
static boost::optional<off_t> file_size(const std::string& path) {
struct stat s;
if (stat(path.c_str(), &s) != 0) {
return boost::none;
}
return s.st_size;
}
static bool is_directory(const std::string& path) {
struct stat s;
if (stat(path.c_str(), &s) == 0) {
return S_ISDIR(s.st_mode);
}
return false;
}
static bool is_owned(const std::string& path, uid_t uid) {
struct stat s;
if (stat(path.c_str(), &s) == 0) {
return s.st_uid == uid;
}
return false;
}
static std::string dirname(const std::string& path) {
size_t pos = get_dirname_position(path);
if (pos == 0) {
return ".";
}
return path.substr(0, pos);
}
static void normalize_file_path(std::string& path) {
if (path.empty()) {
path += '.';
return;
}
size_t end = path.size();
size_t dest = 1;
for (size_t src = 1; src < end; ++src) {
// Skip multiple slashes.
if (path[dest - 1] == '/' && path[src] == '/') {
continue;
}
// Handling . and ..
if (path[src] == '/') {
dest = process_dot(path, dest);
dest = process_dotdot(path, dest);
if (dest == 0) {
if (path[0] != '/') {
continue;
}
} else {
if (path[dest - 1] == '/') {
continue;
}
}
}
if (dest != src) {
path[dest] = path[src];
}
++dest;
}
dest = process_dot(path, dest);
dest = process_dotdot(path, dest);
if (dest == 0) {
path[0] = '.';
dest = 1;
}
path.resize(dest);
}
static boost::optional<std::string> realpath(const std::string& path) {
std::array<char, PATH_MAX> resolved_path;
if (!::realpath(path.c_str(), &(resolved_path[0]))) {
return boost::none;
}
return std::string(&(resolved_path[0]));
}
private:
static size_t get_dirname_position(const std::string& path, size_t pos = std::string::npos) {
if (path.empty()) return 0;
if (pos == std::string::npos) {
pos = path.size() - 1;
}
if (path.size() <= pos) return 0;
if (pos == 0) {
// We retain the first slash for dirname("/") == "/".
if (path[pos] == '/') {
return 1;
} else {
return 0;
}
}
if (path[pos] == '/') {
--pos;
}
size_t i = path.rfind('/', pos);
if (i == std::string::npos) {
return 0;
}
if (i == 0) {
// path starts with "/".
return 1;
}
return i;
}
static size_t process_dot(const std::string& path, size_t pos) {
if (path.empty()) return pos;
// foo/bar/./
// ^
// pos
//
if (pos > 2 &&
path[pos - 2] == '/' &&
path[pos - 1] == '.') {
return pos - 2;
}
// ./foo/bar
// ^
// pos
//
if (pos == 1 &&
path[0] == '.') {
return 0;
}
return pos;
}
static size_t process_dotdot(const std::string& path, size_t pos) {
// Ignore ../../
if (pos > 4 &&
path[pos - 5] == '.' &&
path[pos - 4] == '.' &&
path[pos - 3] == '/' &&
path[pos - 2] == '.' &&
path[pos - 1] == '.') {
return pos;
}
// foo/bar/../
// ^
// pos
//
if (pos > 2 &&
path[pos - 3] == '/' &&
path[pos - 2] == '.' &&
path[pos - 1] == '.') {
pos = get_dirname_position(path, pos - 3);
// foo/bar/../
// ^
// pos
return pos;
}
return pos;
}
};
} // namespace krbn
<commit_msg>update #include<commit_after>#pragma once
#include "boost_defs.hpp"
#include <array>
#include <boost/optional.hpp>
#include <climits>
#include <fstream>
#include <string>
#include <sys/stat.h>
#include <vector>
namespace krbn {
class filesystem final {
public:
static bool exists(const std::string& path) {
struct stat s;
return (stat(path.c_str(), &s) == 0);
}
static bool create_directory_with_intermediate_directories(const std::string& path, mode_t mode) {
std::vector<std::string> parents;
auto directory = path;
while (!exists(directory)) {
parents.push_back(directory);
directory = dirname(directory);
}
for (auto it = std::rbegin(parents); it != std::rend(parents); std::advance(it, 1)) {
if (mkdir(it->c_str(), mode) != 0) {
return false;
}
}
if (!is_directory(path)) {
return false;
}
chmod(path.c_str(), mode);
return true;
}
static void copy(const std::string& from_file_path,
const std::string& to_file_path) {
std::ifstream ifstream(from_file_path);
if (!ifstream) {
return;
}
std::ofstream ofstream(to_file_path);
if (!ofstream) {
return;
}
ofstream << ifstream.rdbuf();
}
static boost::optional<mode_t> file_access_permissions(const std::string& path) {
struct stat s;
if (stat(path.c_str(), &s) != 0) {
return boost::none;
}
return s.st_mode & ACCESSPERMS;
}
static boost::optional<off_t> file_size(const std::string& path) {
struct stat s;
if (stat(path.c_str(), &s) != 0) {
return boost::none;
}
return s.st_size;
}
static bool is_directory(const std::string& path) {
struct stat s;
if (stat(path.c_str(), &s) == 0) {
return S_ISDIR(s.st_mode);
}
return false;
}
static bool is_owned(const std::string& path, uid_t uid) {
struct stat s;
if (stat(path.c_str(), &s) == 0) {
return s.st_uid == uid;
}
return false;
}
static std::string dirname(const std::string& path) {
size_t pos = get_dirname_position(path);
if (pos == 0) {
return ".";
}
return path.substr(0, pos);
}
static void normalize_file_path(std::string& path) {
if (path.empty()) {
path += '.';
return;
}
size_t end = path.size();
size_t dest = 1;
for (size_t src = 1; src < end; ++src) {
// Skip multiple slashes.
if (path[dest - 1] == '/' && path[src] == '/') {
continue;
}
// Handling . and ..
if (path[src] == '/') {
dest = process_dot(path, dest);
dest = process_dotdot(path, dest);
if (dest == 0) {
if (path[0] != '/') {
continue;
}
} else {
if (path[dest - 1] == '/') {
continue;
}
}
}
if (dest != src) {
path[dest] = path[src];
}
++dest;
}
dest = process_dot(path, dest);
dest = process_dotdot(path, dest);
if (dest == 0) {
path[0] = '.';
dest = 1;
}
path.resize(dest);
}
static boost::optional<std::string> realpath(const std::string& path) {
std::array<char, PATH_MAX> resolved_path;
if (!::realpath(path.c_str(), &(resolved_path[0]))) {
return boost::none;
}
return std::string(&(resolved_path[0]));
}
private:
static size_t get_dirname_position(const std::string& path, size_t pos = std::string::npos) {
if (path.empty()) return 0;
if (pos == std::string::npos) {
pos = path.size() - 1;
}
if (path.size() <= pos) return 0;
if (pos == 0) {
// We retain the first slash for dirname("/") == "/".
if (path[pos] == '/') {
return 1;
} else {
return 0;
}
}
if (path[pos] == '/') {
--pos;
}
size_t i = path.rfind('/', pos);
if (i == std::string::npos) {
return 0;
}
if (i == 0) {
// path starts with "/".
return 1;
}
return i;
}
static size_t process_dot(const std::string& path, size_t pos) {
if (path.empty()) return pos;
// foo/bar/./
// ^
// pos
//
if (pos > 2 &&
path[pos - 2] == '/' &&
path[pos - 1] == '.') {
return pos - 2;
}
// ./foo/bar
// ^
// pos
//
if (pos == 1 &&
path[0] == '.') {
return 0;
}
return pos;
}
static size_t process_dotdot(const std::string& path, size_t pos) {
// Ignore ../../
if (pos > 4 &&
path[pos - 5] == '.' &&
path[pos - 4] == '.' &&
path[pos - 3] == '/' &&
path[pos - 2] == '.' &&
path[pos - 1] == '.') {
return pos;
}
// foo/bar/../
// ^
// pos
//
if (pos > 2 &&
path[pos - 3] == '/' &&
path[pos - 2] == '.' &&
path[pos - 1] == '.') {
pos = get_dirname_position(path, pos - 3);
// foo/bar/../
// ^
// pos
return pos;
}
return pos;
}
};
} // namespace krbn
<|endoftext|>
|
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443271. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the GLVis visualization tool and library. For more
// information and source code availability see http://glvis.org.
//
// GLVis 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) version 2.1 dated February 1999.
#ifndef GLVIS_SDL_X11_HPP
#define GLVIS_SDL_X11_HPP
#ifdef SDL_VIDEO_DRIVER_X11
#include "sdl_helper.hpp"
#include "gl/platform_gl.hpp"
#include "aux_vis.hpp"
#include "threads.hpp"
#include <poll.h>
#ifdef SDL_VIDEO_DRIVER_X11_XINPUT2
#include <X11/extensions/XInput2.h>
#endif // SDL_VIDEO_DRIVER_X11_XINPUT2
class SdlX11Platform final : public SdlNativePlatform
{
public:
SdlX11Platform(Display* xdisplay, Window xwindow)
: disp(xdisplay), wnd(xwindow)
{
// Disable XInput extension events since they are generated even outside
// the GLVis window.
Window root_win = DefaultRootWindow(disp);
unsigned char mask[4] = {0,0,0,0};
XIEventMask event_mask;
event_mask.deviceid = XIAllMasterDevices;
event_mask.mask_len = sizeof(mask);
event_mask.mask = mask;
#ifdef SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2
typedef int (*XISelectEvents_ptr)(Display *, Window, XIEventMask *, int);
static XISelectEvents_ptr XISelectEvents_ = NULL;
if (XISelectEvents_ == NULL)
{
void *lib = SDL_LoadObject(SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2);
if (lib != NULL)
{
XISelectEvents_ =
(XISelectEvents_ptr)SDL_LoadFunction(lib, "XISelectEvents");
}
}
if (XISelectEvents_ == NULL)
{
cerr << "Error accessing XISelectEvents!" << endl;
exit(EXIT_FAILURE);
}
#else
#define XISelectEvents_ XISelectEvents
#endif
if (XISelectEvents_(disp, root_win, &event_mask, 1) != Success)
{
cerr << "Failed to disable XInput on the default root window!" << endl;
}
if (XISelectEvents_(disp, wnd, &event_mask, 1) != Success)
{
cerr << "Failed to disable XInput on the current window!" << endl;
}
}
void WaitEvent()
{
int nstr, nfd = 1;
struct pollfd pfd[2];
pfd[0].fd = ConnectionNumber(disp);
pfd[0].events = POLLIN;
pfd[0].revents = 0;
if (glvis_command && visualize == 1)
{
pfd[1].fd = glvis_command->ReadFD();
pfd[1].events = POLLIN;
pfd[1].revents = 0;
nfd = 2;
}
do
{
nstr = poll(pfd, nfd, -1);
}
while (nstr == -1 && errno == EINTR);
if (nstr == -1) { perror("poll()"); }
}
void SendEvent() {}
private:
Display* disp;
Window wnd;
};
#endif // SDL_VIDEO_DRIVER_X11
#endif // GLVIS_SDL_X11_HPP
<commit_msg>Build fix for x11 systems<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443271. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the GLVis visualization tool and library. For more
// information and source code availability see http://glvis.org.
//
// GLVis 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) version 2.1 dated February 1999.
#ifndef GLVIS_SDL_X11_HPP
#define GLVIS_SDL_X11_HPP
#ifdef SDL_VIDEO_DRIVER_X11
#include "sdl_helper.hpp"
#include "gl/platform_gl.hpp"
#include "aux_vis.hpp"
#include "threads.hpp"
#include <poll.h>
#ifdef SDL_VIDEO_DRIVER_X11_XINPUT2
#include <X11/extensions/XInput2.h>
#endif // SDL_VIDEO_DRIVER_X11_XINPUT2
extern int visualize;
class SdlX11Platform final : public SdlNativePlatform
{
public:
SdlX11Platform(Display* xdisplay, Window xwindow)
: disp(xdisplay), wnd(xwindow)
{
// Disable XInput extension events since they are generated even outside
// the GLVis window.
Window root_win = DefaultRootWindow(disp);
unsigned char mask[4] = {0,0,0,0};
XIEventMask event_mask;
event_mask.deviceid = XIAllMasterDevices;
event_mask.mask_len = sizeof(mask);
event_mask.mask = mask;
#ifdef SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2
typedef int (*XISelectEvents_ptr)(Display *, Window, XIEventMask *, int);
static XISelectEvents_ptr XISelectEvents_ = NULL;
if (XISelectEvents_ == NULL)
{
void *lib = SDL_LoadObject(SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2);
if (lib != NULL)
{
XISelectEvents_ =
(XISelectEvents_ptr)SDL_LoadFunction(lib, "XISelectEvents");
}
}
if (XISelectEvents_ == NULL)
{
cerr << "Error accessing XISelectEvents!" << endl;
exit(EXIT_FAILURE);
}
#else
#define XISelectEvents_ XISelectEvents
#endif
if (XISelectEvents_(disp, root_win, &event_mask, 1) != Success)
{
cerr << "Failed to disable XInput on the default root window!" << endl;
}
if (XISelectEvents_(disp, wnd, &event_mask, 1) != Success)
{
cerr << "Failed to disable XInput on the current window!" << endl;
}
}
void WaitEvent()
{
int nstr, nfd = 1;
struct pollfd pfd[2];
pfd[0].fd = ConnectionNumber(disp);
pfd[0].events = POLLIN;
pfd[0].revents = 0;
if (glvis_command && visualize == 1)
{
pfd[1].fd = glvis_command->ReadFD();
pfd[1].events = POLLIN;
pfd[1].revents = 0;
nfd = 2;
}
do
{
nstr = poll(pfd, nfd, -1);
}
while (nstr == -1 && errno == EINTR);
if (nstr == -1) { perror("poll()"); }
}
void SendEvent() {}
private:
Display* disp;
Window wnd;
};
#endif // SDL_VIDEO_DRIVER_X11
#endif // GLVIS_SDL_X11_HPP
<|endoftext|>
|
<commit_before>/**
* @file
* Lists and hashes
*
*/
#include "angort.h"
#include "hash.h"
#include "opcodes.h"
using namespace angort;
namespace angort {
struct RevStdComparator : public ArrayListComparator<Value> {
Angort *ang;
RevStdComparator(Angort *a){
ang = a;
}
virtual int compare(const Value *a, const Value *b){
// binop isn't const, sadly.
ang->binop(const_cast<Value *>(b),
const_cast<Value *>(a),OP_CMP);
return ang->popInt();
}
};
struct FuncComparator : public ArrayListComparator<Value> {
Value *func;
Angort *ang;
FuncComparator(Angort *a,Value *f){
ang = a;
func = f;
}
virtual int compare(const Value *a, const Value *b){
ang->pushval()->copy(a);
ang->pushval()->copy(b);
ang->runValue(func);
return ang->popInt();
}
};
}
%name coll
%word dumplist (list --) Dump a list
{
ArrayList<Value> *list = Types::tList->get(a->popval());
for(int i=0;i<list->count();i++){
const StringBuffer& s = list->get(i)->toString();
printf("%d: %s\n",i,s.get());
}
}
%word get (key coll --) get an item from a list or hash
{
Value *c = a->popval();
Value *keyAndResult = a->stack.peekptr();
Value v;
c->t->getValue(c,keyAndResult,&v);
keyAndResult->copy(&v); // copy into the key's slot
}
%word set (val key coll --) put an item into a list or hash
{
Value *c = a->popval();
Value *k = a->popval();
Value *v = a->popval();
c->t->setValue(c,k,v);
}
%word len (list --) get length of list, hash or string
{
Value *c = a->stack.peekptr();
int ct = c->t->getCount(c);
Types::tInteger->set(c,ct);
}
%word remove (idx list -- item) remove an item by index, returning it
{
Value *c = a->popval();
Value *keyAndResult = a->stack.peekptr();
Value v;
c->t->removeAndReturn(c,keyAndResult,&v);
keyAndResult->copy(&v); // copy into the key's slot
}
%word shift (list -- item) remove and return the first item of the list
{
ArrayList<Value> *list = Types::tList->get(a->popval());
Value *v = a->pushval();
v->copy(list->get(0));
list->remove(0);
}
%word unshift (item list --) prepend an item to a list
{
ArrayList<Value> *list = Types::tList->get(a->popval());
Value *v = a->popval();
list->insert(0)->copy(v);
}
%word pop (list -- item) pop an item from the end of the list
{
ArrayList<Value> *list = Types::tList->get(a->popval());
Value *v = a->pushval();
Value *src = list->get(list->count()-1);
v->copy(src);
list->remove(list->count()-1);
}
%word push (item list --) append an item to a list
{
ArrayList<Value> *list = Types::tList->get(a->popval());
Value *v = a->popval();
list->append()->copy(v);
}
%word map (iter func -- list) apply a function to an iterable, giving a list
{
Value func;
func.copy(a->popval()); // need a local copy
Value *iterable = a->popval();
Iterator<Value *> *iter = iterable->t->makeIterator(iterable);
ArrayList<Value> *list = Types::tList->set(a->pushval());
for(iter->first();!iter->isDone();iter->next()){
a->pushval()->copy(iter->current());
a->runValue(&func);
Value *v = list->append();
v->copy(a->popval());
}
delete iter;
}
%word reduce (start iter func -- result) perform a (left) fold or reduce on an iterable
{
Value func;
func.copy(a->popval()); // need a local copy
Value *iterable = a->popval();
Iterator<Value *> *iter = iterable->t->makeIterator(iterable);
// accumulator is already on the stack
for(iter->first();!iter->isDone();iter->next()){
a->pushval()->copy(iter->current()); // stack the iterator on top of the accum
a->runValue(&func); // run the function, leaving the new accumulator
}
delete iter;
}
%word filter (iter func -- list) filter an iterable with a boolean function
{
Value func;
func.copy(a->popval()); // need a local copy
Value *iterable = a->popval();
Iterator<Value *> *iter = iterable->t->makeIterator(iterable);
ArrayList<Value> *list = Types::tList->set(a->pushval());
for(iter->first();!iter->isDone();iter->next()){
a->pushval()->copy(iter->current());
a->runValue(&func);
if(a->popval()->toInt()){
Value *v = list->append();
v->copy(iter->current());
}
}
delete iter;
}
%word in (item iterable -- bool) return if item is in list or hash keys
{
Value *iterable = a->popval();
Value *item = a->popval();
a->pushInt(iterable->t->isIn(iterable,item)?true:false);
}
%word slice (start len iterable -- iterable) produce a slice of a string or list
{
Value *iterable = a->popval();
int len = a->popInt();
int start = a->popInt();
Value *res = a->pushval();
iterable->t->slice(res,iterable,start,len);
}
%word clone (in -- out) construct a shallow copy of a collection
{
Value *v = a->stack.peekptr();
v->t->clone(v,v,false);
}
%word deepclone (in -- out) produce a deep copy of a value
{
Value *v = a->stack.peekptr();
v->t->clone(v,v,true);
}
struct StdComparator : public ArrayListComparator<Value> {
Angort *ang;
StdComparator(Angort *a){
ang = a;
}
virtual int compare(const Value *a, const Value *b){
// binop isn't const, sadly.
ang->binop(const_cast<Value *>(a),
const_cast<Value *>(b),OP_CMP);
return ang->popInt();
}
};
%word sort (in --) sort a list in place using default comparator
{
Value listv;
// need copy because comparators use the stack
listv.copy(a->popval());
ArrayList<Value> *list = Types::tList->get(&listv);
StdComparator cmp(a);
list->sort(&cmp);
}
%word rsort (in --) reverse sort a list in place using default comparator
{
Value listv;
// need copy because comparators use the stack
listv.copy(a->popval());
ArrayList<Value> *list = Types::tList->get(&listv);
RevStdComparator cmp(a);
list->sort(&cmp);
}
%word fsort (in func --) sort a list in place using function comparator
{
Value func,listv;
// need copies because comparators use the stack
func.copy(a->popval());
listv.copy(a->popval());
ArrayList<Value> *list = Types::tList->get(&listv);
FuncComparator cmp(a,&func);
list->sort(&cmp);
}
%word all (in func --) true if the function returns true for all items
{
int rv=1; // true by default
Value func;
func.copy(a->popval()); // need a local copy
Value *iterable = a->popval();
Iterator<Value *> *iter = iterable->t->makeIterator(iterable);
for(iter->first();!iter->isDone();iter->next()){
a->pushval()->copy(iter->current()); // stack the iterator on top of the accum
a->runValue(&func); // run the function
if(!a->popInt()){
rv = 0;
break;
}
}
a->pushInt(rv);
delete iter;
}
%word any (in func --) true if the function returns true for all items
{
int rv=0; // false by default
Value func;
func.copy(a->popval()); // need a local copy
Value *iterable = a->popval();
Iterator<Value *> *iter = iterable->t->makeIterator(iterable);
for(iter->first();!iter->isDone();iter->next()){
a->pushval()->copy(iter->current()); // stack the iterator on top of the accum
a->runValue(&func); // run the function
if(a->popInt()){
rv = 1;
break;
}
}
a->pushInt(rv);
delete iter;
}
%word zipWith (in1 in2 func -- out) apply binary func to pairs of items in list
{
Value *p[3];
a->popParams(p,"llc");
Iterator<Value *> *iter1 = p[0]->t->makeIterator(p[0]);
Iterator<Value *> *iter2 = p[1]->t->makeIterator(p[1]);
Value func;
func.copy(p[2]); // need a local copy
ArrayList<Value> *list = Types::tList->set(a->pushval());
for(iter1->first(),iter2->first();
!(iter1->isDone() || iter2->isDone());
iter1->next(),iter2->next()){
a->pushval()->copy(iter1->current());
a->pushval()->copy(iter2->current());
a->runValue(&func);
list->append()->copy(a->popval());
}
delete iter1;
delete iter2;
}
%word intercalate (iter string -- string) turn elements of collection into string and intercalate with a separator
{
Value *p[2];
a->popParams(p,"vv"); // can be any type
Value *v = p[0];
Iterator<Value *> *iter = v->t->makeIterator(v);
const StringBuffer& s = p[1]->toString();
const char *sep = s.get();
int seplen = strlen(sep);
int count = v->t->getCount(v);
// first pass to get the lengths
int len=0;
int n=0;
for(n=0,iter->first();!iter->isDone();iter->next(),n++){
len += strlen(iter->current()->toString().get());
if(n!=count-1)
len += seplen;
}
// allocate the result in a new string value on the stack
char *out = Types::tString->allocate(a->pushval(),len+1,Types::tString);
// second pass to write the value
*out = 0;
for(n=0,iter->first();!iter->isDone();iter->next(),n++){
const StringBuffer& b = iter->current()->toString();
strcpy(out,b.get());
out += strlen(b.get());
if(n!=count-1){
strcpy(out,sep);
out+=seplen;
}
}
}
<commit_msg>last added<commit_after>/**
* @file
* Lists and hashes
*
*/
#include "angort.h"
#include "hash.h"
#include "opcodes.h"
using namespace angort;
namespace angort {
struct RevStdComparator : public ArrayListComparator<Value> {
Angort *ang;
RevStdComparator(Angort *a){
ang = a;
}
virtual int compare(const Value *a, const Value *b){
// binop isn't const, sadly.
ang->binop(const_cast<Value *>(b),
const_cast<Value *>(a),OP_CMP);
return ang->popInt();
}
};
struct FuncComparator : public ArrayListComparator<Value> {
Value *func;
Angort *ang;
FuncComparator(Angort *a,Value *f){
ang = a;
func = f;
}
virtual int compare(const Value *a, const Value *b){
ang->pushval()->copy(a);
ang->pushval()->copy(b);
ang->runValue(func);
return ang->popInt();
}
};
}
%name coll
%word dumplist (list --) Dump a list
{
ArrayList<Value> *list = Types::tList->get(a->popval());
for(int i=0;i<list->count();i++){
const StringBuffer& s = list->get(i)->toString();
printf("%d: %s\n",i,s.get());
}
}
%word last (coll -- item/none) get last item
{
Value *c = a->stack.peekptr();
int n = c->t->getCount(c)-1;
if(n<0)
c->clr();
else {
Value v,out;
Types::tInteger->set(&v,n);
c->t->getValue(c,&v,&out);
c->copy(&out);
}
}
%word get (key coll --) get an item from a list or hash
{
Value *c = a->popval();
Value *keyAndResult = a->stack.peekptr();
Value v;
c->t->getValue(c,keyAndResult,&v);
keyAndResult->copy(&v); // copy into the key's slot
}
%word set (val key coll --) put an item into a list or hash
{
Value *c = a->popval();
Value *k = a->popval();
Value *v = a->popval();
c->t->setValue(c,k,v);
}
%word len (list --) get length of list, hash or string
{
Value *c = a->stack.peekptr();
int ct = c->t->getCount(c);
Types::tInteger->set(c,ct);
}
%word remove (idx list -- item) remove an item by index, returning it
{
Value *c = a->popval();
Value *keyAndResult = a->stack.peekptr();
Value v;
c->t->removeAndReturn(c,keyAndResult,&v);
keyAndResult->copy(&v); // copy into the key's slot
}
%word shift (list -- item) remove and return the first item of the list
{
ArrayList<Value> *list = Types::tList->get(a->popval());
Value *v = a->pushval();
v->copy(list->get(0));
list->remove(0);
}
%word unshift (item list --) prepend an item to a list
{
ArrayList<Value> *list = Types::tList->get(a->popval());
Value *v = a->popval();
list->insert(0)->copy(v);
}
%word pop (list -- item) pop an item from the end of the list
{
ArrayList<Value> *list = Types::tList->get(a->popval());
Value *v = a->pushval();
Value *src = list->get(list->count()-1);
v->copy(src);
list->remove(list->count()-1);
}
%word push (item list --) append an item to a list
{
ArrayList<Value> *list = Types::tList->get(a->popval());
Value *v = a->popval();
list->append()->copy(v);
}
%word map (iter func -- list) apply a function to an iterable, giving a list
{
Value func;
func.copy(a->popval()); // need a local copy
Value *iterable = a->popval();
Iterator<Value *> *iter = iterable->t->makeIterator(iterable);
ArrayList<Value> *list = Types::tList->set(a->pushval());
for(iter->first();!iter->isDone();iter->next()){
a->pushval()->copy(iter->current());
a->runValue(&func);
Value *v = list->append();
v->copy(a->popval());
}
delete iter;
}
%word reduce (start iter func -- result) perform a (left) fold or reduce on an iterable
{
Value func;
func.copy(a->popval()); // need a local copy
Value *iterable = a->popval();
Iterator<Value *> *iter = iterable->t->makeIterator(iterable);
// accumulator is already on the stack
for(iter->first();!iter->isDone();iter->next()){
a->pushval()->copy(iter->current()); // stack the iterator on top of the accum
a->runValue(&func); // run the function, leaving the new accumulator
}
delete iter;
}
%word filter (iter func -- list) filter an iterable with a boolean function
{
Value func;
func.copy(a->popval()); // need a local copy
Value *iterable = a->popval();
Iterator<Value *> *iter = iterable->t->makeIterator(iterable);
ArrayList<Value> *list = Types::tList->set(a->pushval());
for(iter->first();!iter->isDone();iter->next()){
a->pushval()->copy(iter->current());
a->runValue(&func);
if(a->popval()->toInt()){
Value *v = list->append();
v->copy(iter->current());
}
}
delete iter;
}
%word in (item iterable -- bool) return if item is in list or hash keys
{
Value *iterable = a->popval();
Value *item = a->popval();
a->pushInt(iterable->t->isIn(iterable,item)?true:false);
}
%word slice (start len iterable -- iterable) produce a slice of a string or list
{
Value *iterable = a->popval();
int len = a->popInt();
int start = a->popInt();
Value *res = a->pushval();
iterable->t->slice(res,iterable,start,len);
}
%word clone (in -- out) construct a shallow copy of a collection
{
Value *v = a->stack.peekptr();
v->t->clone(v,v,false);
}
%word deepclone (in -- out) produce a deep copy of a value
{
Value *v = a->stack.peekptr();
v->t->clone(v,v,true);
}
struct StdComparator : public ArrayListComparator<Value> {
Angort *ang;
StdComparator(Angort *a){
ang = a;
}
virtual int compare(const Value *a, const Value *b){
// binop isn't const, sadly.
ang->binop(const_cast<Value *>(a),
const_cast<Value *>(b),OP_CMP);
return ang->popInt();
}
};
%word sort (in --) sort a list in place using default comparator
{
Value listv;
// need copy because comparators use the stack
listv.copy(a->popval());
ArrayList<Value> *list = Types::tList->get(&listv);
StdComparator cmp(a);
list->sort(&cmp);
}
%word rsort (in --) reverse sort a list in place using default comparator
{
Value listv;
// need copy because comparators use the stack
listv.copy(a->popval());
ArrayList<Value> *list = Types::tList->get(&listv);
RevStdComparator cmp(a);
list->sort(&cmp);
}
%word fsort (in func --) sort a list in place using function comparator
{
Value func,listv;
// need copies because comparators use the stack
func.copy(a->popval());
listv.copy(a->popval());
ArrayList<Value> *list = Types::tList->get(&listv);
FuncComparator cmp(a,&func);
list->sort(&cmp);
}
%word all (in func --) true if the function returns true for all items
{
int rv=1; // true by default
Value func;
func.copy(a->popval()); // need a local copy
Value *iterable = a->popval();
Iterator<Value *> *iter = iterable->t->makeIterator(iterable);
for(iter->first();!iter->isDone();iter->next()){
a->pushval()->copy(iter->current()); // stack the iterator on top of the accum
a->runValue(&func); // run the function
if(!a->popInt()){
rv = 0;
break;
}
}
a->pushInt(rv);
delete iter;
}
%word any (in func --) true if the function returns true for all items
{
int rv=0; // false by default
Value func;
func.copy(a->popval()); // need a local copy
Value *iterable = a->popval();
Iterator<Value *> *iter = iterable->t->makeIterator(iterable);
for(iter->first();!iter->isDone();iter->next()){
a->pushval()->copy(iter->current()); // stack the iterator on top of the accum
a->runValue(&func); // run the function
if(a->popInt()){
rv = 1;
break;
}
}
a->pushInt(rv);
delete iter;
}
%word zipWith (in1 in2 func -- out) apply binary func to pairs of items in list
{
Value *p[3];
a->popParams(p,"llc");
Iterator<Value *> *iter1 = p[0]->t->makeIterator(p[0]);
Iterator<Value *> *iter2 = p[1]->t->makeIterator(p[1]);
Value func;
func.copy(p[2]); // need a local copy
ArrayList<Value> *list = Types::tList->set(a->pushval());
for(iter1->first(),iter2->first();
!(iter1->isDone() || iter2->isDone());
iter1->next(),iter2->next()){
a->pushval()->copy(iter1->current());
a->pushval()->copy(iter2->current());
a->runValue(&func);
list->append()->copy(a->popval());
}
delete iter1;
delete iter2;
}
%word intercalate (iter string -- string) turn elements of collection into string and intercalate with a separator
{
Value *p[2];
a->popParams(p,"vv"); // can be any type
Value *v = p[0];
Iterator<Value *> *iter = v->t->makeIterator(v);
const StringBuffer& s = p[1]->toString();
const char *sep = s.get();
int seplen = strlen(sep);
int count = v->t->getCount(v);
// first pass to get the lengths
int len=0;
int n=0;
for(n=0,iter->first();!iter->isDone();iter->next(),n++){
len += strlen(iter->current()->toString().get());
if(n!=count-1)
len += seplen;
}
// allocate the result in a new string value on the stack
char *out = Types::tString->allocate(a->pushval(),len+1,Types::tString);
// second pass to write the value
*out = 0;
for(n=0,iter->first();!iter->isDone();iter->next(),n++){
const StringBuffer& b = iter->current()->toString();
strcpy(out,b.get());
out += strlen(b.get());
if(n!=count-1){
strcpy(out,sep);
out+=seplen;
}
}
}
<|endoftext|>
|
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* http://razor-qt.org, http://lxde.org/
*
* Copyright: 2010-2011 LXQt team
* Authors:
* Petr Vanek <petr@scribus.info>
* Hong Jen Yee (PCMan) <pcman.tw@gmail.com>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "lxqtmodman.h"
#include <LXQt/Settings>
#include <XdgAutoStart>
#include <XdgDirs>
#include <unistd.h>
#include <QDebug>
#include <QCoreApplication>
#include <QMessageBox>
#include <QSystemTrayIcon>
#include <QFileInfo>
#include <QFile>
#include <QDir>
#include <QFileSystemWatcher>
#include <QDateTime>
#include "wmselectdialog.h"
#include "windowmanager.h"
#include <wordexp.h>
#include <KWindowSystem/KWindowSystem>
#include <KWindowSystem/netwm.h>
#include <QX11Info>
#define MAX_CRASHES_PER_APP 5
using namespace LXQt;
/**
* @brief the constructor, needs a valid modules.conf
*/
LXQtModuleManager::LXQtModuleManager(const QString & windowManager, QObject* parent)
: QObject(parent),
mWindowManager(windowManager),
mWmProcess(new QProcess(this)),
mThemeWatcher(new QFileSystemWatcher(this)),
mWmStarted(false),
mTrayStarted(false),
mWaitLoop(NULL)
{
connect(mThemeWatcher, SIGNAL(directoryChanged(QString)), SLOT(themeFolderChanged(QString)));
connect(LXQt::Settings::globalSettings(), SIGNAL(lxqtThemeChanged()), SLOT(themeChanged()));
qApp->installNativeEventFilter(this);
}
void LXQtModuleManager::startup(LXQt::Settings& s)
{
// The lxqt-confupdate can update the settings of the WM, so run it first.
startConfUpdate();
// Start window manager
startWm(&s);
startAutostartApps();
QStringList paths;
paths << XdgDirs::dataHome(false);
paths << XdgDirs::dataDirs();
foreach(QString path, paths)
{
QFileInfo fi(QString("%1/lxqt/themes").arg(path));
if (fi.exists())
mThemeWatcher->addPath(fi.absoluteFilePath());
}
themeChanged();
}
void LXQtModuleManager::startAutostartApps()
{
// XDG autostart
XdgDesktopFileList fileList = XdgAutoStart::desktopFileList();
QList<XdgDesktopFile*> trayApps;
for (XdgDesktopFileList::iterator i = fileList.begin(); i != fileList.end(); ++i)
{
if (i->value("X-LXQt-Need-Tray", false).toBool())
trayApps.append(&(*i));
else
{
startProcess(*i);
qDebug() << "start" << i->fileName();
}
}
if (!trayApps.isEmpty())
{
mTrayStarted = QSystemTrayIcon::isSystemTrayAvailable();
if(!mTrayStarted)
{
QEventLoop waitLoop;
mWaitLoop = &waitLoop;
// add a timeout to avoid infinite blocking if a WM fail to execute.
QTimer::singleShot(60 * 1000, &waitLoop, SLOT(quit()));
waitLoop.exec();
mWaitLoop = NULL;
}
foreach (XdgDesktopFile* f, trayApps)
{
qDebug() << "start tray app" << f->fileName();
startProcess(*f);
}
}
}
void LXQtModuleManager::themeFolderChanged(const QString& /*path*/)
{
QString newTheme;
if (!QFileInfo(mCurrentThemePath).exists())
{
const QList<LXQtTheme> &allThemes = lxqtTheme.allThemes();
if (!allThemes.isEmpty())
newTheme = allThemes[0].name();
else
return;
}
else
newTheme = lxqtTheme.currentTheme().name();
LXQt::Settings settings("lxqt");
if (newTheme == settings.value("theme"))
{
// force the same theme to be updated
settings.setValue("__theme_updated__", QDateTime::currentMSecsSinceEpoch());
}
else
settings.setValue("theme", newTheme);
sync();
}
void LXQtModuleManager::themeChanged()
{
if (!mCurrentThemePath.isEmpty())
mThemeWatcher->removePath(mCurrentThemePath);
if (lxqtTheme.currentTheme().isValid())
{
mCurrentThemePath = lxqtTheme.currentTheme().path();
mThemeWatcher->addPath(mCurrentThemePath);
}
}
void LXQtModuleManager::startWm(LXQt::Settings *settings)
{
// if the WM is active do not run WM.
// all window managers must set their name according to the spec
if (!QString(NETRootInfo(QX11Info::connection(), NET::SupportingWMCheck).wmName()).isEmpty())
{
mWmStarted = true;
return;
}
if (mWindowManager.isEmpty())
{
mWindowManager = settings->value("window_manager").toString();
}
// If previuos WM was removed, we show dialog.
if (mWindowManager.isEmpty() || ! findProgram(mWindowManager.split(' ')[0]))
{
mWindowManager = showWmSelectDialog();
settings->setValue("window_manager", mWindowManager);
settings->sync();
}
if(mWindowManager == "openbox")
{
QString openboxSettingsPath = QDir().homePath() + "/.config/lxqt/openbox/rc.xml";
// Copy default settings of openbox
if(!QFileInfo::exists(openboxSettingsPath))
{
QDir dir( QDir().homePath() + "/.config/lxqt" );
dir.mkpath("openbox");
QFile::copy("/etc/xdg/lxqt/openbox/rc.xml", openboxSettingsPath);
}
QStringList args;
args << "--config-file" << openboxSettingsPath;
mWmProcess->start(mWindowManager, args);
}
else
mWmProcess->start(mWindowManager);
// other autostart apps will be handled after the WM becomes available
// Wait until the WM loads
QEventLoop waitLoop;
mWaitLoop = &waitLoop;
// add a timeout to avoid infinite blocking if a WM fail to execute.
QTimer::singleShot(30 * 1000, &waitLoop, SLOT(quit()));
waitLoop.exec();
mWaitLoop = NULL;
// FIXME: blocking is a bad idea. We need to start as many apps as possible and
// only wait for the start of WM when it's absolutely needed.
// Maybe we can add a X-Wait-WM=true key in the desktop entry file?
}
void LXQtModuleManager::startProcess(const XdgDesktopFile& file)
{
if (!file.value("X-LXQt-Module", false).toBool())
{
file.startDetached();
return;
}
QStringList args = file.expandExecString();
if (args.isEmpty())
{
qWarning() << "Wrong desktop file" << file.fileName();
return;
}
LXQtModule* proc = new LXQtModule(file, this);
connect(proc, SIGNAL(moduleStateChanged(QString,bool)), this, SIGNAL(moduleStateChanged(QString,bool)));
proc->start();
QString name = QFileInfo(file.fileName()).fileName();
mNameMap[name] = proc;
connect(proc, SIGNAL(finished(int, QProcess::ExitStatus)),
this, SLOT(restartModules(int, QProcess::ExitStatus)));
}
void LXQtModuleManager::startProcess(const QString& name)
{
if (!mNameMap.contains(name))
{
foreach (const XdgDesktopFile& file, XdgAutoStart::desktopFileList(false))
{
if (QFileInfo(file.fileName()).fileName() == name)
{
startProcess(file);
return;
}
}
}
}
void LXQtModuleManager::stopProcess(const QString& name)
{
if (mNameMap.contains(name))
mNameMap[name]->terminate();
}
QStringList LXQtModuleManager::listModules() const
{
return QStringList(mNameMap.keys());
}
void LXQtModuleManager::startConfUpdate()
{
XdgDesktopFile desktop(XdgDesktopFile::ApplicationType, ":lxqt-confupdate", "lxqt-confupdate --watch");
desktop.setValue("Name", "LXQt config updater");
desktop.setValue("X-LXQt-Module", true);
startProcess(desktop);
}
void LXQtModuleManager::restartModules(int exitCode, QProcess::ExitStatus exitStatus)
{
LXQtModule* proc = qobject_cast<LXQtModule*>(sender());
Q_ASSERT(proc);
if (!proc->isTerminating())
{
QString procName = proc->file.name();
switch (exitStatus)
{
case QProcess::NormalExit:
qDebug() << "Process" << procName << "(" << proc << ") exited correctly.";
break;
case QProcess::CrashExit:
{
qDebug() << "Process" << procName << "(" << proc << ") has to be restarted";
time_t now = time(NULL);
mCrashReport[proc].prepend(now);
while (now - mCrashReport[proc].back() > 60)
mCrashReport[proc].pop_back();
if (mCrashReport[proc].length() >= MAX_CRASHES_PER_APP)
{
QMessageBox::warning(0, tr("Crash Report"),
tr("<b>%1</b> crashed too many times. Its autorestart has been disabled until next login.").arg(procName));
}
else
{
proc->start();
return;
}
break;
}
}
}
mNameMap.remove(proc->fileName);
proc->deleteLater();
}
LXQtModuleManager::~LXQtModuleManager()
{
qApp->removeNativeEventFilter(this);
qDeleteAll(mNameMap);
delete mWmProcess;
}
/**
* @brief this logs us out by terminating our session
**/
void LXQtModuleManager::logout()
{
// modules
ModulesMapIterator i(mNameMap);
while (i.hasNext())
{
i.next();
qDebug() << "Module logout" << i.key();
LXQtModule* p = i.value();
p->terminate();
}
i.toFront();
while (i.hasNext())
{
i.next();
LXQtModule* p = i.value();
if (p->state() != QProcess::NotRunning && !p->waitForFinished(2000))
{
qWarning() << QString("Module '%1' won't terminate ... killing.").arg(i.key());
p->kill();
}
}
mWmProcess->terminate();
if (mWmProcess->state() != QProcess::NotRunning && !mWmProcess->waitForFinished(2000))
{
qWarning() << QString("Window Manager won't terminate ... killing.");
mWmProcess->kill();
}
QCoreApplication::exit(0);
}
QString LXQtModuleManager::showWmSelectDialog()
{
WindowManagerList availableWM = getWindowManagerList(true);
if (availableWM.count() == 1)
return availableWM.at(0).command;
WmSelectDialog dlg(availableWM);
dlg.exec();
return dlg.windowManager();
}
void LXQtModuleManager::resetCrashReport()
{
mCrashReport.clear();
}
bool LXQtModuleManager::nativeEventFilter(const QByteArray & eventType, void * message, long * result)
{
if (eventType != "xcb_generic_event_t") // We only want to handle XCB events
return false;
if(!mWmStarted && mWaitLoop)
{
// all window managers must set their name according to the spec
if (!QString(NETRootInfo(QX11Info::connection(), NET::SupportingWMCheck).wmName()).isEmpty())
{
qDebug() << "Window Manager started";
mWmStarted = true;
if (mWaitLoop->isRunning())
mWaitLoop->exit();
}
}
if (!mTrayStarted && QSystemTrayIcon::isSystemTrayAvailable() && mWaitLoop)
{
qDebug() << "System Tray started";
mTrayStarted = true;
if (mWaitLoop->isRunning())
mWaitLoop->exit();
// window manager and system tray have started
qApp->removeNativeEventFilter(this);
}
return false;
}
void lxqt_setenv(const char *env, const QByteArray &value)
{
wordexp_t p;
wordexp(value, &p, 0);
if (p.we_wordc == 1)
{
qDebug() << "Environment variable" << env << "=" << p.we_wordv[0];
qputenv(env, p.we_wordv[0]);
}
else
{
qWarning() << "Error expanding environment variable" << env << "=" << value;
qputenv(env, value);
}
wordfree(&p);
}
void lxqt_setenv_prepend(const char *env, const QByteArray &value, const QByteArray &separator)
{
QByteArray orig(qgetenv(env));
orig = orig.prepend(separator);
orig = orig.prepend(value);
qDebug() << "Setting special" << env << " variable:" << orig;
lxqt_setenv(env, orig);
}
LXQtModule::LXQtModule(const XdgDesktopFile& file, QObject* parent) :
QProcess(parent),
file(file),
fileName(QFileInfo(file.fileName()).fileName()),
mIsTerminating(false)
{
connect(this, SIGNAL(stateChanged(QProcess::ProcessState)), SLOT(updateState(QProcess::ProcessState)));
}
void LXQtModule::start()
{
mIsTerminating = false;
QStringList args = file.expandExecString();
QString command = args.takeFirst();
QProcess::start(command, args);
}
void LXQtModule::terminate()
{
mIsTerminating = true;
QProcess::terminate();
}
bool LXQtModule::isTerminating()
{
return mIsTerminating;
}
void LXQtModule::updateState(QProcess::ProcessState newState)
{
if (newState != QProcess::Starting)
emit moduleStateChanged(fileName, (newState == QProcess::Running));
}
<commit_msg>Openbox default settings removed.<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* http://razor-qt.org, http://lxde.org/
*
* Copyright: 2010-2011 LXQt team
* Authors:
* Petr Vanek <petr@scribus.info>
* Hong Jen Yee (PCMan) <pcman.tw@gmail.com>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "lxqtmodman.h"
#include <LXQt/Settings>
#include <XdgAutoStart>
#include <XdgDirs>
#include <unistd.h>
#include <QDebug>
#include <QCoreApplication>
#include <QMessageBox>
#include <QSystemTrayIcon>
#include <QFileInfo>
#include <QFile>
#include <QDir>
#include <QFileSystemWatcher>
#include <QDateTime>
#include "wmselectdialog.h"
#include "windowmanager.h"
#include <wordexp.h>
#include <KWindowSystem/KWindowSystem>
#include <KWindowSystem/netwm.h>
#include <QX11Info>
#define MAX_CRASHES_PER_APP 5
using namespace LXQt;
/**
* @brief the constructor, needs a valid modules.conf
*/
LXQtModuleManager::LXQtModuleManager(const QString & windowManager, QObject* parent)
: QObject(parent),
mWindowManager(windowManager),
mWmProcess(new QProcess(this)),
mThemeWatcher(new QFileSystemWatcher(this)),
mWmStarted(false),
mTrayStarted(false),
mWaitLoop(NULL)
{
connect(mThemeWatcher, SIGNAL(directoryChanged(QString)), SLOT(themeFolderChanged(QString)));
connect(LXQt::Settings::globalSettings(), SIGNAL(lxqtThemeChanged()), SLOT(themeChanged()));
qApp->installNativeEventFilter(this);
}
void LXQtModuleManager::startup(LXQt::Settings& s)
{
// The lxqt-confupdate can update the settings of the WM, so run it first.
startConfUpdate();
// Start window manager
startWm(&s);
startAutostartApps();
QStringList paths;
paths << XdgDirs::dataHome(false);
paths << XdgDirs::dataDirs();
foreach(QString path, paths)
{
QFileInfo fi(QString("%1/lxqt/themes").arg(path));
if (fi.exists())
mThemeWatcher->addPath(fi.absoluteFilePath());
}
themeChanged();
}
void LXQtModuleManager::startAutostartApps()
{
// XDG autostart
XdgDesktopFileList fileList = XdgAutoStart::desktopFileList();
QList<XdgDesktopFile*> trayApps;
for (XdgDesktopFileList::iterator i = fileList.begin(); i != fileList.end(); ++i)
{
if (i->value("X-LXQt-Need-Tray", false).toBool())
trayApps.append(&(*i));
else
{
startProcess(*i);
qDebug() << "start" << i->fileName();
}
}
if (!trayApps.isEmpty())
{
mTrayStarted = QSystemTrayIcon::isSystemTrayAvailable();
if(!mTrayStarted)
{
QEventLoop waitLoop;
mWaitLoop = &waitLoop;
// add a timeout to avoid infinite blocking if a WM fail to execute.
QTimer::singleShot(60 * 1000, &waitLoop, SLOT(quit()));
waitLoop.exec();
mWaitLoop = NULL;
}
foreach (XdgDesktopFile* f, trayApps)
{
qDebug() << "start tray app" << f->fileName();
startProcess(*f);
}
}
}
void LXQtModuleManager::themeFolderChanged(const QString& /*path*/)
{
QString newTheme;
if (!QFileInfo(mCurrentThemePath).exists())
{
const QList<LXQtTheme> &allThemes = lxqtTheme.allThemes();
if (!allThemes.isEmpty())
newTheme = allThemes[0].name();
else
return;
}
else
newTheme = lxqtTheme.currentTheme().name();
LXQt::Settings settings("lxqt");
if (newTheme == settings.value("theme"))
{
// force the same theme to be updated
settings.setValue("__theme_updated__", QDateTime::currentMSecsSinceEpoch());
}
else
settings.setValue("theme", newTheme);
sync();
}
void LXQtModuleManager::themeChanged()
{
if (!mCurrentThemePath.isEmpty())
mThemeWatcher->removePath(mCurrentThemePath);
if (lxqtTheme.currentTheme().isValid())
{
mCurrentThemePath = lxqtTheme.currentTheme().path();
mThemeWatcher->addPath(mCurrentThemePath);
}
}
void LXQtModuleManager::startWm(LXQt::Settings *settings)
{
// if the WM is active do not run WM.
// all window managers must set their name according to the spec
if (!QString(NETRootInfo(QX11Info::connection(), NET::SupportingWMCheck).wmName()).isEmpty())
{
mWmStarted = true;
return;
}
if (mWindowManager.isEmpty())
{
mWindowManager = settings->value("window_manager").toString();
}
// If previuos WM was removed, we show dialog.
if (mWindowManager.isEmpty() || ! findProgram(mWindowManager.split(' ')[0]))
{
mWindowManager = showWmSelectDialog();
settings->setValue("window_manager", mWindowManager);
settings->sync();
}
mWmProcess->start(mWindowManager);
// other autostart apps will be handled after the WM becomes available
// Wait until the WM loads
QEventLoop waitLoop;
mWaitLoop = &waitLoop;
// add a timeout to avoid infinite blocking if a WM fail to execute.
QTimer::singleShot(30 * 1000, &waitLoop, SLOT(quit()));
waitLoop.exec();
mWaitLoop = NULL;
// FIXME: blocking is a bad idea. We need to start as many apps as possible and
// only wait for the start of WM when it's absolutely needed.
// Maybe we can add a X-Wait-WM=true key in the desktop entry file?
}
void LXQtModuleManager::startProcess(const XdgDesktopFile& file)
{
if (!file.value("X-LXQt-Module", false).toBool())
{
file.startDetached();
return;
}
QStringList args = file.expandExecString();
if (args.isEmpty())
{
qWarning() << "Wrong desktop file" << file.fileName();
return;
}
LXQtModule* proc = new LXQtModule(file, this);
connect(proc, SIGNAL(moduleStateChanged(QString,bool)), this, SIGNAL(moduleStateChanged(QString,bool)));
proc->start();
QString name = QFileInfo(file.fileName()).fileName();
mNameMap[name] = proc;
connect(proc, SIGNAL(finished(int, QProcess::ExitStatus)),
this, SLOT(restartModules(int, QProcess::ExitStatus)));
}
void LXQtModuleManager::startProcess(const QString& name)
{
if (!mNameMap.contains(name))
{
foreach (const XdgDesktopFile& file, XdgAutoStart::desktopFileList(false))
{
if (QFileInfo(file.fileName()).fileName() == name)
{
startProcess(file);
return;
}
}
}
}
void LXQtModuleManager::stopProcess(const QString& name)
{
if (mNameMap.contains(name))
mNameMap[name]->terminate();
}
QStringList LXQtModuleManager::listModules() const
{
return QStringList(mNameMap.keys());
}
void LXQtModuleManager::startConfUpdate()
{
XdgDesktopFile desktop(XdgDesktopFile::ApplicationType, ":lxqt-confupdate", "lxqt-confupdate --watch");
desktop.setValue("Name", "LXQt config updater");
desktop.setValue("X-LXQt-Module", true);
startProcess(desktop);
}
void LXQtModuleManager::restartModules(int exitCode, QProcess::ExitStatus exitStatus)
{
LXQtModule* proc = qobject_cast<LXQtModule*>(sender());
Q_ASSERT(proc);
if (!proc->isTerminating())
{
QString procName = proc->file.name();
switch (exitStatus)
{
case QProcess::NormalExit:
qDebug() << "Process" << procName << "(" << proc << ") exited correctly.";
break;
case QProcess::CrashExit:
{
qDebug() << "Process" << procName << "(" << proc << ") has to be restarted";
time_t now = time(NULL);
mCrashReport[proc].prepend(now);
while (now - mCrashReport[proc].back() > 60)
mCrashReport[proc].pop_back();
if (mCrashReport[proc].length() >= MAX_CRASHES_PER_APP)
{
QMessageBox::warning(0, tr("Crash Report"),
tr("<b>%1</b> crashed too many times. Its autorestart has been disabled until next login.").arg(procName));
}
else
{
proc->start();
return;
}
break;
}
}
}
mNameMap.remove(proc->fileName);
proc->deleteLater();
}
LXQtModuleManager::~LXQtModuleManager()
{
qApp->removeNativeEventFilter(this);
qDeleteAll(mNameMap);
delete mWmProcess;
}
/**
* @brief this logs us out by terminating our session
**/
void LXQtModuleManager::logout()
{
// modules
ModulesMapIterator i(mNameMap);
while (i.hasNext())
{
i.next();
qDebug() << "Module logout" << i.key();
LXQtModule* p = i.value();
p->terminate();
}
i.toFront();
while (i.hasNext())
{
i.next();
LXQtModule* p = i.value();
if (p->state() != QProcess::NotRunning && !p->waitForFinished(2000))
{
qWarning() << QString("Module '%1' won't terminate ... killing.").arg(i.key());
p->kill();
}
}
mWmProcess->terminate();
if (mWmProcess->state() != QProcess::NotRunning && !mWmProcess->waitForFinished(2000))
{
qWarning() << QString("Window Manager won't terminate ... killing.");
mWmProcess->kill();
}
QCoreApplication::exit(0);
}
QString LXQtModuleManager::showWmSelectDialog()
{
WindowManagerList availableWM = getWindowManagerList(true);
if (availableWM.count() == 1)
return availableWM.at(0).command;
WmSelectDialog dlg(availableWM);
dlg.exec();
return dlg.windowManager();
}
void LXQtModuleManager::resetCrashReport()
{
mCrashReport.clear();
}
bool LXQtModuleManager::nativeEventFilter(const QByteArray & eventType, void * message, long * result)
{
if (eventType != "xcb_generic_event_t") // We only want to handle XCB events
return false;
if(!mWmStarted && mWaitLoop)
{
// all window managers must set their name according to the spec
if (!QString(NETRootInfo(QX11Info::connection(), NET::SupportingWMCheck).wmName()).isEmpty())
{
qDebug() << "Window Manager started";
mWmStarted = true;
if (mWaitLoop->isRunning())
mWaitLoop->exit();
}
}
if (!mTrayStarted && QSystemTrayIcon::isSystemTrayAvailable() && mWaitLoop)
{
qDebug() << "System Tray started";
mTrayStarted = true;
if (mWaitLoop->isRunning())
mWaitLoop->exit();
// window manager and system tray have started
qApp->removeNativeEventFilter(this);
}
return false;
}
void lxqt_setenv(const char *env, const QByteArray &value)
{
wordexp_t p;
wordexp(value, &p, 0);
if (p.we_wordc == 1)
{
qDebug() << "Environment variable" << env << "=" << p.we_wordv[0];
qputenv(env, p.we_wordv[0]);
}
else
{
qWarning() << "Error expanding environment variable" << env << "=" << value;
qputenv(env, value);
}
wordfree(&p);
}
void lxqt_setenv_prepend(const char *env, const QByteArray &value, const QByteArray &separator)
{
QByteArray orig(qgetenv(env));
orig = orig.prepend(separator);
orig = orig.prepend(value);
qDebug() << "Setting special" << env << " variable:" << orig;
lxqt_setenv(env, orig);
}
LXQtModule::LXQtModule(const XdgDesktopFile& file, QObject* parent) :
QProcess(parent),
file(file),
fileName(QFileInfo(file.fileName()).fileName()),
mIsTerminating(false)
{
connect(this, SIGNAL(stateChanged(QProcess::ProcessState)), SLOT(updateState(QProcess::ProcessState)));
}
void LXQtModule::start()
{
mIsTerminating = false;
QStringList args = file.expandExecString();
QString command = args.takeFirst();
QProcess::start(command, args);
}
void LXQtModule::terminate()
{
mIsTerminating = true;
QProcess::terminate();
}
bool LXQtModule::isTerminating()
{
return mIsTerminating;
}
void LXQtModule::updateState(QProcess::ProcessState newState)
{
if (newState != QProcess::Starting)
emit moduleStateChanged(fileName, (newState == QProcess::Running));
}
<|endoftext|>
|
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* https://lxqt.org/
*
* Copyright: 2010-2011 LXQt team
* Authors:
* Petr Vanek <petr@scribus.info>
* Hong Jen Yee (PCMan) <pcman.tw@gmail.com>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "lxqtmodman.h"
#include <LXQt/Settings>
#include <XdgAutoStart>
#include <XdgDirs>
#include <unistd.h>
#include <QCoreApplication>
#include <QMessageBox>
#include <QSystemTrayIcon>
#include <QFileInfo>
#include <QFile>
#include <QDir>
#include <QFileSystemWatcher>
#include <QDateTime>
#include "wmselectdialog.h"
#include "windowmanager.h"
#include <wordexp.h>
#include "log.h"
#include <KWindowSystem/KWindowSystem>
#include <KWindowSystem/netwm.h>
#include <QX11Info>
#define MAX_CRASHES_PER_APP 5
using namespace LXQt;
/**
* @brief the constructor, needs a valid modules.conf
*/
LXQtModuleManager::LXQtModuleManager(QObject* parent)
: QObject(parent),
mWmProcess(new QProcess(this)),
mThemeWatcher(new QFileSystemWatcher(this)),
mWmStarted(false),
mTrayStarted(false),
mWaitLoop(NULL)
{
connect(mThemeWatcher, SIGNAL(directoryChanged(QString)), SLOT(themeFolderChanged(QString)));
connect(LXQt::Settings::globalSettings(), SIGNAL(lxqtThemeChanged()), SLOT(themeChanged()));
qApp->installNativeEventFilter(this);
}
void LXQtModuleManager::setWindowManager(const QString & windowManager)
{
mWindowManager = windowManager;
}
void LXQtModuleManager::startup(LXQt::Settings& s)
{
// The lxqt-confupdate can update the settings of the WM, so run it first.
startConfUpdate();
// Start window manager
startWm(&s);
startAutostartApps();
QStringList paths;
paths << XdgDirs::dataHome(false);
paths << XdgDirs::dataDirs();
for(const QString &path : qAsConst(paths))
{
QFileInfo fi(QString("%1/lxqt/themes").arg(path));
if (fi.exists())
mThemeWatcher->addPath(fi.absoluteFilePath());
}
themeChanged();
}
void LXQtModuleManager::startAutostartApps()
{
// XDG autostart
const XdgDesktopFileList fileList = XdgAutoStart::desktopFileList();
QList<const XdgDesktopFile*> trayApps;
for (XdgDesktopFileList::const_iterator i = fileList.constBegin(); i != fileList.constEnd(); ++i)
{
if (i->value("X-LXQt-Need-Tray", false).toBool())
trayApps.append(&(*i));
else
{
startProcess(*i);
qCDebug(SESSION) << "start" << i->fileName();
}
}
if (!trayApps.isEmpty())
{
mTrayStarted = QSystemTrayIcon::isSystemTrayAvailable();
if(!mTrayStarted)
{
QEventLoop waitLoop;
mWaitLoop = &waitLoop;
// add a timeout to avoid infinite blocking if a WM fail to execute.
QTimer::singleShot(60 * 1000, &waitLoop, SLOT(quit()));
waitLoop.exec();
mWaitLoop = NULL;
}
for (const XdgDesktopFile* const f : qAsConst(trayApps))
{
qCDebug(SESSION) << "start tray app" << f->fileName();
startProcess(*f);
}
}
}
void LXQtModuleManager::themeFolderChanged(const QString& /*path*/)
{
QString newTheme;
if (!QFileInfo::exists(mCurrentThemePath))
{
const QList<LXQtTheme> &allThemes = lxqtTheme.allThemes();
if (!allThemes.isEmpty())
newTheme = allThemes[0].name();
else
return;
}
else
newTheme = lxqtTheme.currentTheme().name();
LXQt::Settings settings("lxqt");
if (newTheme == settings.value("theme"))
{
// force the same theme to be updated
settings.setValue("__theme_updated__", QDateTime::currentMSecsSinceEpoch());
}
else
settings.setValue("theme", newTheme);
sync();
}
void LXQtModuleManager::themeChanged()
{
if (!mCurrentThemePath.isEmpty())
mThemeWatcher->removePath(mCurrentThemePath);
if (lxqtTheme.currentTheme().isValid())
{
mCurrentThemePath = lxqtTheme.currentTheme().path();
mThemeWatcher->addPath(mCurrentThemePath);
}
}
void LXQtModuleManager::startWm(LXQt::Settings *settings)
{
// if the WM is active do not run WM.
// all window managers must set their name according to the spec
if (!QString(NETRootInfo(QX11Info::connection(), NET::SupportingWMCheck).wmName()).isEmpty())
{
mWmStarted = true;
return;
}
if (mWindowManager.isEmpty())
{
mWindowManager = settings->value("window_manager").toString();
}
// If previuos WM was removed, we show dialog.
if (mWindowManager.isEmpty() || ! findProgram(mWindowManager.split(' ')[0]))
{
mWindowManager = showWmSelectDialog();
settings->setValue("window_manager", mWindowManager);
settings->sync();
}
if (QFileInfo(mWindowManager).baseName() == "openbox")
{
// Default settings of openbox are copied by lxqt-common/startlxqt.in
QString openboxSettingsPath = XdgDirs::configHome() + "/openbox/lxqt-rc.xml";
QStringList args;
if(QFileInfo::exists(openboxSettingsPath))
args << "--config-file" << openboxSettingsPath;
mWmProcess->start(mWindowManager, args);
}
else
mWmProcess->start(mWindowManager);
// other autostart apps will be handled after the WM becomes available
// Wait until the WM loads
QEventLoop waitLoop;
mWaitLoop = &waitLoop;
// add a timeout to avoid infinite blocking if a WM fail to execute.
QTimer::singleShot(30 * 1000, &waitLoop, SLOT(quit()));
waitLoop.exec();
mWaitLoop = NULL;
// FIXME: blocking is a bad idea. We need to start as many apps as possible and
// only wait for the start of WM when it's absolutely needed.
// Maybe we can add a X-Wait-WM=true key in the desktop entry file?
}
void LXQtModuleManager::startProcess(const XdgDesktopFile& file)
{
if (!file.value("X-LXQt-Module", false).toBool())
{
file.startDetached();
return;
}
QStringList args = file.expandExecString();
if (args.isEmpty())
{
qCWarning(SESSION) << "Wrong desktop file" << file.fileName();
return;
}
LXQtModule* proc = new LXQtModule(file, this);
connect(proc, SIGNAL(moduleStateChanged(QString,bool)), this, SIGNAL(moduleStateChanged(QString,bool)));
proc->start();
QString name = QFileInfo(file.fileName()).fileName();
mNameMap[name] = proc;
connect(proc, SIGNAL(finished(int, QProcess::ExitStatus)),
this, SLOT(restartModules(int, QProcess::ExitStatus)));
}
void LXQtModuleManager::startProcess(const QString& name)
{
if (!mNameMap.contains(name))
{
const auto files = XdgAutoStart::desktopFileList(false);
for (const XdgDesktopFile& file : files)
{
if (QFileInfo(file.fileName()).fileName() == name)
{
startProcess(file);
return;
}
}
}
}
void LXQtModuleManager::stopProcess(const QString& name)
{
if (mNameMap.contains(name))
mNameMap[name]->terminate();
}
QStringList LXQtModuleManager::listModules() const
{
return QStringList(mNameMap.keys());
}
void LXQtModuleManager::startConfUpdate()
{
XdgDesktopFile desktop(XdgDesktopFile::ApplicationType, ":lxqt-confupdate", "lxqt-confupdate --watch");
desktop.setValue("Name", "LXQt config updater");
desktop.setValue("X-LXQt-Module", true);
startProcess(desktop);
}
void LXQtModuleManager::restartModules(int /*exitCode*/, QProcess::ExitStatus exitStatus)
{
LXQtModule* proc = qobject_cast<LXQtModule*>(sender());
if (nullptr == proc) {
qCWarning(SESSION) << "Got an invalid (null) module to restart. Ignoring it";
return;
}
if (!proc->isTerminating())
{
QString procName = proc->file.name();
switch (exitStatus)
{
case QProcess::NormalExit:
qCDebug(SESSION) << "Process" << procName << "(" << proc << ") exited correctly.";
break;
case QProcess::CrashExit:
{
qCDebug(SESSION) << "Process" << procName << "(" << proc << ") has to be restarted";
time_t now = time(NULL);
mCrashReport[proc].prepend(now);
while (now - mCrashReport[proc].back() > 60)
mCrashReport[proc].pop_back();
if (mCrashReport[proc].length() >= MAX_CRASHES_PER_APP)
{
QMessageBox::warning(0, tr("Crash Report"),
tr("<b>%1</b> crashed too many times. Its autorestart has been disabled until next login.").arg(procName));
}
else
{
proc->start();
return;
}
break;
}
}
}
mNameMap.remove(proc->fileName);
proc->deleteLater();
}
LXQtModuleManager::~LXQtModuleManager()
{
qApp->removeNativeEventFilter(this);
// We disconnect the finished signal before deleting the process. We do
// this to prevent a crash that results from a state change signal being
// emmited while deleting a crashing module.
// If the module is still connect restartModules will be called with a
// invalid sender.
ModulesMapIterator i(mNameMap);
while (i.hasNext())
{
i.next();
auto p = i.value();
disconnect(p, SIGNAL(finished(int, QProcess::ExitStatus)), 0, 0);
delete p;
mNameMap[i.key()] = nullptr;
}
delete mWmProcess;
}
/**
* @brief this logs us out by terminating our session
**/
void LXQtModuleManager::logout(bool doExit)
{
// modules
ModulesMapIterator i(mNameMap);
while (i.hasNext())
{
i.next();
qCDebug(SESSION) << "Module logout" << i.key();
LXQtModule* p = i.value();
p->terminate();
}
i.toFront();
while (i.hasNext())
{
i.next();
LXQtModule* p = i.value();
if (p->state() != QProcess::NotRunning && !p->waitForFinished(2000))
{
qCWarning(SESSION) << QString("Module '%1' won't terminate ... killing.").arg(i.key());
p->kill();
}
}
mWmProcess->terminate();
if (mWmProcess->state() != QProcess::NotRunning && !mWmProcess->waitForFinished(2000))
{
qCWarning(SESSION) << QString("Window Manager won't terminate ... killing.");
mWmProcess->kill();
}
if (doExit)
QCoreApplication::exit(0);
}
QString LXQtModuleManager::showWmSelectDialog()
{
WindowManagerList availableWM = getWindowManagerList(true);
if (availableWM.count() == 1)
return availableWM.at(0).command;
WmSelectDialog dlg(availableWM);
dlg.exec();
return dlg.windowManager();
}
void LXQtModuleManager::resetCrashReport()
{
mCrashReport.clear();
}
bool LXQtModuleManager::nativeEventFilter(const QByteArray & eventType, void * /*message*/, long * /*result*/)
{
if (eventType != "xcb_generic_event_t") // We only want to handle XCB events
return false;
if(!mWmStarted && mWaitLoop)
{
// all window managers must set their name according to the spec
if (!QString(NETRootInfo(QX11Info::connection(), NET::SupportingWMCheck).wmName()).isEmpty())
{
qCDebug(SESSION) << "Window Manager started";
mWmStarted = true;
if (mWaitLoop->isRunning())
mWaitLoop->exit();
}
}
if (!mTrayStarted && QSystemTrayIcon::isSystemTrayAvailable() && mWaitLoop)
{
qCDebug(SESSION) << "System Tray started";
mTrayStarted = true;
if (mWaitLoop->isRunning())
mWaitLoop->exit();
// window manager and system tray have started
qApp->removeNativeEventFilter(this);
}
return false;
}
void lxqt_setenv(const char *env, const QByteArray &value)
{
wordexp_t p;
wordexp(value, &p, 0);
if (p.we_wordc == 1)
{
qCDebug(SESSION) << "Environment variable" << env << "=" << p.we_wordv[0];
qputenv(env, p.we_wordv[0]);
}
else
{
qCWarning(SESSION) << "Error expanding environment variable" << env << "=" << value;
qputenv(env, value);
}
wordfree(&p);
}
void lxqt_setenv_prepend(const char *env, const QByteArray &value, const QByteArray &separator)
{
QByteArray orig(qgetenv(env));
orig = orig.prepend(separator);
orig = orig.prepend(value);
qCDebug(SESSION) << "Setting special" << env << " variable:" << orig;
lxqt_setenv(env, orig);
}
LXQtModule::LXQtModule(const XdgDesktopFile& file, QObject* parent) :
QProcess(parent),
file(file),
fileName(QFileInfo(file.fileName()).fileName()),
mIsTerminating(false)
{
connect(this, SIGNAL(stateChanged(QProcess::ProcessState)), SLOT(updateState(QProcess::ProcessState)));
}
void LXQtModule::start()
{
mIsTerminating = false;
QStringList args = file.expandExecString();
QString command = args.takeFirst();
QProcess::start(command, args);
}
void LXQtModule::terminate()
{
mIsTerminating = true;
QProcess::terminate();
}
bool LXQtModule::isTerminating()
{
return mIsTerminating;
}
void LXQtModule::updateState(QProcess::ProcessState newState)
{
if (newState != QProcess::Starting)
emit moduleStateChanged(fileName, (newState == QProcess::Running));
}
<commit_msg>Fix comment link to startlxqt<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* https://lxqt.org/
*
* Copyright: 2010-2011 LXQt team
* Authors:
* Petr Vanek <petr@scribus.info>
* Hong Jen Yee (PCMan) <pcman.tw@gmail.com>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "lxqtmodman.h"
#include <LXQt/Settings>
#include <XdgAutoStart>
#include <XdgDirs>
#include <unistd.h>
#include <QCoreApplication>
#include <QMessageBox>
#include <QSystemTrayIcon>
#include <QFileInfo>
#include <QFile>
#include <QDir>
#include <QFileSystemWatcher>
#include <QDateTime>
#include "wmselectdialog.h"
#include "windowmanager.h"
#include <wordexp.h>
#include "log.h"
#include <KWindowSystem/KWindowSystem>
#include <KWindowSystem/netwm.h>
#include <QX11Info>
#define MAX_CRASHES_PER_APP 5
using namespace LXQt;
/**
* @brief the constructor, needs a valid modules.conf
*/
LXQtModuleManager::LXQtModuleManager(QObject* parent)
: QObject(parent),
mWmProcess(new QProcess(this)),
mThemeWatcher(new QFileSystemWatcher(this)),
mWmStarted(false),
mTrayStarted(false),
mWaitLoop(NULL)
{
connect(mThemeWatcher, SIGNAL(directoryChanged(QString)), SLOT(themeFolderChanged(QString)));
connect(LXQt::Settings::globalSettings(), SIGNAL(lxqtThemeChanged()), SLOT(themeChanged()));
qApp->installNativeEventFilter(this);
}
void LXQtModuleManager::setWindowManager(const QString & windowManager)
{
mWindowManager = windowManager;
}
void LXQtModuleManager::startup(LXQt::Settings& s)
{
// The lxqt-confupdate can update the settings of the WM, so run it first.
startConfUpdate();
// Start window manager
startWm(&s);
startAutostartApps();
QStringList paths;
paths << XdgDirs::dataHome(false);
paths << XdgDirs::dataDirs();
for(const QString &path : qAsConst(paths))
{
QFileInfo fi(QString("%1/lxqt/themes").arg(path));
if (fi.exists())
mThemeWatcher->addPath(fi.absoluteFilePath());
}
themeChanged();
}
void LXQtModuleManager::startAutostartApps()
{
// XDG autostart
const XdgDesktopFileList fileList = XdgAutoStart::desktopFileList();
QList<const XdgDesktopFile*> trayApps;
for (XdgDesktopFileList::const_iterator i = fileList.constBegin(); i != fileList.constEnd(); ++i)
{
if (i->value("X-LXQt-Need-Tray", false).toBool())
trayApps.append(&(*i));
else
{
startProcess(*i);
qCDebug(SESSION) << "start" << i->fileName();
}
}
if (!trayApps.isEmpty())
{
mTrayStarted = QSystemTrayIcon::isSystemTrayAvailable();
if(!mTrayStarted)
{
QEventLoop waitLoop;
mWaitLoop = &waitLoop;
// add a timeout to avoid infinite blocking if a WM fail to execute.
QTimer::singleShot(60 * 1000, &waitLoop, SLOT(quit()));
waitLoop.exec();
mWaitLoop = NULL;
}
for (const XdgDesktopFile* const f : qAsConst(trayApps))
{
qCDebug(SESSION) << "start tray app" << f->fileName();
startProcess(*f);
}
}
}
void LXQtModuleManager::themeFolderChanged(const QString& /*path*/)
{
QString newTheme;
if (!QFileInfo::exists(mCurrentThemePath))
{
const QList<LXQtTheme> &allThemes = lxqtTheme.allThemes();
if (!allThemes.isEmpty())
newTheme = allThemes[0].name();
else
return;
}
else
newTheme = lxqtTheme.currentTheme().name();
LXQt::Settings settings("lxqt");
if (newTheme == settings.value("theme"))
{
// force the same theme to be updated
settings.setValue("__theme_updated__", QDateTime::currentMSecsSinceEpoch());
}
else
settings.setValue("theme", newTheme);
sync();
}
void LXQtModuleManager::themeChanged()
{
if (!mCurrentThemePath.isEmpty())
mThemeWatcher->removePath(mCurrentThemePath);
if (lxqtTheme.currentTheme().isValid())
{
mCurrentThemePath = lxqtTheme.currentTheme().path();
mThemeWatcher->addPath(mCurrentThemePath);
}
}
void LXQtModuleManager::startWm(LXQt::Settings *settings)
{
// if the WM is active do not run WM.
// all window managers must set their name according to the spec
if (!QString(NETRootInfo(QX11Info::connection(), NET::SupportingWMCheck).wmName()).isEmpty())
{
mWmStarted = true;
return;
}
if (mWindowManager.isEmpty())
{
mWindowManager = settings->value("window_manager").toString();
}
// If previuos WM was removed, we show dialog.
if (mWindowManager.isEmpty() || ! findProgram(mWindowManager.split(' ')[0]))
{
mWindowManager = showWmSelectDialog();
settings->setValue("window_manager", mWindowManager);
settings->sync();
}
if (QFileInfo(mWindowManager).baseName() == "openbox")
{
// Default settings of openbox are copied by lxqt-session/startlxqt.in
QString openboxSettingsPath = XdgDirs::configHome() + "/openbox/lxqt-rc.xml";
QStringList args;
if(QFileInfo::exists(openboxSettingsPath))
args << "--config-file" << openboxSettingsPath;
mWmProcess->start(mWindowManager, args);
}
else
mWmProcess->start(mWindowManager);
// other autostart apps will be handled after the WM becomes available
// Wait until the WM loads
QEventLoop waitLoop;
mWaitLoop = &waitLoop;
// add a timeout to avoid infinite blocking if a WM fail to execute.
QTimer::singleShot(30 * 1000, &waitLoop, SLOT(quit()));
waitLoop.exec();
mWaitLoop = NULL;
// FIXME: blocking is a bad idea. We need to start as many apps as possible and
// only wait for the start of WM when it's absolutely needed.
// Maybe we can add a X-Wait-WM=true key in the desktop entry file?
}
void LXQtModuleManager::startProcess(const XdgDesktopFile& file)
{
if (!file.value("X-LXQt-Module", false).toBool())
{
file.startDetached();
return;
}
QStringList args = file.expandExecString();
if (args.isEmpty())
{
qCWarning(SESSION) << "Wrong desktop file" << file.fileName();
return;
}
LXQtModule* proc = new LXQtModule(file, this);
connect(proc, SIGNAL(moduleStateChanged(QString,bool)), this, SIGNAL(moduleStateChanged(QString,bool)));
proc->start();
QString name = QFileInfo(file.fileName()).fileName();
mNameMap[name] = proc;
connect(proc, SIGNAL(finished(int, QProcess::ExitStatus)),
this, SLOT(restartModules(int, QProcess::ExitStatus)));
}
void LXQtModuleManager::startProcess(const QString& name)
{
if (!mNameMap.contains(name))
{
const auto files = XdgAutoStart::desktopFileList(false);
for (const XdgDesktopFile& file : files)
{
if (QFileInfo(file.fileName()).fileName() == name)
{
startProcess(file);
return;
}
}
}
}
void LXQtModuleManager::stopProcess(const QString& name)
{
if (mNameMap.contains(name))
mNameMap[name]->terminate();
}
QStringList LXQtModuleManager::listModules() const
{
return QStringList(mNameMap.keys());
}
void LXQtModuleManager::startConfUpdate()
{
XdgDesktopFile desktop(XdgDesktopFile::ApplicationType, ":lxqt-confupdate", "lxqt-confupdate --watch");
desktop.setValue("Name", "LXQt config updater");
desktop.setValue("X-LXQt-Module", true);
startProcess(desktop);
}
void LXQtModuleManager::restartModules(int /*exitCode*/, QProcess::ExitStatus exitStatus)
{
LXQtModule* proc = qobject_cast<LXQtModule*>(sender());
if (nullptr == proc) {
qCWarning(SESSION) << "Got an invalid (null) module to restart. Ignoring it";
return;
}
if (!proc->isTerminating())
{
QString procName = proc->file.name();
switch (exitStatus)
{
case QProcess::NormalExit:
qCDebug(SESSION) << "Process" << procName << "(" << proc << ") exited correctly.";
break;
case QProcess::CrashExit:
{
qCDebug(SESSION) << "Process" << procName << "(" << proc << ") has to be restarted";
time_t now = time(NULL);
mCrashReport[proc].prepend(now);
while (now - mCrashReport[proc].back() > 60)
mCrashReport[proc].pop_back();
if (mCrashReport[proc].length() >= MAX_CRASHES_PER_APP)
{
QMessageBox::warning(0, tr("Crash Report"),
tr("<b>%1</b> crashed too many times. Its autorestart has been disabled until next login.").arg(procName));
}
else
{
proc->start();
return;
}
break;
}
}
}
mNameMap.remove(proc->fileName);
proc->deleteLater();
}
LXQtModuleManager::~LXQtModuleManager()
{
qApp->removeNativeEventFilter(this);
// We disconnect the finished signal before deleting the process. We do
// this to prevent a crash that results from a state change signal being
// emmited while deleting a crashing module.
// If the module is still connect restartModules will be called with a
// invalid sender.
ModulesMapIterator i(mNameMap);
while (i.hasNext())
{
i.next();
auto p = i.value();
disconnect(p, SIGNAL(finished(int, QProcess::ExitStatus)), 0, 0);
delete p;
mNameMap[i.key()] = nullptr;
}
delete mWmProcess;
}
/**
* @brief this logs us out by terminating our session
**/
void LXQtModuleManager::logout(bool doExit)
{
// modules
ModulesMapIterator i(mNameMap);
while (i.hasNext())
{
i.next();
qCDebug(SESSION) << "Module logout" << i.key();
LXQtModule* p = i.value();
p->terminate();
}
i.toFront();
while (i.hasNext())
{
i.next();
LXQtModule* p = i.value();
if (p->state() != QProcess::NotRunning && !p->waitForFinished(2000))
{
qCWarning(SESSION) << QString("Module '%1' won't terminate ... killing.").arg(i.key());
p->kill();
}
}
mWmProcess->terminate();
if (mWmProcess->state() != QProcess::NotRunning && !mWmProcess->waitForFinished(2000))
{
qCWarning(SESSION) << QString("Window Manager won't terminate ... killing.");
mWmProcess->kill();
}
if (doExit)
QCoreApplication::exit(0);
}
QString LXQtModuleManager::showWmSelectDialog()
{
WindowManagerList availableWM = getWindowManagerList(true);
if (availableWM.count() == 1)
return availableWM.at(0).command;
WmSelectDialog dlg(availableWM);
dlg.exec();
return dlg.windowManager();
}
void LXQtModuleManager::resetCrashReport()
{
mCrashReport.clear();
}
bool LXQtModuleManager::nativeEventFilter(const QByteArray & eventType, void * /*message*/, long * /*result*/)
{
if (eventType != "xcb_generic_event_t") // We only want to handle XCB events
return false;
if(!mWmStarted && mWaitLoop)
{
// all window managers must set their name according to the spec
if (!QString(NETRootInfo(QX11Info::connection(), NET::SupportingWMCheck).wmName()).isEmpty())
{
qCDebug(SESSION) << "Window Manager started";
mWmStarted = true;
if (mWaitLoop->isRunning())
mWaitLoop->exit();
}
}
if (!mTrayStarted && QSystemTrayIcon::isSystemTrayAvailable() && mWaitLoop)
{
qCDebug(SESSION) << "System Tray started";
mTrayStarted = true;
if (mWaitLoop->isRunning())
mWaitLoop->exit();
// window manager and system tray have started
qApp->removeNativeEventFilter(this);
}
return false;
}
void lxqt_setenv(const char *env, const QByteArray &value)
{
wordexp_t p;
wordexp(value, &p, 0);
if (p.we_wordc == 1)
{
qCDebug(SESSION) << "Environment variable" << env << "=" << p.we_wordv[0];
qputenv(env, p.we_wordv[0]);
}
else
{
qCWarning(SESSION) << "Error expanding environment variable" << env << "=" << value;
qputenv(env, value);
}
wordfree(&p);
}
void lxqt_setenv_prepend(const char *env, const QByteArray &value, const QByteArray &separator)
{
QByteArray orig(qgetenv(env));
orig = orig.prepend(separator);
orig = orig.prepend(value);
qCDebug(SESSION) << "Setting special" << env << " variable:" << orig;
lxqt_setenv(env, orig);
}
LXQtModule::LXQtModule(const XdgDesktopFile& file, QObject* parent) :
QProcess(parent),
file(file),
fileName(QFileInfo(file.fileName()).fileName()),
mIsTerminating(false)
{
connect(this, SIGNAL(stateChanged(QProcess::ProcessState)), SLOT(updateState(QProcess::ProcessState)));
}
void LXQtModule::start()
{
mIsTerminating = false;
QStringList args = file.expandExecString();
QString command = args.takeFirst();
QProcess::start(command, args);
}
void LXQtModule::terminate()
{
mIsTerminating = true;
QProcess::terminate();
}
bool LXQtModule::isTerminating()
{
return mIsTerminating;
}
void LXQtModule::updateState(QProcess::ProcessState newState)
{
if (newState != QProcess::Starting)
emit moduleStateChanged(fileName, (newState == QProcess::Running));
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashMatrix.
*
* 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 <unordered_map>
#include "matrix_worker_thread.h"
#include "sparse_matrix.h"
namespace fm
{
static const int MAX_PENDING_IOS = 32;
class matrix_io_callback: public safs::callback
{
typedef std::unordered_map<char *, compute_task::ptr> task_map_t;
task_map_t tasks;
size_t pending_size;
public:
matrix_io_callback() {
pending_size = 0;
}
~matrix_io_callback() {
assert(pending_size == 0);
}
size_t get_pending_size() const {
return pending_size;
}
size_t get_pending_ios() const {
return tasks.size();
}
int invoke(safs::io_request *reqs[], int num);
void add_task(const safs::io_request &req, compute_task::ptr task) {
tasks.insert(task_map_t::value_type(req.get_buf(), task));
pending_size += req.get_size();
}
};
int matrix_io_callback::invoke(safs::io_request *reqs[], int num)
{
for (int i = 0; i < num; i++) {
pending_size -= reqs[i]->get_size();
task_map_t::const_iterator it = tasks.find(reqs[i]->get_buf());
it->second->run(reqs[i]->get_buf(), reqs[i]->get_size());
// Once a task is complete, we can remove it from the hashtable.
tasks.erase(it);
}
return 0;
}
bool matrix_worker_thread::get_next_io(matrix_io &io)
{
if (this_io_gen->has_next_io()) {
io = this_io_gen->get_next_io();
return io.is_valid();
}
else {
for (size_t i = 0; i < io_gens.size(); i++) {
if (io_gens[steal_io_id]->has_next_io()) {
io = io_gens[steal_io_id]->steal_io();
if (io.is_valid())
return true;
}
steal_io_id = (steal_io_id + 1) % io_gens.size();
}
return false;
}
}
void matrix_worker_thread::run()
{
matrix_io_callback *cb = new matrix_io_callback();
io->set_callback(cb);
matrix_io mio;
while (get_next_io(mio)) {
compute_task::ptr task = tcreator->create(mio);
safs::io_request req = task->get_request();
cb->add_task(req, task);
io->access(&req, 1);
// TODO it might not be good to have a fixed number of pending I/O.
// We need to control memory consumption for the buffers.
while (io->num_pending_ios() > MAX_PENDING_IOS)
io->wait4complete(1);
}
io->wait4complete(io->num_pending_ios());
stop();
}
}
<commit_msg>[Matrix]: free callback object.<commit_after>/*
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashMatrix.
*
* 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 <unordered_map>
#include "matrix_worker_thread.h"
#include "sparse_matrix.h"
namespace fm
{
static const int MAX_PENDING_IOS = 32;
class matrix_io_callback: public safs::callback
{
typedef std::unordered_map<char *, compute_task::ptr> task_map_t;
task_map_t tasks;
size_t pending_size;
public:
matrix_io_callback() {
pending_size = 0;
}
~matrix_io_callback() {
assert(pending_size == 0);
}
size_t get_pending_size() const {
return pending_size;
}
size_t get_pending_ios() const {
return tasks.size();
}
int invoke(safs::io_request *reqs[], int num);
void add_task(const safs::io_request &req, compute_task::ptr task) {
tasks.insert(task_map_t::value_type(req.get_buf(), task));
pending_size += req.get_size();
}
};
int matrix_io_callback::invoke(safs::io_request *reqs[], int num)
{
for (int i = 0; i < num; i++) {
pending_size -= reqs[i]->get_size();
task_map_t::const_iterator it = tasks.find(reqs[i]->get_buf());
it->second->run(reqs[i]->get_buf(), reqs[i]->get_size());
// Once a task is complete, we can remove it from the hashtable.
tasks.erase(it);
}
return 0;
}
bool matrix_worker_thread::get_next_io(matrix_io &io)
{
if (this_io_gen->has_next_io()) {
io = this_io_gen->get_next_io();
return io.is_valid();
}
else {
for (size_t i = 0; i < io_gens.size(); i++) {
if (io_gens[steal_io_id]->has_next_io()) {
io = io_gens[steal_io_id]->steal_io();
if (io.is_valid())
return true;
}
steal_io_id = (steal_io_id + 1) % io_gens.size();
}
return false;
}
}
void matrix_worker_thread::run()
{
matrix_io_callback *cb = new matrix_io_callback();
io->set_callback(cb);
matrix_io mio;
while (get_next_io(mio)) {
compute_task::ptr task = tcreator->create(mio);
safs::io_request req = task->get_request();
cb->add_task(req, task);
io->access(&req, 1);
// TODO it might not be good to have a fixed number of pending I/O.
// We need to control memory consumption for the buffers.
while (io->num_pending_ios() > MAX_PENDING_IOS)
io->wait4complete(1);
}
io->wait4complete(io->num_pending_ios());
assert(io->num_pending_ios() == 0);
stop();
delete cb;
}
}
<|endoftext|>
|
<commit_before><commit_msg>Landing patch from Thiago Farina:<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/options/passwords_page_view.h"
#include "app/l10n_util.h"
#include "base/string_util.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "grit/generated_resources.h"
#include "views/background.h"
#include "views/controls/button/native_button.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"
using views::ColumnSet;
using views::GridLayout;
///////////////////////////////////////////////////////////////////////////////
// MultiLabelButtons
MultiLabelButtons::MultiLabelButtons(views::ButtonListener* listener,
const std::wstring& label,
const std::wstring& alt_label)
: NativeButton(listener, label),
label_(label),
alt_label_(alt_label),
pref_size_(-1, -1) {
}
gfx::Size MultiLabelButtons::GetPreferredSize() {
if (pref_size_.width() == -1 && pref_size_.height() == -1) {
// Let's compute our preferred size.
std::wstring current_label = label();
SetLabel(label_);
pref_size_ = NativeButton::GetPreferredSize();
SetLabel(alt_label_);
gfx::Size alt_pref_size = NativeButton::GetPreferredSize();
// Revert to the original label.
SetLabel(current_label);
pref_size_.SetSize(std::max(pref_size_.width(), alt_pref_size.width()),
std::max(pref_size_.height(), alt_pref_size.height()));
}
return gfx::Size(pref_size_.width(), pref_size_.height());
}
///////////////////////////////////////////////////////////////////////////////
// PasswordsTableModel, public
PasswordsTableModel::PasswordsTableModel(Profile* profile)
: observer_(NULL),
row_count_observer_(NULL),
pending_login_query_(NULL),
saved_signons_cleanup_(&saved_signons_),
profile_(profile) {
DCHECK(profile && profile->GetWebDataService(Profile::EXPLICIT_ACCESS));
}
PasswordsTableModel::~PasswordsTableModel() {
CancelLoginsQuery();
}
int PasswordsTableModel::RowCount() {
return static_cast<int>(saved_signons_.size());
}
std::wstring PasswordsTableModel::GetText(int row,
int col_id) {
switch (col_id) {
case IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN: { // Site.
const std::wstring& url = saved_signons_[row]->display_url.display_url();
// Force URL to have LTR directionality.
if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) {
std::wstring localized_url = url;
l10n_util::WrapStringWithLTRFormatting(&localized_url);
return localized_url;
}
return url;
}
case IDS_PASSWORDS_PAGE_VIEW_USERNAME_COLUMN: { // Username.
std::wstring username = GetPasswordFormAt(row)->username_value;
l10n_util::AdjustStringForLocaleDirection(username, &username);
return username;
}
default:
NOTREACHED() << "Invalid column.";
return std::wstring();
}
}
int PasswordsTableModel::CompareValues(int row1, int row2,
int column_id) {
if (column_id == IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN) {
return saved_signons_[row1]->display_url.Compare(
saved_signons_[row2]->display_url, GetCollator());
}
return TableModel::CompareValues(row1, row2, column_id);
}
void PasswordsTableModel::SetObserver(
views::TableModelObserver* observer) {
observer_ = observer;
}
void PasswordsTableModel::GetAllSavedLoginsForProfile() {
DCHECK(!pending_login_query_);
pending_login_query_ = web_data_service()->GetAllAutofillableLogins(this);
}
void PasswordsTableModel::OnWebDataServiceRequestDone(
WebDataService::Handle h,
const WDTypedResult* result) {
DCHECK_EQ(pending_login_query_, h);
pending_login_query_ = NULL;
if (!result)
return;
DCHECK(result->GetType() == PASSWORD_RESULT);
// Get the result from the database into a useable form.
const WDResult<std::vector<PasswordForm*> >* r =
static_cast<const WDResult<std::vector<PasswordForm*> >*>(result);
std::vector<PasswordForm*> rows = r->GetValue();
STLDeleteElements<PasswordRows>(&saved_signons_);
saved_signons_.resize(rows.size(), NULL);
std::wstring languages =
profile_->GetPrefs()->GetString(prefs::kAcceptLanguages);
for (size_t i = 0; i < rows.size(); ++i) {
saved_signons_[i] = new PasswordRow(
gfx::SortedDisplayURL(rows[i]->origin, languages), rows[i]);
}
if (observer_)
observer_->OnModelChanged();
if (row_count_observer_)
row_count_observer_->OnRowCountChanged(RowCount());
}
PasswordForm* PasswordsTableModel::GetPasswordFormAt(int row) {
DCHECK(row >= 0 && row < RowCount());
return saved_signons_[row]->form.get();
}
void PasswordsTableModel::ForgetAndRemoveSignon(int row) {
DCHECK(row >= 0 && row < RowCount());
PasswordRows::iterator target_iter = saved_signons_.begin() + row;
// Remove from DB, memory, and vector.
PasswordRow* password_row = *target_iter;
web_data_service()->RemoveLogin(*(password_row->form.get()));
delete password_row;
saved_signons_.erase(target_iter);
if (observer_)
observer_->OnItemsRemoved(row, 1);
if (row_count_observer_)
row_count_observer_->OnRowCountChanged(RowCount());
}
void PasswordsTableModel::ForgetAndRemoveAllSignons() {
PasswordRows::iterator iter = saved_signons_.begin();
while (iter != saved_signons_.end()) {
// Remove from DB, memory, and vector.
PasswordRow* row = *iter;
web_data_service()->RemoveLogin(*(row->form.get()));
delete row;
iter = saved_signons_.erase(iter);
}
if (observer_)
observer_->OnModelChanged();
if (row_count_observer_)
row_count_observer_->OnRowCountChanged(RowCount());
}
///////////////////////////////////////////////////////////////////////////////
// PasswordsTableModel, private
void PasswordsTableModel::CancelLoginsQuery() {
if (pending_login_query_) {
web_data_service()->CancelRequest(pending_login_query_);
pending_login_query_ = NULL;
}
}
///////////////////////////////////////////////////////////////////////////////
// PasswordsPageView, public
PasswordsPageView::PasswordsPageView(Profile* profile)
: OptionsPageView(profile),
show_button_(
this,
l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON),
l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON)),
remove_button_(this, l10n_util::GetString(
IDS_PASSWORDS_PAGE_VIEW_REMOVE_BUTTON)),
remove_all_button_(this, l10n_util::GetString(
IDS_PASSWORDS_PAGE_VIEW_REMOVE_ALL_BUTTON)),
table_model_(profile),
table_view_(NULL) {
}
void PasswordsPageView::OnSelectionChanged() {
bool has_selection = table_view_->SelectedRowCount() > 0;
remove_button_.SetEnabled(has_selection);
// Reset the password related views.
show_button_.SetLabel(
l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON));
show_button_.SetEnabled(has_selection);
password_label_.SetText(std::wstring());
}
void PasswordsPageView::ButtonPressed(views::Button* sender) {
// Close will result in our destruction.
if (sender == &remove_all_button_) {
table_model_.ForgetAndRemoveAllSignons();
return;
}
// The following require a selection (and only one, since table is single-
// select only).
views::TableSelectionIterator iter = table_view_->SelectionBegin();
int row = *iter;
PasswordForm* selected = table_model_.GetPasswordFormAt(row);
DCHECK(++iter == table_view_->SelectionEnd());
if (sender == &remove_button_) {
table_model_.ForgetAndRemoveSignon(row);
} else if (sender == &show_button_) {
if (password_label_.GetText().length() == 0) {
password_label_.SetText(selected->password_value);
show_button_.SetLabel(
l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON));
} else {
password_label_.SetText(L"");
show_button_.SetLabel(
l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON));
}
} else {
NOTREACHED() << "Invalid button.";
}
}
void PasswordsPageView::OnRowCountChanged(size_t rows) {
remove_all_button_.SetEnabled(rows > 0);
}
///////////////////////////////////////////////////////////////////////////////
// PasswordsPageView, protected
void PasswordsPageView::InitControlLayout() {
SetupButtonsAndLabels();
SetupTable();
// Do the layout thing.
const int top_column_set_id = 0;
const int lower_column_set_id = 1;
GridLayout* layout = CreatePanelGridLayout(this);
SetLayoutManager(layout);
// Design the grid.
ColumnSet* column_set = layout->AddColumnSet(top_column_set_id);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::FIXED, 300, 0);
column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
column_set->AddColumn(GridLayout::FILL, GridLayout::LEADING, 0,
GridLayout::USE_PREF, 0, 0);
column_set = layout->AddColumnSet(lower_column_set_id);
column_set->AddColumn(GridLayout::FILL, GridLayout::LEADING, 0,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(1, kRelatedControlHorizontalSpacing);
column_set->AddColumn(GridLayout::FILL, GridLayout::LEADING, 0,
GridLayout::USE_PREF, 0, 0);
column_set->LinkColumnSizes(0, 2, -1);
// Fill the grid.
layout->StartRow(0.05f, top_column_set_id);
layout->AddView(table_view_, 1, 4);
layout->AddView(&remove_button_);
layout->StartRow(0.05f, top_column_set_id);
layout->SkipColumns(1);
layout->AddView(&remove_all_button_);
layout->StartRow(0.05f, top_column_set_id);
layout->SkipColumns(1);
layout->AddView(&show_button_);
layout->StartRow(0.80f, top_column_set_id);
layout->SkipColumns(1);
layout->AddView(&password_label_);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
// Ask the database for saved password data.
table_model_.GetAllSavedLoginsForProfile();
}
///////////////////////////////////////////////////////////////////////////////
// PasswordsPageView, private
void PasswordsPageView::SetupButtonsAndLabels() {
// Disable all buttons in the first place.
show_button_.SetParentOwned(false);
show_button_.SetEnabled(false);
remove_button_.SetParentOwned(false);
remove_button_.SetEnabled(false);
remove_all_button_.SetParentOwned(false);
remove_all_button_.SetEnabled(false);
password_label_.SetParentOwned(false);
}
void PasswordsPageView::SetupTable() {
// Tell the table model we are concern about how many rows it has.
table_model_.set_row_count_observer(this);
// Creates the different columns for the table.
// The float resize values are the result of much tinkering.
std::vector<views::TableColumn> columns;
columns.push_back(views::TableColumn(IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN,
views::TableColumn::LEFT, -1, 0.55f));
columns.back().sortable = true;
columns.push_back(views::TableColumn(
IDS_PASSWORDS_PAGE_VIEW_USERNAME_COLUMN, views::TableColumn::RIGHT,
-1, 0.37f));
columns.back().sortable = true;
table_view_ = new views::TableView(&table_model_, columns, views::TEXT_ONLY,
true, true, true);
// Make the table initially sorted by host.
views::TableView::SortDescriptors sort;
sort.push_back(views::TableView::SortDescriptor(
IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN, true));
table_view_->SetSortDescriptors(sort);
table_view_->SetObserver(this);
}
<commit_msg>Fix regression caused by gfx::Size no longer accepting negative dimensions.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/options/passwords_page_view.h"
#include "app/l10n_util.h"
#include "base/string_util.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "grit/generated_resources.h"
#include "views/background.h"
#include "views/controls/button/native_button.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"
using views::ColumnSet;
using views::GridLayout;
///////////////////////////////////////////////////////////////////////////////
// MultiLabelButtons
MultiLabelButtons::MultiLabelButtons(views::ButtonListener* listener,
const std::wstring& label,
const std::wstring& alt_label)
: NativeButton(listener, label),
label_(label),
alt_label_(alt_label) {
}
gfx::Size MultiLabelButtons::GetPreferredSize() {
if (pref_size_.IsEmpty()) {
// Let's compute our preferred size.
std::wstring current_label = label();
SetLabel(label_);
pref_size_ = NativeButton::GetPreferredSize();
SetLabel(alt_label_);
gfx::Size alt_pref_size = NativeButton::GetPreferredSize();
// Revert to the original label.
SetLabel(current_label);
pref_size_.SetSize(std::max(pref_size_.width(), alt_pref_size.width()),
std::max(pref_size_.height(), alt_pref_size.height()));
}
return gfx::Size(pref_size_.width(), pref_size_.height());
}
///////////////////////////////////////////////////////////////////////////////
// PasswordsTableModel, public
PasswordsTableModel::PasswordsTableModel(Profile* profile)
: observer_(NULL),
row_count_observer_(NULL),
pending_login_query_(NULL),
saved_signons_cleanup_(&saved_signons_),
profile_(profile) {
DCHECK(profile && profile->GetWebDataService(Profile::EXPLICIT_ACCESS));
}
PasswordsTableModel::~PasswordsTableModel() {
CancelLoginsQuery();
}
int PasswordsTableModel::RowCount() {
return static_cast<int>(saved_signons_.size());
}
std::wstring PasswordsTableModel::GetText(int row,
int col_id) {
switch (col_id) {
case IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN: { // Site.
const std::wstring& url = saved_signons_[row]->display_url.display_url();
// Force URL to have LTR directionality.
if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) {
std::wstring localized_url = url;
l10n_util::WrapStringWithLTRFormatting(&localized_url);
return localized_url;
}
return url;
}
case IDS_PASSWORDS_PAGE_VIEW_USERNAME_COLUMN: { // Username.
std::wstring username = GetPasswordFormAt(row)->username_value;
l10n_util::AdjustStringForLocaleDirection(username, &username);
return username;
}
default:
NOTREACHED() << "Invalid column.";
return std::wstring();
}
}
int PasswordsTableModel::CompareValues(int row1, int row2,
int column_id) {
if (column_id == IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN) {
return saved_signons_[row1]->display_url.Compare(
saved_signons_[row2]->display_url, GetCollator());
}
return TableModel::CompareValues(row1, row2, column_id);
}
void PasswordsTableModel::SetObserver(
views::TableModelObserver* observer) {
observer_ = observer;
}
void PasswordsTableModel::GetAllSavedLoginsForProfile() {
DCHECK(!pending_login_query_);
pending_login_query_ = web_data_service()->GetAllAutofillableLogins(this);
}
void PasswordsTableModel::OnWebDataServiceRequestDone(
WebDataService::Handle h,
const WDTypedResult* result) {
DCHECK_EQ(pending_login_query_, h);
pending_login_query_ = NULL;
if (!result)
return;
DCHECK(result->GetType() == PASSWORD_RESULT);
// Get the result from the database into a useable form.
const WDResult<std::vector<PasswordForm*> >* r =
static_cast<const WDResult<std::vector<PasswordForm*> >*>(result);
std::vector<PasswordForm*> rows = r->GetValue();
STLDeleteElements<PasswordRows>(&saved_signons_);
saved_signons_.resize(rows.size(), NULL);
std::wstring languages =
profile_->GetPrefs()->GetString(prefs::kAcceptLanguages);
for (size_t i = 0; i < rows.size(); ++i) {
saved_signons_[i] = new PasswordRow(
gfx::SortedDisplayURL(rows[i]->origin, languages), rows[i]);
}
if (observer_)
observer_->OnModelChanged();
if (row_count_observer_)
row_count_observer_->OnRowCountChanged(RowCount());
}
PasswordForm* PasswordsTableModel::GetPasswordFormAt(int row) {
DCHECK(row >= 0 && row < RowCount());
return saved_signons_[row]->form.get();
}
void PasswordsTableModel::ForgetAndRemoveSignon(int row) {
DCHECK(row >= 0 && row < RowCount());
PasswordRows::iterator target_iter = saved_signons_.begin() + row;
// Remove from DB, memory, and vector.
PasswordRow* password_row = *target_iter;
web_data_service()->RemoveLogin(*(password_row->form.get()));
delete password_row;
saved_signons_.erase(target_iter);
if (observer_)
observer_->OnItemsRemoved(row, 1);
if (row_count_observer_)
row_count_observer_->OnRowCountChanged(RowCount());
}
void PasswordsTableModel::ForgetAndRemoveAllSignons() {
PasswordRows::iterator iter = saved_signons_.begin();
while (iter != saved_signons_.end()) {
// Remove from DB, memory, and vector.
PasswordRow* row = *iter;
web_data_service()->RemoveLogin(*(row->form.get()));
delete row;
iter = saved_signons_.erase(iter);
}
if (observer_)
observer_->OnModelChanged();
if (row_count_observer_)
row_count_observer_->OnRowCountChanged(RowCount());
}
///////////////////////////////////////////////////////////////////////////////
// PasswordsTableModel, private
void PasswordsTableModel::CancelLoginsQuery() {
if (pending_login_query_) {
web_data_service()->CancelRequest(pending_login_query_);
pending_login_query_ = NULL;
}
}
///////////////////////////////////////////////////////////////////////////////
// PasswordsPageView, public
PasswordsPageView::PasswordsPageView(Profile* profile)
: OptionsPageView(profile),
show_button_(
this,
l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON),
l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON)),
remove_button_(this, l10n_util::GetString(
IDS_PASSWORDS_PAGE_VIEW_REMOVE_BUTTON)),
remove_all_button_(this, l10n_util::GetString(
IDS_PASSWORDS_PAGE_VIEW_REMOVE_ALL_BUTTON)),
table_model_(profile),
table_view_(NULL) {
}
void PasswordsPageView::OnSelectionChanged() {
bool has_selection = table_view_->SelectedRowCount() > 0;
remove_button_.SetEnabled(has_selection);
// Reset the password related views.
show_button_.SetLabel(
l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON));
show_button_.SetEnabled(has_selection);
password_label_.SetText(std::wstring());
}
void PasswordsPageView::ButtonPressed(views::Button* sender) {
// Close will result in our destruction.
if (sender == &remove_all_button_) {
table_model_.ForgetAndRemoveAllSignons();
return;
}
// The following require a selection (and only one, since table is single-
// select only).
views::TableSelectionIterator iter = table_view_->SelectionBegin();
int row = *iter;
PasswordForm* selected = table_model_.GetPasswordFormAt(row);
DCHECK(++iter == table_view_->SelectionEnd());
if (sender == &remove_button_) {
table_model_.ForgetAndRemoveSignon(row);
} else if (sender == &show_button_) {
if (password_label_.GetText().length() == 0) {
password_label_.SetText(selected->password_value);
show_button_.SetLabel(
l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON));
} else {
password_label_.SetText(L"");
show_button_.SetLabel(
l10n_util::GetString(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON));
}
} else {
NOTREACHED() << "Invalid button.";
}
}
void PasswordsPageView::OnRowCountChanged(size_t rows) {
remove_all_button_.SetEnabled(rows > 0);
}
///////////////////////////////////////////////////////////////////////////////
// PasswordsPageView, protected
void PasswordsPageView::InitControlLayout() {
SetupButtonsAndLabels();
SetupTable();
// Do the layout thing.
const int top_column_set_id = 0;
const int lower_column_set_id = 1;
GridLayout* layout = CreatePanelGridLayout(this);
SetLayoutManager(layout);
// Design the grid.
ColumnSet* column_set = layout->AddColumnSet(top_column_set_id);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::FIXED, 300, 0);
column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
column_set->AddColumn(GridLayout::FILL, GridLayout::LEADING, 0,
GridLayout::USE_PREF, 0, 0);
column_set = layout->AddColumnSet(lower_column_set_id);
column_set->AddColumn(GridLayout::FILL, GridLayout::LEADING, 0,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(1, kRelatedControlHorizontalSpacing);
column_set->AddColumn(GridLayout::FILL, GridLayout::LEADING, 0,
GridLayout::USE_PREF, 0, 0);
column_set->LinkColumnSizes(0, 2, -1);
// Fill the grid.
layout->StartRow(0.05f, top_column_set_id);
layout->AddView(table_view_, 1, 4);
layout->AddView(&remove_button_);
layout->StartRow(0.05f, top_column_set_id);
layout->SkipColumns(1);
layout->AddView(&remove_all_button_);
layout->StartRow(0.05f, top_column_set_id);
layout->SkipColumns(1);
layout->AddView(&show_button_);
layout->StartRow(0.80f, top_column_set_id);
layout->SkipColumns(1);
layout->AddView(&password_label_);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
// Ask the database for saved password data.
table_model_.GetAllSavedLoginsForProfile();
}
///////////////////////////////////////////////////////////////////////////////
// PasswordsPageView, private
void PasswordsPageView::SetupButtonsAndLabels() {
// Disable all buttons in the first place.
show_button_.SetParentOwned(false);
show_button_.SetEnabled(false);
remove_button_.SetParentOwned(false);
remove_button_.SetEnabled(false);
remove_all_button_.SetParentOwned(false);
remove_all_button_.SetEnabled(false);
password_label_.SetParentOwned(false);
}
void PasswordsPageView::SetupTable() {
// Tell the table model we are concern about how many rows it has.
table_model_.set_row_count_observer(this);
// Creates the different columns for the table.
// The float resize values are the result of much tinkering.
std::vector<views::TableColumn> columns;
columns.push_back(views::TableColumn(IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN,
views::TableColumn::LEFT, -1, 0.55f));
columns.back().sortable = true;
columns.push_back(views::TableColumn(
IDS_PASSWORDS_PAGE_VIEW_USERNAME_COLUMN, views::TableColumn::RIGHT,
-1, 0.37f));
columns.back().sortable = true;
table_view_ = new views::TableView(&table_model_, columns, views::TEXT_ONLY,
true, true, true);
// Make the table initially sorted by host.
views::TableView::SortDescriptors sort;
sort.push_back(views::TableView::SortDescriptor(
IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN, true));
table_view_->SetSortDescriptors(sort);
table_view_->SetObserver(this);
}
<|endoftext|>
|
<commit_before><commit_msg>Fix include path for header file to fix sync build. I'll hold off committing until Idan lets me know I didn't butcher anything else, too :) Review URL: http://codereview.chromium.org/165004<commit_after><|endoftext|>
|
<commit_before><commit_msg>Ajokki: use elevation map for Helsinki east downtown `Scene`.<commit_after><|endoftext|>
|
<commit_before>//-----------------------------------------------------------------------------
// File: CTime.cpp
//
// class: CTime
// methods:
// void CTime::setCurrentTime()
//
//
//-----------------------------------------------------------------------------
#include "CTime.h"
namespace NP_DATETIME
{
void CTime::setHour(short hour)
{
if (hour >= 0 && hour < HOURS_IN_DAY) {
m_hour = hour;
}
else {
m_hour = 0;
}
}
void CTime::setMinute(short minute)
{
if (minute >= 0 && minute < SEXAGESIMAL_RATE) {
m_minute = minute;
}
else {
m_minute = 0;
}
}
void CTime::setSecond(short second)
{
if (second >= 0 && second < SEXAGESIMAL_RATE) {
m_second = second;
}
else {
m_second = 0;
}
}
//-----------------------------------------------------------------------------
// Class: CTime
// method: setCurrentTime()
//
// description: sets the time from the system clock
//
// Called By: constructor, mutators
//
// History Log:
// 2/9/08 PB completed version 1.0
// ----------------------------------------------------------------------------
void CTime::setCurrentTime()
{
time_t rawtime;
tm *currentTimePtr;
time(&rawtime);
currentTimePtr = localtime(&rawtime);
m_hour = currentTimePtr->tm_hour;
m_minute = currentTimePtr->tm_min;
m_second = currentTimePtr->tm_sec;
}
CTime::CTime(void)
{
this->setCurrentTime();
}
CTime::CTime(int hour, int minute, int second)
{
this->setHour(hour);
this->setMinute(minute);
this->setSecond(second);
}
void CTime::input(istream & sin)
{
bool reset = false;
short hour, minute, second;
char c;
sin >> hour;
sin.get(c);
if (c != ':') { reset = true; }
sin >> minute;
sin.get(c);
if (c != ':') { reset = true; }
sin >> second;
if (reset) {
hour = 0;
minute = 0;
second = 0;
}
else {
if (hour < 0 || hour >= HOURS_IN_DAY) {
hour = 0;
}
if (minute < 0 || minute >= SEXAGESIMAL_RATE) {
minute = 0;
}
if (second < 0 || second >= SEXAGESIMAL_RATE) {
second = 0;
}
}
setHour(hour);
setMinute(minute);
setSecond(second);
}
void CTime::print(ostream & sout) const
{
sout << m_hour << ':' << m_minute << ':' << m_second;
}
bool CTime::operator==(const Comparable & other) const
{
bool returnValue = false;
try
{
const CTime otherTime = dynamic_cast<const CTime&>(other);
if (
m_hour == otherTime.m_hour &&
m_minute == otherTime.m_minute &&
m_second == otherTime.m_second
)
returnValue = true;
}
catch (bad_cast e)
{
// Should something happen here?
}
return returnValue;
}
ostream & operator << (ostream & sout, const CTime & time)
{
time.print(sout);
return sout;
}
istream & operator >> (istream & sin, CTime & time)
{
time.input(sin);
return sin;
}
}
<commit_msg>create lt operator overload<commit_after>//-----------------------------------------------------------------------------
// File: CTime.cpp
//
// class: CTime
// methods:
// void CTime::setCurrentTime()
//
//
//-----------------------------------------------------------------------------
#include "CTime.h"
namespace NP_DATETIME
{
void CTime::setHour(short hour)
{
if (hour >= 0 && hour < HOURS_IN_DAY) {
m_hour = hour;
}
else {
m_hour = 0;
}
}
void CTime::setMinute(short minute)
{
if (minute >= 0 && minute < SEXAGESIMAL_RATE) {
m_minute = minute;
}
else {
m_minute = 0;
}
}
void CTime::setSecond(short second)
{
if (second >= 0 && second < SEXAGESIMAL_RATE) {
m_second = second;
}
else {
m_second = 0;
}
}
//-----------------------------------------------------------------------------
// Class: CTime
// method: setCurrentTime()
//
// description: sets the time from the system clock
//
// Called By: constructor, mutators
//
// History Log:
// 2/9/08 PB completed version 1.0
// ----------------------------------------------------------------------------
void CTime::setCurrentTime()
{
time_t rawtime;
tm *currentTimePtr;
time(&rawtime);
currentTimePtr = localtime(&rawtime);
m_hour = currentTimePtr->tm_hour;
m_minute = currentTimePtr->tm_min;
m_second = currentTimePtr->tm_sec;
}
CTime::CTime(void)
{
this->setCurrentTime();
}
CTime::CTime(int hour, int minute, int second)
{
this->setHour(hour);
this->setMinute(minute);
this->setSecond(second);
}
void CTime::input(istream & sin)
{
bool reset = false;
short hour, minute, second;
char c;
sin >> hour;
sin.get(c);
if (c != ':') { reset = true; }
sin >> minute;
sin.get(c);
if (c != ':') { reset = true; }
sin >> second;
if (reset) {
hour = 0;
minute = 0;
second = 0;
}
else {
if (hour < 0 || hour >= HOURS_IN_DAY) {
hour = 0;
}
if (minute < 0 || minute >= SEXAGESIMAL_RATE) {
minute = 0;
}
if (second < 0 || second >= SEXAGESIMAL_RATE) {
second = 0;
}
}
setHour(hour);
setMinute(minute);
setSecond(second);
}
void CTime::print(ostream & sout) const
{
sout << m_hour << ':' << m_minute << ':' << m_second;
}
bool CTime::operator==(const Comparable & other) const
{
bool returnValue = false;
try
{
CTime otherTime = dynamic_cast<const CTime&>(other);
if (
m_hour == otherTime.getHour() &&
m_minute == otherTime.getMinute() &&
m_second == otherTime.getSecond()
)
returnValue = true;
}
catch (bad_cast e)
{
// Should something happen here?
}
return returnValue;
}
bool CTime::operator<(const Comparable & other) const
{
/*
3:12:33 9:53:01
3:11:33 9:53:00
*/
bool isLT = false;
try {
CTime otherTime = dynamic_cast<const CTime&>(other);
bool hourIsLT = m_hour < otherTime.getHour();
bool hourIsEq = m_hour == otherTime.getHour();
bool minIsLT = m_minute < otherTime.getMinute();
bool minIsEq = m_minute == otherTime.getMinute();
bool secIsLT = m_second < otherTime.getSecond();
if (hourIsLT)
isLT = true;
else if (hourIsEq && minIsLT)
isLT = true;
else if (hourIsEq && minIsEq && secIsLT)
isLT = true;
}
catch (bad_cast e) {
// Should something happen here?
}
return isLT;
}
ostream & operator << (ostream & sout, const CTime & time)
{
time.print(sout);
return sout;
}
istream & operator >> (istream & sin, CTime & time)
{
time.input(sin);
return sin;
}
}
<|endoftext|>
|
<commit_before>/* -------------------------------------------------------------------------- *
* Simbody(tm) *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2008-12 Stanford University and the Authors. *
* Authors: Peter Eastman *
* Contributors: Michael Sherman *
* *
* 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 "simbody/internal/common.h"
#include "simbody/internal/SimbodyMatterSubsystem.h"
#include "VisualizerGeometry.h"
#include "VisualizerProtocol.h"
using namespace SimTK;
static const Vec3 DefaultBodyColor = Gray;
static const Vec3 DefaultPointColor = Magenta;
VisualizerGeometry::VisualizerGeometry
(VisualizerProtocol& protocol, const SimbodyMatterSubsystem& matter,
const State& state)
: protocol(protocol), matter(matter), state(state) {}
// The DecorativeGeometry's frame D is given in the body frame B, via transform
// X_BD. We want to know X_GD, the pose of the geometry in Ground, which we get
// via X_GD=X_GB*X_BD.
Transform VisualizerGeometry::calcX_GD(const DecorativeGeometry& geom) const {
const MobilizedBody& mobod =
matter.getMobilizedBody(MobilizedBodyIndex(geom.getBodyId()));
const Transform& X_GB = mobod.getBodyTransform(state);
const Transform& X_BD = geom.getTransform();
return X_GB*X_BD;
}
// We're going to draw three short lines aligned with the body axes
// that intersect at the point.
void VisualizerGeometry::
implementPointGeometry(const SimTK::DecorativePoint& geom) {
const MobilizedBody& mobod =
matter.getMobilizedBody(MobilizedBodyIndex(geom.getBodyId()));
const Transform& X_GB = mobod.getBodyTransform(state);
const Transform& X_BD = geom.getTransform();
const Transform X_GD = X_GB*X_BD;
const Vec3 p_GP = X_GD*geom.getPoint();
const Real thickness =
geom.getLineThickness() == -1 ? Real(1) : geom.getLineThickness();
const Real DefaultLength = Real(0.05); // 1/20 of a unit length
const Vec3 lengths = DefaultLength * getScaleFactors(geom);
const Vec4 color = getColor(geom, DefaultPointColor);
protocol.drawLine(p_GP - lengths[0]*X_GB.x(),
p_GP + lengths[0]*X_GB.x(), color, thickness);
protocol.drawLine(p_GP - lengths[1]*X_GB.y(),
p_GP + lengths[1]*X_GB.y(), color, thickness);
protocol.drawLine(p_GP - lengths[2]*X_GB.z(),
p_GP + lengths[2]*X_GB.z(), color, thickness);
}
void VisualizerGeometry::implementLineGeometry(const SimTK::DecorativeLine& geom) {
const Transform X_GD = calcX_GD(geom);
protocol.drawLine(X_GD*geom.getPoint1(), X_GD*geom.getPoint2(), getColor(geom), geom.getLineThickness() == -1 ? 1 : geom.getLineThickness());
}
void VisualizerGeometry::implementBrickGeometry(const SimTK::DecorativeBrick& geom) {
const Transform X_GD = calcX_GD(geom);
const Vec3 hlen = getScaleFactors(geom).elementwiseMultiply(geom.getHalfLengths());
protocol.drawBox(X_GD, hlen, getColor(geom), getRepresentation(geom));
}
void VisualizerGeometry::implementCylinderGeometry(const SimTK::DecorativeCylinder& geom) {
const Transform X_GD = calcX_GD(geom);
const Vec3 scale = getScaleFactors(geom);
protocol.drawCylinder(X_GD, Vec3(scale[0]*geom.getRadius(),
scale[1]*geom.getHalfHeight(),
scale[2]*geom.getRadius()),
getColor(geom), getRepresentation(geom), getResolution(geom));
}
void VisualizerGeometry::implementCircleGeometry(const SimTK::DecorativeCircle& geom) {
const Transform X_GD = calcX_GD(geom);
const Vec3 scale = getScaleFactors(geom); // z ignored
protocol.drawCircle(X_GD, Vec3(scale[0]*geom.getRadius(),
scale[1]*geom.getRadius(), 1),
getColor(geom), getRepresentation(geom), getResolution(geom));
}
void VisualizerGeometry::implementSphereGeometry(const SimTK::DecorativeSphere& geom) {
const Transform X_GD = calcX_GD(geom);
protocol.drawEllipsoid(X_GD, geom.getRadius()*getScaleFactors(geom),
getColor(geom), getRepresentation(geom), getResolution(geom));
}
void VisualizerGeometry::implementEllipsoidGeometry(const SimTK::DecorativeEllipsoid& geom) {
const Transform X_GD = calcX_GD(geom);
const Vec3 radii = getScaleFactors(geom).elementwiseMultiply(geom.getRadii());
protocol.drawEllipsoid(X_GD, radii, getColor(geom), getRepresentation(geom),
getResolution(geom));
}
void VisualizerGeometry::implementFrameGeometry(const SimTK::DecorativeFrame& geom) {
const Transform X_GD = calcX_GD(geom);
protocol.drawCoords(X_GD, geom.getAxisLength()*getScaleFactors(geom), getColor(geom));
}
void VisualizerGeometry::implementTextGeometry(const SimTK::DecorativeText& geom) {
const Transform X_GD = calcX_GD(geom);
// The default is to face the camera.
bool faceCamera = geom.getFaceCamera()<0 ? true : (geom.getFaceCamera()!=0);
bool isScreenText = geom.getIsScreenText();
protocol.drawText(X_GD.p(), getScaleFactors(geom), getColor(geom),
geom.getText(), faceCamera, isScreenText);
}
void VisualizerGeometry::implementMeshGeometry(const SimTK::DecorativeMesh& geom) {
const Transform X_GD = calcX_GD(geom);
protocol.drawPolygonalMesh(geom.getMesh(), X_GD, getScaleFactors(geom),
getColor(geom), getRepresentation(geom));
}
Vec4 VisualizerGeometry::getColor(const DecorativeGeometry& geom,
const Vec3& defaultColor) {
Vec4 result;
if (geom.getColor()[0] >= 0)
result.updSubVec<3>(0) = geom.getColor();
else {
const Vec3 def = defaultColor[0] >= 0 ? defaultColor : DefaultBodyColor;
result.updSubVec<3>(0) = def;
}
result[3] = (geom.getOpacity() < 0 ? 1 : geom.getOpacity());
return result;
}
int VisualizerGeometry::getRepresentation(const DecorativeGeometry& geom) const {
if (geom.getRepresentation() == DecorativeGeometry::DrawDefault)
return DecorativeGeometry::DrawSurface;
return geom.getRepresentation();
}
unsigned short VisualizerGeometry::
getResolution(const DecorativeGeometry& geom) const {
if (geom.getResolution() <= 0)
return 2;
return std::max((unsigned short) 1, (unsigned short) (geom.getResolution()*2));
}
Vec3 VisualizerGeometry::getScaleFactors(const DecorativeGeometry& geom) const {
const Vec3& scale = geom.getScaleFactors();
Vec3 actual;
for (int i=0; i<3; ++i)
actual[i] = scale[i] <= 0 ? 1 : scale[i];
return actual;
}
<commit_msg>Forgot to pass the rotation.<commit_after>/* -------------------------------------------------------------------------- *
* Simbody(tm) *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2008-12 Stanford University and the Authors. *
* Authors: Peter Eastman *
* Contributors: Michael Sherman *
* *
* 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 "simbody/internal/common.h"
#include "simbody/internal/SimbodyMatterSubsystem.h"
#include "VisualizerGeometry.h"
#include "VisualizerProtocol.h"
using namespace SimTK;
static const Vec3 DefaultBodyColor = Gray;
static const Vec3 DefaultPointColor = Magenta;
VisualizerGeometry::VisualizerGeometry
(VisualizerProtocol& protocol, const SimbodyMatterSubsystem& matter,
const State& state)
: protocol(protocol), matter(matter), state(state) {}
// The DecorativeGeometry's frame D is given in the body frame B, via transform
// X_BD. We want to know X_GD, the pose of the geometry in Ground, which we get
// via X_GD=X_GB*X_BD.
Transform VisualizerGeometry::calcX_GD(const DecorativeGeometry& geom) const {
const MobilizedBody& mobod =
matter.getMobilizedBody(MobilizedBodyIndex(geom.getBodyId()));
const Transform& X_GB = mobod.getBodyTransform(state);
const Transform& X_BD = geom.getTransform();
return X_GB*X_BD;
}
// We're going to draw three short lines aligned with the body axes
// that intersect at the point.
void VisualizerGeometry::
implementPointGeometry(const SimTK::DecorativePoint& geom) {
const MobilizedBody& mobod =
matter.getMobilizedBody(MobilizedBodyIndex(geom.getBodyId()));
const Transform& X_GB = mobod.getBodyTransform(state);
const Transform& X_BD = geom.getTransform();
const Transform X_GD = X_GB*X_BD;
const Vec3 p_GP = X_GD*geom.getPoint();
const Real thickness =
geom.getLineThickness() == -1 ? Real(1) : geom.getLineThickness();
const Real DefaultLength = Real(0.05); // 1/20 of a unit length
const Vec3 lengths = DefaultLength * getScaleFactors(geom);
const Vec4 color = getColor(geom, DefaultPointColor);
protocol.drawLine(p_GP - lengths[0]*X_GB.x(),
p_GP + lengths[0]*X_GB.x(), color, thickness);
protocol.drawLine(p_GP - lengths[1]*X_GB.y(),
p_GP + lengths[1]*X_GB.y(), color, thickness);
protocol.drawLine(p_GP - lengths[2]*X_GB.z(),
p_GP + lengths[2]*X_GB.z(), color, thickness);
}
void VisualizerGeometry::implementLineGeometry(const SimTK::DecorativeLine& geom) {
const Transform X_GD = calcX_GD(geom);
protocol.drawLine(X_GD*geom.getPoint1(), X_GD*geom.getPoint2(), getColor(geom), geom.getLineThickness() == -1 ? 1 : geom.getLineThickness());
}
void VisualizerGeometry::implementBrickGeometry(const SimTK::DecorativeBrick& geom) {
const Transform X_GD = calcX_GD(geom);
const Vec3 hlen = getScaleFactors(geom).elementwiseMultiply(geom.getHalfLengths());
protocol.drawBox(X_GD, hlen, getColor(geom), getRepresentation(geom));
}
void VisualizerGeometry::implementCylinderGeometry(const SimTK::DecorativeCylinder& geom) {
const Transform X_GD = calcX_GD(geom);
const Vec3 scale = getScaleFactors(geom);
protocol.drawCylinder(X_GD, Vec3(scale[0]*geom.getRadius(),
scale[1]*geom.getHalfHeight(),
scale[2]*geom.getRadius()),
getColor(geom), getRepresentation(geom), getResolution(geom));
}
void VisualizerGeometry::implementCircleGeometry(const SimTK::DecorativeCircle& geom) {
const Transform X_GD = calcX_GD(geom);
const Vec3 scale = getScaleFactors(geom); // z ignored
protocol.drawCircle(X_GD, Vec3(scale[0]*geom.getRadius(),
scale[1]*geom.getRadius(), 1),
getColor(geom), getRepresentation(geom), getResolution(geom));
}
void VisualizerGeometry::implementSphereGeometry(const SimTK::DecorativeSphere& geom) {
const Transform X_GD = calcX_GD(geom);
protocol.drawEllipsoid(X_GD, geom.getRadius()*getScaleFactors(geom),
getColor(geom), getRepresentation(geom), getResolution(geom));
}
void VisualizerGeometry::implementEllipsoidGeometry(const SimTK::DecorativeEllipsoid& geom) {
const Transform X_GD = calcX_GD(geom);
const Vec3 radii = getScaleFactors(geom).elementwiseMultiply(geom.getRadii());
protocol.drawEllipsoid(X_GD, radii, getColor(geom), getRepresentation(geom),
getResolution(geom));
}
void VisualizerGeometry::implementFrameGeometry(const SimTK::DecorativeFrame& geom) {
const Transform X_GD = calcX_GD(geom);
protocol.drawCoords(X_GD, geom.getAxisLength()*getScaleFactors(geom), getColor(geom));
}
void VisualizerGeometry::implementTextGeometry(const SimTK::DecorativeText& geom) {
const Transform X_GD = calcX_GD(geom);
// The default is to face the camera.
bool faceCamera = geom.getFaceCamera()<0 ? true : (geom.getFaceCamera()!=0);
bool isScreenText = geom.getIsScreenText();
protocol.drawText(X_GD, getScaleFactors(geom), getColor(geom),
geom.getText(), faceCamera, isScreenText);
}
void VisualizerGeometry::implementMeshGeometry(const SimTK::DecorativeMesh& geom) {
const Transform X_GD = calcX_GD(geom);
protocol.drawPolygonalMesh(geom.getMesh(), X_GD, getScaleFactors(geom),
getColor(geom), getRepresentation(geom));
}
Vec4 VisualizerGeometry::getColor(const DecorativeGeometry& geom,
const Vec3& defaultColor) {
Vec4 result;
if (geom.getColor()[0] >= 0)
result.updSubVec<3>(0) = geom.getColor();
else {
const Vec3 def = defaultColor[0] >= 0 ? defaultColor : DefaultBodyColor;
result.updSubVec<3>(0) = def;
}
result[3] = (geom.getOpacity() < 0 ? 1 : geom.getOpacity());
return result;
}
int VisualizerGeometry::getRepresentation(const DecorativeGeometry& geom) const {
if (geom.getRepresentation() == DecorativeGeometry::DrawDefault)
return DecorativeGeometry::DrawSurface;
return geom.getRepresentation();
}
unsigned short VisualizerGeometry::
getResolution(const DecorativeGeometry& geom) const {
if (geom.getResolution() <= 0)
return 2;
return std::max((unsigned short) 1, (unsigned short) (geom.getResolution()*2));
}
Vec3 VisualizerGeometry::getScaleFactors(const DecorativeGeometry& geom) const {
const Vec3& scale = geom.getScaleFactors();
Vec3 actual;
for (int i=0; i<3; ++i)
actual[i] = scale[i] <= 0 ? 1 : scale[i];
return actual;
}
<|endoftext|>
|
<commit_before>#include "vm.h"
#include "opcodes.h"
#include <cassert>
#include <iostream>
static void print(ceos::VM &vm, int argv) {
while (argv--) {
std::cout << vm.stack_pop() << "\n";
}
}
namespace ceos {
void VM::registerBuiltins() {
m_functionTable["print"] = print;
}
void VM::stack_push(uintptr_t value) {
m_stack.push_back(value);
}
uintptr_t VM::stack_pop() {
uintptr_t value = m_stack.back();
m_stack.pop_back();
return value;
}
#define READ_INT(INT_NAME) \
int INT_NAME; \
{ \
union { \
char c[4]; \
int i; \
} tmp; \
m_bytecode.get(tmp.c[0]); \
m_bytecode.get(tmp.c[1]); \
m_bytecode.get(tmp.c[2]); \
m_bytecode.get(tmp.c[3]); \
INT_NAME = tmp.i; \
}
void VM::execute() {
while (true) {
READ_INT(ceos);
if (m_bytecode.eof()) break;
// section marker
assert(ceos == 0xCE05);
READ_INT(section);
switch (section) {
case 0x0001: // strings
loadStrings();
break;
case 0x0002: //text
run();
break;
default:
assert(0);
}
}
}
void VM::loadStrings() {
const char *str = m_bytecode.str().c_str() + m_bytecode.tellg();
m_stringTable.push_back(str);
m_bytecode.seekg(strlen(str) + 1, m_bytecode.cur);
}
void VM::run() {
while (true) {
READ_INT(opcode);
if (m_bytecode.eof()) break;
switch (opcode) {
case Opcode::push: {
READ_INT(value);
stack_push(value);
break;
}
case Opcode::call: {
int nargs = stack_pop();
void (*fn)(VM &, int) = reinterpret_cast<__typeof__(fn)>(stack_pop());
fn(*this, nargs - 1);
break;
}
case Opcode::load_string: {
READ_INT(stringID);
stack_push(reinterpret_cast<uintptr_t>(&m_stringTable[stringID]));
break;
}
case Opcode::lookup: {
std::string *fnName = reinterpret_cast<std::string *>(stack_pop());
stack_push(reinterpret_cast<uintptr_t>(m_functionTable[*fnName]));
break;
}
case Opcode::jmp: {
READ_INT(target);
m_bytecode.seekg(target, m_bytecode.cur);
break;
}
case Opcode::jz: {
READ_INT(target);
int value = static_cast<int>(stack_pop());
if (value == 0) {
m_bytecode.seekg(target, m_bytecode.cur);
}
break;
}
default:
break;
}
}
}
#undef READ_INT
}
<commit_msg>Use sections.h instead of magic numbers<commit_after>#include "vm.h"
#include "opcodes.h"
#include "sections.h"
#include <cassert>
#include <iostream>
static void print(ceos::VM &vm, int argv) {
while (argv--) {
std::cout << vm.stack_pop() << "\n";
}
}
namespace ceos {
void VM::registerBuiltins() {
m_functionTable["print"] = print;
}
void VM::stack_push(uintptr_t value) {
m_stack.push_back(value);
}
uintptr_t VM::stack_pop() {
uintptr_t value = m_stack.back();
m_stack.pop_back();
return value;
}
#define READ_INT(INT_NAME) \
int INT_NAME; \
{ \
union { \
char c[4]; \
int i; \
} tmp; \
m_bytecode.get(tmp.c[0]); \
m_bytecode.get(tmp.c[1]); \
m_bytecode.get(tmp.c[2]); \
m_bytecode.get(tmp.c[3]); \
INT_NAME = tmp.i; \
}
void VM::execute() {
while (true) {
READ_INT(ceos);
if (m_bytecode.eof()) break;
// section marker
assert(ceos == Section::Header);
READ_INT(section);
switch (section) {
case Section::Strings:
loadStrings();
break;
case Section::Text:
run();
break;
case Section::Functions:
assert(0);
}
}
}
void VM::loadStrings() {
const char *str = m_bytecode.str().c_str() + m_bytecode.tellg();
m_stringTable.push_back(str);
m_bytecode.seekg(strlen(str) + 1, m_bytecode.cur);
}
void VM::run() {
while (true) {
READ_INT(opcode);
if (m_bytecode.eof()) break;
switch (opcode) {
case Opcode::push: {
READ_INT(value);
stack_push(value);
break;
}
case Opcode::call: {
int nargs = stack_pop();
void (*fn)(VM &, int) = reinterpret_cast<__typeof__(fn)>(stack_pop());
fn(*this, nargs - 1);
break;
}
case Opcode::load_string: {
READ_INT(stringID);
stack_push(reinterpret_cast<uintptr_t>(&m_stringTable[stringID]));
break;
}
case Opcode::lookup: {
std::string *fnName = reinterpret_cast<std::string *>(stack_pop());
stack_push(reinterpret_cast<uintptr_t>(m_functionTable[*fnName]));
break;
}
case Opcode::jmp: {
READ_INT(target);
m_bytecode.seekg(target, m_bytecode.cur);
break;
}
case Opcode::jz: {
READ_INT(target);
int value = static_cast<int>(stack_pop());
if (value == 0) {
m_bytecode.seekg(target, m_bytecode.cur);
}
break;
}
default:
break;
}
}
}
#undef READ_INT
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/focus/accelerator_handler.h"
#include <bitset>
#include <gtk/gtk.h>
#if defined(HAVE_XINPUT2)
#include <X11/extensions/XInput2.h>
#else
#include <X11/Xlib.h>
#endif
#include "views/accelerator.h"
#include "views/events/event.h"
#include "views/focus/focus_manager.h"
#include "views/touchui/touch_factory.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_gtk.h"
namespace views {
namespace {
RootView* FindRootViewForGdkWindow(GdkWindow* gdk_window) {
gpointer data = NULL;
gdk_window_get_user_data(gdk_window, &data);
GtkWidget* gtk_widget = reinterpret_cast<GtkWidget*>(data);
if (!gtk_widget || !GTK_IS_WIDGET(gtk_widget)) {
DLOG(WARNING) << "no GtkWidget found for that GdkWindow";
return NULL;
}
WidgetGtk* widget_gtk = WidgetGtk::GetViewForNative(gtk_widget);
if (!widget_gtk) {
DLOG(WARNING) << "no WidgetGtk found for that GtkWidget";
return NULL;
}
return widget_gtk->GetRootView();
}
#if defined(HAVE_XINPUT2)
bool X2EventIsTouchEvent(XEvent* xev) {
// TODO(sad): Determine if the captured event is a touch-event.
XGenericEventCookie* cookie = &xev->xcookie;
switch (cookie->evtype) {
case XI_ButtonPress:
case XI_ButtonRelease:
case XI_Motion: {
// Is the event coming from a touch device?
return TouchFactory::GetInstance()->IsTouchDevice(
static_cast<XIDeviceEvent*>(cookie->data)->sourceid);
}
default:
return false;
}
}
#endif // HAVE_XINPUT2
} // namespace
#if defined(HAVE_XINPUT2)
bool DispatchX2Event(RootView* root, XEvent* xev) {
XGenericEventCookie* cookie = &xev->xcookie;
bool touch_event = false;
if (X2EventIsTouchEvent(xev)) {
// Hide the cursor when a touch event comes in.
TouchFactory::GetInstance()->SetCursorVisible(false, false);
touch_event = true;
// Create a TouchEvent, and send it off to |root|. If the event
// is processed by |root|, then return. Otherwise let it fall through so it
// can be used (if desired) as a mouse event.
TouchEvent touch(xev);
if (root->OnTouchEvent(touch) != views::View::TOUCH_STATUS_UNKNOWN)
return true;
}
switch (cookie->evtype) {
case XI_KeyPress:
case XI_KeyRelease: {
// TODO(sad): We don't capture XInput2 events from keyboard yet.
break;
}
case XI_ButtonPress:
case XI_ButtonRelease:
case XI_Motion: {
// Scrolling the wheel generates press/release events with button id's 4
// and 5. In case of a wheelscroll, we do not want to show the cursor.
XIDeviceEvent* xievent = static_cast<XIDeviceEvent*>(cookie->data);
if (xievent->detail == 4 || xievent->detail == 5) {
Event::FromNativeEvent2 from_native;
return root->OnMouseWheel(MouseWheelEvent(xev, from_native));
}
MouseEvent mouseev(xev);
if (!touch_event) {
// Show the cursor, and decide whether or not the cursor should be
// automatically hidden after a certain time of inactivity.
int button_flags = mouseev.flags() & (ui::EF_RIGHT_BUTTON_DOWN |
ui::EF_MIDDLE_BUTTON_DOWN | ui::EF_LEFT_BUTTON_DOWN);
bool start_timer = false;
switch (cookie->evtype) {
case XI_ButtonPress:
start_timer = false;
break;
case XI_ButtonRelease:
// For a release, start the timer if this was only button pressed
// that is being released.
if (button_flags == ui::EF_RIGHT_BUTTON_DOWN ||
button_flags == ui::EF_LEFT_BUTTON_DOWN ||
button_flags == ui::EF_MIDDLE_BUTTON_DOWN)
start_timer = true;
break;
case XI_Motion:
start_timer = !button_flags;
break;
}
TouchFactory::GetInstance()->SetCursorVisible(true, start_timer);
}
// Dispatch the event.
switch (cookie->evtype) {
case XI_ButtonPress:
return root->OnMousePressed(mouseev);
case XI_ButtonRelease:
root->OnMouseReleased(mouseev, false);
return true;
case XI_Motion: {
if (mouseev.type() == ui::ET_MOUSE_DRAGGED) {
return root->OnMouseDragged(mouseev);
} else {
root->OnMouseMoved(mouseev);
return true;
}
}
}
}
}
return false;
}
#endif // HAVE_XINPUT2
bool DispatchXEvent(XEvent* xev) {
GdkDisplay* gdisp = gdk_display_get_default();
XID xwindow = xev->xany.window;
#if defined(HAVE_XINPUT2)
if (xev->type == GenericEvent) {
XGenericEventCookie* cookie = &xev->xcookie;
XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(cookie->data);
xwindow = xiev->event;
}
#endif
GdkWindow* gwind = gdk_window_lookup_for_display(gdisp, xwindow);
if (RootView* root = FindRootViewForGdkWindow(gwind)) {
switch (xev->type) {
case KeyPress:
case KeyRelease: {
Event::FromNativeEvent2 from_native;
KeyEvent keyev(xev, from_native);
return root->ProcessKeyEvent(keyev);
}
case ButtonPress:
case ButtonRelease: {
if (xev->xbutton.button == 4 || xev->xbutton.button == 5) {
// Scrolling the wheel triggers button press/release events.
Event::FromNativeEvent2 from_native;
return root->OnMouseWheel(MouseWheelEvent(xev, from_native));
} else {
MouseEvent mouseev(xev);
if (xev->type == ButtonPress) {
return root->OnMousePressed(mouseev);
} else {
root->OnMouseReleased(mouseev, false);
return true; // Assume the event has been processed to make sure we
// don't process it twice.
}
}
}
case MotionNotify: {
MouseEvent mouseev(xev);
if (mouseev.type() == ui::ET_MOUSE_DRAGGED) {
return root->OnMouseDragged(mouseev);
} else {
root->OnMouseMoved(mouseev);
return true;
}
}
#if defined(HAVE_XINPUT2)
case GenericEvent: {
return DispatchX2Event(root, xev);
}
#endif
}
}
return false;
}
#if defined(HAVE_XINPUT2)
void SetTouchDeviceList(std::vector<unsigned int>& devices) {
TouchFactory::GetInstance()->SetTouchDeviceList(devices);
}
#endif
AcceleratorHandler::AcceleratorHandler() {}
bool AcceleratorHandler::Dispatch(GdkEvent* event) {
gtk_main_do_event(event);
return true;
}
base::MessagePumpGlibXDispatcher::DispatchStatus
AcceleratorHandler::DispatchX(XEvent* xev) {
return DispatchXEvent(xev) ?
base::MessagePumpGlibXDispatcher::EVENT_PROCESSED :
base::MessagePumpGlibXDispatcher::EVENT_IGNORED;
}
} // namespace views
<commit_msg>touchui: Fix building on a buildbot.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/focus/accelerator_handler.h"
#include <bitset>
#include <gtk/gtk.h>
#if defined(HAVE_XINPUT2)
#include <X11/extensions/XInput2.h>
#else
#include <X11/Xlib.h>
#endif
#include "views/accelerator.h"
#include "views/events/event.h"
#include "views/focus/focus_manager.h"
#include "views/touchui/touch_factory.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_gtk.h"
namespace views {
namespace {
RootView* FindRootViewForGdkWindow(GdkWindow* gdk_window) {
gpointer data = NULL;
gdk_window_get_user_data(gdk_window, &data);
GtkWidget* gtk_widget = reinterpret_cast<GtkWidget*>(data);
if (!gtk_widget || !GTK_IS_WIDGET(gtk_widget)) {
DLOG(WARNING) << "no GtkWidget found for that GdkWindow";
return NULL;
}
WidgetGtk* widget_gtk = WidgetGtk::GetViewForNative(gtk_widget);
if (!widget_gtk) {
DLOG(WARNING) << "no WidgetGtk found for that GtkWidget";
return NULL;
}
return widget_gtk->GetRootView();
}
#if defined(HAVE_XINPUT2)
bool X2EventIsTouchEvent(XEvent* xev) {
// TODO(sad): Determine if the captured event is a touch-event.
XGenericEventCookie* cookie = &xev->xcookie;
switch (cookie->evtype) {
case XI_ButtonPress:
case XI_ButtonRelease:
case XI_Motion: {
// Is the event coming from a touch device?
return TouchFactory::GetInstance()->IsTouchDevice(
static_cast<XIDeviceEvent*>(cookie->data)->sourceid);
}
default:
return false;
}
}
#endif // HAVE_XINPUT2
} // namespace
#if defined(HAVE_XINPUT2)
bool DispatchX2Event(RootView* root, XEvent* xev) {
XGenericEventCookie* cookie = &xev->xcookie;
bool touch_event = false;
if (X2EventIsTouchEvent(xev)) {
// Hide the cursor when a touch event comes in.
TouchFactory::GetInstance()->SetCursorVisible(false, false);
touch_event = true;
// Create a TouchEvent, and send it off to |root|. If the event
// is processed by |root|, then return. Otherwise let it fall through so it
// can be used (if desired) as a mouse event.
TouchEvent touch(xev);
if (root->OnTouchEvent(touch) != views::View::TOUCH_STATUS_UNKNOWN)
return true;
}
switch (cookie->evtype) {
case XI_KeyPress:
case XI_KeyRelease: {
// TODO(sad): We don't capture XInput2 events from keyboard yet.
break;
}
case XI_ButtonPress:
case XI_ButtonRelease:
case XI_Motion: {
// Scrolling the wheel generates press/release events with button id's 4
// and 5. In case of a wheelscroll, we do not want to show the cursor.
XIDeviceEvent* xievent = static_cast<XIDeviceEvent*>(cookie->data);
if (xievent->detail == 4 || xievent->detail == 5) {
Event::FromNativeEvent2 from_native;
MouseWheelEvent wheelev(xev, from_native);
return root->OnMouseWheel(wheelev);
}
MouseEvent mouseev(xev);
if (!touch_event) {
// Show the cursor, and decide whether or not the cursor should be
// automatically hidden after a certain time of inactivity.
int button_flags = mouseev.flags() & (ui::EF_RIGHT_BUTTON_DOWN |
ui::EF_MIDDLE_BUTTON_DOWN | ui::EF_LEFT_BUTTON_DOWN);
bool start_timer = false;
switch (cookie->evtype) {
case XI_ButtonPress:
start_timer = false;
break;
case XI_ButtonRelease:
// For a release, start the timer if this was only button pressed
// that is being released.
if (button_flags == ui::EF_RIGHT_BUTTON_DOWN ||
button_flags == ui::EF_LEFT_BUTTON_DOWN ||
button_flags == ui::EF_MIDDLE_BUTTON_DOWN)
start_timer = true;
break;
case XI_Motion:
start_timer = !button_flags;
break;
}
TouchFactory::GetInstance()->SetCursorVisible(true, start_timer);
}
// Dispatch the event.
switch (cookie->evtype) {
case XI_ButtonPress:
return root->OnMousePressed(mouseev);
case XI_ButtonRelease:
root->OnMouseReleased(mouseev, false);
return true;
case XI_Motion: {
if (mouseev.type() == ui::ET_MOUSE_DRAGGED) {
return root->OnMouseDragged(mouseev);
} else {
root->OnMouseMoved(mouseev);
return true;
}
}
}
}
}
return false;
}
#endif // HAVE_XINPUT2
bool DispatchXEvent(XEvent* xev) {
GdkDisplay* gdisp = gdk_display_get_default();
XID xwindow = xev->xany.window;
#if defined(HAVE_XINPUT2)
if (xev->type == GenericEvent) {
XGenericEventCookie* cookie = &xev->xcookie;
XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(cookie->data);
xwindow = xiev->event;
}
#endif
GdkWindow* gwind = gdk_window_lookup_for_display(gdisp, xwindow);
if (RootView* root = FindRootViewForGdkWindow(gwind)) {
switch (xev->type) {
case KeyPress:
case KeyRelease: {
Event::FromNativeEvent2 from_native;
KeyEvent keyev(xev, from_native);
return root->ProcessKeyEvent(keyev);
}
case ButtonPress:
case ButtonRelease: {
if (xev->xbutton.button == 4 || xev->xbutton.button == 5) {
// Scrolling the wheel triggers button press/release events.
Event::FromNativeEvent2 from_native;
MouseWheelEvent wheelev(xev, from_native);
return root->OnMouseWheel(wheelev);
} else {
MouseEvent mouseev(xev);
if (xev->type == ButtonPress) {
return root->OnMousePressed(mouseev);
} else {
root->OnMouseReleased(mouseev, false);
return true; // Assume the event has been processed to make sure we
// don't process it twice.
}
}
}
case MotionNotify: {
MouseEvent mouseev(xev);
if (mouseev.type() == ui::ET_MOUSE_DRAGGED) {
return root->OnMouseDragged(mouseev);
} else {
root->OnMouseMoved(mouseev);
return true;
}
}
#if defined(HAVE_XINPUT2)
case GenericEvent: {
return DispatchX2Event(root, xev);
}
#endif
}
}
return false;
}
#if defined(HAVE_XINPUT2)
void SetTouchDeviceList(std::vector<unsigned int>& devices) {
TouchFactory::GetInstance()->SetTouchDeviceList(devices);
}
#endif
AcceleratorHandler::AcceleratorHandler() {}
bool AcceleratorHandler::Dispatch(GdkEvent* event) {
gtk_main_do_event(event);
return true;
}
base::MessagePumpGlibXDispatcher::DispatchStatus
AcceleratorHandler::DispatchX(XEvent* xev) {
return DispatchXEvent(xev) ?
base::MessagePumpGlibXDispatcher::EVENT_PROCESSED :
base::MessagePumpGlibXDispatcher::EVENT_IGNORED;
}
} // namespace views
<|endoftext|>
|
<commit_before>// Copyright 2017 0lento. All Rights Reserved.
#include "FixedTimestepDemo.h"
#include "PhysicsPublic.h"
#include "PhysicsPawn.h"
APhysicsPawn::APhysicsPawn()
{
PrimaryActorTick.bCanEverTick = true;
PrimaryActorTick.TickGroup = ETickingGroup::TG_PrePhysics;
PrimaryActorTick.bStartWithTickEnabled = true;
PostPhysicsTickFunction.TickGroup = TG_PostPhysics;
PostPhysicsTickFunction.bCanEverTick = true;
PostPhysicsTickFunction.bStartWithTickEnabled = true;
}
void APhysicsPawn::BeginPlay()
{
Super::BeginPlay();
if (!IsTemplate() && PostPhysicsTickFunction.bCanEverTick)
{
PostPhysicsTickFunction.Target = this;
PostPhysicsTickFunction.SetTickFunctionEnable(PostPhysicsTickFunction.bStartWithTickEnabled);
PostPhysicsTickFunction.RegisterTickFunction(GetLevel());
}
FPhysScene* PScene = GetWorld()->GetPhysicsScene();
if (PScene != NULL)
{
OnPhysScenePreTickHandle = PScene->OnPhysScenePreTick.AddUObject(this, &APhysicsPawn::PhysScenePreTick);
OnPhysSceneStepHandle = PScene->OnPhysSceneStep.AddUObject(this, &APhysicsPawn::PhysSceneStep);
}
}
void FPostPhysicsTickFunction::ExecuteTick(float DeltaTime, ELevelTick TickType, ENamedThreads::Type CurrentThread, const FGraphEventRef& CompletionGraphEvent)
{
if (Target && !Target->HasAnyFlags(EObjectFlags::RF_BeginDestroyed | EObjectFlags::RF_FinishDestroyed))
{
FScopeCycleCounterUObject ActorScope(Target);
Target->PostPhysicsTick(DeltaTime, TickType, *this);
}
}
FString FPostPhysicsTickFunction::DiagnosticMessage()
{
return Target->GetFullName() + TEXT("[FixedTimestepPawn Post Physics Tick]");
}
void APhysicsPawn::PhysScenePreTick(FPhysScene* PhysScene, uint32 SceneType, float DeltaTime)
{
PhysicsStepCount = 0;
PhysicsPreSim(DeltaTime);
}
void APhysicsPawn::PhysSceneStep(FPhysScene* PhysScene, uint32 SceneType, float DeltaTime)
{
// If not the first physics step, make sure to run previous steps post step before new one
if (PhysicsStepCount)
{
PhysicsPostStep(DeltaTime);
PhysicsStepCount++;
}
PhysicsStep(DeltaTime);
}
void APhysicsPawn::PostPhysicsTick(float DeltaTime, ELevelTick TickType, FPostPhysicsTickFunction& TickFunction)
{
PhysicsStepCount++;
PhysicsPostStep(DeltaTime); // Run PhysScenePostTick for the last physics step
PhysicsPostSim(DeltaTime);
}
void APhysicsPawn::PhysicsPreSim(float DeltaTime)
{
}
void APhysicsPawn::PhysicsStep(float DeltaTime)
{
}
void APhysicsPawn::PhysicsPostStep(float DeltaTime)
{
}
void APhysicsPawn::PhysicsPostSim(float DeltaTime)
{
}
<commit_msg>Minor tweak.<commit_after>// Copyright 2017 0lento. All Rights Reserved.
#include "FixedTimestepDemo.h"
#include "PhysicsPublic.h"
#include "PhysicsPawn.h"
APhysicsPawn::APhysicsPawn()
{
PrimaryActorTick.bCanEverTick = true;
PrimaryActorTick.TickGroup = ETickingGroup::TG_PrePhysics;
PrimaryActorTick.bStartWithTickEnabled = true;
PostPhysicsTickFunction.TickGroup = TG_PostPhysics;
PostPhysicsTickFunction.bCanEverTick = true;
PostPhysicsTickFunction.bStartWithTickEnabled = true;
}
void APhysicsPawn::BeginPlay()
{
Super::BeginPlay();
if (!IsTemplate() && PostPhysicsTickFunction.bCanEverTick)
{
PostPhysicsTickFunction.Target = this;
PostPhysicsTickFunction.SetTickFunctionEnable(PostPhysicsTickFunction.bStartWithTickEnabled);
PostPhysicsTickFunction.RegisterTickFunction(GetLevel());
}
FPhysScene* PScene = GetWorld()->GetPhysicsScene();
if (PScene != NULL)
{
OnPhysScenePreTickHandle = PScene->OnPhysScenePreTick.AddUObject(this, &APhysicsPawn::PhysScenePreTick);
OnPhysSceneStepHandle = PScene->OnPhysSceneStep.AddUObject(this, &APhysicsPawn::PhysSceneStep);
}
}
void FPostPhysicsTickFunction::ExecuteTick(float DeltaTime, ELevelTick TickType, ENamedThreads::Type CurrentThread, const FGraphEventRef& CompletionGraphEvent)
{
if (Target && !Target->HasAnyFlags(EObjectFlags::RF_BeginDestroyed | EObjectFlags::RF_FinishDestroyed))
{
FScopeCycleCounterUObject ActorScope(Target);
Target->PostPhysicsTick(DeltaTime, TickType, *this);
}
}
FString FPostPhysicsTickFunction::DiagnosticMessage()
{
return Target->GetFullName() + TEXT("[FixedTimestepPawn Post Physics Tick]");
}
void APhysicsPawn::PhysScenePreTick(FPhysScene* PhysScene, uint32 SceneType, float DeltaTime)
{
PhysicsStepCount = 0;
PhysicsPreSim(DeltaTime);
}
void APhysicsPawn::PhysSceneStep(FPhysScene* PhysScene, uint32 SceneType, float DeltaTime)
{
// If not the first physics step, make sure to run previous steps post step before new one
if (PhysicsStepCount)
{
PhysicsPostStep(DeltaTime);
}
PhysicsStepCount++;
PhysicsStep(DeltaTime);
}
void APhysicsPawn::PostPhysicsTick(float DeltaTime, ELevelTick TickType, FPostPhysicsTickFunction& TickFunction)
{
PhysicsPostStep(DeltaTime); // Run PhysScenePostTick for the last physics step
PhysicsPostSim(DeltaTime);
}
void APhysicsPawn::PhysicsPreSim(float DeltaTime)
{
}
void APhysicsPawn::PhysicsStep(float DeltaTime)
{
}
void APhysicsPawn::PhysicsPostStep(float DeltaTime)
{
}
void APhysicsPawn::PhysicsPostSim(float DeltaTime)
{
}
<|endoftext|>
|
<commit_before>
#include "../Flare.h"
#include "FlareSpacecraftPawn.h"
#include "FlareRCS.h"
#include "../Player/FlarePlayerController.h"
#include "../Game/FlareGame.h"
/*----------------------------------------------------
Constructor
----------------------------------------------------*/
AFlareSpacecraftPawn::AFlareSpacecraftPawn(const class FObjectInitializer& PCIP)
: Super(PCIP)
, PresentationMode(false)
, CameraPanSpeed(2)
, CameraMaxPitch(60)
, CameraMaxYaw(180)
, CameraMinDistance(1.5)
, CameraMaxDistance(4)
, CameraDistanceStepAmount(0.5)
, Company(NULL)
{
// Camera containers
CameraContainerYaw = PCIP.CreateDefaultSubobject<USceneComponent>(this, TEXT("CameraContainerYaw"));
CameraContainerPitch = PCIP.CreateDefaultSubobject<USceneComponent>(this, TEXT("CameraContainerPitch"));
CameraContainerPitch->AttachTo(CameraContainerYaw);
// Camera component
Camera = PCIP.CreateDefaultSubobject<UCameraComponent>(this, TEXT("Camera"));
Camera->AttachTo(CameraContainerPitch);
}
/*----------------------------------------------------
Gameplay
----------------------------------------------------*/
void AFlareSpacecraftPawn::BeginPlay()
{
Super::BeginPlay();
}
void AFlareSpacecraftPawn::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
// Apply interpolated values
CameraContainerPitch->SetRelativeRotation(FRotator(CameraOffsetPitch, 0, 0).GetNormalized());
CameraContainerYaw->SetRelativeRotation(FRotator(0, CameraOffsetYaw, 0).GetNormalized());
Camera->SetRelativeLocation(CameraLocalPosition - FVector(CameraOffsetDistance, 0, 0));
}
/*----------------------------------------------------
Camera control
----------------------------------------------------*/
void AFlareSpacecraftPawn::SetCameraPitch(float Value)
{
CameraOffsetPitch = FMath::Clamp(Value, -CameraMaxPitch, +CameraMaxPitch);
}
void AFlareSpacecraftPawn::SetCameraYaw(float Value)
{
CameraOffsetYaw = FMath::Clamp(Value, -CameraMaxYaw, +CameraMaxYaw);
}
void AFlareSpacecraftPawn::SetCameraLocalPosition(FVector Value)
{
CameraLocalPosition = Value;
}
void AFlareSpacecraftPawn::SetCameraDistance(float Value)
{
CameraOffsetDistance = Value;
}
void AFlareSpacecraftPawn::StepCameraDistance(bool TowardCenter)
{
// Compute camera data
float Scale = GetMeshScale();
float LimitNear = Scale * CameraMinDistance;
float LimitFar = Scale * CameraMaxDistance;
float Offset = Scale * (TowardCenter ? -CameraDistanceStepAmount : CameraDistanceStepAmount);
// Move camera
SetCameraDistance(FMath::Clamp(CameraOffsetDistance + Offset, LimitNear, LimitFar));
}
/*----------------------------------------------------
Customization
----------------------------------------------------*/
void AFlareSpacecraftPawn::SetCompany(UFlareCompany* NewCompany)
{
Company = NewCompany;
}
void AFlareSpacecraftPawn::ReloadPart(UFlareSpacecraftComponent* Target, const FFlareSpacecraftComponentSave* Data)
{
Target->Initialize(Data, Company, this);
}
void AFlareSpacecraftPawn::UpdateCustomization()
{
// Required data
TArray<UActorComponent*> ActorComponents;
GetComponents(ActorComponents);
// Find all components
for (TArray<UActorComponent*>::TIterator ComponentIt(ActorComponents); ComponentIt; ++ComponentIt)
{
UFlareSpacecraftComponent* Component = Cast<UFlareSpacecraftComponent>(*ComponentIt);
if (Component)
{
if (!Component->IsInitialized())
{
ReloadPart(Component, NULL);
}
Component->UpdateCustomization();
}
}
}
void AFlareSpacecraftPawn::StartPresentation()
{
PresentationMode = true;
PresentationModeStarted();
}
/*----------------------------------------------------
Helpers
----------------------------------------------------*/
float AFlareSpacecraftPawn::GetRotationAmount(const FQuat& X, bool ClampToHalfTurn)
{
float Angle;
FVector Vector;
X.ToAxisAndAngle(Vector, Angle);
if (ClampToHalfTurn)
{
return FMath::Clamp(FMath::RadiansToDegrees(Angle), 0.0f, 180.0f);
}
else
{
return FMath::RadiansToDegrees(Angle);
}
}
FQuat AFlareSpacecraftPawn::ClampQuaternion(const FQuat& X, float Angle)
{
float RotAngle = GetRotationAmount(X);
if (RotAngle > Angle)
{
return FQuat::Slerp(FQuat::MakeFromEuler(FVector::ZeroVector), X, Angle / RotAngle);
}
else
{
return X;
}
}
float AFlareSpacecraftPawn::TriStateRegulator(float Target, float Current, float Threshold)
{
float Diff = Target - Current;
float AbsDiff = FMath::Abs(Diff);
if (AbsDiff > Threshold)
{
return (Diff > 0) ? -1 : 1;
}
else
{
return 0;
}
}
FQuat AFlareSpacecraftPawn::WorldToLocal(const FQuat& World)
{
FRotator WorldRotator = World.Rotator();
FTransform ParentWorldTransform = RootComponent->GetComponentTransform();
FVector Forward = ParentWorldTransform.InverseTransformVector(FRotationMatrix(WorldRotator).GetScaledAxis(EAxis::X));
FVector Right = ParentWorldTransform.InverseTransformVector(FRotationMatrix(WorldRotator).GetScaledAxis(EAxis::Y));
FVector Up = ParentWorldTransform.InverseTransformVector(FRotationMatrix(WorldRotator).GetScaledAxis(EAxis::Z));
FMatrix RotMatrix(Forward, Right, Up, FVector::ZeroVector);
FQuat Result = RotMatrix.ToQuat();
Result.Normalize();
return Result;
}
FVector AFlareSpacecraftPawn::WorldToLocal(FVector World)
{
return RootComponent->GetComponentTransform().InverseTransformVectorNoScale(World);
}
AFlarePlayerController* AFlareSpacecraftPawn::GetPC() const
{
return Cast<AFlarePlayerController>(GetController());
}
bool AFlareSpacecraftPawn::IsFlownByPlayer() const
{
AFlarePlayerController* PC = Cast<AFlarePlayerController>(GetWorld()->GetFirstPlayerController());
if (PC)
{
return (PC->GetShipPawn() == this);
}
else
{
return false;
}
}
AFlareGame* AFlareSpacecraftPawn::GetGame() const
{
return Cast<AFlareGame>(GetWorld()->GetAuthGameMode());
}
float AFlareSpacecraftPawn::GetMeshScale() const
{
FVector Origin;
FVector Extent;
FBox Box = GetComponentsBoundingBox();
return FMath::Max(Box.GetExtent().Size(), 1.0f);
}
<commit_msg>Add TODO on strange code<commit_after>
#include "../Flare.h"
#include "FlareSpacecraftPawn.h"
#include "FlareRCS.h"
#include "../Player/FlarePlayerController.h"
#include "../Game/FlareGame.h"
/*----------------------------------------------------
Constructor
----------------------------------------------------*/
AFlareSpacecraftPawn::AFlareSpacecraftPawn(const class FObjectInitializer& PCIP)
: Super(PCIP)
, PresentationMode(false)
, CameraPanSpeed(2)
, CameraMaxPitch(60)
, CameraMaxYaw(180)
, CameraMinDistance(1.5)
, CameraMaxDistance(4)
, CameraDistanceStepAmount(0.5)
, Company(NULL)
{
// Camera containers
CameraContainerYaw = PCIP.CreateDefaultSubobject<USceneComponent>(this, TEXT("CameraContainerYaw"));
CameraContainerPitch = PCIP.CreateDefaultSubobject<USceneComponent>(this, TEXT("CameraContainerPitch"));
CameraContainerPitch->AttachTo(CameraContainerYaw);
// Camera component
Camera = PCIP.CreateDefaultSubobject<UCameraComponent>(this, TEXT("Camera"));
Camera->AttachTo(CameraContainerPitch);
}
/*----------------------------------------------------
Gameplay
----------------------------------------------------*/
void AFlareSpacecraftPawn::BeginPlay()
{
Super::BeginPlay();
}
void AFlareSpacecraftPawn::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
// Apply interpolated values
CameraContainerPitch->SetRelativeRotation(FRotator(CameraOffsetPitch, 0, 0).GetNormalized());
CameraContainerYaw->SetRelativeRotation(FRotator(0, CameraOffsetYaw, 0).GetNormalized());
Camera->SetRelativeLocation(CameraLocalPosition - FVector(CameraOffsetDistance, 0, 0));
}
/*----------------------------------------------------
Camera control
----------------------------------------------------*/
void AFlareSpacecraftPawn::SetCameraPitch(float Value)
{
CameraOffsetPitch = FMath::Clamp(Value, -CameraMaxPitch, +CameraMaxPitch);
}
void AFlareSpacecraftPawn::SetCameraYaw(float Value)
{
CameraOffsetYaw = FMath::Clamp(Value, -CameraMaxYaw, +CameraMaxYaw);
}
void AFlareSpacecraftPawn::SetCameraLocalPosition(FVector Value)
{
CameraLocalPosition = Value;
}
void AFlareSpacecraftPawn::SetCameraDistance(float Value)
{
CameraOffsetDistance = Value;
}
void AFlareSpacecraftPawn::StepCameraDistance(bool TowardCenter)
{
// Compute camera data
float Scale = GetMeshScale();
float LimitNear = Scale * CameraMinDistance;
float LimitFar = Scale * CameraMaxDistance;
float Offset = Scale * (TowardCenter ? -CameraDistanceStepAmount : CameraDistanceStepAmount);
// Move camera
SetCameraDistance(FMath::Clamp(CameraOffsetDistance + Offset, LimitNear, LimitFar));
}
/*----------------------------------------------------
Customization
----------------------------------------------------*/
void AFlareSpacecraftPawn::SetCompany(UFlareCompany* NewCompany)
{
Company = NewCompany;
}
void AFlareSpacecraftPawn::ReloadPart(UFlareSpacecraftComponent* Target, const FFlareSpacecraftComponentSave* Data)
{
Target->Initialize(Data, Company, this);
}
void AFlareSpacecraftPawn::UpdateCustomization()
{
// Required data
TArray<UActorComponent*> ActorComponents;
GetComponents(ActorComponents);
// Find all components
for (TArray<UActorComponent*>::TIterator ComponentIt(ActorComponents); ComponentIt; ++ComponentIt)
{
UFlareSpacecraftComponent* Component = Cast<UFlareSpacecraftComponent>(*ComponentIt);
if (Component)
{
if (!Component->IsInitialized())
{
ReloadPart(Component, NULL);
}
Component->UpdateCustomization();
}
}
}
void AFlareSpacecraftPawn::StartPresentation()
{
PresentationMode = true;
PresentationModeStarted();
}
/*----------------------------------------------------
Helpers
----------------------------------------------------*/
float AFlareSpacecraftPawn::GetRotationAmount(const FQuat& X, bool ClampToHalfTurn)
{
float Angle;
FVector Vector;
X.ToAxisAndAngle(Vector, Angle);
if (ClampToHalfTurn)
{
return FMath::Clamp(FMath::RadiansToDegrees(Angle), 0.0f, 180.0f);
}
else
{
return FMath::RadiansToDegrees(Angle);
}
}
FQuat AFlareSpacecraftPawn::ClampQuaternion(const FQuat& X, float Angle)
{
float RotAngle = GetRotationAmount(X);
if (RotAngle > Angle)
{
return FQuat::Slerp(FQuat::MakeFromEuler(FVector::ZeroVector), X, Angle / RotAngle);
}
else
{
return X;
}
}
float AFlareSpacecraftPawn::TriStateRegulator(float Target, float Current, float Threshold)
{
float Diff = Target - Current;
float AbsDiff = FMath::Abs(Diff);
if (AbsDiff > Threshold)
{
return (Diff > 0) ? -1 : 1;
}
else
{
return 0;
}
}
FQuat AFlareSpacecraftPawn::WorldToLocal(const FQuat& World)
{
FRotator WorldRotator = World.Rotator();
FTransform ParentWorldTransform = RootComponent->GetComponentTransform();
FVector Forward = ParentWorldTransform.InverseTransformVector(FRotationMatrix(WorldRotator).GetScaledAxis(EAxis::X));
FVector Right = ParentWorldTransform.InverseTransformVector(FRotationMatrix(WorldRotator).GetScaledAxis(EAxis::Y));
FVector Up = ParentWorldTransform.InverseTransformVector(FRotationMatrix(WorldRotator).GetScaledAxis(EAxis::Z));
FMatrix RotMatrix(Forward, Right, Up, FVector::ZeroVector);
FQuat Result = RotMatrix.ToQuat();
Result.Normalize();
return Result;
}
FVector AFlareSpacecraftPawn::WorldToLocal(FVector World)
{
return RootComponent->GetComponentTransform().InverseTransformVectorNoScale(World);
}
AFlarePlayerController* AFlareSpacecraftPawn::GetPC() const
{
return Cast<AFlarePlayerController>(GetController());
}
bool AFlareSpacecraftPawn::IsFlownByPlayer() const
{
AFlarePlayerController* PC = Cast<AFlarePlayerController>(GetWorld()->GetFirstPlayerController());
if (PC)
{
return (PC->GetShipPawn() == this);
}
else
{
return false;
}
}
AFlareGame* AFlareSpacecraftPawn::GetGame() const
{
return Cast<AFlareGame>(GetWorld()->GetAuthGameMode());
}
float AFlareSpacecraftPawn::GetMeshScale() const
{
// TODO check diameter/radius usage
FVector Origin;
FVector Extent;
FBox Box = GetComponentsBoundingBox();
return FMath::Max(Box.GetExtent().Size(), 1.0f);
}
<|endoftext|>
|
<commit_before><commit_msg>Fix potential startup crash with some window positions<commit_after><|endoftext|>
|
<commit_before>//
// ColourUtils.cpp
// Chilli Source
// Created by Scott Downie on 03/04/2014.
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Tag Games Limited
//
// 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 <ChilliSource/Core/Base/ColourUtils.h>
#include <ChilliSource/Core/Math/MathUtils.h>
namespace ChilliSource
{
namespace Core
{
namespace ColourUtils
{
//-----------------------------------------------------------
//-----------------------------------------------------------
ByteColour ColourToByteColour(const Colour& in_colour)
{
return ColourToByteColour(in_colour.r, in_colour.g, in_colour.b, in_colour.a);
}
//-----------------------------------------------------------
//-----------------------------------------------------------
ByteColour ColourToByteColour(f32 in_red, f32 in_green, f32 in_blue, f32 in_alpha)
{
CS_ASSERT(in_red >= 0.0f && in_red <= 1.0f, "Colour must be in range 0.0 - 1.0");
CS_ASSERT(in_green >= 0.0f && in_green <= 1.0f, "Colour must be in range 0.0 - 1.0");
CS_ASSERT(in_blue >= 0.0f && in_blue <= 1.0f, "Colour must be in range 0.0 - 1.0");
CS_ASSERT(in_alpha >= 0.0f && in_alpha <= 1.0f, "Colour must be in range 0.0 - 1.0");
ByteColour result;
result.r = MathUtils::Round(in_red * 255.0f);
result.g = MathUtils::Round(in_green * 255.0f);
result.b = MathUtils::Round(in_blue * 255.0f);
result.a = MathUtils::Round(in_alpha * 255.0f);
return result;
}
//-----------------------------------------------------------
//-----------------------------------------------------------
Colour PackedRGBAToColour(u32 in_rgba)
{
u8 byteR = (in_rgba >> 24) & 255;
u8 byteG = (in_rgba >> 16) & 255;
u8 byteB = (in_rgba >> 8) & 255;
u8 byteA = (in_rgba) & 255;
return Colour((f32)byteR/255.0f, (f32)byteG/255.0f, (f32)byteB/255.0f, (f32)byteA/255.0f);
}
}
}
}
<commit_msg>Explicitly casting ColourToByteColour to u8<commit_after>//
// ColourUtils.cpp
// Chilli Source
// Created by Scott Downie on 03/04/2014.
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Tag Games Limited
//
// 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 <ChilliSource/Core/Base/ColourUtils.h>
#include <ChilliSource/Core/Math/MathUtils.h>
namespace ChilliSource
{
namespace Core
{
namespace ColourUtils
{
//-----------------------------------------------------------
//-----------------------------------------------------------
ByteColour ColourToByteColour(const Colour& in_colour)
{
return ColourToByteColour(in_colour.r, in_colour.g, in_colour.b, in_colour.a);
}
//-----------------------------------------------------------
//-----------------------------------------------------------
ByteColour ColourToByteColour(f32 in_red, f32 in_green, f32 in_blue, f32 in_alpha)
{
CS_ASSERT(in_red >= 0.0f && in_red <= 1.0f, "Colour must be in range 0.0 - 1.0");
CS_ASSERT(in_green >= 0.0f && in_green <= 1.0f, "Colour must be in range 0.0 - 1.0");
CS_ASSERT(in_blue >= 0.0f && in_blue <= 1.0f, "Colour must be in range 0.0 - 1.0");
CS_ASSERT(in_alpha >= 0.0f && in_alpha <= 1.0f, "Colour must be in range 0.0 - 1.0");
ByteColour result;
result.r = (u8)MathUtils::Round(in_red * 255.0f);
result.g = (u8)MathUtils::Round(in_green * 255.0f);
result.b = (u8)MathUtils::Round(in_blue * 255.0f);
result.a = (u8)MathUtils::Round(in_alpha * 255.0f);
return result;
}
//-----------------------------------------------------------
//-----------------------------------------------------------
Colour PackedRGBAToColour(u32 in_rgba)
{
u8 byteR = (in_rgba >> 24) & 255;
u8 byteG = (in_rgba >> 16) & 255;
u8 byteB = (in_rgba >> 8) & 255;
u8 byteA = (in_rgba) & 255;
return Colour((f32)byteR/255.0f, (f32)byteG/255.0f, (f32)byteB/255.0f, (f32)byteA/255.0f);
}
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <Chaos/Base/Platform.h>
#include <Chaos/Base/Types.h>
#include <Chaos/Except/SystemError.h>
#include <Chaos/IO/ColorIO.h>
#include <Chaos/Kern/KernCommon.h>
#include <Chaos/Datetime/Date.h>
#include <Chaos/Datetime/Timezone.h>
namespace Chaos {
struct Transition {
std::time_t gmttime;
std::time_t localtime;
int localtime_index;
Transition(std::time_t gmt, std::time_t lt, int index)
: gmttime(gmt)
, localtime(lt)
, localtime_index(index) {
}
};
struct TransitionCompare {
bool compare_with_gmt{};
explicit TransitionCompare(bool cmp_with_gmt)
: compare_with_gmt(cmp_with_gmt) {
}
bool operator()(const Transition& a, const Transition& b) const {
if (compare_with_gmt)
return a.gmttime < b.gmttime;
else
return a.localtime < b.localtime;
}
bool equal(const Transition& a, const Transition& b) const {
if (compare_with_gmt)
return a.gmttime == b.gmttime;
else
return a.localtime == b.localtime;
}
};
struct Localtime {
std::time_t gmtoff;
bool isdst;
int arrb_index;
Localtime(std::time_t _gmtoff, bool _isdst, int _arrb)
: gmtoff(_gmtoff)
, isdst(_isdst)
, arrb_index(_arrb) {
}
};
static constexpr int kSecondsPerDay = 86400; // 24 * 60 * 60
struct TZData {
std::vector<Transition> transitions;
std::vector<Localtime> localtimes;
std::vector<std::string> names;
std::string abbreviation;
};
inline void fill_time(std::uint32_t sec, struct std::tm& utc) {
std::uint32_t min = sec / 60;
utc.tm_hour = min / 60;
utc.tm_min = min % 60;
utc.tm_sec = sec % 60;
}
class TZFile : private UnCopyable {
std::FILE* stream_{};
public:
TZFile(const char* fname)
: stream_(std::fopen(fname, "rb")) {
}
~TZFile(void) {
if (nullptr != stream_)
std::fclose(stream_);
}
bool is_valid(void) const {
return nullptr != stream_;
}
std::string read_bytes(std::size_t bytes) {
CHAOS_ARRAY(char, buf, bytes);
std::size_t n = std::fread(buf, 1, bytes, stream_);
if (n != bytes)
__chaos_throw_exception(std::logic_error("no enough data"));
return buf;
}
template <typename Integer>
Integer read_integer(void) {
static_assert(
(sizeof(Integer) == sizeof(std::int8_t) ||
sizeof(Integer) == sizeof(std::int16_t) ||
sizeof(Integer) == sizeof(std::int32_t) ||
sizeof(Integer) == sizeof(std::int64_t)),
"Integer size should be `1`, `2`, `4`, `8` bytes");
Integer x = 0;
std::size_t n = std::fread(&x, 1, sizeof(Integer), stream_);
if (n != sizeof(Integer))
__chaos_throw_exception(std::logic_error("bad Integer data"));
return x;
}
std::uint8_t read_uint8(void) {
return read_integer<std::uint8_t>();
}
std::int32_t read_int32(void) {
return read_integer<std::int32_t>();
}
};
bool read_timezone_file(const char* zonefile, struct TZData* tzdata) {
TZFile f(zonefile);
if (f.is_valid()) {
try {
std::string head = f.read_bytes(4);
if (head != "TZif")
throw std::logic_error("read_timezone_file - bad head");
std::string version = f.read_bytes(1);
f.read_bytes(15);
std::int32_t isgmtcnt = f.read_int32();
std::int32_t isstdcnt = f.read_int32();
std::int32_t leapcnt = f.read_int32();
std::int32_t timecnt = f.read_int32();
std::int32_t typecnt = f.read_int32();
std::int32_t charcnt = f.read_int32();
std::vector<std::int32_t> trans;
std::vector<int> localtimes;
trans.reserve(timecnt);
for (int i = 0; i < timecnt; ++i)
trans.push_back(f.read_int32());
for (int i = 0; i < timecnt; ++i)
localtimes.push_back(f.read_uint8());
for (int i = 0; i < typecnt; ++i) {
std::int32_t gmtoff = f.read_int32();
bool isdst = 0 != f.read_uint8();
std::uint8_t arrb_index = f.read_uint8();
tzdata->localtimes.push_back(Localtime(gmtoff, isdst, arrb_index));
}
for (int i = 0; i < timecnt; ++i) {
int local_index = localtimes[i];
std::time_t lt = trans[i] + tzdata->localtimes[local_index].gmtoff;
tzdata->transitions.push_back(Transition(trans[i], lt, local_index));
}
tzdata->abbreviation = f.read_bytes(charcnt);
for (int i = 0; i < leapcnt; ++i) {
}
CHAOS_UNUSED(isstdcnt);
CHAOS_UNUSED(isgmtcnt);
}
catch (std::logic_error& e) {
ColorIO::fprintf(stderr,
ColorIO::ColorType::COLORTYPE_FG_RED, "%s\n", e.what());
}
}
return true;
}
const Localtime* find_localtime(
const TZData& tzdata, Transition sentry, TransitionCompare cmp) {
const Localtime* local = nullptr;
if (tzdata.transitions.empty() || cmp(sentry, tzdata.transitions.front())) {
local = &tzdata.localtimes.front();
}
else {
auto trans_iter = std::lower_bound(
tzdata.transitions.begin(), tzdata.transitions.end(), sentry, cmp);
if (trans_iter != tzdata.transitions.end()) {
if (!cmp.equal(sentry, *trans_iter)) {
CHAOS_CHECK(trans_iter != tzdata.transitions.begin(),
"TZData's transitions error");
--trans_iter;
}
local = &tzdata.localtimes[trans_iter->localtime_index];
}
else {
local = &tzdata.localtimes[tzdata.transitions.back().localtime_index];
}
}
return local;
}
Timezone::Timezone(const char* zonefile)
: data_(new TZData()) {
if (!read_timezone_file(zonefile, data_.get()))
data_.reset();
}
Timezone::Timezone(int east_of_utc, const char* tzname)
: data_(new TZData()) {
data_->localtimes.push_back(Localtime(east_of_utc, false, 0));
data_->abbreviation = tzname;
}
bool Timezone::is_valid(void) const {
return static_cast<bool>(data_);
}
struct std::tm Timezone::to_localtime(std::time_t sec_since_epoch) const {
struct std::tm ltime{};
CHAOS_CHECK(nullptr != data_,
"Timezone::to_localtime - `data_` should not be null");
const TZData& data(*data_);
Transition sentry(sec_since_epoch, 0, 0);
const Localtime* local =
find_localtime(data, sentry, TransitionCompare(true));
if (nullptr != local) {
std::time_t local_seconds = sec_since_epoch + local->gmtoff;
Chaos::kern_gmtime(&local_seconds, <ime);
ltime.tm_isdst = local->isdst;
#if !defined(CHAOS_WINDOWS)
ltime.tm_gmtoff = local->gmtoff;
ltime.tm_zone = (char*)&data.abbreviation[local->arrb_index];
#endif
}
return ltime;
}
std::time_t Timezone::from_localtime(const struct std::tm& t) const {
CHAOS_CHECK(nullptr != data_,
"Timezone::from_localtime - `data_` should not be null");
const TZData data(*data_);
struct std::tm tmp = t;
std::time_t seconds = Chaos::kern_timegm(&tmp);
Transition sentry(0, seconds, 0);
const Localtime* local =
find_localtime(data, sentry, TransitionCompare(false));
if (t.tm_isdst) {
struct std::tm try_tm = to_localtime(seconds - local->gmtoff);
if (try_tm.tm_isdst && try_tm.tm_hour ==
t.tm_hour && try_tm.tm_min == t.tm_min)
seconds -= 3600;
}
return seconds - local->gmtoff;
}
struct std::tm Timezone::to_utc_time(std::time_t sec_since_epoch, bool yday) {
struct std::tm utc{};
#if !defined(CHAOS_WINDOWS)
utc.tm_zone = const_cast<char*>("GMT");
#endif
int seconds = static_cast<int>(sec_since_epoch % kSecondsPerDay);
int days = static_cast<int>(sec_since_epoch / kSecondsPerDay);
if (seconds < 0) {
seconds += kSecondsPerDay;
--days;
}
fill_time(seconds, utc);
Date date(days + Date::kEpochDay19700101);
Date::DateValue dv = date.get_date();
utc.tm_year = dv.year - 1900;
utc.tm_mon = dv.month - 1;
utc.tm_mday = dv.day;
utc.tm_wday = date.weekday();
if (yday) {
Date start(dv.year, 1, 1);
utc.tm_yday = date.epoch_day() - start.epoch_day();
}
return utc;
}
std::time_t Timezone::from_utc_time(const struct std::tm& utc) {
return from_utc_time(utc.tm_year + 1900,
utc.tm_mon + 1, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec);
}
std::time_t Timezone::from_utc_time(
int year, int month, int day, int hour, int min, int sec) {
Date date(year, month, day);
int sec_in_day = hour * 3600 + min * 60 + sec;
std::time_t days = date.epoch_day() - Date::kEpochDay19700101;
return days * kSecondsPerDay + sec_in_day;
}
}
<commit_msg>:construction: chore(timezone): updated the checking of timezone<commit_after>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <Chaos/Base/Platform.h>
#include <Chaos/Base/Types.h>
#include <Chaos/Except/SystemError.h>
#include <Chaos/IO/ColorIO.h>
#include <Chaos/Kern/KernCommon.h>
#include <Chaos/Datetime/Date.h>
#include <Chaos/Datetime/Timezone.h>
namespace Chaos {
struct Transition {
std::time_t gmttime;
std::time_t localtime;
int localtime_index;
Transition(std::time_t gmt, std::time_t lt, int index)
: gmttime(gmt)
, localtime(lt)
, localtime_index(index) {
}
};
struct TransitionCompare {
bool compare_with_gmt{};
explicit TransitionCompare(bool cmp_with_gmt)
: compare_with_gmt(cmp_with_gmt) {
}
bool operator()(const Transition& a, const Transition& b) const {
if (compare_with_gmt)
return a.gmttime < b.gmttime;
else
return a.localtime < b.localtime;
}
bool equal(const Transition& a, const Transition& b) const {
if (compare_with_gmt)
return a.gmttime == b.gmttime;
else
return a.localtime == b.localtime;
}
};
struct Localtime {
std::time_t gmtoff;
bool isdst;
int arrb_index;
Localtime(std::time_t _gmtoff, bool _isdst, int _arrb)
: gmtoff(_gmtoff)
, isdst(_isdst)
, arrb_index(_arrb) {
}
};
static constexpr int kSecondsPerDay = 86400; // 24 * 60 * 60
struct TZData {
std::vector<Transition> transitions;
std::vector<Localtime> localtimes;
std::vector<std::string> names;
std::string abbreviation;
};
inline void fill_time(std::uint32_t sec, struct std::tm& utc) {
std::uint32_t min = sec / 60;
utc.tm_hour = min / 60;
utc.tm_min = min % 60;
utc.tm_sec = sec % 60;
}
class TZFile : private UnCopyable {
std::FILE* stream_{};
public:
TZFile(const char* fname)
: stream_(std::fopen(fname, "rb")) {
}
~TZFile(void) {
if (nullptr != stream_)
std::fclose(stream_);
}
bool is_valid(void) const {
return nullptr != stream_;
}
std::string read_bytes(std::size_t bytes) {
CHAOS_ARRAY(char, buf, bytes);
std::size_t n = std::fread(buf, 1, bytes, stream_);
if (n != bytes)
__chaos_throw_exception(std::logic_error("no enough data"));
return buf;
}
template <typename Integer>
Integer read_integer(void) {
static_assert(
(sizeof(Integer) == sizeof(std::int8_t) ||
sizeof(Integer) == sizeof(std::int16_t) ||
sizeof(Integer) == sizeof(std::int32_t) ||
sizeof(Integer) == sizeof(std::int64_t)),
"Integer size should be `1`, `2`, `4`, `8` bytes");
Integer x = 0;
std::size_t n = std::fread(&x, 1, sizeof(Integer), stream_);
if (n != sizeof(Integer))
__chaos_throw_exception(std::logic_error("bad Integer data"));
return x;
}
std::uint8_t read_uint8(void) {
return read_integer<std::uint8_t>();
}
std::int32_t read_int32(void) {
return read_integer<std::int32_t>();
}
};
bool read_timezone_file(const char* zonefile, struct TZData* tzdata) {
if (TZFile f(zonefile); f.is_valid()) {
try {
std::string head = f.read_bytes(4);
if (head != "TZif")
throw std::logic_error("read_timezone_file - bad head");
std::string version = f.read_bytes(1);
f.read_bytes(15);
std::int32_t isgmtcnt = f.read_int32();
std::int32_t isstdcnt = f.read_int32();
std::int32_t leapcnt = f.read_int32();
std::int32_t timecnt = f.read_int32();
std::int32_t typecnt = f.read_int32();
std::int32_t charcnt = f.read_int32();
std::vector<std::int32_t> trans;
std::vector<int> localtimes;
trans.reserve(timecnt);
for (int i = 0; i < timecnt; ++i)
trans.push_back(f.read_int32());
for (int i = 0; i < timecnt; ++i)
localtimes.push_back(f.read_uint8());
for (int i = 0; i < typecnt; ++i) {
std::int32_t gmtoff = f.read_int32();
bool isdst = 0 != f.read_uint8();
std::uint8_t arrb_index = f.read_uint8();
tzdata->localtimes.push_back(Localtime(gmtoff, isdst, arrb_index));
}
for (int i = 0; i < timecnt; ++i) {
int local_index = localtimes[i];
std::time_t lt = trans[i] + tzdata->localtimes[local_index].gmtoff;
tzdata->transitions.push_back(Transition(trans[i], lt, local_index));
}
tzdata->abbreviation = f.read_bytes(charcnt);
for (int i = 0; i < leapcnt; ++i) {
}
CHAOS_UNUSED(isstdcnt);
CHAOS_UNUSED(isgmtcnt);
}
catch (std::logic_error& e) {
ColorIO::fprintf(stderr,
ColorIO::ColorType::COLORTYPE_FG_RED, "%s\n", e.what());
}
}
return true;
}
const Localtime* find_localtime(
const TZData& tzdata, Transition sentry, TransitionCompare cmp) {
const Localtime* local = nullptr;
if (tzdata.transitions.empty() || cmp(sentry, tzdata.transitions.front())) {
local = &tzdata.localtimes.front();
}
else {
auto trans_iter = std::lower_bound(
tzdata.transitions.begin(), tzdata.transitions.end(), sentry, cmp);
if (trans_iter != tzdata.transitions.end()) {
if (!cmp.equal(sentry, *trans_iter)) {
CHAOS_CHECK(trans_iter != tzdata.transitions.begin(),
"TZData's transitions error");
--trans_iter;
}
local = &tzdata.localtimes[trans_iter->localtime_index];
}
else {
local = &tzdata.localtimes[tzdata.transitions.back().localtime_index];
}
}
return local;
}
Timezone::Timezone(const char* zonefile)
: data_(new TZData()) {
if (!read_timezone_file(zonefile, data_.get()))
data_.reset();
}
Timezone::Timezone(int east_of_utc, const char* tzname)
: data_(new TZData()) {
data_->localtimes.push_back(Localtime(east_of_utc, false, 0));
data_->abbreviation = tzname;
}
bool Timezone::is_valid(void) const {
return static_cast<bool>(data_);
}
struct std::tm Timezone::to_localtime(std::time_t sec_since_epoch) const {
struct std::tm ltime{};
CHAOS_CHECK(nullptr != data_,
"Timezone::to_localtime - `data_` should not be null");
const TZData& data(*data_);
Transition sentry(sec_since_epoch, 0, 0);
const Localtime* local =
find_localtime(data, sentry, TransitionCompare(true));
if (nullptr != local) {
std::time_t local_seconds = sec_since_epoch + local->gmtoff;
Chaos::kern_gmtime(&local_seconds, <ime);
ltime.tm_isdst = local->isdst;
#if !defined(CHAOS_WINDOWS)
ltime.tm_gmtoff = local->gmtoff;
ltime.tm_zone = (char*)&data.abbreviation[local->arrb_index];
#endif
}
return ltime;
}
std::time_t Timezone::from_localtime(const struct std::tm& t) const {
CHAOS_CHECK(nullptr != data_,
"Timezone::from_localtime - `data_` should not be null");
const TZData data(*data_);
struct std::tm tmp = t;
std::time_t seconds = Chaos::kern_timegm(&tmp);
Transition sentry(0, seconds, 0);
const Localtime* local =
find_localtime(data, sentry, TransitionCompare(false));
if (t.tm_isdst) {
struct std::tm try_tm = to_localtime(seconds - local->gmtoff);
if (try_tm.tm_isdst && try_tm.tm_hour ==
t.tm_hour && try_tm.tm_min == t.tm_min)
seconds -= 3600;
}
return seconds - local->gmtoff;
}
struct std::tm Timezone::to_utc_time(std::time_t sec_since_epoch, bool yday) {
struct std::tm utc{};
#if !defined(CHAOS_WINDOWS)
utc.tm_zone = const_cast<char*>("GMT");
#endif
int seconds = static_cast<int>(sec_since_epoch % kSecondsPerDay);
int days = static_cast<int>(sec_since_epoch / kSecondsPerDay);
if (seconds < 0) {
seconds += kSecondsPerDay;
--days;
}
fill_time(seconds, utc);
Date date(days + Date::kEpochDay19700101);
Date::DateValue dv = date.get_date();
utc.tm_year = dv.year - 1900;
utc.tm_mon = dv.month - 1;
utc.tm_mday = dv.day;
utc.tm_wday = date.weekday();
if (yday) {
Date start(dv.year, 1, 1);
utc.tm_yday = date.epoch_day() - start.epoch_day();
}
return utc;
}
std::time_t Timezone::from_utc_time(const struct std::tm& utc) {
return from_utc_time(utc.tm_year + 1900,
utc.tm_mon + 1, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec);
}
std::time_t Timezone::from_utc_time(
int year, int month, int day, int hour, int min, int sec) {
Date date(year, month, day);
int sec_in_day = hour * 3600 + min * 60 + sec;
std::time_t days = date.epoch_day() - Date::kEpochDay19700101;
return days * kSecondsPerDay + sec_in_day;
}
}
<|endoftext|>
|
<commit_before>#include "vortex_controller/controller_ros.h"
#include "vortex/eigen_helper.h"
#include <tf/transform_datatypes.h>
#include <eigen_conversions/eigen_msg.h>
#include "std_msgs/String.h"
#include <math.h>
#include <map>
#include <string>
#include <vector>
Controller::Controller(ros::NodeHandle nh) : nh(nh)
{
command_sub = nh.subscribe("propulsion_command", 10, &Controller::commandCallback, this);
state_sub = nh.subscribe("state_estimate", 10, &Controller::stateCallback, this);
wrench_pub = nh.advertise<geometry_msgs::Wrench>("rov_forces", 10);
mode_pub = nh.advertise<std_msgs::String>("controller/mode", 10);
control_mode = ControlModes::OPEN_LOOP;
if (!nh.getParam("/controller/frequency", frequency))
{
ROS_WARN("Failed to read parameter controller frequency, defaulting to 10 Hz.");
frequency = 10;
}
state = new State();
initSetpoints();
initPositionHoldController();
// Set up a dynamic reconfigure server
dynamic_reconfigure::Server<vortex_controller::VortexControllerConfig>::CallbackType dr_cb;
dr_cb = boost::bind(&Controller::configCallback, this, _1, _2);
dr_srv.setCallback(dr_cb);
ROS_INFO("Node initialized.");
}
void Controller::commandCallback(const vortex_msgs::PropulsionCommand& msg)
{
if (!healthyMessage(msg))
return;
ControlMode new_control_mode;
{
int i;
for (i = 0; i < msg.control_mode.size(); ++i)
if (msg.control_mode[i])
break;
new_control_mode = static_cast<ControlMode>(i);
}
if (new_control_mode != control_mode)
{
control_mode = new_control_mode;
Eigen::Vector3d position;
Eigen::Quaterniond orientation;
Eigen::Vector6d velocity;
// Reset setpoints to be equal to state
state->get(&position, &orientation, &velocity);
setpoints->set(position, orientation);
ROS_INFO_STREAM("Changing mode to " << controlModeString(control_mode) << ".");
}
publishControlMode();
double time = msg.header.stamp.toSec();
Eigen::Vector6d command;
for (int i = 0; i < 6; ++i)
command(i) = msg.motion[i];
setpoints->update(time, command);
}
void Controller::stateCallback(const nav_msgs::Odometry &msg)
{
Eigen::Vector3d position;
Eigen::Quaterniond orientation;
Eigen::Vector6d velocity;
tf::pointMsgToEigen(msg.pose.pose.position, position);
tf::quaternionMsgToEigen(msg.pose.pose.orientation, orientation);
tf::twistMsgToEigen(msg.twist.twist, velocity);
const double MAX_QUAT_NORM_DEVIATION = 0.1;
bool orientation_invalid = (abs(orientation.norm() - 1) > MAX_QUAT_NORM_DEVIATION);
if (isFucked(position) || isFucked(velocity) || orientation_invalid)
{
ROS_WARN("Requested state not valid, ignoring...");
return;
}
state->set(position, orientation, velocity);
}
void Controller::configCallback(const vortex_controller::VortexControllerConfig &config, uint32_t level)
{
ROS_INFO_STREAM("Setting gains: [velocity = " << config.velocity_gain << ", position = " << config.position_gain
<< ", attitude = " << config.attitude_gain << "]");
controller->setGains(config.velocity_gain, config.position_gain, config.attitude_gain);
}
void Controller::spin()
{
Eigen::Vector6d tau_command = Eigen::VectorXd::Zero(6);
Eigen::Vector6d tau_openloop = Eigen::VectorXd::Zero(6);
Eigen::Vector6d tau_restoring = Eigen::VectorXd::Zero(6);
Eigen::Vector6d tau_staylevel = Eigen::VectorXd::Zero(6);
Eigen::Vector6d tau_depthhold = Eigen::VectorXd::Zero(6);
Eigen::Vector3d position_state = Eigen::Vector3d::Zero();
Eigen::Quaterniond orientation_state = Eigen::Quaterniond::Identity();
Eigen::Vector6d velocity_state = Eigen::VectorXd::Zero(6);
Eigen::Vector3d position_setpoint = Eigen::Vector3d::Zero();
Eigen::Quaterniond orientation_setpoint = Eigen::Quaterniond::Identity();
ros::Rate rate(frequency);
while (ros::ok())
{
// TODO(mortenfyhn): check value of bool return from getters
// Read state and setpoint
state->get(&position_state, &orientation_state, &velocity_state);
setpoints->get(&position_setpoint, &orientation_setpoint);
// Calculate terms of control vector
setpoints->get(&tau_openloop);
tau_restoring = controller->getRestoring(orientation_state);
switch (control_mode)
{
case ControlModes::OPEN_LOOP:
{
tau_command = tau_openloop;
break;
}
case ControlModes::OPEN_LOOP_RESTORING:
{
tau_command = tau_openloop + tau_restoring;
break;
}
case ControlModes::STAY_LEVEL:
{
// Convert quaternion setpoint to euler angles (ZYX convention)
Eigen::Vector3d euler;
euler = orientation_setpoint.toRotationMatrix().eulerAngles(2, 1, 0);
// Set pitch and roll setpoints to zero
euler(1) = 0;
euler(2) = 0;
// Convert euler setpoint back to quaternions
Eigen::Matrix3d R;
R = Eigen::AngleAxisd(euler(0), Eigen::Vector3d::UnitZ())
* Eigen::AngleAxisd(euler(1), Eigen::Vector3d::UnitY())
* Eigen::AngleAxisd(euler(2), Eigen::Vector3d::UnitX());
Eigen::Quaterniond orientation_staylevel(R);
tau_staylevel = controller->getFeedback(Eigen::Vector3d::Zero(), orientation_state, velocity_state,
Eigen::Vector3d::Zero(), orientation_setpoint);
// Turn off openloop roll and pitch commands
tau_openloop(3) = 0;
tau_openloop(4) = 0;
tau_command = tau_openloop + tau_staylevel;
break;
}
case ControlModes::DEPTH_HOLD:
{
tau_depthhold = controller->getFeedback(position_state,
Eigen::Quaterniond::Identity(),
Eigen::VectorXd::Zero(6),
position_setpoint,
Eigen::Quaterniond::Identity());
tau_command = tau_openloop + tau_depthhold;
break;
}
default:
{
ROS_ERROR("Default control mode reached.");
break;
}
}
geometry_msgs::Wrench msg;
tf::wrenchEigenToMsg(tau_command, msg);
wrench_pub.publish(msg);
ros::spinOnce();
rate.sleep();
}
}
void Controller::initSetpoints()
{
std::vector<double> v;
if (!nh.getParam("/propulsion/command/wrench/max", v))
ROS_FATAL("Failed to read parameter max wrench command.");
Eigen::Vector6d wrench_command_max = Eigen::Vector6d::Map(v.data(), v.size());
if (!nh.getParam("/propulsion/command/wrench/scaling", v))
ROS_FATAL("Failed to read parameter scaling wrench command.");
Eigen::Vector6d wrench_command_scaling = Eigen::Vector6d::Map(v.data(), v.size());
if (!nh.getParam("/propulsion/command/pose/rate", v))
ROS_FATAL("Failed to read parameter pose command rate.");
Eigen::Vector6d pose_command_rate = Eigen::Vector6d::Map(v.data(), v.size());
setpoints = new Setpoints(wrench_command_scaling,
wrench_command_max,
pose_command_rate);
}
void Controller::initPositionHoldController()
{
// Read controller gains from parameter server
double a, b, c;
if (!nh.getParam("/controller/velocity_gain", a))
ROS_ERROR("Failed to read parameter velocity_gain.");
if (!nh.getParam("/controller/position_gain", b))
ROS_ERROR("Failed to read parameter position_gain.");
if (!nh.getParam("/controller/attitude_gain", c))
ROS_ERROR("Failed to read parameter attitude_gain.");
// Read center of gravity and buoyancy vectors
std::vector<double> r_G_vec, r_B_vec;
if (!nh.getParam("/physical/center_of_mass", r_G_vec))
ROS_FATAL("Failed to read robot center of mass parameter.");
if (!nh.getParam("/physical/center_of_buoyancy", r_B_vec))
ROS_FATAL("Failed to read robot center of buoyancy parameter.");
Eigen::Vector3d r_G(r_G_vec.data());
Eigen::Vector3d r_B(r_B_vec.data());
// Read and calculate ROV weight and buoyancy
double mass, displacement, acceleration_of_gravity, density_of_water;
if (!nh.getParam("/physical/mass_kg", mass))
ROS_FATAL("Failed to read parameter mass.");
if (!nh.getParam("/physical/displacement_m3", displacement))
ROS_FATAL("Failed to read parameter displacement.");
if (!nh.getParam("/gravity/acceleration", acceleration_of_gravity))
ROS_FATAL("Failed to read parameter acceleration of gravity");
if (!nh.getParam("/water/density", density_of_water))
ROS_FATAL("Failed to read parameter density of water");
double W = mass * acceleration_of_gravity;
double B = density_of_water * displacement * acceleration_of_gravity;
controller = new QuaternionPdController(a, b, c, W, B, r_G, r_B);
}
bool Controller::healthyMessage(const vortex_msgs::PropulsionCommand& msg)
{
// Check that motion commands are in range
for (int i = 0; i < msg.motion.size(); ++i)
{
if (msg.motion[i] > 1 || msg.motion[i] < -1)
{
ROS_WARN("Motion command out of range.");
return false;
}
}
// Check that exactly one control mode is requested
int num_requested_modes = 0;
for (int i = 0; i < msg.control_mode.size(); ++i)
if (msg.control_mode[i])
num_requested_modes++;
if (num_requested_modes != 1)
{
ROS_WARN_STREAM("Invalid control mode. Attempt to set "
<< num_requested_modes << " control modes at once.");
return false;
}
return true;
}
void Controller::publishControlMode()
{
std::string s = controlModeString(control_mode);
std_msgs::String msg;
msg.data = s;
mode_pub.publish(msg);
}
<commit_msg>Fix stay level bug<commit_after>#include "vortex_controller/controller_ros.h"
#include "vortex/eigen_helper.h"
#include <tf/transform_datatypes.h>
#include <eigen_conversions/eigen_msg.h>
#include "std_msgs/String.h"
#include <math.h>
#include <map>
#include <string>
#include <vector>
Controller::Controller(ros::NodeHandle nh) : nh(nh)
{
command_sub = nh.subscribe("propulsion_command", 10, &Controller::commandCallback, this);
state_sub = nh.subscribe("state_estimate", 10, &Controller::stateCallback, this);
wrench_pub = nh.advertise<geometry_msgs::Wrench>("rov_forces", 10);
mode_pub = nh.advertise<std_msgs::String>("controller/mode", 10);
control_mode = ControlModes::OPEN_LOOP;
if (!nh.getParam("/controller/frequency", frequency))
{
ROS_WARN("Failed to read parameter controller frequency, defaulting to 10 Hz.");
frequency = 10;
}
state = new State();
initSetpoints();
initPositionHoldController();
// Set up a dynamic reconfigure server
dynamic_reconfigure::Server<vortex_controller::VortexControllerConfig>::CallbackType dr_cb;
dr_cb = boost::bind(&Controller::configCallback, this, _1, _2);
dr_srv.setCallback(dr_cb);
ROS_INFO("Node initialized.");
}
void Controller::commandCallback(const vortex_msgs::PropulsionCommand& msg)
{
if (!healthyMessage(msg))
return;
ControlMode new_control_mode;
{
int i;
for (i = 0; i < msg.control_mode.size(); ++i)
if (msg.control_mode[i])
break;
new_control_mode = static_cast<ControlMode>(i);
}
if (new_control_mode != control_mode)
{
control_mode = new_control_mode;
Eigen::Vector3d position;
Eigen::Quaterniond orientation;
Eigen::Vector6d velocity;
// Reset setpoints to be equal to state
state->get(&position, &orientation, &velocity);
setpoints->set(position, orientation);
ROS_INFO_STREAM("Changing mode to " << controlModeString(control_mode) << ".");
}
publishControlMode();
double time = msg.header.stamp.toSec();
Eigen::Vector6d command;
for (int i = 0; i < 6; ++i)
command(i) = msg.motion[i];
setpoints->update(time, command);
}
void Controller::stateCallback(const nav_msgs::Odometry &msg)
{
Eigen::Vector3d position;
Eigen::Quaterniond orientation;
Eigen::Vector6d velocity;
tf::pointMsgToEigen(msg.pose.pose.position, position);
tf::quaternionMsgToEigen(msg.pose.pose.orientation, orientation);
tf::twistMsgToEigen(msg.twist.twist, velocity);
const double MAX_QUAT_NORM_DEVIATION = 0.1;
bool orientation_invalid = (abs(orientation.norm() - 1) > MAX_QUAT_NORM_DEVIATION);
if (isFucked(position) || isFucked(velocity) || orientation_invalid)
{
ROS_WARN("Requested state not valid, ignoring...");
return;
}
state->set(position, orientation, velocity);
}
void Controller::configCallback(const vortex_controller::VortexControllerConfig &config, uint32_t level)
{
ROS_INFO_STREAM("Setting gains: [velocity = " << config.velocity_gain << ", position = " << config.position_gain
<< ", attitude = " << config.attitude_gain << "]");
controller->setGains(config.velocity_gain, config.position_gain, config.attitude_gain);
}
void Controller::spin()
{
Eigen::Vector6d tau_command = Eigen::VectorXd::Zero(6);
Eigen::Vector6d tau_openloop = Eigen::VectorXd::Zero(6);
Eigen::Vector6d tau_restoring = Eigen::VectorXd::Zero(6);
Eigen::Vector6d tau_staylevel = Eigen::VectorXd::Zero(6);
Eigen::Vector6d tau_depthhold = Eigen::VectorXd::Zero(6);
Eigen::Vector3d position_state = Eigen::Vector3d::Zero();
Eigen::Quaterniond orientation_state = Eigen::Quaterniond::Identity();
Eigen::Vector6d velocity_state = Eigen::VectorXd::Zero(6);
Eigen::Vector3d position_setpoint = Eigen::Vector3d::Zero();
Eigen::Quaterniond orientation_setpoint = Eigen::Quaterniond::Identity();
ros::Rate rate(frequency);
while (ros::ok())
{
// TODO(mortenfyhn): check value of bool return from getters
// Read state and setpoint
state->get(&position_state, &orientation_state, &velocity_state);
setpoints->get(&position_setpoint, &orientation_setpoint);
// Calculate terms of control vector
setpoints->get(&tau_openloop);
tau_restoring = controller->getRestoring(orientation_state);
switch (control_mode)
{
case ControlModes::OPEN_LOOP:
{
tau_command = tau_openloop;
break;
}
case ControlModes::OPEN_LOOP_RESTORING:
{
tau_command = tau_openloop + tau_restoring;
break;
}
case ControlModes::STAY_LEVEL:
{
// Convert quaternion setpoint to euler angles (ZYX convention)
Eigen::Vector3d euler;
euler = orientation_state.toRotationMatrix().eulerAngles(2, 1, 0);
// Set pitch and roll setpoints to zero
euler(1) = 0;
euler(2) = 0;
// Convert euler setpoint back to quaternions
Eigen::Matrix3d R;
R = Eigen::AngleAxisd(euler(0), Eigen::Vector3d::UnitZ())
* Eigen::AngleAxisd(euler(1), Eigen::Vector3d::UnitY())
* Eigen::AngleAxisd(euler(2), Eigen::Vector3d::UnitX());
Eigen::Quaterniond orientation_staylevel(R);
tau_staylevel = controller->getFeedback(Eigen::Vector3d::Zero(), orientation_state, velocity_state,
Eigen::Vector3d::Zero(), orientation_staylevel);
// Turn off openloop roll and pitch commands
tau_openloop(3) = 0;
tau_openloop(4) = 0;
tau_command = tau_openloop + tau_staylevel;
break;
}
case ControlModes::DEPTH_HOLD:
{
tau_depthhold = controller->getFeedback(position_state,
Eigen::Quaterniond::Identity(),
Eigen::VectorXd::Zero(6),
position_setpoint,
Eigen::Quaterniond::Identity());
tau_command = tau_openloop + tau_depthhold;
break;
}
default:
{
ROS_ERROR("Default control mode reached.");
break;
}
}
geometry_msgs::Wrench msg;
tf::wrenchEigenToMsg(tau_command, msg);
wrench_pub.publish(msg);
ros::spinOnce();
rate.sleep();
}
}
void Controller::initSetpoints()
{
std::vector<double> v;
if (!nh.getParam("/propulsion/command/wrench/max", v))
ROS_FATAL("Failed to read parameter max wrench command.");
Eigen::Vector6d wrench_command_max = Eigen::Vector6d::Map(v.data(), v.size());
if (!nh.getParam("/propulsion/command/wrench/scaling", v))
ROS_FATAL("Failed to read parameter scaling wrench command.");
Eigen::Vector6d wrench_command_scaling = Eigen::Vector6d::Map(v.data(), v.size());
if (!nh.getParam("/propulsion/command/pose/rate", v))
ROS_FATAL("Failed to read parameter pose command rate.");
Eigen::Vector6d pose_command_rate = Eigen::Vector6d::Map(v.data(), v.size());
setpoints = new Setpoints(wrench_command_scaling,
wrench_command_max,
pose_command_rate);
}
void Controller::initPositionHoldController()
{
// Read controller gains from parameter server
double a, b, c;
if (!nh.getParam("/controller/velocity_gain", a))
ROS_ERROR("Failed to read parameter velocity_gain.");
if (!nh.getParam("/controller/position_gain", b))
ROS_ERROR("Failed to read parameter position_gain.");
if (!nh.getParam("/controller/attitude_gain", c))
ROS_ERROR("Failed to read parameter attitude_gain.");
// Read center of gravity and buoyancy vectors
std::vector<double> r_G_vec, r_B_vec;
if (!nh.getParam("/physical/center_of_mass", r_G_vec))
ROS_FATAL("Failed to read robot center of mass parameter.");
if (!nh.getParam("/physical/center_of_buoyancy", r_B_vec))
ROS_FATAL("Failed to read robot center of buoyancy parameter.");
Eigen::Vector3d r_G(r_G_vec.data());
Eigen::Vector3d r_B(r_B_vec.data());
// Read and calculate ROV weight and buoyancy
double mass, displacement, acceleration_of_gravity, density_of_water;
if (!nh.getParam("/physical/mass_kg", mass))
ROS_FATAL("Failed to read parameter mass.");
if (!nh.getParam("/physical/displacement_m3", displacement))
ROS_FATAL("Failed to read parameter displacement.");
if (!nh.getParam("/gravity/acceleration", acceleration_of_gravity))
ROS_FATAL("Failed to read parameter acceleration of gravity");
if (!nh.getParam("/water/density", density_of_water))
ROS_FATAL("Failed to read parameter density of water");
double W = mass * acceleration_of_gravity;
double B = density_of_water * displacement * acceleration_of_gravity;
controller = new QuaternionPdController(a, b, c, W, B, r_G, r_B);
}
bool Controller::healthyMessage(const vortex_msgs::PropulsionCommand& msg)
{
// Check that motion commands are in range
for (int i = 0; i < msg.motion.size(); ++i)
{
if (msg.motion[i] > 1 || msg.motion[i] < -1)
{
ROS_WARN("Motion command out of range.");
return false;
}
}
// Check that exactly one control mode is requested
int num_requested_modes = 0;
for (int i = 0; i < msg.control_mode.size(); ++i)
if (msg.control_mode[i])
num_requested_modes++;
if (num_requested_modes != 1)
{
ROS_WARN_STREAM("Invalid control mode. Attempt to set "
<< num_requested_modes << " control modes at once.");
return false;
}
return true;
}
void Controller::publishControlMode()
{
std::string s = controlModeString(control_mode);
std_msgs::String msg;
msg.data = s;
mode_pub.publish(msg);
}
<|endoftext|>
|
<commit_before>
#ifndef _WIN32
#include <boost/asio.hpp>
#include <boost/asio/local/stream_protocol.hpp>
#include <sstream>
#include <deque>
#include <algorithm>
#include "vtrc-endpoint-iface.h"
#include "vtrc-application.h"
#include "vtrc-connection-iface.h"
#include "vtrc-connection-list.h"
#include "protocol/vtrc-auth.pb.h"
#include "vtrc-common/vtrc-sizepack-policy.h"
#include "vtrc-common/vtrc-enviroment.h"
#include "vtrc-common/vtrc-hash-iface.h"
#include "vtrc-common/vtrc-data-queue.h"
#include "vtrc-common/vtrc-transport-unix-local.h"
#include "vtrc-protocol-layer-s.h"
#include "vtrc-connection-impl.h"
namespace vtrc { namespace server { namespace endpoints {
namespace {
namespace basio = boost::asio;
namespace bsys = boost::system;
namespace blocal = basio::local;
typedef blocal::stream_protocol bstream;
struct endpoint_unix: public endpoint_iface {
typedef endpoint_unix this_type;
typedef common::transport_unix_local transport_type;
typedef connection_impl<transport_type> connection_type;
typedef connection_type::socket_type socket_type;
application &app_;
basio::io_service &ios_;
common::enviroment env_;
bstream::endpoint endpoint_;
bstream::acceptor acceptor_;
endpoint_options opts_;
endpoint_unix( application &app,
const endpoint_options &opts,
const std::string &name )
:app_(app)
,ios_(app_.get_io_service( ))
,env_(app_.get_enviroment())
,endpoint_(name)
,acceptor_(ios_, endpoint_)
,opts_(opts)
{}
virtual const endpoint_options &get_options( ) const
{
return opts_;
}
application &get_application( )
{
return app_;
}
common::enviroment &get_enviroment( )
{
return env_;
}
std::string string( ) const
{
std::ostringstream oss;
oss << "unix://" << endpoint_.path( );
return oss.str( );
}
void start_accept( )
{
vtrc::shared_ptr<socket_type> new_sock
(vtrc::make_shared<socket_type>(vtrc::ref(ios_)));
acceptor_.async_accept( *new_sock,
vtrc::bind( &this_type::on_accept, this,
basio::placeholders::error, new_sock ));
}
void start( )
{
start_accept( );
app_.on_endpoint_started( this );
}
void stop ( )
{
app_.on_endpoint_stopped( this );
acceptor_.close( );
::unlink(endpoint_.path( ).c_str( ));
}
void on_accept( const bsys::error_code &error,
vtrc::shared_ptr<socket_type> sock )
{
if( error ) {
//delete sock;
} else {
try {
std::cout << "accept\n";
vtrc::shared_ptr<connection_type> new_conn
(connection_type::create(*this, sock, 4096));
app_.get_clients( )->store( new_conn );
} catch( ... ) {
;;;
}
start_accept( );
}
}
};
}
namespace unix_local {
endpoint_iface *create(application &app,
const endpoint_options &opts,
const std::string &name)
{
::unlink( name.c_str( ) );
return new endpoint_unix( app, opts, name );
}
endpoint_iface *create( application &app, const std::string &name )
{
const endpoint_options def_opts = { 5, 20 };
return create( app, def_opts, name );
}
}
}}}
#endif
<commit_msg>protocol<commit_after>
#ifndef _WIN32
#include <boost/asio.hpp>
#include <boost/asio/local/stream_protocol.hpp>
#include <sstream>
#include <deque>
#include <algorithm>
#include "vtrc-endpoint-iface.h"
#include "vtrc-application.h"
#include "vtrc-connection-iface.h"
#include "vtrc-connection-list.h"
#include "vtrc-common/vtrc-enviroment.h"
#include "vtrc-common/vtrc-hash-iface.h"
#include "vtrc-common/vtrc-data-queue.h"
#include "vtrc-common/vtrc-transport-unix-local.h"
#include "vtrc-protocol-layer-s.h"
#include "vtrc-connection-impl.h"
namespace vtrc { namespace server { namespace endpoints {
namespace {
namespace basio = boost::asio;
namespace bsys = boost::system;
namespace blocal = basio::local;
typedef blocal::stream_protocol bstream;
struct endpoint_unix: public endpoint_iface {
typedef endpoint_unix this_type;
typedef common::transport_unix_local transport_type;
typedef connection_impl<transport_type> connection_type;
typedef connection_type::socket_type socket_type;
application &app_;
basio::io_service &ios_;
common::enviroment env_;
bstream::endpoint endpoint_;
bstream::acceptor acceptor_;
endpoint_options opts_;
endpoint_unix( application &app,
const endpoint_options &opts,
const std::string &name )
:app_(app)
,ios_(app_.get_io_service( ))
,env_(app_.get_enviroment())
,endpoint_(name)
,acceptor_(ios_, endpoint_)
,opts_(opts)
{}
virtual const endpoint_options &get_options( ) const
{
return opts_;
}
application &get_application( )
{
return app_;
}
common::enviroment &get_enviroment( )
{
return env_;
}
std::string string( ) const
{
std::ostringstream oss;
oss << "unix://" << endpoint_.path( );
return oss.str( );
}
void start_accept( )
{
vtrc::shared_ptr<socket_type> new_sock
(vtrc::make_shared<socket_type>(vtrc::ref(ios_)));
acceptor_.async_accept( *new_sock,
vtrc::bind( &this_type::on_accept, this,
basio::placeholders::error, new_sock ));
}
void start( )
{
start_accept( );
app_.on_endpoint_started( this );
}
void stop ( )
{
app_.on_endpoint_stopped( this );
acceptor_.close( );
::unlink(endpoint_.path( ).c_str( ));
}
void on_accept( const bsys::error_code &error,
vtrc::shared_ptr<socket_type> sock )
{
if( error ) {
//delete sock;
} else {
try {
std::cout << "accept\n";
vtrc::shared_ptr<connection_type> new_conn
(connection_type::create(*this, sock, 4096));
app_.get_clients( )->store( new_conn );
} catch( ... ) {
;;;
}
start_accept( );
}
}
};
}
namespace unix_local {
endpoint_iface *create(application &app,
const endpoint_options &opts,
const std::string &name)
{
::unlink( name.c_str( ) );
return new endpoint_unix( app, opts, name );
}
endpoint_iface *create( application &app, const std::string &name )
{
const endpoint_options def_opts = { 5, 20 };
return create( app, def_opts, name );
}
}
}}}
#endif
<|endoftext|>
|
<commit_before>/*
Copyright Eli Dupree and Isaac Dupree, 2011, 2012
This file is part of Lasercake.
Lasercake 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.
Lasercake 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 Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LASERCAKE_BORROWED_BITSET_HPP__
#define LASERCAKE_BORROWED_BITSET_HPP__
#include <list>
#include <stack>
#include <boost/utility.hpp>
#include <boost/dynamic_bitset.hpp>
#include "../utils.hpp"
#if !LASERCAKE_NO_THREADS
#include <boost/thread/thread.hpp>
#endif
typedef uint64_t bit_index_type;
namespace borrowed_bitset_impl {
// Noncopying singly linked list that owns its members unless you pop them.
template<typename T>
struct liststack_node : boost::noncopyable {
liststack_node* next;
T here;
liststack_node() : next(nullptr), here() {}
template<typename Arg>
explicit liststack_node(Arg const& arg, liststack_node* next = nullptr)
: next(next), here(arg) {}
~liststack_node() { delete next; }
};
template<typename T>
struct liststack : boost::noncopyable {
typedef borrowed_bitset_impl::liststack_node<T> liststack_node;
liststack_node* next;
liststack() : next(nullptr) {}
explicit liststack(liststack_node* next) : next(next) {}
~liststack() { delete next; }
liststack_node* pop() {
liststack_node* result = next;
next = result->next;
// for clarity:
result->next = nullptr;
return result;
}
void push(liststack_node* add) {
add->next = next;
next = add;
}
bool empty() {
return next == nullptr;
}
};
struct zeroable_bitset {
// until this implementation becomes profile-measurable, it's good enough.
bit_index_type num_bits;
boost::dynamic_bitset<> bits;
std::vector<bit_index_type> bits_to_clear;
zeroable_bitset(bit_index_type num_bits)
: num_bits(num_bits), bits(num_bits), bits_to_clear() {}
};
typedef liststack<zeroable_bitset> zeroable_bitset_list;
// node/iterator/such
typedef liststack_node<zeroable_bitset> zeroable_bitset_node;
static const size_t array_of_bitset_lists_len = 40;
static const size_t bit_to_min_size_exponent = 6;
// if we track 4-8byteses individually, this exponent would be smaller.
static const size_t bit_exponent_below_which_its_worth_tracking_bits_individually = 8;
// array of array_of_bitset_lists_len sizes, from 2**bit_to_min_size_exponent bits up.
typedef zeroable_bitset_list* zeroable_bitset_array;
extern thread_local zeroable_bitset_array array_of_bitset_lists;
inline
void delete_array_of_bitset_lists() { delete[] array_of_bitset_lists; }
inline
zeroable_bitset_array get_this_thread_array_of_bitset_lists() {
if(array_of_bitset_lists == nullptr) {
array_of_bitset_lists = new zeroable_bitset_list[array_of_bitset_lists_len];
#if !LASERCAKE_NO_THREADS
try {
// (note, if we use forcible thread cancelation, this won't run)
// Also, donating them to another thread might be more useful
// than deleting them.
boost::this_thread::at_thread_exit(delete_array_of_bitset_lists);
}
catch(...) {
delete array_of_bitset_lists;
array_of_bitset_lists = nullptr;
throw;
}
#endif
}
return array_of_bitset_lists;
};
inline size_t which_bitset_index_is_size(bit_index_type num_bits) {
if(num_bits == 0) return 0;
const bit_index_type max_bit_index = num_bits - 1;
const bit_index_type max_8byte_index = max_bit_index >> bit_to_min_size_exponent;
caller_error_if(max_8byte_index != size_t(max_8byte_index), "More bits requested than your architecture can handle!");
const size_t which_bitset_size_index = num_bits_in_integer_that_are_not_leading_zeroes(max_8byte_index);
caller_error_if(which_bitset_size_index >= array_of_bitset_lists_len, "More bits requested than we support!");
return which_bitset_size_index;
}
inline bit_index_type how_many_bits_at_bitset_index(size_t bitset_index) {
return bit_index_type(1) << (bitset_index + bit_to_min_size_exponent);
}
inline
zeroable_bitset_node* borrow_bitset(bit_index_type num_bits_desired) {
zeroable_bitset_array array_of_bitset_lists = get_this_thread_array_of_bitset_lists();
const size_t which_bitset_size_index = which_bitset_index_is_size(num_bits_desired);
const bit_index_type actual_bits = how_many_bits_at_bitset_index(which_bitset_size_index);
assert(actual_bits >= num_bits_desired);
assert(actual_bits < num_bits_desired*2 || actual_bits == (1<<bit_to_min_size_exponent));
zeroable_bitset_list& result_list = array_of_bitset_lists[which_bitset_size_index];
if(!result_list.empty()) {
zeroable_bitset_node* result = result_list.pop();
assert(result->here.num_bits == actual_bits);
return result;
}
else {
return new zeroable_bitset_node(actual_bits);
}
}
inline void return_bitset(zeroable_bitset_node* node) noexcept {
zeroable_bitset_array array_of_bitset_lists;
try {
array_of_bitset_lists = get_this_thread_array_of_bitset_lists();
}
catch(std::exception const&) {
// This function is called from destructors so it must be nothrow.
// In particular, this may happen if the destructor is called in a different
// thread than the constructor was (std::bad_alloc or similar).
delete node;
return;
}
const size_t which_bitset_size_index = which_bitset_index_is_size(node->here.num_bits);
array_of_bitset_lists[which_bitset_size_index].push(node);
}
class borrowed_bitset : boost::noncopyable {
public:
explicit borrowed_bitset(bit_index_type num_bits_desired) : bs_(borrow_bitset(num_bits_desired)) {}
bool test(bit_index_type which)const { return bs_->here.bits.test(which); }
bool set(bit_index_type which) {
bool was_already_set = test(which);
if(!was_already_set && tracking_bits_individually_()) {
bs_->here.bits_to_clear.push_back(which);
}
bs_->here.bits.set(which);
return was_already_set;
}
bit_index_type size()const { return bs_->here.num_bits; }
~borrowed_bitset() {
if(tracking_bits_individually_()) {
for(bit_index_type which : bs_->here.bits_to_clear) {
bs_->here.bits.reset(which);
}
}
else {
bs_->here.bits.reset();
}
bs_->here.bits_to_clear.clear();
return_bitset(bs_);
}
private:
bool tracking_bits_individually_() const {
return bs_->here.bits_to_clear.size()
< (bs_->here.num_bits >> bit_exponent_below_which_its_worth_tracking_bits_individually);
}
zeroable_bitset_node* bs_;
};
}
using borrowed_bitset_impl::borrowed_bitset;
#endif
<commit_msg>Document borrowed_bitset<commit_after>/*
Copyright Eli Dupree and Isaac Dupree, 2011, 2012
This file is part of Lasercake.
Lasercake 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.
Lasercake 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 Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LASERCAKE_BORROWED_BITSET_HPP__
#define LASERCAKE_BORROWED_BITSET_HPP__
#include <list>
#include <stack>
#include <boost/utility.hpp>
#include <boost/dynamic_bitset.hpp>
#include "../utils.hpp"
#if !LASERCAKE_NO_THREADS
#include <boost/thread/thread.hpp>
#endif
typedef uint64_t bit_index_type;
namespace borrowed_bitset_impl {
// Noncopying singly linked list that owns its members unless you pop them.
template<typename T>
struct liststack_node : boost::noncopyable {
liststack_node* next;
T here;
liststack_node() : next(nullptr), here() {}
template<typename Arg>
explicit liststack_node(Arg const& arg, liststack_node* next = nullptr)
: next(next), here(arg) {}
~liststack_node() { delete next; }
};
template<typename T>
struct liststack : boost::noncopyable {
typedef borrowed_bitset_impl::liststack_node<T> liststack_node;
liststack_node* next;
liststack() : next(nullptr) {}
explicit liststack(liststack_node* next) : next(next) {}
~liststack() { delete next; }
liststack_node* pop() {
liststack_node* result = next;
next = result->next;
// for clarity:
result->next = nullptr;
return result;
}
void push(liststack_node* add) {
add->next = next;
next = add;
}
bool empty() {
return next == nullptr;
}
};
struct zeroable_bitset {
// until this implementation becomes profile-measurable, it's good enough.
bit_index_type num_bits;
boost::dynamic_bitset<> bits;
std::vector<bit_index_type> bits_to_clear;
zeroable_bitset(bit_index_type num_bits)
: num_bits(num_bits), bits(num_bits), bits_to_clear() {}
};
typedef liststack<zeroable_bitset> zeroable_bitset_list;
// node/iterator/such
typedef liststack_node<zeroable_bitset> zeroable_bitset_node;
static const size_t array_of_bitset_lists_len = 40;
static const size_t bit_to_min_size_exponent = 6;
// if we track 4-8byteses individually, this exponent would be smaller.
static const size_t bit_exponent_below_which_its_worth_tracking_bits_individually = 8;
// array of array_of_bitset_lists_len sizes, from 2**bit_to_min_size_exponent bits up.
typedef zeroable_bitset_list* zeroable_bitset_array;
extern thread_local zeroable_bitset_array array_of_bitset_lists;
inline
void delete_array_of_bitset_lists() { delete[] array_of_bitset_lists; }
inline
zeroable_bitset_array get_this_thread_array_of_bitset_lists() {
if(array_of_bitset_lists == nullptr) {
array_of_bitset_lists = new zeroable_bitset_list[array_of_bitset_lists_len];
#if !LASERCAKE_NO_THREADS
try {
// (note, if we use forcible thread cancelation, this won't run)
// Also, donating them to another thread might be more useful
// than deleting them.
boost::this_thread::at_thread_exit(delete_array_of_bitset_lists);
}
catch(...) {
delete array_of_bitset_lists;
array_of_bitset_lists = nullptr;
throw;
}
#endif
}
return array_of_bitset_lists;
};
inline size_t which_bitset_index_is_size(bit_index_type num_bits) {
if(num_bits == 0) return 0;
const bit_index_type max_bit_index = num_bits - 1;
const bit_index_type max_8byte_index = max_bit_index >> bit_to_min_size_exponent;
caller_error_if(max_8byte_index != size_t(max_8byte_index), "More bits requested than your architecture can handle!");
const size_t which_bitset_size_index = num_bits_in_integer_that_are_not_leading_zeroes(max_8byte_index);
caller_error_if(which_bitset_size_index >= array_of_bitset_lists_len, "More bits requested than we support!");
return which_bitset_size_index;
}
inline bit_index_type how_many_bits_at_bitset_index(size_t bitset_index) {
return bit_index_type(1) << (bitset_index + bit_to_min_size_exponent);
}
inline
zeroable_bitset_node* borrow_bitset(bit_index_type num_bits_desired) {
zeroable_bitset_array array_of_bitset_lists = get_this_thread_array_of_bitset_lists();
const size_t which_bitset_size_index = which_bitset_index_is_size(num_bits_desired);
const bit_index_type actual_bits = how_many_bits_at_bitset_index(which_bitset_size_index);
assert(actual_bits >= num_bits_desired);
assert(actual_bits < num_bits_desired*2 || actual_bits == (1<<bit_to_min_size_exponent));
zeroable_bitset_list& result_list = array_of_bitset_lists[which_bitset_size_index];
if(!result_list.empty()) {
zeroable_bitset_node* result = result_list.pop();
assert(result->here.num_bits == actual_bits);
return result;
}
else {
return new zeroable_bitset_node(actual_bits);
}
}
inline void return_bitset(zeroable_bitset_node* node) noexcept {
zeroable_bitset_array array_of_bitset_lists;
try {
array_of_bitset_lists = get_this_thread_array_of_bitset_lists();
}
catch(std::exception const&) {
// This function is called from destructors so it must be nothrow.
// In particular, this may happen if the destructor is called in a different
// thread than the constructor was (std::bad_alloc or similar).
delete node;
return;
}
const size_t which_bitset_size_index = which_bitset_index_is_size(node->here.num_bits);
array_of_bitset_lists[which_bitset_size_index].push(node);
}
// borrowed_bitset(n) borrows an array of zero bits of size n (rounded
// up to something), and when destructed it restores the zeroes and returns
// that array. (There's a dynamically allocated pool of arrays of zeroes
// waiting to be borrowed; if none are available, borrowed_bitset allocates
// a new one, which it will return to the pool when destructed.)
//
// If there aren't too many borrowed_bitsets at once and program runs for
// a while, borrowed_bitset() effectively has O(1) construction, and
// destruction time <= the number of operations performed on it (so no worse
// than a constant factor). This is pretty good for something this much
// faster at uniquing than an unordered_set<uint>.
class borrowed_bitset : boost::noncopyable {
public:
explicit borrowed_bitset(bit_index_type num_bits_desired) : bs_(borrow_bitset(num_bits_desired)) {}
bool test(bit_index_type which)const { return bs_->here.bits.test(which); }
bool set(bit_index_type which) {
bool was_already_set = test(which);
if(!was_already_set && tracking_bits_individually_()) {
bs_->here.bits_to_clear.push_back(which);
}
bs_->here.bits.set(which);
return was_already_set;
}
bit_index_type size()const { return bs_->here.num_bits; }
~borrowed_bitset() {
if(tracking_bits_individually_()) {
for(bit_index_type which : bs_->here.bits_to_clear) {
bs_->here.bits.reset(which);
}
}
else {
bs_->here.bits.reset();
}
bs_->here.bits_to_clear.clear();
return_bitset(bs_);
}
private:
bool tracking_bits_individually_() const {
return bs_->here.bits_to_clear.size()
< (bs_->here.num_bits >> bit_exponent_below_which_its_worth_tracking_bits_individually);
}
zeroable_bitset_node* bs_;
};
}
using borrowed_bitset_impl::borrowed_bitset;
#endif
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbFragmentShader.h"
#include "otbFragmentShaderRegistry.h"
namespace otb
{
FragmentShader::FragmentShader()
{}
FragmentShader::~FragmentShader()
{}
void FragmentShader::BuildShader()
{
std::string source = this->GetSource();
std::string name = this->GetName();
std::cout<<"Name: "<<name<<", source: "<<source<<std::endl;
try
{
otb::FragmentShaderRegistry::Instance()->RegisterShader(name,source);
}
catch(itk::ExceptionObject& err)
{
std::cerr<<err<<std::endl;
// Shader already registered, do nothing
}
}
void FragmentShader::LoadShader()
{
otb::FragmentShaderRegistry::Instance()->LoadShader(GetName());
}
void FragmentShader::UnloadShader()
{
otb::FragmentShaderRegistry::Instance()->UnloadShader();
}
void FragmentShader::SetupShader()
{
// // Default always report corners
// GLint shader_ul = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_ul");
// glUniform2f(shader_ul,m_UL[0],m_UL[1]);
// GLint shader_ur = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_ur");
// glUniform2f(shader_ur,m_UR[0],m_UR[1]);
// GLint shader_ll = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_ll");
// glUniform2f(shader_ll,m_LL[0],m_LL[1]);
// GLint shader_lr = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_lr");
// glUniform2f(shader_lr,m_LR[0],m_LR[1]);
}
}
<commit_msg>ENH: Removing heavy logs<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbFragmentShader.h"
#include "otbFragmentShaderRegistry.h"
namespace otb
{
FragmentShader::FragmentShader()
{}
FragmentShader::~FragmentShader()
{}
void FragmentShader::BuildShader()
{
std::string source = this->GetSource();
std::string name = this->GetName();
try
{
// Assumption here is that each shader has its unique name
if(!otb::FragmentShaderRegistry::Instance()->IsShaderRegistered(name))
{
otb::FragmentShaderRegistry::Instance()->RegisterShader(name,source);
}
}
catch(itk::ExceptionObject& err)
{
// Log compilation errors if any
std::cerr<<err<<std::endl;
}
}
void FragmentShader::LoadShader()
{
otb::FragmentShaderRegistry::Instance()->LoadShader(GetName());
}
void FragmentShader::UnloadShader()
{
otb::FragmentShaderRegistry::Instance()->UnloadShader();
}
void FragmentShader::SetupShader()
{
// // Default always report corners
// GLint shader_ul = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_ul");
// glUniform2f(shader_ul,m_UL[0],m_UL[1]);
// GLint shader_ur = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_ur");
// glUniform2f(shader_ur,m_UR[0],m_UR[1]);
// GLint shader_ll = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_ll");
// glUniform2f(shader_ll,m_LL[0],m_LL[1]);
// GLint shader_lr = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_lr");
// glUniform2f(shader_lr,m_LR[0],m_LR[1]);
}
}
<|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "singleselectiondialogspage.h"
#include <MAbstractCellCreator>
#include <MButton>
#include <MBasicListItem>
#include <MDialog>
#include <MLabel>
#include <MLayout>
#include <MList>
#include <MLinearLayoutPolicy>
#include <MMessageBox>
#include <MTextEdit>
#include <QGraphicsLinearLayout>
#include <QStringListModel>
#include <QTimer>
class SingleSelectionDialogsPageCellCreator : public MAbstractCellCreator<MBasicListItem>
{
public:
SingleSelectionDialogsPageCellCreator() : MAbstractCellCreator<MBasicListItem>() {
}
MWidget *createCell(const QModelIndex &index, MWidgetRecycler &recycler) const {
Q_UNUSED(index);
MBasicListItem *cell = dynamic_cast<MBasicListItem *>(recycler.take(MBasicListItem::staticMetaObject.className()));
if (cell == NULL) {
cell = new MBasicListItem(MBasicListItem::SingleTitle);
cell->initLayout();
cell->setLayoutPosition(M::CenterPosition);
}
updateCell(index, cell);
return cell;
}
void updateCell(const QModelIndex &index, MWidget *cell) const {
MBasicListItem *item = qobject_cast<MBasicListItem*>(cell);
if(!item)
return;
item->setTitle(index.data().toString());
}
};
SingleSelectionDialogsPage::SingleSelectionDialogsPage()
: TemplatePage(TemplatePage::DialogsAndBanners),
policy(0),
list(0),
dialog(),
nestedDialog(),
nestedMessageBox()
{
}
QString SingleSelectionDialogsPage::timedemoTitle()
{
return "SingleSelectionDialogsPage";
}
void SingleSelectionDialogsPage::createContent()
{
MApplicationPage::createContent();
QGraphicsWidget *panel = centralWidget();
MLayout *layout = new MLayout(panel);
layout->setContentsMargins(0, 0, 0, 0);
panel->setLayout(layout);
policy = new MLinearLayoutPolicy(layout, Qt::Vertical);
policy->setContentsMargins(0, 0, 0, 0);
policy->setSpacing(0);
populateLayout();
retranslateUi();
}
void SingleSelectionDialogsPage::populateLayout()
{
list = new MList(centralWidget());
list->setCellCreator(new SingleSelectionDialogsPageCellCreator());
list->setItemModel(new QStringListModel(list));
policy->addItem(list, Qt::AlignCenter);
connect(list, SIGNAL(itemClicked(QModelIndex)), this, SLOT(itemClicked(QModelIndex)));
}
void SingleSelectionDialogsPage::itemClicked(const QModelIndex &index)
{
switch (index.row()) {
case 0:
openEntryDialog();
break;
case 1:
openLongDialog();
break;
case 2:
openSystemDialog();
break;
case 3:
openSystemModalDialog();
break;
case 4:
openDialogWithProgressIndicator();
break;
case 5:
openStackedDialogs();
break;
case 6:
openDialogWithIcon();
break;
default:
break;
}
}
void SingleSelectionDialogsPage::openStackedDialogs()
{
if (dialog)
return;
QGraphicsWidget *alignContainer = new QGraphicsWidget();
QGraphicsWidget *leftSpacer = createSpacer();
QGraphicsWidget *rightSpacer = createSpacer();
QGraphicsLinearLayout *alignLayout = new QGraphicsLinearLayout(Qt::Horizontal, alignContainer);
alignLayout->addItem(leftSpacer);
//% "Click to spawn a nested dialog"
MButton *button = new MButton(qtTrId("xx_dialogs_and_notifications_stacked_dialog_button"));
//% "Stacked dialogs"
dialog = new MDialog(qtTrId("xx_dialogs_and_notifications_stacked_dialog_title"), M::CancelButton);
alignLayout->addItem(button);
alignLayout->addItem(rightSpacer);
dialog->setCentralWidget(alignContainer);
connect(button, SIGNAL(clicked()), SLOT(openNestedDialog()));
dialog->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::openNestedDialog()
{
if (nestedDialog)
return;
QGraphicsWidget *alignContainer = new QGraphicsWidget();
QGraphicsWidget *leftSpacer = createSpacer();
QGraphicsWidget *rightSpacer = createSpacer();
QGraphicsLinearLayout *alignLayout = new QGraphicsLinearLayout(Qt::Horizontal, alignContainer);
alignLayout->addItem(leftSpacer);
//% "Click to open a nested message box"
MButton *button = new MButton(qtTrId("xx_dialogs_and_notifications_stacked_dialog_open_nested_messagebox"));
//% "This is a nested dialog"
nestedDialog = new MDialog(qtTrId("xx_dialogs_and_notifications_stacked_dialog_nested_dialog_title"), M::CancelButton);
alignLayout->addItem(button);
alignLayout->addItem(rightSpacer);
nestedDialog->setCentralWidget(alignContainer);
connect(button, SIGNAL(clicked()), SLOT(openNestedMessageBox()));
nestedDialog->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::openNestedMessageBox()
{
if (nestedMessageBox)
return;
//% "I'm a nested message box"
nestedMessageBox = new MMessageBox(qtTrId("xx_dialogs_and_notifications_stacked_dialog_messagebox_text"));
nestedMessageBox->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::openSystemDialog()
{
if (dialog)
return;
dialog = new MDialog(
//% "System Dialog"
qtTrId("xx_dialogs_and_notifications_system_dialog_title"),
M::OkButton);
dialog->setCentralWidget(
//% "I'm a system dialog.<br>"
//% "You can skip me with the home button.<br>"
//% "I'll be minimised to the task switcher<br>"
//% "but I'll remain alive until you make a selection."
new MLabel(qtTrId("xx_dialogs_and_notifications_system_dialog_label")));
dialog->setSystem(true);
dialog->setModal(false);
dialog->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::openSystemModalDialog()
{
if (dialog)
return;
dialog = new MDialog(
//% "System Modal Dialog"
qtTrId("xx_dialogs_and_notifications_system_modal_dialog_title"),
M::OkButton);
//% "I'm a system modal dialog.<br>"
//% "You can't skip me as I'm designed for<br>"
//% "use cases that require immediate user attention."
MLabel *textSystemModal= new MLabel(qtTrId("xx_dialogs_and_notifications_system_modal_dialog_label"));
textSystemModal->setStyleName("CommonBodyTextInverted");
textSystemModal->setAlignment(Qt::AlignCenter);
textSystemModal->setWordWrap(true);
textSystemModal->setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(Qt::Horizontal);
layout->addStretch();
layout->addItem(textSystemModal);
layout->addStretch();
dialog->centralWidget()->setLayout(layout);
dialog->setSystem(true);
dialog->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::openDialogWithProgressIndicator()
{
if (dialog)
return;
MButton *button = new MButton();
button->setViewType(MButton::switchType);
button->setCheckable(true);
button->setChecked(true);
connect(button, SIGNAL(toggled(bool)), this, SLOT(setDialogProgressIndicatorVisible(bool)));
//% "Progress Indicator"
MLabel *label = new MLabel(qtTrId("xx_dialogs_and_notifications_progress_indicator"));
label->setStyleName("CommonTitleInverted");
QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(Qt::Horizontal);
layout->addStretch();
layout->addItem(label);
layout->addItem(button);
layout->addStretch();
dialog = new MDialog("Lorem ipsum", M::NoStandardButton);
dialog->centralWidget()->setLayout(layout);
dialog->setProgressIndicatorVisible(true);
dialog->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::openDialogWithIcon()
{
if (dialog)
return;
MButton *button = new MButton();
button->setViewType(MButton::switchType);
button->setCheckable(true);
button->setChecked(true);
connect(button, SIGNAL(toggled(bool)), this, SLOT(setDialogIconVisible(bool)));
//% "Progress Indicator"
MLabel *label = new MLabel(qtTrId("xx_dialogs_and_notifications_icon"));
label->setStyleName("CommonTitleInverted");
QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(Qt::Horizontal);
layout->addStretch();
layout->addItem(label);
layout->addItem(button);
layout->addStretch();
dialog = new MDialog("Lorem ipsum", M::NoStandardButton);
dialog->centralWidget()->setLayout(layout);
dialog->setTitleBarIconId("icon-l-default-application");
dialog->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::openEntryDialog()
{
if (dialog)
return;
MWidget *centralWidget = new MWidget;
QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(Qt::Vertical);
layout->setContentsMargins(0,0,0,0);
layout->setSpacing(0);
//% "Name"
MLabel *label = new MLabel(qtTrId("xx_dialogs_and_notifications_entry_dialog_label"), centralWidget);
label->setStyleName("CommonTitleInverted");
MTextEdit *textEdit = new MTextEdit(MTextEditModel::SingleLine,
QString(),
centralWidget);
textEdit->setStyleName("CommonSingleInputField");
MLabel *spacer = new MLabel();
spacer->setObjectName("CommonSpacer");
centralWidget->setLayout(layout);
layout->addItem(label);
layout->addItem(textEdit);
layout->addItem(spacer);
//% "Please enter your name"
dialog = new MDialog(qtTrId("xx_dialogs_and_notifications_entry_dialog_title"),
M::OkButton | M::ResetButton);
dialog->setCentralWidget(centralWidget);
dialog->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::openLongDialog()
{
if (dialog)
return;
MWidget *centralWidget = new MWidget;
QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(Qt::Vertical);
//% "Select printer"
dialog = new MDialog(qtTrId("xx_dialogs_and_notifications_long_dialog_title"), M::CancelButton);
dialog->setCentralWidget(centralWidget);
centralWidget->setLayout(layout);
const char * printers[] = {"Lexmark A", "Lexmark A", "Lexmark B", "Lexmark C", "Lexmark D", "Canon Alpha", "Canon Beta", "Canon Gama",
"Canon Zeta", "Brother 1", "Brother 2", "Brother 3", "Brother 4", "Xerox I", "Xerox II", "Xerox III",
"Xerox IV", "Dell Roger", "Dell Charlie", "Dell Bravo", "Dell Tango", "HP X", "HP Y", "HP Z", "HP Plus", "Epson Stylus",
"Epson Pro", "Epson Office", "Epson Extra", NULL};
for(int i = 0; printers[i] != NULL; i++) {
MBasicListItem *printerItem = new MBasicListItem;
printerItem->setTitle(printers[i]);
dialog->connect(printerItem, SIGNAL(clicked()), SLOT(accept()));
layout->addItem(printerItem);
}
dialog->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::setDialogProgressIndicatorVisible(bool visible)
{
if (dialog) {
dialog->setProgressIndicatorVisible(visible);
}
}
void SingleSelectionDialogsPage::setDialogIconVisible(bool visible)
{
if (dialog) {
if(visible)
dialog->setTitleBarIconId("icon-l-default-application");
else
dialog->setTitleBarIconId("");
}
}
void SingleSelectionDialogsPage::retranslateUi()
{
//% "Single Selection Dialogs"
setTitle(qtTrId("xx_single_selection_dialog_title"));
if (!isContentCreated())
return;
QStringList singleSelectionDialogTypes;
//% "Entry Dialog"
singleSelectionDialogTypes << qtTrId("xx_wg_query_dialogs_page_entry_dialog");
//% "Long Dialog"
singleSelectionDialogTypes << qtTrId("xx_wg_query_dialogs_page_long_dialog");
//% "System Dialog"
singleSelectionDialogTypes << qtTrId("xx_wg_single_selection_dialogs_page_system_dialog");
//% "System Modal Dialog"
singleSelectionDialogTypes << qtTrId("xx_wg_single_selection_dialogs_page_system_modal_dialog");
//% "Dialog with Progress Indicator"
singleSelectionDialogTypes << qtTrId("xx_wg_single_selection_dialogs_page_dialog_with_progress_indicator");
//% "Stacked Dialogs"
singleSelectionDialogTypes << qtTrId("xx_wg_single_selection_dialogs_page_stacked_dialogs");
//% "Dialog with Icon"
singleSelectionDialogTypes << qtTrId("xx_wg_single_selection_dialogs_page_dialog_with_icon");
static_cast<QStringListModel *>(list->itemModel())->setStringList(singleSelectionDialogTypes);
}
QGraphicsWidget *SingleSelectionDialogsPage::createSpacer()
{
QGraphicsWidget *spacer = new QGraphicsWidget();
spacer->hide();
spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
spacer->setMinimumSize(0, 0);
spacer->setPreferredSize(0, 0);
spacer->setFlag(QGraphicsItem::ItemHasNoContents, true);
return spacer;
}
<commit_msg>Changes: widgetsgallery. Fix copy-and-paste error in "dialog with icon" example<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "singleselectiondialogspage.h"
#include <MAbstractCellCreator>
#include <MButton>
#include <MBasicListItem>
#include <MDialog>
#include <MLabel>
#include <MLayout>
#include <MList>
#include <MLinearLayoutPolicy>
#include <MMessageBox>
#include <MTextEdit>
#include <QGraphicsLinearLayout>
#include <QStringListModel>
#include <QTimer>
class SingleSelectionDialogsPageCellCreator : public MAbstractCellCreator<MBasicListItem>
{
public:
SingleSelectionDialogsPageCellCreator() : MAbstractCellCreator<MBasicListItem>() {
}
MWidget *createCell(const QModelIndex &index, MWidgetRecycler &recycler) const {
Q_UNUSED(index);
MBasicListItem *cell = dynamic_cast<MBasicListItem *>(recycler.take(MBasicListItem::staticMetaObject.className()));
if (cell == NULL) {
cell = new MBasicListItem(MBasicListItem::SingleTitle);
cell->initLayout();
cell->setLayoutPosition(M::CenterPosition);
}
updateCell(index, cell);
return cell;
}
void updateCell(const QModelIndex &index, MWidget *cell) const {
MBasicListItem *item = qobject_cast<MBasicListItem*>(cell);
if(!item)
return;
item->setTitle(index.data().toString());
}
};
SingleSelectionDialogsPage::SingleSelectionDialogsPage()
: TemplatePage(TemplatePage::DialogsAndBanners),
policy(0),
list(0),
dialog(),
nestedDialog(),
nestedMessageBox()
{
}
QString SingleSelectionDialogsPage::timedemoTitle()
{
return "SingleSelectionDialogsPage";
}
void SingleSelectionDialogsPage::createContent()
{
MApplicationPage::createContent();
QGraphicsWidget *panel = centralWidget();
MLayout *layout = new MLayout(panel);
layout->setContentsMargins(0, 0, 0, 0);
panel->setLayout(layout);
policy = new MLinearLayoutPolicy(layout, Qt::Vertical);
policy->setContentsMargins(0, 0, 0, 0);
policy->setSpacing(0);
populateLayout();
retranslateUi();
}
void SingleSelectionDialogsPage::populateLayout()
{
list = new MList(centralWidget());
list->setCellCreator(new SingleSelectionDialogsPageCellCreator());
list->setItemModel(new QStringListModel(list));
policy->addItem(list, Qt::AlignCenter);
connect(list, SIGNAL(itemClicked(QModelIndex)), this, SLOT(itemClicked(QModelIndex)));
}
void SingleSelectionDialogsPage::itemClicked(const QModelIndex &index)
{
switch (index.row()) {
case 0:
openEntryDialog();
break;
case 1:
openLongDialog();
break;
case 2:
openSystemDialog();
break;
case 3:
openSystemModalDialog();
break;
case 4:
openDialogWithProgressIndicator();
break;
case 5:
openStackedDialogs();
break;
case 6:
openDialogWithIcon();
break;
default:
break;
}
}
void SingleSelectionDialogsPage::openStackedDialogs()
{
if (dialog)
return;
QGraphicsWidget *alignContainer = new QGraphicsWidget();
QGraphicsWidget *leftSpacer = createSpacer();
QGraphicsWidget *rightSpacer = createSpacer();
QGraphicsLinearLayout *alignLayout = new QGraphicsLinearLayout(Qt::Horizontal, alignContainer);
alignLayout->addItem(leftSpacer);
//% "Click to spawn a nested dialog"
MButton *button = new MButton(qtTrId("xx_dialogs_and_notifications_stacked_dialog_button"));
//% "Stacked dialogs"
dialog = new MDialog(qtTrId("xx_dialogs_and_notifications_stacked_dialog_title"), M::CancelButton);
alignLayout->addItem(button);
alignLayout->addItem(rightSpacer);
dialog->setCentralWidget(alignContainer);
connect(button, SIGNAL(clicked()), SLOT(openNestedDialog()));
dialog->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::openNestedDialog()
{
if (nestedDialog)
return;
QGraphicsWidget *alignContainer = new QGraphicsWidget();
QGraphicsWidget *leftSpacer = createSpacer();
QGraphicsWidget *rightSpacer = createSpacer();
QGraphicsLinearLayout *alignLayout = new QGraphicsLinearLayout(Qt::Horizontal, alignContainer);
alignLayout->addItem(leftSpacer);
//% "Click to open a nested message box"
MButton *button = new MButton(qtTrId("xx_dialogs_and_notifications_stacked_dialog_open_nested_messagebox"));
//% "This is a nested dialog"
nestedDialog = new MDialog(qtTrId("xx_dialogs_and_notifications_stacked_dialog_nested_dialog_title"), M::CancelButton);
alignLayout->addItem(button);
alignLayout->addItem(rightSpacer);
nestedDialog->setCentralWidget(alignContainer);
connect(button, SIGNAL(clicked()), SLOT(openNestedMessageBox()));
nestedDialog->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::openNestedMessageBox()
{
if (nestedMessageBox)
return;
//% "I'm a nested message box"
nestedMessageBox = new MMessageBox(qtTrId("xx_dialogs_and_notifications_stacked_dialog_messagebox_text"));
nestedMessageBox->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::openSystemDialog()
{
if (dialog)
return;
dialog = new MDialog(
//% "System Dialog"
qtTrId("xx_dialogs_and_notifications_system_dialog_title"),
M::OkButton);
dialog->setCentralWidget(
//% "I'm a system dialog.<br>"
//% "You can skip me with the home button.<br>"
//% "I'll be minimised to the task switcher<br>"
//% "but I'll remain alive until you make a selection."
new MLabel(qtTrId("xx_dialogs_and_notifications_system_dialog_label")));
dialog->setSystem(true);
dialog->setModal(false);
dialog->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::openSystemModalDialog()
{
if (dialog)
return;
dialog = new MDialog(
//% "System Modal Dialog"
qtTrId("xx_dialogs_and_notifications_system_modal_dialog_title"),
M::OkButton);
//% "I'm a system modal dialog.<br>"
//% "You can't skip me as I'm designed for<br>"
//% "use cases that require immediate user attention."
MLabel *textSystemModal= new MLabel(qtTrId("xx_dialogs_and_notifications_system_modal_dialog_label"));
textSystemModal->setStyleName("CommonBodyTextInverted");
textSystemModal->setAlignment(Qt::AlignCenter);
textSystemModal->setWordWrap(true);
textSystemModal->setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(Qt::Horizontal);
layout->addStretch();
layout->addItem(textSystemModal);
layout->addStretch();
dialog->centralWidget()->setLayout(layout);
dialog->setSystem(true);
dialog->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::openDialogWithProgressIndicator()
{
if (dialog)
return;
MButton *button = new MButton();
button->setViewType(MButton::switchType);
button->setCheckable(true);
button->setChecked(true);
connect(button, SIGNAL(toggled(bool)), this, SLOT(setDialogProgressIndicatorVisible(bool)));
//% "Progress Indicator"
MLabel *label = new MLabel(qtTrId("xx_dialogs_and_notifications_progress_indicator"));
label->setStyleName("CommonTitleInverted");
QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(Qt::Horizontal);
layout->addStretch();
layout->addItem(label);
layout->addItem(button);
layout->addStretch();
dialog = new MDialog("Lorem ipsum", M::NoStandardButton);
dialog->centralWidget()->setLayout(layout);
dialog->setProgressIndicatorVisible(true);
dialog->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::openDialogWithIcon()
{
if (dialog)
return;
MButton *button = new MButton();
button->setViewType(MButton::switchType);
button->setCheckable(true);
button->setChecked(true);
connect(button, SIGNAL(toggled(bool)), this, SLOT(setDialogIconVisible(bool)));
//% "Title Bar Icon"
MLabel *label = new MLabel(qtTrId("xx_dialogs_and_notifications_icon"));
label->setStyleName("CommonTitleInverted");
QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(Qt::Horizontal);
layout->addStretch();
layout->addItem(label);
layout->addItem(button);
layout->addStretch();
dialog = new MDialog("Lorem ipsum", M::NoStandardButton);
dialog->centralWidget()->setLayout(layout);
dialog->setTitleBarIconId("icon-l-default-application");
dialog->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::openEntryDialog()
{
if (dialog)
return;
MWidget *centralWidget = new MWidget;
QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(Qt::Vertical);
layout->setContentsMargins(0,0,0,0);
layout->setSpacing(0);
//% "Name"
MLabel *label = new MLabel(qtTrId("xx_dialogs_and_notifications_entry_dialog_label"), centralWidget);
label->setStyleName("CommonTitleInverted");
MTextEdit *textEdit = new MTextEdit(MTextEditModel::SingleLine,
QString(),
centralWidget);
textEdit->setStyleName("CommonSingleInputField");
MLabel *spacer = new MLabel();
spacer->setObjectName("CommonSpacer");
centralWidget->setLayout(layout);
layout->addItem(label);
layout->addItem(textEdit);
layout->addItem(spacer);
//% "Please enter your name"
dialog = new MDialog(qtTrId("xx_dialogs_and_notifications_entry_dialog_title"),
M::OkButton | M::ResetButton);
dialog->setCentralWidget(centralWidget);
dialog->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::openLongDialog()
{
if (dialog)
return;
MWidget *centralWidget = new MWidget;
QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(Qt::Vertical);
//% "Select printer"
dialog = new MDialog(qtTrId("xx_dialogs_and_notifications_long_dialog_title"), M::CancelButton);
dialog->setCentralWidget(centralWidget);
centralWidget->setLayout(layout);
const char * printers[] = {"Lexmark A", "Lexmark A", "Lexmark B", "Lexmark C", "Lexmark D", "Canon Alpha", "Canon Beta", "Canon Gama",
"Canon Zeta", "Brother 1", "Brother 2", "Brother 3", "Brother 4", "Xerox I", "Xerox II", "Xerox III",
"Xerox IV", "Dell Roger", "Dell Charlie", "Dell Bravo", "Dell Tango", "HP X", "HP Y", "HP Z", "HP Plus", "Epson Stylus",
"Epson Pro", "Epson Office", "Epson Extra", NULL};
for(int i = 0; printers[i] != NULL; i++) {
MBasicListItem *printerItem = new MBasicListItem;
printerItem->setTitle(printers[i]);
dialog->connect(printerItem, SIGNAL(clicked()), SLOT(accept()));
layout->addItem(printerItem);
}
dialog->appear(MSceneWindow::DestroyWhenDone);
}
void SingleSelectionDialogsPage::setDialogProgressIndicatorVisible(bool visible)
{
if (dialog) {
dialog->setProgressIndicatorVisible(visible);
}
}
void SingleSelectionDialogsPage::setDialogIconVisible(bool visible)
{
if (dialog) {
if(visible)
dialog->setTitleBarIconId("icon-l-default-application");
else
dialog->setTitleBarIconId("");
}
}
void SingleSelectionDialogsPage::retranslateUi()
{
//% "Single Selection Dialogs"
setTitle(qtTrId("xx_single_selection_dialog_title"));
if (!isContentCreated())
return;
QStringList singleSelectionDialogTypes;
//% "Entry Dialog"
singleSelectionDialogTypes << qtTrId("xx_wg_query_dialogs_page_entry_dialog");
//% "Long Dialog"
singleSelectionDialogTypes << qtTrId("xx_wg_query_dialogs_page_long_dialog");
//% "System Dialog"
singleSelectionDialogTypes << qtTrId("xx_wg_single_selection_dialogs_page_system_dialog");
//% "System Modal Dialog"
singleSelectionDialogTypes << qtTrId("xx_wg_single_selection_dialogs_page_system_modal_dialog");
//% "Dialog with Progress Indicator"
singleSelectionDialogTypes << qtTrId("xx_wg_single_selection_dialogs_page_dialog_with_progress_indicator");
//% "Stacked Dialogs"
singleSelectionDialogTypes << qtTrId("xx_wg_single_selection_dialogs_page_stacked_dialogs");
//% "Dialog with Icon"
singleSelectionDialogTypes << qtTrId("xx_wg_single_selection_dialogs_page_dialog_with_icon");
static_cast<QStringListModel *>(list->itemModel())->setStringList(singleSelectionDialogTypes);
}
QGraphicsWidget *SingleSelectionDialogsPage::createSpacer()
{
QGraphicsWidget *spacer = new QGraphicsWidget();
spacer->hide();
spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
spacer->setMinimumSize(0, 0);
spacer->setPreferredSize(0, 0);
spacer->setFlag(QGraphicsItem::ItemHasNoContents, true);
return spacer;
}
<|endoftext|>
|
<commit_before>TEveRGBAPalette *g_zdc_palette = 0;
Float_t g_zdc_scale = 0.1;
Float_t g_zdc_dist = 11695;
Float_t g_zdc_cross = 20;
TEveGeoShape* zdc_make_shape(const Text_t* name, const Text_t* title_base,
Double_t signal, const Text_t* path)
{
if ( ! gGeoManager->cd(path))
{
Warning("zdc_make_shape", "Module name=%s, path='%s' not found.\n", name, path);
return 0;
}
UChar_t rgb[3];
g_zdc_palette->ColorFromValue(TMath::Nint(signal), rgb, kFALSE);
TGeoShape *gs = (TGeoShape*) gGeoManager->GetCurrentVolume()->GetShape()->Clone();
TEveGeoShape *s = new TEveGeoShape(name, Form("%s %s, E=%.3f", title_base, name, signal));
s->SetPickable(kTRUE);
s->SetMainColorRGB(rgb[0], rgb[1], rgb[2]);
s->SetShape(gs);
s->RefMainTrans().SetFrom(*gGeoManager->GetCurrentMatrix());
// Scale z-dictance by 0.1
Double_t* t = s->RefMainTrans().ArrT();
t[2] *= g_zdc_scale;
return s;
}
TEveStraightLineSet*
zdc_make_cross(const Text_t* name, const Text_t* title_base,
Float_t x, Float_t y, Float_t z, Float_t dx, Float_t dy, Float_t dz)
{
TEveStraightLineSet* ls = new TEveStraightLineSet(name, Form("%s, x=%.3f, y=%.3f", title_base, x, y));
ls->SetMainColor(kYellow);
ls->SetLineWidth(2);
ls->RefMainTrans().SetPos(x, y, z);
ls->AddLine(dx, 0, 0, -dx, 0, 0);
ls->AddLine(0, dy, 0, 0, -dy, 0);
ls->AddLine(0, 0, dz, 0, 0, -dz);
return ls;
}
// ???? There are 5 towers in ESD, 4 in geom.
// Not sure about assignment A/C <-> 1/2
void esd_zdc()
{
AliEveEventManager::AssertGeometry();
AliESDZDC *esd = AliEveEventManager::AssertESD()->GetESDZDC();
if (g_zdc_palette == 0)
{
// Map values from 0, 50 on a spectrum palette.
g_zdc_palette = new TEveRGBAPalette(0, 50, kTRUE, kFALSE);
g_zdc_palette->IncRefCount();
gStyle->SetPalette(1, 0);
g_zdc_palette->SetupColorArray();
}
TEveElementList* l = new TEveElementList("ZDC Data", "");
gEve->AddElement(l);
TEveElementList *c = 0;
TEveGeoShape *s = 0;
Double_t *te = 0;
Text_t *tb = 0;
// ZNC geometry ------------------------------------
tb = "ZNC";
c = new TEveElementList(tb);
l->AddElement(c);
te = esd->GetZN1TowerEnergy();
c->AddElement(zdc_make_shape("Tower 1", tb, te[1],
"ALIC_1/ZDCC_1/ZNEU_1/ZNTX_1/ZN1_1"));
c->AddElement(zdc_make_shape("Tower 2", tb, te[2],
"ALIC_1/ZDCC_1/ZNEU_1/ZNTX_1/ZN1_2"));
c->AddElement(zdc_make_shape("Tower 3", tb, te[3],
"ALIC_1/ZDCC_1/ZNEU_1/ZNTX_2/ZN1_1"));
c->AddElement(zdc_make_shape("Tower 4", tb, te[4],
"ALIC_1/ZDCC_1/ZNEU_1/ZNTX_2/ZN1_2"));
// ZNA geometry
tb = "ZNA";
c = new TEveElementList(tb);
l->AddElement(c);
te = esd->GetZN2TowerEnergy();
c->AddElement(zdc_make_shape("Tower 1", tb, te[1],
"ALIC_1/ZDCA_1/ZNEU_2/ZNTX_1/ZN1_1"));
c->AddElement(zdc_make_shape("Tower 2", tb, te[2],
"ALIC_1/ZDCA_1/ZNEU_2/ZNTX_1/ZN1_2"));
c->AddElement(zdc_make_shape("Tower 3", tb, te[3],
"ALIC_1/ZDCA_1/ZNEU_2/ZNTX_2/ZN1_1"));
c->AddElement(zdc_make_shape("Tower 4", tb, te[4],
"ALIC_1/ZDCA_1/ZNEU_2/ZNTX_2/ZN1_2"));
// ZPC geometry ------------------------------------
tb = "ZPC";
c = new TEveElementList(tb);
l->AddElement(c);
te = esd->GetZP1TowerEnergy();
c->AddElement(zdc_make_shape("Tower 1", tb, te[1],
"ALIC_1/ZDCC_1/ZPRO_1/ZPTX_1/ZP1_1"));
c->AddElement(zdc_make_shape("Tower 2", tb, te[2],
"ALIC_1/ZDCC_1/ZPRO_1/ZPTX_2/ZP1_1"));
c->AddElement(zdc_make_shape("Tower 3", tb, te[3],
"ALIC_1/ZDCC_1/ZPRO_1/ZPTX_3/ZP1_1"));
c->AddElement(zdc_make_shape("Tower 4", tb, te[4],
"ALIC_1/ZDCC_1/ZPRO_1/ZPTX_4/ZP1_1"));
// ZPA geometry
tb = "ZPA";
c = new TEveElementList(tb);
l->AddElement(c);
te = esd->GetZP2TowerEnergy();
c->AddElement(zdc_make_shape("Tower 1", tb, te[1],
"ALIC_1/ZDCA_1/ZPRO_2/ZPTX_1/ZP1_1"));
c->AddElement(zdc_make_shape("Tower 2", tb, te[2],
"ALIC_1/ZDCA_1/ZPRO_2/ZPTX_2/ZP1_1"));
c->AddElement(zdc_make_shape("Tower 3", tb, te[3],
"ALIC_1/ZDCA_1/ZPRO_2/ZPTX_3/ZP1_1"));
c->AddElement(zdc_make_shape("Tower 4", tb, te[4],
"ALIC_1/ZDCA_1/ZPRO_2/ZPTX_4/ZP1_1"));
// Centroids
TEveStraightLineSet *ls = 0;
Double32_t *cNA = esd->GetZNACentroid();
ls = zdc_make_cross("ZNA Centroid", "ZNA",
cNA[0], cNA[1], g_zdc_dist * g_zdc_scale,
g_zdc_cross, g_zdc_cross, g_zdc_cross);
l->AddElement(ls);
Double32_t *cNC = esd->GetZNCCentroid();
ls = zdc_make_cross("ZNA Centroid", "ZNA",
cNC[0], cNC[1], -g_zdc_dist * g_zdc_scale,
g_zdc_cross, g_zdc_cross, g_zdc_cross);
l->AddElement(ls);
// End - refresh screen
gEve->Redraw3D();
}
<commit_msg>Obsolete part commented out<commit_after>TEveRGBAPalette *g_zdc_palette = 0;
Float_t g_zdc_scale = 0.1;
Float_t g_zdc_dist = 11695;
Float_t g_zdc_cross = 20;
TEveGeoShape* zdc_make_shape(const Text_t* name, const Text_t* title_base,
Double_t signal, const Text_t* path)
{
if ( ! gGeoManager->cd(path))
{
Warning("zdc_make_shape", "Module name=%s, path='%s' not found.\n", name, path);
return 0;
}
UChar_t rgb[3];
g_zdc_palette->ColorFromValue(TMath::Nint(signal), rgb, kFALSE);
TGeoShape *gs = (TGeoShape*) gGeoManager->GetCurrentVolume()->GetShape()->Clone();
TEveGeoShape *s = new TEveGeoShape(name, Form("%s %s, E=%.3f", title_base, name, signal));
s->SetPickable(kTRUE);
s->SetMainColorRGB(rgb[0], rgb[1], rgb[2]);
s->SetShape(gs);
s->RefMainTrans().SetFrom(*gGeoManager->GetCurrentMatrix());
// Scale z-dictance by 0.1
Double_t* t = s->RefMainTrans().ArrT();
t[2] *= g_zdc_scale;
return s;
}
TEveStraightLineSet*
zdc_make_cross(const Text_t* name, const Text_t* title_base,
Float_t x, Float_t y, Float_t z, Float_t dx, Float_t dy, Float_t dz)
{
TEveStraightLineSet* ls = new TEveStraightLineSet(name, Form("%s, x=%.3f, y=%.3f", title_base, x, y));
ls->SetMainColor(kYellow);
ls->SetLineWidth(2);
ls->RefMainTrans().SetPos(x, y, z);
ls->AddLine(dx, 0, 0, -dx, 0, 0);
ls->AddLine(0, dy, 0, 0, -dy, 0);
ls->AddLine(0, 0, dz, 0, 0, -dz);
return ls;
}
// ???? There are 5 towers in ESD, 4 in geom.
// Not sure about assignment A/C <-> 1/2
void esd_zdc()
{
AliEveEventManager::AssertGeometry();
AliESDZDC *esd = AliEveEventManager::AssertESD()->GetESDZDC();
if (g_zdc_palette == 0)
{
// Map values from 0, 50 on a spectrum palette.
g_zdc_palette = new TEveRGBAPalette(0, 50, kTRUE, kFALSE);
g_zdc_palette->IncRefCount();
gStyle->SetPalette(1, 0);
g_zdc_palette->SetupColorArray();
}
TEveElementList* l = new TEveElementList("ZDC Data", "");
gEve->AddElement(l);
TEveElementList *c = 0;
TEveGeoShape *s = 0;
Double_t *te = 0;
Text_t *tb = 0;
// ZNC geometry ------------------------------------
tb = "ZNC";
c = new TEveElementList(tb);
l->AddElement(c);
te = esd->GetZN1TowerEnergy();
c->AddElement(zdc_make_shape("Tower 1", tb, te[1],
"ALIC_1/ZDCC_1/ZNEU_1/ZNTX_1/ZN1_1"));
c->AddElement(zdc_make_shape("Tower 2", tb, te[2],
"ALIC_1/ZDCC_1/ZNEU_1/ZNTX_1/ZN1_2"));
c->AddElement(zdc_make_shape("Tower 3", tb, te[3],
"ALIC_1/ZDCC_1/ZNEU_1/ZNTX_2/ZN1_1"));
c->AddElement(zdc_make_shape("Tower 4", tb, te[4],
"ALIC_1/ZDCC_1/ZNEU_1/ZNTX_2/ZN1_2"));
// ZNA geometry
tb = "ZNA";
c = new TEveElementList(tb);
l->AddElement(c);
te = esd->GetZN2TowerEnergy();
c->AddElement(zdc_make_shape("Tower 1", tb, te[1],
"ALIC_1/ZDCA_1/ZNEU_2/ZNTX_1/ZN1_1"));
c->AddElement(zdc_make_shape("Tower 2", tb, te[2],
"ALIC_1/ZDCA_1/ZNEU_2/ZNTX_1/ZN1_2"));
c->AddElement(zdc_make_shape("Tower 3", tb, te[3],
"ALIC_1/ZDCA_1/ZNEU_2/ZNTX_2/ZN1_1"));
c->AddElement(zdc_make_shape("Tower 4", tb, te[4],
"ALIC_1/ZDCA_1/ZNEU_2/ZNTX_2/ZN1_2"));
// ZPC geometry ------------------------------------
tb = "ZPC";
c = new TEveElementList(tb);
l->AddElement(c);
te = esd->GetZP1TowerEnergy();
c->AddElement(zdc_make_shape("Tower 1", tb, te[1],
"ALIC_1/ZDCC_1/ZPRO_1/ZPTX_1/ZP1_1"));
c->AddElement(zdc_make_shape("Tower 2", tb, te[2],
"ALIC_1/ZDCC_1/ZPRO_1/ZPTX_2/ZP1_1"));
c->AddElement(zdc_make_shape("Tower 3", tb, te[3],
"ALIC_1/ZDCC_1/ZPRO_1/ZPTX_3/ZP1_1"));
c->AddElement(zdc_make_shape("Tower 4", tb, te[4],
"ALIC_1/ZDCC_1/ZPRO_1/ZPTX_4/ZP1_1"));
// ZPA geometry
tb = "ZPA";
c = new TEveElementList(tb);
l->AddElement(c);
te = esd->GetZP2TowerEnergy();
c->AddElement(zdc_make_shape("Tower 1", tb, te[1],
"ALIC_1/ZDCA_1/ZPRO_2/ZPTX_1/ZP1_1"));
c->AddElement(zdc_make_shape("Tower 2", tb, te[2],
"ALIC_1/ZDCA_1/ZPRO_2/ZPTX_2/ZP1_1"));
c->AddElement(zdc_make_shape("Tower 3", tb, te[3],
"ALIC_1/ZDCA_1/ZPRO_2/ZPTX_3/ZP1_1"));
c->AddElement(zdc_make_shape("Tower 4", tb, te[4],
"ALIC_1/ZDCA_1/ZPRO_2/ZPTX_4/ZP1_1"));
// Centroids
/*
TEveStraightLineSet *ls = 0;
This part has to be fixed: the getters now depend on the beam type: pp or PbPb,
and in case of PbPb we also habe to provide the beam. Peter
Double32_t *cNA = esd->GetZNACentroid();
ls = zdc_make_cross("ZNA Centroid", "ZNA",
cNA[0], cNA[1], g_zdc_dist * g_zdc_scale,
g_zdc_cross, g_zdc_cross, g_zdc_cross);
l->AddElement(ls);
Double32_t *cNC = esd->GetZNCCentroid();
ls = zdc_make_cross("ZNA Centroid", "ZNA",
cNC[0], cNC[1], -g_zdc_dist * g_zdc_scale,
g_zdc_cross, g_zdc_cross, g_zdc_cross);
l->AddElement(ls);
*/
// End - refresh screen
gEve->Redraw3D();
}
<|endoftext|>
|
<commit_before>#include "TcpServer.h"
#include <iostream>
#include <string>
#include "StaticCommand.h"
void callback(Object&,EventArgs) {
std::cerr << "Read Timed Out [Intentional]" << std::endl;
}
int main() {
Impact::TcpServer server(25565);
std::cout << "- SERVER STARTED -" << std::endl;
auto connection = server.accept();
connection->setTimeout(2500); // 2.5 seconds
connection->onTimeout += StaticCommandPtr(
EventArgs,
callback
);
std::cout << "Found new Client" << std::endl;
std::string msg;
std::getline(*connection, msg);
std::cout << "msg: " << msg << std::endl;
*connection << "Hello From Server" << std::endl;
std::string done;
std::getline(*connection, done);
std::cout << "done: " << done << std::endl;
// attempt to wait for client but timeout because nothing arrives
std::string latemsg = "- NO MESSAGE -";
std::getline(*connection, latemsg);
std::cout << latemsg << std::endl;
std::cout << "- END OF LINE -" << std::endl;
return 0;
}<commit_msg>Update DemoTCPServer.cpp<commit_after>#include "TcpServer.h"
#include <iostream>
#include <string>
#include "StaticCommand.h"
void callback(Object&,EventArgs) {
std::cerr << "Read Timed Out [Intentional]" << std::endl;
}
int main() {
Impact::TcpServer server(25565);
std::cout << "- SERVER STARTED -" << std::endl;
auto connection = server.accept();
connection->setTimeout(2500); // 2.5 seconds
connection->onTimeout += StaticCommandPtr(
EventArgs,
callback
);
std::cout << "Found new Client" << std::endl;
std::string msg;
std::getline(*connection, msg);
std::cout << "msg: " << msg << std::endl;
*connection << "Hello From Server" << std::endl;
std::string done;
std::getline(*connection, done);
std::cout << "done: " << done << std::endl;
// attempt to wait for client but timeout because nothing arrives
std::string latemsg = "- NO MESSAGE -";
std::getline(*connection, latemsg);
std::cout << latemsg << std::endl;
std::cout << "- END OF LINE -" << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
// Utility class to manage DSP parameters which can change value smoothly (be ramped) while rendering, without introducing clicks or other distortion into the signal.
//
// Originally based on Apple sample code, but significantly altered by Aurelius Prochazka
#pragma once
#ifdef __cplusplus
// N.B. This is C++.
#import <AudioToolbox/AudioToolbox.h>
#import <libkern/OSAtomic.h>
#import <atomic>
class ParameterRamper {
float clampLow, clampHigh;
float _uiValue;
float _goal;
float inverseSlope;
AUAudioFrameCount samplesRemaining;
std::atomic<int32_t> changeCounter;
int32_t updateCounter = 0;
void setImmediate(float value) {
// only to be called from the render thread or when resources are not allocated.
_goal = _uiValue = value;
inverseSlope = 0.0;
samplesRemaining = 0;
}
public:
ParameterRamper(float value = 0.0f) : changeCounter(0) {
setImmediate(value);
}
void init() {
/*
Call this from the kernel init.
Updates the internal value from the UI value.
*/
setImmediate(_uiValue);
}
void reset() {
changeCounter = updateCounter = 0;
}
void setUIValue(float value) {
_uiValue = value;
std::atomic_fetch_add(&changeCounter, 1);
}
float getUIValue() const { return _uiValue; }
void dezipperCheck(AUAudioFrameCount rampDuration)
{
// check to see if the UI has changed and if so, start a ramp to dezipper it.
int32_t changeCounterSnapshot = changeCounter;
if (updateCounter != changeCounterSnapshot) {
updateCounter = changeCounterSnapshot;
startRamp(_uiValue, rampDuration);
}
}
void startRamp(float newGoal, AUAudioFrameCount duration) {
if (duration == 0) {
setImmediate(newGoal);
}
else {
/*
Set a new ramp.
Assigning to inverseSlope must come before assigning to goal.
*/
inverseSlope = (get() - newGoal) / float(duration);
samplesRemaining = duration;
_goal = _uiValue = newGoal;
}
}
float get() const {
/*
For long ramps, integrating a sum loses precision and does not reach
the goal at the right time. So instead, a line equation is used. y = m * x + b.
*/
return inverseSlope * float(samplesRemaining) + _goal;
}
void step() {
// Do this in each inner loop iteration after getting the value.
if (samplesRemaining != 0) {
--samplesRemaining;
}
}
float getAndStep() {
// Combines get and step. Saves a multiply-add when not ramping.
if (samplesRemaining != 0) {
float value = get();
--samplesRemaining;
return value;
}
else {
return _goal;
}
}
void stepBy(AUAudioFrameCount n) {
/*
When a parameter does not participate in the current inner loop, you
will want to advance it after the end of the loop.
*/
if (n >= samplesRemaining) {
samplesRemaining = 0;
}
else {
samplesRemaining -= n;
}
}
};
#endif
<commit_msg>Fix data race detected by TSAN.<commit_after>// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
// Utility class to manage DSP parameters which can change value smoothly (be ramped) while rendering, without introducing clicks or other distortion into the signal.
//
// Originally based on Apple sample code, but significantly altered by Aurelius Prochazka
#pragma once
#ifdef __cplusplus
// N.B. This is C++.
#import <AudioToolbox/AudioToolbox.h>
#import <libkern/OSAtomic.h>
#import <atomic>
class ParameterRamper {
float clampLow, clampHigh;
std::atomic<float> _uiValue{0};
float _goal;
float inverseSlope;
AUAudioFrameCount samplesRemaining;
std::atomic<int32_t> changeCounter;
int32_t updateCounter = 0;
void setImmediate(float value) {
// only to be called from the render thread or when resources are not allocated.
_goal = _uiValue = value;
inverseSlope = 0.0;
samplesRemaining = 0;
}
public:
ParameterRamper(float value = 0.0f) : changeCounter(0) {
setImmediate(value);
}
void init() {
/*
Call this from the kernel init.
Updates the internal value from the UI value.
*/
setImmediate(_uiValue);
}
void reset() {
changeCounter = updateCounter = 0;
}
void setUIValue(float value) {
_uiValue = value;
std::atomic_fetch_add(&changeCounter, 1);
}
float getUIValue() const { return _uiValue; }
void dezipperCheck(AUAudioFrameCount rampDuration)
{
// check to see if the UI has changed and if so, start a ramp to dezipper it.
int32_t changeCounterSnapshot = changeCounter;
if (updateCounter != changeCounterSnapshot) {
updateCounter = changeCounterSnapshot;
startRamp(_uiValue, rampDuration);
}
}
void startRamp(float newGoal, AUAudioFrameCount duration) {
if (duration == 0) {
setImmediate(newGoal);
}
else {
/*
Set a new ramp.
Assigning to inverseSlope must come before assigning to goal.
*/
inverseSlope = (get() - newGoal) / float(duration);
samplesRemaining = duration;
_goal = _uiValue = newGoal;
}
}
float get() const {
/*
For long ramps, integrating a sum loses precision and does not reach
the goal at the right time. So instead, a line equation is used. y = m * x + b.
*/
return inverseSlope * float(samplesRemaining) + _goal;
}
void step() {
// Do this in each inner loop iteration after getting the value.
if (samplesRemaining != 0) {
--samplesRemaining;
}
}
float getAndStep() {
// Combines get and step. Saves a multiply-add when not ramping.
if (samplesRemaining != 0) {
float value = get();
--samplesRemaining;
return value;
}
else {
return _goal;
}
}
void stepBy(AUAudioFrameCount n) {
/*
When a parameter does not participate in the current inner loop, you
will want to advance it after the end of the loop.
*/
if (n >= samplesRemaining) {
samplesRemaining = 0;
}
else {
samplesRemaining -= n;
}
}
};
#endif
<|endoftext|>
|
<commit_before>// file : cli/runtime-source.cxx
// author : Boris Kolpackov <boris@codesynthesis.com>
// copyright : Copyright (c) 2009 Code Synthesis Tools CC
// license : MIT; see accompanying LICENSE file
#include "runtime-source.hxx"
using namespace std;
void
generate_runtime_source (context& ctx)
{
ostream& os (ctx.os);
os << "#include <string>" << endl
<< "#include <vector>" << endl
<< "#include <ostream>" << endl
<< "#include <sstream>" << endl
<< endl;
os << "namespace cli"
<< "{";
// unknown_option
//
os << "// unknown_option" << endl
<< "//" << endl
<< "unknown_option::" << endl
<< "~unknown_option () throw ()"
<< "{"
<< "}"
<< "void unknown_option::" << endl
<< "print (std::ostream& os) const"
<< "{"
<< "os << \"unknown option '\" << option () << \"'\";"
<< "}"
<< "const char* unknown_option::" << endl
<< "what () const throw ()"
<< "{"
<< "return \"unknown option\";"
<< "}";
// unknown_argument
//
os << "// unknown_argument" << endl
<< "//" << endl
<< "unknown_argument::" << endl
<< "~unknown_argument () throw ()"
<< "{"
<< "}"
<< "void unknown_argument::" << endl
<< "print (std::ostream& os) const"
<< "{"
<< "os << \"unknown argument '\" << argument () << \"'\";"
<< "}"
<< "const char* unknown_argument::" << endl
<< "what () const throw ()"
<< "{"
<< "return \"unknown argument\";"
<< "}";
// missing_value
//
os << "// missing_value" << endl
<< "//" << endl
<< "missing_value::" << endl
<< "~missing_value () throw ()"
<< "{"
<< "}"
<< "void missing_value::" << endl
<< "print (std::ostream& os) const"
<< "{"
<< "os << \"missing value for option '\" << option () << \"'\";"
<< "}"
<< "const char* missing_value::" << endl
<< "what () const throw ()"
<< "{"
<< "return \"missing option value\";"
<< "}";
// invalid_value
//
os << "// invalid_value" << endl
<< "//" << endl
<< "invalid_value::" << endl
<< "~invalid_value () throw ()"
<< "{"
<< "}"
<< "void invalid_value::" << endl
<< "print (std::ostream& os) const"
<< "{"
<< "os << \"invalid value '\" << value () << \"' for option '\"" << endl
<< " << option () << \"'\";"
<< "}"
<< "const char* invalid_value::" << endl
<< "what () const throw ()"
<< "{"
<< "return \"invalid option value\";"
<< "}";
// parser class template & its specializations
//
os << "template <typename X>" << endl
<< "struct parser"
<< "{"
<< "static int" << endl
<< "parse (X& x, char** argv, int n)"
<< "{"
<< "if (n > 1)"
<< "{"
<< "std::istringstream is (argv[1]);"
<< "if (!(is >> x && is.eof ()))" << endl
<< "throw invalid_value (argv[0], argv[1]);"
<< "return 2;"
<< "}"
<< "else" << endl
<< "throw missing_value (argv[0]);"
<< "}"
<< "};";
// parser<bool>
//
os << "template <>" << endl
<< "struct parser<bool>"
<< "{"
<< "static int" << endl
<< "parse (bool& x, char**, int)"
<< "{"
<< "x = true;"
<< "return 1;"
<< "}"
<< "};";
// parser<string>
//
os << "template <>" << endl
<< "struct parser<std::string>"
<< "{"
<< "static int" << endl
<< "parse (std::string& x, char** argv, int n)"
<< "{"
<< "if (n > 1)"
<< "{"
<< "x = argv[1];"
<< "return 2;"
<< "}"
<< "else" << endl
<< "throw missing_value (argv[0]);"
<< "}"
<< "};";
// parser<std::vector<X>>
//
os << "template <typename X>" << endl
<< "struct parser<std::vector<X> >"
<< "{"
<< "static int" << endl
<< "parse (std::vector<X>& v, char** argv, int n)"
<< "{"
<< "X x;"
<< "int i (parser<X>::parse (x, argv, n));"
<< "v.push_back (x);"
<< "return i;"
<< "}"
<< "};";
// Parser thunk.
//
os << "template <typename X, typename T, T X::*P>" << endl
<< "int" << endl
<< "thunk (X& x, char** argv, int n)"
<< "{"
<< "return parser<T>::parse (x.*P, argv, n);"
<< "}";
os << "}"; // namespace cli
}
<commit_msg>Add a parser for std::map<commit_after>// file : cli/runtime-source.cxx
// author : Boris Kolpackov <boris@codesynthesis.com>
// copyright : Copyright (c) 2009 Code Synthesis Tools CC
// license : MIT; see accompanying LICENSE file
#include "runtime-source.hxx"
using namespace std;
void
generate_runtime_source (context& ctx)
{
ostream& os (ctx.os);
os << "#include <map>" << endl
<< "#include <string>" << endl
<< "#include <vector>" << endl
<< "#include <ostream>" << endl
<< "#include <sstream>" << endl
<< endl;
os << "namespace cli"
<< "{";
// unknown_option
//
os << "// unknown_option" << endl
<< "//" << endl
<< "unknown_option::" << endl
<< "~unknown_option () throw ()"
<< "{"
<< "}"
<< "void unknown_option::" << endl
<< "print (std::ostream& os) const"
<< "{"
<< "os << \"unknown option '\" << option () << \"'\";"
<< "}"
<< "const char* unknown_option::" << endl
<< "what () const throw ()"
<< "{"
<< "return \"unknown option\";"
<< "}";
// unknown_argument
//
os << "// unknown_argument" << endl
<< "//" << endl
<< "unknown_argument::" << endl
<< "~unknown_argument () throw ()"
<< "{"
<< "}"
<< "void unknown_argument::" << endl
<< "print (std::ostream& os) const"
<< "{"
<< "os << \"unknown argument '\" << argument () << \"'\";"
<< "}"
<< "const char* unknown_argument::" << endl
<< "what () const throw ()"
<< "{"
<< "return \"unknown argument\";"
<< "}";
// missing_value
//
os << "// missing_value" << endl
<< "//" << endl
<< "missing_value::" << endl
<< "~missing_value () throw ()"
<< "{"
<< "}"
<< "void missing_value::" << endl
<< "print (std::ostream& os) const"
<< "{"
<< "os << \"missing value for option '\" << option () << \"'\";"
<< "}"
<< "const char* missing_value::" << endl
<< "what () const throw ()"
<< "{"
<< "return \"missing option value\";"
<< "}";
// invalid_value
//
os << "// invalid_value" << endl
<< "//" << endl
<< "invalid_value::" << endl
<< "~invalid_value () throw ()"
<< "{"
<< "}"
<< "void invalid_value::" << endl
<< "print (std::ostream& os) const"
<< "{"
<< "os << \"invalid value '\" << value () << \"' for option '\"" << endl
<< " << option () << \"'\";"
<< "}"
<< "const char* invalid_value::" << endl
<< "what () const throw ()"
<< "{"
<< "return \"invalid option value\";"
<< "}";
// parser class template & its specializations
//
os << "template <typename X>" << endl
<< "struct parser"
<< "{"
<< "static int" << endl
<< "parse (X& x, char** argv, int n)"
<< "{"
<< "if (n > 1)"
<< "{"
<< "std::istringstream is (argv[1]);"
<< "if (!(is >> x && is.eof ()))" << endl
<< "throw invalid_value (argv[0], argv[1]);"
<< "return 2;"
<< "}"
<< "else" << endl
<< "throw missing_value (argv[0]);"
<< "}"
<< "};";
// parser<bool>
//
os << "template <>" << endl
<< "struct parser<bool>"
<< "{"
<< "static int" << endl
<< "parse (bool& x, char**, int)"
<< "{"
<< "x = true;"
<< "return 1;"
<< "}"
<< "};";
// parser<string>
//
os << "template <>" << endl
<< "struct parser<std::string>"
<< "{"
<< "static int" << endl
<< "parse (std::string& x, char** argv, int n)"
<< "{"
<< "if (n > 1)"
<< "{"
<< "x = argv[1];"
<< "return 2;"
<< "}"
<< "else" << endl
<< "throw missing_value (argv[0]);"
<< "}"
<< "};";
// parser<std::vector<X>>
//
os << "template <typename X>" << endl
<< "struct parser<std::vector<X> >"
<< "{"
<< "static int" << endl
<< "parse (std::vector<X>& v, char** argv, int n)"
<< "{"
<< "X x;"
<< "int i (parser<X>::parse (x, argv, n));"
<< "v.push_back (x);"
<< "return i;"
<< "}"
<< "};";
// parser<std::map<K,V>>
//
os << "template <typename K, typename V>" << endl
<< "struct parser<std::map<K, V> >"
<< "{"
<< "static int" << endl
<< "parse (std::map<K, V>& m, char** argv, int n)"
<< "{"
<< "if (n > 1)"
<< "{"
<< "std::string s (argv[1]);"
<< "std::string::size_type p (s.find ('='));"
<< endl
<< "if (p == std::string::npos)"
<< "{"
<< "K k = K ();"
<< endl
<< "if (!s.empty ())"
<< "{"
<< "std::istringstream ks (s);"
<< endl
<< "if (!(ks >> k && ks.eof ()))" << endl
<< "throw invalid_value (argv[0], argv[1]);"
<< "}"
<< "m[k] = V ();"
<< "}"
<< "else"
<< "{"
<< "K k = K ();"
<< "V v = V ();"
<< "std::string kstr (s, 0, p);"
<< "std::string vstr (s, p + 1);"
<< endl
<< "if (!kstr.empty ())"
<< "{"
<< "std::istringstream ks (kstr);"
<< endl
<< "if (!(ks >> k && ks.eof ()))" << endl
<< "throw invalid_value (argv[0], argv[1]);"
<< "}"
<< "if (!vstr.empty ())"
<< "{"
<< "std::istringstream vs (vstr);"
<< endl
<< "if (!(vs >> v && vs.eof ()))" << endl
<< "throw invalid_value (argv[0], argv[1]);"
<< "}"
<< "m[k] = v;"
<< "}"
<< "return 2;"
<< "}"
<< "else" << endl
<< "throw missing_value (argv[0]);"
<< "}"
<< "};";
// Parser thunk.
//
os << "template <typename X, typename T, T X::*P>" << endl
<< "int" << endl
<< "thunk (X& x, char** argv, int n)"
<< "{"
<< "return parser<T>::parse (x.*P, argv, n);"
<< "}";
os << "}"; // namespace cli
}
<|endoftext|>
|
<commit_before>// Copyright 2011 Branan Purvine-Riley and Adam Johnson
//
// 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 SENSE_CLIENT_DATAMANAGER_HPP
#define SENSE_CLIENT_DATAMANAGER_HPP
class Loader;
// The data manager loads anything that exists inside
// a game data package. It should be run on a worker thread,
// and "mainThreadTick" should be called every frame.
class DataManager
{
public:
DataManager(Loader*);
~DataManager();
void exec();
void finish();
void mainThreadTick();
private:
Loader* m_loader;
volatile bool m_finished;
};
#endif // SENSE_CLIENT_DATAMANAGER_HPP
<commit_msg>Add loadMaterial declaration<commit_after>// Copyright 2011 Branan Purvine-Riley and Adam Johnson
//
// 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 SENSE_CLIENT_DATAMANAGER_HPP
#define SENSE_CLIENT_DATAMANAGER_HPP
#include <unordered_map>
class Loader;
class Material;
// The data manager loads anything that exists inside
// a game data package. It should be run on a worker thread,
// and "mainThreadTick" should be called every frame in the main rendering thread.
class DataManager
{
public:
DataManager(Loader*);
~DataManager();
void exec();
void finish();
void mainThreadTick();
Material* loadMaterial(std::string);
private:
Loader* m_loader;
volatile bool m_finished;
std::unordered_map<std::string, Material*> m_materials;
};
#endif // SENSE_CLIENT_DATAMANAGER_HPP
<|endoftext|>
|
<commit_before>/* The Next Great Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* This library is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public */
/* License as published by the Free Software Foundation; either */
/* version 2.1 of the License, or (at your option) any later version. */
/* This library is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */
/* Lesser General Public License for more details. */
/* You should have received a copy of the GNU Lesser General Public */
/* License along with this library; if not, write to the Free Software */
/* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
// <h1>Adaptivity Example 1 - Solving 1D PDE Using Adaptive Mesh Refinement</h1>
//
// This example demonstrates how to solve a simple 1D problem
// using adaptive mesh refinement. The PDE that is solved is:
// -epsilon*u''(x) + u(x) = 1, on the domain [0,1] with boundary conditions
// u(0) = u(1) = 0 and where epsilon << 1.
//
// The approach used to solve 1D problems in libMesh is virtually identical to
// solving 2D or 3D problems, so in this sense this example represents a good
// starting point for new users. Note that many concepts are used in this
// example which are explained more fully in subsequent examples.
// Libmesh includes
#include "mesh.h"
#include "mesh_generation.h"
#include "edge_edge3.h"
#include "gnuplot_io.h"
#include "equation_systems.h"
#include "linear_implicit_system.h"
#include "fe.h"
#include "quadrature_gauss.h"
#include "sparse_matrix.h"
#include "dof_map.h"
#include "numeric_vector.h"
#include "dense_matrix.h"
#include "dense_vector.h"
#include "error_vector.h"
#include "kelly_error_estimator.h"
#include "mesh_refinement.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
void assemble_1D(EquationSystems& es, const std::string& system_name);
int main(int argc, char** argv)
{
// Initialize the library. This is necessary because the library
// may depend on a number of other libraries (i.e. MPI and PETSc)
// that require initialization before use. When the LibMeshInit
// object goes out of scope, other libraries and resources are
// finalized.
LibMeshInit init (argc, argv);
// Skip adaptive examples on a non-adaptive libMesh build
#ifndef LIBMESH_ENABLE_AMR
libmesh_example_assert(false, "--enable-amr");
#else
// Create a new mesh
Mesh mesh;
// Build a 1D mesh with 4 elements from x=0 to x=1, using
// EDGE3 (i.e. quadratic) 1D elements. They are called EDGE3 elements
// because a quadratic element contains 3 nodes.
MeshTools::Generation::build_line(mesh,4,0.,1.,EDGE3);
// Define the equation systems object and the system we are going
// to solve. See Example 2 for more details.
EquationSystems equation_systems(mesh);
LinearImplicitSystem& system = equation_systems.add_system
<LinearImplicitSystem>("1D");
// Add a variable "u" to the system, using second-order approximation
system.add_variable("u",SECOND);
// Give the system a pointer to the matrix assembly function. This
// will be called when needed by the library.
system.attach_assemble_function(assemble_1D);
// Define the mesh refinement object that takes care of adaptively
// refining the mesh.
MeshRefinement mesh_refinement(mesh);
// These parameters determine the proportion of elements that will
// be refined and coarsened. Any element within 30% of the maximum
// error on any element will be refined, and any element within 30%
// of the minimum error on any element might be coarsened
mesh_refinement.refine_fraction() = 0.7;
mesh_refinement.coarsen_fraction() = 0.3;
// We won't refine any element more than 5 times in total
mesh_refinement.max_h_level() = 5;
// Initialize the data structures for the equation system.
equation_systems.init();
// Refinement parameters
const unsigned int max_r_steps = 5; // Refine the mesh 5 times
// Define the refinement loop
for(unsigned int r_step=0; r_step<=max_r_steps; r_step++)
{
// Solve the equation system
equation_systems.get_system("1D").solve();
// We need to ensure that the mesh is not refined on the last iteration
// of this loop, since we do not want to refine the mesh unless we are
// going to solve the equation system for that refined mesh.
if(r_step != max_r_steps)
{
// Objects for error estimation, see Example 10 for more details.
ErrorVector error;
KellyErrorEstimator error_estimator;
// Compute the error for each active element
error_estimator.estimate_error(system, error);
// Flag elements to be refined and coarsened
mesh_refinement.flag_elements_by_error_fraction (error);
// Perform refinement and coarsening
mesh_refinement.refine_and_coarsen_elements();
// Reinitialize the equation_systems object for the newly refined
// mesh. One of the steps in this is project the solution onto the
// new mesh
equation_systems.reinit();
}
}
// Construct gnuplot plotting object, pass in mesh, title of plot
// and boolean to indicate use of grid in plot. The grid is used to
// show the edges of each element in the mesh.
GnuPlotIO plot(mesh,"Example 0", GnuPlotIO::GRID_ON);
// Write out script to be called from within gnuplot:
// Load gnuplot, then type "call 'gnuplot_script'" from gnuplot prompt
plot.write_equation_systems("gnuplot_script",equation_systems);
#endif // #ifndef LIBMESH_ENABLE_AMR
// All done. libMesh objects are destroyed here. Because the
// LibMeshInit object was created first, its destruction occurs
// last, and it's destructor finalizes any external libraries and
// checks for leaked memory.
return 0;
}
// Define the matrix assembly function for the 1D PDE we are solving
void assemble_1D(EquationSystems& es, const std::string& system_name)
{
#ifdef LIBMESH_ENABLE_AMR
// It is a good idea to check we are solving the correct system
libmesh_assert(system_name == "1D");
// Get a reference to the mesh object
const MeshBase& mesh = es.get_mesh();
// The dimension we are using, i.e. dim==1
const unsigned int dim = mesh.mesh_dimension();
// Get a reference to the system we are solving
LinearImplicitSystem& system = es.get_system<LinearImplicitSystem>("1D");
// Get a reference to the DofMap object for this system. The DofMap object
// handles the index translation from node and element numbers to degree of
// freedom numbers. DofMap's are discussed in more detail in future examples.
const DofMap& dof_map = system.get_dof_map();
// Get a constant reference to the Finite Element type for the first
// (and only) variable in the system.
FEType fe_type = dof_map.variable_type(0);
// Build a finite element object of the specified type. The build
// function dynamically allocates memory so we use an AutoPtr in this case.
// An AutoPtr is a pointer that cleans up after itself. See examples 3 and 4
// for more details on AutoPtr.
AutoPtr<FEBase> fe(FEBase::build(dim, fe_type));
// Tell the finite element object to use fifth order Gaussian quadrature
QGauss qrule(dim,FIFTH);
fe->attach_quadrature_rule(&qrule);
// Here we define some references to cell-specific data that will be used to
// assemble the linear system.
// The element Jacobian * quadrature weight at each integration point.
const std::vector<Real>& JxW = fe->get_JxW();
// The element shape functions evaluated at the quadrature points.
const std::vector<std::vector<Real> >& phi = fe->get_phi();
// The element shape function gradients evaluated at the quadrature points.
const std::vector<std::vector<RealGradient> >& dphi = fe->get_dphi();
// Declare a dense matrix and dense vector to hold the element matrix
// and right-hand-side contribution
DenseMatrix<Number> Ke;
DenseVector<Number> Fe;
// This vector will hold the degree of freedom indices for the element.
// These define where in the global system the element degrees of freedom
// get mapped.
std::vector<unsigned int> dof_indices;
// We now loop over all the active elements in the mesh in order to calculate
// the matrix and right-hand-side contribution from each element. Use a
// const_element_iterator to loop over the elements. We make
// el_end const as it is used only for the stopping condition of the loop.
MeshBase::const_element_iterator el = mesh.active_local_elements_begin();
const MeshBase::const_element_iterator el_end = mesh.active_local_elements_end();
// Note that ++el is preferred to el++ when using loops with iterators
for( ; el != el_end; ++el)
{
// It is convenient to store a pointer to the current element
const Elem* elem = *el;
// Get the degree of freedom indices for the current element.
// These define where in the global matrix and right-hand-side this
// element will contribute to.
dof_map.dof_indices(elem, dof_indices);
// Compute the element-specific data for the current element. This
// involves computing the location of the quadrature points (q_point)
// and the shape functions (phi, dphi) for the current element.
fe->reinit(elem);
// Store the number of local degrees of freedom contained in this element
const int n_dofs = dof_indices.size();
// We resize and zero out Ke and Fe (resize() also clears the matrix and
// vector). In this example, all elements in the mesh are EDGE3's, so
// Ke will always be 3x3, and Fe will always be 3x1. If the mesh contained
// different element types, then the size of Ke and Fe would change.
Ke.resize(n_dofs, n_dofs);
Fe.resize(n_dofs);
// Now loop over quadrature points to handle numerical integration
for(unsigned int qp=0; qp<qrule.n_points(); qp++)
{
// Now build the element matrix and right-hand-side using loops to
// integrate the test functions (i) against the trial functions (j).
for(unsigned int i=0; i<phi.size(); i++)
{
Fe(i) += JxW[qp]*phi[i][qp];
for(unsigned int j=0; j<phi.size(); j++)
{
Ke(i,j) += JxW[qp]*(1.e-3*dphi[i][qp]*dphi[j][qp] +
phi[i][qp]*phi[j][qp]);
}
}
}
// At this point we have completed the matrix and RHS summation. The
// final step is to apply boundary conditions, which in this case are
// simple Dirichlet conditions with u(0) = u(1) = 0.
// Define the penalty parameter used to enforce the BC's
double penalty = 1.e10;
// Loop over the sides of this element. For a 1D element, the "sides"
// are defined as the nodes on each edge of the element, i.e. 1D elements
// have 2 sides.
for(unsigned int s=0; s<elem->n_sides(); s++)
{
// If this element has a NULL neighbor, then it is on the edge of the
// mesh and we need to enforce a boundary condition using the penalty
// method.
if(elem->neighbor(s) == NULL)
{
Ke(s,s) += penalty;
Fe(s) += 0*penalty;
}
}
// This is a function call that is necessary when using adaptive
// mesh refinement. See Example 10 for more details.
dof_map.constrain_element_matrix_and_vector (Ke, Fe, dof_indices);
// Add Ke and Fe to the global matrix and right-hand-side.
system.matrix->add_matrix(Ke, dof_indices);
system.rhs->add_vector(Fe, dof_indices);
}
#endif // #ifdef LIBMESH_ENABLE_AMR
}
<commit_msg>Allow overriding of initial mesh size, for testing purposes<commit_after>/* The Next Great Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* This library is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public */
/* License as published by the Free Software Foundation; either */
/* version 2.1 of the License, or (at your option) any later version. */
/* This library is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */
/* Lesser General Public License for more details. */
/* You should have received a copy of the GNU Lesser General Public */
/* License along with this library; if not, write to the Free Software */
/* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
// <h1>Adaptivity Example 1 - Solving 1D PDE Using Adaptive Mesh Refinement</h1>
//
// This example demonstrates how to solve a simple 1D problem
// using adaptive mesh refinement. The PDE that is solved is:
// -epsilon*u''(x) + u(x) = 1, on the domain [0,1] with boundary conditions
// u(0) = u(1) = 0 and where epsilon << 1.
//
// The approach used to solve 1D problems in libMesh is virtually identical to
// solving 2D or 3D problems, so in this sense this example represents a good
// starting point for new users. Note that many concepts are used in this
// example which are explained more fully in subsequent examples.
// Libmesh includes
#include "mesh.h"
#include "mesh_generation.h"
#include "edge_edge3.h"
#include "gnuplot_io.h"
#include "equation_systems.h"
#include "linear_implicit_system.h"
#include "fe.h"
#include "getpot.h"
#include "quadrature_gauss.h"
#include "sparse_matrix.h"
#include "dof_map.h"
#include "numeric_vector.h"
#include "dense_matrix.h"
#include "dense_vector.h"
#include "error_vector.h"
#include "kelly_error_estimator.h"
#include "mesh_refinement.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
void assemble_1D(EquationSystems& es, const std::string& system_name);
int main(int argc, char** argv)
{
// Initialize the library. This is necessary because the library
// may depend on a number of other libraries (i.e. MPI and PETSc)
// that require initialization before use. When the LibMeshInit
// object goes out of scope, other libraries and resources are
// finalized.
LibMeshInit init (argc, argv);
// Skip adaptive examples on a non-adaptive libMesh build
#ifndef LIBMESH_ENABLE_AMR
libmesh_example_assert(false, "--enable-amr");
#else
// Create a new mesh
Mesh mesh;
GetPot command_line (argc, argv);
int n = 4;
if ( command_line.search(1, "-n") )
n = command_line.next(n);
// Build a 1D mesh with 4 elements from x=0 to x=1, using
// EDGE3 (i.e. quadratic) 1D elements. They are called EDGE3 elements
// because a quadratic element contains 3 nodes.
MeshTools::Generation::build_line(mesh,n,0.,1.,EDGE3);
// Define the equation systems object and the system we are going
// to solve. See Example 2 for more details.
EquationSystems equation_systems(mesh);
LinearImplicitSystem& system = equation_systems.add_system
<LinearImplicitSystem>("1D");
// Add a variable "u" to the system, using second-order approximation
system.add_variable("u",SECOND);
// Give the system a pointer to the matrix assembly function. This
// will be called when needed by the library.
system.attach_assemble_function(assemble_1D);
// Define the mesh refinement object that takes care of adaptively
// refining the mesh.
MeshRefinement mesh_refinement(mesh);
// These parameters determine the proportion of elements that will
// be refined and coarsened. Any element within 30% of the maximum
// error on any element will be refined, and any element within 30%
// of the minimum error on any element might be coarsened
mesh_refinement.refine_fraction() = 0.7;
mesh_refinement.coarsen_fraction() = 0.3;
// We won't refine any element more than 5 times in total
mesh_refinement.max_h_level() = 5;
// Initialize the data structures for the equation system.
equation_systems.init();
// Refinement parameters
const unsigned int max_r_steps = 5; // Refine the mesh 5 times
// Define the refinement loop
for(unsigned int r_step=0; r_step<=max_r_steps; r_step++)
{
// Solve the equation system
equation_systems.get_system("1D").solve();
// We need to ensure that the mesh is not refined on the last iteration
// of this loop, since we do not want to refine the mesh unless we are
// going to solve the equation system for that refined mesh.
if(r_step != max_r_steps)
{
// Objects for error estimation, see Example 10 for more details.
ErrorVector error;
KellyErrorEstimator error_estimator;
// Compute the error for each active element
error_estimator.estimate_error(system, error);
// Flag elements to be refined and coarsened
mesh_refinement.flag_elements_by_error_fraction (error);
// Perform refinement and coarsening
mesh_refinement.refine_and_coarsen_elements();
// Reinitialize the equation_systems object for the newly refined
// mesh. One of the steps in this is project the solution onto the
// new mesh
equation_systems.reinit();
}
}
// Construct gnuplot plotting object, pass in mesh, title of plot
// and boolean to indicate use of grid in plot. The grid is used to
// show the edges of each element in the mesh.
GnuPlotIO plot(mesh,"Example 0", GnuPlotIO::GRID_ON);
// Write out script to be called from within gnuplot:
// Load gnuplot, then type "call 'gnuplot_script'" from gnuplot prompt
plot.write_equation_systems("gnuplot_script",equation_systems);
#endif // #ifndef LIBMESH_ENABLE_AMR
// All done. libMesh objects are destroyed here. Because the
// LibMeshInit object was created first, its destruction occurs
// last, and it's destructor finalizes any external libraries and
// checks for leaked memory.
return 0;
}
// Define the matrix assembly function for the 1D PDE we are solving
void assemble_1D(EquationSystems& es, const std::string& system_name)
{
#ifdef LIBMESH_ENABLE_AMR
// It is a good idea to check we are solving the correct system
libmesh_assert(system_name == "1D");
// Get a reference to the mesh object
const MeshBase& mesh = es.get_mesh();
// The dimension we are using, i.e. dim==1
const unsigned int dim = mesh.mesh_dimension();
// Get a reference to the system we are solving
LinearImplicitSystem& system = es.get_system<LinearImplicitSystem>("1D");
// Get a reference to the DofMap object for this system. The DofMap object
// handles the index translation from node and element numbers to degree of
// freedom numbers. DofMap's are discussed in more detail in future examples.
const DofMap& dof_map = system.get_dof_map();
// Get a constant reference to the Finite Element type for the first
// (and only) variable in the system.
FEType fe_type = dof_map.variable_type(0);
// Build a finite element object of the specified type. The build
// function dynamically allocates memory so we use an AutoPtr in this case.
// An AutoPtr is a pointer that cleans up after itself. See examples 3 and 4
// for more details on AutoPtr.
AutoPtr<FEBase> fe(FEBase::build(dim, fe_type));
// Tell the finite element object to use fifth order Gaussian quadrature
QGauss qrule(dim,FIFTH);
fe->attach_quadrature_rule(&qrule);
// Here we define some references to cell-specific data that will be used to
// assemble the linear system.
// The element Jacobian * quadrature weight at each integration point.
const std::vector<Real>& JxW = fe->get_JxW();
// The element shape functions evaluated at the quadrature points.
const std::vector<std::vector<Real> >& phi = fe->get_phi();
// The element shape function gradients evaluated at the quadrature points.
const std::vector<std::vector<RealGradient> >& dphi = fe->get_dphi();
// Declare a dense matrix and dense vector to hold the element matrix
// and right-hand-side contribution
DenseMatrix<Number> Ke;
DenseVector<Number> Fe;
// This vector will hold the degree of freedom indices for the element.
// These define where in the global system the element degrees of freedom
// get mapped.
std::vector<unsigned int> dof_indices;
// We now loop over all the active elements in the mesh in order to calculate
// the matrix and right-hand-side contribution from each element. Use a
// const_element_iterator to loop over the elements. We make
// el_end const as it is used only for the stopping condition of the loop.
MeshBase::const_element_iterator el = mesh.active_local_elements_begin();
const MeshBase::const_element_iterator el_end = mesh.active_local_elements_end();
// Note that ++el is preferred to el++ when using loops with iterators
for( ; el != el_end; ++el)
{
// It is convenient to store a pointer to the current element
const Elem* elem = *el;
// Get the degree of freedom indices for the current element.
// These define where in the global matrix and right-hand-side this
// element will contribute to.
dof_map.dof_indices(elem, dof_indices);
// Compute the element-specific data for the current element. This
// involves computing the location of the quadrature points (q_point)
// and the shape functions (phi, dphi) for the current element.
fe->reinit(elem);
// Store the number of local degrees of freedom contained in this element
const int n_dofs = dof_indices.size();
// We resize and zero out Ke and Fe (resize() also clears the matrix and
// vector). In this example, all elements in the mesh are EDGE3's, so
// Ke will always be 3x3, and Fe will always be 3x1. If the mesh contained
// different element types, then the size of Ke and Fe would change.
Ke.resize(n_dofs, n_dofs);
Fe.resize(n_dofs);
// Now loop over quadrature points to handle numerical integration
for(unsigned int qp=0; qp<qrule.n_points(); qp++)
{
// Now build the element matrix and right-hand-side using loops to
// integrate the test functions (i) against the trial functions (j).
for(unsigned int i=0; i<phi.size(); i++)
{
Fe(i) += JxW[qp]*phi[i][qp];
for(unsigned int j=0; j<phi.size(); j++)
{
Ke(i,j) += JxW[qp]*(1.e-3*dphi[i][qp]*dphi[j][qp] +
phi[i][qp]*phi[j][qp]);
}
}
}
// At this point we have completed the matrix and RHS summation. The
// final step is to apply boundary conditions, which in this case are
// simple Dirichlet conditions with u(0) = u(1) = 0.
// Define the penalty parameter used to enforce the BC's
double penalty = 1.e10;
// Loop over the sides of this element. For a 1D element, the "sides"
// are defined as the nodes on each edge of the element, i.e. 1D elements
// have 2 sides.
for(unsigned int s=0; s<elem->n_sides(); s++)
{
// If this element has a NULL neighbor, then it is on the edge of the
// mesh and we need to enforce a boundary condition using the penalty
// method.
if(elem->neighbor(s) == NULL)
{
Ke(s,s) += penalty;
Fe(s) += 0*penalty;
}
}
// This is a function call that is necessary when using adaptive
// mesh refinement. See Example 10 for more details.
dof_map.constrain_element_matrix_and_vector (Ke, Fe, dof_indices);
// Add Ke and Fe to the global matrix and right-hand-side.
system.matrix->add_matrix(Ke, dof_indices);
system.rhs->add_vector(Fe, dof_indices);
}
#endif // #ifdef LIBMESH_ENABLE_AMR
}
<|endoftext|>
|
<commit_before>#include "../../include/states/MainState.hpp"
#include "../../include/observers/StreamObserver.hpp"
#include "../../include/observers/StationsObserver.hpp"
#include "../../include/observers/StatusObserver.hpp"
#include "../../include/Constants.hpp"
#include "../../include/Utilities.hpp"
#include <nana/gui/widgets/menubar.hpp>
using namespace constants;
MainState::MainState(StatesManager& manager, Context& context)
: State(manager, context)
, container_(context.window)
, current_song_label_(context.window, "no song is playing")
, current_station_label_(context.window, "no station is playing")
, play_button_(context.window)
, pause_button_(context.window)
, mute_button_(context.window)
, search_textbox_(context.window)
, stations_listbox_(context.window)
, volume_slider_(context.window)
, song_label_menu_()
, listbox_item_menu_()
{
add_observers();
build_interface();
init_contextual_menus();
init_listbox();
run_concurrent_song_name_updater();
}
void MainState::change_visibility(bool visible)
{
container_.field_display("content", visible);
context_.menubar.show();
}
void MainState::add_observers()
{
subject_.attach(std::make_unique<StreamObserver>());
subject_.attach(std::make_unique<StationsObserver>());
subject_.attach(std::make_unique<StatusObserver>());
}
void MainState::run_concurrent_song_name_updater()
{
song_title_updater_ = std::thread(&MainState::update_titles, this);
song_title_updater_.detach();
}
void MainState::build_interface()
{
current_song_label_.events().mouse_up([this](const nana::arg_mouse& arg)
{
if (!arg.is_left_button())
{
pop_song_title_menu();
}
});
play_button_.caption("Play");
play_button_.events().click([this]()
{
subject_.notify(std::make_any<bool>(true), context_, events::Event::StreamPlay);
subject_.notify(Observer::placeholder, context_, events::Event::StreamPlayingStatus);
});
pause_button_.caption("Pause");
pause_button_.events().click([this]()
{
subject_.notify(std::make_any<bool>(true), context_, events::Event::StreamPause);
subject_.notify(Observer::placeholder, context_, events::Event::StreamPausedStatus);
});
mute_button_.caption("Mute");
mute_button_.enable_pushed(true);
mute_button_.events().mouse_up([this]()
{
if(mute_button_.pushed())
{
subject_.notify(std::make_any<unsigned int>(volume_slider_.value()), context_, events::Event::StreamMute);
}
else
{
subject_.notify(std::make_any<unsigned int>(volume_slider_.value()), context_, events::Event::VolumeChanged);
}
});
volume_slider_.scheme().color_vernier = VERNIER_COLOR;
volume_slider_.maximum(100);
volume_slider_.value(volume_float_to_int(context_.stream_manager.get_current_volume()));
volume_slider_.vernier([](unsigned int maximum, unsigned int cursor_value)
{
return std::string(std::to_string(cursor_value) + "/" + std::to_string(maximum));
});
volume_slider_.events().value_changed([this]()
{
if (!mute_button_.pushed())
{
subject_.notify(std::make_any<unsigned int>(volume_slider_.value()), context_, events::Event::VolumeChanged);
}
});
search_textbox_.line_wrapped(true).multi_lines(false).tip_string("Search...");
search_textbox_.events().text_changed([this]()
{
search_stations();
});
container_.div(
"<content vertical margin=[5%,0,0,0]"
"<buttons weight=12% arrange=[10%,10%,10%,10%] gap=1% margin=1%>"
"<labels weight=10% arrange=[49%,48%] gap=1% margin=1% >"
"<misc weight=8% arrange=[25%,72%] gap=1% margin=1%>"
"<listbox margin=[1%,1%,7%,1%]>"
">");
container_.field("buttons") << play_button_ << pause_button_ << mute_button_ ;
container_.field("labels") << current_station_label_ << current_song_label_;
container_.field("misc") << search_textbox_ << volume_slider_;
container_.field("listbox") << stations_listbox_;
container_.collocate();
}
void MainState::init_contextual_menus()
{
song_label_menu_.append("Copy title to clipboard.", [this](auto&)
{
std::string title = current_song_label_.caption();
copy_to_clipboard(title);
});
listbox_item_menu_.append("Play", [this](auto&)
{
set_new_stream();
});
listbox_item_menu_.append("Subscribe", [this](auto&)
{
subscribe_to_station();
});
listbox_item_menu_.append("Delete from list", [this](auto&)
{
delete_station();
});
}
void MainState::init_listbox()
{
stations_listbox_.append("User stations");
stations_listbox_.append("Default stations");
stations_listbox_.append_header("Station's name");
stations_listbox_.append_header("Ip");
stations_listbox_.append_header("Favorite");
stations_listbox_.append_header("User defined");
stations_listbox_.column_at(static_cast<std::size_t>(StationListboxColumns::Name)).width(300u);
stations_listbox_.column_at(static_cast<std::size_t>(StationListboxColumns::Ip)).width(200u);
stations_listbox_.column_at(static_cast<std::size_t>(StationListboxColumns::Favorite)).width(100u);
stations_listbox_.column_at(static_cast<std::size_t>(StationListboxColumns::UserDefined)).width(0u); // 0u to make this column invisibe to the user and so that we can check easly whether it is user defined etc.
stations_listbox_.enable_single(true, false);
populate_listbox();
stations_listbox_.sort_col(static_cast<std::size_t>(StationListboxColumns::Favorite), true);
stations_listbox_.events().mouse_up([this](const nana::arg_mouse& arg)
{
if (!arg.is_left_button() && !stations_listbox_.selected().empty() && !stations_listbox_.cast(arg.pos).empty() && !stations_listbox_.cast(arg.pos).is_category())
pop_stations_listbox_menu();
});
stations_listbox_.events().dbl_click([this](const nana::arg_mouse& arg)
{
if(!stations_listbox_.cast(arg.pos).is_category()) // this condition must be fulfilled because when we click category it selects the last item in it so when we dbl_click category it works just as we would click last item in it
{
set_new_stream();
update_station_label();
update_song_label();
}
});
}
void MainState::update_titles()
{
update_song_label();
while(true)
{
std::this_thread::sleep_for(TIME_TO_CHECK_IF_SONG_CHANGED);
std::lock_guard<std::mutex>{song_title_mutex_};
update_song_label();
}
}
void MainState::update_song_label()
{
current_song_label_.caption(context_.stream_manager.get_song_title());
}
void MainState::update_station_label()
{
if (!stations_listbox_.selected().empty())
{
auto selected_item = stations_listbox_.selected().front();
if (selected_item.cat == static_cast<std::size_t>(StationListboxCategories::Default))
{
auto category_index = static_cast<std::size_t>(StationListboxCategories::Default);
auto column_index = static_cast<std::size_t>(StationListboxColumns::Name);
auto station_category = stations_listbox_.at(category_index);
auto station_name = station_category.at(selected_item.item).text(column_index);
current_station_label_.caption(station_name);
}
else
{
auto category_index = static_cast<std::size_t>(StationListboxCategories::UserDefined);
auto column_index = static_cast<std::size_t>(StationListboxColumns::Name);
auto station_category = stations_listbox_.at(category_index);
auto station_name = station_category.at(selected_item.item).text(column_index);
current_station_label_.caption(station_name);
}
}
}
/**
* \brief Changes favorite value in both listbox and StationsManager::stations_.
*/
void MainState::subscribe_to_station()
{
auto selected_item = stations_listbox_.selected().front();
if (selected_item.cat == static_cast<std::size_t>(StationListboxCategories::Default))
{
auto category_index = static_cast<std::size_t>(StationListboxCategories::Default);
auto column_index = static_cast<std::size_t>(StationListboxColumns::Name);
auto station_category = stations_listbox_.at(category_index);
auto station_name = station_category.at(selected_item.item).text(column_index);
context_.stations_manager.set_favorite(station_name);
populate_listbox();
}
else
{
auto category_index = static_cast<std::size_t>(StationListboxCategories::UserDefined);
auto column_index = static_cast<std::size_t>(StationListboxColumns::Name);
auto station_category = stations_listbox_.at(category_index);
auto station_name = station_category.at(selected_item.item).text(column_index);
context_.stations_manager.set_favorite(station_name);
populate_listbox();
}
}
void MainState::populate_listbox()
{
stations_listbox_.auto_draw(false);
stations_listbox_.clear();
for (const auto& station : context_.stations_manager.get_stations())
{
if (station.user_defined_)
{
stations_listbox_.at(static_cast<nana::drawerbase::listbox::size_type>(StationListboxCategories::UserDefined)).append(station);
}
else
{
stations_listbox_.at(static_cast<nana::drawerbase::listbox::size_type>(StationListboxCategories::Default)).append(station);
}
}
stations_listbox_.sort_col(static_cast<std::size_t>(StationListboxColumns::Favorite), true);
stations_listbox_.auto_draw(true);
}
void MainState::search_stations()
{
subject_.notify(Observer::placeholder, context_, events::Event::SearchingStationsStatus);
std::string string_to_find{};
search_textbox_.getline(0, string_to_find);
stations_listbox_.auto_draw(false);
if (!string_to_find.empty())
{
stations_listbox_.clear();
auto station_names = context_.stations_manager.get_matching_stations(string_to_find);
for (const auto& listed_station : context_.stations_manager.get_stations())
{
for (const auto& name : station_names)
{
if (string_to_lower(listed_station.name_) == name)
{
if (listed_station.user_defined_)
stations_listbox_.at(static_cast<std::size_t>(StationListboxCategories::UserDefined)).append(listed_station);
else
stations_listbox_.at(static_cast<std::size_t>(StationListboxCategories::Default)).append(listed_station);
}
}
}
}
else
{
stations_listbox_.clear();
populate_listbox();
}
stations_listbox_.auto_draw(true);
subject_.notify(Observer::placeholder, context_, events::Event::NormalStatus);
}
void MainState::pop_song_title_menu()
{
auto position = nana::API::cursor_position();
nana::API::calc_window_point(context_.window, position);
song_label_menu_.popup(context_.window, position.x, position.y);
}
void MainState::pop_stations_listbox_menu()
{
auto position = nana::API::cursor_position();
nana::API::calc_window_point(context_.window, position);
listbox_item_menu_.popup(context_.window, position.x, position.y);
}
void MainState::set_new_stream()
{
subject_.notify(Observer::placeholder, context_, events::Event::LoadingStreamStatus);
if (!stations_listbox_.selected().empty())
{
auto selected_item = stations_listbox_.selected().front();
std::string station_name;
if (selected_item.cat == static_cast<std::size_t>(StationListboxCategories::Default))
{
auto category_index = static_cast<std::size_t>(StationListboxCategories::Default);
auto column_index = static_cast<std::size_t>(StationListboxColumns::Name);
auto station_category = stations_listbox_.at(category_index);
station_name = station_category.at(selected_item.item).text(column_index);
}
else
{
auto category_index = static_cast<std::size_t>(StationListboxCategories::UserDefined);
auto column_index = static_cast<std::size_t>(StationListboxColumns::Name);
auto station_category = stations_listbox_.at(category_index);
station_name = station_category.at(selected_item.item).text(column_index);
}
subject_.notify(station_name, context_, events::Event::StreamNew);
subject_.notify(Observer::placeholder, context_, events::Event::StreamPlayingStatus);
}
}
void MainState::delete_station()
{
Station station{};
auto indexes = stations_listbox_.selected().at(0);
stations_listbox_.at(indexes.cat).at(indexes.item).resolve_to(station);
subject_.notify(std::make_any<Station>(station), context_, events::Event::DeleteStation);
populate_listbox();
}
<commit_msg>More code readability improvements.<commit_after>#include "../../include/states/MainState.hpp"
#include "../../include/observers/StreamObserver.hpp"
#include "../../include/observers/StationsObserver.hpp"
#include "../../include/observers/StatusObserver.hpp"
#include "../../include/Constants.hpp"
#include "../../include/Utilities.hpp"
#include <nana/gui/widgets/menubar.hpp>
using namespace constants;
MainState::MainState(StatesManager& manager, Context& context)
: State(manager, context)
, container_(context.window)
, current_song_label_(context.window, "no song is playing")
, current_station_label_(context.window, "no station is playing")
, play_button_(context.window)
, pause_button_(context.window)
, mute_button_(context.window)
, search_textbox_(context.window)
, stations_listbox_(context.window)
, volume_slider_(context.window)
, song_label_menu_()
, listbox_item_menu_()
{
add_observers();
build_interface();
init_contextual_menus();
init_listbox();
run_concurrent_song_name_updater();
}
void MainState::change_visibility(bool visible)
{
container_.field_display("content", visible);
context_.menubar.show();
}
void MainState::add_observers()
{
subject_.attach(std::make_unique<StreamObserver>());
subject_.attach(std::make_unique<StationsObserver>());
subject_.attach(std::make_unique<StatusObserver>());
}
void MainState::run_concurrent_song_name_updater()
{
song_title_updater_ = std::thread(&MainState::update_titles, this);
song_title_updater_.detach();
}
void MainState::build_interface()
{
current_song_label_.events().mouse_up([this](const nana::arg_mouse& arg)
{
if (!arg.is_left_button())
{
pop_song_title_menu();
}
});
play_button_.caption("Play");
play_button_.events().click([this]()
{
subject_.notify(std::make_any<bool>(true), context_, events::Event::StreamPlay);
subject_.notify(Observer::placeholder, context_, events::Event::StreamPlayingStatus);
});
pause_button_.caption("Pause");
pause_button_.events().click([this]()
{
subject_.notify(std::make_any<bool>(true), context_, events::Event::StreamPause);
subject_.notify(Observer::placeholder, context_, events::Event::StreamPausedStatus);
});
mute_button_.caption("Mute");
mute_button_.enable_pushed(true);
mute_button_.events().mouse_up([this]()
{
if(mute_button_.pushed())
{
subject_.notify(std::make_any<unsigned int>(volume_slider_.value()), context_, events::Event::StreamMute);
}
else
{
subject_.notify(std::make_any<unsigned int>(volume_slider_.value()), context_, events::Event::VolumeChanged);
}
});
volume_slider_.scheme().color_vernier = VERNIER_COLOR;
volume_slider_.maximum(100);
volume_slider_.value(volume_float_to_int(context_.stream_manager.get_current_volume()));
volume_slider_.vernier([](unsigned int maximum, unsigned int cursor_value)
{
return std::string(std::to_string(cursor_value) + "/" + std::to_string(maximum));
});
volume_slider_.events().value_changed([this]()
{
if (!mute_button_.pushed())
{
subject_.notify(std::make_any<unsigned int>(volume_slider_.value()), context_, events::Event::VolumeChanged);
}
});
search_textbox_.line_wrapped(true).multi_lines(false).tip_string("Search...");
search_textbox_.events().text_changed([this]()
{
search_stations();
});
container_.div(
"<content vertical margin=[5%,0,0,0]"
"<buttons weight=12% arrange=[10%,10%,10%,10%] gap=1% margin=1%>"
"<labels weight=10% arrange=[49%,48%] gap=1% margin=1% >"
"<misc weight=8% arrange=[25%,72%] gap=1% margin=1%>"
"<listbox margin=[1%,1%,7%,1%]>"
">");
container_.field("buttons") << play_button_ << pause_button_ << mute_button_ ;
container_.field("labels") << current_station_label_ << current_song_label_;
container_.field("misc") << search_textbox_ << volume_slider_;
container_.field("listbox") << stations_listbox_;
container_.collocate();
}
void MainState::init_contextual_menus()
{
song_label_menu_.append("Copy title to clipboard.", [this](auto&)
{
std::string title = current_song_label_.caption();
copy_to_clipboard(title);
});
listbox_item_menu_.append("Play", [this](auto&)
{
set_new_stream();
});
listbox_item_menu_.append("Subscribe", [this](auto&)
{
subscribe_to_station();
});
listbox_item_menu_.append("Delete from list", [this](auto&)
{
delete_station();
});
}
void MainState::init_listbox()
{
stations_listbox_.append("User stations");
stations_listbox_.append("Default stations");
stations_listbox_.append_header("Station's name");
stations_listbox_.append_header("Ip");
stations_listbox_.append_header("Favorite");
stations_listbox_.append_header("User defined");
stations_listbox_.column_at(static_cast<std::size_t>(StationListboxColumns::Name)).width(300u);
stations_listbox_.column_at(static_cast<std::size_t>(StationListboxColumns::Ip)).width(200u);
stations_listbox_.column_at(static_cast<std::size_t>(StationListboxColumns::Favorite)).width(100u);
stations_listbox_.column_at(static_cast<std::size_t>(StationListboxColumns::UserDefined)).width(0u); // 0u to make this column invisibe to the user and so that we can check easly whether it is user defined etc.
stations_listbox_.enable_single(true, false);
populate_listbox();
stations_listbox_.sort_col(static_cast<std::size_t>(StationListboxColumns::Favorite), true);
stations_listbox_.events().mouse_down([this](const nana::arg_mouse& arg)
{
if (!arg.is_left_button() && !stations_listbox_.selected().empty() && !stations_listbox_.cast(arg.pos).empty() && !stations_listbox_.cast(arg.pos).is_category())
pop_stations_listbox_menu();
});
stations_listbox_.events().dbl_click([this](const nana::arg_mouse& arg)
{
if(!stations_listbox_.cast(arg.pos).is_category() && arg.is_left_button()) // this condition must be fulfilled because when we click category it selects the last item in it so when we dbl_click category it works just as we would click last item in it
{
set_new_stream();
update_station_label();
update_song_label();
}
});
}
void MainState::update_titles()
{
update_song_label();
while(true)
{
std::this_thread::sleep_for(TIME_TO_CHECK_IF_SONG_CHANGED);
std::lock_guard<std::mutex>{song_title_mutex_};
update_song_label();
}
}
void MainState::update_song_label()
{
current_song_label_.caption(context_.stream_manager.get_song_title());
}
void MainState::update_station_label()
{
if (!stations_listbox_.selected().empty())
{
auto selected_item = stations_listbox_.selected().front();
if (selected_item.cat == static_cast<std::size_t>(StationListboxCategories::Default))
{
auto category_index = static_cast<std::size_t>(StationListboxCategories::Default);
auto column_index = static_cast<std::size_t>(StationListboxColumns::Name);
auto station_category = stations_listbox_.at(category_index);
auto station_name = station_category.at(selected_item.item).text(column_index);
current_station_label_.caption(station_name);
}
else
{
auto category_index = static_cast<std::size_t>(StationListboxCategories::UserDefined);
auto column_index = static_cast<std::size_t>(StationListboxColumns::Name);
auto station_category = stations_listbox_.at(category_index);
auto station_name = station_category.at(selected_item.item).text(column_index);
current_station_label_.caption(station_name);
}
}
}
/**
* \brief Changes favorite value in both listbox and StationsManager::stations_.
*/
void MainState::subscribe_to_station()
{
auto selected_item = stations_listbox_.selected().front();
if (selected_item.cat == static_cast<std::size_t>(StationListboxCategories::Default))
{
auto category_index = static_cast<std::size_t>(StationListboxCategories::Default);
auto column_index = static_cast<std::size_t>(StationListboxColumns::Name);
auto station_category = stations_listbox_.at(category_index);
auto station_name = station_category.at(selected_item.item).text(column_index);
context_.stations_manager.set_favorite(station_name);
populate_listbox();
}
else
{
auto category_index = static_cast<std::size_t>(StationListboxCategories::UserDefined);
auto column_index = static_cast<std::size_t>(StationListboxColumns::Name);
auto station_category = stations_listbox_.at(category_index);
auto station_name = station_category.at(selected_item.item).text(column_index);
context_.stations_manager.set_favorite(station_name);
populate_listbox();
}
}
void MainState::populate_listbox()
{
stations_listbox_.auto_draw(false);
stations_listbox_.clear();
for (const auto& station : context_.stations_manager.get_stations())
{
if (station.user_defined_)
{
auto category_index = static_cast<std::size_t>(StationListboxCategories::UserDefined);
stations_listbox_.at(category_index).append(station);
}
else
{
auto category_index = static_cast<std::size_t>(StationListboxCategories::Default);
stations_listbox_.at(category_index).append(station);
}
}
stations_listbox_.sort_col(static_cast<std::size_t>(StationListboxColumns::Favorite), true);
stations_listbox_.auto_draw(true);
}
void MainState::search_stations()
{
subject_.notify(Observer::placeholder, context_, events::Event::SearchingStationsStatus);
std::string string_to_find{};
search_textbox_.getline(0, string_to_find);
stations_listbox_.auto_draw(false);
if (!string_to_find.empty())
{
stations_listbox_.clear();
auto station_names = context_.stations_manager.get_matching_stations(string_to_find);
for (const auto& listed_station : context_.stations_manager.get_stations())
{
for (const auto& name : station_names)
{
if (string_to_lower(listed_station.name_) == name)
{
if (listed_station.user_defined_)
{
auto category_index = static_cast<std::size_t>(StationListboxCategories::UserDefined);
stations_listbox_.at(category_index).append(listed_station);
}
else
{
auto category_index = static_cast<std::size_t>(StationListboxCategories::Default);
stations_listbox_.at(category_index).append(listed_station);
}
}
}
}
}
else
{
stations_listbox_.clear();
populate_listbox();
}
stations_listbox_.auto_draw(true);
subject_.notify(Observer::placeholder, context_, events::Event::NormalStatus);
}
void MainState::pop_song_title_menu()
{
auto position = nana::API::cursor_position();
nana::API::calc_window_point(context_.window, position);
song_label_menu_.popup(context_.window, position.x, position.y);
}
void MainState::pop_stations_listbox_menu()
{
auto position = nana::API::cursor_position();
nana::API::calc_window_point(context_.window, position);
listbox_item_menu_.popup(context_.window, position.x, position.y);
}
void MainState::set_new_stream()
{
subject_.notify(Observer::placeholder, context_, events::Event::LoadingStreamStatus);
if (!stations_listbox_.selected().empty())
{
auto selected_item = stations_listbox_.selected().front();
std::string station_name;
if (selected_item.cat == static_cast<std::size_t>(StationListboxCategories::Default))
{
auto category_index = static_cast<std::size_t>(StationListboxCategories::Default);
auto column_index = static_cast<std::size_t>(StationListboxColumns::Name);
auto station_category = stations_listbox_.at(category_index);
station_name = station_category.at(selected_item.item).text(column_index);
}
else
{
auto category_index = static_cast<std::size_t>(StationListboxCategories::UserDefined);
auto column_index = static_cast<std::size_t>(StationListboxColumns::Name);
auto station_category = stations_listbox_.at(category_index);
station_name = station_category.at(selected_item.item).text(column_index);
}
subject_.notify(station_name, context_, events::Event::StreamNew);
subject_.notify(Observer::placeholder, context_, events::Event::StreamPlayingStatus);
}
}
void MainState::delete_station()
{
Station station{};
auto indexes = stations_listbox_.selected().at(0);
stations_listbox_.at(indexes.cat).at(indexes.item).resolve_to(station);
subject_.notify(std::make_any<Station>(station), context_, events::Event::DeleteStation);
populate_listbox();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: View.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2004-07-13 14:14:32 $
*
* 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 SD_VIEW_HXX
#define SD_VIEW_HXX
#ifndef _PRESENTATION_HXX
#include "pres.hxx"
#endif
#ifndef _GEN_HXX //autogen
#include <tools/gen.hxx>
#endif
#ifndef _TRANSFER_HXX //autogen
#include <svtools/transfer.hxx>
#endif
#ifndef _SVX_FMVIEW_HXX
#include <svx/fmview.hxx>
#endif
#ifndef _SVDMARK_HXX //autogen
#include <svx/svdmark.hxx>
#endif
#ifndef _SVDVMARK_HXX //autogen
#include <svx/svdvmark.hxx>
#endif
#ifndef _SVDPAGE_HXX //autogen
#include <svx/svdpage.hxx>
#endif
class SdDrawDocument;
class SdrOle2Obj;
class SdrGrafObj;
class OutputDevice;
class VirtualDevice;
class ImageMap;
class Point;
class Graphic;
class SdrOutliner;
class TransferableDataHelper;
struct StyleRequestData;
namespace sd {
class DrawDocShell;
struct SdNavigatorDropEvent;
class ViewShell;
class Window;
class ViewClipboard;
// -------------------
// - SdViewRedrawRec -
// -------------------
struct SdViewRedrawRec
{
OutputDevice* pOut;
Rectangle aRect;
};
class View : public FmFormView
{
public:
TYPEINFO();
View (
SdDrawDocument* pDrawDoc,
OutputDevice* pOutDev,
ViewShell* pViewSh=NULL);
virtual ~View (void);
void CompleteRedraw( OutputDevice* pOutDev, const Region& rReg, ::sdr::contact::ViewObjectContactRedirector* pRedirector = 0L);
virtual BOOL GetAttributes( SfxItemSet& rTargetSet, BOOL bOnlyHardAttr=FALSE ) const;
virtual BOOL SetAttributes(const SfxItemSet& rSet, BOOL bReplaceAll = FALSE);
virtual void MarkListHasChanged();
virtual void ModelHasChanged();
virtual void SelectAll();
virtual void DoCut(::Window* pWindow=NULL);
virtual void DoCopy(::Window* pWindow=NULL);
virtual void DoPaste(::Window* pWindow=NULL);
virtual void DoConnect(SdrOle2Obj* pOleObj);
virtual BOOL SetStyleSheet(SfxStyleSheet* pStyleSheet, BOOL bDontRemoveHardAttr = FALSE);
virtual void StartDrag( const Point& rStartPos, Window* pWindow );
virtual void DragFinished( sal_Int8 nDropAction );
virtual sal_Int8 AcceptDrop (
const AcceptDropEvent& rEvt,
DropTargetHelper& rTargetHelper,
::sd::Window* pTargetWindow = NULL,
USHORT nPage = SDRPAGE_NOTFOUND,
USHORT nLayer = SDRPAGE_NOTFOUND);
virtual sal_Int8 ExecuteDrop (
const ExecuteDropEvent& rEvt,
DropTargetHelper& rTargetHelper,
::sd::Window* pTargetWindow = NULL,
USHORT nPage = SDRPAGE_NOTFOUND,
USHORT nLayer = SDRPAGE_NOTFOUND);
::com::sun::star::uno::Reference<
::com::sun::star::datatransfer::XTransferable>
CreateClipboardDataObject (::sd::View*, ::Window& rWindow);
::com::sun::star::uno::Reference<
::com::sun::star::datatransfer::XTransferable>
CreateDragDataObject (::sd::View*, ::Window& rWindow,
const Point& rDragPos);
::com::sun::star::uno::Reference<
::com::sun::star::datatransfer::XTransferable>
CreateSelectionDataObject (::sd::View*, ::Window& rWindow);
void UpdateSelectionClipboard( BOOL bForceDeselect );
inline DrawDocShell* GetDocSh (void) const;
inline SdDrawDocument* GetDoc (void) const;
inline ViewShell* GetViewShell (void) const;
BOOL BegTextEdit( SdrObject* pObj, SdrPageView* pPV=NULL, Window* pWin=NULL, BOOL bIsNewObj=FALSE,
SdrOutliner* pGivenOutliner=NULL, OutlinerView* pGivenOutlinerView=NULL,
BOOL bDontDeleteOutliner=FALSE, BOOL bOnlyOneView=FALSE );
SdrEndTextEditKind EndTextEdit(BOOL bDontDeleteReally=FALSE);
BOOL InsertData( const TransferableDataHelper& rDataHelper,
const Point& rPos, sal_Int8& rDnDAction, BOOL bDrag,
ULONG nFormat = 0, USHORT nPage = SDRPAGE_NOTFOUND, USHORT nLayer = SDRLAYER_NOTFOUND );
SdrGrafObj* InsertGraphic( const Graphic& rGraphic,
sal_Int8& rAction, const Point& rPos,
SdrObject* pSelectedObj, ImageMap* pImageMap );
BOOL IsPresObjSelected(BOOL bOnPage=TRUE, BOOL bOnMasterPage=TRUE, BOOL bCheckPresObjListOnly=FALSE, BOOL bCheckLayoutOnly=FALSE) const;
void SetMarkedOriginalSize();
VirtualDevice* CreatePageVDev(USHORT nSdPage, PageKind ePageKind, ULONG nWidthPixel);
void LockRedraw(BOOL bLock);
BOOL IsMorphingAllowed() const;
BOOL IsVectorizeAllowed() const;
virtual SfxStyleSheet* GetStyleSheet() const;
BOOL GetExchangeList( List*& rpExchangeList, List* pBookmarkList, USHORT nType );
virtual void onAccessibilityOptionsChanged();
virtual SdrModel* GetMarkedObjModel() const;
virtual BOOL Paste(const SdrModel& rMod, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0);
protected:
SdDrawDocument* pDoc;
DrawDocShell* pDocSh;
ViewShell* pViewSh;
SdrMarkList* pDragSrcMarkList;
SdrObject* pDropMarkerObj;
SdrViewUserMarker* pDropMarker;
USHORT nDragSrcPgNum;
Point aDropPos;
::std::vector< String > aDropFileVector;
sal_Int8 nAction;
Timer aDropErrorTimer;
Timer aDropInsertFileTimer;
USHORT nLockRedrawSmph;
List* pLockedRedraws;
bool bIsDropAllowed;
DECL_LINK( DropErrorHdl, Timer* );
DECL_LINK( DropInsertFileHdl, Timer* );
DECL_LINK( ExecuteNavigatorDrop, SdNavigatorDropEvent* pSdNavigatorDropEvent );
private:
::std::auto_ptr<ViewClipboard> mpClipboard;
};
DrawDocShell* View::GetDocSh (void) const
{
return pDocSh;
}
SdDrawDocument* View::GetDoc (void) const
{
return pDoc;
}
ViewShell* View::GetViewShell (void) const
{
return pViewSh;
}
} // end of namespace sd
#endif
<commit_msg>INTEGRATION: CWS jmf2 (1.5.14); FILE MERGED 2004/08/03 10:30:29 ka 1.5.14.1: media support for d&d<commit_after>/*************************************************************************
*
* $RCSfile: View.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2004-08-12 09:16:16 $
*
* 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 SD_VIEW_HXX
#define SD_VIEW_HXX
#ifndef _PRESENTATION_HXX
#include "pres.hxx"
#endif
#ifndef _GEN_HXX //autogen
#include <tools/gen.hxx>
#endif
#ifndef _TRANSFER_HXX //autogen
#include <svtools/transfer.hxx>
#endif
#ifndef _SVX_FMVIEW_HXX
#include <svx/fmview.hxx>
#endif
#ifndef _SVDMARK_HXX //autogen
#include <svx/svdmark.hxx>
#endif
#ifndef _SVDVMARK_HXX //autogen
#include <svx/svdvmark.hxx>
#endif
#ifndef _SVDPAGE_HXX //autogen
#include <svx/svdpage.hxx>
#endif
class SdDrawDocument;
class SdrOle2Obj;
class SdrGrafObj;
class SdrMediaObj;
class OutputDevice;
class VirtualDevice;
class ImageMap;
class Point;
class Graphic;
class SdrOutliner;
class TransferableDataHelper;
struct StyleRequestData;
namespace sd {
class DrawDocShell;
struct SdNavigatorDropEvent;
class ViewShell;
class Window;
class ViewClipboard;
// -------------------
// - SdViewRedrawRec -
// -------------------
struct SdViewRedrawRec
{
OutputDevice* pOut;
Rectangle aRect;
};
class View : public FmFormView
{
public:
TYPEINFO();
View (
SdDrawDocument* pDrawDoc,
OutputDevice* pOutDev,
ViewShell* pViewSh=NULL);
virtual ~View (void);
void CompleteRedraw( OutputDevice* pOutDev, const Region& rReg, ::sdr::contact::ViewObjectContactRedirector* pRedirector = 0L);
virtual BOOL GetAttributes( SfxItemSet& rTargetSet, BOOL bOnlyHardAttr=FALSE ) const;
virtual BOOL SetAttributes(const SfxItemSet& rSet, BOOL bReplaceAll = FALSE);
virtual void MarkListHasChanged();
virtual void ModelHasChanged();
virtual void SelectAll();
virtual void DoCut(::Window* pWindow=NULL);
virtual void DoCopy(::Window* pWindow=NULL);
virtual void DoPaste(::Window* pWindow=NULL);
virtual void DoConnect(SdrOle2Obj* pOleObj);
virtual BOOL SetStyleSheet(SfxStyleSheet* pStyleSheet, BOOL bDontRemoveHardAttr = FALSE);
virtual void StartDrag( const Point& rStartPos, Window* pWindow );
virtual void DragFinished( sal_Int8 nDropAction );
virtual sal_Int8 AcceptDrop (
const AcceptDropEvent& rEvt,
DropTargetHelper& rTargetHelper,
::sd::Window* pTargetWindow = NULL,
USHORT nPage = SDRPAGE_NOTFOUND,
USHORT nLayer = SDRPAGE_NOTFOUND);
virtual sal_Int8 ExecuteDrop (
const ExecuteDropEvent& rEvt,
DropTargetHelper& rTargetHelper,
::sd::Window* pTargetWindow = NULL,
USHORT nPage = SDRPAGE_NOTFOUND,
USHORT nLayer = SDRPAGE_NOTFOUND);
::com::sun::star::uno::Reference<
::com::sun::star::datatransfer::XTransferable>
CreateClipboardDataObject (::sd::View*, ::Window& rWindow);
::com::sun::star::uno::Reference<
::com::sun::star::datatransfer::XTransferable>
CreateDragDataObject (::sd::View*, ::Window& rWindow,
const Point& rDragPos);
::com::sun::star::uno::Reference<
::com::sun::star::datatransfer::XTransferable>
CreateSelectionDataObject (::sd::View*, ::Window& rWindow);
void UpdateSelectionClipboard( BOOL bForceDeselect );
inline DrawDocShell* GetDocSh (void) const;
inline SdDrawDocument* GetDoc (void) const;
inline ViewShell* GetViewShell (void) const;
BOOL BegTextEdit( SdrObject* pObj, SdrPageView* pPV=NULL, Window* pWin=NULL, BOOL bIsNewObj=FALSE,
SdrOutliner* pGivenOutliner=NULL, OutlinerView* pGivenOutlinerView=NULL,
BOOL bDontDeleteOutliner=FALSE, BOOL bOnlyOneView=FALSE );
SdrEndTextEditKind EndTextEdit(BOOL bDontDeleteReally=FALSE);
BOOL InsertData( const TransferableDataHelper& rDataHelper,
const Point& rPos, sal_Int8& rDnDAction, BOOL bDrag,
ULONG nFormat = 0, USHORT nPage = SDRPAGE_NOTFOUND, USHORT nLayer = SDRLAYER_NOTFOUND );
SdrGrafObj* InsertGraphic( const Graphic& rGraphic,
sal_Int8& rAction, const Point& rPos,
SdrObject* pSelectedObj, ImageMap* pImageMap );
SdrMediaObj* InsertMediaURL( const rtl::OUString& rMediaURL, sal_Int8& rAction,
const Point& rPos, const Size& rSize );
BOOL IsPresObjSelected(BOOL bOnPage=TRUE, BOOL bOnMasterPage=TRUE, BOOL bCheckPresObjListOnly=FALSE, BOOL bCheckLayoutOnly=FALSE) const;
void SetMarkedOriginalSize();
VirtualDevice* CreatePageVDev(USHORT nSdPage, PageKind ePageKind, ULONG nWidthPixel);
void LockRedraw(BOOL bLock);
BOOL IsMorphingAllowed() const;
BOOL IsVectorizeAllowed() const;
virtual SfxStyleSheet* GetStyleSheet() const;
BOOL GetExchangeList( List*& rpExchangeList, List* pBookmarkList, USHORT nType );
virtual void onAccessibilityOptionsChanged();
virtual SdrModel* GetMarkedObjModel() const;
virtual BOOL Paste(const SdrModel& rMod, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0);
protected:
SdDrawDocument* pDoc;
DrawDocShell* pDocSh;
ViewShell* pViewSh;
SdrMarkList* pDragSrcMarkList;
SdrObject* pDropMarkerObj;
SdrViewUserMarker* pDropMarker;
USHORT nDragSrcPgNum;
Point aDropPos;
::std::vector< String > aDropFileVector;
sal_Int8 nAction;
Timer aDropErrorTimer;
Timer aDropInsertFileTimer;
USHORT nLockRedrawSmph;
List* pLockedRedraws;
bool bIsDropAllowed;
DECL_LINK( DropErrorHdl, Timer* );
DECL_LINK( DropInsertFileHdl, Timer* );
DECL_LINK( ExecuteNavigatorDrop, SdNavigatorDropEvent* pSdNavigatorDropEvent );
private:
::std::auto_ptr<ViewClipboard> mpClipboard;
};
DrawDocShell* View::GetDocSh (void) const
{
return pDocSh;
}
SdDrawDocument* View::GetDoc (void) const
{
return pDoc;
}
ViewShell* View::GetViewShell (void) const
{
return pViewSh;
}
} // end of namespace sd
#endif
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <functional>
#include <string>
#include <tuple>
#include <vector>
namespace K3
{
using namespace std;
template <typename Elem>
class ListDS : public StlDS<Elem, std::list> {
typedef StlDS<Elem, std::list> super;
public:
// Constructors
ListDS(Engine * eng) : StlDS<Elem, std::list>(eng) {}
template<typename Iterator>
ListDS(Engine * eng, Iterator start, Iterator finish)
: StlDS<Elem, std::list>(eng, start, finish) {}
ListDS(const ListDS& other) : StlDS<Elem,std::list>(other) {}
ListDS(StlDS<Elem,std::list> other) : StlDS<Elem,std::list>(other) {}
ListDS(std::list<Elem> container) : StlDS<Elem, std::list>(container) {}
// Need to convert from StlDS to ListDS
template<typename NewElem>
ListDS<NewElem> map(std::function<NewElem(Elem)> f) {
StlDS<NewElem, std::list> s = super::map(f);
return ListDS<NewElem>(s);
}
ListDS filter(std::function<bool(Elem)> pred) {
super s = super::filter(pred);
return ListDS(s);
}
tuple< ListDS, ListDS > split() {
tuple<super, super> tup = super::split();
ListDS ds1 = ListDS(get<0>(tup));
ListDS ds2 = ListDS(get<1>(tup));
return std::make_tuple(ds1, ds2);
}
ListDS combine(ListDS other) {
super s = super::combine(other);
return ListDS(s);
}
ListDS sort(std::function<int(Elem, Elem)> comp) {
std::list<Elem> l = std::list<Elem>(super::getContainer());
std::function<bool(Elem,Elem)> f = [&] (Elem a, Elem b) { return comp(a,b) < 0; };
l.sort(f);
return ListDS(l);
}
};
}
<commit_msg>Add necessary include and header guard to ListDS.hpp<commit_after>#ifndef K3_RUNTIME_DATASPACE_LISTDS_H
#define K3_RUNTIME_DATASPACE_LISTDS_H
#include <algorithm>
#include <functional>
#include <string>
#include <tuple>
#include <vector>
#include <dataspace/StlDS.hpp>
namespace K3
{
using namespace std;
template <typename Elem>
class ListDS : public StlDS<Elem, std::list> {
typedef StlDS<Elem, std::list> super;
public:
// Constructors
ListDS(Engine * eng) : StlDS<Elem, std::list>(eng) {}
template<typename Iterator>
ListDS(Engine * eng, Iterator start, Iterator finish)
: StlDS<Elem, std::list>(eng, start, finish) {}
ListDS(const ListDS& other) : StlDS<Elem,std::list>(other) {}
ListDS(StlDS<Elem,std::list> other) : StlDS<Elem,std::list>(other) {}
ListDS(std::list<Elem> container) : StlDS<Elem, std::list>(container) {}
// Need to convert from StlDS to ListDS
template<typename NewElem>
ListDS<NewElem> map(std::function<NewElem(Elem)> f) {
StlDS<NewElem, std::list> s = super::map(f);
return ListDS<NewElem>(s);
}
ListDS filter(std::function<bool(Elem)> pred) {
super s = super::filter(pred);
return ListDS(s);
}
tuple< ListDS, ListDS > split() {
tuple<super, super> tup = super::split();
ListDS ds1 = ListDS(get<0>(tup));
ListDS ds2 = ListDS(get<1>(tup));
return std::make_tuple(ds1, ds2);
}
ListDS combine(ListDS other) {
super s = super::combine(other);
return ListDS(s);
}
ListDS sort(std::function<int(Elem, Elem)> comp) {
std::list<Elem> l = std::list<Elem>(super::getContainer());
std::function<bool(Elem,Elem)> f = [&] (Elem a, Elem b) { return comp(a,b) < 0; };
l.sort(f);
return ListDS(l);
}
};
}
#endif // K3_RUNTIME_DATASPACE_LISTDS_H
<|endoftext|>
|
<commit_before>#include "ClientAuthOperation.hpp"
#include "AccountStorage.hpp"
#include "CAppInformation.hpp"
#include "ClientBackend.hpp"
#include "ClientConnection.hpp"
#include "ClientRpcLayer.hpp"
#include "ClientRpcAuthLayer.hpp"
#include "ClientRpcAccountLayer.hpp"
#include "PendingRpcOperation.hpp"
#include "Utils.hpp"
#include "RpcError.hpp"
#ifdef DEVELOPER_BUILD
#include "TLTypesDebug.hpp"
#endif
#include <QLoggingCategory>
namespace Telegram {
namespace Client {
// Explicit templates instantiation to suppress compilation warnings
template <>
bool BaseRpcLayerExtension::processReply(PendingRpcOperation *operation, TLAccountPassword *output);
template <>
bool BaseRpcLayerExtension::processReply(PendingRpcOperation *operation, TLAuthAuthorization *output);
template <>
bool BaseRpcLayerExtension::processReply(PendingRpcOperation *operation, TLAuthSentCode *output);
AuthOperation::AuthOperation(QObject *parent) :
PendingOperation(parent)
{
}
AuthOperation::AuthOperation(Backend *backend) :
PendingOperation(backend),
m_backend(backend)
{
}
void AuthOperation::setBackend(Backend *backend)
{
m_backend = backend;
}
void AuthOperation::setRunMethod(AuthOperation::RunMethod method)
{
m_runMethod = method;
}
void AuthOperation::setPhoneNumber(const QString &phoneNumber)
{
m_phoneNumber = phoneNumber;
}
void AuthOperation::start()
{
if (m_runMethod) {
callMember<>(this, m_runMethod);
}
}
void AuthOperation::abort()
{
qWarning() << Q_FUNC_INFO << "STUB";
}
PendingOperation *AuthOperation::requestAuthCode()
{
const CAppInformation *appInfo = m_backend->m_appInformation;
if (!appInfo) {
const QString text = QStringLiteral("Unable to request auth code, because the application information is not set");
return PendingOperation::failOperation({{QStringLiteral("text"), text}});
}
if (phoneNumber().isEmpty()) {
emit phoneNumberRequired();
return nullptr;
}
AuthRpcLayer::PendingAuthSentCode *requestCodeOperation = m_backend->authLayer()->sendCode(phoneNumber(), appInfo->appId(), appInfo->appHash());
qDebug() << Q_FUNC_INFO << "requestPhoneCode" << Telegram::Utils::maskPhoneNumber(phoneNumber())
<< "on dc" << Connection::fromOperation(requestCodeOperation)->dcOption().id;
connect(requestCodeOperation, &PendingOperation::finished, this, [this, requestCodeOperation] {
this->onRequestAuthCodeFinished(requestCodeOperation);
});
return requestCodeOperation;
}
PendingOperation *AuthOperation::submitAuthCode(const QString &code)
{
if (m_authCodeHash.isEmpty()) {
const QString text = QStringLiteral("Unable to submit auth code without a code hash");
qWarning() << Q_FUNC_INFO << text;
return PendingOperation::failOperation({{QStringLiteral("text"), text}});
}
PendingRpcOperation *sendCodeOperation = authLayer()->signIn(phoneNumber(), m_authCodeHash, code);
connect(sendCodeOperation, &PendingRpcOperation::finished, this, &AuthOperation::onSignInFinished);
return sendCodeOperation;
}
PendingOperation *AuthOperation::getPassword()
{
PendingRpcOperation *passwordRequest = accountLayer()->getPassword();
connect(passwordRequest, &PendingRpcOperation::finished, this, &AuthOperation::onPasswordRequestFinished);
return passwordRequest;
}
PendingOperation *AuthOperation::submitPassword(const QString &password)
{
if (m_passwordCurrentSalt.isEmpty()) {
const QString text = QStringLiteral("Unable to submit auth password (password salt is missing)");
return PendingOperation::failOperation({{QStringLiteral("text"), text}});
}
const QByteArray pwdData = m_passwordCurrentSalt + password.toUtf8() + m_passwordCurrentSalt;
const QByteArray pwdHash = Utils::sha256(pwdData);
qDebug() << Q_FUNC_INFO << "slt:" << m_passwordCurrentSalt.toHex();
qDebug() << Q_FUNC_INFO << "pwd:" << pwdHash.toHex();
PendingRpcOperation *sendPasswordOperation = authLayer()->checkPassword(pwdHash);
connect(sendPasswordOperation, &PendingRpcOperation::finished, this, &AuthOperation::onCheckPasswordFinished);
return sendPasswordOperation;
}
void AuthOperation::submitPhoneNumber(const QString &phoneNumber)
{
setPhoneNumber(phoneNumber);
if (!isFinished()) {
start();
}
}
void AuthOperation::requestCall()
{
qWarning() << Q_FUNC_INFO << "STUB";
}
void AuthOperation::requestSms()
{
qWarning() << Q_FUNC_INFO << "STUB";
}
void AuthOperation::recovery()
{
qWarning() << Q_FUNC_INFO << "STUB";
}
void AuthOperation::setWantedDc(quint32 dcId)
{
m_backend->setDcForLayer(ConnectionSpec(dcId), authLayer());
m_backend->setDcForLayer(ConnectionSpec(dcId), accountLayer());
}
void AuthOperation::setPasswordCurrentSalt(const QByteArray &salt)
{
m_passwordCurrentSalt = salt;
}
void AuthOperation::setPasswordHint(const QString &hint)
{
if (m_passwordHint == hint) {
return;
}
m_passwordHint = hint;
emit passwordHintChanged(hint);
}
AccountRpcLayer *AuthOperation::accountLayer() const
{
return m_backend->accountLayer();
}
AuthRpcLayer *AuthOperation::authLayer() const
{
return m_backend->authLayer();
}
void AuthOperation::onRequestAuthCodeFinished(AuthRpcLayer::PendingAuthSentCode *operation)
{
if (operation->rpcError() && operation->rpcError()->type == RpcError::SeeOther) {
setWantedDc(operation->rpcError()->argument);
m_backend->processSeeOthers(operation);
return;
}
if (!operation->isSucceeded()) {
setDelayedFinishedWithError(operation->errorDetails());
return;
}
TLAuthSentCode result;
operation->getResult(&result);
qDebug() << Q_FUNC_INFO << result.tlType << result.phoneCodeHash;
if (result.isValid()) {
m_authCodeHash = result.phoneCodeHash;
emit authCodeRequired();
}
}
void AuthOperation::onSignInFinished(PendingRpcOperation *operation)
{
if (operation->rpcError()) {
const RpcError *error = operation->rpcError();
if (error->reason == RpcError::SessionPasswordNeeded) {
emit passwordRequired();
return;
}
}
if (!operation->isSucceeded()) {
setDelayedFinishedWithError(operation->errorDetails());
return;
}
TLAuthAuthorization result;
authLayer()->processReply(operation, &result);
onGotAuthorization(operation, result);
}
void AuthOperation::onPasswordRequestFinished(PendingRpcOperation *operation)
{
if (!operation->isSucceeded()) {
setDelayedFinishedWithError(operation->errorDetails());
return;
}
TLAccountPassword result;
authLayer()->processReply(operation, &result);
qDebug() << Q_FUNC_INFO << "Password data:" << result.currentSalt << result.newSalt << result.hasRecovery << result.hint;
setPasswordCurrentSalt(result.currentSalt);
setPasswordHint(result.hint);
}
void AuthOperation::onCheckPasswordFinished(PendingRpcOperation *operation)
{
if (operation->rpcError()) {
const RpcError *error = operation->rpcError();
if (error->reason == RpcError::PasswordHashInvalid) {
emit passwordCheckFailed();
return;
}
}
if (!operation->isSucceeded()) {
setDelayedFinishedWithError(operation->errorDetails());
return;
}
TLAuthAuthorization result;
authLayer()->processReply(operation, &result);
onGotAuthorization(operation, result);
}
void AuthOperation::onGotAuthorization(PendingRpcOperation *operation, const TLAuthAuthorization &authorization)
{
qDebug() << authorization.user.phone << authorization.user.firstName << authorization.user.lastName;
AccountStorage *storage = m_backend->accountStorage();
storage->setPhoneNumber(authorization.user.phone);
if (storage->accountIdentifier().isEmpty()) {
storage->setAccountIdentifier(authorization.user.phone);
}
Connection *conn = Connection::fromOperation(operation);
m_backend->setMainConnection(conn);
conn->setStatus(BaseConnection::Status::Signed, BaseConnection::StatusReason::Remote);
setFinished();
}
} // Client
} // Telegram namespace
<commit_msg>ClientAuthOperation: Use logging categories<commit_after>#include "ClientAuthOperation.hpp"
#include "AccountStorage.hpp"
#include "CAppInformation.hpp"
#include "ClientBackend.hpp"
#include "ClientConnection.hpp"
#include "ClientRpcLayer.hpp"
#include "ClientRpcAuthLayer.hpp"
#include "ClientRpcAccountLayer.hpp"
#include "PendingRpcOperation.hpp"
#include "Utils.hpp"
#include "RpcError.hpp"
#ifdef DEVELOPER_BUILD
#include "TLTypesDebug.hpp"
#endif
#include <QLoggingCategory>
Q_LOGGING_CATEGORY(c_loggingClientAuthOperation, "telegram.client.auth.operation", QtDebugMsg)
namespace Telegram {
namespace Client {
// Explicit templates instantiation to suppress compilation warnings
template <>
bool BaseRpcLayerExtension::processReply(PendingRpcOperation *operation, TLAccountPassword *output);
template <>
bool BaseRpcLayerExtension::processReply(PendingRpcOperation *operation, TLAuthAuthorization *output);
template <>
bool BaseRpcLayerExtension::processReply(PendingRpcOperation *operation, TLAuthSentCode *output);
AuthOperation::AuthOperation(QObject *parent) :
PendingOperation(parent)
{
}
AuthOperation::AuthOperation(Backend *backend) :
PendingOperation(backend),
m_backend(backend)
{
}
void AuthOperation::setBackend(Backend *backend)
{
m_backend = backend;
}
void AuthOperation::setRunMethod(AuthOperation::RunMethod method)
{
m_runMethod = method;
}
void AuthOperation::setPhoneNumber(const QString &phoneNumber)
{
m_phoneNumber = phoneNumber;
}
void AuthOperation::start()
{
if (m_runMethod) {
callMember<>(this, m_runMethod);
}
}
void AuthOperation::abort()
{
qCWarning(c_loggingClientAuthOperation) << Q_FUNC_INFO << "STUB";
}
PendingOperation *AuthOperation::requestAuthCode()
{
qCDebug(c_loggingClientAuthOperation) << Q_FUNC_INFO;
const CAppInformation *appInfo = m_backend->m_appInformation;
if (!appInfo) {
const QString text = QStringLiteral("Unable to request auth code, "
"because the application information is not set");
return PendingOperation::failOperation(text, this);
}
if (phoneNumber().isEmpty()) {
emit phoneNumberRequired();
return nullptr;
}
AuthRpcLayer::PendingAuthSentCode *requestCodeOperation
= m_backend->authLayer()->sendCode(phoneNumber(), appInfo->appId(), appInfo->appHash());
qCDebug(c_loggingClientAuthOperation) << Q_FUNC_INFO
<< "requestPhoneCode"
<< Telegram::Utils::maskPhoneNumber(phoneNumber())
<< "on dc" << Connection::fromOperation(requestCodeOperation)->dcOption().id;
connect(requestCodeOperation, &PendingOperation::finished, this, [this, requestCodeOperation] {
this->onRequestAuthCodeFinished(requestCodeOperation);
});
return requestCodeOperation;
}
PendingOperation *AuthOperation::submitAuthCode(const QString &code)
{
if (m_authCodeHash.isEmpty()) {
const QString text = QStringLiteral("Unable to submit auth code without a code hash");
qCWarning(c_loggingClientAuthOperation) << Q_FUNC_INFO << text;
return PendingOperation::failOperation({{QStringLiteral("text"), text}});
}
PendingRpcOperation *sendCodeOperation = authLayer()->signIn(phoneNumber(), m_authCodeHash, code);
connect(sendCodeOperation, &PendingRpcOperation::finished, this, &AuthOperation::onSignInFinished);
return sendCodeOperation;
}
PendingOperation *AuthOperation::getPassword()
{
PendingRpcOperation *passwordRequest = accountLayer()->getPassword();
connect(passwordRequest, &PendingRpcOperation::finished, this, &AuthOperation::onPasswordRequestFinished);
return passwordRequest;
}
PendingOperation *AuthOperation::submitPassword(const QString &password)
{
if (m_passwordCurrentSalt.isEmpty()) {
const QString text = QStringLiteral("Unable to submit auth password (password salt is missing)");
return PendingOperation::failOperation({{QStringLiteral("text"), text}});
}
const QByteArray pwdData = m_passwordCurrentSalt + password.toUtf8() + m_passwordCurrentSalt;
const QByteArray pwdHash = Utils::sha256(pwdData);
qCDebug(c_loggingClientAuthOperation) << Q_FUNC_INFO << "slt:" << m_passwordCurrentSalt.toHex();
qCDebug(c_loggingClientAuthOperation) << Q_FUNC_INFO << "pwd:" << pwdHash.toHex();
PendingRpcOperation *sendPasswordOperation = authLayer()->checkPassword(pwdHash);
connect(sendPasswordOperation, &PendingRpcOperation::finished, this, &AuthOperation::onCheckPasswordFinished);
return sendPasswordOperation;
}
void AuthOperation::submitPhoneNumber(const QString &phoneNumber)
{
setPhoneNumber(phoneNumber);
if (!isFinished()) {
start();
}
}
void AuthOperation::requestCall()
{
qCWarning(c_loggingClientAuthOperation) << Q_FUNC_INFO << "STUB";
}
void AuthOperation::requestSms()
{
qCWarning(c_loggingClientAuthOperation) << Q_FUNC_INFO << "STUB";
}
void AuthOperation::recovery()
{
qCWarning(c_loggingClientAuthOperation) << Q_FUNC_INFO << "STUB";
}
void AuthOperation::setWantedDc(quint32 dcId)
{
m_backend->setDcForLayer(ConnectionSpec(dcId), authLayer());
m_backend->setDcForLayer(ConnectionSpec(dcId), accountLayer());
}
void AuthOperation::setPasswordCurrentSalt(const QByteArray &salt)
{
m_passwordCurrentSalt = salt;
}
void AuthOperation::setPasswordHint(const QString &hint)
{
if (m_passwordHint == hint) {
return;
}
m_passwordHint = hint;
emit passwordHintChanged(hint);
}
AccountRpcLayer *AuthOperation::accountLayer() const
{
return m_backend->accountLayer();
}
AuthRpcLayer *AuthOperation::authLayer() const
{
return m_backend->authLayer();
}
void AuthOperation::onRequestAuthCodeFinished(AuthRpcLayer::PendingAuthSentCode *operation)
{
if (operation->rpcError() && operation->rpcError()->type == RpcError::SeeOther) {
setWantedDc(operation->rpcError()->argument);
m_backend->processSeeOthers(operation);
return;
}
if (!operation->isSucceeded()) {
setDelayedFinishedWithError(operation->errorDetails());
return;
}
TLAuthSentCode result;
operation->getResult(&result);
qCDebug(c_loggingClientAuthOperation) << Q_FUNC_INFO << result.tlType << result.phoneCodeHash;
if (result.isValid()) {
m_authCodeHash = result.phoneCodeHash;
emit authCodeRequired();
}
}
void AuthOperation::onSignInFinished(PendingRpcOperation *operation)
{
if (operation->rpcError()) {
const RpcError *error = operation->rpcError();
if (error->reason == RpcError::SessionPasswordNeeded) {
emit passwordRequired();
return;
}
}
if (!operation->isSucceeded()) {
setDelayedFinishedWithError(operation->errorDetails());
return;
}
TLAuthAuthorization result;
authLayer()->processReply(operation, &result);
onGotAuthorization(operation, result);
}
void AuthOperation::onPasswordRequestFinished(PendingRpcOperation *operation)
{
if (!operation->isSucceeded()) {
setDelayedFinishedWithError(operation->errorDetails());
return;
}
TLAccountPassword result;
authLayer()->processReply(operation, &result);
#ifdef DEVELOPER_BUILD
qCDebug(c_loggingClientAuthOperation) << Q_FUNC_INFO << result;
#endif
setPasswordCurrentSalt(result.currentSalt);
setPasswordHint(result.hint);
}
void AuthOperation::onCheckPasswordFinished(PendingRpcOperation *operation)
{
if (operation->rpcError()) {
const RpcError *error = operation->rpcError();
if (error->reason == RpcError::PasswordHashInvalid) {
emit passwordCheckFailed();
return;
}
}
if (!operation->isSucceeded()) {
setDelayedFinishedWithError(operation->errorDetails());
return;
}
TLAuthAuthorization result;
authLayer()->processReply(operation, &result);
onGotAuthorization(operation, result);
}
void AuthOperation::onGotAuthorization(PendingRpcOperation *operation, const TLAuthAuthorization &authorization)
{
qCDebug(c_loggingClientAuthOperation) << authorization.user.phone
<< authorization.user.firstName
<< authorization.user.lastName;
AccountStorage *storage = m_backend->accountStorage();
storage->setPhoneNumber(authorization.user.phone);
if (storage->accountIdentifier().isEmpty()) {
storage->setAccountIdentifier(authorization.user.phone);
}
Connection *conn = Connection::fromOperation(operation);
m_backend->setMainConnection(conn);
conn->setStatus(BaseConnection::Status::Signed, BaseConnection::StatusReason::Remote);
setFinished();
}
} // Client
} // Telegram namespace
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "system_wrappers/interface/cpu_wrapper.h"
#include "gtest/gtest.h"
#include "system_wrappers/interface/cpu_info.h"
#include "system_wrappers/interface/event_wrapper.h"
#include "system_wrappers/interface/trace.h"
using webrtc::CpuInfo;
using webrtc::CpuWrapper;
using webrtc::Trace;
// Only utilizes some of the cpu_info.h and cpu_wrapper.h code. Does not verify
// anything except that it doesn't crash.
// TODO(kjellander): Improve this test so it verifies the implementation
// executes as expected.
TEST(CpuWrapperTest, Usage) {
Trace::CreateTrace();
Trace::SetTraceFile("cpu_wrapper_unittest.txt");
Trace::SetLevelFilter(webrtc::kTraceAll);
printf("Number of cores detected:%u\n", CpuInfo::DetectNumberOfCores());
CpuWrapper* cpu = CpuWrapper::CreateCpu();
ASSERT_TRUE(cpu != NULL);
webrtc::EventWrapper* sleep_event = webrtc::EventWrapper::Create();
ASSERT_TRUE(sleep_event != NULL);
int num_iterations = 0;
WebRtc_UWord32 num_cores = 0;
WebRtc_UWord32* cores = NULL;
bool cpu_usage_available = cpu->CpuUsageMultiCore(num_cores, cores) != -1;
// Initializing the CPU measurements may take a couple of seconds on Windows.
// Since the initialization is lazy we need to wait until it is completed.
// Should not take more than 10000 ms.
while (cpu_usage_available && (++num_iterations < 10000)) {
if (cores != NULL) {
ASSERT_GT(num_cores, 0);
break;
}
sleep_event->Wait(1);
cpu_usage_available = cpu->CpuUsageMultiCore(num_cores, cores) != -1;
}
ASSERT_TRUE(cpu_usage_available);
const WebRtc_Word32 total = cpu->CpuUsageMultiCore(num_cores, cores);
ASSERT_TRUE(cores != NULL);
EXPECT_GT(num_cores, 0);
EXPECT_GE(total, 0);
printf("\nNumCores:%d\n", num_cores);
printf("Total cpu:%d\n", total);
for (WebRtc_UWord32 i = 0; i < num_cores; i++) {
printf("Core:%u CPU:%u \n", i, cores[i]);
EXPECT_LE(cores[i], total);
}
delete cpu;
Trace::ReturnTrace();
};
<commit_msg>Fixes linux build error introduced in r980. Review URL: http://webrtc-codereview.appspot.com/279012<commit_after>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "system_wrappers/interface/cpu_wrapper.h"
#include "gtest/gtest.h"
#include "system_wrappers/interface/cpu_info.h"
#include "system_wrappers/interface/event_wrapper.h"
#include "system_wrappers/interface/trace.h"
using webrtc::CpuInfo;
using webrtc::CpuWrapper;
using webrtc::Trace;
// Only utilizes some of the cpu_info.h and cpu_wrapper.h code. Does not verify
// anything except that it doesn't crash.
// TODO(kjellander): Improve this test so it verifies the implementation
// executes as expected.
TEST(CpuWrapperTest, Usage) {
Trace::CreateTrace();
Trace::SetTraceFile("cpu_wrapper_unittest.txt");
Trace::SetLevelFilter(webrtc::kTraceAll);
printf("Number of cores detected:%u\n", CpuInfo::DetectNumberOfCores());
CpuWrapper* cpu = CpuWrapper::CreateCpu();
ASSERT_TRUE(cpu != NULL);
webrtc::EventWrapper* sleep_event = webrtc::EventWrapper::Create();
ASSERT_TRUE(sleep_event != NULL);
int num_iterations = 0;
WebRtc_UWord32 num_cores = 0;
WebRtc_UWord32* cores = NULL;
bool cpu_usage_available = cpu->CpuUsageMultiCore(num_cores, cores) != -1;
// Initializing the CPU measurements may take a couple of seconds on Windows.
// Since the initialization is lazy we need to wait until it is completed.
// Should not take more than 10000 ms.
while (cpu_usage_available && (++num_iterations < 10000)) {
if (cores != NULL) {
ASSERT_GT(num_cores, 0u);
break;
}
sleep_event->Wait(1);
cpu_usage_available = cpu->CpuUsageMultiCore(num_cores, cores) != -1;
}
ASSERT_TRUE(cpu_usage_available);
const WebRtc_Word32 total = cpu->CpuUsageMultiCore(num_cores, cores);
ASSERT_TRUE(cores != NULL);
EXPECT_GT(num_cores, 0u);
EXPECT_GE(total, 0);
printf("\nNumCores:%d\n", num_cores);
printf("Total cpu:%d\n", total);
for (WebRtc_UWord32 i = 0; i < num_cores; i++) {
printf("Core:%u CPU:%u \n", i, cores[i]);
EXPECT_LE(cores[i], static_cast<WebRtc_UWord32> (total));
}
delete cpu;
Trace::ReturnTrace();
};
<|endoftext|>
|
<commit_before>#ifndef MJOLNIR_UTIL_GET_TOML_VALUE
#define MJOLNIR_UTIL_GET_TOML_VALUE
#include <extlib/toml/toml.hpp>
#include <mjolnir/util/type_traits.hpp>
#include <mjolnir/util/throw_exception.hpp>
#include <string>
#include <stdexcept>
namespace mjolnir
{
inline toml::value const&
toml_value_at(const toml::Table& tab, const std::string& key,
const std::string& tablename)
{
try
{
return tab.at(key);
}
catch(const std::out_of_range& oor)
{
throw_exception<std::runtime_error>(
"mjolnir: while reading toml file: key(", key,
") in table(", tablename, ") missing");
}
}
// one of the toml values. needs no conversion. so it can return a reference.
template<typename T, typename std::enable_if<disjunction<
std::is_same<T, toml::Boolean >,
std::is_same<T, toml::Integer >,
std::is_same<T, toml::Float >,
std::is_same<T, toml::String >,
std::is_same<T, toml::Datetime>,
std::is_same<T, toml::Array >,
std::is_same<T, toml::Table >
>::value, std::nullptr_t>::type = nullptr>
T const& get_toml_value(const toml::Table& tab, const std::string& key,
const std::string& tablename)
{
try
{
return tab.at(key).cast<toml::value_traits<T>::type_index>();
}
catch(const std::out_of_range& oor)
{
throw_exception<std::runtime_error>(
"mjolnir: while reading toml file: key(", key,
") in table(", tablename, ") missing");
}
catch(const toml::type_error& tte)
{
throw_exception<std::runtime_error>(
"mjolnir: while reading toml file: key(", key,
") in table(", tablename, ") has type `",
tab.at(key).type(), "`, expected `",
toml::value_traits<T>::type_index, "`.");
}
}
// none of the toml values. needs conversion.
template<typename T, typename std::enable_if<conjunction<
negation<std::is_same<T, toml::Boolean >>,
negation<std::is_same<T, toml::Integer >>,
negation<std::is_same<T, toml::Float >>,
negation<std::is_same<T, toml::String >>,
negation<std::is_same<T, toml::Datetime>>,
negation<std::is_same<T, toml::Array >>,
negation<std::is_same<T, toml::Table >>
>::value, std::nullptr_t>::type = nullptr>
T get_toml_value(const toml::Table& tab, const std::string& key,
const std::string& tablename)
{
try
{
return toml::get<T>(tab.at(key));
}
catch(const std::out_of_range& oor)
{
throw_exception<std::runtime_error>(
"mjolnir: while reading toml file: key(", key,
") in table(", tablename, ") missing");
}
catch(const toml::type_error& tte)
{
throw_exception<std::runtime_error>(
"mjolnir: while reading toml file: key(", key,
") in table(", tablename, ") has type `",
tab.at(key).type(), "`, expected `",
toml::value_traits<T>::type_index, "`.");
}
}
} // mjolnir
#endif// MJOLNIR_INPUT_GET_TOML_VALUE
<commit_msg>add overload for get_toml_value<commit_after>#ifndef MJOLNIR_UTIL_GET_TOML_VALUE
#define MJOLNIR_UTIL_GET_TOML_VALUE
#include <extlib/toml/toml.hpp>
#include <mjolnir/util/type_traits.hpp>
#include <mjolnir/util/throw_exception.hpp>
#include <string>
#include <stdexcept>
namespace mjolnir
{
inline toml::value const&
toml_value_at(const toml::Table& tab, const std::string& key,
const std::string& tablename)
{
try
{
return tab.at(key);
}
catch(const std::out_of_range& oor)
{
throw_exception<std::runtime_error>(
"mjolnir: while reading toml file: key(", key,
") in table(", tablename, ") missing");
}
}
// one of the toml values. needs no conversion. so it can return a reference.
template<typename T, typename std::enable_if<disjunction<
std::is_same<T, toml::Boolean >,
std::is_same<T, toml::Integer >,
std::is_same<T, toml::Float >,
std::is_same<T, toml::String >,
std::is_same<T, toml::Datetime>,
std::is_same<T, toml::Array >,
std::is_same<T, toml::Table >
>::value, std::nullptr_t>::type = nullptr>
T const& get_toml_value(const toml::Table& tab, const std::string& key,
const std::string& tablename)
{
try
{
return tab.at(key).cast<toml::value_traits<T>::type_index>();
}
catch(const std::out_of_range& oor)
{
throw_exception<std::runtime_error>(
"mjolnir: while reading toml file: key(", key,
") in table(", tablename, ") missing");
}
catch(const toml::type_error& tte)
{
throw_exception<std::runtime_error>(
"mjolnir: while reading toml file: key(", key,
") in table(", tablename, ") has type `",
tab.at(key).type(), "`, expected `",
toml::value_traits<T>::type_index, "`.");
}
}
// none of the toml values. needs conversion.
template<typename T, typename std::enable_if<conjunction<
negation<std::is_same<T, toml::Boolean >>,
negation<std::is_same<T, toml::Integer >>,
negation<std::is_same<T, toml::Float >>,
negation<std::is_same<T, toml::String >>,
negation<std::is_same<T, toml::Datetime>>,
negation<std::is_same<T, toml::Array >>,
negation<std::is_same<T, toml::Table >>
>::value, std::nullptr_t>::type = nullptr>
T get_toml_value(const toml::Table& tab, const std::string& key,
const std::string& tablename)
{
try
{
return toml::get<T>(tab.at(key));
}
catch(const std::out_of_range& oor)
{
throw_exception<std::runtime_error>(
"mjolnir: while reading toml file: key(", key,
") in table(", tablename, ") missing");
}
catch(const toml::type_error& tte)
{
throw_exception<std::runtime_error>(
"mjolnir: while reading toml file: key(", key,
") in table(", tablename, ") has type `",
tab.at(key).type(), "`, expected `",
toml::value_traits<T>::type_index, "`.");
}
}
// one of the toml values. needs no conversion. so it can return a reference.
template<typename T, typename std::enable_if<disjunction<
std::is_same<T, toml::Boolean >,
std::is_same<T, toml::Integer >,
std::is_same<T, toml::Float >,
std::is_same<T, toml::String >,
std::is_same<T, toml::Datetime>,
std::is_same<T, toml::Array >,
std::is_same<T, toml::Table >
>::value, std::nullptr_t>::type = nullptr>
T const& get_toml_value(const toml::Table& tab,
std::initializer_list<std::string> keys,
const std::string& tablename)
{
for(const auto& key : keys)
{
const auto iter = tab.find(key);
if(iter != tab.end())
{
return tab.at(key).cast<toml::value_traits<T>::type_index>();
}
}
std::ostringstream oss;
oss << "mjolnir: while reading toml file: none of the key(";
for(const auto& key : keys)
{
oss << key << ", ";
}
oss << ") are found in table (" << tablename << ").";
throw std::runtime_error(oss.str());
}
// none of the toml values. needs conversion.
template<typename T, typename std::enable_if<conjunction<
negation<std::is_same<T, toml::Boolean >>,
negation<std::is_same<T, toml::Integer >>,
negation<std::is_same<T, toml::Float >>,
negation<std::is_same<T, toml::String >>,
negation<std::is_same<T, toml::Datetime>>,
negation<std::is_same<T, toml::Array >>,
negation<std::is_same<T, toml::Table >>
>::value, std::nullptr_t>::type = nullptr>
T get_toml_value(const toml::Table& tab,
std::initializer_list<std::string> keys,
const std::string& tablename)
{
for(const auto& key : keys)
{
const auto iter = tab.find(key);
if(iter != tab.end())
{
return toml::get<T>(tab.at(key));
}
}
std::ostringstream oss;
oss << "mjolnir: while reading toml file: none of the key(";
for(const auto& key : keys)
{
oss << key << ", ";
}
oss << ") are found in table (" << tablename << ").";
throw std::runtime_error(oss.str());}
} // mjolnir
#endif// MJOLNIR_INPUT_GET_TOML_VALUE
<|endoftext|>
|
<commit_before>//=============================================================================================================
/**
* @file calcmetric.cpp
* @author Louis Eichhorst <louis.eichhorst@tu-ilmenau.de>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version 1.0
* @date January, 2017
*
* @section LICENSE
*
* Copyright (C) 2017, Louis Eichhorst and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief CalcMetric class definition.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "calcmetric.h"
#include <thread>
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <iostream>
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QElapsedTimer>
#include <QtConcurrent/QtConcurrent>
#include <QtConcurrent/QtConcurrentMap>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace Eigen;
using namespace std;
using namespace QtConcurrent;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
CalcMetric::CalcMetric()
{
m_iListLength = 10;
m_iKurtosisHistoryPosition = 0;
m_iP2PHistoryPosition = 0;
m_iFuzzyEnHistoryPosition = 0;
m_iFuzzyEnStart = 0;
m_iFuzzyEnStep = 10;
m_bSetNewP2P = false;
m_bSetNewFuzzyEn = false;
m_bSetNewKurtosis = false;
m_bHistoryReady=false;
}
//*************************************************************************************************************
QPair<RowVectorXd, QPair<QList<double>, int> > createInputList(RowVectorXd input, int dim, double r, double n, double mean, double stdDev)
{
QPair<RowVectorXd, QPair<QList<double>, int> > funcInput;
funcInput.first = input;
QPair<QList<double>, int> inputValues;
QList<double> doubleInputValues;
doubleInputValues << mean;
doubleInputValues << stdDev;
doubleInputValues << r;
doubleInputValues << n;
inputValues.first = doubleInputValues;
inputValues.second = dim;
funcInput.second = inputValues;
return funcInput;
}
//*************************************************************************************************************
double calcFuzzyEn(QPair<RowVectorXd, QPair<QList<double>, int> > input)//RowVectorXd data, double mean, double stdDev, int dim, double r, double n)
{
RowVectorXd data = input.first;
QPair<QList<double>, int> inputValues = input.second;
QList<double> doubleInputValues= inputValues.first;
int dim = inputValues.second;
double mean = doubleInputValues[0];
double stdDev = doubleInputValues[1];
double r = doubleInputValues[2];
double n = doubleInputValues[3];
int length = data.cols();
double fuzzyEn;
ArrayXd arDataNorm = (data.array()- mean).array()/(stdDev);
VectorXd dataNorm = arDataNorm;
Vector2d phi;
for(int j=0; j<2; j++)
{
int m = dim+j;
MatrixXd patterns;
patterns.resize(m, length-m+1);
if (m==1)
patterns = dataNorm;
else
{
for(int i=0; i<m; i++)
patterns.row(i)=dataNorm.segment(i,length-m+1);
}
VectorXd patternsMean = patterns.colwise().mean();
patterns = patterns.rowwise() - patternsMean.transpose(); //check whether correct
VectorXd aux;
aux.resize(length-m+1);
for (int i = 0; i< length-m+1; i++)
{
MatrixXd column;
column.resize(patterns.rows(),patterns.cols());
for (int l= 0; l < patterns.cols(); l++)
column.col(l) = patterns.col(i);
VectorXd distance = ((patterns.array()-column.array()).abs()).colwise().maxCoeff();
//cout << "dist " << i << ": " << distance << "\n";
VectorXd similarty = (((-1)*(distance.array().pow(n)))/r).exp();
//cout << "simi " << i << ": " << similarty << "\n";
aux(i) = ((similarty.sum()-1)/(length-m-1));
}
phi[j] = (aux.sum()/(length-m));
}
fuzzyEn = log(phi[0])-log(phi[1]);
return fuzzyEn;
}
//*************************************************************************************************************
VectorXd CalcMetric::getFuzzyEn()
{
return m_dvecFuzzyEn;
}
//*************************************************************************************************************
VectorXd CalcMetric::getP2P()
{
return m_dvecP2P;
}
//*************************************************************************************************************
VectorXd CalcMetric::getKurtosis()
{
return m_dvecKurtosis;
}
//*************************************************************************************************************
MatrixXd CalcMetric::getFuzzyEnHistory()
{
return m_dmatFuzzyEnHistory;
}
//*************************************************************************************************************
MatrixXd CalcMetric::getKurtosisHistory()
{
return m_dmatKurtosisHistory;
}
//*************************************************************************************************************
MatrixXd CalcMetric::getP2PHistory()
{
return m_dmatP2PHistory;
}
//*************************************************************************************************************
void CalcMetric::setData(Eigen::MatrixXd input)
{
m_dmatData = input;
m_iDataLength = m_dmatData.cols();
if (m_iChannelCount != m_dmatData.rows())
{
m_iChannelCount = m_dmatData.rows();
m_dvecStdDev.resize(m_iChannelCount);
m_dvecKurtosis.resize(m_iChannelCount);
m_dvecMean.resize(m_iChannelCount);
m_dvecFuzzyEn.resize(m_iChannelCount);
m_dvecP2P.resize(m_iChannelCount);
m_dmatFuzzyEnHistory.resize(m_iChannelCount, m_iListLength);
m_dmatKurtosisHistory.resize(m_iChannelCount, m_iListLength);
m_dmatP2PHistory.resize(m_iChannelCount, m_iListLength);
}
}
//*************************************************************************************************************
VectorXd CalcMetric::onSeizureDetection(int dim, double r, double n, QList<int> checkChs)
{
qSort(m_lFuzzyEnUsedChs);
QList<QPair<RowVectorXd, QPair<QList<double>, int> > > inputList;
for (int i = 0; i < checkChs.length(); i++)
{
if (!m_lFuzzyEnUsedChs.contains(checkChs[i]))
{
QPair<RowVectorXd, QPair<QList<double>, int> > funcInput = createInputList(m_dmatData.row(checkChs[i]), dim, r, n, m_dvecMean(checkChs[i]), m_dvecStdDev(checkChs[i]));
inputList << funcInput;
}
}
QList<double> fuzzyEnResults;
QFuture<double> fuzzyEnFuture = mapped(inputList, calcFuzzyEn);
fuzzyEnFuture.waitForFinished();
QFutureIterator<double> futureResult(fuzzyEnFuture);
while (futureResult.hasNext())
fuzzyEnResults << futureResult.next();
int j = 0;
for (int i = 0; i < checkChs.length(); i++)
{
if (!m_lFuzzyEnUsedChs.contains(checkChs[i]))
{
m_dvecFuzzyEn(checkChs[i]) = fuzzyEnResults[j];
j++;
}
}
return m_dvecFuzzyEn;
}
//*************************************************************************************************************
VectorXd calcP2P(MatrixXd data)
{
VectorXd max = data.rowwise().maxCoeff();
VectorXd min = data.rowwise().minCoeff();
VectorXd P2P = max-min;
return P2P;
}
//*************************************************************************************************************
void CalcMetric::calcP2P()
{
if (m_bSetNewP2P)
{
m_dmatP2PHistory.col(m_iP2PHistoryPosition) = m_dvecP2P;
m_bSetNewP2P = false;
m_iP2PHistoryPosition++;
if (m_iP2PHistoryPosition>(m_iListLength-1))
{
m_iP2PHistoryPosition = 0;
}
}
VectorXd max = m_dmatData.rowwise().maxCoeff();
VectorXd min = m_dmatData.rowwise().minCoeff();
m_dvecP2P = max-min;
m_bSetNewP2P = true;
}
//*************************************************************************************************************
QPair<VectorXd, VectorXd> calcKurtosis(MatrixXd data, VectorXd mean, int start, int end)
{
if (end > data.rows())
end=data.rows();
double sum;
int length = data.cols();
VectorXd stdDev;
VectorXd kurtosis;
for(int i=start; i < end; i++)
{
for(int j=0; j < length; j++)
{
if (j==0)
{
sum = (data(i,j)-mean(i));
stdDev(i) = pow(sum, 2);
kurtosis(i) = pow(sum, 4);
}
else
{
sum = data(i,j) - mean(i);
stdDev(i) = stdDev(i) + pow(sum, 2);
kurtosis(i) = kurtosis(i) + pow(sum,4);
}
}
stdDev(i) = stdDev(i)/(length-1);
stdDev(i) = sqrt(stdDev(i));
kurtosis(i)=(kurtosis(i))/((length)*pow((stdDev(i)*sqrt(length-1))/sqrt(length),4));
}
QPair <VectorXd, VectorXd> outputPair;
outputPair.first = kurtosis;
outputPair.second = stdDev;
return outputPair;
}
//*************************************************************************************************************
void CalcMetric::calcKurtosis(int start, int end)
{
if (end > m_iChannelCount)
end=m_iChannelCount;
if (m_bSetNewKurtosis)
{
m_dmatKurtosisHistory.col(m_iKurtosisHistoryPosition) = m_dvecKurtosis;
m_bSetNewKurtosis = false;
m_iKurtosisHistoryPosition++;
if (m_iKurtosisHistoryPosition>(m_iListLength-1))
m_iKurtosisHistoryPosition = 0;
}
m_dvecMean = m_dmatData.rowwise().mean();
double sum;
for(int i=start; i < end; i++)
{
for(int j=0; j < m_iDataLength; j++)
{
if (j==0)
{
sum = (m_dmatData(i,j)-m_dvecMean(i));
m_dvecStdDev(i) = pow(sum, 2);
m_dvecKurtosis(i) = pow(sum, 4);
}
else
{
sum = m_dmatData(i,j) - m_dvecMean(i);
m_dvecStdDev(i) = m_dvecStdDev(i) + pow(sum, 2);
m_dvecKurtosis(i) = m_dvecKurtosis(i) + pow(sum,4);
}
}
m_dvecStdDev(i) = m_dvecStdDev(i)/(m_iDataLength-1);
m_dvecStdDev(i) = sqrt(m_dvecStdDev(i));
m_dvecKurtosis(i)=(m_dvecKurtosis(i))/((m_iDataLength)*pow((m_dvecStdDev(i)*sqrt(m_iDataLength-1))/sqrt(m_iDataLength),4));
}
m_bSetNewKurtosis = true;
}
//*************************************************************************************************************
void CalcMetric::calcAll(Eigen::MatrixXd input, int dim, double r, double n)
{
this->setData(input);
this->calcP2P();
this->calcKurtosis(0,1000);
m_lFuzzyEnUsedChs.clear();
if (m_iFuzzyEnStart == m_iFuzzyEnStep-1)
{
m_dmatFuzzyEnHistory.col(m_iFuzzyEnHistoryPosition) = m_dvecFuzzyEn;
if (m_iFuzzyEnHistoryPosition < m_iListLength-1)
m_iFuzzyEnHistoryPosition++;
else
{
m_iFuzzyEnHistoryPosition = 0;
m_bHistoryReady = true;
}
}
QList<QPair<RowVectorXd, QPair<QList<double>, int> > > inputList;
for (int i = m_iFuzzyEnStart; i< m_iChannelCount; i=i+m_iFuzzyEnStep)
{
m_lFuzzyEnUsedChs << i;
QPair<RowVectorXd, QPair<QList<double>, int> > funcInput = createInputList(input.row(i), dim, r, n, m_dvecMean(i), m_dvecStdDev(i));
inputList << funcInput;
}
QList<double> fuzzyEnResults;
QFuture<double> fuzzyEnFuture = mapped(inputList, calcFuzzyEn);
fuzzyEnFuture.waitForFinished();
QFutureIterator<double> futureResult(fuzzyEnFuture);
while (futureResult.hasNext())
fuzzyEnResults << futureResult.next();
int j = 0;
for (int i = m_iFuzzyEnStart; i<m_iChannelCount; i=i+m_iFuzzyEnStep)
{
m_dvecFuzzyEn(i) = fuzzyEnResults[j];
j++;
}
if (m_iFuzzyEnStart < m_iFuzzyEnStep-1)
m_iFuzzyEnStart++;
else
m_iFuzzyEnStart = 0;
}
<commit_msg>initialized scalars to default of zero in constructor -- cov161901<commit_after>//=============================================================================================================
/**
* @file calcmetric.cpp
* @author Louis Eichhorst <louis.eichhorst@tu-ilmenau.de>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version 1.0
* @date January, 2017
*
* @section LICENSE
*
* Copyright (C) 2017, Louis Eichhorst and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief CalcMetric class definition.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "calcmetric.h"
#include <thread>
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <iostream>
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QElapsedTimer>
#include <QtConcurrent/QtConcurrent>
#include <QtConcurrent/QtConcurrentMap>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace Eigen;
using namespace std;
using namespace QtConcurrent;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
CalcMetric::CalcMetric()
{
m_iListLength = 10;
m_iKurtosisHistoryPosition = 0;
m_iP2PHistoryPosition = 0;
m_iFuzzyEnHistoryPosition = 0;
m_iFuzzyEnStart = 0;
m_iFuzzyEnStep = 10;
m_bSetNewP2P = false;
m_bSetNewFuzzyEn = false;
m_bSetNewKurtosis = false;
m_bHistoryReady=false;
m_iChannelCount = 0;
m_iDataLength = 0;
}
//*************************************************************************************************************
QPair<RowVectorXd, QPair<QList<double>, int> > createInputList(RowVectorXd input, int dim, double r, double n, double mean, double stdDev)
{
QPair<RowVectorXd, QPair<QList<double>, int> > funcInput;
funcInput.first = input;
QPair<QList<double>, int> inputValues;
QList<double> doubleInputValues;
doubleInputValues << mean;
doubleInputValues << stdDev;
doubleInputValues << r;
doubleInputValues << n;
inputValues.first = doubleInputValues;
inputValues.second = dim;
funcInput.second = inputValues;
return funcInput;
}
//*************************************************************************************************************
double calcFuzzyEn(QPair<RowVectorXd, QPair<QList<double>, int> > input)//RowVectorXd data, double mean, double stdDev, int dim, double r, double n)
{
RowVectorXd data = input.first;
QPair<QList<double>, int> inputValues = input.second;
QList<double> doubleInputValues= inputValues.first;
int dim = inputValues.second;
double mean = doubleInputValues[0];
double stdDev = doubleInputValues[1];
double r = doubleInputValues[2];
double n = doubleInputValues[3];
int length = data.cols();
double fuzzyEn;
ArrayXd arDataNorm = (data.array()- mean).array()/(stdDev);
VectorXd dataNorm = arDataNorm;
Vector2d phi;
for(int j=0; j<2; j++)
{
int m = dim+j;
MatrixXd patterns;
patterns.resize(m, length-m+1);
if (m==1)
patterns = dataNorm;
else
{
for(int i=0; i<m; i++)
patterns.row(i)=dataNorm.segment(i,length-m+1);
}
VectorXd patternsMean = patterns.colwise().mean();
patterns = patterns.rowwise() - patternsMean.transpose(); //check whether correct
VectorXd aux;
aux.resize(length-m+1);
for (int i = 0; i< length-m+1; i++)
{
MatrixXd column;
column.resize(patterns.rows(),patterns.cols());
for (int l= 0; l < patterns.cols(); l++)
column.col(l) = patterns.col(i);
VectorXd distance = ((patterns.array()-column.array()).abs()).colwise().maxCoeff();
//cout << "dist " << i << ": " << distance << "\n";
VectorXd similarty = (((-1)*(distance.array().pow(n)))/r).exp();
//cout << "simi " << i << ": " << similarty << "\n";
aux(i) = ((similarty.sum()-1)/(length-m-1));
}
phi[j] = (aux.sum()/(length-m));
}
fuzzyEn = log(phi[0])-log(phi[1]);
return fuzzyEn;
}
//*************************************************************************************************************
VectorXd CalcMetric::getFuzzyEn()
{
return m_dvecFuzzyEn;
}
//*************************************************************************************************************
VectorXd CalcMetric::getP2P()
{
return m_dvecP2P;
}
//*************************************************************************************************************
VectorXd CalcMetric::getKurtosis()
{
return m_dvecKurtosis;
}
//*************************************************************************************************************
MatrixXd CalcMetric::getFuzzyEnHistory()
{
return m_dmatFuzzyEnHistory;
}
//*************************************************************************************************************
MatrixXd CalcMetric::getKurtosisHistory()
{
return m_dmatKurtosisHistory;
}
//*************************************************************************************************************
MatrixXd CalcMetric::getP2PHistory()
{
return m_dmatP2PHistory;
}
//*************************************************************************************************************
void CalcMetric::setData(Eigen::MatrixXd input)
{
m_dmatData = input;
m_iDataLength = m_dmatData.cols();
if (m_iChannelCount != m_dmatData.rows())
{
m_iChannelCount = m_dmatData.rows();
m_dvecStdDev.resize(m_iChannelCount);
m_dvecKurtosis.resize(m_iChannelCount);
m_dvecMean.resize(m_iChannelCount);
m_dvecFuzzyEn.resize(m_iChannelCount);
m_dvecP2P.resize(m_iChannelCount);
m_dmatFuzzyEnHistory.resize(m_iChannelCount, m_iListLength);
m_dmatKurtosisHistory.resize(m_iChannelCount, m_iListLength);
m_dmatP2PHistory.resize(m_iChannelCount, m_iListLength);
}
}
//*************************************************************************************************************
VectorXd CalcMetric::onSeizureDetection(int dim, double r, double n, QList<int> checkChs)
{
qSort(m_lFuzzyEnUsedChs);
QList<QPair<RowVectorXd, QPair<QList<double>, int> > > inputList;
for (int i = 0; i < checkChs.length(); i++)
{
if (!m_lFuzzyEnUsedChs.contains(checkChs[i]))
{
QPair<RowVectorXd, QPair<QList<double>, int> > funcInput = createInputList(m_dmatData.row(checkChs[i]), dim, r, n, m_dvecMean(checkChs[i]), m_dvecStdDev(checkChs[i]));
inputList << funcInput;
}
}
QList<double> fuzzyEnResults;
QFuture<double> fuzzyEnFuture = mapped(inputList, calcFuzzyEn);
fuzzyEnFuture.waitForFinished();
QFutureIterator<double> futureResult(fuzzyEnFuture);
while (futureResult.hasNext())
fuzzyEnResults << futureResult.next();
int j = 0;
for (int i = 0; i < checkChs.length(); i++)
{
if (!m_lFuzzyEnUsedChs.contains(checkChs[i]))
{
m_dvecFuzzyEn(checkChs[i]) = fuzzyEnResults[j];
j++;
}
}
return m_dvecFuzzyEn;
}
//*************************************************************************************************************
VectorXd calcP2P(MatrixXd data)
{
VectorXd max = data.rowwise().maxCoeff();
VectorXd min = data.rowwise().minCoeff();
VectorXd P2P = max-min;
return P2P;
}
//*************************************************************************************************************
void CalcMetric::calcP2P()
{
if (m_bSetNewP2P)
{
m_dmatP2PHistory.col(m_iP2PHistoryPosition) = m_dvecP2P;
m_bSetNewP2P = false;
m_iP2PHistoryPosition++;
if (m_iP2PHistoryPosition>(m_iListLength-1))
{
m_iP2PHistoryPosition = 0;
}
}
VectorXd max = m_dmatData.rowwise().maxCoeff();
VectorXd min = m_dmatData.rowwise().minCoeff();
m_dvecP2P = max-min;
m_bSetNewP2P = true;
}
//*************************************************************************************************************
QPair<VectorXd, VectorXd> calcKurtosis(MatrixXd data, VectorXd mean, int start, int end)
{
if (end > data.rows())
end=data.rows();
double sum;
int length = data.cols();
VectorXd stdDev;
VectorXd kurtosis;
for(int i=start; i < end; i++)
{
for(int j=0; j < length; j++)
{
if (j==0)
{
sum = (data(i,j)-mean(i));
stdDev(i) = pow(sum, 2);
kurtosis(i) = pow(sum, 4);
}
else
{
sum = data(i,j) - mean(i);
stdDev(i) = stdDev(i) + pow(sum, 2);
kurtosis(i) = kurtosis(i) + pow(sum,4);
}
}
stdDev(i) = stdDev(i)/(length-1);
stdDev(i) = sqrt(stdDev(i));
kurtosis(i)=(kurtosis(i))/((length)*pow((stdDev(i)*sqrt(length-1))/sqrt(length),4));
}
QPair <VectorXd, VectorXd> outputPair;
outputPair.first = kurtosis;
outputPair.second = stdDev;
return outputPair;
}
//*************************************************************************************************************
void CalcMetric::calcKurtosis(int start, int end)
{
if (end > m_iChannelCount)
end=m_iChannelCount;
if (m_bSetNewKurtosis)
{
m_dmatKurtosisHistory.col(m_iKurtosisHistoryPosition) = m_dvecKurtosis;
m_bSetNewKurtosis = false;
m_iKurtosisHistoryPosition++;
if (m_iKurtosisHistoryPosition>(m_iListLength-1))
m_iKurtosisHistoryPosition = 0;
}
m_dvecMean = m_dmatData.rowwise().mean();
double sum;
for(int i=start; i < end; i++)
{
for(int j=0; j < m_iDataLength; j++)
{
if (j==0)
{
sum = (m_dmatData(i,j)-m_dvecMean(i));
m_dvecStdDev(i) = pow(sum, 2);
m_dvecKurtosis(i) = pow(sum, 4);
}
else
{
sum = m_dmatData(i,j) - m_dvecMean(i);
m_dvecStdDev(i) = m_dvecStdDev(i) + pow(sum, 2);
m_dvecKurtosis(i) = m_dvecKurtosis(i) + pow(sum,4);
}
}
m_dvecStdDev(i) = m_dvecStdDev(i)/(m_iDataLength-1);
m_dvecStdDev(i) = sqrt(m_dvecStdDev(i));
m_dvecKurtosis(i)=(m_dvecKurtosis(i))/((m_iDataLength)*pow((m_dvecStdDev(i)*sqrt(m_iDataLength-1))/sqrt(m_iDataLength),4));
}
m_bSetNewKurtosis = true;
}
//*************************************************************************************************************
void CalcMetric::calcAll(Eigen::MatrixXd input, int dim, double r, double n)
{
this->setData(input);
this->calcP2P();
this->calcKurtosis(0,1000);
m_lFuzzyEnUsedChs.clear();
if (m_iFuzzyEnStart == m_iFuzzyEnStep-1)
{
m_dmatFuzzyEnHistory.col(m_iFuzzyEnHistoryPosition) = m_dvecFuzzyEn;
if (m_iFuzzyEnHistoryPosition < m_iListLength-1)
m_iFuzzyEnHistoryPosition++;
else
{
m_iFuzzyEnHistoryPosition = 0;
m_bHistoryReady = true;
}
}
QList<QPair<RowVectorXd, QPair<QList<double>, int> > > inputList;
for (int i = m_iFuzzyEnStart; i< m_iChannelCount; i=i+m_iFuzzyEnStep)
{
m_lFuzzyEnUsedChs << i;
QPair<RowVectorXd, QPair<QList<double>, int> > funcInput = createInputList(input.row(i), dim, r, n, m_dvecMean(i), m_dvecStdDev(i));
inputList << funcInput;
}
QList<double> fuzzyEnResults;
QFuture<double> fuzzyEnFuture = mapped(inputList, calcFuzzyEn);
fuzzyEnFuture.waitForFinished();
QFutureIterator<double> futureResult(fuzzyEnFuture);
while (futureResult.hasNext())
fuzzyEnResults << futureResult.next();
int j = 0;
for (int i = m_iFuzzyEnStart; i<m_iChannelCount; i=i+m_iFuzzyEnStep)
{
m_dvecFuzzyEn(i) = fuzzyEnResults[j];
j++;
}
if (m_iFuzzyEnStart < m_iFuzzyEnStep-1)
m_iFuzzyEnStart++;
else
m_iFuzzyEnStart = 0;
}
<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include "ompl_interface/planning_context_manager.h"
#include <planning_models/conversions.h>
#include <algorithm>
#include <set>
#include <ompl/geometric/planners/rrt/RRT.h>
#include <ompl/geometric/planners/rrt/pRRT.h>
#include <ompl/geometric/planners/rrt/RRTConnect.h>
#include <ompl/geometric/planners/rrt/msRRTConnect.h>
#include <ompl/geometric/planners/rrt/LazyRRT.h>
#include <ompl/geometric/planners/est/EST.h>
#include <ompl/geometric/planners/sbl/SBL.h>
#include <ompl/geometric/planners/sbl/pSBL.h>
#include <ompl/geometric/planners/kpiece/KPIECE1.h>
#include <ompl/geometric/planners/kpiece/BKPIECE1.h>
#include <ompl/geometric/planners/kpiece/LBKPIECE1.h>
#include <ompl/contrib/rrt_star/RRTstar.h>
#include <ompl/geometric/planners/prm/PRM.h>
#include <ompl/tools/debug/Profiler.h>
#include "ompl_interface/parameterization/joint_space/joint_model_state_space_factory.h"
#include "ompl_interface/parameterization/work_space/pose_model_state_space_factory.h"
namespace ompl_interface
{
class PlanningContextManager::LastPlanningContext
{
public:
ModelBasedPlanningContextPtr getContext(void)
{
boost::mutex::scoped_lock slock(lock_);
return last_planning_context_solve_;
}
void setContext(const ModelBasedPlanningContextPtr &context)
{
boost::mutex::scoped_lock slock(lock_);
last_planning_context_solve_ = context;
}
void clear(void)
{
boost::mutex::scoped_lock slock(lock_);
last_planning_context_solve_.reset();
}
private:
/* The planning group for which solve() was called last */
ModelBasedPlanningContextPtr last_planning_context_solve_;
boost::mutex lock_;
};
struct PlanningContextManager::CachedContexts
{
std::map<std::pair<std::string, std::string>,
std::vector<ModelBasedPlanningContextPtr> > contexts_;
boost::mutex lock_;
};
}
ompl_interface::PlanningContextManager::PlanningContextManager(const planning_models::KinematicModelConstPtr &kmodel) :
kmodel_(kmodel), constraint_sampler_manager_(NULL), max_goal_samples_(10), max_state_sampling_attempts_(10), max_goal_sampling_attempts_(1000),
max_planning_threads_(4), max_velocity_(10), max_acceleration_(2.0), max_solution_segment_length_(0.0)
{
last_planning_context_.reset(new LastPlanningContext());
cached_contexts_.reset(new CachedContexts());
registerDefaultPlanners();
registerDefaultStateSpaces();
}
ompl_interface::PlanningContextManager::~PlanningContextManager(void)
{
}
namespace ompl_interface
{
template<typename T>
static ob::PlannerPtr allocatePlanner(const ob::SpaceInformationPtr &si)
{
return ob::PlannerPtr(new T(si));
}
}
ompl::base::PlannerPtr ompl_interface::PlanningContextManager::plannerAllocator(const ompl::base::SpaceInformationPtr &si, const std::string &planner,
const std::string &name, const std::map<std::string, std::string> &config) const
{
std::map<std::string, ob::PlannerAllocator>::const_iterator it = known_planners_.find(planner);
if (it != known_planners_.end())
{
ob::PlannerPtr p = it->second(si);
if (!name.empty())
p->setName(name);
p->params().setParams(config, true);
p->setup();
return p;
}
else
{
ROS_ERROR("Unknown planner: '%s'", planner.c_str());
return ob::PlannerPtr();
}
}
ompl_interface::ConfiguredPlannerAllocator ompl_interface::PlanningContextManager::getPlannerAllocator(void) const
{
return boost::bind(&PlanningContextManager::plannerAllocator, this, _1, _2, _3, _4);
}
void ompl_interface::PlanningContextManager::registerDefaultPlanners(void)
{
registerPlannerAllocator("geometric::RRT", boost::bind(&allocatePlanner<og::RRT>, _1));
registerPlannerAllocator("geometric::RRTConnect", boost::bind(&allocatePlanner<og::RRTConnect>, _1));
registerPlannerAllocator("geometric::msRRTConnect", boost::bind(&allocatePlanner<og::msRRTConnect>, _1));
registerPlannerAllocator("geometric::LazyRRT", boost::bind(&allocatePlanner<og::LazyRRT>, _1));
registerPlannerAllocator("geometric::EST", boost::bind(&allocatePlanner<og::EST>, _1));
registerPlannerAllocator("geometric::SBL", boost::bind(&allocatePlanner<og::SBL>, _1));
registerPlannerAllocator("geometric::KPIECE", boost::bind(&allocatePlanner<og::KPIECE1>, _1));
registerPlannerAllocator("geometric::BKPIECE", boost::bind(&allocatePlanner<og::BKPIECE1>, _1));
registerPlannerAllocator("geometric::LBKPIECE", boost::bind(&allocatePlanner<og::LBKPIECE1>, _1));
registerPlannerAllocator("geometric::RRTstar", boost::bind(&allocatePlanner<og::RRTstar>, _1));
registerPlannerAllocator("geometric::PRM", boost::bind(&allocatePlanner<og::PRM>, _1));
}
void ompl_interface::PlanningContextManager::registerDefaultStateSpaces(void)
{
registerStateSpaceFactory(ModelBasedStateSpaceFactoryPtr(new JointModelStateSpaceFactory()));
registerStateSpaceFactory(ModelBasedStateSpaceFactoryPtr(new PoseModelStateSpaceFactory()));
}
void ompl_interface::PlanningContextManager::setPlanningConfigurations(const std::vector<PlanningConfigurationSettings> &pconfig)
{
planner_configs_.clear();
for (std::size_t i = 0 ; i < pconfig.size() ; ++i)
planner_configs_[pconfig[i].name] = pconfig[i];
// construct default configurations
const std::map<std::string, planning_models::KinematicModel::JointModelGroup*>& groups = kmodel_->getJointModelGroupMap();
for (std::map<std::string, planning_models::KinematicModel::JointModelGroup*>::const_iterator it = groups.begin() ; it != groups.end() ; ++it)
if (planner_configs_.find(it->first) == planner_configs_.end())
{
PlanningConfigurationSettings empty;
empty.name = empty.group = it->first;
planner_configs_[empty.name] = empty;
}
}
ompl_interface::ModelBasedPlanningContextPtr ompl_interface::PlanningContextManager::getPlanningContext(const std::string &config, const std::string& factory_type) const
{
std::map<std::string, PlanningConfigurationSettings>::const_iterator pc = planner_configs_.find(config);
if (pc != planner_configs_.end())
{
std::map<std::string, ModelBasedStateSpaceFactoryPtr>::const_iterator f =
factory_type.empty() ? state_space_factories_.begin() : state_space_factories_.find(factory_type);
if (f != state_space_factories_.end())
return getPlanningContext(pc->second, f->second.get());
else
ROS_ERROR("Factory of type '%s' was not found", factory_type.c_str());
}
else
ROS_ERROR("Planning configuration '%s' was not found", config.c_str());
return ModelBasedPlanningContextPtr();
}
ompl_interface::ModelBasedPlanningContextPtr ompl_interface::PlanningContextManager::getPlanningContext(const PlanningConfigurationSettings &config,
const ModelBasedStateSpaceFactory *factory) const
{
ModelBasedPlanningContextPtr context;
{
boost::mutex::scoped_lock slock(cached_contexts_->lock_);
std::map<std::pair<std::string, std::string>, std::vector<ModelBasedPlanningContextPtr> >::const_iterator cc =
cached_contexts_->contexts_.find(std::make_pair(config.name, factory->getType()));
if (cc != cached_contexts_->contexts_.end())
{
for (std::size_t i = 0 ; i < cc->second.size() ; ++i)
if (cc->second[i].unique())
{
ROS_DEBUG("Reusing cached planning context");
context = cc->second[i];
break;
}
}
}
if (!context)
{
ModelBasedStateSpaceSpecification space_spec(kmodel_, config.group);
planning_scene::KinematicsAllocators::const_iterator it = kinematics_allocators_.find(space_spec.joint_model_group_);
if (it != kinematics_allocators_.end())
{
space_spec.kinematics_allocator_ = it->second.first;
space_spec.kinematics_subgroup_allocators_ = it->second.second;
}
ModelBasedPlanningContextSpecification context_spec;
context_spec.config_ = config.config;
context_spec.planner_allocator_ = getPlannerAllocator();
context_spec.constraint_sampler_manager_ = constraint_sampler_manager_;
ROS_DEBUG("Creating new planning context");
context.reset(new ModelBasedPlanningContext(config.name, factory->getNewStateSpace(space_spec), context_spec));
{
boost::mutex::scoped_lock slock(cached_contexts_->lock_);
cached_contexts_->contexts_[std::make_pair(config.name, factory->getType())].push_back(context);
}
}
context->setMaximumPlanningThreads(max_planning_threads_);
context->setMaximumGoalSamples(max_goal_samples_);
context->setMaximumStateSamplingAttempts(max_state_sampling_attempts_);
context->setMaximumGoalSamplingAttempts(max_goal_sampling_attempts_);
context->setMaximumVelocity(max_velocity_);
context->setMaximumAcceleration(max_acceleration_);
if (max_solution_segment_length_ <= std::numeric_limits<double>::epsilon())
context->setMaximumSolutionSegmentLength(context->getOMPLSimpleSetup().getStateSpace()->getMaximumExtent() / 100.0);
else
context->setMaximumSolutionSegmentLength(max_solution_segment_length_);
last_planning_context_->setContext(context);
return context;
}
ompl_interface::ModelBasedPlanningContextPtr ompl_interface::PlanningContextManager::getPlanningContext(const moveit_msgs::MotionPlanRequest &req) const
{
if (req.group_name.empty())
{
ROS_ERROR("No group specified to plan for");
return ModelBasedPlanningContextPtr();
}
// find the problem representation to use
const ModelBasedStateSpaceFactory *factory = NULL;
int prev_priority = -1;
for (std::map<std::string, ModelBasedStateSpaceFactoryPtr>::const_iterator it = state_space_factories_.begin() ; it != state_space_factories_.end() ; ++it)
{
int priority = it->second->canRepresentProblem(req, kmodel_, kinematics_allocators_);
if (priority >= 0)
if (!factory || priority > prev_priority)
{
factory = it->second.get();
prev_priority = priority;
}
}
if (!factory)
{
ROS_ERROR("There are no known state spaces that can represent the given planning problem");
return ModelBasedPlanningContextPtr();
}
else
ROS_DEBUG("Using '%s' parameterization for solving problem", factory->getType().c_str());
// identify the correct planning configuration
std::map<std::string, PlanningConfigurationSettings>::const_iterator pc = planner_configs_.end();
if (!req.planner_id.empty())
{
pc = planner_configs_.find(req.group_name + "[" + req.planner_id + "]");
if (pc == planner_configs_.end())
ROS_WARN_STREAM("Cannot find planning configuration for group '" << req.group_name
<< "' using planner '" << req.planner_id << "'. Will use defaults instead.");
}
if (pc == planner_configs_.end())
{
pc = planner_configs_.find(req.group_name);
if (pc == planner_configs_.end())
{
ROS_ERROR_STREAM("Cannot find planning configuration for group '" << req.group_name << "'");
return ModelBasedPlanningContextPtr();
}
}
return getPlanningContext(pc->second, factory);
}
ompl_interface::ModelBasedPlanningContextPtr ompl_interface::PlanningContextManager::getLastPlanningContext(void) const
{
return last_planning_context_->getContext();
}
<commit_msg>disable multi-space planner<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include "ompl_interface/planning_context_manager.h"
#include <planning_models/conversions.h>
#include <algorithm>
#include <set>
#include <ompl/geometric/planners/rrt/RRT.h>
#include <ompl/geometric/planners/rrt/pRRT.h>
#include <ompl/geometric/planners/rrt/RRTConnect.h>
//#include <ompl/geometric/planners/rrt/msRRTConnect.h>
#include <ompl/geometric/planners/rrt/LazyRRT.h>
#include <ompl/geometric/planners/est/EST.h>
#include <ompl/geometric/planners/sbl/SBL.h>
#include <ompl/geometric/planners/sbl/pSBL.h>
#include <ompl/geometric/planners/kpiece/KPIECE1.h>
#include <ompl/geometric/planners/kpiece/BKPIECE1.h>
#include <ompl/geometric/planners/kpiece/LBKPIECE1.h>
#include <ompl/contrib/rrt_star/RRTstar.h>
#include <ompl/geometric/planners/prm/PRM.h>
#include <ompl/tools/debug/Profiler.h>
#include "ompl_interface/parameterization/joint_space/joint_model_state_space_factory.h"
#include "ompl_interface/parameterization/work_space/pose_model_state_space_factory.h"
namespace ompl_interface
{
class PlanningContextManager::LastPlanningContext
{
public:
ModelBasedPlanningContextPtr getContext(void)
{
boost::mutex::scoped_lock slock(lock_);
return last_planning_context_solve_;
}
void setContext(const ModelBasedPlanningContextPtr &context)
{
boost::mutex::scoped_lock slock(lock_);
last_planning_context_solve_ = context;
}
void clear(void)
{
boost::mutex::scoped_lock slock(lock_);
last_planning_context_solve_.reset();
}
private:
/* The planning group for which solve() was called last */
ModelBasedPlanningContextPtr last_planning_context_solve_;
boost::mutex lock_;
};
struct PlanningContextManager::CachedContexts
{
std::map<std::pair<std::string, std::string>,
std::vector<ModelBasedPlanningContextPtr> > contexts_;
boost::mutex lock_;
};
}
ompl_interface::PlanningContextManager::PlanningContextManager(const planning_models::KinematicModelConstPtr &kmodel) :
kmodel_(kmodel), constraint_sampler_manager_(NULL), max_goal_samples_(10), max_state_sampling_attempts_(10), max_goal_sampling_attempts_(1000),
max_planning_threads_(4), max_velocity_(10), max_acceleration_(2.0), max_solution_segment_length_(0.0)
{
last_planning_context_.reset(new LastPlanningContext());
cached_contexts_.reset(new CachedContexts());
registerDefaultPlanners();
registerDefaultStateSpaces();
}
ompl_interface::PlanningContextManager::~PlanningContextManager(void)
{
}
namespace ompl_interface
{
template<typename T>
static ob::PlannerPtr allocatePlanner(const ob::SpaceInformationPtr &si)
{
return ob::PlannerPtr(new T(si));
}
}
ompl::base::PlannerPtr ompl_interface::PlanningContextManager::plannerAllocator(const ompl::base::SpaceInformationPtr &si, const std::string &planner,
const std::string &name, const std::map<std::string, std::string> &config) const
{
std::map<std::string, ob::PlannerAllocator>::const_iterator it = known_planners_.find(planner);
if (it != known_planners_.end())
{
ob::PlannerPtr p = it->second(si);
if (!name.empty())
p->setName(name);
p->params().setParams(config, true);
p->setup();
return p;
}
else
{
ROS_ERROR("Unknown planner: '%s'", planner.c_str());
return ob::PlannerPtr();
}
}
ompl_interface::ConfiguredPlannerAllocator ompl_interface::PlanningContextManager::getPlannerAllocator(void) const
{
return boost::bind(&PlanningContextManager::plannerAllocator, this, _1, _2, _3, _4);
}
void ompl_interface::PlanningContextManager::registerDefaultPlanners(void)
{
registerPlannerAllocator("geometric::RRT", boost::bind(&allocatePlanner<og::RRT>, _1));
registerPlannerAllocator("geometric::RRTConnect", boost::bind(&allocatePlanner<og::RRTConnect>, _1));
// registerPlannerAllocator("geometric::msRRTConnect", boost::bind(&allocatePlanner<og::msRRTConnect>, _1));
registerPlannerAllocator("geometric::LazyRRT", boost::bind(&allocatePlanner<og::LazyRRT>, _1));
registerPlannerAllocator("geometric::EST", boost::bind(&allocatePlanner<og::EST>, _1));
registerPlannerAllocator("geometric::SBL", boost::bind(&allocatePlanner<og::SBL>, _1));
registerPlannerAllocator("geometric::KPIECE", boost::bind(&allocatePlanner<og::KPIECE1>, _1));
registerPlannerAllocator("geometric::BKPIECE", boost::bind(&allocatePlanner<og::BKPIECE1>, _1));
registerPlannerAllocator("geometric::LBKPIECE", boost::bind(&allocatePlanner<og::LBKPIECE1>, _1));
registerPlannerAllocator("geometric::RRTstar", boost::bind(&allocatePlanner<og::RRTstar>, _1));
registerPlannerAllocator("geometric::PRM", boost::bind(&allocatePlanner<og::PRM>, _1));
}
void ompl_interface::PlanningContextManager::registerDefaultStateSpaces(void)
{
registerStateSpaceFactory(ModelBasedStateSpaceFactoryPtr(new JointModelStateSpaceFactory()));
registerStateSpaceFactory(ModelBasedStateSpaceFactoryPtr(new PoseModelStateSpaceFactory()));
}
void ompl_interface::PlanningContextManager::setPlanningConfigurations(const std::vector<PlanningConfigurationSettings> &pconfig)
{
planner_configs_.clear();
for (std::size_t i = 0 ; i < pconfig.size() ; ++i)
planner_configs_[pconfig[i].name] = pconfig[i];
// construct default configurations
const std::map<std::string, planning_models::KinematicModel::JointModelGroup*>& groups = kmodel_->getJointModelGroupMap();
for (std::map<std::string, planning_models::KinematicModel::JointModelGroup*>::const_iterator it = groups.begin() ; it != groups.end() ; ++it)
if (planner_configs_.find(it->first) == planner_configs_.end())
{
PlanningConfigurationSettings empty;
empty.name = empty.group = it->first;
planner_configs_[empty.name] = empty;
}
}
ompl_interface::ModelBasedPlanningContextPtr ompl_interface::PlanningContextManager::getPlanningContext(const std::string &config, const std::string& factory_type) const
{
std::map<std::string, PlanningConfigurationSettings>::const_iterator pc = planner_configs_.find(config);
if (pc != planner_configs_.end())
{
std::map<std::string, ModelBasedStateSpaceFactoryPtr>::const_iterator f =
factory_type.empty() ? state_space_factories_.begin() : state_space_factories_.find(factory_type);
if (f != state_space_factories_.end())
return getPlanningContext(pc->second, f->second.get());
else
ROS_ERROR("Factory of type '%s' was not found", factory_type.c_str());
}
else
ROS_ERROR("Planning configuration '%s' was not found", config.c_str());
return ModelBasedPlanningContextPtr();
}
ompl_interface::ModelBasedPlanningContextPtr ompl_interface::PlanningContextManager::getPlanningContext(const PlanningConfigurationSettings &config,
const ModelBasedStateSpaceFactory *factory) const
{
ModelBasedPlanningContextPtr context;
{
boost::mutex::scoped_lock slock(cached_contexts_->lock_);
std::map<std::pair<std::string, std::string>, std::vector<ModelBasedPlanningContextPtr> >::const_iterator cc =
cached_contexts_->contexts_.find(std::make_pair(config.name, factory->getType()));
if (cc != cached_contexts_->contexts_.end())
{
for (std::size_t i = 0 ; i < cc->second.size() ; ++i)
if (cc->second[i].unique())
{
ROS_DEBUG("Reusing cached planning context");
context = cc->second[i];
break;
}
}
}
if (!context)
{
ModelBasedStateSpaceSpecification space_spec(kmodel_, config.group);
planning_scene::KinematicsAllocators::const_iterator it = kinematics_allocators_.find(space_spec.joint_model_group_);
if (it != kinematics_allocators_.end())
{
space_spec.kinematics_allocator_ = it->second.first;
space_spec.kinematics_subgroup_allocators_ = it->second.second;
}
ModelBasedPlanningContextSpecification context_spec;
context_spec.config_ = config.config;
context_spec.planner_allocator_ = getPlannerAllocator();
context_spec.constraint_sampler_manager_ = constraint_sampler_manager_;
ROS_DEBUG("Creating new planning context");
context.reset(new ModelBasedPlanningContext(config.name, factory->getNewStateSpace(space_spec), context_spec));
{
boost::mutex::scoped_lock slock(cached_contexts_->lock_);
cached_contexts_->contexts_[std::make_pair(config.name, factory->getType())].push_back(context);
}
}
context->setMaximumPlanningThreads(max_planning_threads_);
context->setMaximumGoalSamples(max_goal_samples_);
context->setMaximumStateSamplingAttempts(max_state_sampling_attempts_);
context->setMaximumGoalSamplingAttempts(max_goal_sampling_attempts_);
context->setMaximumVelocity(max_velocity_);
context->setMaximumAcceleration(max_acceleration_);
if (max_solution_segment_length_ <= std::numeric_limits<double>::epsilon())
context->setMaximumSolutionSegmentLength(context->getOMPLSimpleSetup().getStateSpace()->getMaximumExtent() / 100.0);
else
context->setMaximumSolutionSegmentLength(max_solution_segment_length_);
last_planning_context_->setContext(context);
return context;
}
ompl_interface::ModelBasedPlanningContextPtr ompl_interface::PlanningContextManager::getPlanningContext(const moveit_msgs::MotionPlanRequest &req) const
{
if (req.group_name.empty())
{
ROS_ERROR("No group specified to plan for");
return ModelBasedPlanningContextPtr();
}
// find the problem representation to use
const ModelBasedStateSpaceFactory *factory = NULL;
int prev_priority = -1;
for (std::map<std::string, ModelBasedStateSpaceFactoryPtr>::const_iterator it = state_space_factories_.begin() ; it != state_space_factories_.end() ; ++it)
{
int priority = it->second->canRepresentProblem(req, kmodel_, kinematics_allocators_);
if (priority >= 0)
if (!factory || priority > prev_priority)
{
factory = it->second.get();
prev_priority = priority;
}
}
if (!factory)
{
ROS_ERROR("There are no known state spaces that can represent the given planning problem");
return ModelBasedPlanningContextPtr();
}
else
ROS_DEBUG("Using '%s' parameterization for solving problem", factory->getType().c_str());
// identify the correct planning configuration
std::map<std::string, PlanningConfigurationSettings>::const_iterator pc = planner_configs_.end();
if (!req.planner_id.empty())
{
pc = planner_configs_.find(req.group_name + "[" + req.planner_id + "]");
if (pc == planner_configs_.end())
ROS_WARN_STREAM("Cannot find planning configuration for group '" << req.group_name
<< "' using planner '" << req.planner_id << "'. Will use defaults instead.");
}
if (pc == planner_configs_.end())
{
pc = planner_configs_.find(req.group_name);
if (pc == planner_configs_.end())
{
ROS_ERROR_STREAM("Cannot find planning configuration for group '" << req.group_name << "'");
return ModelBasedPlanningContextPtr();
}
}
return getPlanningContext(pc->second, factory);
}
ompl_interface::ModelBasedPlanningContextPtr ompl_interface::PlanningContextManager::getLastPlanningContext(void) const
{
return last_planning_context_->getContext();
}
<|endoftext|>
|
<commit_before>#include <Windows.h>
#define WINDOW_LISTBOX 101
#define APPLY_BUTTON 102
#define DESKTOP_COMBOBOX 103
// TODO: Convert to LISTVIEW
//#define IDC_MAIN_LISTVIEW
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
BOOL CALLBACK PopulateWindowsEnumProc(HWND, LPARAM);
BOOL CALLBACK PopulateDesktopsEnumProc(HMONITOR, HDC, LPRECT, LPARAM);
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR szCmdLine,
int nCmdShow)
{
static TCHAR szAppName[] = TEXT("Selector Window");
HWND hWnd;
MSG msg;
WNDCLASSEX wc;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW|CS_VREDRAW|CS_OWNDC;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = szAppName;
wc.hIconSm = NULL;
wc.lpszClassName = szAppName;
if(!RegisterClassEx(&wc))
{
MessageBox(NULL,
TEXT("This program requires Windows NT."),
szAppName,
MB_ICONERROR);
return 0;
}
// Create main window
hWnd = CreateWindowEx(0,
szAppName,
TEXT("Border Remover"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
400,
500,
HWND_DESKTOP,
NULL,
hInstance,
NULL);
if(!hWnd)
{
MessageBox(hWnd, TEXT("Could not create window."), TEXT("Error"), MB_OK | MB_ICONERROR);
return FALSE;
}
// Get the dimensions available
RECT rcClient;
GetClientRect(hWnd, &rcClient);
// Create listbox
HWND hList;
hList = CreateWindowEx(WS_EX_CLIENTEDGE,
TEXT("LISTBOX"),
TEXT(""),
WS_CHILD|WS_VISIBLE|WS_VSCROLL|WS_HSCROLL|LBS_SORT|LBS_NOINTEGRALHEIGHT,
0,
0,
rcClient.right,
rcClient.bottom-25,
hWnd,
(HMENU)WINDOW_LISTBOX,
hInstance,
NULL);
// Check for failure
if(!hList)
{
MessageBox(hWnd, TEXT("Could not create list box."), TEXT("Error"), MB_OK | MB_ICONERROR);
return FALSE;
}
// Allow Horizontal Scrolling
SendMessage(hList, LB_SETHORIZONTALEXTENT, 1920, NULL);
// Populate the list
EnumWindows(PopulateWindowsEnumProc, (LPARAM)hWnd);
// Create the apply button
HWND hButton;
hButton = CreateWindowEx(WS_EX_CLIENTEDGE,
TEXT("BUTTON"),
TEXT("Apply"),
WS_CHILDWINDOW|WS_VISIBLE|BS_PUSHBUTTON,
rcClient.right-100,
rcClient.bottom-25,
100,
25,
hWnd,
(HMENU)APPLY_BUTTON,
hInstance,
NULL);
// Check for failure
if(!hButton)
{
MessageBox(hWnd, TEXT("Could not create button."), TEXT("Error"), MB_OK | MB_ICONERROR);
return FALSE;
}
// Create the desktop selection menu
HWND hDesktopBox;
hDesktopBox = CreateWindowEx(WS_EX_CLIENTEDGE,
TEXT("COMBOBOX"),
TEXT(""),
WS_CHILDWINDOW|WS_VISIBLE|CBS_DROPDOWNLIST|CBS_HASSTRINGS,
0,
rcClient.bottom-25,
rcClient.right-100,
125,
hWnd,
(HMENU)DESKTOP_COMBOBOX,
hInstance,
NULL);
// Check for failure
if(!hDesktopBox)
{
MessageBox(hWnd, TEXT("Could not create combo box."), TEXT("Error"), MB_OK | MB_ICONERROR);
return FALSE;
}
// Populate combo box
EnumDisplayMonitors(NULL, NULL, PopulateDesktopsEnumProc, (LPARAM)hWnd);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
while(GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(
HWND hWnd,
UINT msg,
WPARAM wParam,
LPARAM lParam
)
{
switch(msg)
{
case WM_CREATE:
{
break;
}
case WM_COMMAND:
{
switch(LOWORD(wParam))
{
case APPLY_BUTTON:
{
int index;
HWND targetWindow;
HMONITOR targetDesktop;
MONITORINFO desktopInfo;
LPRECT desktopRect;
// Get the index of the selected window in the list
index = SendDlgItemMessage(hWnd, WINDOW_LISTBOX, LB_GETCURSEL, NULL, NULL);
// Make sure we have selected a window
if(index == LB_ERR)
{
MessageBox(hWnd, TEXT("Must select a window."), TEXT("Error"), MB_OK | MB_ICONERROR);
return FALSE;
}
// Get the handle to the window that we want to modify from the selected item
targetWindow = (HWND)SendDlgItemMessage(hWnd, WINDOW_LISTBOX, LB_GETITEMDATA, index, NULL);
// Get the index of the selected desktop in the combo box
index = SendDlgItemMessage(hWnd, DESKTOP_COMBOBOX, CB_GETCURSEL, NULL, NULL);
// Make sure we have selected a desktop
if(index == CB_ERR)
{
MessageBox(hWnd, TEXT("Must select a desktop."), TEXT("Error"), MB_OK | MB_ICONERROR);
return FALSE;
}
// Get the handle to the desktop we want to place the window on
targetDesktop = (HMONITOR)SendDlgItemMessage(hWnd, DESKTOP_COMBOBOX, CB_GETITEMDATA, index, NULL);
//desktopRect = (LPRECT)SendDlgItemMessage(hWnd, DESKTOP_COMBOBOX, CB_GETITEMDATA, index, NULL);
// Get a pointer to the rectangle describing the desktop
desktopInfo.cbSize = sizeof(MONITORINFO);
GetMonitorInfo(targetDesktop, &desktopInfo);
desktopRect = &(desktopInfo.rcMonitor);
// Get the old style
DWORD newStyle, oldStyle;
oldStyle = GetWindowLong(targetWindow, GWL_STYLE);
// Apply changes
newStyle = oldStyle ^ 0x00C00000L;
SetWindowLong(targetWindow, GWL_STYLE, newStyle);
SetWindowPos(targetWindow,
NULL,
desktopRect->left,
desktopRect->top,
desktopRect->right - desktopRect->left,
desktopRect->bottom - desktopRect->top,
SWP_DRAWFRAME|SWP_FRAMECHANGED|SWP_NOZORDER|SWP_NOACTIVATE);
InvalidateRect(targetWindow, NULL, TRUE);
break;
}
}
break;
}
case WM_SIZE:
{
HWND hList;
HWND hButton;
HWND hCombo;
RECT rcClient;
GetClientRect(hWnd, &rcClient);
// Set appropriate dimensions for when the window is resized
hList = GetDlgItem(hWnd, WINDOW_LISTBOX);
SetWindowPos(hList, NULL, 0, 0, rcClient.right, rcClient.bottom-25, SWP_NOZORDER);
hButton = GetDlgItem(hWnd, APPLY_BUTTON);
SetWindowPos(hButton, NULL, rcClient.right-100, rcClient.bottom-25, 100, 25, SWP_NOZORDER);
hCombo = GetDlgItem(hWnd, DESKTOP_COMBOBOX);
SetWindowPos(hCombo, NULL, 0, rcClient.bottom-25, rcClient.right-100, 125, SWP_NOZORDER);
break;
}
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
// Populates our WINDOW_LISTBOX with every window that does not have an empty title.
// Ideally, we could use the icons and the .exe file to identify, but those are non-trivial
// in comparison to the title.
BOOL CALLBACK PopulateWindowsEnumProc(HWND hWnd, LPARAM lParam)
{
// Adjust this length
WCHAR fileName[512];
//GetWindowModuleFileName(hWnd,fileName,512);
// Get the title
SendMessage(hWnd, WM_GETTEXT, MAX_PATH, (LPARAM)fileName);
// Remove Windows without titles
if(fileName[0]!='\0')
{
// Add the item to the listbox
int index = SendDlgItemMessage((HWND)lParam, WINDOW_LISTBOX, LB_ADDSTRING, 0, (LPARAM)fileName);
// Add the window handle as the item data. This may not be safe on x64 machines because
// the data is required to be 32 bit and I'm not positive hWnd has the same requirements.
SendDlgItemMessage((HWND)lParam, WINDOW_LISTBOX, LB_SETITEMDATA, index, (LPARAM)hWnd);
}
return TRUE;
}
BOOL CALLBACK PopulateDesktopsEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM lParam)
{
// Add an item to the combo box.
int index = SendDlgItemMessage((HWND)lParam, DESKTOP_COMBOBOX, CB_ADDSTRING, NULL, (LPARAM)TEXT("fad"));
// Attach the data to the combo box as the item data.
SendDlgItemMessage((HWND)lParam, DESKTOP_COMBOBOX, CB_SETITEMDATA, index, (LPARAM)hMonitor);
return TRUE;
}<commit_msg>Labels n desktops 0-n instead of "fad"<commit_after>#include <Windows.h>
#define WINDOW_LISTBOX 101
#define APPLY_BUTTON 102
#define DESKTOP_COMBOBOX 103
// TODO: Convert to LISTVIEW
//#define IDC_MAIN_LISTVIEW
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
BOOL CALLBACK PopulateWindowsEnumProc(HWND, LPARAM);
BOOL CALLBACK PopulateDesktopsEnumProc(HMONITOR, HDC, LPRECT, LPARAM);
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR szCmdLine,
int nCmdShow)
{
static TCHAR szAppName[] = TEXT("Selector Window");
HWND hWnd;
MSG msg;
WNDCLASSEX wc;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW|CS_VREDRAW|CS_OWNDC;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = szAppName;
wc.hIconSm = NULL;
wc.lpszClassName = szAppName;
if(!RegisterClassEx(&wc))
{
MessageBox(NULL,
TEXT("This program requires Windows NT."),
szAppName,
MB_ICONERROR);
return 0;
}
// Create main window
hWnd = CreateWindowEx(0,
szAppName,
TEXT("Border Remover"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
400,
500,
HWND_DESKTOP,
NULL,
hInstance,
NULL);
if(!hWnd)
{
MessageBox(hWnd, TEXT("Could not create window."), TEXT("Error"), MB_OK | MB_ICONERROR);
return FALSE;
}
// Get the dimensions available
RECT rcClient;
GetClientRect(hWnd, &rcClient);
// Create listbox
HWND hList;
hList = CreateWindowEx(WS_EX_CLIENTEDGE,
TEXT("LISTBOX"),
TEXT(""),
WS_CHILD|WS_VISIBLE|WS_VSCROLL|WS_HSCROLL|LBS_SORT|LBS_NOINTEGRALHEIGHT,
0,
0,
rcClient.right,
rcClient.bottom-25,
hWnd,
(HMENU)WINDOW_LISTBOX,
hInstance,
NULL);
// Check for failure
if(!hList)
{
MessageBox(hWnd, TEXT("Could not create list box."), TEXT("Error"), MB_OK | MB_ICONERROR);
return FALSE;
}
// Allow Horizontal Scrolling
SendMessage(hList, LB_SETHORIZONTALEXTENT, 1920, NULL);
// Populate the list
EnumWindows(PopulateWindowsEnumProc, (LPARAM)hWnd);
// Create the apply button
HWND hButton;
hButton = CreateWindowEx(WS_EX_CLIENTEDGE,
TEXT("BUTTON"),
TEXT("Apply"),
WS_CHILDWINDOW|WS_VISIBLE|BS_PUSHBUTTON,
rcClient.right-100,
rcClient.bottom-25,
100,
25,
hWnd,
(HMENU)APPLY_BUTTON,
hInstance,
NULL);
// Check for failure
if(!hButton)
{
MessageBox(hWnd, TEXT("Could not create button."), TEXT("Error"), MB_OK | MB_ICONERROR);
return FALSE;
}
// Create the desktop selection menu
HWND hDesktopBox;
hDesktopBox = CreateWindowEx(WS_EX_CLIENTEDGE,
TEXT("COMBOBOX"),
TEXT(""),
WS_CHILDWINDOW|WS_VISIBLE|CBS_DROPDOWNLIST|CBS_HASSTRINGS,
0,
rcClient.bottom-25,
rcClient.right-100,
125,
hWnd,
(HMENU)DESKTOP_COMBOBOX,
hInstance,
NULL);
// Check for failure
if(!hDesktopBox)
{
MessageBox(hWnd, TEXT("Could not create combo box."), TEXT("Error"), MB_OK | MB_ICONERROR);
return FALSE;
}
// Populate combo box
EnumDisplayMonitors(NULL, NULL, PopulateDesktopsEnumProc, (LPARAM)hWnd);
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
while(GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(
HWND hWnd,
UINT msg,
WPARAM wParam,
LPARAM lParam
)
{
switch(msg)
{
case WM_CREATE:
{
break;
}
case WM_COMMAND:
{
switch(LOWORD(wParam))
{
case APPLY_BUTTON:
{
int index;
HWND targetWindow;
HMONITOR targetDesktop;
MONITORINFO desktopInfo;
LPRECT desktopRect;
// Get the index of the selected window in the list
index = SendDlgItemMessage(hWnd, WINDOW_LISTBOX, LB_GETCURSEL, NULL, NULL);
// Make sure we have selected a window
if(index == LB_ERR)
{
MessageBox(hWnd, TEXT("Must select a window."), TEXT("Error"), MB_OK | MB_ICONERROR);
return FALSE;
}
// Get the handle to the window that we want to modify from the selected item
targetWindow = (HWND)SendDlgItemMessage(hWnd, WINDOW_LISTBOX, LB_GETITEMDATA, index, NULL);
// Get the index of the selected desktop in the combo box
index = SendDlgItemMessage(hWnd, DESKTOP_COMBOBOX, CB_GETCURSEL, NULL, NULL);
// Make sure we have selected a desktop
if(index == CB_ERR)
{
MessageBox(hWnd, TEXT("Must select a desktop."), TEXT("Error"), MB_OK | MB_ICONERROR);
return FALSE;
}
// Get the handle to the desktop we want to place the window on
targetDesktop = (HMONITOR)SendDlgItemMessage(hWnd, DESKTOP_COMBOBOX, CB_GETITEMDATA, index, NULL);
//desktopRect = (LPRECT)SendDlgItemMessage(hWnd, DESKTOP_COMBOBOX, CB_GETITEMDATA, index, NULL);
// Get a pointer to the rectangle describing the desktop
desktopInfo.cbSize = sizeof(MONITORINFO);
GetMonitorInfo(targetDesktop, &desktopInfo);
desktopRect = &(desktopInfo.rcMonitor);
// Get the old style
DWORD newStyle, oldStyle;
oldStyle = GetWindowLong(targetWindow, GWL_STYLE);
// Apply changes
newStyle = oldStyle ^ 0x00C00000L;
SetWindowLong(targetWindow, GWL_STYLE, newStyle);
SetWindowPos(targetWindow,
NULL,
desktopRect->left,
desktopRect->top,
desktopRect->right - desktopRect->left,
desktopRect->bottom - desktopRect->top,
SWP_DRAWFRAME|SWP_FRAMECHANGED|SWP_NOZORDER|SWP_NOACTIVATE);
InvalidateRect(targetWindow, NULL, TRUE);
break;
}
}
break;
}
case WM_SIZE:
{
HWND hList;
HWND hButton;
HWND hCombo;
RECT rcClient;
GetClientRect(hWnd, &rcClient);
// Set appropriate dimensions for when the window is resized
hList = GetDlgItem(hWnd, WINDOW_LISTBOX);
SetWindowPos(hList, NULL, 0, 0, rcClient.right, rcClient.bottom-25, SWP_NOZORDER);
hButton = GetDlgItem(hWnd, APPLY_BUTTON);
SetWindowPos(hButton, NULL, rcClient.right-100, rcClient.bottom-25, 100, 25, SWP_NOZORDER);
hCombo = GetDlgItem(hWnd, DESKTOP_COMBOBOX);
SetWindowPos(hCombo, NULL, 0, rcClient.bottom-25, rcClient.right-100, 125, SWP_NOZORDER);
break;
}
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
// Populates our WINDOW_LISTBOX with every window that does not have an empty title.
// Ideally, we could use the icons and the .exe file to identify, but those are non-trivial
// in comparison to the title.
BOOL CALLBACK PopulateWindowsEnumProc(HWND hWnd, LPARAM lParam)
{
// Adjust this length
WCHAR fileName[512];
//GetWindowModuleFileName(hWnd,fileName,512);
// Get the title
SendMessage(hWnd, WM_GETTEXT, MAX_PATH, (LPARAM)fileName);
// Remove Windows without titles
if(fileName[0]!='\0')
{
// Add the item to the listbox
int index = SendDlgItemMessage((HWND)lParam, WINDOW_LISTBOX, LB_ADDSTRING, 0, (LPARAM)fileName);
// Add the window handle as the item data. This may not be safe on x64 machines because
// the data is required to be 32 bit and I'm not positive hWnd has the same requirements.
SendDlgItemMessage((HWND)lParam, WINDOW_LISTBOX, LB_SETITEMDATA, index, (LPARAM)hWnd);
}
return TRUE;
}
BOOL CALLBACK PopulateDesktopsEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM lParam)
{
// Surely no one has more than 10^4 monitors... right?
WCHAR displayID[4];
int index;
// Get the desktop number by looking at the number of items currently in the combo box
index = SendDlgItemMessage((HWND)lParam, DESKTOP_COMBOBOX, CB_GETCOUNT, NULL, NULL);
// Convert the index into a string
_itow_s(index, displayID, 10);
// Add an item to the combo box
index = SendDlgItemMessage((HWND)lParam, DESKTOP_COMBOBOX, CB_ADDSTRING, NULL, (LPARAM)displayID);
// Attach the data to the combo box as the item data
SendDlgItemMessage((HWND)lParam, DESKTOP_COMBOBOX, CB_SETITEMDATA, index, (LPARAM)hMonitor);
return TRUE;
}<|endoftext|>
|
<commit_before>
#include <iostream>
#include <libxml/parser.h>
#include <libxml/xmlerror.h>
#include <mathmlconfig.h>
void structuredErrorCallback(void *userData, xmlErrorPtr error)
{
std::string errorString = std::string(error->message);
// Swap libxml2 carriage return for a period.
if (errorString.substr(errorString.length() - 1) == "\n") {
errorString.replace(errorString.end() - 1, errorString.end(), ".");
}
std::cout << errorString << std::endl;
}
int main(int argc, char *argv[])
{
const std::string input = "<math><ci cellml:units=\"dimensionless\">B</ci></math>";
const std::string mathmlDtd = "<!DOCTYPE math SYSTEM \"" + libcellml::LIBCELLML_MATHML_DTD_LOCATION + "\">";
std::string mathmlString = mathmlDtd + input;
xmlInitParser();
xmlParserCtxtPtr context = xmlNewParserCtxt();
xmlSetStructuredErrorFunc(context, structuredErrorCallback);
xmlDocPtr xmlDoc = xmlCtxtReadDoc(context, reinterpret_cast<const xmlChar *>(mathmlString.c_str()), "/", nullptr, XML_PARSE_DTDVALID);
xmlFreeParserCtxt(context);
xmlSetStructuredErrorFunc(nullptr, nullptr);
xmlFreeDoc(xmlDoc);
xmlCleanupParser();
xmlCleanupGlobals();
}
<commit_msg>Remove cmake/test_libxml2.cpp file.<commit_after><|endoftext|>
|
<commit_before><commit_msg>Ajokki: bind `mini_console` to `my_font_2d`.<commit_after><|endoftext|>
|
<commit_before>/**
* This file is part of the "FnordStream" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* Licensed under the MIT license (see LICENSE).
*/
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include "database.h"
#include "pagemanager.h"
#include "cursor.h"
namespace fnordmetric {
namespace database {
// TODO test freelist serialization / after file reloads
// TODO test in memory db
class DatabaseTest {
public:
DatabaseTest() {}
void run() {
//testStreamIdAssignment();
//testStreamRefCreation();
testPageManager();
testMmapPageManager();
testOpenFile();
}
void testStreamIdAssignment() {
auto backend = fnordmetric::database::Database::openFile(
"/tmp/__fnordmetric_testStreamIdAssignment",
database::MODE_CONSERVATIVE | database::FILE_TRUNCATE);
std::string key1 = "83d2f71c457206bf-Ia9f37ed7-F76b77d1a";
std::string key2 = "83d2f71c457216bf-Ia9f37ed7-F76b77d1a";
assert(backend->getStreamId(key1) == 1);
assert(backend->getStreamId(key2) == 2);
assert(backend->getStreamId(key1) == 1);
assert(backend->getStreamId(key2) == 2);
}
void testStreamRefCreation() {
auto backend = fnordmetric::database::Database::openFile(
"/tmp/__fnordmetric_testStreamRefCreation",
database::MODE_CONSERVATIVE | database::FILE_TRUNCATE |
database::FILE_AUTODELETE);
std::string key1 = "83d2f71c457206bf-Ia9f37ed7-F76b77d1a";
std::string key2 = "83d2f71c457216bf-Ia9f37ed7-F76b77d1a";
auto ref1 = backend->openStream(key1);
assert(ref1.get() != nullptr);
auto ref2 = backend->openStream(key1);
assert(ref1.get() == ref2.get());
auto ref3 = backend->openStream(key2);
assert(ref1.get() != ref3.get());
assert(ref2.get() != ref3.get());
auto ref4 = backend->openStream(key2);
assert(ref1.get() != ref4.get());
assert(ref2.get() != ref4.get());
assert(ref3.get() == ref4.get());
}
void testPageManager() {
class ConcreteTestPageManager : public PageManager {
public:
ConcreteTestPageManager() : PageManager(4096) {}
std::unique_ptr<PageRef> getPage(const PageManager::Page& page) override {
return std::unique_ptr<PageRef>(nullptr);
}
};
ConcreteTestPageManager page_manager;
auto page1 = page_manager.allocPage(3000);
assert(page_manager.end_pos_ == 4096);
assert(page1.offset == 0);
assert(page1.size == 4096);
page_manager.freePage(page1);
auto page2 = page_manager.allocPage(8000);
assert(page_manager.end_pos_ == 12288);
assert(page2.offset == 4096);
assert(page2.size == 8192);
auto page3 = page_manager.allocPage(3000);
assert(page3.offset == 0);
assert(page3.size == 4096);
page_manager.freePage(page2);
auto page4 = page_manager.allocPage(4000);
assert(page_manager.end_pos_ == 12288);
assert(page4.offset == 4096);
assert(page4.size == 8192);
}
void testMmapPageManager() {
int fd = open("/tmp/__fnordmetric_testMmapPageManager",
O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);
assert(fd > 0);
unlink("/tmp/__fnordmetric_testMmapPageManager");
auto page_manager = new MmapPageManager(fd, 0, 4096);
auto mfile1 = page_manager->getMmapedFile(3000);
auto mfile2 = page_manager->getMmapedFile(304200);
assert(mfile1->size == 1048576);
assert(mfile1 == mfile2);
mfile2->incrRefs();
auto mfile3 = page_manager->getMmapedFile(1048577);
assert(mfile3->size == 1048576 * 2);
assert(mfile3 != mfile2);
mfile2->decrRefs();
delete page_manager;
close(fd);
}
void testOpenFile() {
//printf("TEST: File backed database insert, reopen, read\n");
uint32_t stream_id;
std::vector<fnordmetric::database::StreamPosition> insert_times;
std::vector<Field> fields = {
fnordmetric::IntegerField("sequence_num"),
fnordmetric::IntegerField("test1"),
fnordmetric::StringField("test2")};
Schema schema(fields);
int rows_written = 0;
for (int j = 0; j < 50; ++j) {
int flags = database::MODE_CONSERVATIVE;
if (j == 0) { flags |= database::FILE_TRUNCATE; }
//if (j == 49) { flags |= database::FILE_AUTODELETE; }
auto database = fnordmetric::database::Database::openFile(
"/tmp/__fnordmetric_testOpenFile",
flags);
assert(database.get() != nullptr);
auto stream = database->openStream("mystream");
if (j == 0) {
stream_id = stream->stream_id_;
} else {
assert(stream_id == stream->stream_id_);
}
assert(database->max_stream_id_ == stream_id);
RecordWriter record_writer(schema);
for (int i = (j + 1) * 1000; i > 0; i--) {
record_writer.setIntegerField(0, ++rows_written);
record_writer.setIntegerField(1, 1337);
record_writer.setStringField(2, "fnordbar", 8);
auto new_row_pos = stream->appendRow(record_writer);
if (insert_times.size() > 0) {
assert(
new_row_pos.logical_offset > insert_times.back().logical_offset);
}
insert_times.push_back(new_row_pos);
record_writer.reset();
}
auto cursor = stream->getCursor();
assert(cursor->seekToFirst() == insert_times[0]);
RecordReader record_reader(schema);
for (int i = 0; i < insert_times.size() - 1; ++i) {
auto row = cursor->getCurrentRow();
assert(cursor->getCurrentPosition() == insert_times[i]);
assert(row->time == insert_times[i].unix_millis);
assert(cursor->next());
assert(record_reader.getIntegerField(row->data, 0) == i+1);
assert(record_reader.getIntegerField(row->data, 1) == 1337);
char* str;
size_t str_len;
record_reader.getStringField(row->data, 2, &str, &str_len);
assert(str_len == 8);
assert(strncmp(str, "fnordbar", str_len) == 0);
}
assert(cursor->next() == false);
}
}
};
}
}
int main() {
fnordmetric::database::DatabaseTest test;
test.run();
printf("all tests passed! :)\n");
}
<commit_msg>include fix<commit_after>/**
* This file is part of the "FnordStream" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* Licensed under the MIT license (see LICENSE).
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include "database.h"
#include "pagemanager.h"
#include "cursor.h"
namespace fnordmetric {
namespace database {
// TODO test freelist serialization / after file reloads
// TODO test in memory db
class DatabaseTest {
public:
DatabaseTest() {}
void run() {
//testStreamIdAssignment();
//testStreamRefCreation();
testPageManager();
testMmapPageManager();
testOpenFile();
}
void testStreamIdAssignment() {
auto backend = fnordmetric::database::Database::openFile(
"/tmp/__fnordmetric_testStreamIdAssignment",
database::MODE_CONSERVATIVE | database::FILE_TRUNCATE);
std::string key1 = "83d2f71c457206bf-Ia9f37ed7-F76b77d1a";
std::string key2 = "83d2f71c457216bf-Ia9f37ed7-F76b77d1a";
assert(backend->getStreamId(key1) == 1);
assert(backend->getStreamId(key2) == 2);
assert(backend->getStreamId(key1) == 1);
assert(backend->getStreamId(key2) == 2);
}
void testStreamRefCreation() {
auto backend = fnordmetric::database::Database::openFile(
"/tmp/__fnordmetric_testStreamRefCreation",
database::MODE_CONSERVATIVE | database::FILE_TRUNCATE |
database::FILE_AUTODELETE);
std::string key1 = "83d2f71c457206bf-Ia9f37ed7-F76b77d1a";
std::string key2 = "83d2f71c457216bf-Ia9f37ed7-F76b77d1a";
auto ref1 = backend->openStream(key1);
assert(ref1.get() != nullptr);
auto ref2 = backend->openStream(key1);
assert(ref1.get() == ref2.get());
auto ref3 = backend->openStream(key2);
assert(ref1.get() != ref3.get());
assert(ref2.get() != ref3.get());
auto ref4 = backend->openStream(key2);
assert(ref1.get() != ref4.get());
assert(ref2.get() != ref4.get());
assert(ref3.get() == ref4.get());
}
void testPageManager() {
class ConcreteTestPageManager : public PageManager {
public:
ConcreteTestPageManager() : PageManager(4096) {}
std::unique_ptr<PageRef> getPage(const PageManager::Page& page) override {
return std::unique_ptr<PageRef>(nullptr);
}
};
ConcreteTestPageManager page_manager;
auto page1 = page_manager.allocPage(3000);
assert(page_manager.end_pos_ == 4096);
assert(page1.offset == 0);
assert(page1.size == 4096);
page_manager.freePage(page1);
auto page2 = page_manager.allocPage(8000);
assert(page_manager.end_pos_ == 12288);
assert(page2.offset == 4096);
assert(page2.size == 8192);
auto page3 = page_manager.allocPage(3000);
assert(page3.offset == 0);
assert(page3.size == 4096);
page_manager.freePage(page2);
auto page4 = page_manager.allocPage(4000);
assert(page_manager.end_pos_ == 12288);
assert(page4.offset == 4096);
assert(page4.size == 8192);
}
void testMmapPageManager() {
int fd = open("/tmp/__fnordmetric_testMmapPageManager",
O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);
assert(fd > 0);
unlink("/tmp/__fnordmetric_testMmapPageManager");
auto page_manager = new MmapPageManager(fd, 0, 4096);
auto mfile1 = page_manager->getMmapedFile(3000);
auto mfile2 = page_manager->getMmapedFile(304200);
assert(mfile1->size == 1048576);
assert(mfile1 == mfile2);
mfile2->incrRefs();
auto mfile3 = page_manager->getMmapedFile(1048577);
assert(mfile3->size == 1048576 * 2);
assert(mfile3 != mfile2);
mfile2->decrRefs();
delete page_manager;
close(fd);
}
void testOpenFile() {
//printf("TEST: File backed database insert, reopen, read\n");
uint32_t stream_id;
std::vector<fnordmetric::database::StreamPosition> insert_times;
std::vector<Field> fields = {
fnordmetric::IntegerField("sequence_num"),
fnordmetric::IntegerField("test1"),
fnordmetric::StringField("test2")};
Schema schema(fields);
int rows_written = 0;
for (int j = 0; j < 50; ++j) {
int flags = database::MODE_CONSERVATIVE;
if (j == 0) { flags |= database::FILE_TRUNCATE; }
//if (j == 49) { flags |= database::FILE_AUTODELETE; }
auto database = fnordmetric::database::Database::openFile(
"/tmp/__fnordmetric_testOpenFile",
flags);
assert(database.get() != nullptr);
auto stream = database->openStream("mystream");
if (j == 0) {
stream_id = stream->stream_id_;
} else {
assert(stream_id == stream->stream_id_);
}
assert(database->max_stream_id_ == stream_id);
RecordWriter record_writer(schema);
for (int i = (j + 1) * 1000; i > 0; i--) {
record_writer.setIntegerField(0, ++rows_written);
record_writer.setIntegerField(1, 1337);
record_writer.setStringField(2, "fnordbar", 8);
auto new_row_pos = stream->appendRow(record_writer);
if (insert_times.size() > 0) {
assert(
new_row_pos.logical_offset > insert_times.back().logical_offset);
}
insert_times.push_back(new_row_pos);
record_writer.reset();
}
auto cursor = stream->getCursor();
assert(cursor->seekToFirst() == insert_times[0]);
RecordReader record_reader(schema);
for (int i = 0; i < insert_times.size() - 1; ++i) {
auto row = cursor->getCurrentRow();
assert(cursor->getCurrentPosition() == insert_times[i]);
assert(row->time == insert_times[i].unix_millis);
assert(cursor->next());
assert(record_reader.getIntegerField(row->data, 0) == i+1);
assert(record_reader.getIntegerField(row->data, 1) == 1337);
char* str;
size_t str_len;
record_reader.getStringField(row->data, 2, &str, &str_len);
assert(str_len == 8);
assert(strncmp(str, "fnordbar", str_len) == 0);
}
assert(cursor->next() == false);
}
}
};
}
}
int main() {
fnordmetric::database::DatabaseTest test;
test.run();
printf("all tests passed! :)\n");
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.