text
stringlengths 54
60.6k
|
|---|
<commit_before>/*****************************************************************************
* icon_view.cpp : Icon view for the Playlist
****************************************************************************
* Copyright © 2010 the VideoLAN team
* $Id$
*
* Authors: Jean-Baptiste Kempf <jb@videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "components/playlist/icon_view.hpp"
#include "components/playlist/playlist_model.hpp"
#include "input_manager.hpp"
#include <QApplication>
#include <QPainter>
#include <QRect>
#include <QStyleOptionViewItem>
#include <QFontMetrics>
#include <QPixmapCache>
#include "assert.h"
#define RECT_SIZE 100
#define ART_SIZE 64
#define OFFSET (RECT_SIZE-64)/2
#define ITEMS_SPACING 10
#define ART_RADIUS 5
static const QRect drawRect = QRect( 0, 0, RECT_SIZE, RECT_SIZE );
static const QRect artRect = drawRect.adjusted( OFFSET - 1, 0, - OFFSET, - OFFSET *2 );
void PlListViewItemDelegate::paint( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
PLItem *currentItem = static_cast<PLItem*>( index.internalPointer() );
assert( currentItem );
char *meta;
meta = input_item_GetTitleFbName( currentItem->inputItem() );
QString title = qfu( meta );
free( meta );
meta = input_item_GetArtist( currentItem->inputItem() );
QString artist = qfu( meta );
free( meta );
QString artUrl = InputManager::decodeArtURL( currentItem->inputItem() );
// look up through all children and use the first picture found
if( artUrl.isEmpty() )
{
int children = currentItem->childCount();
for( int i = 0; i < children; i++ )
{
PLItem *child = currentItem->child( i );
artUrl = InputManager::decodeArtURL( child->inputItem() );
if( !artUrl.isEmpty() )
break;
}
}
/*if( option.state & QStyle::State_Selected )
painter->fillRect(option.rect, option.palette.highlight());*/
QApplication::style()->drawPrimitive( QStyle::PE_PanelItemViewItem, &option,
painter );
// picture where all the rendering happens and which will be cached
QPixmap pix;
QString key = title + artist + artUrl
+ QString( index.data( PLModel::IsCurrentRole ).toInt() );
if(QPixmapCache::find( key, pix ))
{
// cool, we found it in the cache
painter->drawPixmap( option.rect, pix );
return;
}
// load album art
QPixmap artPix;
if( artUrl.isEmpty() || !artPix.load( artUrl ) )
artPix = QPixmap( ":/noart64" );
else
artPix = artPix.scaled( ART_SIZE, ART_SIZE,
Qt::KeepAspectRatioByExpanding );
pix = QPixmap( RECT_SIZE, RECT_SIZE );
pix.fill( Qt::transparent );
QPainter *pixpainter = new QPainter( &pix );
pixpainter->setRenderHints(
QPainter::Antialiasing | QPainter::SmoothPixmapTransform );
// Draw the drop shadow
pixpainter->save();
pixpainter->setOpacity( 0.7 );
pixpainter->setBrush( QBrush( Qt::gray ) );
pixpainter->drawRoundedRect( artRect.adjusted( 2, 2, 2, 2 ), ART_RADIUS, ART_RADIUS );
pixpainter->restore();
// Draw the art pix
QPainterPath artRectPath;
artRectPath.addRoundedRect( artRect, ART_RADIUS, ART_RADIUS );
pixpainter->setClipPath( artRectPath );
pixpainter->drawPixmap( artRect, artPix );
pixpainter->setClipping( false );
QColor text = qApp->palette().text().color();
// Draw title
pixpainter->setPen( text );
QFont font;
font.setPointSize( 7 );
font.setItalic(true);
font.setBold( index.data( Qt::FontRole ).value<QFont>().bold() );
pixpainter->setFont( font );
QFontMetrics fm = pixpainter->fontMetrics();
QRect textRect = drawRect.adjusted( 1, ART_SIZE + 4, 0, -1 );
textRect.setHeight( fm.height() + 2 );
pixpainter->drawText( textRect,
fm.elidedText( title, Qt::ElideRight, textRect.width() ),
QTextOption( Qt::AlignCenter ) );
// Draw artist
pixpainter->setPen( text.lighter( 240 ) );
font.setItalic( false );
pixpainter->setFont( font );
fm = pixpainter->fontMetrics();
textRect = textRect.adjusted( 0, textRect.height(),
0, textRect.height() );
pixpainter->drawText( textRect,
fm.elidedText( artist, Qt::ElideRight, textRect.width() ),
QTextOption( Qt::AlignCenter ) );
delete pixpainter; // Ensure all paint operations have finished
// Here real drawing happens
painter->drawPixmap( option.rect, pix );
// Cache the rendering
QPixmapCache::insert( key, pix );
}
QSize PlListViewItemDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
return QSize( RECT_SIZE, RECT_SIZE);
}
PlIconView::PlIconView( PLModel *model, QWidget *parent ) : QListView( parent )
{
setModel( model );
setViewMode( QListView::IconMode );
setMovement( QListView::Static );
setResizeMode( QListView::Adjust );
setGridSize( QSize( RECT_SIZE, RECT_SIZE ) );
setUniformItemSizes( true );
setSpacing( ITEMS_SPACING );
setWrapping( true );
setSelectionMode( QAbstractItemView::ExtendedSelection );
setAcceptDrops( true );
PlListViewItemDelegate *pl = new PlListViewItemDelegate();
setItemDelegate( pl );
}
<commit_msg>qt4: show more clearly current item in iconview<commit_after>/*****************************************************************************
* icon_view.cpp : Icon view for the Playlist
****************************************************************************
* Copyright © 2010 the VideoLAN team
* $Id$
*
* Authors: Jean-Baptiste Kempf <jb@videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "components/playlist/icon_view.hpp"
#include "components/playlist/playlist_model.hpp"
#include "input_manager.hpp"
#include <QApplication>
#include <QPainter>
#include <QRect>
#include <QStyleOptionViewItem>
#include <QFontMetrics>
#include <QPixmapCache>
#include "assert.h"
#define RECT_SIZE 100
#define ART_SIZE 64
#define OFFSET (RECT_SIZE-64)/2
#define ITEMS_SPACING 10
#define ART_RADIUS 5
static const QRect drawRect = QRect( 0, 0, RECT_SIZE, RECT_SIZE );
static const QRect artRect = drawRect.adjusted( OFFSET - 1, 0, - OFFSET, - OFFSET *2 );
void PlListViewItemDelegate::paint( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
PLItem *currentItem = static_cast<PLItem*>( index.internalPointer() );
assert( currentItem );
char *meta;
meta = input_item_GetTitleFbName( currentItem->inputItem() );
QString title = qfu( meta );
free( meta );
meta = input_item_GetArtist( currentItem->inputItem() );
QString artist = qfu( meta );
free( meta );
QString artUrl = InputManager::decodeArtURL( currentItem->inputItem() );
// look up through all children and use the first picture found
if( artUrl.isEmpty() )
{
int children = currentItem->childCount();
for( int i = 0; i < children; i++ )
{
PLItem *child = currentItem->child( i );
artUrl = InputManager::decodeArtURL( child->inputItem() );
if( !artUrl.isEmpty() )
break;
}
}
/*if( option.state & QStyle::State_Selected )
painter->fillRect(option.rect, option.palette.highlight());*/
QApplication::style()->drawPrimitive( QStyle::PE_PanelItemViewItem, &option,
painter );
// picture where all the rendering happens and which will be cached
QPixmap pix;
QString key = title + artist + artUrl
+ QString( index.data( PLModel::IsCurrentRole ).toInt() );
if(QPixmapCache::find( key, pix ))
{
// cool, we found it in the cache
painter->drawPixmap( option.rect, pix );
return;
}
// load album art
QPixmap artPix;
if( artUrl.isEmpty() || !artPix.load( artUrl ) )
artPix = QPixmap( ":/noart64" );
else
artPix = artPix.scaled( ART_SIZE, ART_SIZE,
Qt::KeepAspectRatioByExpanding );
pix = QPixmap( RECT_SIZE, RECT_SIZE );
pix.fill( Qt::transparent );
QPainter *pixpainter = new QPainter( &pix );
pixpainter->setRenderHints(
QPainter::Antialiasing | QPainter::SmoothPixmapTransform |
QPainter::TextAntialiasing );
if( index.data( PLModel::IsCurrentRole ).toInt() > 0 )
{
pixpainter->save();
pixpainter->setOpacity( 0.2 );
pixpainter->setBrush( QBrush( Qt::gray ) );
pixpainter->drawRoundedRect( 0, -1, RECT_SIZE, RECT_SIZE+1, ART_RADIUS, ART_RADIUS );
pixpainter->restore();
}
// Draw the drop shadow
pixpainter->save();
pixpainter->setOpacity( 0.7 );
pixpainter->setBrush( QBrush( Qt::gray ) );
pixpainter->drawRoundedRect( artRect.adjusted( 2, 2, 2, 2 ), ART_RADIUS, ART_RADIUS );
pixpainter->restore();
// Draw the art pix
QPainterPath artRectPath;
artRectPath.addRoundedRect( artRect, ART_RADIUS, ART_RADIUS );
pixpainter->setClipPath( artRectPath );
pixpainter->drawPixmap( artRect, artPix );
pixpainter->setClipping( false );
QColor text = qApp->palette().text().color();
// Draw title
pixpainter->setPen( text );
QFont font;
font.setPointSize( 7 );
font.setItalic(true);
font.setBold( index.data( Qt::FontRole ).value<QFont>().bold() );
pixpainter->setFont( font );
QFontMetrics fm = pixpainter->fontMetrics();
QRect textRect = drawRect.adjusted( 1, ART_SIZE + 4, 0, -1 );
textRect.setHeight( fm.height() + 2 );
pixpainter->drawText( textRect,
fm.elidedText( title, Qt::ElideRight, textRect.width() ),
QTextOption( Qt::AlignCenter ) );
// Draw artist
pixpainter->setPen( text.lighter( 240 ) );
font.setItalic( false );
pixpainter->setFont( font );
fm = pixpainter->fontMetrics();
textRect = textRect.adjusted( 0, textRect.height(),
0, textRect.height() );
pixpainter->drawText( textRect,
fm.elidedText( artist, Qt::ElideRight, textRect.width() ),
QTextOption( Qt::AlignCenter ) );
delete pixpainter; // Ensure all paint operations have finished
// Here real drawing happens
painter->drawPixmap( option.rect, pix );
// Cache the rendering
QPixmapCache::insert( key, pix );
}
QSize PlListViewItemDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
return QSize( RECT_SIZE, RECT_SIZE);
}
PlIconView::PlIconView( PLModel *model, QWidget *parent ) : QListView( parent )
{
setModel( model );
setViewMode( QListView::IconMode );
setMovement( QListView::Static );
setResizeMode( QListView::Adjust );
setGridSize( QSize( RECT_SIZE, RECT_SIZE ) );
setUniformItemSizes( true );
setSpacing( ITEMS_SPACING );
setWrapping( true );
setSelectionMode( QAbstractItemView::ExtendedSelection );
setAcceptDrops( true );
PlListViewItemDelegate *pl = new PlListViewItemDelegate();
setItemDelegate( pl );
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// The Loki Library
// Copyright (c) 2005 Richard Sposato
// Copyright (c) 2005 Peter Kmmel
// Permission to use, copy, modify, distribute and sell this software for any
// purpose is hereby granted without fee, provided that the above copyright
// notice appear in all copies and that both that copyright notice and this
// permission notice appear in supporting documentation.
// The authors make no representations about the
// suitability of this software for any purpose. It is provided "as is"
// without express or implied warranty.
////////////////////////////////////////////////////////////////////////////////
// $Header$
#include "../../include/loki/SmallObj.h"
#include "../../include/loki/Singleton.h"
#include <iostream>
// define DO_EXTRA_LOKI_TESTS in src/SmallObj.cpp to get
// a message when a SmallObject is created/deleted.
using namespace std;
// ----------------------------------------------------------------------------
//
// LongevityLifetime Parent/Child policies
//
// ----------------------------------------------------------------------------
typedef Loki::SmallValueObject< LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL,
LOKI_DEFAULT_CHUNK_SIZE, LOKI_MAX_SMALL_OBJECT_SIZE,
LOKI_DEFAULT_OBJECT_ALIGNMENT,
Loki::LongevityLifetime::DieAsSmallObjectParent
>
SmallObjectParent;
class SmallObjectChild : public SmallObjectParent
{
public:
typedef Loki::SingletonHolder< SmallObjectChild, Loki::CreateUsingNew,
Loki::LongevityLifetime::DieAsSmallObjectChild>
MySmallSingleton;
/// Returns reference to the singleton.
inline static SmallObjectChild & Instance( void )
{
return MySmallSingleton::Instance();
}
SmallObjectChild( void )
{
cout << "SmallObjectChild created" << endl;
}
~SmallObjectChild( void )
{
cout << "~SmallObjectChild" << endl;
}
void DoThat( void )
{
cout << "SmallObjectChild::DoThat" << endl << endl;
}
private:
char m_stuff[ 16 ];
};
// ----------------------------------------------------------------------------
//
// SingletonWithLongevity policy
//
// ----------------------------------------------------------------------------
typedef Loki::SmallValueObject< LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL,
LOKI_DEFAULT_CHUNK_SIZE, LOKI_MAX_SMALL_OBJECT_SIZE,
LOKI_DEFAULT_OBJECT_ALIGNMENT,
Loki::SingletonWithLongevity
>
LongLivedObject;
class LongLivedSingleton : public LongLivedObject
{
public:
typedef Loki::SingletonHolder< LongLivedSingleton, Loki::CreateUsingNew,
Loki::SingletonWithLongevity>
MySmallSingleton;
/// Returns reference to the singleton.
inline static LongLivedSingleton & Instance( void )
{
return MySmallSingleton::Instance();
}
LongLivedSingleton( void )
{
cout << "LongLivedSingleton created" << endl;
}
~LongLivedSingleton( void )
{
cout << "~LongLivedSingleton" << endl;
}
void DoThat( void )
{
cout << "LongLivedSingleton::DoThat" << endl << endl;
}
private:
char m_stuff[ 16 ];
};
inline unsigned int GetLongevity( LongLivedSingleton * )
{
/// @note Must return a longevity level lower than the one in SmallObj.h.
return 1;
}
#if !defined(_MSC_VER) || (_MSC_VER>=1400)
// ----------------------------------------------------------------------------
//
// FollowIntoDeath policy
//
// ----------------------------------------------------------------------------
typedef Loki::SmallValueObject< LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL,
LOKI_DEFAULT_CHUNK_SIZE, LOKI_MAX_SMALL_OBJECT_SIZE,
LOKI_DEFAULT_OBJECT_ALIGNMENT,
Loki::FollowIntoDeath::With<Loki::DefaultLifetime>::AsMasterLifetime
>
MasterObject;
class FollowerSingleton : public MasterObject
{
public:
typedef Loki::SingletonHolder< FollowerSingleton, Loki::CreateUsingNew,
Loki::FollowIntoDeath::AfterMaster<FollowerSingleton::ObjAllocatorSingleton>::IsDestroyed>
MySmallSingleton;
/// Returns reference to the singleton.
inline static FollowerSingleton & Instance( void )
{
return MySmallSingleton::Instance();
}
FollowerSingleton( void )
{
cout << "FollowerSingleton created" << endl;
}
~FollowerSingleton( void )
{
cout << "~FollowerSingleton" << endl;
}
void DoThat( void )
{
cout << "FollowerSingleton::DoThat" << endl << endl;
}
private:
char m_stuff[ 16 ];
};
#endif
// ----------------------------------------------------------------------------
//
// NoDestroy policy
//
// ----------------------------------------------------------------------------
typedef Loki::SmallValueObject< LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL,
LOKI_DEFAULT_CHUNK_SIZE, LOKI_MAX_SMALL_OBJECT_SIZE,
LOKI_DEFAULT_OBJECT_ALIGNMENT, Loki::NoDestroy >
ImmortalObject;
class ImmortalSingleton : public ImmortalObject
{
public:
typedef Loki::SingletonHolder< ImmortalSingleton, Loki::CreateUsingNew,
Loki::NoDestroy>
MySmallSingleton;
/// Returns reference to the singleton.
inline static ImmortalSingleton & Instance( void )
{
return MySmallSingleton::Instance();
}
ImmortalSingleton( void )
{
cout << "ImmortalSingleton created" << endl;
}
~ImmortalSingleton( void )
{
cout << "~ImmortalSingleton destructor should never get called!" << endl;
}
void DoThat( void )
{
cout << "ImmortalSingleton::DoThat" << endl << endl;
}
private:
char m_stuff[ 16 ];
};
// ----------------------------------------------------------------------------
//
// NoDestroy and SingletonWithLongevity policy combination
//
// ----------------------------------------------------------------------------
class MortalSingleton : public ImmortalObject
{
public:
typedef Loki::SingletonHolder< MortalSingleton, Loki::CreateUsingNew,
Loki::SingletonWithLongevity>
MySmallSingleton;
/// Returns reference to the singleton.
inline static MortalSingleton & Instance( void )
{
return MySmallSingleton::Instance();
}
MortalSingleton( void )
{
cout << "MortalSingleton created" << endl;
}
~MortalSingleton( void )
{
cout << "~MortalSingleton" << endl;
}
void DoThat( void )
{
cout << "MortalSingleton::DoThat" << endl << endl;
}
private:
char m_stuff[ 16 ];
};
inline unsigned int GetLongevity( MortalSingleton * )
{
/// @note Must return a longevity level lower than the one in SmallObj.h.
return 1;
}
// ----------------------------------------------------------------------------
//
// detect memory leaks on MSVC Ide
//
// ----------------------------------------------------------------------------
//#define LOKI_MSVC_CHECK_FOR_MEMORY_LEAKS
#ifdef LOKI_MSVC_CHECK_FOR_MEMORY_LEAKS
#include <crtdbg.h>
#include <cassert>
void heap_debug()
{
int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
// Turn on leak-checking bit
tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
//tmpFlag |= _CRTDBG_CHECK_MasterLWMasterYS_DF;
// Turn off CRT block checking bit
tmpFlag &= ~_CRTDBG_CHECK_CRT_DF;
// Set flag to the new value
_CrtSetDbgFlag( tmpFlag );
}
#else
void heap_debug()
{}
#endif
// ----------------------------------------------------------------------------
//
// main
//
// ----------------------------------------------------------------------------
int main()
{
heap_debug();
cout << endl
<< "This program tests the lifetime policies for Loki's " << endl
<< "Small-Object Allocator and singleton objects that are derived " << endl
<< "from SmallObject or SmallValueObject." << endl
<< endl
<< "Use one of the following lifetime policies" << endl
<< "to manage the lifetime dependency:" << endl
<< endl
<< "- LongevityLifetime Parent/Child: SmallObject has" << endl
<< " LongevityLifetime::DieAsSmallObjectParent" << endl
<< " policy and the derived Singleton has " << endl
<< " LongevityLifetime::DieAsSmallObjectChild" << endl
<< " This is tested by the SmallObjectChild class." << endl
<< endl
<< "- Both SmallObject and derived Singleton use" << endl
<< " SingletonWithLongevity" << endl
<< " policy. This is tested by the LongLivedSingleton class." << endl
<< endl
#if !defined(_MSC_VER) || (_MSC_VER>=1400)
<< "- FollowIntoDeath: SmallObject has" << endl
<< " FollowIntoDeath::With<LIFETIME>::AsMasterLiftime" << endl
<< " policy and the derived Singleton has " << endl
<< " FollowIntoDeath::AfterMaster<MASTERSINGLETON>::IsDestroyed" << endl
<< " policy. This is tested by the FollowerSingleton class." << endl
<< endl
#endif
<< "- Both SmallObject and derived Singleton use" << endl
<< " NoDestroy" << endl
<< " policy. This is tested by the ImmortalSingleton class." << endl
<< " Note: yow will get memory leaks" << endl
<< endl
<< "- SmallObject has"<< endl
<< " NoDestroy" << endl
<< " policy but the derived Singleton has" << endl
<< " SingletonWithLongevity" << endl
<< " policy. This is tested by the MortalSingleton class." << endl
<< " Note: yow will get memory leaks" << endl << endl
<< endl << endl
<< "If this program executes without crashing or asserting" << endl
<< "at exit time, then all policies work." << endl << endl;
SmallObjectChild::Instance().DoThat();
LongLivedSingleton::Instance().DoThat();
#if !defined(_MSC_VER) || (_MSC_VER>=1400)
FollowerSingleton::Instance().DoThat();
#endif
#define ENABLE_MEMORY_LEAK
#ifdef ENABLE_MEMORY_LEAK
ImmortalSingleton::Instance().DoThat();
MortalSingleton::Instance().DoThat();
#else
cout << endl;
cout << "ImmortalSingleton and MortalSingleton" << endl;
cout << "are disabled due to the test on memory leaks.";
cout << endl << endl;
#endif
#if defined(__BORLANDC__) || defined(__GNUC__) || defined(_MSC_VER)
system("pause");
#endif
cout << endl<< endl << "now leaving main" << endl;
cout << "________________________________" << endl << endl;
return 0;
}
// ----------------------------------------------------------------------------
// $Log$
// Revision 1.10 2005/11/13 13:39:15 syntheticpp
// add removed tests with NoDestroy plolicy
//
// Revision 1.9 2005/11/07 12:06:43 syntheticpp
// change lifetime policy DieOrder to a msvc7.1 compilable version. Make this the default lifetime for SmallObject
//
// Revision 1.8 2005/11/05 17:43:55 syntheticpp
// disable FollowIntoDeath/DieOrder lifetime policies when using the msvc 7.1 compiler, bug article: 839821 'Microsoft has confirmed that this is a problem..'
//
// Revision 1.7 2005/11/02 15:00:38 syntheticpp
// use new singleton lifetime policies
//
// Revision 1.6 2005/11/02 14:15:44 syntheticpp
// use new singleton lifetime policies
//
// Revision 1.5 2005/11/02 14:11:18 syntheticpp
// use new singleton lifetime policies
//
// Revision 1.4 2005/11/02 13:58:18 syntheticpp
// use new singleton lifetime policies
//
// Revision 1.3 2005/10/30 14:03:23 syntheticpp
// replace tabs space
//
// Revision 1.2 2005/10/29 10:21:46 syntheticpp
// find loki include files without a correct sreach pathand some small fixes
//
// Revision 1.1 2005/10/14 18:48:10 rich_sposato
// Adding SmallSingleton test project to CVS.
//
<commit_msg>Changed template parameter values for SmallObject allocator.<commit_after>////////////////////////////////////////////////////////////////////////////////
// The Loki Library
// Copyright (c) 2005 Richard Sposato
// Copyright (c) 2005 Peter Kmmel
// Permission to use, copy, modify, distribute and sell this software for any
// purpose is hereby granted without fee, provided that the above copyright
// notice appear in all copies and that both that copyright notice and this
// permission notice appear in supporting documentation.
// The authors make no representations about the
// suitability of this software for any purpose. It is provided "as is"
// without express or implied warranty.
////////////////////////////////////////////////////////////////////////////////
// $Header$
#include "../../include/loki/SmallObj.h"
#include "../../include/loki/Singleton.h"
#include <iostream>
// define DO_EXTRA_LOKI_TESTS in src/SmallObj.cpp to get
// a message when a SmallObject is created/deleted.
using namespace std;
// ----------------------------------------------------------------------------
//
// LongevityLifetime Parent/Child policies
//
// ----------------------------------------------------------------------------
typedef Loki::SmallValueObject< LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL,
512, 32, 4, Loki::LongevityLifetime::DieAsSmallObjectParent
>
SmallObjectParent;
class SmallObjectChild : public SmallObjectParent
{
public:
typedef Loki::SingletonHolder< SmallObjectChild, Loki::CreateUsingNew,
Loki::LongevityLifetime::DieAsSmallObjectChild>
MySmallSingleton;
/// Returns reference to the singleton.
inline static SmallObjectChild & Instance( void )
{
return MySmallSingleton::Instance();
}
SmallObjectChild( void )
{
cout << "SmallObjectChild created" << endl;
}
~SmallObjectChild( void )
{
cout << "~SmallObjectChild" << endl;
}
void DoThat( void )
{
cout << "SmallObjectChild::DoThat" << endl << endl;
}
private:
char m_stuff[ 16 ];
};
// ----------------------------------------------------------------------------
//
// SingletonWithLongevity policy
//
// ----------------------------------------------------------------------------
typedef Loki::SmallValueObject< LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL,
LOKI_DEFAULT_CHUNK_SIZE, LOKI_MAX_SMALL_OBJECT_SIZE,
LOKI_DEFAULT_OBJECT_ALIGNMENT,
Loki::SingletonWithLongevity
>
LongLivedObject;
class LongLivedSingleton : public LongLivedObject
{
public:
typedef Loki::SingletonHolder< LongLivedSingleton, Loki::CreateUsingNew,
Loki::SingletonWithLongevity>
MySmallSingleton;
/// Returns reference to the singleton.
inline static LongLivedSingleton & Instance( void )
{
return MySmallSingleton::Instance();
}
LongLivedSingleton( void )
{
cout << "LongLivedSingleton created" << endl;
}
~LongLivedSingleton( void )
{
cout << "~LongLivedSingleton" << endl;
}
void DoThat( void )
{
cout << "LongLivedSingleton::DoThat" << endl << endl;
}
private:
char m_stuff[ 16 ];
};
inline unsigned int GetLongevity( LongLivedSingleton * )
{
/// @note Must return a longevity level lower than the one in SmallObj.h.
return 1;
}
#if !defined(_MSC_VER) || (_MSC_VER>=1400)
// ----------------------------------------------------------------------------
//
// FollowIntoDeath policy
//
// ----------------------------------------------------------------------------
typedef Loki::SmallValueObject< LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL,
LOKI_DEFAULT_CHUNK_SIZE, LOKI_MAX_SMALL_OBJECT_SIZE,
LOKI_DEFAULT_OBJECT_ALIGNMENT,
Loki::FollowIntoDeath::With<Loki::DefaultLifetime>::AsMasterLifetime
>
MasterObject;
class FollowerSingleton : public MasterObject
{
public:
typedef Loki::SingletonHolder< FollowerSingleton, Loki::CreateUsingNew,
Loki::FollowIntoDeath::AfterMaster<FollowerSingleton::ObjAllocatorSingleton>::IsDestroyed>
MySmallSingleton;
/// Returns reference to the singleton.
inline static FollowerSingleton & Instance( void )
{
return MySmallSingleton::Instance();
}
FollowerSingleton( void )
{
cout << "FollowerSingleton created" << endl;
}
~FollowerSingleton( void )
{
cout << "~FollowerSingleton" << endl;
}
void DoThat( void )
{
cout << "FollowerSingleton::DoThat" << endl << endl;
}
private:
char m_stuff[ 16 ];
};
#endif
// ----------------------------------------------------------------------------
//
// NoDestroy policy
//
// ----------------------------------------------------------------------------
typedef Loki::SmallValueObject< LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL,
LOKI_DEFAULT_CHUNK_SIZE, LOKI_MAX_SMALL_OBJECT_SIZE,
LOKI_DEFAULT_OBJECT_ALIGNMENT, Loki::NoDestroy >
ImmortalObject;
class ImmortalSingleton : public ImmortalObject
{
public:
typedef Loki::SingletonHolder< ImmortalSingleton, Loki::CreateUsingNew,
Loki::NoDestroy>
MySmallSingleton;
/// Returns reference to the singleton.
inline static ImmortalSingleton & Instance( void )
{
return MySmallSingleton::Instance();
}
ImmortalSingleton( void )
{
cout << "ImmortalSingleton created" << endl;
}
~ImmortalSingleton( void )
{
cout << "~ImmortalSingleton destructor should never get called!" << endl;
}
void DoThat( void )
{
cout << "ImmortalSingleton::DoThat" << endl << endl;
}
private:
char m_stuff[ 16 ];
};
// ----------------------------------------------------------------------------
//
// NoDestroy and SingletonWithLongevity policy combination
//
// ----------------------------------------------------------------------------
class MortalSingleton : public ImmortalObject
{
public:
typedef Loki::SingletonHolder< MortalSingleton, Loki::CreateUsingNew,
Loki::SingletonWithLongevity>
MySmallSingleton;
/// Returns reference to the singleton.
inline static MortalSingleton & Instance( void )
{
return MySmallSingleton::Instance();
}
MortalSingleton( void )
{
cout << "MortalSingleton created" << endl;
}
~MortalSingleton( void )
{
cout << "~MortalSingleton" << endl;
}
void DoThat( void )
{
cout << "MortalSingleton::DoThat" << endl << endl;
}
private:
char m_stuff[ 16 ];
};
inline unsigned int GetLongevity( MortalSingleton * )
{
/// @note Must return a longevity level lower than the one in SmallObj.h.
return 1;
}
// ----------------------------------------------------------------------------
//
// detect memory leaks on MSVC Ide
//
// ----------------------------------------------------------------------------
//#define LOKI_MSVC_CHECK_FOR_MEMORY_LEAKS
#ifdef LOKI_MSVC_CHECK_FOR_MEMORY_LEAKS
#include <crtdbg.h>
#include <cassert>
void heap_debug()
{
int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
// Turn on leak-checking bit
tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
//tmpFlag |= _CRTDBG_CHECK_MasterLWMasterYS_DF;
// Turn off CRT block checking bit
tmpFlag &= ~_CRTDBG_CHECK_CRT_DF;
// Set flag to the new value
_CrtSetDbgFlag( tmpFlag );
}
#else
void heap_debug()
{}
#endif
// ----------------------------------------------------------------------------
//
// main
//
// ----------------------------------------------------------------------------
int main()
{
heap_debug();
cout << endl
<< "This program tests the lifetime policies for Loki's " << endl
<< "Small-Object Allocator and singleton objects that are derived " << endl
<< "from SmallObject or SmallValueObject." << endl
<< endl
<< "Use one of the following lifetime policies" << endl
<< "to manage the lifetime dependency:" << endl
<< endl
<< "- LongevityLifetime Parent/Child: SmallObject has" << endl
<< " LongevityLifetime::DieAsSmallObjectParent" << endl
<< " policy and the derived Singleton has " << endl
<< " LongevityLifetime::DieAsSmallObjectChild" << endl
<< " This is tested by the SmallObjectChild class." << endl
<< endl
<< "- Both SmallObject and derived Singleton use" << endl
<< " SingletonWithLongevity" << endl
<< " policy. This is tested by the LongLivedSingleton class." << endl
<< endl
#if !defined(_MSC_VER) || (_MSC_VER>=1400)
<< "- FollowIntoDeath: SmallObject has" << endl
<< " FollowIntoDeath::With<LIFETIME>::AsMasterLiftime" << endl
<< " policy and the derived Singleton has " << endl
<< " FollowIntoDeath::AfterMaster<MASTERSINGLETON>::IsDestroyed" << endl
<< " policy. This is tested by the FollowerSingleton class." << endl
<< endl
#endif
<< "- Both SmallObject and derived Singleton use" << endl
<< " NoDestroy" << endl
<< " policy. This is tested by the ImmortalSingleton class." << endl
<< " Note: yow will get memory leaks" << endl
<< endl
<< "- SmallObject has"<< endl
<< " NoDestroy" << endl
<< " policy but the derived Singleton has" << endl
<< " SingletonWithLongevity" << endl
<< " policy. This is tested by the MortalSingleton class." << endl
<< " Note: yow will get memory leaks" << endl << endl
<< endl << endl
<< "If this program executes without crashing or asserting" << endl
<< "at exit time, then all policies work." << endl << endl;
SmallObjectChild::Instance().DoThat();
LongLivedSingleton::Instance().DoThat();
#if !defined(_MSC_VER) || (_MSC_VER>=1400)
FollowerSingleton::Instance().DoThat();
#endif
#define ENABLE_MEMORY_LEAK
#ifdef ENABLE_MEMORY_LEAK
ImmortalSingleton::Instance().DoThat();
MortalSingleton::Instance().DoThat();
#else
cout << endl;
cout << "ImmortalSingleton and MortalSingleton" << endl;
cout << "are disabled due to the test on memory leaks.";
cout << endl << endl;
#endif
#if defined(__BORLANDC__) || defined(__GNUC__) || defined(_MSC_VER)
system("pause");
#endif
cout << endl<< endl << "now leaving main" << endl;
cout << "________________________________" << endl << endl;
return 0;
}
// ----------------------------------------------------------------------------
// $Log$
// Revision 1.11 2005/12/08 21:03:02 rich_sposato
// Changed template parameter values for SmallObject allocator.
//
// Revision 1.10 2005/11/13 13:39:15 syntheticpp
// add removed tests with NoDestroy plolicy
//
// Revision 1.9 2005/11/07 12:06:43 syntheticpp
// change lifetime policy DieOrder to a msvc7.1 compilable version. Make this the default lifetime for SmallObject
//
// Revision 1.8 2005/11/05 17:43:55 syntheticpp
// disable FollowIntoDeath/DieOrder lifetime policies when using the msvc 7.1 compiler, bug article: 839821 'Microsoft has confirmed that this is a problem..'
//
// Revision 1.7 2005/11/02 15:00:38 syntheticpp
// use new singleton lifetime policies
//
// Revision 1.6 2005/11/02 14:15:44 syntheticpp
// use new singleton lifetime policies
//
// Revision 1.5 2005/11/02 14:11:18 syntheticpp
// use new singleton lifetime policies
//
// Revision 1.4 2005/11/02 13:58:18 syntheticpp
// use new singleton lifetime policies
//
// Revision 1.3 2005/10/30 14:03:23 syntheticpp
// replace tabs space
//
// Revision 1.2 2005/10/29 10:21:46 syntheticpp
// find loki include files without a correct sreach pathand some small fixes
//
// Revision 1.1 2005/10/14 18:48:10 rich_sposato
// Adding SmallSingleton test project to CVS.
//
<|endoftext|>
|
<commit_before>#include "BaseImage.h"
// Constructor used for loading image
BaseImage::BaseImage(std::string filename, int startCol, int startRow)
: m_iColumns(0)
, m_iRows(0)
, m_iBpp(0)
, m_ppImageMatrix(NULL)
, m_lPointerOffset(0)
{
if(filename.size() == 0)
{
throw std::invalid_argument("No file name specified. ");
}
else
{
m_Filename = filename;
}
m_ImageFile.open(filename, std::ios::in|std::ios::binary);
if(m_ImageFile.is_open())
{
if(ReadHeader(255) < 0)
{
return;
}
m_ppImageMatrix = (unsigned char**)CreateMatrix(m_iColumns+2*(startCol<0 ? -startCol : 0), m_iRows+2*(startRow<0 ? -startRow : 0), startCol, startRow, sizeof(unsigned char), &m_lPointerOffset);
if(m_ppImageMatrix == NULL)
{
std::cerr<<"Failed to allocate memory."<<std::endl;
return;
}
for(int i=0;i<m_iRows;i++)
{
m_ImageFile.read((char*)&m_ppImageMatrix[i][0], m_iColumns);
}
Reflect<unsigned char>(m_iColumns, m_iRows, std::abs(startCol), m_ppImageMatrix);
}
else
{
std::cerr<<"Unable to open file!"<<std::endl;
exit(-1);
}
m_ImageFile.close();
}
BaseImage::~BaseImage()
{
if(m_ppImageMatrix!=NULL)
{
m_ppImageMatrix += m_lPointerOffset;
free(m_ppImageMatrix);
m_ppImageMatrix = NULL;
}
}
int BaseImage::ReadHeader(int MaxValue)
{
std::string line;
std::getline(m_ImageFile, line);
while(*line.begin() == '#')
{
std::getline(m_ImageFile, line);
}
if(*line.begin() != 'P' || *(line.begin()+1) != '5')
{
std::cerr<<"File is not supported."<<std::endl;
return -1;
}
std::getline(m_ImageFile, line);
while(*line.begin() == '#')
{
std::getline(m_ImageFile, line);
}
std::stringstream ss(line);
if(!(ss>>m_iColumns>>m_iRows))
{
std::cerr<<"Column number or Row number not recognized."<<std::endl;
return -1;
}
ss.str(std::string());
ss.clear();
std::getline(m_ImageFile, line);
while(*line.begin() == '#')
{
std::getline(m_ImageFile, line);
}
ss<<line;
if(!(ss>>m_iBpp))
{
std::cerr<<"Bpp value is not recognized."<<std::endl;
return -1;
}
if(m_iBpp>MaxValue)
{
std::cerr<<"Bad bpp value."<<std::endl;
return -1;
}
return 0;
}
void** BaseImage::CreateMatrix(int col, int row, int startCol, int startRow, int element_size, long long* offset)
{
void **p;
void **temp;
int alignment = 0;
long i = 0;
if(col<1 || row<1)
{
throw std::invalid_argument("Image Columns and Rows must be larger than 0.");
}
i = row*sizeof(void *);
alignment = i%sizeof(long double);
if(alignment != 0)
{
alignment = sizeof(long double) - alignment;
}
i+= row*col*element_size+alignment;
if((p = (void **)malloc((size_t)i)) != NULL)
{
temp = p;
p[0] = (char*)(p+row) + alignment - startCol*element_size;
for(i=1;i<row;i++)
{
p[i] = (char*)(p[i-1])+col*element_size;
}
p-=startRow;
}
*offset = temp-p;
return (p);
}
void BaseImage::WriteToFile(std::string filename, unsigned char** input, int startCol, int startRow, int col, int row)
{
std::fstream file(filename, std::ios::out|std::ios::binary);
if(file.is_open())
{
file<<"P5"<<std::endl;
file<<col<<" "<<row<<std::endl;
file<<"255"<<std::endl;
for(int i=startRow;i<m_iRows+std::abs(startCol);i++)
{
file.write((char*)&input[i][startCol], col);
}
}
else
{
std::cerr<<"Unable to open file to write!"<<std::endl;
return;
}
file.close();
}
unsigned char** BaseImage::GetImagePointer()
{
return m_ppImageMatrix;
}
int BaseImage::GetColumns()
{
return m_iColumns;
}
int BaseImage::GetRows()
{
return m_iRows;
}<commit_msg>fstream fix<commit_after>#include "BaseImage.h"
// Constructor used for loading image
BaseImage::BaseImage(std::string filename, int startCol, int startRow)
: m_iColumns(0)
, m_iRows(0)
, m_iBpp(0)
, m_ppImageMatrix(NULL)
, m_lPointerOffset(0)
{
if(filename.size() == 0)
{
throw std::invalid_argument("No file name specified. ");
}
else
{
m_Filename = filename;
}
m_ImageFile.open(filename.c_str(), std::ios::in|std::ios::binary);
if(m_ImageFile.is_open())
{
if(ReadHeader(255) < 0)
{
return;
}
m_ppImageMatrix = (unsigned char**)CreateMatrix(m_iColumns+2*(startCol<0 ? -startCol : 0), m_iRows+2*(startRow<0 ? -startRow : 0), startCol, startRow, sizeof(unsigned char), &m_lPointerOffset);
if(m_ppImageMatrix == NULL)
{
std::cerr<<"Failed to allocate memory."<<std::endl;
return;
}
for(int i=0;i<m_iRows;i++)
{
m_ImageFile.read((char*)&m_ppImageMatrix[i][0], m_iColumns);
}
Reflect<unsigned char>(m_iColumns, m_iRows, std::abs(startCol), m_ppImageMatrix);
}
else
{
std::cerr<<"Unable to open file!"<<std::endl;
exit(-1);
}
m_ImageFile.close();
}
BaseImage::~BaseImage()
{
if(m_ppImageMatrix!=NULL)
{
m_ppImageMatrix += m_lPointerOffset;
free(m_ppImageMatrix);
m_ppImageMatrix = NULL;
}
}
int BaseImage::ReadHeader(int MaxValue)
{
std::string line;
std::getline(m_ImageFile, line);
while(*line.begin() == '#')
{
std::getline(m_ImageFile, line);
}
if(*line.begin() != 'P' || *(line.begin()+1) != '5')
{
std::cerr<<"File is not supported."<<std::endl;
return -1;
}
std::getline(m_ImageFile, line);
while(*line.begin() == '#')
{
std::getline(m_ImageFile, line);
}
std::stringstream ss(line);
if(!(ss>>m_iColumns>>m_iRows))
{
std::cerr<<"Column number or Row number not recognized."<<std::endl;
return -1;
}
ss.str(std::string());
ss.clear();
std::getline(m_ImageFile, line);
while(*line.begin() == '#')
{
std::getline(m_ImageFile, line);
}
ss<<line;
if(!(ss>>m_iBpp))
{
std::cerr<<"Bpp value is not recognized."<<std::endl;
return -1;
}
if(m_iBpp>MaxValue)
{
std::cerr<<"Bad bpp value."<<std::endl;
return -1;
}
return 0;
}
void** BaseImage::CreateMatrix(int col, int row, int startCol, int startRow, int element_size, long long* offset)
{
void **p;
void **temp;
int alignment = 0;
long i = 0;
if(col<1 || row<1)
{
throw std::invalid_argument("Image Columns and Rows must be larger than 0.");
}
i = row*sizeof(void *);
alignment = i%sizeof(long double);
if(alignment != 0)
{
alignment = sizeof(long double) - alignment;
}
i+= row*col*element_size+alignment;
if((p = (void **)malloc((size_t)i)) != NULL)
{
temp = p;
p[0] = (char*)(p+row) + alignment - startCol*element_size;
for(i=1;i<row;i++)
{
p[i] = (char*)(p[i-1])+col*element_size;
}
p-=startRow;
}
*offset = temp-p;
return (p);
}
void BaseImage::WriteToFile(std::string filename, unsigned char** input, int startCol, int startRow, int col, int row)
{
std::fstream file(filename.c_str(), std::ios::out|std::ios::binary);
if(file.is_open())
{
file<<"P5"<<std::endl;
file<<col<<" "<<row<<std::endl;
file<<"255"<<std::endl;
for(int i=startRow;i<m_iRows+std::abs(startCol);i++)
{
file.write((char*)&input[i][startCol], col);
}
}
else
{
std::cerr<<"Unable to open file to write!"<<std::endl;
return;
}
file.close();
}
unsigned char** BaseImage::GetImagePointer()
{
return m_ppImageMatrix;
}
int BaseImage::GetColumns()
{
return m_iColumns;
}
int BaseImage::GetRows()
{
return m_iRows;
}<|endoftext|>
|
<commit_before>/*
* Copyright 2022 The CFU-Playground Authors
*
* 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 "proj_menu.h"
#include <stdio.h>
#include "fccm_cfu.h"
#include "menu.h"
namespace {
// Template Fn
void do_hello_world(void) { puts("Hello, World!!!\n"); }
// Tests multiply-add CFU
void do_test_cfu(void) {
printf("\r\nCFU Test... ");
// Calculated on a spreadsheet
cfu_reset();
cfu_accumulate(0x884CF61A, 0xE49F2F1C);
cfu_accumulate(0x0BE31854, 0x527FDBCF);
cfu_accumulate(0xADB43251, 0x4E36D172);
cfu_accumulate(0x6F867FFB, 0x442C7B76);
printf("%s\n", static_cast<int32_t>(cfu_read()) == 81978 ? "PASS!" : "FAIL");
}
struct Menu MENU = {
"Project Menu",
"project",
{
MENU_ITEM('1', "test cfu", do_test_cfu),
MENU_ITEM('h', "say Hello", do_hello_world),
MENU_END,
},
};
}; // anonymous namespace
extern "C" void do_proj_menu() { menu_run(&MENU); }<commit_msg>fccum_tutorial/proj_menu: new test case<commit_after>/*
* Copyright 2022 The CFU-Playground Authors
*
* 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 "proj_menu.h"
#include <stdio.h>
#include "fccm_cfu.h"
#include "menu.h"
namespace {
// Template Fn
void do_hello_world(void) { puts("Hello, World!!!\n"); }
void check_cfu(uint32_t a, uint32_t b, uint32_t expected) {
cfu_accumulate(a, b);
uint32_t actual = cfu_read();
printf("%08lx ", actual);
if (actual == expected) {
printf("ok\n");
} else {
printf("FAIL (0x%08lx) %ld != %ld\n", expected, actual, expected);
}
}
// Tests multiply-add CFU
void do_test_cfu(void) {
printf("\r\nCFU Test... ");
cfu_reset();
printf("%08lx\n", cfu_read());
check_cfu(0x00808080, 0x98000000, -13312);
check_cfu(0x80B38080, 0x002B0000, -11119);
check_cfu(0x8080E180, 0x0000AE00, -19073);
check_cfu(0x8080801C, 0x000000AD, -32021);
}
struct Menu MENU = {
"Project Menu",
"project",
{
MENU_ITEM('1', "test cfu", do_test_cfu),
MENU_ITEM('h', "say Hello", do_hello_world),
MENU_END,
},
};
}; // anonymous namespace
extern "C" void do_proj_menu() { menu_run(&MENU); }<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: smplmailclient.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: tra $ $Date: 2001-05-16 13:34:53 $
*
* 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): _______________________________________
*
*
************************************************************************/
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _SMPLMAILCLIENT_HXX_
#include "smplmailclient.hxx"
#endif
#ifndef _SMPLMAILMSG_HXX_
#include "smplmailmsg.hxx"
#endif
#ifndef _COM_SUN_STAR_SYSTEM_SIMPLEMAILCLIENTFLAGS_HPP_
#include <com/sun/star/system/SimpleMailClientFlags.hpp>
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------
using com::sun::star::uno::Reference;
using com::sun::star::uno::Exception;
using com::sun::star::uno::RuntimeException;
using com::sun::star::uno::Sequence;
using com::sun::star::lang::IllegalArgumentException;
using com::sun::star::system::XSimpleMailClient;
using com::sun::star::system::XSimpleMailMessage;
using rtl::OUString;
using rtl::OString;
using osl::Mutex;
using namespace com::sun::star::system::SimpleMailClientFlags;
using namespace cppu;
//------------------------------------------------
//
//------------------------------------------------
namespace // private
{
const sal_uInt32 LEN_SMTP_PREFIX = 5; // "SMTP:"
inline
OString getSmtpPrefixedEmailAddress( const OUString& aAddress )
{
return OString( "SMTP:" ) +
OString(
aAddress.getStr( ),
aAddress.getLength( ),
osl_getThreadTextEncoding( ) );
}
} // end private namespace
//------------------------------------------------
//
//------------------------------------------------
CSmplMailClient::CSmplMailClient( ) :
m_pSimpleMapi( CSimpleMapi::create( ) )
{
}
//------------------------------------------------
//
//------------------------------------------------
Reference< XSimpleMailMessage > SAL_CALL CSmplMailClient::createSimpleMailMessage( )
throw (::com::sun::star::uno::RuntimeException)
{
return Reference< XSimpleMailMessage >( new CSmplMailMsg( ) );
}
//------------------------------------------------
//
//------------------------------------------------
void SAL_CALL CSmplMailClient::sendSimpleMailMessage( const Reference< XSimpleMailMessage >& xSimpleMailMessage, sal_Int32 aFlag )
throw (IllegalArgumentException, Exception, RuntimeException)
{
try
{
validateParameter( xSimpleMailMessage, aFlag );
MapiMessage mapiMsg;
FLAGS flFlags;
initMapiMessage( xSimpleMailMessage, mapiMsg );
initMapiSendMailFlags( aFlag, flFlags );
ULONG ulRet = m_pSimpleMapi->MAPISendMail(
0, // no session, create a new one
0, // no parent window
&mapiMsg, // a configured mapi message struct
flFlags, // some flags
0 ); // reserved
if ( SUCCESS_SUCCESS != ulRet )
throw Exception(
getMapiErrorMsg( ulRet ),
static_cast< XSimpleMailClient* >( this ) );
}
catch( RuntimeException& )
{
OSL_ASSERT( sal_False );
}
}
//------------------------------------------------
//
//------------------------------------------------
void CSmplMailClient::validateParameter(
const Reference< XSimpleMailMessage >& xSimpleMailMessage, sal_Int32 aFlag )
{
// check the flags, the allowed range is 0 - (2^n - 1)
if ( aFlag < 0 || aFlag > 3 )
throw IllegalArgumentException(
OUString::createFromAscii( "Invalid flag value" ),
static_cast< XSimpleMailClient* >( this ),
2 );
// check if a recipient is specified of the flags NO_USER_INTERFACE is specified
if ( (aFlag & NO_USER_INTERFACE) && !xSimpleMailMessage->getRecipient( ).getLength( ) )
throw IllegalArgumentException(
OUString::createFromAscii( "No recipient specified" ),
static_cast< XSimpleMailClient* >( this ),
1 );
}
//------------------------------------------------
//
//------------------------------------------------
void CSmplMailClient::initMapiMessage(
const Reference< XSimpleMailMessage >& xSimpleMailMessage, MapiMessage& aMapiMessage )
{
ZeroMemory( &aMapiMessage, sizeof( aMapiMessage ) );
if ( xSimpleMailMessage.is( ) )
{
// unfortunately the simple mapi functions have
// only an ANSI prototype, so we have to convert
// all strings to ascii assuming an us-ascii
// encoding
// we hand the buffer of this OStrings directly
// to the MapiMessage members but have to
// cast away the constness of the returned buffer
// pointer, we assume the function MAPISendMail
// doesn't alter the strings
m_Subject = OString(
xSimpleMailMessage->getSubject( ).getStr( ),
xSimpleMailMessage->getSubject( ).getLength( ),
osl_getThreadTextEncoding( ) );
aMapiMessage.lpszSubject = const_cast< LPSTR >( m_Subject.getStr( ) );
// set the originator information
if ( xSimpleMailMessage->getOriginator( ).getLength( ) )
{
ZeroMemory( &m_MsgOriginator, sizeof( m_MsgOriginator ) );
m_SmtpAddressOriginator = getSmtpPrefixedEmailAddress(
xSimpleMailMessage->getOriginator( ) );
m_MsgOriginator.ulRecipClass = MAPI_ORIG;
m_MsgOriginator.lpszName = "";
m_MsgOriginator.lpszAddress =
const_cast< LPSTR >( m_SmtpAddressOriginator.getStr( ) );
aMapiMessage.lpOriginator = &m_MsgOriginator;
}
// set the recipient information
sal_uInt32 nRecips = calcNumRecipients( xSimpleMailMessage );
if ( nRecips > 0 )
{
m_RecipientList.realloc( nRecips );
m_RecipientList.clean( );
m_RecipsSmtpAddressList.clear( );
size_t nPos = 0;
// init the main recipient
OUString aRecipient = xSimpleMailMessage->getRecipient( );
if ( aRecipient.getLength( ) )
{
m_RecipsSmtpAddressList.push_back(
getSmtpPrefixedEmailAddress( aRecipient ) );
m_RecipientList[nPos].ulRecipClass = MAPI_TO;
m_RecipientList[nPos].lpszName =
const_cast< LPSTR >( m_RecipsSmtpAddressList.back( ).getStr( ) + LEN_SMTP_PREFIX );
m_RecipientList[nPos].lpszAddress =
const_cast< LPSTR >( m_RecipsSmtpAddressList.back( ).getStr( ) );
nPos++;
}
// add all cc recipients to the list
initRecipientList(
xSimpleMailMessage->getCcRecipient( ),
MAPI_CC,
nPos );
// add all bcc recipients to the list
initRecipientList(
xSimpleMailMessage->getBccRecipient( ),
MAPI_BCC,
nPos );
aMapiMessage.lpRecips = &m_RecipientList;
aMapiMessage.nRecipCount = m_RecipientList.size( );
}
initAttachementList( xSimpleMailMessage );
aMapiMessage.lpFiles = &m_AttachementList;
aMapiMessage.nFileCount = m_AttachementList.size( );
}
}
//------------------------------------------------
//
//------------------------------------------------
sal_uInt32 CSmplMailClient::calcNumRecipients(
const Reference< XSimpleMailMessage >& xSimpleMailMessage )
{
sal_uInt32 nRecips = xSimpleMailMessage->getCcRecipient( ).getLength( );
nRecips += xSimpleMailMessage->getBccRecipient( ).getLength( );
if ( xSimpleMailMessage->getRecipient( ).getLength( ) )
nRecips += 1;
return nRecips;
}
//------------------------------------------------
//
//------------------------------------------------
void CSmplMailClient::initRecipientList(
const Sequence< rtl::OUString >& aRecipList,
ULONG ulRecipClass,
size_t& nPos )
{
OSL_PRECOND( nPos < m_RecipientList.size( ), "Wrong index" );
for( sal_Int32 i = 0; i < aRecipList.getLength( ); i++ )
{
m_RecipsSmtpAddressList.push_back(
getSmtpPrefixedEmailAddress( aRecipList[i] ) );
m_RecipientList[nPos].ulRecipClass = ulRecipClass;
m_RecipientList[nPos].lpszName =
const_cast< LPSTR >( m_RecipsSmtpAddressList.back( ).getStr( ) + LEN_SMTP_PREFIX );
m_RecipientList[nPos].lpszAddress =
const_cast< LPSTR >( m_RecipsSmtpAddressList.back( ).getStr( ) );
nPos++;
}
}
//------------------------------------------------
//
//------------------------------------------------
void CSmplMailClient::initAttachementList(
const Reference< XSimpleMailMessage >& xSimpleMailMessage )
{
Sequence< OUString > aAttachementList =
xSimpleMailMessage->getAttachement( );
sal_uInt32 nAttachements = aAttachementList.getLength( );
// avoid old entries
m_AttchmtsSysPathList.clear( );
m_AttachementList.realloc( nAttachements );
m_AttachementList.clean( );
OUString aSysPath;
for ( sal_uInt32 i = 0; i < nAttachements; i++ )
{
#ifdef TF_FILEURL
osl::FileBase::RC rc =
osl::FileBase::getSystemPathFromFileURL(
aAttachementList[i], aSysPath );
if ( osl::FileBase::RC::E_None != rc )
throw IllegalArgumentException(
OUString::createFromAscii( " " ),
static_cast< XSimpleMailClient* >( this ),
1 );
m_AttchmtsSysPathList.push_back(
OString(
aSysPath.getStr( ),
aSysPath.getLength( ),
osl_getThreadTextEncoding( ) ) );
m_AttachementList[i].lpszFileName = const_cast< LPSTR >(
m_AttchmtsSysPathList.back( ).getStr( ) );
#endif
}
}
//------------------------------------------------
//
//------------------------------------------------
void CSmplMailClient::initMapiSendMailFlags( sal_Int32 aFlags, FLAGS& aMapiFlags )
{
aMapiFlags = MAPI_NEW_SESSION | MAPI_UNICODE;
if ( !( aFlags & NO_USER_INTERFACE ) )
aMapiFlags |= MAPI_DIALOG;
if ( !( aFlags & NO_LOGON_DIALOG ) )
aMapiFlags |= MAPI_LOGON_UI;
}
//------------------------------------------------
//
//------------------------------------------------
rtl::OUString CSmplMailClient::getMapiErrorMsg( ULONG ulMapiError )
{
LPVOID lpMsgBuff;
DWORD dwRet = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE,
GetModuleHandleA( "mapi32.dll" ),
ulMapiError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast< LPSTR >( &lpMsgBuff ),
0,
NULL );
OUString errMsg;
if ( dwRet )
{
errMsg = OUString::createFromAscii(
static_cast< LPSTR >( lpMsgBuff ) );
LocalFree( lpMsgBuff );
}
return errMsg;
}<commit_msg>#87458#fixed bug that did prevent sending mails with attachement<commit_after>/*************************************************************************
*
* $RCSfile: smplmailclient.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: tra $ $Date: 2001-05-25 08:21:23 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _SMPLMAILCLIENT_HXX_
#include "smplmailclient.hxx"
#endif
#ifndef _SMPLMAILMSG_HXX_
#include "smplmailmsg.hxx"
#endif
#ifndef _COM_SUN_STAR_SYSTEM_SIMPLEMAILCLIENTFLAGS_HPP_
#include <com/sun/star/system/SimpleMailClientFlags.hpp>
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------
using com::sun::star::uno::Reference;
using com::sun::star::uno::Exception;
using com::sun::star::uno::RuntimeException;
using com::sun::star::uno::Sequence;
using com::sun::star::lang::IllegalArgumentException;
using com::sun::star::system::XSimpleMailClient;
using com::sun::star::system::XSimpleMailMessage;
using rtl::OUString;
using rtl::OString;
using osl::Mutex;
using namespace com::sun::star::system::SimpleMailClientFlags;
using namespace cppu;
//------------------------------------------------
//
//------------------------------------------------
namespace // private
{
const sal_uInt32 LEN_SMTP_PREFIX = 5; // "SMTP:"
inline
OString getSmtpPrefixedEmailAddress( const OUString& aAddress )
{
return OString( "SMTP:" ) +
OString(
aAddress.getStr( ),
aAddress.getLength( ),
osl_getThreadTextEncoding( ) );
}
} // end private namespace
//------------------------------------------------
//
//------------------------------------------------
CSmplMailClient::CSmplMailClient( ) :
m_pSimpleMapi( CSimpleMapi::create( ) )
{
}
//------------------------------------------------
//
//------------------------------------------------
Reference< XSimpleMailMessage > SAL_CALL CSmplMailClient::createSimpleMailMessage( )
throw (::com::sun::star::uno::RuntimeException)
{
return Reference< XSimpleMailMessage >( new CSmplMailMsg( ) );
}
//------------------------------------------------
//
//------------------------------------------------
void SAL_CALL CSmplMailClient::sendSimpleMailMessage( const Reference< XSimpleMailMessage >& xSimpleMailMessage, sal_Int32 aFlag )
throw (IllegalArgumentException, Exception, RuntimeException)
{
try
{
validateParameter( xSimpleMailMessage, aFlag );
MapiMessage mapiMsg;
FLAGS flFlags;
initMapiMessage( xSimpleMailMessage, mapiMsg );
initMapiSendMailFlags( aFlag, flFlags );
ULONG ulRet = m_pSimpleMapi->MAPISendMail(
0, // no session, create a new one
0, // no parent window
&mapiMsg, // a configured mapi message struct
flFlags, // some flags
0 ); // reserved
if ( SUCCESS_SUCCESS != ulRet )
throw Exception(
getMapiErrorMsg( ulRet ),
static_cast< XSimpleMailClient* >( this ) );
}
catch( RuntimeException& )
{
OSL_ASSERT( sal_False );
}
}
//------------------------------------------------
//
//------------------------------------------------
void CSmplMailClient::validateParameter(
const Reference< XSimpleMailMessage >& xSimpleMailMessage, sal_Int32 aFlag )
{
// check the flags, the allowed range is 0 - (2^n - 1)
if ( aFlag < 0 || aFlag > 3 )
throw IllegalArgumentException(
OUString::createFromAscii( "Invalid flag value" ),
static_cast< XSimpleMailClient* >( this ),
2 );
// check if a recipient is specified of the flags NO_USER_INTERFACE is specified
if ( (aFlag & NO_USER_INTERFACE) && !xSimpleMailMessage->getRecipient( ).getLength( ) )
throw IllegalArgumentException(
OUString::createFromAscii( "No recipient specified" ),
static_cast< XSimpleMailClient* >( this ),
1 );
}
//------------------------------------------------
//
//------------------------------------------------
void CSmplMailClient::initMapiMessage(
const Reference< XSimpleMailMessage >& xSimpleMailMessage, MapiMessage& aMapiMessage )
{
ZeroMemory( &aMapiMessage, sizeof( aMapiMessage ) );
if ( xSimpleMailMessage.is( ) )
{
// unfortunately the simple mapi functions have
// only an ANSI prototype, so we have to convert
// all strings to ascii assuming an us-ascii
// encoding
// we hand the buffer of this OStrings directly
// to the MapiMessage members but have to
// cast away the constness of the returned buffer
// pointer, we assume the function MAPISendMail
// doesn't alter the strings
m_Subject = OString(
xSimpleMailMessage->getSubject( ).getStr( ),
xSimpleMailMessage->getSubject( ).getLength( ),
osl_getThreadTextEncoding( ) );
aMapiMessage.lpszSubject = const_cast< LPSTR >( m_Subject.getStr( ) );
// set the originator information
if ( xSimpleMailMessage->getOriginator( ).getLength( ) )
{
ZeroMemory( &m_MsgOriginator, sizeof( m_MsgOriginator ) );
m_SmtpAddressOriginator = getSmtpPrefixedEmailAddress(
xSimpleMailMessage->getOriginator( ) );
m_MsgOriginator.ulRecipClass = MAPI_ORIG;
m_MsgOriginator.lpszName = "";
m_MsgOriginator.lpszAddress =
const_cast< LPSTR >( m_SmtpAddressOriginator.getStr( ) );
aMapiMessage.lpOriginator = &m_MsgOriginator;
}
// set the recipient information
sal_uInt32 nRecips = calcNumRecipients( xSimpleMailMessage );
if ( nRecips > 0 )
{
m_RecipientList.realloc( nRecips );
m_RecipientList.clean( );
m_RecipsSmtpAddressList.clear( );
size_t nPos = 0;
// init the main recipient
OUString aRecipient = xSimpleMailMessage->getRecipient( );
if ( aRecipient.getLength( ) )
{
m_RecipsSmtpAddressList.push_back(
getSmtpPrefixedEmailAddress( aRecipient ) );
m_RecipientList[nPos].ulRecipClass = MAPI_TO;
m_RecipientList[nPos].lpszName =
const_cast< LPSTR >( m_RecipsSmtpAddressList.back( ).getStr( ) + LEN_SMTP_PREFIX );
m_RecipientList[nPos].lpszAddress =
const_cast< LPSTR >( m_RecipsSmtpAddressList.back( ).getStr( ) );
nPos++;
}
// add all cc recipients to the list
initRecipientList(
xSimpleMailMessage->getCcRecipient( ),
MAPI_CC,
nPos );
// add all bcc recipients to the list
initRecipientList(
xSimpleMailMessage->getBccRecipient( ),
MAPI_BCC,
nPos );
aMapiMessage.lpRecips = &m_RecipientList;
aMapiMessage.nRecipCount = m_RecipientList.size( );
}
initAttachementList( xSimpleMailMessage );
aMapiMessage.lpFiles = &m_AttachementList;
aMapiMessage.nFileCount = m_AttachementList.size( );
}
}
//------------------------------------------------
//
//------------------------------------------------
sal_uInt32 CSmplMailClient::calcNumRecipients(
const Reference< XSimpleMailMessage >& xSimpleMailMessage )
{
sal_uInt32 nRecips = xSimpleMailMessage->getCcRecipient( ).getLength( );
nRecips += xSimpleMailMessage->getBccRecipient( ).getLength( );
if ( xSimpleMailMessage->getRecipient( ).getLength( ) )
nRecips += 1;
return nRecips;
}
//------------------------------------------------
//
//------------------------------------------------
void CSmplMailClient::initRecipientList(
const Sequence< rtl::OUString >& aRecipList,
ULONG ulRecipClass,
size_t& nPos )
{
OSL_PRECOND( nPos < m_RecipientList.size( ), "Wrong index" );
for( sal_Int32 i = 0; i < aRecipList.getLength( ); i++ )
{
m_RecipsSmtpAddressList.push_back(
getSmtpPrefixedEmailAddress( aRecipList[i] ) );
m_RecipientList[nPos].ulRecipClass = ulRecipClass;
m_RecipientList[nPos].lpszName =
const_cast< LPSTR >( m_RecipsSmtpAddressList.back( ).getStr( ) + LEN_SMTP_PREFIX );
m_RecipientList[nPos].lpszAddress =
const_cast< LPSTR >( m_RecipsSmtpAddressList.back( ).getStr( ) );
nPos++;
}
}
//------------------------------------------------
//
//------------------------------------------------
void CSmplMailClient::initAttachementList(
const Reference< XSimpleMailMessage >& xSimpleMailMessage )
{
Sequence< OUString > aAttachementList =
xSimpleMailMessage->getAttachement( );
sal_uInt32 nAttachements = aAttachementList.getLength( );
// avoid old entries
m_AttchmtsSysPathList.clear( );
m_AttachementList.realloc( nAttachements );
m_AttachementList.clean( );
OUString aSysPath;
for ( sal_uInt32 i = 0; i < nAttachements; i++ )
{
osl::FileBase::RC rc =
osl::FileBase::getSystemPathFromFileURL(
aAttachementList[i], aSysPath );
if ( osl::FileBase::RC::E_None != rc )
throw IllegalArgumentException(
OUString::createFromAscii( " " ),
static_cast< XSimpleMailClient* >( this ),
1 );
m_AttchmtsSysPathList.push_back(
OString(
aSysPath.getStr( ),
aSysPath.getLength( ),
osl_getThreadTextEncoding( ) ) );
m_AttachementList[i].lpszPathName = const_cast< LPSTR >(
m_AttchmtsSysPathList.back( ).getStr( ) );
m_AttachementList[i].nPosition = -1;
}
}
//------------------------------------------------
//
//------------------------------------------------
void CSmplMailClient::initMapiSendMailFlags( sal_Int32 aFlags, FLAGS& aMapiFlags )
{
aMapiFlags = MAPI_NEW_SESSION | MAPI_UNICODE;
if ( !( aFlags & NO_USER_INTERFACE ) )
aMapiFlags |= MAPI_DIALOG;
if ( !( aFlags & NO_LOGON_DIALOG ) )
aMapiFlags |= MAPI_LOGON_UI;
}
//------------------------------------------------
//
//------------------------------------------------
rtl::OUString CSmplMailClient::getMapiErrorMsg( ULONG ulMapiError )
{
LPVOID lpMsgBuff;
DWORD dwRet = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE,
GetModuleHandleA( "mapi32.dll" ),
ulMapiError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast< LPSTR >( &lpMsgBuff ),
0,
NULL );
OUString errMsg;
if ( dwRet )
{
errMsg = OUString::createFromAscii(
static_cast< LPSTR >( lpMsgBuff ) );
LocalFree( lpMsgBuff );
}
return errMsg;
}<|endoftext|>
|
<commit_before>#ifndef ROOT_TFPBlock
#include "TFPBlock.h"
#endif
#include <cstdlib>
#include <malloc.h>
ClassImp(TFPBlock)
//__________________________________________________________________
//constructor
TFPBlock::TFPBlock(Long64_t* offset, Int_t* length, Int_t nb)
{
Int_t aux = 0;
fNblock = nb;
fPos = new Long64_t[nb];
fLen = new Int_t[nb];
for (Int_t i=0; i < nb; i++){
fPos[i] = offset[i];
fLen[i] = length[i];
aux += length[i];
}
fFullSize = aux;
fBuffer = new char[fFullSize];
}
//__________________________________________________________________
//destructor
TFPBlock::~TFPBlock()
{
delete[] fPos;
delete[] fLen;
delete[] fBuffer;
}
//__________________________________________________________________
Long64_t* TFPBlock::GetPos()
{
// Get pointer to the array of postions.
return fPos;
}
//__________________________________________________________________
Int_t* TFPBlock::GetLen()
{
// Get pointer to the array of lengths.
return fLen;
}
//__________________________________________________________________
Int_t TFPBlock::GetFullSize()
{
// Return size of the block.
return fFullSize;
}
//__________________________________________________________________
Int_t TFPBlock::GetNoElem()
{
// Return number of elements in the block.
return fNblock;
}
//__________________________________________________________________
Long64_t TFPBlock::GetPos(Int_t i)
{
// Get position of the element at index i.
return fPos[i];
}
//__________________________________________________________________
Int_t TFPBlock::GetLen(Int_t i)
{
// Get length of the element at index i.
return fLen[i];
}
//__________________________________________________________________
char* TFPBlock::GetBuffer()
{
// Get block buffer.
return fBuffer;
}
//__________________________________________________________________
void TFPBlock::SetBuffer(char* buf)
{
//Set block buffer.
fBuffer = buf;
}
//__________________________________________________________________
void TFPBlock::ReallocBlock(Long64_t* offset, Int_t* length, Int_t nb)
{
// Reallocate the block's buffer based on the length
// of the elements it will contain.
Int_t aux = 0;
fNblock = nb;
fPos = new Long64_t[nb];
fLen = new Int_t[nb];
for(Int_t i=0; i < nb; i++){
fPos[i] = offset[i];
fLen[i] = length[i];
aux += fLen[i];
}
fFullSize = aux;
fBuffer = (char*) realloc(fBuffer, fFullSize);
}
<commit_msg>fix OSX compilation issue.<commit_after>#ifndef ROOT_TFPBlock
#include "TFPBlock.h"
#endif
#include <cstdlib>
#ifndef __APPLE__
#include <malloc.h>
#endif
ClassImp(TFPBlock)
//__________________________________________________________________
//constructor
TFPBlock::TFPBlock(Long64_t* offset, Int_t* length, Int_t nb)
{
Int_t aux = 0;
fNblock = nb;
fPos = new Long64_t[nb];
fLen = new Int_t[nb];
for (Int_t i=0; i < nb; i++){
fPos[i] = offset[i];
fLen[i] = length[i];
aux += length[i];
}
fFullSize = aux;
fBuffer = new char[fFullSize];
}
//__________________________________________________________________
//destructor
TFPBlock::~TFPBlock()
{
delete[] fPos;
delete[] fLen;
delete[] fBuffer;
}
//__________________________________________________________________
Long64_t* TFPBlock::GetPos()
{
// Get pointer to the array of postions.
return fPos;
}
//__________________________________________________________________
Int_t* TFPBlock::GetLen()
{
// Get pointer to the array of lengths.
return fLen;
}
//__________________________________________________________________
Int_t TFPBlock::GetFullSize()
{
// Return size of the block.
return fFullSize;
}
//__________________________________________________________________
Int_t TFPBlock::GetNoElem()
{
// Return number of elements in the block.
return fNblock;
}
//__________________________________________________________________
Long64_t TFPBlock::GetPos(Int_t i)
{
// Get position of the element at index i.
return fPos[i];
}
//__________________________________________________________________
Int_t TFPBlock::GetLen(Int_t i)
{
// Get length of the element at index i.
return fLen[i];
}
//__________________________________________________________________
char* TFPBlock::GetBuffer()
{
// Get block buffer.
return fBuffer;
}
//__________________________________________________________________
void TFPBlock::SetBuffer(char* buf)
{
//Set block buffer.
fBuffer = buf;
}
//__________________________________________________________________
void TFPBlock::ReallocBlock(Long64_t* offset, Int_t* length, Int_t nb)
{
// Reallocate the block's buffer based on the length
// of the elements it will contain.
Int_t aux = 0;
fNblock = nb;
fPos = new Long64_t[nb];
fLen = new Int_t[nb];
for(Int_t i=0; i < nb; i++){
fPos[i] = offset[i];
fLen[i] = length[i];
aux += fLen[i];
}
fFullSize = aux;
fBuffer = (char*) realloc(fBuffer, fFullSize);
}
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _MSC_VER
#pragma warning( 4: 4786 )
#endif
// class-interface header
#include "WorldWeapons.h"
// system headers
#include <vector>
// common-interface headers
#include "TimeKeeper.h"
#include "ShotUpdate.h"
#include "Protocol.h"
#include "Address.h"
#include "StateDatabase.h"
char *getDirectMessageBuffer();
void broadcastMessage(uint16_t code, int len, const void *msg);
WorldWeapons::WorldWeapons()
: worldShotId(0)
{
}
WorldWeapons::~WorldWeapons()
{
clear();
}
void WorldWeapons::clear(void)
{
for (std::vector<Weapon*>::iterator it = weapons.begin();
it != weapons.end(); ++it) {
Weapon *w = *it;
delete w;
}
weapons.clear();
}
float WorldWeapons::nextTime ()
{
TimeKeeper nextShot = TimeKeeper::getSunExplodeTime();
for (std::vector<Weapon*>::iterator it = weapons.begin();
it != weapons.end(); ++it) {
Weapon *w = *it;
if (w->nextTime <= nextShot) {
nextShot = w->nextTime;
}
}
return (float)(nextShot - TimeKeeper::getCurrent());
}
int fireWorldWep ( FlagType* type, float lifetime, PlayerId player, float *pos, float tilt, float direction, int shotID, float dt )
{
void *buf, *bufStart = getDirectMessageBuffer();
FiringInfo firingInfo;
firingInfo.flagType = type;
firingInfo.lifetime = lifetime;
firingInfo.shot.player = player;
memmove(firingInfo.shot.pos, pos, 3 * sizeof(float));
float shotSpeed = BZDB.eval(StateDatabase::BZDB_SHOTSPEED);
const float tiltFactor = cosf(tilt);
firingInfo.shot.vel[0] = shotSpeed * tiltFactor * cosf(direction);
firingInfo.shot.vel[1] = shotSpeed * tiltFactor * sinf(direction);
firingInfo.shot.vel[2] = shotSpeed * sinf(tilt);
firingInfo.shot.id = shotID;
firingInfo.shot.dt = dt;
buf = firingInfo.pack(bufStart);
if (BZDB.isTrue(StateDatabase::BZDB_WEAPONS)) {
broadcastMessage(MsgShotBegin, (char *)buf - (char *)bufStart, bufStart);
}
return shotID;
}
void WorldWeapons::fire()
{
TimeKeeper nowTime = TimeKeeper::getCurrent();
for (std::vector<Weapon*>::iterator it = weapons.begin();
it != weapons.end(); ++it) {
Weapon *w = *it;
if (w->nextTime <= nowTime) {
fireWorldWep( (FlagType*)w->type,BZDB.eval(StateDatabase::BZDB_RELOADTIME),
ServerPlayer,w->origin,w->tilt,w->direction,
worldShotId++,0);
if (worldShotId > 30) // Maximum of 30 world shots
worldShotId = 0;
//Set up timer for next shot, and eat any shots that have been missed
while (w->nextTime <= nowTime) {
w->nextTime += w->delay[w->nextDelay];
w->nextDelay++;
if (w->nextDelay == (int)w->delay.size()) {
w->nextDelay = 0;
}
}
}
}
}
void WorldWeapons::add(const FlagType *type, const float *origin,
float direction, float tilt,
float initdelay, const std::vector<float> &delay,
TimeKeeper &sync)
{
Weapon *w = new Weapon();
w->type = type;
memmove(&w->origin, origin, 3*sizeof(float));
w->direction = direction;
w->tilt = tilt;
w->nextTime = sync;
w->nextTime += initdelay;
w->initDelay = initdelay;
w->nextDelay = 0;
w->delay = delay;
weapons.push_back(w);
}
unsigned int WorldWeapons::count(void)
{
return weapons.size();
}
void * WorldWeapons::pack(void *buf) const
{
buf = nboPackUInt(buf, weapons.size());
for (unsigned int i=0 ; i < weapons.size(); i++) {
const Weapon *w = (const Weapon *) weapons[i];
buf = w->type->pack (buf);
buf = nboPackVector(buf, w->origin);
buf = nboPackFloat(buf, w->direction);
buf = nboPackFloat(buf, w->initDelay);
buf = nboPackUShort(buf, w->delay.size());
for (unsigned int j = 0; j < w->delay.size(); j++) {
buf = nboPackFloat(buf, w->delay[j]);
}
}
return buf;
}
int WorldWeapons::packSize(void) const
{
int fullSize = 0;
fullSize += sizeof(uint32_t);
for (unsigned int i=0 ; i < weapons.size(); i++) {
const Weapon *w = (const Weapon *) weapons[i];
fullSize += FlagType::packSize; // flag type
fullSize += sizeof(float[3]); // pos
fullSize += sizeof(float); // direction
fullSize += sizeof(float); // init delay
fullSize += sizeof(uint16_t); // delay count
for (unsigned int j = 0; j < w->delay.size(); j++) {
fullSize += sizeof(float);
}
}
return fullSize;
}
//----------WorldWeaponGlobalEventHandaler---------------------
// where we do the world weapon handaling for event based shots since they are not realy done by the "world"
WorldWeaponGlobalEventHandaler::WorldWeaponGlobalEventHandaler(FlagType *_type, const float *_origin, float _direction, float _tilt)
{
type = _type;
if ( _origin)
memcpy(origin,_origin,sizeof(float)*3);
else
origin[0] = origin[1] = origin[2] = 0.0f;
direction = _direction;
tilt = _tilt;
}
WorldWeaponGlobalEventHandaler::~WorldWeaponGlobalEventHandaler()
{
}
void WorldWeaponGlobalEventHandaler::process (BaseEventData */*eventData*/)
{
fireWorldWep( type,BZDB.eval(StateDatabase::BZDB_RELOADTIME),
ServerPlayer,origin,tilt,direction,0,0);
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>use so called "unused" variable so that it will compile on windows ( can't have a comment in the middle of a param list ).<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _MSC_VER
#pragma warning( 4: 4786 )
#endif
// class-interface header
#include "WorldWeapons.h"
// system headers
#include <vector>
// common-interface headers
#include "TimeKeeper.h"
#include "ShotUpdate.h"
#include "Protocol.h"
#include "Address.h"
#include "StateDatabase.h"
char *getDirectMessageBuffer();
void broadcastMessage(uint16_t code, int len, const void *msg);
WorldWeapons::WorldWeapons()
: worldShotId(0)
{
}
WorldWeapons::~WorldWeapons()
{
clear();
}
void WorldWeapons::clear(void)
{
for (std::vector<Weapon*>::iterator it = weapons.begin();
it != weapons.end(); ++it) {
Weapon *w = *it;
delete w;
}
weapons.clear();
}
float WorldWeapons::nextTime ()
{
TimeKeeper nextShot = TimeKeeper::getSunExplodeTime();
for (std::vector<Weapon*>::iterator it = weapons.begin();
it != weapons.end(); ++it) {
Weapon *w = *it;
if (w->nextTime <= nextShot) {
nextShot = w->nextTime;
}
}
return (float)(nextShot - TimeKeeper::getCurrent());
}
int fireWorldWep ( FlagType* type, float lifetime, PlayerId player, float *pos, float tilt, float direction, int shotID, float dt )
{
void *buf, *bufStart = getDirectMessageBuffer();
FiringInfo firingInfo;
firingInfo.flagType = type;
firingInfo.lifetime = lifetime;
firingInfo.shot.player = player;
memmove(firingInfo.shot.pos, pos, 3 * sizeof(float));
float shotSpeed = BZDB.eval(StateDatabase::BZDB_SHOTSPEED);
const float tiltFactor = cosf(tilt);
firingInfo.shot.vel[0] = shotSpeed * tiltFactor * cosf(direction);
firingInfo.shot.vel[1] = shotSpeed * tiltFactor * sinf(direction);
firingInfo.shot.vel[2] = shotSpeed * sinf(tilt);
firingInfo.shot.id = shotID;
firingInfo.shot.dt = dt;
buf = firingInfo.pack(bufStart);
if (BZDB.isTrue(StateDatabase::BZDB_WEAPONS)) {
broadcastMessage(MsgShotBegin, (char *)buf - (char *)bufStart, bufStart);
}
return shotID;
}
void WorldWeapons::fire()
{
TimeKeeper nowTime = TimeKeeper::getCurrent();
for (std::vector<Weapon*>::iterator it = weapons.begin();
it != weapons.end(); ++it) {
Weapon *w = *it;
if (w->nextTime <= nowTime) {
fireWorldWep( (FlagType*)w->type,BZDB.eval(StateDatabase::BZDB_RELOADTIME),
ServerPlayer,w->origin,w->tilt,w->direction,
worldShotId++,0);
if (worldShotId > 30) // Maximum of 30 world shots
worldShotId = 0;
//Set up timer for next shot, and eat any shots that have been missed
while (w->nextTime <= nowTime) {
w->nextTime += w->delay[w->nextDelay];
w->nextDelay++;
if (w->nextDelay == (int)w->delay.size()) {
w->nextDelay = 0;
}
}
}
}
}
void WorldWeapons::add(const FlagType *type, const float *origin,
float direction, float tilt,
float initdelay, const std::vector<float> &delay,
TimeKeeper &sync)
{
Weapon *w = new Weapon();
w->type = type;
memmove(&w->origin, origin, 3*sizeof(float));
w->direction = direction;
w->tilt = tilt;
w->nextTime = sync;
w->nextTime += initdelay;
w->initDelay = initdelay;
w->nextDelay = 0;
w->delay = delay;
weapons.push_back(w);
}
unsigned int WorldWeapons::count(void)
{
return weapons.size();
}
void * WorldWeapons::pack(void *buf) const
{
buf = nboPackUInt(buf, weapons.size());
for (unsigned int i=0 ; i < weapons.size(); i++) {
const Weapon *w = (const Weapon *) weapons[i];
buf = w->type->pack (buf);
buf = nboPackVector(buf, w->origin);
buf = nboPackFloat(buf, w->direction);
buf = nboPackFloat(buf, w->initDelay);
buf = nboPackUShort(buf, w->delay.size());
for (unsigned int j = 0; j < w->delay.size(); j++) {
buf = nboPackFloat(buf, w->delay[j]);
}
}
return buf;
}
int WorldWeapons::packSize(void) const
{
int fullSize = 0;
fullSize += sizeof(uint32_t);
for (unsigned int i=0 ; i < weapons.size(); i++) {
const Weapon *w = (const Weapon *) weapons[i];
fullSize += FlagType::packSize; // flag type
fullSize += sizeof(float[3]); // pos
fullSize += sizeof(float); // direction
fullSize += sizeof(float); // init delay
fullSize += sizeof(uint16_t); // delay count
for (unsigned int j = 0; j < w->delay.size(); j++) {
fullSize += sizeof(float);
}
}
return fullSize;
}
//----------WorldWeaponGlobalEventHandaler---------------------
// where we do the world weapon handaling for event based shots since they are not realy done by the "world"
WorldWeaponGlobalEventHandaler::WorldWeaponGlobalEventHandaler(FlagType *_type, const float *_origin, float _direction, float _tilt)
{
type = _type;
if ( _origin)
memcpy(origin,_origin,sizeof(float)*3);
else
origin[0] = origin[1] = origin[2] = 0.0f;
direction = _direction;
tilt = _tilt;
}
WorldWeaponGlobalEventHandaler::~WorldWeaponGlobalEventHandaler()
{
}
void WorldWeaponGlobalEventHandaler::process (BaseEventData *eventData)
{
if (eventData->eventType != eCaptureEvent)
return;
fireWorldWep( type,BZDB.eval(StateDatabase::BZDB_RELOADTIME),
ServerPlayer,origin,tilt,direction,0,0);
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>#include <Rcpp.h>
#include "ZeroMQ.hpp"
class CMQWorker { // : public ZeroMQ {
public:
CMQWorker(std::string addr): ctx(new zmq::context_t(1)) {
sock = zmq::socket_t(*ctx, ZMQ_REQ);
sock.set(zmq::sockopt::connect_timeout, 10000);
sock.connect(addr);
}
~CMQWorker() {
sock.set(zmq::sockopt::linger, 0);
sock.close();
ctx->close();
delete ctx;
}
void send(SEXP data) {
if (TYPEOF(data) != RAWSXP)
data = R_serialize(data, R_NilValue);
zmq::message_t content(Rf_xlength(data));
memcpy(content.data(), RAW(data), Rf_xlength(data));
sock.send(content, zmq::send_flags::none);
}
SEXP receive() {
zmq::message_t msg;
sock.recv(msg, zmq::recv_flags::none);
SEXP ans = Rf_allocVector(RAWSXP, msg.size());
memcpy(RAW(ans), msg.data(), msg.size());
return R_unserialize(ans);
}
SEXP get_data_redirect(std::string addr, SEXP data) {
auto rsock = zmq::socket_t(*ctx, ZMQ_REQ);
rsock.set(zmq::sockopt::connect_timeout, 10000);
rsock.connect(addr);
data = R_serialize(data, R_NilValue);
zmq::message_t content(Rf_xlength(data));
memcpy(content.data(), RAW(data), Rf_xlength(data));
rsock.send(content, zmq::send_flags::none);
zmq::message_t msg;
rsock.recv(msg, zmq::recv_flags::none);
SEXP ans = Rf_allocVector(RAWSXP, msg.size());
memcpy(RAW(ans), msg.data(), msg.size());
rsock.set(zmq::sockopt::linger, 0);
rsock.close();
return R_unserialize(ans);
}
void main_loop() {
}
private:
zmq::context_t *ctx;
zmq::socket_t sock;
};
RCPP_MODULE(cmq_worker) {
using namespace Rcpp;
class_<CMQWorker>("CMQWorker")
.constructor<std::string>()
.method("main_loop", &CMQWorker::main_loop)
.method("get_data_redirect", &CMQWorker::get_data_redirect)
.method("send", &CMQWorker::send)
.method("receive", &CMQWorker::receive)
;
}
<commit_msg>add and poll disc monitor<commit_after>#include <Rcpp.h>
#include "ZeroMQ.hpp"
class CMQWorker { // : public ZeroMQ {
public:
CMQWorker(std::string addr): ctx(new zmq::context_t(1)) {
sock = zmq::socket_t(*ctx, ZMQ_REQ);
sock.set(zmq::sockopt::connect_timeout, 10000);
sock.connect(addr);
int rc = zmq_socket_monitor(sock, "inproc://monitor", ZMQ_EVENT_DISCONNECTED);
if (rc < 0) // C API needs return value check
Rf_error("failed to create socket monitor");
mon = zmq::socket_t(*ctx, ZMQ_PAIR);
mon.connect("inproc://monitor");
}
~CMQWorker() {
mon.set(zmq::sockopt::linger, 0);
mon.close();
sock.set(zmq::sockopt::linger, 0);
sock.close();
ctx->close();
delete ctx;
}
void send(SEXP data) {
if (TYPEOF(data) != RAWSXP)
data = R_serialize(data, R_NilValue);
zmq::message_t content(Rf_xlength(data));
memcpy(content.data(), RAW(data), Rf_xlength(data));
sock.send(content, zmq::send_flags::none);
}
SEXP receive() {
poll();
zmq::message_t msg;
sock.recv(msg, zmq::recv_flags::none);
SEXP ans = Rf_allocVector(RAWSXP, msg.size());
memcpy(RAW(ans), msg.data(), msg.size());
return R_unserialize(ans);
}
SEXP get_data_redirect(std::string addr, SEXP data) {
//todo: this should ideally also be monitored (although short connection)
auto rsock = zmq::socket_t(*ctx, ZMQ_REQ);
rsock.set(zmq::sockopt::connect_timeout, 10000);
rsock.connect(addr);
data = R_serialize(data, R_NilValue);
zmq::message_t content(Rf_xlength(data));
memcpy(content.data(), RAW(data), Rf_xlength(data));
rsock.send(content, zmq::send_flags::none);
zmq::message_t msg;
rsock.recv(msg, zmq::recv_flags::none);
SEXP ans = Rf_allocVector(RAWSXP, msg.size());
memcpy(RAW(ans), msg.data(), msg.size());
rsock.set(zmq::sockopt::linger, 0);
rsock.close();
return R_unserialize(ans);
}
void main_loop() {
}
private:
zmq::context_t *ctx;
zmq::socket_t sock;
zmq::socket_t mon;
void poll() {
auto pitems = std::vector<zmq::pollitem_t>(2);
pitems[0].socket = sock;
pitems[0].events = ZMQ_POLLIN;
pitems[1].socket = mon;
pitems[1].events = ZMQ_POLLIN;
int total_sock_ev = 0;
do {
try {
zmq::poll(pitems, std::chrono::duration<long int>::max());
} catch (zmq::error_t const &e) {
if (errno != EINTR || pending_interrupt())
Rf_error(e.what());
}
if (pitems[1].revents > 0)
Rf_error("Unexpected peer disconnect");
total_sock_ev = pitems[0].revents;
} while (total_sock_ev == 0);
}
};
RCPP_MODULE(cmq_worker) {
using namespace Rcpp;
class_<CMQWorker>("CMQWorker")
.constructor<std::string>()
.method("main_loop", &CMQWorker::main_loop)
.method("get_data_redirect", &CMQWorker::get_data_redirect)
.method("send", &CMQWorker::send)
.method("receive", &CMQWorker::receive)
;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/common_types.h"
#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
#include "webrtc/modules/video_coding/codecs/interface/video_codec_interface.h"
#include "webrtc/modules/video_coding/main/source/encoded_frame.h"
#include "webrtc/modules/video_coding/main/source/jitter_buffer.h"
#include "webrtc/modules/video_coding/main/source/packet.h"
#include "webrtc/modules/video_coding/main/source/video_coding_impl.h"
#include "webrtc/system_wrappers/include/clock.h"
namespace webrtc {
namespace vcm {
int64_t
VCMProcessTimer::Period() const {
return _periodMs;
}
int64_t
VCMProcessTimer::TimeUntilProcess() const {
const int64_t time_since_process = _clock->TimeInMilliseconds() - _latestMs;
const int64_t time_until_process = _periodMs - time_since_process;
return std::max<int64_t>(time_until_process, 0);
}
void
VCMProcessTimer::Processed() {
_latestMs = _clock->TimeInMilliseconds();
}
} // namespace vcm
namespace {
// This wrapper provides a way to modify the callback without the need to expose
// a register method all the way down to the function calling it.
class EncodedImageCallbackWrapper : public EncodedImageCallback {
public:
EncodedImageCallbackWrapper()
: cs_(CriticalSectionWrapper::CreateCriticalSection()), callback_(NULL) {}
virtual ~EncodedImageCallbackWrapper() {}
void Register(EncodedImageCallback* callback) {
CriticalSectionScoped cs(cs_.get());
callback_ = callback;
}
// TODO(andresp): Change to void as return value is ignored.
virtual int32_t Encoded(const EncodedImage& encoded_image,
const CodecSpecificInfo* codec_specific_info,
const RTPFragmentationHeader* fragmentation) {
CriticalSectionScoped cs(cs_.get());
if (callback_)
return callback_->Encoded(
encoded_image, codec_specific_info, fragmentation);
return 0;
}
private:
rtc::scoped_ptr<CriticalSectionWrapper> cs_;
EncodedImageCallback* callback_ GUARDED_BY(cs_);
};
class VideoCodingModuleImpl : public VideoCodingModule {
public:
VideoCodingModuleImpl(Clock* clock,
EventFactory* event_factory,
bool owns_event_factory,
VideoEncoderRateObserver* encoder_rate_observer,
VCMQMSettingsCallback* qm_settings_callback)
: VideoCodingModule(),
sender_(new vcm::VideoSender(clock,
&post_encode_callback_,
encoder_rate_observer,
qm_settings_callback)),
receiver_(new vcm::VideoReceiver(clock, event_factory)),
own_event_factory_(owns_event_factory ? event_factory : NULL) {}
virtual ~VideoCodingModuleImpl() {
sender_.reset();
receiver_.reset();
own_event_factory_.reset();
}
int64_t TimeUntilNextProcess() override {
int64_t sender_time = sender_->TimeUntilNextProcess();
int64_t receiver_time = receiver_->TimeUntilNextProcess();
assert(sender_time >= 0);
assert(receiver_time >= 0);
return VCM_MIN(sender_time, receiver_time);
}
int32_t Process() override {
int32_t sender_return = sender_->Process();
int32_t receiver_return = receiver_->Process();
if (sender_return != VCM_OK)
return sender_return;
return receiver_return;
}
int32_t RegisterSendCodec(const VideoCodec* sendCodec,
uint32_t numberOfCores,
uint32_t maxPayloadSize) override {
return sender_->RegisterSendCodec(sendCodec, numberOfCores, maxPayloadSize);
}
const VideoCodec& GetSendCodec() const override {
return sender_->GetSendCodec();
}
// DEPRECATED.
int32_t SendCodec(VideoCodec* currentSendCodec) const override {
return sender_->SendCodecBlocking(currentSendCodec);
}
// DEPRECATED.
VideoCodecType SendCodec() const override {
return sender_->SendCodecBlocking();
}
int32_t RegisterExternalEncoder(VideoEncoder* externalEncoder,
uint8_t payloadType,
bool internalSource) override {
return sender_->RegisterExternalEncoder(
externalEncoder, payloadType, internalSource);
}
int Bitrate(unsigned int* bitrate) const override {
return sender_->Bitrate(bitrate);
}
int FrameRate(unsigned int* framerate) const override {
return sender_->FrameRate(framerate);
}
int32_t SetChannelParameters(uint32_t target_bitrate, // bits/s.
uint8_t lossRate,
int64_t rtt) override {
return sender_->SetChannelParameters(target_bitrate, lossRate, rtt);
}
int32_t RegisterTransportCallback(
VCMPacketizationCallback* transport) override {
return sender_->RegisterTransportCallback(transport);
}
int32_t RegisterSendStatisticsCallback(
VCMSendStatisticsCallback* sendStats) override {
return sender_->RegisterSendStatisticsCallback(sendStats);
}
int32_t RegisterProtectionCallback(
VCMProtectionCallback* protection) override {
return sender_->RegisterProtectionCallback(protection);
}
int32_t SetVideoProtection(VCMVideoProtection videoProtection,
bool enable) override {
// TODO(pbos): Remove enable from receive-side protection modes as well.
if (enable)
sender_->SetVideoProtection(videoProtection);
return receiver_->SetVideoProtection(videoProtection, enable);
}
int32_t AddVideoFrame(const VideoFrame& videoFrame,
const VideoContentMetrics* contentMetrics,
const CodecSpecificInfo* codecSpecificInfo) override {
return sender_->AddVideoFrame(
videoFrame, contentMetrics, codecSpecificInfo);
}
int32_t IntraFrameRequest(int stream_index) override {
return sender_->IntraFrameRequest(stream_index);
}
int32_t EnableFrameDropper(bool enable) override {
return sender_->EnableFrameDropper(enable);
}
void SuspendBelowMinBitrate() override {
return sender_->SuspendBelowMinBitrate();
}
bool VideoSuspended() const override { return sender_->VideoSuspended(); }
int32_t RegisterReceiveCodec(const VideoCodec* receiveCodec,
int32_t numberOfCores,
bool requireKeyFrame) override {
return receiver_->RegisterReceiveCodec(
receiveCodec, numberOfCores, requireKeyFrame);
}
int32_t RegisterExternalDecoder(VideoDecoder* externalDecoder,
uint8_t payloadType,
bool internalRenderTiming) override {
return receiver_->RegisterExternalDecoder(
externalDecoder, payloadType, internalRenderTiming);
}
int32_t RegisterReceiveCallback(
VCMReceiveCallback* receiveCallback) override {
return receiver_->RegisterReceiveCallback(receiveCallback);
}
int32_t RegisterReceiveStatisticsCallback(
VCMReceiveStatisticsCallback* receiveStats) override {
return receiver_->RegisterReceiveStatisticsCallback(receiveStats);
}
int32_t RegisterDecoderTimingCallback(
VCMDecoderTimingCallback* decoderTiming) override {
return receiver_->RegisterDecoderTimingCallback(decoderTiming);
}
int32_t RegisterFrameTypeCallback(
VCMFrameTypeCallback* frameTypeCallback) override {
return receiver_->RegisterFrameTypeCallback(frameTypeCallback);
}
int32_t RegisterPacketRequestCallback(
VCMPacketRequestCallback* callback) override {
return receiver_->RegisterPacketRequestCallback(callback);
}
int RegisterRenderBufferSizeCallback(
VCMRenderBufferSizeCallback* callback) override {
return receiver_->RegisterRenderBufferSizeCallback(callback);
}
int32_t Decode(uint16_t maxWaitTimeMs) override {
return receiver_->Decode(maxWaitTimeMs);
}
int32_t ResetDecoder() override { return receiver_->ResetDecoder(); }
int32_t ReceiveCodec(VideoCodec* currentReceiveCodec) const override {
return receiver_->ReceiveCodec(currentReceiveCodec);
}
VideoCodecType ReceiveCodec() const override {
return receiver_->ReceiveCodec();
}
int32_t IncomingPacket(const uint8_t* incomingPayload,
size_t payloadLength,
const WebRtcRTPHeader& rtpInfo) override {
return receiver_->IncomingPacket(incomingPayload, payloadLength, rtpInfo);
}
int32_t SetMinimumPlayoutDelay(uint32_t minPlayoutDelayMs) override {
return receiver_->SetMinimumPlayoutDelay(minPlayoutDelayMs);
}
int32_t SetRenderDelay(uint32_t timeMS) override {
return receiver_->SetRenderDelay(timeMS);
}
int32_t Delay() const override { return receiver_->Delay(); }
uint32_t DiscardedPackets() const override {
return receiver_->DiscardedPackets();
}
int SetReceiverRobustnessMode(ReceiverRobustness robustnessMode,
VCMDecodeErrorMode errorMode) override {
return receiver_->SetReceiverRobustnessMode(robustnessMode, errorMode);
}
void SetNackSettings(size_t max_nack_list_size,
int max_packet_age_to_nack,
int max_incomplete_time_ms) override {
return receiver_->SetNackSettings(
max_nack_list_size, max_packet_age_to_nack, max_incomplete_time_ms);
}
void SetDecodeErrorMode(VCMDecodeErrorMode decode_error_mode) override {
return receiver_->SetDecodeErrorMode(decode_error_mode);
}
int SetMinReceiverDelay(int desired_delay_ms) override {
return receiver_->SetMinReceiverDelay(desired_delay_ms);
}
int32_t SetReceiveChannelParameters(int64_t rtt) override {
return receiver_->SetReceiveChannelParameters(rtt);
}
void RegisterPreDecodeImageCallback(EncodedImageCallback* observer) override {
receiver_->RegisterPreDecodeImageCallback(observer);
}
void RegisterPostEncodeImageCallback(
EncodedImageCallback* observer) override {
post_encode_callback_.Register(observer);
}
void TriggerDecoderShutdown() override {
receiver_->TriggerDecoderShutdown();
}
private:
EncodedImageCallbackWrapper post_encode_callback_;
// TODO(tommi): Change sender_ and receiver_ to be non pointers
// (construction is 1 alloc instead of 3).
rtc::scoped_ptr<vcm::VideoSender> sender_;
rtc::scoped_ptr<vcm::VideoReceiver> receiver_;
rtc::scoped_ptr<EventFactory> own_event_factory_;
};
} // namespace
uint8_t VideoCodingModule::NumberOfCodecs() {
return VCMCodecDataBase::NumberOfCodecs();
}
int32_t VideoCodingModule::Codec(uint8_t listId, VideoCodec* codec) {
if (codec == NULL) {
return VCM_PARAMETER_ERROR;
}
return VCMCodecDataBase::Codec(listId, codec) ? 0 : -1;
}
int32_t VideoCodingModule::Codec(VideoCodecType codecType, VideoCodec* codec) {
if (codec == NULL) {
return VCM_PARAMETER_ERROR;
}
return VCMCodecDataBase::Codec(codecType, codec) ? 0 : -1;
}
VideoCodingModule* VideoCodingModule::Create(
Clock* clock,
VideoEncoderRateObserver* encoder_rate_observer,
VCMQMSettingsCallback* qm_settings_callback) {
return new VideoCodingModuleImpl(clock, new EventFactoryImpl, true,
encoder_rate_observer, qm_settings_callback);
}
VideoCodingModule* VideoCodingModule::Create(
Clock* clock,
EventFactory* event_factory) {
assert(clock);
assert(event_factory);
return new VideoCodingModuleImpl(clock, event_factory, false, nullptr,
nullptr);
}
void VideoCodingModule::Destroy(VideoCodingModule* module) {
if (module != NULL) {
delete static_cast<VideoCodingModuleImpl*>(module);
}
}
} // namespace webrtc
<commit_msg>Remove scoped_ptrs for VCM sender_ and receiver_.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/common_types.h"
#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
#include "webrtc/modules/video_coding/codecs/interface/video_codec_interface.h"
#include "webrtc/modules/video_coding/main/source/encoded_frame.h"
#include "webrtc/modules/video_coding/main/source/jitter_buffer.h"
#include "webrtc/modules/video_coding/main/source/packet.h"
#include "webrtc/modules/video_coding/main/source/video_coding_impl.h"
#include "webrtc/system_wrappers/include/clock.h"
namespace webrtc {
namespace vcm {
int64_t
VCMProcessTimer::Period() const {
return _periodMs;
}
int64_t
VCMProcessTimer::TimeUntilProcess() const {
const int64_t time_since_process = _clock->TimeInMilliseconds() - _latestMs;
const int64_t time_until_process = _periodMs - time_since_process;
return std::max<int64_t>(time_until_process, 0);
}
void
VCMProcessTimer::Processed() {
_latestMs = _clock->TimeInMilliseconds();
}
} // namespace vcm
namespace {
// This wrapper provides a way to modify the callback without the need to expose
// a register method all the way down to the function calling it.
class EncodedImageCallbackWrapper : public EncodedImageCallback {
public:
EncodedImageCallbackWrapper()
: cs_(CriticalSectionWrapper::CreateCriticalSection()), callback_(NULL) {}
virtual ~EncodedImageCallbackWrapper() {}
void Register(EncodedImageCallback* callback) {
CriticalSectionScoped cs(cs_.get());
callback_ = callback;
}
// TODO(andresp): Change to void as return value is ignored.
virtual int32_t Encoded(const EncodedImage& encoded_image,
const CodecSpecificInfo* codec_specific_info,
const RTPFragmentationHeader* fragmentation) {
CriticalSectionScoped cs(cs_.get());
if (callback_)
return callback_->Encoded(
encoded_image, codec_specific_info, fragmentation);
return 0;
}
private:
rtc::scoped_ptr<CriticalSectionWrapper> cs_;
EncodedImageCallback* callback_ GUARDED_BY(cs_);
};
class VideoCodingModuleImpl : public VideoCodingModule {
public:
VideoCodingModuleImpl(Clock* clock,
EventFactory* event_factory,
bool owns_event_factory,
VideoEncoderRateObserver* encoder_rate_observer,
VCMQMSettingsCallback* qm_settings_callback)
: VideoCodingModule(),
sender_(clock,
&post_encode_callback_,
encoder_rate_observer,
qm_settings_callback),
receiver_(clock, event_factory),
own_event_factory_(owns_event_factory ? event_factory : NULL) {}
virtual ~VideoCodingModuleImpl() {
own_event_factory_.reset();
}
int64_t TimeUntilNextProcess() override {
int64_t sender_time = sender_.TimeUntilNextProcess();
int64_t receiver_time = receiver_.TimeUntilNextProcess();
assert(sender_time >= 0);
assert(receiver_time >= 0);
return VCM_MIN(sender_time, receiver_time);
}
int32_t Process() override {
int32_t sender_return = sender_.Process();
int32_t receiver_return = receiver_.Process();
if (sender_return != VCM_OK)
return sender_return;
return receiver_return;
}
int32_t RegisterSendCodec(const VideoCodec* sendCodec,
uint32_t numberOfCores,
uint32_t maxPayloadSize) override {
return sender_.RegisterSendCodec(sendCodec, numberOfCores, maxPayloadSize);
}
const VideoCodec& GetSendCodec() const override {
return sender_.GetSendCodec();
}
// DEPRECATED.
int32_t SendCodec(VideoCodec* currentSendCodec) const override {
return sender_.SendCodecBlocking(currentSendCodec);
}
// DEPRECATED.
VideoCodecType SendCodec() const override {
return sender_.SendCodecBlocking();
}
int32_t RegisterExternalEncoder(VideoEncoder* externalEncoder,
uint8_t payloadType,
bool internalSource) override {
return sender_.RegisterExternalEncoder(externalEncoder, payloadType,
internalSource);
}
int Bitrate(unsigned int* bitrate) const override {
return sender_.Bitrate(bitrate);
}
int FrameRate(unsigned int* framerate) const override {
return sender_.FrameRate(framerate);
}
int32_t SetChannelParameters(uint32_t target_bitrate, // bits/s.
uint8_t lossRate,
int64_t rtt) override {
return sender_.SetChannelParameters(target_bitrate, lossRate, rtt);
}
int32_t RegisterTransportCallback(
VCMPacketizationCallback* transport) override {
return sender_.RegisterTransportCallback(transport);
}
int32_t RegisterSendStatisticsCallback(
VCMSendStatisticsCallback* sendStats) override {
return sender_.RegisterSendStatisticsCallback(sendStats);
}
int32_t RegisterProtectionCallback(
VCMProtectionCallback* protection) override {
return sender_.RegisterProtectionCallback(protection);
}
int32_t SetVideoProtection(VCMVideoProtection videoProtection,
bool enable) override {
// TODO(pbos): Remove enable from receive-side protection modes as well.
if (enable)
sender_.SetVideoProtection(videoProtection);
return receiver_.SetVideoProtection(videoProtection, enable);
}
int32_t AddVideoFrame(const VideoFrame& videoFrame,
const VideoContentMetrics* contentMetrics,
const CodecSpecificInfo* codecSpecificInfo) override {
return sender_.AddVideoFrame(videoFrame, contentMetrics, codecSpecificInfo);
}
int32_t IntraFrameRequest(int stream_index) override {
return sender_.IntraFrameRequest(stream_index);
}
int32_t EnableFrameDropper(bool enable) override {
return sender_.EnableFrameDropper(enable);
}
void SuspendBelowMinBitrate() override {
return sender_.SuspendBelowMinBitrate();
}
bool VideoSuspended() const override { return sender_.VideoSuspended(); }
int32_t RegisterReceiveCodec(const VideoCodec* receiveCodec,
int32_t numberOfCores,
bool requireKeyFrame) override {
return receiver_.RegisterReceiveCodec(receiveCodec, numberOfCores,
requireKeyFrame);
}
int32_t RegisterExternalDecoder(VideoDecoder* externalDecoder,
uint8_t payloadType,
bool internalRenderTiming) override {
return receiver_.RegisterExternalDecoder(externalDecoder, payloadType,
internalRenderTiming);
}
int32_t RegisterReceiveCallback(
VCMReceiveCallback* receiveCallback) override {
return receiver_.RegisterReceiveCallback(receiveCallback);
}
int32_t RegisterReceiveStatisticsCallback(
VCMReceiveStatisticsCallback* receiveStats) override {
return receiver_.RegisterReceiveStatisticsCallback(receiveStats);
}
int32_t RegisterDecoderTimingCallback(
VCMDecoderTimingCallback* decoderTiming) override {
return receiver_.RegisterDecoderTimingCallback(decoderTiming);
}
int32_t RegisterFrameTypeCallback(
VCMFrameTypeCallback* frameTypeCallback) override {
return receiver_.RegisterFrameTypeCallback(frameTypeCallback);
}
int32_t RegisterPacketRequestCallback(
VCMPacketRequestCallback* callback) override {
return receiver_.RegisterPacketRequestCallback(callback);
}
int RegisterRenderBufferSizeCallback(
VCMRenderBufferSizeCallback* callback) override {
return receiver_.RegisterRenderBufferSizeCallback(callback);
}
int32_t Decode(uint16_t maxWaitTimeMs) override {
return receiver_.Decode(maxWaitTimeMs);
}
int32_t ResetDecoder() override { return receiver_.ResetDecoder(); }
int32_t ReceiveCodec(VideoCodec* currentReceiveCodec) const override {
return receiver_.ReceiveCodec(currentReceiveCodec);
}
VideoCodecType ReceiveCodec() const override {
return receiver_.ReceiveCodec();
}
int32_t IncomingPacket(const uint8_t* incomingPayload,
size_t payloadLength,
const WebRtcRTPHeader& rtpInfo) override {
return receiver_.IncomingPacket(incomingPayload, payloadLength, rtpInfo);
}
int32_t SetMinimumPlayoutDelay(uint32_t minPlayoutDelayMs) override {
return receiver_.SetMinimumPlayoutDelay(minPlayoutDelayMs);
}
int32_t SetRenderDelay(uint32_t timeMS) override {
return receiver_.SetRenderDelay(timeMS);
}
int32_t Delay() const override { return receiver_.Delay(); }
uint32_t DiscardedPackets() const override {
return receiver_.DiscardedPackets();
}
int SetReceiverRobustnessMode(ReceiverRobustness robustnessMode,
VCMDecodeErrorMode errorMode) override {
return receiver_.SetReceiverRobustnessMode(robustnessMode, errorMode);
}
void SetNackSettings(size_t max_nack_list_size,
int max_packet_age_to_nack,
int max_incomplete_time_ms) override {
return receiver_.SetNackSettings(max_nack_list_size, max_packet_age_to_nack,
max_incomplete_time_ms);
}
void SetDecodeErrorMode(VCMDecodeErrorMode decode_error_mode) override {
return receiver_.SetDecodeErrorMode(decode_error_mode);
}
int SetMinReceiverDelay(int desired_delay_ms) override {
return receiver_.SetMinReceiverDelay(desired_delay_ms);
}
int32_t SetReceiveChannelParameters(int64_t rtt) override {
return receiver_.SetReceiveChannelParameters(rtt);
}
void RegisterPreDecodeImageCallback(EncodedImageCallback* observer) override {
receiver_.RegisterPreDecodeImageCallback(observer);
}
void RegisterPostEncodeImageCallback(
EncodedImageCallback* observer) override {
post_encode_callback_.Register(observer);
}
void TriggerDecoderShutdown() override { receiver_.TriggerDecoderShutdown(); }
private:
EncodedImageCallbackWrapper post_encode_callback_;
vcm::VideoSender sender_;
vcm::VideoReceiver receiver_;
rtc::scoped_ptr<EventFactory> own_event_factory_;
};
} // namespace
uint8_t VideoCodingModule::NumberOfCodecs() {
return VCMCodecDataBase::NumberOfCodecs();
}
int32_t VideoCodingModule::Codec(uint8_t listId, VideoCodec* codec) {
if (codec == NULL) {
return VCM_PARAMETER_ERROR;
}
return VCMCodecDataBase::Codec(listId, codec) ? 0 : -1;
}
int32_t VideoCodingModule::Codec(VideoCodecType codecType, VideoCodec* codec) {
if (codec == NULL) {
return VCM_PARAMETER_ERROR;
}
return VCMCodecDataBase::Codec(codecType, codec) ? 0 : -1;
}
VideoCodingModule* VideoCodingModule::Create(
Clock* clock,
VideoEncoderRateObserver* encoder_rate_observer,
VCMQMSettingsCallback* qm_settings_callback) {
return new VideoCodingModuleImpl(clock, new EventFactoryImpl, true,
encoder_rate_observer, qm_settings_callback);
}
VideoCodingModule* VideoCodingModule::Create(
Clock* clock,
EventFactory* event_factory) {
assert(clock);
assert(event_factory);
return new VideoCodingModuleImpl(clock, event_factory, false, nullptr,
nullptr);
}
void VideoCodingModule::Destroy(VideoCodingModule* module) {
if (module != NULL) {
delete static_cast<VideoCodingModuleImpl*>(module);
}
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>#include "../../ppasskeeper-module.h"
#include "../../tokenizer.h"
#include <string>
#include <windows.h>
#include "list_pwd.h"
//Local definitions
static const char* baseKey="SOFTWARE\\PPassKeeper\\";
//local functions
std::string* last_error()
{
static std::string lerror;
return &lerror;
}
void setError(std::string error)
{
*(last_error())="PPK_SaveToRegistry : " + error;
}
bool getPassword(const char* key, ppk_data* edata)
{
static char tmpBuf[1000000];
HKEY hk;
if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, baseKey, 0, KEY_QUERY_VALUE, &hk))
{
DWORD size=sizeof(tmpBuf);
DWORD type;
long res=RegQueryValueEx(hk, key, 0, &type, (BYTE*)tmpBuf, &size);
RegCloseKey(hk);
if(res==ERROR_SUCCESS)
{
if(type==REG_BINARY)
{
edata->type=ppk_blob;
edata->blob.data=tmpBuf;
edata->blob.size=size;
return true;
}
else if(type==REG_SZ)
{
edata->type=ppk_string;
edata->string=tmpBuf;
return true;
}
else
{
setError("Unknown data type !");
return false;
}
}
else
return false;
}
else
return false;
}
bool setPassword(const char* key, const ppk_data edata)
{
HKEY hk;
if(!RegCreateKeyEx(HKEY_LOCAL_MACHINE, baseKey, 0, 0, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, 0, &hk, 0))
{
long res;
if(edata.type==ppk_string)
res=RegSetValueEx(hk, key, 0, REG_SZ, (const BYTE*)edata.string, strlen(edata.string)+1);
else if(edata.type==ppk_blob)
res=RegSetValueEx(hk, key, 0, REG_BINARY, (const BYTE*)edata.blob.data, edata.blob.size);
else
setError("setPassword : Undefined data type !");
RegCloseKey(hk);
return res==ERROR_SUCCESS;
}
else
return false;
}
bool removePassword(const char* key)
{
HKEY hk;
if(!RegCreateKeyEx(HKEY_LOCAL_MACHINE, baseKey, 0, 0, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, 0, &hk, 0))
{
long res=RegDeleteValue(hk, key);
RegCloseKey(hk);
return res==ERROR_SUCCESS;
}
else
return false;
}
std::string generateNetworkKey(std::string server, int port, std::string username)
{
return "ppasskeeper_network://"+username+"@"+server+":"+toString(port);
}
std::string generateApplicationKey(std::string application_name, std::string username)
{
return "ppasskeeper_app://"+username+"@"+application_name;
}
std::string generateItemKey(std::string key)
{
return "ppasskeeper_item://"+key;
}
//exported functions
extern "C" const char* getModuleID()
{
return "SaveToRegistry";
}
extern "C" const char* getModuleName()
{
return "SaveToRegistry - Store it into the registry";
}
extern "C" const int getABIVersion()
{
return 1;
}
extern "C" ppk_boolean isWritable()
{
return PPK_TRUE;
}
extern "C" ppk_security_level securityLevel(const char* module_id)
{
return ppk_sec_lowest;
}
//Get available flags
extern "C" unsigned int readFlagsAvailable()
{
return ppk_rf_none|ppk_rf_silent;
}
extern "C" unsigned int writeFlagsAvailable()
{
return ppk_wf_none|ppk_wf_silent;
}
extern "C" unsigned int listingFlagsAvailable()
{
return ppk_lf_none|ppk_lf_silent;
}
//List passwords available
std::string prefix(const ppk_entry entry)
{
std::string prefix="ppasskeeper_";
switch(entry.type)
{
case ppk_network:
prefix+="network";
break;
case ppk_application:
prefix+="app";
break;
case ppk_item:
prefix+="item";
break;
}
return prefix+"://";
}
extern "C" unsigned int getEntryListCount(unsigned int entry_types, unsigned int flags)
{
ListPwd pwdl;
return pwdl.getEntryListCount(baseKey, entry_types, flags);
}
extern "C" unsigned int getEntryList(unsigned int entry_types, ppk_entry *entryList, unsigned int nbEntries, unsigned int flags)
{
static ListPwd pwdl;
return pwdl.getEntryList(baseKey, entry_types, entryList, nbEntries, flags);
}
//Functions
extern "C" ppk_boolean getEntry(const ppk_entry entry, ppk_data *edata, unsigned int flags)
{
static std::string pwd;
std::string text;
if(entry.type==ppk_network)
text=generateNetworkKey(entry.net.host, entry.net.port, entry.net.login);
else if(entry.type==ppk_application)
text=generateApplicationKey(entry.app.app_name, entry.app.username);
else if(entry.type==ppk_item)
text=generateItemKey(entry.item);
else
{
setError("getEntry : Invalid entry type.");
return PPK_FALSE;
}
//if everything went fine
if(getPassword(text.c_str(), edata))
{
setError("");
return PPK_TRUE;
}
else
return PPK_FALSE;
}
extern "C" ppk_boolean setEntry(const ppk_entry entry, const ppk_data edata, unsigned int flags)
{
static std::string pwd;
std::string text;
if(entry.type==ppk_network)
text=generateNetworkKey(entry.net.host, entry.net.port, entry.net.login);
else if(entry.type==ppk_application)
text=generateApplicationKey(entry.app.app_name, entry.app.username);
else if(entry.type==ppk_item)
text=generateItemKey(entry.item);
else
{
setError("setEntry : Invalid entry type.");
return PPK_FALSE;
}
//if everything went fine
if(setPassword(text.c_str(), edata))
{
setError("");
return PPK_TRUE;
}
else
return PPK_FALSE;
}
extern "C" ppk_boolean removeEntry(const ppk_entry entry, unsigned int flags)
{
std::string text;
if(entry.type==ppk_network)
text=generateNetworkKey(entry.net.host, entry.net.port, entry.net.login);
else if(entry.type==ppk_application)
text=generateApplicationKey(entry.app.app_name, entry.app.username);
else if(entry.type==ppk_item)
text=generateItemKey(entry.item);
else
{
setError("removeEntry : Invalid entry type.");
return PPK_FALSE;
}
return removePassword(text.c_str())?PPK_TRUE:PPK_FALSE;
}
extern "C" ppk_boolean entryExists(const ppk_entry entry, unsigned int flags)
{
ppk_data edata;
return getEntry(entry, &edata, flags);
}
extern "C" unsigned int maxDataSize(ppk_data_type type)
{
switch(type)
{
case ppk_string:
return 1000000;
case ppk_blob:
return 1000000;
}
return 0;
}
extern "C" const char* getLastError()
{
return last_error()->c_str();
}
<commit_msg>STR module: Initial support to the new API<commit_after>#include "../../ppasskeeper-module.h"
#include "../../tokenizer.h"
#include <string>
#include <windows.h>
#include "list_pwd.h"
//Local definitions
static const char* baseKey="SOFTWARE\\PPassKeeper\\";
//local functions
std::string* last_error()
{
static std::string lerror;
return &lerror;
}
void setError(std::string error)
{
*(last_error())="PPK_SaveToRegistry : " + error;
}
ppk_error getPassword(const char* key, ppk_data** edata)
{
HKEY hk;
if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, baseKey, 0, KEY_QUERY_VALUE, &hk))
{
DWORD size=0;
DWORD type;
//Get the size of the entry
if(RegQueryValueEx(hk, key, 0, &type, NULL, &size)!=ERROR_SUCCESS)
return PPK_UNKNOWN_ERROR;
//Get the data
char tmpBuf=new char[size];
long res=RegQueryValueEx(hk, key, 0, &type, (BYTE*)tmpBuf, &size);
RegCloseKey(hk);
if(res==ERROR_SUCCESS)
{
if(type==REG_BINARY)
{
*edata=ppk_blob_data_new(tmpBuf, size);
delete[] tmpBuf;
return PPK_OK;
}
else if(type==REG_SZ)
{
*edata=ppk_string_data_new(tmpBuf);
delete[] tmpBuf;
return PPK_OK;
}
else
return PPK_UNKNOWN_ENTRY_TYPE;
}
else
return PPK_UNKNOWN_ERROR;
}
else
return PPK_ENTRY_UNAVAILABLE;
}
ppk_error setPassword(const char* key, const ppk_data* edata)
{
HKEY hk;
if(!RegCreateKeyEx(HKEY_LOCAL_MACHINE, baseKey, 0, 0, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, 0, &hk, 0))
{
long res;
if(edata->type==ppk_string)
res=RegSetValueEx(hk, key, 0, REG_SZ, (const BYTE*)edata->string, strlen(edata->string)+1);
else if(edata->type==ppk_blob)
res=RegSetValueEx(hk, key, 0, REG_BINARY, (const BYTE*)edata->blob.data, edata->blob.size);
else
return PPK_UNKNOWN_ENTRY_TYPE;
RegCloseKey(hk);
return res==ERROR_SUCCESS?PPK_OK:PPK_UNKNOWN_ERROR;
}
else
return PPK_ENTRY_UNAVAILABLE;
}
ppk_error removePassword(const char* key)
{
HKEY hk;
if(!RegCreateKeyEx(HKEY_LOCAL_MACHINE, baseKey, 0, 0, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, 0, &hk, 0))
{
long res=RegDeleteValue(hk, key);
RegCloseKey(hk);
return res==ERROR_SUCCESS?PPK_OK:PPK_UNKNOWN_ERROR;
}
else
return PPK_ENTRY_UNAVAILABLE;
}
std::string generateNetworkKey(std::string server, int port, std::string username)
{
return "ppasskeeper_network://"+username+"@"+server+":"+toString(port);
}
std::string generateApplicationKey(std::string application_name, std::string username)
{
return "ppasskeeper_app://"+username+"@"+application_name;
}
std::string generateItemKey(std::string key)
{
return "ppasskeeper_item://"+key;
}
//exported functions
extern "C" const char* getModuleID()
{
return "SaveToRegistry";
}
extern "C" const char* getModuleName()
{
return "SaveToRegistry - Store it into the registry";
}
extern "C" const int getABIVersion()
{
return 1;
}
extern "C" ppk_boolean isWritable()
{
return PPK_TRUE;
}
extern "C" ppk_security_level securityLevel(const char* module_id)
{
return ppk_sec_lowest;
}
//Get available flags
extern "C" unsigned int readFlagsAvailable()
{
return ppk_rf_none|ppk_rf_silent;
}
extern "C" unsigned int writeFlagsAvailable()
{
return ppk_wf_none|ppk_wf_silent;
}
extern "C" unsigned int listingFlagsAvailable()
{
return ppk_lf_none|ppk_lf_silent;
}
//List passwords available
std::string prefix(const ppk_entry entry)
{
std::string prefix="ppasskeeper_";
switch(entry.type)
{
case ppk_network:
prefix+="network";
break;
case ppk_application:
prefix+="app";
break;
case ppk_item:
prefix+="item";
break;
}
return prefix+"://";
}
extern "C" unsigned int getEntryListCount(unsigned int entry_types, unsigned int flags)
{
ListPwd pwdl;
return pwdl.getEntryListCount(baseKey, entry_types, flags);
}
extern "C" unsigned int getEntryList(unsigned int entry_types, ppk_entry *entryList, unsigned int nbEntries, unsigned int flags)
{
static ListPwd pwdl;
return pwdl.getEntryList(baseKey, entry_types, entryList, nbEntries, flags);
}
//Functions
extern "C" ppk_error getEntry(const ppk_entry* entry, ppk_data **edata, unsigned int flags)
{
static std::string pwd;
std::string text;
if(entry->type==ppk_network)
text=generateNetworkKey(entry->net.host, entry->net.port, entry->net.login);
else if(entry->type==ppk_application)
text=generateApplicationKey(entry->app.app_name, entry->app.username);
else if(entry->type==ppk_item)
text=generateItemKey(entry->item);
else
return PPK_UNKNOWN_ENTRY_TYPE;
return getPassword(text.c_str(), edata);
}
extern "C" ppk_error setEntry(const ppk_entry* entry, const ppk_data* edata, unsigned int flags)
{
std::string text;
if(entry->type==ppk_network)
text=generateNetworkKey(entry->net.host, entry->net.port, entry->net.login);
else if(entry->type==ppk_application)
text=generateApplicationKey(entry->app.app_name, entry->app.username);
else if(entry->type==ppk_item)
text=generateItemKey(entry->item);
else
return PPK_UNKNOWN_ENTRY_TYPE;
//if everything went fine
return setPassword(text.c_str(), edata);
}
extern "C" ppk_error removeEntry(const ppk_entry entry, unsigned int flags)
{
std::string text;
if(entry.type==ppk_network)
text=generateNetworkKey(entry.net.host, entry.net.port, entry.net.login);
else if(entry.type==ppk_application)
text=generateApplicationKey(entry.app.app_name, entry.app.username);
else if(entry.type==ppk_item)
text=generateItemKey(entry.item);
else
return PPK_UNKNOWN_ENTRY_TYPE;
return removePassword(text.c_str());
}
extern "C" ppk_boolean entryExists(const ppk_entry entry, unsigned int flags)
{
ppk_data* edata;
ppk_boolean res=getEntry(entry, &edata, flags)==PPK_OK?PPK_TRUE:PPK_FALSE;
if(res==PPK_TRUE)
ppk_data_free(edata);
return res;
}
extern "C" unsigned int maxDataSize(ppk_data_type type)
{
switch(type)
{
case ppk_string:
return 1000000;
case ppk_blob:
return 1000000;
}
return 0;
}
extern "C" const char* getLastError()
{
return last_error()->c_str();
}
<|endoftext|>
|
<commit_before>#pragma once
#include <sstream>
#include <string>
#include <boost/algorithm/string.hpp>
#include "blackhole/attribute.hpp"
#include "blackhole/detail/stream/stream.hpp"
#include "blackhole/error.hpp"
#include "blackhole/formatter/map/value.hpp"
namespace blackhole {
namespace formatter {
namespace string {
static const char VARIADIC_KEY_PREFIX[] = "...";
static const std::size_t VARIADIC_KEY_PRFFIX_LENGTH = std::strlen(VARIADIC_KEY_PREFIX);
namespace builder {
class variadic_visitor_t : public boost::static_visitor<> {
std::ostringstream& stream;
public:
variadic_visitor_t(std::ostringstream& stream) :
stream(stream)
{}
template<typename T>
void operator()(const T& value) const {
stream << value;
}
void operator()(const std::string& value) const {
stream << "'" << value << "'";
}
};
namespace placeholder {
struct variadic_t {
typedef attribute::scope_underlying_type scope_underlying_type;
const std::string placeholder;
void operator()(blackhole::aux::attachable_ostringstream& stream,
const mapping::value_t&,
const attribute::set_view_t& attributes) const
{
std::vector<std::string> passed;
passed.reserve(attributes.upper_size());
for (auto pit = placeholder.begin() + string::VARIADIC_KEY_PRFFIX_LENGTH; pit != placeholder.end(); ++pit) {
const scope_underlying_type scope = *pit - '0';
for (auto it = attributes.begin(); it != attributes.end(); ++it) {
const std::string& name = it->first;
const attribute_t& attribute = it->second;
if (static_cast<scope_underlying_type>(attribute.scope) & scope) {
std::ostringstream stream;
stream << "'" << name << "': ";
variadic_visitor_t visitor(stream);
boost::apply_visitor(visitor, attribute.value);
passed.push_back(stream.str());
}
}
}
stream.rdbuf()->storage()->append(boost::algorithm::join(passed, ", "));
}
};
} // namespace placeholder
} // namespace builder
} // namespace string
} // namespace formatter
} // namespace blackhole
<commit_msg>[Tasks] One more.<commit_after>#pragma once
#include <sstream>
#include <string>
#include <boost/algorithm/string.hpp>
#include "blackhole/attribute.hpp"
#include "blackhole/detail/stream/stream.hpp"
#include "blackhole/error.hpp"
#include "blackhole/formatter/map/value.hpp"
namespace blackhole {
namespace formatter {
namespace string {
static const char VARIADIC_KEY_PREFIX[] = "...";
static const std::size_t VARIADIC_KEY_PRFFIX_LENGTH = std::strlen(VARIADIC_KEY_PREFIX);
namespace builder {
class variadic_visitor_t : public boost::static_visitor<> {
std::ostringstream& stream;
public:
variadic_visitor_t(std::ostringstream& stream) :
stream(stream)
{}
template<typename T>
void operator()(const T& value) const {
stream << value;
}
void operator()(const std::string& value) const {
stream << "'" << value << "'";
}
};
namespace placeholder {
struct variadic_t {
typedef attribute::scope_underlying_type scope_underlying_type;
const std::string placeholder;
void operator()(blackhole::aux::attachable_ostringstream& stream,
const mapping::value_t&,
const attribute::set_view_t& attributes) const
{
std::vector<std::string> passed;
passed.reserve(attributes.upper_size());
for (auto pit = placeholder.begin() + string::VARIADIC_KEY_PRFFIX_LENGTH; pit != placeholder.end(); ++pit) {
const scope_underlying_type scope = *pit - '0';
for (auto it = attributes.begin(); it != attributes.end(); ++it) {
const std::string& name = it->first;
const attribute_t& attribute = it->second;
if (static_cast<scope_underlying_type>(attribute.scope) & scope) {
//!@todo: This code needs some optimization love.
std::ostringstream stream;
stream << "'" << name << "': ";
variadic_visitor_t visitor(stream);
boost::apply_visitor(visitor, attribute.value);
passed.push_back(stream.str());
}
}
}
stream.rdbuf()->storage()->append(boost::algorithm::join(passed, ", "));
}
};
} // namespace placeholder
} // namespace builder
} // namespace string
} // namespace formatter
} // namespace blackhole
<|endoftext|>
|
<commit_before>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2014/7/28
// Author: Mike Ovsiannikov
//
// Copyright 2014 Quantcast Corp.
//
// This file is part of Kosmos File System (KFS).
//
// Licensed under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// \file kfsdecls.cc
//
//----------------------------------------------------------------------------
#include "kfsdecls.h"
#include "IntToString.h"
#include "RequestParser.h"
#include <stdlib.h>
#include <ctype.h>
namespace KFS
{
string
ServerLocation::ToString() const
{
string ret;
ret.reserve(hostname.size() + 16);
ret.assign(hostname.data(), hostname.size());
ret.append(1, (char)' ');
AppendDecIntToString(ret, port);
return ret;
}
bool
ServerLocation::FromString(const char* str, size_t len)
{
const char* ptr = str;
const char* const end = ptr + len;
while (ptr < end && (*ptr & 0xFF) <= ' ' && *ptr) {
++ptr;
}
const char* const sptr = ptr;
while (ptr < end && (*ptr & 0xFF) > ' ') {
++ptr;
}
if (ptr <= sptr || *ptr == 0) {
Reset(0, -1);
return false;
}
hostname.assign(sptr, ptr - sptr);
if (! DecIntParser::Parse(ptr, end - ptr, port) || port < 0) {
Reset(0, -1);
return false;
}
return true;
}
} // namespace KFS
<commit_msg>Common library: remove extraneous include directives.<commit_after>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2014/7/28
// Author: Mike Ovsiannikov
//
// Copyright 2014 Quantcast Corp.
//
// This file is part of Kosmos File System (KFS).
//
// Licensed under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// \file kfsdecls.cc
//
//----------------------------------------------------------------------------
#include "kfsdecls.h"
#include "IntToString.h"
#include "RequestParser.h"
namespace KFS
{
string
ServerLocation::ToString() const
{
string ret;
ret.reserve(hostname.size() + 16);
ret.assign(hostname.data(), hostname.size());
ret.append(1, (char)' ');
AppendDecIntToString(ret, port);
return ret;
}
bool
ServerLocation::FromString(const char* str, size_t len)
{
const char* ptr = str;
const char* const end = ptr + len;
while (ptr < end && (*ptr & 0xFF) <= ' ' && *ptr) {
++ptr;
}
const char* const sptr = ptr;
while (ptr < end && (*ptr & 0xFF) > ' ') {
++ptr;
}
if (ptr <= sptr || *ptr == 0) {
Reset(0, -1);
return false;
}
hostname.assign(sptr, ptr - sptr);
if (! DecIntParser::Parse(ptr, end - ptr, port) || port < 0) {
Reset(0, -1);
return false;
}
return true;
}
} // namespace KFS
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2011-2016 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bitcoin/bitcoin/c/chain/transaction.h>
#include <bitcoin/bitcoin/c/internal/chain/transaction.hpp>
#include <bitcoin/bitcoin/c/internal/error.hpp>
#include <bitcoin/bitcoin/c/internal/chain/chain_state.hpp>
#include <bitcoin/bitcoin/c/internal/chain/input.hpp>
#include <bitcoin/bitcoin/c/internal/chain/output.hpp>
#include <bitcoin/bitcoin/c/internal/chain/point.hpp>
#include <bitcoin/bitcoin/c/internal/math/hash.hpp>
#include <bitcoin/bitcoin/c/internal/utility/data.hpp>
#include <bitcoin/bitcoin/c/internal/utility/string.hpp>
#include <bitcoin/bitcoin/c/internal/utility/vector.hpp>
extern "C" {
BC_IMPLEMENT_VECTOR(transaction_list, bc_transaction_t, bc_destroy_transaction,
libbitcoin::chain::transaction::list);
// Constructor
bc_transaction_t* bc_create_transaction()
{
return new bc_transaction_t{ new libbitcoin::chain::transaction, true };
}
bc_transaction_t* bc_create_transaction_copy(const bc_transaction_t* other)
{
return new bc_transaction_t{ new libbitcoin::chain::transaction(
*other->obj), true };
}
bc_transaction_t* bc_create_transaction_copy_Hash(
const bc_transaction_t* other, const bc_hash_digest_t* hash)
{
return new bc_transaction_t{ new libbitcoin::chain::transaction(
*other->obj, *hash->obj), true };
}
bc_transaction_t* bc_create_transaction_Parts(
uint32_t version, uint32_t locktime,
const bc_input_list_t* inputs, const bc_output_list_t* outputs)
{
return new bc_transaction_t{ new libbitcoin::chain::transaction(
version, locktime, *inputs->obj, *outputs->obj), true };
}
// Destructor
void bc_destroy_transaction(bc_transaction_t* self)
{
if (self->delete_obj)
delete self->obj;
delete self;
}
// Operators.
void bc_transaction__copy(
bc_transaction_t* self, const bc_transaction_t* other)
{
*self->obj = *other->obj;
}
bool bc_transaction__equals(
const bc_transaction_t* self, const bc_transaction_t* other)
{
return *self->obj == *other->obj;
}
bool bc_transaction__not_equals(
const bc_transaction_t* self, const bc_transaction_t* other)
{
return *self->obj != *other->obj;
}
// Deserialization.
bc_transaction_t* bc_transaction__factory_from_data(
const bc_data_chunk_t* data)
{
return new bc_transaction_t{ new libbitcoin::chain::transaction(
libbitcoin::chain::transaction::factory_from_data(*data->obj)), true };
}
bc_transaction_t* bc_transaction__factory_from_data_nowire(
const bc_data_chunk_t* data)
{
return new bc_transaction_t{ new libbitcoin::chain::transaction(
libbitcoin::chain::transaction::factory_from_data(
*data->obj, false)), true };
}
bool bc_transaction__from_data(bc_transaction_t* self,
const bc_data_chunk_t* data)
{
return self->obj->from_data(*data->obj);
}
bool bc_transaction__from_data_nowire(bc_transaction_t* self,
const bc_data_chunk_t* data)
{
return self->obj->from_data(*data->obj, false);
}
bool bc_transaction__is_valid(const bc_transaction_t* self)
{
return self->obj->is_valid();
}
// Serialization.
bc_data_chunk_t* bc_transaction__to_data(const bc_transaction_t* self)
{
return bc_create_data_chunk_Internal(self->obj->to_data());
}
bc_data_chunk_t* bc_transaction__to_data_nowire(
const bc_transaction_t* self)
{
return bc_create_data_chunk_Internal(self->obj->to_data(false));
}
// Properties (size, accessors, cache).
uint64_t bc_transaction__serialized_size(const bc_transaction_t* self)
{
return self->obj->serialized_size();
}
uint64_t bc_transaction__serialized_size_nowire(const bc_transaction_t* self)
{
return self->obj->serialized_size(false);
}
uint32_t bc_transaction__version(const bc_transaction_t* self)
{
return self->obj->version();
}
void bc_transaction__set_version(bc_transaction_t* self, uint32_t version)
{
self->obj->set_version(version);
}
uint32_t bc_transaction__locktime(const bc_transaction_t* self)
{
return self->obj->locktime();
}
void bc_transaction__set_locktime(bc_transaction_t* self, uint32_t locktime)
{
self->obj->set_locktime(locktime);
}
bc_input_list_t* bc_transaction__inputs(const bc_transaction_t* self)
{
return new bc_input_list_t{ new libbitcoin::chain::input::list(
self->obj->inputs()), true };
}
void bc_transaction__set_inputs(bc_transaction_t* self,
const bc_input_list_t* inputs)
{
self->obj->set_inputs(*inputs->obj);
}
bc_output_list_t* bc_transaction__outputs(const bc_transaction_t* self)
{
return new bc_output_list_t{ new libbitcoin::chain::output::list(
self->obj->outputs()), true };
}
void bc_transaction__set_outputs(bc_transaction_t* self,
const bc_output_list_t* outputs)
{
self->obj->set_outputs(*outputs->obj);
}
bc_hash_digest_t* bc_transaction__hash(const bc_transaction_t* self)
{
return bc_create_hash_digest_Internal(self->obj->hash());
}
bc_hash_digest_t* bc_transaction__hash_Sighash(const bc_transaction_t* self,
uint32_t sighash_type)
{
return bc_create_hash_digest_Internal(self->obj->hash(sighash_type));
}
// Validation.
uint64_t bc_transaction__fees(const bc_transaction_t* self)
{
return self->obj->fees();
}
bc_point_indexes_t* bc_transaction__double_spends(
const bc_transaction_t* self, bool include_unconfirmed)
{
const auto indexes = self->obj->double_spends(include_unconfirmed);
return new bc_point_indexes_t{ new libbitcoin::chain::point::indexes(
indexes), true };
}
bc_point_indexes_t* bc_transaction__immature_inputs(
const bc_transaction_t* self, size_t target_height)
{
const auto indexes = self->obj->immature_inputs(target_height);
return new bc_point_indexes_t{ new libbitcoin::chain::point::indexes(
indexes), true };
}
bc_point_indexes_t* bc_transaction__missing_previous_outputs(
const bc_transaction_t* self)
{
const auto indexes = self->obj->missing_previous_outputs();
return new bc_point_indexes_t{ new libbitcoin::chain::point::indexes(
indexes), true };
}
uint64_t bc_transaction__total_input_value(const bc_transaction_t* self)
{
return self->obj->total_input_value();
}
uint64_t bc_transaction__total_output_value(const bc_transaction_t* self)
{
return self->obj->total_output_value();
}
size_t bc_transaction__signature_operations(
const bc_transaction_t* self, bool bip16_active)
{
return self->obj->signature_operations(bip16_active);
}
bool bc_transaction__is_coinbase(const bc_transaction_t* self)
{
return self->obj->is_coinbase();
}
bool bc_transaction__is_null_non_coinbase(const bc_transaction_t* self)
{
return self->obj->is_null_non_coinbase();
}
bool bc_transaction__is_oversized_coinbase(const bc_transaction_t* self)
{
return self->obj->is_oversized_coinbase();
}
bool bc_transaction__is_immature(const bc_transaction_t* self,
size_t target_height)
{
return self->obj->is_immature(target_height);
}
bool bc_transaction__is_overspent(const bc_transaction_t* self)
{
return self->obj->is_overspent();
}
bool bc_transaction__is_missing_previous_outputs(const bc_transaction_t* self)
{
return self->obj->is_missing_previous_outputs();
}
bool bc_transaction__is_final(const bc_transaction_t* self,
uint64_t block_height, uint32_t block_time)
{
return self->obj->is_final(block_height, block_time);
}
bool bc_transaction__is_locktime_conflict(const bc_transaction_t* self)
{
return self->obj->is_locktime_conflict();
}
bc_error_code_t* bc_transaction__check(const bc_transaction_t* self)
{
return new bc_error_code_t{ new std::error_code(
self->obj->check()) };
}
bc_error_code_t* bc_transaction__check_notransaction_pool(
const bc_transaction_t* self)
{
return new bc_error_code_t{ new std::error_code(
self->obj->check(false)) };
}
bc_error_code_t* bc_transaction__accept(
const bc_transaction_t* self, const bc_chain_state_t* state)
{
return new bc_error_code_t{ new std::error_code(
self->obj->accept(*state->obj)) };
}
bc_error_code_t* bc_transaction__accept_notransaction_pool(
const bc_transaction_t* self, const bc_chain_state_t* state)
{
return new bc_error_code_t{ new std::error_code(
self->obj->accept(*state->obj, false)) };
}
bc_error_code_t* bc_transaction__connect(
const bc_transaction_t* self, const bc_chain_state_t* state)
{
return new bc_error_code_t{ new std::error_code(
self->obj->connect(*state->obj)) };
}
bc_error_code_t* bc_transaction__connect_input(
const bc_transaction_t* self, const bc_chain_state_t* state,
uint32_t input_index)
{
return new bc_error_code_t{ new std::error_code(
self->obj->connect_input(*state->obj, input_index)) };
}
} // extern C
<commit_msg>added missing impl bc_transaction__is_double_spend<commit_after>/**
* Copyright (c) 2011-2016 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bitcoin/bitcoin/c/chain/transaction.h>
#include <bitcoin/bitcoin/c/internal/chain/transaction.hpp>
#include <bitcoin/bitcoin/c/internal/error.hpp>
#include <bitcoin/bitcoin/c/internal/chain/chain_state.hpp>
#include <bitcoin/bitcoin/c/internal/chain/input.hpp>
#include <bitcoin/bitcoin/c/internal/chain/output.hpp>
#include <bitcoin/bitcoin/c/internal/chain/point.hpp>
#include <bitcoin/bitcoin/c/internal/math/hash.hpp>
#include <bitcoin/bitcoin/c/internal/utility/data.hpp>
#include <bitcoin/bitcoin/c/internal/utility/string.hpp>
#include <bitcoin/bitcoin/c/internal/utility/vector.hpp>
extern "C" {
BC_IMPLEMENT_VECTOR(transaction_list, bc_transaction_t, bc_destroy_transaction,
libbitcoin::chain::transaction::list);
// Constructor
bc_transaction_t* bc_create_transaction()
{
return new bc_transaction_t{ new libbitcoin::chain::transaction, true };
}
bc_transaction_t* bc_create_transaction_copy(const bc_transaction_t* other)
{
return new bc_transaction_t{ new libbitcoin::chain::transaction(
*other->obj), true };
}
bc_transaction_t* bc_create_transaction_copy_Hash(
const bc_transaction_t* other, const bc_hash_digest_t* hash)
{
return new bc_transaction_t{ new libbitcoin::chain::transaction(
*other->obj, *hash->obj), true };
}
bc_transaction_t* bc_create_transaction_Parts(
uint32_t version, uint32_t locktime,
const bc_input_list_t* inputs, const bc_output_list_t* outputs)
{
return new bc_transaction_t{ new libbitcoin::chain::transaction(
version, locktime, *inputs->obj, *outputs->obj), true };
}
// Destructor
void bc_destroy_transaction(bc_transaction_t* self)
{
if (self->delete_obj)
delete self->obj;
delete self;
}
// Operators.
void bc_transaction__copy(
bc_transaction_t* self, const bc_transaction_t* other)
{
*self->obj = *other->obj;
}
bool bc_transaction__equals(
const bc_transaction_t* self, const bc_transaction_t* other)
{
return *self->obj == *other->obj;
}
bool bc_transaction__not_equals(
const bc_transaction_t* self, const bc_transaction_t* other)
{
return *self->obj != *other->obj;
}
// Deserialization.
bc_transaction_t* bc_transaction__factory_from_data(
const bc_data_chunk_t* data)
{
return new bc_transaction_t{ new libbitcoin::chain::transaction(
libbitcoin::chain::transaction::factory_from_data(*data->obj)), true };
}
bc_transaction_t* bc_transaction__factory_from_data_nowire(
const bc_data_chunk_t* data)
{
return new bc_transaction_t{ new libbitcoin::chain::transaction(
libbitcoin::chain::transaction::factory_from_data(
*data->obj, false)), true };
}
bool bc_transaction__from_data(bc_transaction_t* self,
const bc_data_chunk_t* data)
{
return self->obj->from_data(*data->obj);
}
bool bc_transaction__from_data_nowire(bc_transaction_t* self,
const bc_data_chunk_t* data)
{
return self->obj->from_data(*data->obj, false);
}
bool bc_transaction__is_valid(const bc_transaction_t* self)
{
return self->obj->is_valid();
}
// Serialization.
bc_data_chunk_t* bc_transaction__to_data(const bc_transaction_t* self)
{
return bc_create_data_chunk_Internal(self->obj->to_data());
}
bc_data_chunk_t* bc_transaction__to_data_nowire(
const bc_transaction_t* self)
{
return bc_create_data_chunk_Internal(self->obj->to_data(false));
}
// Properties (size, accessors, cache).
uint64_t bc_transaction__serialized_size(const bc_transaction_t* self)
{
return self->obj->serialized_size();
}
uint64_t bc_transaction__serialized_size_nowire(const bc_transaction_t* self)
{
return self->obj->serialized_size(false);
}
uint32_t bc_transaction__version(const bc_transaction_t* self)
{
return self->obj->version();
}
void bc_transaction__set_version(bc_transaction_t* self, uint32_t version)
{
self->obj->set_version(version);
}
uint32_t bc_transaction__locktime(const bc_transaction_t* self)
{
return self->obj->locktime();
}
void bc_transaction__set_locktime(bc_transaction_t* self, uint32_t locktime)
{
self->obj->set_locktime(locktime);
}
bc_input_list_t* bc_transaction__inputs(const bc_transaction_t* self)
{
return new bc_input_list_t{ new libbitcoin::chain::input::list(
self->obj->inputs()), true };
}
void bc_transaction__set_inputs(bc_transaction_t* self,
const bc_input_list_t* inputs)
{
self->obj->set_inputs(*inputs->obj);
}
bc_output_list_t* bc_transaction__outputs(const bc_transaction_t* self)
{
return new bc_output_list_t{ new libbitcoin::chain::output::list(
self->obj->outputs()), true };
}
void bc_transaction__set_outputs(bc_transaction_t* self,
const bc_output_list_t* outputs)
{
self->obj->set_outputs(*outputs->obj);
}
bc_hash_digest_t* bc_transaction__hash(const bc_transaction_t* self)
{
return bc_create_hash_digest_Internal(self->obj->hash());
}
bc_hash_digest_t* bc_transaction__hash_Sighash(const bc_transaction_t* self,
uint32_t sighash_type)
{
return bc_create_hash_digest_Internal(self->obj->hash(sighash_type));
}
// Validation.
uint64_t bc_transaction__fees(const bc_transaction_t* self)
{
return self->obj->fees();
}
bc_point_indexes_t* bc_transaction__double_spends(
const bc_transaction_t* self, bool include_unconfirmed)
{
const auto indexes = self->obj->double_spends(include_unconfirmed);
return new bc_point_indexes_t{ new libbitcoin::chain::point::indexes(
indexes), true };
}
bc_point_indexes_t* bc_transaction__immature_inputs(
const bc_transaction_t* self, size_t target_height)
{
const auto indexes = self->obj->immature_inputs(target_height);
return new bc_point_indexes_t{ new libbitcoin::chain::point::indexes(
indexes), true };
}
bc_point_indexes_t* bc_transaction__missing_previous_outputs(
const bc_transaction_t* self)
{
const auto indexes = self->obj->missing_previous_outputs();
return new bc_point_indexes_t{ new libbitcoin::chain::point::indexes(
indexes), true };
}
uint64_t bc_transaction__total_input_value(const bc_transaction_t* self)
{
return self->obj->total_input_value();
}
uint64_t bc_transaction__total_output_value(const bc_transaction_t* self)
{
return self->obj->total_output_value();
}
size_t bc_transaction__signature_operations(
const bc_transaction_t* self, bool bip16_active)
{
return self->obj->signature_operations(bip16_active);
}
bool bc_transaction__is_coinbase(const bc_transaction_t* self)
{
return self->obj->is_coinbase();
}
bool bc_transaction__is_null_non_coinbase(const bc_transaction_t* self)
{
return self->obj->is_null_non_coinbase();
}
bool bc_transaction__is_oversized_coinbase(const bc_transaction_t* self)
{
return self->obj->is_oversized_coinbase();
}
bool bc_transaction__is_immature(const bc_transaction_t* self,
size_t target_height)
{
return self->obj->is_immature(target_height);
}
bool bc_transaction__is_overspent(const bc_transaction_t* self)
{
return self->obj->is_overspent();
}
bool bc_transaction__is_double_spend(const bc_transaction_t* self,
bool include_unconfirmed)
{
return self->obj->is_double_spend(include_unconfirmed);
}
bool bc_transaction__is_missing_previous_outputs(const bc_transaction_t* self)
{
return self->obj->is_missing_previous_outputs();
}
bool bc_transaction__is_final(const bc_transaction_t* self,
uint64_t block_height, uint32_t block_time)
{
return self->obj->is_final(block_height, block_time);
}
bool bc_transaction__is_locktime_conflict(const bc_transaction_t* self)
{
return self->obj->is_locktime_conflict();
}
bc_error_code_t* bc_transaction__check(const bc_transaction_t* self)
{
return new bc_error_code_t{ new std::error_code(
self->obj->check()) };
}
bc_error_code_t* bc_transaction__check_notransaction_pool(
const bc_transaction_t* self)
{
return new bc_error_code_t{ new std::error_code(
self->obj->check(false)) };
}
bc_error_code_t* bc_transaction__accept(
const bc_transaction_t* self, const bc_chain_state_t* state)
{
return new bc_error_code_t{ new std::error_code(
self->obj->accept(*state->obj)) };
}
bc_error_code_t* bc_transaction__accept_notransaction_pool(
const bc_transaction_t* self, const bc_chain_state_t* state)
{
return new bc_error_code_t{ new std::error_code(
self->obj->accept(*state->obj, false)) };
}
bc_error_code_t* bc_transaction__connect(
const bc_transaction_t* self, const bc_chain_state_t* state)
{
return new bc_error_code_t{ new std::error_code(
self->obj->connect(*state->obj)) };
}
bc_error_code_t* bc_transaction__connect_input(
const bc_transaction_t* self, const bc_chain_state_t* state,
uint32_t input_index)
{
return new bc_error_code_t{ new std::error_code(
self->obj->connect_input(*state->obj, input_index)) };
}
} // extern C
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <copyright holder> 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 "TestOutput.h"
#include <stdio.h>
#include "SimpleString.h"
#include "Utest.h"
#include "Failure.h"
#include "TestResult.h"
TestOutput::TestOutput() : dotCount_(0), verbose_(false)
{}
TestOutput::~TestOutput()
{}
void TestOutput::verbose()
{
verbose_ = true;
}
void TestOutput::print(const char* s)
{
printf(s);
}
void TestOutput::print(long n)
{
print(StringFrom(n).asCharString());
}
TestOutput& operator<<(TestOutput& p, const char* s)
{
p.print(s);
return p;
}
TestOutput& operator<<(TestOutput& p, long int i)
{
p.print(i);
return p;
}
void TestOutput::printCurrentTest(const Utest& test)
{
if (verbose_) {
print(test.getFormattedName().asCharString());
print("\n");
}
else {
print(".");
if (++dotCount_ % 50 == 0)
print("\n");
}
}
void TestOutput::printTestsStarted()
{
}
void TestOutput::flush()
{
}
void TestOutput::printTestsEnded(const TestResult& result)
{
if (result.getFailureCount() > 0) {
print("\nErrors (");
print(result.getFailureCount());
print(" failures, ");
}
else {
print("\nOK (");
}
print(result.getTestCount());
print(" tests, ");
print(result.getRunCount());
print(" ran, ");
print(result.getCheckCount());
print(" checks, ");
print(result.getIgnoredCount());
print(" ignored, ");
print(result.getFilteredOutCount());
print(" filtered out)\n\n");
}
void TestOutput::printTestRun(int number, int total)
{
if (total > 1) {
print("Test run ");
print(number);
print(" of ");
print(total);
print("\n");
}
}
void TestOutput::print(const Failure& failure)
{
print("\n");
print(failure.getFileName().asCharString());
print(":");
print(failure.getLineNumber());
print(":");
print("Failure in ");
print(failure.getTestName().asCharString());
print("\n");
print("\t");
print(failure.getMessage().asCharString());
print("\n\n");
}
<commit_msg>Changed the test output<commit_after>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <copyright holder> 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 "TestOutput.h"
#include <stdio.h>
#include "SimpleString.h"
#include "Utest.h"
#include "Failure.h"
#include "TestResult.h"
TestOutput::TestOutput() : dotCount_(0), verbose_(false)
{}
TestOutput::~TestOutput()
{}
void TestOutput::verbose()
{
verbose_ = true;
}
void TestOutput::print(const char* s)
{
printf(s);
}
void TestOutput::print(long n)
{
print(StringFrom(n).asCharString());
}
TestOutput& operator<<(TestOutput& p, const char* s)
{
p.print(s);
return p;
}
TestOutput& operator<<(TestOutput& p, long int i)
{
p.print(i);
return p;
}
void TestOutput::printCurrentTest(const Utest& test)
{
if (verbose_) {
print(test.getFormattedName().asCharString());
print("\n");
}
else {
print(".");
if (++dotCount_ % 50 == 0)
print("\n");
}
}
void TestOutput::printTestsStarted()
{
}
void TestOutput::flush()
{
}
void TestOutput::printTestsEnded(const TestResult& result)
{
if (result.getFailureCount() > 0) {
print("\nErrors (");
print(result.getFailureCount());
print(" failures, ");
}
else {
print("\nOK (");
}
print(result.getTestCount());
print(" tests, ");
print(result.getRunCount());
print(" ran, ");
print(result.getCheckCount());
print(" checks, ");
print(result.getIgnoredCount());
print(" ignored, ");
print(result.getFilteredOutCount());
print(" filtered out)\n\n");
}
void TestOutput::printTestRun(int number, int total)
{
if (total > 1) {
print("Test run ");
print(number);
print(" of ");
print(total);
print("\n");
}
}
void TestOutput::print(const Failure& failure)
{
print("\n");
print(failure.getFileName().asCharString());
print(":");
print(failure.getLineNumber());
print(":");
print(" error: ");
print("Failure in ");
print(failure.getTestName().asCharString());
print("\n");
print("\t");
print(failure.getMessage().asCharString());
print("\n\n");
}
<|endoftext|>
|
<commit_before>/*
* opencog/attention/FocusBoundaryUpdatingAgent.cc
*
* Written by Roman Treutlein
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <algorithm>
#include <math.h>
#include <time.h>
#include <map>
#include <chrono>
#include <fstream>
#include <stdio.h>
#include <opencog/util/Config.h>
#include <opencog/util/mt19937ar.h>
#include <opencog/attention/atom_types.h>
#include <opencog/atomspace/AtomSpace.h>
#include <opencog/attentionbank/AttentionBank.h>
#include "FocusBoundaryUpdatingAgent.h"
//#define DEBUG
using namespace opencog;
using namespace std::chrono;
FocusBoundaryUpdatingAgent::FocusBoundaryUpdatingAgent(CogServer& cs) :
Agent(cs)
{
// Provide a logger
setLogger(new opencog::Logger("FocusBoundaryUpdatingAgent.log", Logger::FINE, true));
afbSize = config().get_double("ECAN_AFB_SIZE", 0.2);
decay = config().get_double("ECAN_AFB_DECAY", 0.05);
bottomBoundary = config().get_int("ECAN_AFB_BOTTOM", 50);
minAFSize = config().get_int("MIN_AF_SIZE", 100);
maxAFSize = config().get_int("MAX_AF_SIZE", 500);
_bank->setAttentionalFocusBoundary(bottomBoundary);
}
void FocusBoundaryUpdatingAgent::run()
{
AttentionValue::sti_t afboundary = _bank->getAttentionalFocusBoundary();
/*
AttentionValue::sti_t maxsti = _bank->get_max_STI();
AttentionValue::sti_t minsti = _bank->get_min_STI();
AttentionValue::sti_t range = maxsti - minsti;
int newafb = maxsti - (range * afbSize);
//int oldafb = afboundary;
afboundary = newafb * decay + (1.0 - decay) * afboundary;
afboundary = std::max(afboundary, bottomBoundary);
//printf("NewAfb: %d OldAfb: %d Afb: %d \n",newafb,oldafb,afboundary);
*/
HandleSeq afset;
_bank->get_handle_set_in_attentional_focus(std::back_inserter(afset));
if(afset.size() > minAFSize ) {
afboundary = get_cutoff(afset);
}
// Set the AF boundary
_bank->setAttentionalFocusBoundary(afboundary);
}
/**
* Finds the natural cut off STI value between the minimum and maximum AF set.
* The natural cutoff here is assumed as the index where the biggest STI
* difference occured in the decreasingly ordered set of atoms bn Min and Max AF
* size.
*
* @param afset - Atoms in the AF
* @return the natural cutoff STI value
*/
AttentionValue::sti_t FocusBoundaryUpdatingAgent::get_cutoff(HandleSeq& afset)
{
auto getSTI = [&](const Handle& h)->AttentionValue::sti_t {
return _bank->get_sti(h);
};
std::sort(afset.begin(), afset.end(),
[&](const Handle& h1, const Handle& h2)->bool {
return getSTI(h1) > getSTI(h2);
});
HandleSeq afAtoms = HandleSeq(afset.begin() + minAFSize, afset.begin() + maxAFSize);
int cut_off_index = 0;
int biggest_diff = -1 ; // diffs are always +ve. so, its okay to initialize it with -ve number.
constexpr int DIFF_MAGNITUDE = 0.5; // make this a parameter
for( HandleSeq::size_type i = 0 ; i < afAtoms.size()-1; i++ ){
int diff = getSTI(afAtoms[i]) - getSTI(afAtoms[i+1]);
if(diff > biggest_diff*(1 + DIFF_MAGNITUDE )) {
biggest_diff = diff;
cut_off_index = i;
}
}
return getSTI(afAtoms[cut_off_index]);
}
<commit_msg>Bug-fix for #2570<commit_after>/*
* opencog/attention/FocusBoundaryUpdatingAgent.cc
*
* Written by Roman Treutlein
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <algorithm>
#include <math.h>
#include <time.h>
#include <map>
#include <chrono>
#include <fstream>
#include <stdio.h>
#include <opencog/util/Config.h>
#include <opencog/util/mt19937ar.h>
#include <opencog/attention/atom_types.h>
#include <opencog/atomspace/AtomSpace.h>
#include <opencog/attentionbank/AttentionBank.h>
#include "FocusBoundaryUpdatingAgent.h"
//#define DEBUG
using namespace opencog;
using namespace std::chrono;
FocusBoundaryUpdatingAgent::FocusBoundaryUpdatingAgent(CogServer& cs) :
Agent(cs)
{
// Provide a logger
setLogger(new opencog::Logger("FocusBoundaryUpdatingAgent.log", Logger::FINE, true));
afbSize = config().get_double("ECAN_AFB_SIZE", 0.2);
decay = config().get_double("ECAN_AFB_DECAY", 0.05);
bottomBoundary = config().get_int("ECAN_AFB_BOTTOM", 50);
minAFSize = config().get_int("MIN_AF_SIZE", 100);
maxAFSize = config().get_int("MAX_AF_SIZE", 500);
_bank = &attentionbank(_as);
_bank->setAttentionalFocusBoundary(bottomBoundary);
}
void FocusBoundaryUpdatingAgent::run()
{
AttentionValue::sti_t afboundary = _bank->getAttentionalFocusBoundary();
/*
AttentionValue::sti_t maxsti = _bank->get_max_STI();
AttentionValue::sti_t minsti = _bank->get_min_STI();
AttentionValue::sti_t range = maxsti - minsti;
int newafb = maxsti - (range * afbSize);
//int oldafb = afboundary;
afboundary = newafb * decay + (1.0 - decay) * afboundary;
afboundary = std::max(afboundary, bottomBoundary);
//printf("NewAfb: %d OldAfb: %d Afb: %d \n",newafb,oldafb,afboundary);
*/
HandleSeq afset;
_bank->get_handle_set_in_attentional_focus(std::back_inserter(afset));
if(afset.size() > minAFSize ) {
afboundary = get_cutoff(afset);
}
// Set the AF boundary
_bank->setAttentionalFocusBoundary(afboundary);
}
/**
* Finds the natural cut off STI value between the minimum and maximum AF set.
* The natural cutoff here is assumed as the index where the biggest STI
* difference occured in the decreasingly ordered set of atoms bn Min and Max AF
* size.
*
* @param afset - Atoms in the AF
* @return the natural cutoff STI value
*/
AttentionValue::sti_t FocusBoundaryUpdatingAgent::get_cutoff(HandleSeq& afset)
{
auto getSTI = [&](const Handle& h)->AttentionValue::sti_t {
return _bank->get_sti(h);
};
std::sort(afset.begin(), afset.end(),
[&](const Handle& h1, const Handle& h2)->bool {
return getSTI(h1) > getSTI(h2);
});
HandleSeq afAtoms = HandleSeq(afset.begin() + minAFSize, afset.begin() + maxAFSize);
int cut_off_index = 0;
int biggest_diff = -1 ; // diffs are always +ve. so, its okay to initialize it with -ve number.
constexpr int DIFF_MAGNITUDE = 0.5; // make this a parameter
for( HandleSeq::size_type i = 0 ; i < afAtoms.size()-1; i++ ){
int diff = getSTI(afAtoms[i]) - getSTI(afAtoms[i+1]);
if(diff > biggest_diff*(1 + DIFF_MAGNITUDE )) {
biggest_diff = diff;
cut_off_index = i;
}
}
return getSTI(afAtoms[cut_off_index]);
}
<|endoftext|>
|
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "internet.h"
#include "my_hostname.h"
#include "condor_attributes.h"
#include "condor_netdb.h"
#include "ipv6_hostname.h"
#include "condor_sinful.h"
#include "CondorError.h"
static bool shared_port_address_rewriting = false;
static bool network_interface_matches_all;
const char* my_ip_string() {
static MyString __my_ip_string;
// TODO: Picking IPv4 arbitrarily. WARNING: This function
// gets called while the configuration file is being loaded,
// before we know if IPV4 and/or IPv6 is enabled. It needs to
// return a stable answer, because having it change midway
// through parsing the file is a recipe for failure.
__my_ip_string = get_local_ipaddr(CP_IPV4).to_ip_string();
return __my_ip_string.Value();
}
bool
network_interface_to_ip(char const *interface_param_name,char const *interface_pattern,std::string & ipv4, std::string & ipv6, std::string & ipbest)
{
ASSERT( interface_pattern );
if( !interface_param_name ) {
interface_param_name = "";
}
condor_sockaddr addr;
if (addr.from_ip_string(interface_pattern)) {
if(addr.is_ipv4()) {
ipv4 = interface_pattern;
ipbest = ipv4;
} else {
ASSERT(addr.is_ipv6());
ipv6 = interface_pattern;
ipbest = ipv6;
}
dprintf(D_HOSTNAME,"%s=%s, so choosing IP %s\n",
interface_param_name,
interface_pattern,
ipbest.c_str());
// addr.to_ip_string().Value());
return true;
}
unsigned interfaceCount = 0;
StringList pattern(interface_pattern);
std::string matches_str;
std::vector<NetworkDeviceInfo> dev_list;
std::vector<NetworkDeviceInfo>::iterator dev;
bool want_v4 = ! param_false( "ENABLE_IPV4" );
bool want_v6 = ! param_false( "ENABLE_IPV6" );
sysapi_get_network_device_info(dev_list, want_v4, want_v6);
// Order of preference:
// * non-private IP
// * private IP (e.g. 192.168.*)
// * loopback
// In case of a tie, choose the first device in the list.
int best_so_far_v4 = -1;
int best_so_far_v6 = -1;
int best_overall = -1;
for(dev = dev_list.begin();
dev != dev_list.end();
dev++)
{
bool matches = false;
if( strcmp(dev->name(),"")!=0 &&
pattern.contains_anycase_withwildcard(dev->name()) )
{
matches = true;
}
else if( strcmp(dev->IP(),"")!=0 &&
pattern.contains_anycase_withwildcard(dev->IP()) )
{
matches = true;
}
if( !matches ) {
dprintf(D_HOSTNAME,"Ignoring network interface %s (%s) because it does not match %s=%s.\n",
dev->name(), dev->IP(), interface_param_name, interface_pattern);
continue;
}
condor_sockaddr this_addr;
if (!this_addr.from_ip_string(dev->IP())) {
dprintf(D_HOSTNAME,"Ignoring network interface %s (%s) because it does not have a useable IP address.\n",
dev->name(), dev->IP());
continue;
}
if( matches_str.size() ) {
matches_str += ", ";
}
matches_str += dev->name();
matches_str += " ";
matches_str += dev->IP();
++interfaceCount;
int desireability = this_addr.desirability();
if(dev->is_up()) { desireability *= 10; }
int * best_so_far = 0;
std::string * ip = 0;
if(this_addr.is_ipv4()) {
best_so_far = & best_so_far_v4;
ip = & ipv4;
} else {
ASSERT(this_addr.is_ipv6());
best_so_far = & best_so_far_v6;
ip = & ipv6;
}
//dprintf(D_HOSTNAME, "Considering %s (Ranked at %d) as possible local hostname versus %s (%d)\n", addr.to_ip_string().Value(), desireability, ip.c_str(), desireability);
if( desireability > *best_so_far ) {
*best_so_far = desireability;
*ip = dev->IP();
}
if( desireability > best_overall ) {
best_overall = desireability;
ipbest = dev->IP();
}
}
if( best_overall < 0 ) {
dprintf(D_ALWAYS,"Failed to convert %s=%s to an IP address.\n",
interface_param_name, interface_pattern);
return false;
}
//
// Add some smarts to ENABLE_IPV[4|6] = AUTO.
//
// If we only found one protocol, do nothing. Otherwise,
// if both ipv4 and ipv6 are not at least as desirable as a private
// address, then do nothing. If both are at least as desirable as a
// private address, do nothing. If only one is, and that ENABLE
// knob is AUTO, clear the corresponding ipv[4|6] variable.
//
// We're using the raw desirability parameter here, but we should maybe
// be checking to see if the address is public or private instead...
//
condor_sockaddr v4sa, v6sa;
if( v4sa.from_ip_string( ipv4 ) && v6sa.from_ip_string( ipv6 ) ) {
if( (v4sa.desirability() < 4) ^ (v6sa.desirability() < 4) ) {
if( want_v4 && ! param_true( "ENABLE_IPV4" ) ) {
if( v4sa.desirability() < 4 ) {
ipv4.clear();
ipbest = ipv6;
}
}
if( want_v6 && ! param_true( "ENABLE_IPV6" ) ) {
if( v6sa.desirability() < 4) {
ipv6.clear();
ipbest = ipv4;
}
}
}
}
dprintf(D_HOSTNAME,"%s=%s matches %s, choosing IP %s\n",
interface_param_name,
interface_pattern,
matches_str.c_str(),
ipbest.c_str());
return true;
}
bool
init_network_interfaces( CondorError * errorStack )
{
dprintf( D_HOSTNAME, "Trying to getting network interface information after reading config\n" );
bool enable_ipv4_true = false;
bool enable_ipv4_false = false;
bool enable_ipv6_true = false;
bool enable_ipv6_false = false;
std::string enable_ipv4_str;
std::string enable_ipv6_str;
param( enable_ipv4_str, "ENABLE_IPV4" );
param( enable_ipv6_str, "ENABLE_IPV6" );
bool result = false;
if ( string_is_boolean_param( enable_ipv4_str.c_str(), result ) ) {
enable_ipv4_true = result;
enable_ipv4_false = !result;
}
if ( string_is_boolean_param( enable_ipv6_str.c_str(), result ) ) {
enable_ipv6_true = result;
enable_ipv6_false = !result;
}
std::string network_interface;
param( network_interface, "NETWORK_INTERFACE" );
network_interface_matches_all = (network_interface == "*");
if( enable_ipv4_false && enable_ipv6_false ) {
errorStack->pushf( "init_network_interfaces", 1, "ENABLE_IPV4 and ENABLE_IPV6 are both false." );
return false;
}
std::string network_interface_ipv4;
std::string network_interface_ipv6;
std::string network_interface_best;
bool ok;
ok = network_interface_to_ip(
"NETWORK_INTERFACE",
network_interface.c_str(),
network_interface_ipv4,
network_interface_ipv6,
network_interface_best);
if( !ok ) {
errorStack->pushf( "init_network_interfaces", 2,
"Failed to determine my IP address using NETWORK_INTERFACE=%s",
network_interface.c_str());
return false;
}
//
// Check the validity of the configuration.
//
if( network_interface_ipv4.empty() && enable_ipv4_true ) {
errorStack->pushf( "init_network_interfaces", 3, "ENABLE_IPV4 is TRUE, but no IPv4 address was detected. Ensure that your NETWORK_INTERFACE parameter is not set to an IPv6 address." );
return false;
}
// We don't have an enum type in the param system (yet), so check.
if( !enable_ipv4_true && !enable_ipv4_false ) {
if( strcasecmp( enable_ipv4_str.c_str(), "AUTO" ) ) {
errorStack->pushf( "init_network_interfaces", 4, "ENABLE_IPV4 is '%s', must be 'true', 'false', or 'auto'.", enable_ipv4_str.c_str() );
return false;
}
}
if( network_interface_ipv6.empty() && enable_ipv6_true ) {
errorStack->pushf( "init_network_interfaces", 5, "ENABLE_IPV6 is TRUE, but no IPv6 address was detected. Ensure that your NETWORK_INTERFACE parameter is not set to an IPv4 address." );
return false;
}
// We don't have an enum type in the param system (yet), so check.
if( !enable_ipv6_true && !enable_ipv6_false ) {
if( strcasecmp( enable_ipv6_str.c_str(), "AUTO" ) ) {
errorStack->pushf( "init_network_interfaces", 6, "ENABLE_IPV6 is '%s', must be 'true', 'false', or 'auto'.", enable_ipv6_str.c_str() );
return false;
}
}
if( (!network_interface_ipv4.empty()) && enable_ipv4_false ) {
errorStack->pushf( "init_network_interfaces", 7, "ENABLE_IPV4 is false, yet we found an IPv4 address. Ensure that NETWORK_INTERFACE is set appropriately." );
return false;
}
if( (!network_interface_ipv6.empty()) && enable_ipv6_false ) {
errorStack->pushf( "init_network_interfaces", 8, "ENABLE_IPV6 is false, yet we found an IPv6 address. Ensure that NETWORK_INTERFACE is set appropriately." );
return false;
}
return true;
}
<commit_msg>Remove unused variables related to sinful rewriting. #6525<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "internet.h"
#include "my_hostname.h"
#include "condor_attributes.h"
#include "condor_netdb.h"
#include "ipv6_hostname.h"
#include "condor_sinful.h"
#include "CondorError.h"
const char* my_ip_string() {
static MyString __my_ip_string;
// TODO: Picking IPv4 arbitrarily. WARNING: This function
// gets called while the configuration file is being loaded,
// before we know if IPV4 and/or IPv6 is enabled. It needs to
// return a stable answer, because having it change midway
// through parsing the file is a recipe for failure.
__my_ip_string = get_local_ipaddr(CP_IPV4).to_ip_string();
return __my_ip_string.Value();
}
bool
network_interface_to_ip(char const *interface_param_name,char const *interface_pattern,std::string & ipv4, std::string & ipv6, std::string & ipbest)
{
ASSERT( interface_pattern );
if( !interface_param_name ) {
interface_param_name = "";
}
condor_sockaddr addr;
if (addr.from_ip_string(interface_pattern)) {
if(addr.is_ipv4()) {
ipv4 = interface_pattern;
ipbest = ipv4;
} else {
ASSERT(addr.is_ipv6());
ipv6 = interface_pattern;
ipbest = ipv6;
}
dprintf(D_HOSTNAME,"%s=%s, so choosing IP %s\n",
interface_param_name,
interface_pattern,
ipbest.c_str());
// addr.to_ip_string().Value());
return true;
}
unsigned interfaceCount = 0;
StringList pattern(interface_pattern);
std::string matches_str;
std::vector<NetworkDeviceInfo> dev_list;
std::vector<NetworkDeviceInfo>::iterator dev;
bool want_v4 = ! param_false( "ENABLE_IPV4" );
bool want_v6 = ! param_false( "ENABLE_IPV6" );
sysapi_get_network_device_info(dev_list, want_v4, want_v6);
// Order of preference:
// * non-private IP
// * private IP (e.g. 192.168.*)
// * loopback
// In case of a tie, choose the first device in the list.
int best_so_far_v4 = -1;
int best_so_far_v6 = -1;
int best_overall = -1;
for(dev = dev_list.begin();
dev != dev_list.end();
dev++)
{
bool matches = false;
if( strcmp(dev->name(),"")!=0 &&
pattern.contains_anycase_withwildcard(dev->name()) )
{
matches = true;
}
else if( strcmp(dev->IP(),"")!=0 &&
pattern.contains_anycase_withwildcard(dev->IP()) )
{
matches = true;
}
if( !matches ) {
dprintf(D_HOSTNAME,"Ignoring network interface %s (%s) because it does not match %s=%s.\n",
dev->name(), dev->IP(), interface_param_name, interface_pattern);
continue;
}
condor_sockaddr this_addr;
if (!this_addr.from_ip_string(dev->IP())) {
dprintf(D_HOSTNAME,"Ignoring network interface %s (%s) because it does not have a useable IP address.\n",
dev->name(), dev->IP());
continue;
}
if( matches_str.size() ) {
matches_str += ", ";
}
matches_str += dev->name();
matches_str += " ";
matches_str += dev->IP();
++interfaceCount;
int desireability = this_addr.desirability();
if(dev->is_up()) { desireability *= 10; }
int * best_so_far = 0;
std::string * ip = 0;
if(this_addr.is_ipv4()) {
best_so_far = & best_so_far_v4;
ip = & ipv4;
} else {
ASSERT(this_addr.is_ipv6());
best_so_far = & best_so_far_v6;
ip = & ipv6;
}
//dprintf(D_HOSTNAME, "Considering %s (Ranked at %d) as possible local hostname versus %s (%d)\n", addr.to_ip_string().Value(), desireability, ip.c_str(), desireability);
if( desireability > *best_so_far ) {
*best_so_far = desireability;
*ip = dev->IP();
}
if( desireability > best_overall ) {
best_overall = desireability;
ipbest = dev->IP();
}
}
if( best_overall < 0 ) {
dprintf(D_ALWAYS,"Failed to convert %s=%s to an IP address.\n",
interface_param_name, interface_pattern);
return false;
}
//
// Add some smarts to ENABLE_IPV[4|6] = AUTO.
//
// If we only found one protocol, do nothing. Otherwise,
// if both ipv4 and ipv6 are not at least as desirable as a private
// address, then do nothing. If both are at least as desirable as a
// private address, do nothing. If only one is, and that ENABLE
// knob is AUTO, clear the corresponding ipv[4|6] variable.
//
// We're using the raw desirability parameter here, but we should maybe
// be checking to see if the address is public or private instead...
//
condor_sockaddr v4sa, v6sa;
if( v4sa.from_ip_string( ipv4 ) && v6sa.from_ip_string( ipv6 ) ) {
if( (v4sa.desirability() < 4) ^ (v6sa.desirability() < 4) ) {
if( want_v4 && ! param_true( "ENABLE_IPV4" ) ) {
if( v4sa.desirability() < 4 ) {
ipv4.clear();
ipbest = ipv6;
}
}
if( want_v6 && ! param_true( "ENABLE_IPV6" ) ) {
if( v6sa.desirability() < 4) {
ipv6.clear();
ipbest = ipv4;
}
}
}
}
dprintf(D_HOSTNAME,"%s=%s matches %s, choosing IP %s\n",
interface_param_name,
interface_pattern,
matches_str.c_str(),
ipbest.c_str());
return true;
}
bool
init_network_interfaces( CondorError * errorStack )
{
dprintf( D_HOSTNAME, "Trying to getting network interface information after reading config\n" );
bool enable_ipv4_true = false;
bool enable_ipv4_false = false;
bool enable_ipv6_true = false;
bool enable_ipv6_false = false;
std::string enable_ipv4_str;
std::string enable_ipv6_str;
param( enable_ipv4_str, "ENABLE_IPV4" );
param( enable_ipv6_str, "ENABLE_IPV6" );
bool result = false;
if ( string_is_boolean_param( enable_ipv4_str.c_str(), result ) ) {
enable_ipv4_true = result;
enable_ipv4_false = !result;
}
if ( string_is_boolean_param( enable_ipv6_str.c_str(), result ) ) {
enable_ipv6_true = result;
enable_ipv6_false = !result;
}
std::string network_interface;
param( network_interface, "NETWORK_INTERFACE" );
if( enable_ipv4_false && enable_ipv6_false ) {
errorStack->pushf( "init_network_interfaces", 1, "ENABLE_IPV4 and ENABLE_IPV6 are both false." );
return false;
}
std::string network_interface_ipv4;
std::string network_interface_ipv6;
std::string network_interface_best;
bool ok;
ok = network_interface_to_ip(
"NETWORK_INTERFACE",
network_interface.c_str(),
network_interface_ipv4,
network_interface_ipv6,
network_interface_best);
if( !ok ) {
errorStack->pushf( "init_network_interfaces", 2,
"Failed to determine my IP address using NETWORK_INTERFACE=%s",
network_interface.c_str());
return false;
}
//
// Check the validity of the configuration.
//
if( network_interface_ipv4.empty() && enable_ipv4_true ) {
errorStack->pushf( "init_network_interfaces", 3, "ENABLE_IPV4 is TRUE, but no IPv4 address was detected. Ensure that your NETWORK_INTERFACE parameter is not set to an IPv6 address." );
return false;
}
// We don't have an enum type in the param system (yet), so check.
if( !enable_ipv4_true && !enable_ipv4_false ) {
if( strcasecmp( enable_ipv4_str.c_str(), "AUTO" ) ) {
errorStack->pushf( "init_network_interfaces", 4, "ENABLE_IPV4 is '%s', must be 'true', 'false', or 'auto'.", enable_ipv4_str.c_str() );
return false;
}
}
if( network_interface_ipv6.empty() && enable_ipv6_true ) {
errorStack->pushf( "init_network_interfaces", 5, "ENABLE_IPV6 is TRUE, but no IPv6 address was detected. Ensure that your NETWORK_INTERFACE parameter is not set to an IPv4 address." );
return false;
}
// We don't have an enum type in the param system (yet), so check.
if( !enable_ipv6_true && !enable_ipv6_false ) {
if( strcasecmp( enable_ipv6_str.c_str(), "AUTO" ) ) {
errorStack->pushf( "init_network_interfaces", 6, "ENABLE_IPV6 is '%s', must be 'true', 'false', or 'auto'.", enable_ipv6_str.c_str() );
return false;
}
}
if( (!network_interface_ipv4.empty()) && enable_ipv4_false ) {
errorStack->pushf( "init_network_interfaces", 7, "ENABLE_IPV4 is false, yet we found an IPv4 address. Ensure that NETWORK_INTERFACE is set appropriately." );
return false;
}
if( (!network_interface_ipv6.empty()) && enable_ipv6_false ) {
errorStack->pushf( "init_network_interfaces", 8, "ENABLE_IPV6 is false, yet we found an IPv6 address. Ensure that NETWORK_INTERFACE is set appropriately." );
return false;
}
return true;
}
<|endoftext|>
|
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "layouts/PositionLayout.h"
#include "shapes/Shape.h"
#include "../renderer/ModelRenderer.h"
#include "../node_extensions/FullDetailSize.h"
#include "../views/MainView.h"
#include "ModelBase/src/model/TreeManager.h"
namespace Visualization {
ITEM_COMMON_DEFINITIONS( PositionLayout, "layout" )
constexpr bool ENABLE_AUTOMATIC_SEMANTIC_ZOOM = false;
// TODO: Do this properly.
// Defines the semantic zoom level to be used when abstracting an item.
// for performance reasons this is a constant but in the interest of general consistency its value should be
// scene()->defaultRenderer()->semanticZoomLevelId("project_module_class_method_abstraction");
constexpr int FULL_DECLARATION_ABSTRACTION_SEMANTIC_ZOOM_LEVEL = 5;
PositionLayout::PositionLayout(Item* parent, const StyleType* style) :
Super(parent, style)
{
}
PositionLayout::~PositionLayout()
{
for (int i = 0; i<items.size(); i++) SAFE_DELETE_ITEM( items[i]);
}
int PositionLayout::length() const
{
return items.size();
}
bool PositionLayout::containsNode(Model::Node* node_)
{
for (int i=0; i<items.size(); ++i)
if (items[i]->node() == node_) return true;
return false;
}
void PositionLayout::insert(Item* item)
{
// Check whether this item has a node and a position associated with it
ensureItemHasCompositeNode(item);
item->setParentItem(this);
items.append(item);
setUpdateNeeded(StandardUpdate);
}
void PositionLayout::remove(int index, bool deleteItem)
{
if (deleteItem) SAFE_DELETE_ITEM( items[index]);
else if (items[index]) items[index]->setParentItem(nullptr);
items.remove(index);
setUpdateNeeded(StandardUpdate);
}
void PositionLayout::removeAll(Item* item, bool deleteItem)
{
for (int i = items.size() - 1; i>=0; --i)
{
if (items.at(i) == item)
items.remove(i);
}
if (deleteItem) SAFE_DELETE_ITEM(item);
else if (item) item->setParentItem(nullptr);
setUpdateNeeded(StandardUpdate);
}
void PositionLayout::clear(bool deleteItems)
{
for (int i = 0; i<items.size(); ++i)
{
if (deleteItems) SAFE_DELETE_ITEM(items[i]);
else if (items[i]) items[i]->setParentItem(nullptr);
}
items.clear();
}
void PositionLayout::swap(int i, int j)
{
Item* t = items[i];
items[i] = items[j];
items[j] = t;
}
void PositionLayout::synchronizeWithNodes(const QList<Model::Node*>& nodes)
{
// Check if any node is lacking a position info
allNodesLackPositionInfo = items.isEmpty();
if (allNodesLackPositionInfo)
for (auto node : nodes)
if (auto extNode = DCast<Model::CompositeNode> (node))
if (auto pos = extNode->extension<Position>())
if (pos->xNode() || pos->yNode())
{
allNodesLackPositionInfo = false;
break;
}
synchronizeCollections(nodes, items,
[](Model::Node* node, Item* item){return item->node() == node;},
[](Item* parent, Model::Node* node) -> Item*
{
if (ENABLE_AUTOMATIC_SEMANTIC_ZOOM)
parent->setChildNodeSemanticZoomLevel(node, FULL_DECLARATION_ABSTRACTION_SEMANTIC_ZOOM_LEVEL);
auto newItem = parent->renderer()->render(parent, node);
ensureItemHasCompositeNode(newItem);
return newItem;
},
[](Item* parent, Model::Node* node, Item*& item) ->bool
{
bool changed = parent->renderer()->sync(item, parent, node);
ensureItemHasCompositeNode(item);
return changed;
});
}
int PositionLayout::toGrid(const int& pos) const
{
int mod = (pos >=0) ? ( pos % style()->gridSize() ) : ( (-pos) % style()->gridSize() );
int add = (pos >=0) ? ( style()->gridSize() - mod) : mod;
return pos + ( (mod !=0) ? add : 0 );
}
bool PositionLayout::isEmpty() const
{
for (int i = 0; i<items.size(); ++i)
if (!items[i]->isEmpty()) return false;
return true;
}
void PositionLayout::updateGeometry(int, int)
{
QList<Model::TreeManager*> modifiedManagers;
// This is a list of all managers that are modified as a result of this call. Managers are modified when the
// elements of a PositionLayout are arranged for the first time or when the size of an element is updated.
Model::TreeManager* lastModifiedManager = nullptr;
// Arrange items if they were all missing positions.
if (allNodesLackPositionInfo && !items.isEmpty())
{
// Get averages
double averageWidth = 0;
double averageHeight = 0;
for (auto i : items)
{
averageWidth += i->widthInParent();
averageHeight += i->heightInParent();
}
averageWidth /= items.size();
averageHeight /= items.size();
// Get 'optimal' number of rows to achieve a square
double prevRatio = 0;
int rows = 1;
for (rows = 1; rows<items.size(); ++rows)
{
int cols = (items.size()/rows) + ((items.size()%rows)?1:0);
double ratio = (averageWidth*cols) / (averageHeight*rows);
if (ratio > 1) ratio = 1/ratio;
if (ratio > prevRatio)
{
prevRatio = ratio;
}
else
{
if (rows > 1) --rows;
break;
}
}
int heightLimit = rows*averageHeight;
//Compute the columns and set the positions
int lastBottom = 0;
int lastRight = 0;
int colWidth = 0;
lastModifiedManager = items[0]->node()->manager();
modifiedManagers << lastModifiedManager;
lastModifiedManager->beginModification(items[0]->node(), "Automatically set position");
for (int i = 0; i<items.size(); ++i)
{
int x = lastRight;
int y = lastBottom;
if (lastBottom == 0 || (lastBottom + items[i]->heightInParent() <= heightLimit))
{
lastBottom += 10 + items[i]->heightInParent();
lastBottom = toGrid(lastBottom);
if (items[i]->widthInParent() > colWidth) colWidth = items[i]->widthInParent();
}
else
{
y = 0;
lastBottom = 10 + items[i]->heightInParent();
lastRight += 10 + colWidth;
lastRight = toGrid(lastRight);
x = lastRight;
colWidth = items[i]->widthInParent();
}
auto newManager = items[i]->node()->manager();
if (newManager != lastModifiedManager)
{
if (!modifiedManagers.contains(newManager))
{
modifiedManagers << newManager;
newManager->beginModification(items[i]->node(), "Automatically set position");
}
lastModifiedManager = newManager;
}
lastModifiedManager->changeModificationTarget(items[i]->node());
QScopedPointer<Position> position{positionOf(items[i])};
position->set(x, y);
}
allNodesLackPositionInfo = false;
}
// Set the size of all items
for (auto item : items)
{
Model::Node* node = item->node();
auto fds = (static_cast<Model::CompositeNode*>(node))->extension<FullDetailSize>();
if (!fds->hasSize() || fds->size() != item->sizeInParent().toSize())
{
auto newManager = node->manager();
if (newManager != lastModifiedManager)
{
if (!modifiedManagers.contains(newManager))
{
modifiedManagers << newManager;
newManager->beginModification(node, "Set size");
}
lastModifiedManager = newManager;
}
lastModifiedManager->changeModificationTarget(node);
fds->set(item->sizeInParent().toSize());
}
delete fds;
}
// It is important to batch the modifications, since model::endModification() send a notification signal.
for (auto m : modifiedManagers) m->endModification(false);
if (ENABLE_AUTOMATIC_SEMANTIC_ZOOM && adjustChildrenSemanticZoom())
{
setUpdateNeeded(RepeatUpdate);
return;
}
QPoint topLeft;
QPoint bottomRight;
for (int i = 0; i<items.size(); ++i)
{
QScopedPointer<Position> position{positionOf(items[i])};
int x = position->xNode() ? toGrid(position->x()) : 0;
int y = position->yNode() ? toGrid(position->y()) : 0;
if (i==0 || topLeft.x() > x )
topLeft.setX( x );
if (i==0 || topLeft.y() > y )
topLeft.setY( y );
if (i==0 || bottomRight.x() < x + items[i]->widthInParent() )
bottomRight.setX( x + items[i]->widthInParent() );
if (i==0 || bottomRight.y() < y + items[i]->heightInParent() )
bottomRight.setY( y + items[i]->heightInParent() );
}
int sizeWidth = bottomRight.x() - topLeft.x() + style()->leftInnerMargin() + style()->rightInnerMargin();
int sizeHeight = bottomRight.y() - topLeft.y() + style()->topInnerMargin() + style()->bottomInnerMargin();
setInnerSize(sizeWidth, sizeHeight);
for (int i =0; i<items.size(); ++i)
{
QScopedPointer<Position> position{positionOf(items[i])};
int x = position->xNode() ? toGrid(position->x()) : 0;
int y = position->yNode() ? toGrid(position->y()) : 0;
items[i]->setPos( xOffset() + style()->leftInnerMargin() + x - topLeft.x(),
yOffset() + style()->topInnerMargin() + y - topLeft.y());
}
}
int PositionLayout::focusedElementIndex() const
{
for (int i = 0; i<items.size(); ++i)
if ( items[i]->itemOrChildHasFocus()) return i;
return -1;
}
bool PositionLayout::isSensitiveToScale() const
{
return ENABLE_AUTOMATIC_SEMANTIC_ZOOM;
}
void PositionLayout::determineChildren()
{
for (auto & item : items)
renderer()->sync(item, this, item->node());
Super::determineChildren();
}
bool PositionLayout::adjustChildrenSemanticZoom()
{
// An item gets abstracted if its perceived width falls below this value
constexpr qreal ABSTRACTION_THRESHOLD = 200;
bool changesMade = false;
qreal geometricZoomScale = mainViewScalingFactor();
if (geometricZoomScale != previousMainViewScalingFactor())
{
// Computes wherehter this Layout is entirely outside of view
bool inViewport = false;
for (auto views : scene()->views())
{
if (auto mv = dynamic_cast<MainView*>(views))
{
inViewport = mv->visibleRect().intersects(mapRectToScene(0, 0, widthInLocal(), heightInLocal()));
break;
}
}
for (auto item : items)
{
if (geometricZoomScale < 1)
{
if (!inViewport || (item->totalScale() * geometricZoomScale * item->widthInLocal() < ABSTRACTION_THRESHOLD))
{
if (item->semanticZoomLevel() != FULL_DECLARATION_ABSTRACTION_SEMANTIC_ZOOM_LEVEL)
{
setChildNodeSemanticZoomLevel(item->node(), FULL_DECLARATION_ABSTRACTION_SEMANTIC_ZOOM_LEVEL);
changesMade = true;
}
}
else
{
if (inViewport && item->semanticZoomLevel() == FULL_DECLARATION_ABSTRACTION_SEMANTIC_ZOOM_LEVEL)
{
clearChildNodeSemanticZoomLevel(item->node());
changesMade = true;
}
}
}
else
{
// if the geometric zoom scale is larger or equal to 1 everything should be shown in full detail
if (definesChildNodeSemanticZoomLevel(item->node()))
{
clearChildNodeSemanticZoomLevel(item->node());
changesMade = true;
}
}
}
}
return changesMade;
}
}
<commit_msg>Fix the broken Undo due to PositionLayout setting item size<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "layouts/PositionLayout.h"
#include "shapes/Shape.h"
#include "../renderer/ModelRenderer.h"
#include "../node_extensions/FullDetailSize.h"
#include "../views/MainView.h"
#include "ModelBase/src/model/TreeManager.h"
namespace Visualization {
ITEM_COMMON_DEFINITIONS( PositionLayout, "layout" )
constexpr bool ENABLE_AUTOMATIC_SEMANTIC_ZOOM = false;
// TODO: Do this properly.
// Defines the semantic zoom level to be used when abstracting an item.
// for performance reasons this is a constant but in the interest of general consistency its value should be
// scene()->defaultRenderer()->semanticZoomLevelId("project_module_class_method_abstraction");
constexpr int FULL_DECLARATION_ABSTRACTION_SEMANTIC_ZOOM_LEVEL = 5;
PositionLayout::PositionLayout(Item* parent, const StyleType* style) :
Super(parent, style)
{
}
PositionLayout::~PositionLayout()
{
for (int i = 0; i<items.size(); i++) SAFE_DELETE_ITEM( items[i]);
}
int PositionLayout::length() const
{
return items.size();
}
bool PositionLayout::containsNode(Model::Node* node_)
{
for (int i=0; i<items.size(); ++i)
if (items[i]->node() == node_) return true;
return false;
}
void PositionLayout::insert(Item* item)
{
// Check whether this item has a node and a position associated with it
ensureItemHasCompositeNode(item);
item->setParentItem(this);
items.append(item);
setUpdateNeeded(StandardUpdate);
}
void PositionLayout::remove(int index, bool deleteItem)
{
if (deleteItem) SAFE_DELETE_ITEM( items[index]);
else if (items[index]) items[index]->setParentItem(nullptr);
items.remove(index);
setUpdateNeeded(StandardUpdate);
}
void PositionLayout::removeAll(Item* item, bool deleteItem)
{
for (int i = items.size() - 1; i>=0; --i)
{
if (items.at(i) == item)
items.remove(i);
}
if (deleteItem) SAFE_DELETE_ITEM(item);
else if (item) item->setParentItem(nullptr);
setUpdateNeeded(StandardUpdate);
}
void PositionLayout::clear(bool deleteItems)
{
for (int i = 0; i<items.size(); ++i)
{
if (deleteItems) SAFE_DELETE_ITEM(items[i]);
else if (items[i]) items[i]->setParentItem(nullptr);
}
items.clear();
}
void PositionLayout::swap(int i, int j)
{
Item* t = items[i];
items[i] = items[j];
items[j] = t;
}
void PositionLayout::synchronizeWithNodes(const QList<Model::Node*>& nodes)
{
// Check if any node is lacking a position info
allNodesLackPositionInfo = items.isEmpty();
if (allNodesLackPositionInfo)
for (auto node : nodes)
if (auto extNode = DCast<Model::CompositeNode> (node))
if (auto pos = extNode->extension<Position>())
if (pos->xNode() || pos->yNode())
{
allNodesLackPositionInfo = false;
break;
}
synchronizeCollections(nodes, items,
[](Model::Node* node, Item* item){return item->node() == node;},
[](Item* parent, Model::Node* node) -> Item*
{
if (ENABLE_AUTOMATIC_SEMANTIC_ZOOM)
parent->setChildNodeSemanticZoomLevel(node, FULL_DECLARATION_ABSTRACTION_SEMANTIC_ZOOM_LEVEL);
auto newItem = parent->renderer()->render(parent, node);
ensureItemHasCompositeNode(newItem);
return newItem;
},
[](Item* parent, Model::Node* node, Item*& item) ->bool
{
bool changed = parent->renderer()->sync(item, parent, node);
ensureItemHasCompositeNode(item);
return changed;
});
}
int PositionLayout::toGrid(const int& pos) const
{
int mod = (pos >=0) ? ( pos % style()->gridSize() ) : ( (-pos) % style()->gridSize() );
int add = (pos >=0) ? ( style()->gridSize() - mod) : mod;
return pos + ( (mod !=0) ? add : 0 );
}
bool PositionLayout::isEmpty() const
{
for (int i = 0; i<items.size(); ++i)
if (!items[i]->isEmpty()) return false;
return true;
}
void PositionLayout::updateGeometry(int, int)
{
QList<Model::TreeManager*> modifiedManagers;
// This is a list of all managers that are modified as a result of this call. Managers are modified when the
// elements of a PositionLayout are arranged for the first time or when the size of an element is updated.
Model::TreeManager* lastModifiedManager = nullptr;
// Arrange items if they were all missing positions.
if (allNodesLackPositionInfo && !items.isEmpty())
{
// Get averages
double averageWidth = 0;
double averageHeight = 0;
for (auto i : items)
{
averageWidth += i->widthInParent();
averageHeight += i->heightInParent();
}
averageWidth /= items.size();
averageHeight /= items.size();
// Get 'optimal' number of rows to achieve a square
double prevRatio = 0;
int rows = 1;
for (rows = 1; rows<items.size(); ++rows)
{
int cols = (items.size()/rows) + ((items.size()%rows)?1:0);
double ratio = (averageWidth*cols) / (averageHeight*rows);
if (ratio > 1) ratio = 1/ratio;
if (ratio > prevRatio)
{
prevRatio = ratio;
}
else
{
if (rows > 1) --rows;
break;
}
}
int heightLimit = rows*averageHeight;
//Compute the columns and set the positions
int lastBottom = 0;
int lastRight = 0;
int colWidth = 0;
lastModifiedManager = items[0]->node()->manager();
modifiedManagers << lastModifiedManager;
lastModifiedManager->beginModification(items[0]->node(), "Automatically set position");
for (int i = 0; i<items.size(); ++i)
{
int x = lastRight;
int y = lastBottom;
if (lastBottom == 0 || (lastBottom + items[i]->heightInParent() <= heightLimit))
{
lastBottom += 10 + items[i]->heightInParent();
lastBottom = toGrid(lastBottom);
if (items[i]->widthInParent() > colWidth) colWidth = items[i]->widthInParent();
}
else
{
y = 0;
lastBottom = 10 + items[i]->heightInParent();
lastRight += 10 + colWidth;
lastRight = toGrid(lastRight);
x = lastRight;
colWidth = items[i]->widthInParent();
}
auto newManager = items[i]->node()->manager();
if (newManager != lastModifiedManager)
{
if (!modifiedManagers.contains(newManager))
{
modifiedManagers << newManager;
newManager->beginModification(items[i]->node(), "Automatically set position");
}
lastModifiedManager = newManager;
}
lastModifiedManager->changeModificationTarget(items[i]->node());
QScopedPointer<Position> position{positionOf(items[i])};
position->set(x, y);
}
allNodesLackPositionInfo = false;
}
// Set the size of all items
// TODO: Enabling this prevents undo as it always registers a new action. There should be a better time to do this.
// for (auto item : items)
// {
// Model::Node* node = item->node();
// auto fds = (static_cast<Model::CompositeNode*>(node))->extension<FullDetailSize>();
// if (!fds->hasSize() || fds->size() != item->sizeInParent().toSize())
// {
// auto newManager = node->manager();
// if (newManager != lastModifiedManager)
// {
// if (!modifiedManagers.contains(newManager))
// {
// modifiedManagers << newManager;
// newManager->beginModification(node, "Set size");
// qDebug() << "SETTING SIZE";
// }
// lastModifiedManager = newManager;
// }
// lastModifiedManager->changeModificationTarget(node);
// fds->set(item->sizeInParent().toSize());
// }
// delete fds;
// }
// It is important to batch the modifications, since model::endModification() send a notification signal.
for (auto m : modifiedManagers) m->endModification(false);
if (ENABLE_AUTOMATIC_SEMANTIC_ZOOM && adjustChildrenSemanticZoom())
{
setUpdateNeeded(RepeatUpdate);
return;
}
QPoint topLeft;
QPoint bottomRight;
for (int i = 0; i<items.size(); ++i)
{
QScopedPointer<Position> position{positionOf(items[i])};
int x = position->xNode() ? toGrid(position->x()) : 0;
int y = position->yNode() ? toGrid(position->y()) : 0;
if (i==0 || topLeft.x() > x )
topLeft.setX( x );
if (i==0 || topLeft.y() > y )
topLeft.setY( y );
if (i==0 || bottomRight.x() < x + items[i]->widthInParent() )
bottomRight.setX( x + items[i]->widthInParent() );
if (i==0 || bottomRight.y() < y + items[i]->heightInParent() )
bottomRight.setY( y + items[i]->heightInParent() );
}
int sizeWidth = bottomRight.x() - topLeft.x() + style()->leftInnerMargin() + style()->rightInnerMargin();
int sizeHeight = bottomRight.y() - topLeft.y() + style()->topInnerMargin() + style()->bottomInnerMargin();
setInnerSize(sizeWidth, sizeHeight);
for (int i =0; i<items.size(); ++i)
{
QScopedPointer<Position> position{positionOf(items[i])};
int x = position->xNode() ? toGrid(position->x()) : 0;
int y = position->yNode() ? toGrid(position->y()) : 0;
items[i]->setPos( xOffset() + style()->leftInnerMargin() + x - topLeft.x(),
yOffset() + style()->topInnerMargin() + y - topLeft.y());
}
}
int PositionLayout::focusedElementIndex() const
{
for (int i = 0; i<items.size(); ++i)
if ( items[i]->itemOrChildHasFocus()) return i;
return -1;
}
bool PositionLayout::isSensitiveToScale() const
{
return ENABLE_AUTOMATIC_SEMANTIC_ZOOM;
}
void PositionLayout::determineChildren()
{
for (auto & item : items)
renderer()->sync(item, this, item->node());
Super::determineChildren();
}
bool PositionLayout::adjustChildrenSemanticZoom()
{
// An item gets abstracted if its perceived width falls below this value
constexpr qreal ABSTRACTION_THRESHOLD = 200;
bool changesMade = false;
qreal geometricZoomScale = mainViewScalingFactor();
if (geometricZoomScale != previousMainViewScalingFactor())
{
// Computes wherehter this Layout is entirely outside of view
bool inViewport = false;
for (auto views : scene()->views())
{
if (auto mv = dynamic_cast<MainView*>(views))
{
inViewport = mv->visibleRect().intersects(mapRectToScene(0, 0, widthInLocal(), heightInLocal()));
break;
}
}
for (auto item : items)
{
if (geometricZoomScale < 1)
{
if (!inViewport || (item->totalScale() * geometricZoomScale * item->widthInLocal() < ABSTRACTION_THRESHOLD))
{
if (item->semanticZoomLevel() != FULL_DECLARATION_ABSTRACTION_SEMANTIC_ZOOM_LEVEL)
{
setChildNodeSemanticZoomLevel(item->node(), FULL_DECLARATION_ABSTRACTION_SEMANTIC_ZOOM_LEVEL);
changesMade = true;
}
}
else
{
if (inViewport && item->semanticZoomLevel() == FULL_DECLARATION_ABSTRACTION_SEMANTIC_ZOOM_LEVEL)
{
clearChildNodeSemanticZoomLevel(item->node());
changesMade = true;
}
}
}
else
{
// if the geometric zoom scale is larger or equal to 1 everything should be shown in full detail
if (definesChildNodeSemanticZoomLevel(item->node()))
{
clearChildNodeSemanticZoomLevel(item->node());
changesMade = true;
}
}
}
}
return changesMade;
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
enum MoveDirection { LEFT, UP, RIGHT, DOWN };
class ConsoleMoveDirectionReader {
public:
MoveDirection next() {
while (true) {
std::cout << "WASD then <enter> to move: ";
int keyCode = std::cin.get();
if (keyCode == 97) {
return MoveDirection::LEFT;
break;
}
else if (keyCode == 115) {
return MoveDirection::DOWN;
break;
}
else if (keyCode == 100) {
return MoveDirection::RIGHT;
break;
}
else if (keyCode == 119) {
return MoveDirection::UP;
break;
}
}
}
};
class TileGenerator {
public:
TileGenerator() {
std::srand(0);
}
std::tuple<int, int, int> next() {
int value = std::rand() % 10 == 0 ? 2 : 1;
return std::tuple<int, int, int>(std::rand() % 4, std::rand() % 4, value);
}
};
#include <cstdlib>
void print (int board[4][4]) {
std::cout << " +---+---+---+---+" << std::endl;
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
int val = board[y][x] > 0 ? (1 << board[y][x]) : 0;
std::cout << " | " << val;
}
std::cout << " |" << std::endl;
std::cout << " +---+---+---+---+" << std::endl;
}
std::cout << std:: endl;
}
int main() {
std::cout << "[ TwentyFortyEight ]" << std::endl;
int board[4][4];
TileGenerator tileGenerator;
for (int i = 0; i < 2; i++) {
std::tuple<int, int, int> tile = tileGenerator.next();
int xPos = std::get<0>(tile);
int yPos = std::get<1>(tile);
board[yPos][xPos] = std::get<2>(tile);
}
ConsoleMoveDirectionReader directionReader;
while (true) {
print(board);
MoveDirection direction = directionReader.next();
std::cout << (int)direction << std::endl;
}
return 0;
}
<commit_msg>Continuously adds tiles into gameplay.<commit_after>#include <iostream>
enum MoveDirection { LEFT, UP, RIGHT, DOWN };
class ConsoleMoveDirectionReader {
public:
MoveDirection next() {
while (true) {
std::cout << "WASD then <enter> to move: ";
int keyCode = std::cin.get();
// ignore subsequent characters so next read is fresh
std::cin.clear();
std::cin.ignore(INT_MAX,'\n');
if (keyCode == 97) {
return MoveDirection::LEFT;
break;
}
else if (keyCode == 115) {
return MoveDirection::DOWN;
break;
}
else if (keyCode == 100) {
return MoveDirection::RIGHT;
break;
}
else if (keyCode == 119) {
return MoveDirection::UP;
break;
}
}
}
};
class TileGenerator {
public:
TileGenerator() {
std::srand(0);
}
std::tuple<int, int, int> next() {
int value = std::rand() % 10 == 0 ? 2 : 1;
return std::tuple<int, int, int>(std::rand() % 4, std::rand() % 4, value);
}
};
#include <cstdlib>
class GameBoard {
private:
TileGenerator tileGenerator;
int board[4][4] = {{ 0 }}; // initialize board to 0
public:
GameBoard() {
for (int i = 0; i < 2; i++) {
addTile();
}
}
bool addTile() {
std::tuple<int, int, int> tile;
while (true) {
tile = tileGenerator.next();
int xPos = std::get<0>(tile);
int yPos = std::get<1>(tile);
if (board[yPos][xPos] > 0) {
// TODO check if any spot is possible
//return false;
continue;
}
break;
}
int xPos = std::get<0>(tile);
int yPos = std::get<1>(tile);
board[yPos][xPos] = std::get<2>(tile);
return true;
}
void print() {
std::cout << " +---+---+---+---+" << std::endl;
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
int val = board[y][x] > 0 ? (1 << board[y][x]) : 0;
std::cout << " | " << val;
}
std::cout << " |" << std::endl;
std::cout << " +---+---+---+---+" << std::endl;
}
std::cout << std:: endl;
}
};
int main() {
std::cout << "[ TwentyFortyEight ]" << std::endl;
GameBoard board = GameBoard();
ConsoleMoveDirectionReader directionReader;
while (true) {
board.print();
MoveDirection direction = directionReader.next();
std::cout << (int)direction << std::endl;
board.addTile();
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2010-2012 Google
// 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 <string>
#include <vector>
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/stringprintf.h"
#include "base/stl_util.h"
#include "constraint_solver/constraint_solver.h"
#include "util/string_array.h"
namespace operations_research {
// ----- Base Class -----
void NoGoodManager::EnterSearch() {
Init();
}
void NoGoodManager::BeginNextDecision(DecisionBuilder* const db) {
Apply();
}
bool NoGoodManager::AcceptSolution() {
Apply();
return true;
}
NoGood* NoGoodManager::MakeNoGood() {
return new NoGood();
}
// ----- Base class for NoGood terms -----
class NoGoodTerm {
public:
enum TermStatus {
ALWAYS_TRUE,
ALWAYS_FALSE,
UNDECIDED
};
NoGoodTerm() {}
virtual ~NoGoodTerm() {}
virtual TermStatus Evaluate() const = 0;
virtual void Refute() = 0;
virtual string DebugString() const = 0;
private:
DISALLOW_COPY_AND_ASSIGN(NoGoodTerm);
};
namespace {
// ----- IntegerVariableNoGoodTerm -----
// IntVar == int64 specialization.
class IntegerVariableNoGoodTerm : public NoGoodTerm {
public:
IntegerVariableNoGoodTerm(IntVar* const var, int64 value, bool assign)
: integer_variable_(var), value_(value), assign_(assign) {
CHECK_NOTNULL(integer_variable_);
}
virtual TermStatus Evaluate() const {
if (!integer_variable_->Contains(value_)) {
return assign_ ? ALWAYS_FALSE : ALWAYS_TRUE;
} else if (integer_variable_->Bound()) {
return assign_ ? ALWAYS_TRUE : ALWAYS_FALSE;
} else {
return UNDECIDED;
}
}
virtual void Refute() {
if (assign_) {
integer_variable_->RemoveValue(value_);
} else {
integer_variable_->SetValue(value_);
}
}
virtual string DebugString() const {
return StringPrintf("(var_%s %s %lld)",
integer_variable_->name().c_str(),
assign_ ? "==" : "!=",
value_);
}
IntVar* integer_variable() const { return integer_variable_; }
int64 value() const { return value_; }
bool assign() const { return assign_; }
private:
IntVar* const integer_variable_;
const int64 value_;
const bool assign_;
DISALLOW_COPY_AND_ASSIGN(IntegerVariableNoGoodTerm);
};
} // namespace
// ----- NoGood -----
NoGood::~NoGood() {
STLDeleteElements(&terms_);
}
void NoGood::AddIntegerVariableEqualValueTerm(IntVar* const var, int64 value) {
terms_.push_back(new IntegerVariableNoGoodTerm(var, value, true));
}
void NoGood::AddIntegerVariableNotEqualValueTerm(IntVar* const var,
int64 value) {
terms_.push_back(new IntegerVariableNoGoodTerm(var, value, false));
}
bool NoGood::Apply(Solver* const solver) {
NoGoodTerm* first_undecided = NULL;
for (int i = 0; i < terms_.size(); ++i) {
switch (terms_[i]->Evaluate()) {
case NoGoodTerm::ALWAYS_TRUE: {
break;
}
case NoGoodTerm::ALWAYS_FALSE: {
return false;
}
case NoGoodTerm::UNDECIDED: {
if (first_undecided == NULL) {
first_undecided = terms_[i];
} else {
// more than one undecided, we cannot deduce anything.
return true;
}
break;
}
}
}
if (first_undecided == NULL && terms_.size() > 0) {
solver->Fail();
}
if (first_undecided != NULL) {
first_undecided->Refute();
return false;
}
return false;
}
string NoGood::DebugString() const {
return StringPrintf("(%s)", DebugStringVector(terms_, " && ").c_str());
}
namespace {
// ----- NoGoodManager -----
// This implementation is very naive. It will be kept in the future as
// a reference point.
class NaiveNoGoodManager : public NoGoodManager {
public:
explicit NaiveNoGoodManager(Solver* const solver) : NoGoodManager(solver) {}
virtual ~NaiveNoGoodManager() {
Clear();
}
virtual void Clear() {
STLDeleteElements(&nogoods_);
}
virtual void Init() {}
virtual void AddNoGood(NoGood* const nogood) {
nogoods_.push_back(nogood);
}
virtual int NoGoodCount() const {
return nogoods_.size();
}
virtual void Apply() {
Solver* const s = solver();
for (int i = 0; i < nogoods_.size(); ++i) {
nogoods_[i]->Apply(s);
}
}
string DebugString() const {
return StringPrintf("NaiveNoGoodManager(%d)", NoGoodCount());
}
private:
std::vector<NoGood*> nogoods_;
};
} // namespace
// ----- API -----
NoGoodManager* Solver::MakeNoGoodManager() {
return RevAlloc(new NaiveNoGoodManager(this));
}
} // namespace operations_research
<commit_msg>more logging on log based restart<commit_after>// Copyright 2010-2012 Google
// 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 <string>
#include <vector>
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/stringprintf.h"
#include "base/stl_util.h"
#include "constraint_solver/constraint_solver.h"
#include "util/string_array.h"
namespace operations_research {
// ----- Base Class -----
void NoGoodManager::EnterSearch() {
Init();
}
void NoGoodManager::BeginNextDecision(DecisionBuilder* const db) {
Apply();
}
bool NoGoodManager::AcceptSolution() {
Apply();
return true;
}
NoGood* NoGoodManager::MakeNoGood() {
return new NoGood();
}
// ----- Base class for NoGood terms -----
class NoGoodTerm {
public:
enum TermStatus {
ALWAYS_TRUE,
ALWAYS_FALSE,
UNDECIDED
};
NoGoodTerm() {}
virtual ~NoGoodTerm() {}
virtual TermStatus Evaluate() const = 0;
virtual void Refute() = 0;
virtual string DebugString() const = 0;
private:
DISALLOW_COPY_AND_ASSIGN(NoGoodTerm);
};
namespace {
// ----- IntegerVariableNoGoodTerm -----
// IntVar == int64 specialization.
class IntegerVariableNoGoodTerm : public NoGoodTerm {
public:
IntegerVariableNoGoodTerm(IntVar* const var, int64 value, bool assign)
: integer_variable_(var), value_(value), assign_(assign) {
CHECK_NOTNULL(integer_variable_);
}
virtual TermStatus Evaluate() const {
if (!integer_variable_->Contains(value_)) {
return assign_ ? ALWAYS_FALSE : ALWAYS_TRUE;
} else if (integer_variable_->Bound()) {
return assign_ ? ALWAYS_TRUE : ALWAYS_FALSE;
} else {
return UNDECIDED;
}
}
virtual void Refute() {
if (assign_) {
integer_variable_->RemoveValue(value_);
} else {
integer_variable_->SetValue(value_);
}
}
virtual string DebugString() const {
return StringPrintf("(var_%s %s %lld)",
integer_variable_->name().c_str(),
assign_ ? "==" : "!=",
value_);
}
IntVar* integer_variable() const { return integer_variable_; }
int64 value() const { return value_; }
bool assign() const { return assign_; }
private:
IntVar* const integer_variable_;
const int64 value_;
const bool assign_;
DISALLOW_COPY_AND_ASSIGN(IntegerVariableNoGoodTerm);
};
} // namespace
// ----- NoGood -----
NoGood::~NoGood() {
STLDeleteElements(&terms_);
}
void NoGood::AddIntegerVariableEqualValueTerm(IntVar* const var, int64 value) {
terms_.push_back(new IntegerVariableNoGoodTerm(var, value, true));
}
void NoGood::AddIntegerVariableNotEqualValueTerm(IntVar* const var,
int64 value) {
terms_.push_back(new IntegerVariableNoGoodTerm(var, value, false));
}
bool NoGood::Apply(Solver* const solver) {
NoGoodTerm* first_undecided = NULL;
for (int i = 0; i < terms_.size(); ++i) {
switch (terms_[i]->Evaluate()) {
case NoGoodTerm::ALWAYS_TRUE: {
break;
}
case NoGoodTerm::ALWAYS_FALSE: {
return false;
}
case NoGoodTerm::UNDECIDED: {
if (first_undecided == NULL) {
first_undecided = terms_[i];
} else {
// more than one undecided, we cannot deduce anything.
return true;
}
break;
}
}
}
if (first_undecided == NULL && terms_.size() > 0) {
VLOG(1) << "No Good " << DebugString() << " -> Fail";
solver->Fail();
}
if (first_undecided != NULL) {
VLOG(1) << "No Good " << DebugString() << " -> Refute "
<< first_undecided->DebugString();;
first_undecided->Refute();
return false;
}
return false;
}
string NoGood::DebugString() const {
return StringPrintf("(%s)", DebugStringVector(terms_, " && ").c_str());
}
namespace {
// ----- NoGoodManager -----
// This implementation is very naive. It will be kept in the future as
// a reference point.
class NaiveNoGoodManager : public NoGoodManager {
public:
explicit NaiveNoGoodManager(Solver* const solver) : NoGoodManager(solver) {}
virtual ~NaiveNoGoodManager() {
Clear();
}
virtual void Clear() {
STLDeleteElements(&nogoods_);
}
virtual void Init() {}
virtual void AddNoGood(NoGood* const nogood) {
nogoods_.push_back(nogood);
}
virtual int NoGoodCount() const {
return nogoods_.size();
}
virtual void Apply() {
Solver* const s = solver();
for (int i = 0; i < nogoods_.size(); ++i) {
nogoods_[i]->Apply(s);
}
}
string DebugString() const {
return StringPrintf("NaiveNoGoodManager(%d)", NoGoodCount());
}
private:
std::vector<NoGood*> nogoods_;
};
} // namespace
// ----- API -----
NoGoodManager* Solver::MakeNoGoodManager() {
return RevAlloc(new NaiveNoGoodManager(this));
}
} // namespace operations_research
<|endoftext|>
|
<commit_before>// Copyright 2017 ASTRON - Netherlands Institute for Radio Astronomy
// Copyright 2017 NLeSC - Netherlands eScience Center
//
// 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.
// Contributor: Alessio Sclocco <a.sclocco@esciencecenter.nl>
#include <Trigger.hpp>
void trigger(const bool subbandDedispersion, const unsigned int padding, const unsigned int integration, const float threshold, const AstroData::Observation & observation, const std::vector<float> & snrData, const std::vector<unsigned int> & samplesData, triggeredEvents_t & triggeredEvents) {
unsigned int nrDMs = 0;
if ( subbandDedispersion ) {
nrDMs = observation.getNrDMsSubbanding() * observation.getNrDMs();
} else {
nrDMs = observation.getNrDMs();
}
#pragma omp parallel for
for ( unsigned int beam = 0; beam < observation.getNrSynthesizedBeams(); beam++ ) {
for ( unsigned int dm = 0; dm < nrDMs; dm++ ) {
if ( snrData[(beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm] >= threshold ) {
triggeredEvent event;
event.beam = beam;
event.sample = samplesData[(beam * isa::utils::pad(nrDMs, padding / sizeof(unsigned int))) + dm];
event.integration = integration;
event.DM = dm;
event.SNR = snrData[(beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm];
if ( triggeredEvents.at(beam).at(dm) != std::out_of_range ) {
// Add event to its existing list
triggeredEvents.at(beam).at(dm).push_back(event);
} else {
// Add event to new list
std::vector<triggeredEvent> events;
events.push_back(event);
triggeredEvents.at(beam).insert(std::pair(dm, events));
}
}
}
}
}
void compact(const AstroData::Observation & observation, const triggeredEvents_t & triggeredEvents, compactedEvents_t & compactedEvents) {
compactedEvents_t temporaryEvents(observation.getNrSynthesizedBeams());
// Compact integration
#pragma omp parallel for
for ( auto beamEvents = triggeredEvents.begin(); beamEvents != triggeredEvents.end(); ++beamEvents ) {
compactedEvent event;
for ( auto dmEvent = beamEvents->second.begin(); dmEvent != beamEvents->second.end(); ++dmEvent ) {
if ( dmEvent->SNR > event.SNR ) {
event.beam = dmEvent->beam;
event.sample = dmEvent->sample;
event.integration = dmEvent->integration;
event.DM = dmEvent->DM;
event.SNR = dmEvent->SNR;
}
}
temporaryEvents.at(event.beam).push_back(event);
}
// Compact DM
#pragma omp parallel for
for ( auto beamEvents = temporaryEvents.begin(); beamEvents != temporaryEvents.end(); ++beamEvents ) {
for ( auto event = beamEvents->begin(); event != beamEvents->end(); ++event ) {
compactedEvent finalEvent;
unsigned int window = 0;
while ( (event->dm + window) == (event + window)->dm ) {
finalEvent.beam = event->beam;
finalEvent.sample = event->sample;
finalEvent.integration = event->integration;
finalEvent.DM = event->DM;
finalEvent.SNR = event->SNR;
finalEvent.compactedDMs += window;
window++;
}
event += (window - 1);
compactedEvent.at(finalEvent.beam).push_back(finalEvent);
}
}
}
<commit_msg>Added the template arguments.<commit_after>// Copyright 2017 ASTRON - Netherlands Institute for Radio Astronomy
// Copyright 2017 NLeSC - Netherlands eScience Center
//
// 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.
// Contributor: Alessio Sclocco <a.sclocco@esciencecenter.nl>
#include <Trigger.hpp>
void trigger(const bool subbandDedispersion, const unsigned int padding, const unsigned int integration, const float threshold, const AstroData::Observation & observation, const std::vector<float> & snrData, const std::vector<unsigned int> & samplesData, triggeredEvents_t & triggeredEvents) {
unsigned int nrDMs = 0;
if ( subbandDedispersion ) {
nrDMs = observation.getNrDMsSubbanding() * observation.getNrDMs();
} else {
nrDMs = observation.getNrDMs();
}
#pragma omp parallel for
for ( unsigned int beam = 0; beam < observation.getNrSynthesizedBeams(); beam++ ) {
for ( unsigned int dm = 0; dm < nrDMs; dm++ ) {
if ( snrData[(beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm] >= threshold ) {
triggeredEvent event;
event.beam = beam;
event.sample = samplesData[(beam * isa::utils::pad(nrDMs, padding / sizeof(unsigned int))) + dm];
event.integration = integration;
event.DM = dm;
event.SNR = snrData[(beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm];
if ( triggeredEvents.at(beam).at(dm) != std::out_of_range ) {
// Add event to its existing list
triggeredEvents.at(beam).at(dm).push_back(event);
} else {
// Add event to new list
std::vector<triggeredEvent> events;
events.push_back(event);
triggeredEvents.at(beam).insert(std::pair<unsigned int, std::vector<triggeredEvnt>>(dm, events));
}
}
}
}
}
void compact(const AstroData::Observation & observation, const triggeredEvents_t & triggeredEvents, compactedEvents_t & compactedEvents) {
compactedEvents_t temporaryEvents(observation.getNrSynthesizedBeams());
// Compact integration
#pragma omp parallel for
for ( auto beamEvents = triggeredEvents.begin(); beamEvents != triggeredEvents.end(); ++beamEvents ) {
compactedEvent event;
for ( auto dmEvent = beamEvents->second.begin(); dmEvent != beamEvents->second.end(); ++dmEvent ) {
if ( dmEvent->SNR > event.SNR ) {
event.beam = dmEvent->beam;
event.sample = dmEvent->sample;
event.integration = dmEvent->integration;
event.DM = dmEvent->DM;
event.SNR = dmEvent->SNR;
}
}
temporaryEvents.at(event.beam).push_back(event);
}
// Compact DM
#pragma omp parallel for
for ( auto beamEvents = temporaryEvents.begin(); beamEvents != temporaryEvents.end(); ++beamEvents ) {
for ( auto event = beamEvents->begin(); event != beamEvents->end(); ++event ) {
compactedEvent finalEvent;
unsigned int window = 0;
while ( (event->dm + window) == (event + window)->dm ) {
finalEvent.beam = event->beam;
finalEvent.sample = event->sample;
finalEvent.integration = event->integration;
finalEvent.DM = event->DM;
finalEvent.SNR = event->SNR;
finalEvent.compactedDMs += window;
window++;
}
event += (window - 1);
compactedEvent.at(finalEvent.beam).push_back(finalEvent);
}
}
}
<|endoftext|>
|
<commit_before>#include "Utility.h"
#include <vector>
#include <random>
#include <chrono>
#include <fstream>
#include <algorithm>
std::vector<std::string> String::split(const std::string& s, const std::string& delim, size_t count)
{
std::vector<std::string> result;
size_t start_index = 0;
size_t end_index = 0;
size_t split_count = 0;
while(end_index < s.size() && split_count < count)
{
end_index = (delim.empty() ?
s.find_first_of(" \t\n", start_index) :
s.find(delim, start_index));
result.push_back(s.substr(start_index, end_index-start_index));
if(end_index == std::string::npos)
{
start_index = std::string::npos;
}
else
{
start_index = end_index + (delim.empty() ? 1 : delim.size());
}
++split_count;
}
if(start_index < s.size())
{
result.push_back(s.substr(start_index));
}
if(delim.empty())
{
auto it = result.begin();
while(it != result.end())
{
if((*it).empty())
{
it = result.erase(it);
}
else
{
++it;
}
}
}
return result;
}
bool String::starts_with(const std::string& s, const std::string& beginning)
{
if(beginning.size() > s.size())
{
return false;
}
for(size_t i = 0; i < beginning.size(); ++i)
{
if(beginning[i] != s[i])
{
return false;
}
}
return true;
}
bool String::starts_with(const std::string& s, char beginning)
{
return s[0] == beginning;
}
std::string String::trim_outer_whitespace(const std::string& str)
{
if (str.empty())
{
return str;
}
size_t start = 0;
while(start < str.size() && isspace(str[start]))
{
++start;
}
size_t end = std::max(str.size() - 1, start);
while(end > start && isspace(str[end]))
{
--end;
}
return str.substr(start, end - start + 1);
}
std::string String::strip_comments(const std::string& str, char comment)
{
return trim_outer_whitespace(str.substr(0, str.find(comment)));
}
int Random::random_integer(int min, int max)
{
static std::mt19937_64
generator(std::chrono::system_clock::now().time_since_epoch().count());
return std::uniform_int_distribution<int>(min, max)(generator);
}
double Random::random_normal(double standard_deviation)
{
static std::mt19937_64
generator(std::chrono::system_clock::now().time_since_epoch().count());
return std::normal_distribution<double>(0, standard_deviation)(generator);
}
double Random::random_real(double min, double max)
{
static std::mt19937_64
generator(std::chrono::system_clock::now().time_since_epoch().count());
return std::uniform_real_distribution<double>(min, max)(generator);
}
bool Random::coin_flip()
{
return success_probability(0.5);
}
bool Random::success_probability(double probability)
{
return random_real(0, 1) < probability;
}
// Mean moves left in game given that a number of moves have been made already.
double Math::average_moves_left(double mean_moves, size_t moves_so_far)
{
double A = 0;
double A_prev = -1;
double B = 0;
double B_prev = -1;
for(size_t N = moves_so_far + 1; A != A_prev && B != B_prev; ++N)
{
A_prev = A;
B_prev = B;
auto p = poisson_probability(mean_moves, N);
A += p;
B += N*p;
}
return B/A - moves_so_far;
}
double Math::poisson_probability(double mean, size_t value)
{
auto p = std::exp(-mean);
for(size_t i = 1; i <= value; ++i)
{
p *= (mean/i);
}
return p;
}
Configuration_File::Configuration_File(const std::string& file_name)
{
std::ifstream ifs(file_name);
std::string line;
while(getline(ifs, line))
{
line = String::strip_comments(line, '#');
if(line.empty())
{
continue;
}
if( ! String::contains(line, '='))
{
throw std::runtime_error("Configuration file lines must be of form \"Name = Value\"\n" + line);
}
auto line_split = String::split(line, "=", 1);
parameters[String::trim_outer_whitespace(line_split[0])] = line_split[1];
}
}
std::string Configuration_File::get_text(const std::string& parameter) const
{
try
{
return String::trim_outer_whitespace(parameters.at(parameter));
}
catch(const std::out_of_range&)
{
return "";
}
}
double Configuration_File::get_number(const std::string& parameter) const
{
try
{
return std::stod(get_text(parameter));
}
catch(const std::invalid_argument&)
{
return 0.0;
}
}
<commit_msg>Trim whitespace from results of default String::split()<commit_after>#include "Utility.h"
#include <vector>
#include <random>
#include <chrono>
#include <fstream>
#include <algorithm>
std::vector<std::string> String::split(const std::string& s, const std::string& delim, size_t count)
{
std::vector<std::string> result;
size_t start_index = 0;
size_t end_index = 0;
size_t split_count = 0;
while(end_index < s.size() && split_count < count)
{
end_index = (delim.empty() ?
s.find_first_of(" \t\n", start_index) :
s.find(delim, start_index));
result.push_back(s.substr(start_index, end_index-start_index));
if(end_index == std::string::npos)
{
start_index = std::string::npos;
}
else
{
start_index = end_index + (delim.empty() ? 1 : delim.size());
}
++split_count;
}
if(start_index < s.size())
{
result.push_back(s.substr(start_index));
}
if(delim.empty())
{
auto it = result.begin();
while(it != result.end())
{
if((*it).empty())
{
it = result.erase(it);
}
else
{
(*it) = String::trim_outer_whitespace(*it);
++it;
}
}
}
return result;
}
bool String::starts_with(const std::string& s, const std::string& beginning)
{
if(beginning.size() > s.size())
{
return false;
}
for(size_t i = 0; i < beginning.size(); ++i)
{
if(beginning[i] != s[i])
{
return false;
}
}
return true;
}
bool String::starts_with(const std::string& s, char beginning)
{
return s[0] == beginning;
}
std::string String::trim_outer_whitespace(const std::string& str)
{
if (str.empty())
{
return str;
}
size_t start = 0;
while(start < str.size() && isspace(str[start]))
{
++start;
}
size_t end = std::max(str.size() - 1, start);
while(end > start && isspace(str[end]))
{
--end;
}
return str.substr(start, end - start + 1);
}
std::string String::strip_comments(const std::string& str, char comment)
{
return trim_outer_whitespace(str.substr(0, str.find(comment)));
}
int Random::random_integer(int min, int max)
{
static std::mt19937_64
generator(std::chrono::system_clock::now().time_since_epoch().count());
return std::uniform_int_distribution<int>(min, max)(generator);
}
double Random::random_normal(double standard_deviation)
{
static std::mt19937_64
generator(std::chrono::system_clock::now().time_since_epoch().count());
return std::normal_distribution<double>(0, standard_deviation)(generator);
}
double Random::random_real(double min, double max)
{
static std::mt19937_64
generator(std::chrono::system_clock::now().time_since_epoch().count());
return std::uniform_real_distribution<double>(min, max)(generator);
}
bool Random::coin_flip()
{
return success_probability(0.5);
}
bool Random::success_probability(double probability)
{
return random_real(0, 1) < probability;
}
// Mean moves left in game given that a number of moves have been made already.
double Math::average_moves_left(double mean_moves, size_t moves_so_far)
{
double A = 0;
double A_prev = -1;
double B = 0;
double B_prev = -1;
for(size_t N = moves_so_far + 1; A != A_prev && B != B_prev; ++N)
{
A_prev = A;
B_prev = B;
auto p = poisson_probability(mean_moves, N);
A += p;
B += N*p;
}
return B/A - moves_so_far;
}
double Math::poisson_probability(double mean, size_t value)
{
auto p = std::exp(-mean);
for(size_t i = 1; i <= value; ++i)
{
p *= (mean/i);
}
return p;
}
Configuration_File::Configuration_File(const std::string& file_name)
{
std::ifstream ifs(file_name);
std::string line;
while(getline(ifs, line))
{
line = String::strip_comments(line, '#');
if(line.empty())
{
continue;
}
if( ! String::contains(line, '='))
{
throw std::runtime_error("Configuration file lines must be of form \"Name = Value\"\n" + line);
}
auto line_split = String::split(line, "=", 1);
parameters[String::trim_outer_whitespace(line_split[0])] = line_split[1];
}
}
std::string Configuration_File::get_text(const std::string& parameter) const
{
try
{
return String::trim_outer_whitespace(parameters.at(parameter));
}
catch(const std::out_of_range&)
{
return "";
}
}
double Configuration_File::get_number(const std::string& parameter) const
{
try
{
return std::stod(get_text(parameter));
}
catch(const std::invalid_argument&)
{
return 0.0;
}
}
<|endoftext|>
|
<commit_before>#include "jobwidget.h"
#include "debug.h"
#include "restoredialog.h"
#include "ui_jobwidget.h"
#include "utils.h"
#include <QMenu>
JobWidget::JobWidget(QWidget *parent)
: QWidget(parent), _ui(new Ui::JobWidget), _saveEnabled(false)
{
_ui->setupUi(this);
_ui->archiveListWidget->setAttribute(Qt::WA_MacShowFocusRect, false);
connect(_ui->jobNameLineEdit, &QLineEdit::textChanged, [&]() {
if(_job->objectKey().isEmpty())
emit enableSave(canSaveNew());
});
connect(_ui->jobTreeWidget, &FilePickerWidget::selectionChanged, [&]() {
if(_job->objectKey().isEmpty())
emit enableSave(canSaveNew());
else
save();
});
// connect(_ui->jobTreeWidget, &FilePickerWidget::focusLost,
// [&](){
// if(!_job->objectKey().isEmpty())
// save();
// });
connect(_ui->includeScheduledCheckBox, &QCheckBox::toggled, this,
&JobWidget::save);
connect(_ui->preservePathsCheckBox, &QCheckBox::toggled, this,
&JobWidget::save);
connect(_ui->traverseMountCheckBox, &QCheckBox::toggled, this,
&JobWidget::save);
connect(_ui->followSymLinksCheckBox, &QCheckBox::toggled, this,
&JobWidget::save);
connect(_ui->skipNoDumpCheckBox, &QCheckBox::toggled, this, &JobWidget::save);
connect(_ui->skipFilesSizeSpinBox, &QSpinBox::editingFinished, this,
&JobWidget::save);
connect(_ui->skipFilesCheckBox, &QCheckBox::toggled, this, &JobWidget::save);
connect(_ui->skipFilesLineEdit, &QLineEdit::editingFinished, this,
&JobWidget::save);
connect(_ui->hideButton, &QPushButton::clicked, this, &JobWidget::collapse);
connect(_ui->restoreLatestArchiveButton, &QPushButton::clicked, this,
&JobWidget::restoreLatestArchive);
connect(_ui->archiveListWidget, &ArchiveListWidget::inspectArchive, this,
&JobWidget::inspectJobArchive);
connect(_ui->archiveListWidget, &ArchiveListWidget::restoreArchive, this,
&JobWidget::restoreJobArchive);
connect(_ui->archiveListWidget, &ArchiveListWidget::deleteArchives, this,
&JobWidget::deleteJobArchives);
connect(_ui->skipFilesDefaultsButton, &QPushButton::clicked, [&]() {
QSettings settings;
_ui->skipFilesLineEdit->setText(
settings.value("app/skip_system_files", DEFAULT_SKIP_FILES).toString());
});
connect(_ui->archiveListWidget,
&ArchiveListWidget::customContextMenuRequested, this,
&JobWidget::showArchiveListMenu);
connect(_ui->actionDelete, &QAction::triggered, _ui->archiveListWidget,
&ArchiveListWidget::removeSelectedItems);
connect(_ui->actionRestore, &QAction::triggered, _ui->archiveListWidget,
&ArchiveListWidget::restoreSelectedItem);
connect(_ui->actionInspect, &QAction::triggered, _ui->archiveListWidget,
&ArchiveListWidget::inspectSelectedItem);
}
JobWidget::~JobWidget()
{
delete _ui;
}
JobPtr JobWidget::job() const
{
return _job;
}
void JobWidget::setJob(const JobPtr &job)
{
_job = job;
// Creating a new job?
if(_job->objectKey().isEmpty())
{
_ui->tabWidget->setTabEnabled(_ui->tabWidget->indexOf(_ui->archiveListTab),
false);
_ui->restoreLatestArchiveButton->hide();
_ui->jobNameLabel->hide();
_ui->jobNameLineEdit->show();
_ui->tabWidget->setCurrentWidget(_ui->jobTreeTab);
_ui->jobNameLineEdit->setFocus();
}
else
{
_saveEnabled = false;
_ui->tabWidget->setTabEnabled(_ui->tabWidget->indexOf(_ui->archiveListTab),
true);
_ui->restoreLatestArchiveButton->show();
_ui->jobNameLabel->show();
_ui->jobNameLineEdit->hide();
_ui->tabWidget->setCurrentWidget(_ui->jobTreeTab);
connect(_job.data(), &Job::changed, this, &JobWidget::updateDetails);
_saveEnabled = true;
}
updateDetails();
}
void JobWidget::save()
{
if(_saveEnabled && !_job->objectKey().isEmpty())
{
DEBUG << "SAVE JOB";
_job->setUrls(_ui->jobTreeWidget->getSelectedUrls());
_job->setOptionScheduledEnabled(
_ui->includeScheduledCheckBox->isChecked());
_job->setOptionPreservePaths(_ui->preservePathsCheckBox->isChecked());
_job->setOptionTraverseMount(_ui->traverseMountCheckBox->isChecked());
_job->setOptionFollowSymLinks(_ui->followSymLinksCheckBox->isChecked());
_job->setOptionSkipNoDump(_ui->skipNoDumpCheckBox->isChecked());
_job->setOptionSkipFilesSize(_ui->skipFilesSizeSpinBox->value());
_job->setOptionSkipFiles(_ui->skipFilesCheckBox->isChecked());
_job->setOptionSkipFilesPatterns(_ui->skipFilesLineEdit->text());
_job->save();
}
}
void JobWidget::saveNew()
{
if(canSaveNew())
{
DEBUG << "SAVE NEW JOB";
_job->setName(_ui->jobNameLineEdit->text());
_job->setUrls(_ui->jobTreeWidget->getSelectedUrls());
_job->setOptionScheduledEnabled(
_ui->includeScheduledCheckBox->isChecked());
_job->setOptionPreservePaths(_ui->preservePathsCheckBox->isChecked());
_job->setOptionTraverseMount(_ui->traverseMountCheckBox->isChecked());
_job->setOptionFollowSymLinks(_ui->followSymLinksCheckBox->isChecked());
_job->setOptionSkipNoDump(_ui->skipNoDumpCheckBox->isChecked());
_job->setOptionSkipFilesSize(_ui->skipFilesSizeSpinBox->value());
_job->setOptionSkipFiles(_ui->skipFilesCheckBox->isChecked());
_job->setOptionSkipFilesPatterns(_ui->skipFilesLineEdit->text());
_job->save();
emit jobAdded(_job);
}
}
void JobWidget::updateDetails()
{
if(_job)
{
_ui->jobNameLineEdit->setText(_job->name());
_ui->jobNameLabel->setText(_job->name());
_ui->jobTreeWidget->blockSignals(true);
_ui->jobTreeWidget->setSelectedUrls(_job->urls());
_ui->jobTreeWidget->blockSignals(false);
_ui->archiveListWidget->clear();
_ui->archiveListWidget->addArchives(_job->archives());
_ui->includeScheduledCheckBox->setChecked(_job->optionScheduledEnabled());
_ui->preservePathsCheckBox->setChecked(_job->optionPreservePaths());
_ui->traverseMountCheckBox->setChecked(_job->optionTraverseMount());
_ui->followSymLinksCheckBox->setChecked(_job->optionFollowSymLinks());
_ui->skipNoDumpCheckBox->setChecked(_job->optionSkipNoDump());
_ui->skipFilesSizeSpinBox->setValue(_job->optionSkipFilesSize());
_ui->skipFilesCheckBox->setChecked(_job->optionSkipFiles());
_ui->skipFilesLineEdit->setText(_job->optionSkipFilesPatterns());
}
}
void JobWidget::restoreLatestArchive()
{
if(_job && !_job->archives().isEmpty())
{
ArchivePtr archive = _job->archives().first();
RestoreDialog restoreDialog(archive, this);
if(QDialog::Accepted == restoreDialog.exec())
emit restoreJobArchive(archive, restoreDialog.getOptions());
}
}
bool JobWidget::canSaveNew()
{
if(_job->objectKey().isEmpty() && !_ui->jobNameLineEdit->text().isEmpty() &&
!_ui->jobTreeWidget->getSelectedUrls().isEmpty())
return true;
else
return false;
}
void JobWidget::showArchiveListMenu(const QPoint &pos)
{
QPoint globalPos = _ui->archiveListWidget->viewport()->mapToGlobal(pos);
QMenu archiveListMenu(_ui->archiveListWidget);
if(!_ui->archiveListWidget->selectedItems().isEmpty())
{
if(_ui->archiveListWidget->selectedItems().count() == 1)
{
archiveListMenu.addAction(_ui->actionInspect);
archiveListMenu.addAction(_ui->actionRestore);
}
archiveListMenu.addAction(_ui->actionDelete);
}
archiveListMenu.exec(globalPos);
}
<commit_msg>Resolve issues when setting a new Job for JobWidget.<commit_after>#include "jobwidget.h"
#include "debug.h"
#include "restoredialog.h"
#include "ui_jobwidget.h"
#include "utils.h"
#include <QMenu>
JobWidget::JobWidget(QWidget *parent)
: QWidget(parent), _ui(new Ui::JobWidget), _saveEnabled(false)
{
_ui->setupUi(this);
_ui->archiveListWidget->setAttribute(Qt::WA_MacShowFocusRect, false);
connect(_ui->jobNameLineEdit, &QLineEdit::textChanged, [&]() {
if(_job->objectKey().isEmpty())
emit enableSave(canSaveNew());
});
connect(_ui->jobTreeWidget, &FilePickerWidget::selectionChanged, [&]() {
if(_job->objectKey().isEmpty())
emit enableSave(canSaveNew());
else
save();
});
// connect(_ui->jobTreeWidget, &FilePickerWidget::focusLost,
// [&](){
// if(!_job->objectKey().isEmpty())
// save();
// });
connect(_ui->includeScheduledCheckBox, &QCheckBox::toggled, this,
&JobWidget::save);
connect(_ui->preservePathsCheckBox, &QCheckBox::toggled, this,
&JobWidget::save);
connect(_ui->traverseMountCheckBox, &QCheckBox::toggled, this,
&JobWidget::save);
connect(_ui->followSymLinksCheckBox, &QCheckBox::toggled, this,
&JobWidget::save);
connect(_ui->skipNoDumpCheckBox, &QCheckBox::toggled, this, &JobWidget::save);
connect(_ui->skipFilesSizeSpinBox, &QSpinBox::editingFinished, this,
&JobWidget::save);
connect(_ui->skipFilesCheckBox, &QCheckBox::toggled, this, &JobWidget::save);
connect(_ui->skipFilesLineEdit, &QLineEdit::editingFinished, this,
&JobWidget::save);
connect(_ui->hideButton, &QPushButton::clicked, this, &JobWidget::collapse);
connect(_ui->restoreLatestArchiveButton, &QPushButton::clicked, this,
&JobWidget::restoreLatestArchive);
connect(_ui->archiveListWidget, &ArchiveListWidget::inspectArchive, this,
&JobWidget::inspectJobArchive);
connect(_ui->archiveListWidget, &ArchiveListWidget::restoreArchive, this,
&JobWidget::restoreJobArchive);
connect(_ui->archiveListWidget, &ArchiveListWidget::deleteArchives, this,
&JobWidget::deleteJobArchives);
connect(_ui->skipFilesDefaultsButton, &QPushButton::clicked, [&]() {
QSettings settings;
_ui->skipFilesLineEdit->setText(
settings.value("app/skip_system_files", DEFAULT_SKIP_FILES).toString());
});
connect(_ui->archiveListWidget,
&ArchiveListWidget::customContextMenuRequested, this,
&JobWidget::showArchiveListMenu);
connect(_ui->actionDelete, &QAction::triggered, _ui->archiveListWidget,
&ArchiveListWidget::removeSelectedItems);
connect(_ui->actionRestore, &QAction::triggered, _ui->archiveListWidget,
&ArchiveListWidget::restoreSelectedItem);
connect(_ui->actionInspect, &QAction::triggered, _ui->archiveListWidget,
&ArchiveListWidget::inspectSelectedItem);
}
JobWidget::~JobWidget()
{
delete _ui;
}
JobPtr JobWidget::job() const
{
return _job;
}
void JobWidget::setJob(const JobPtr &job)
{
_job = job;
_saveEnabled = false;
// Creating a new job?
if(_job->objectKey().isEmpty())
{
_ui->tabWidget->setTabEnabled(_ui->tabWidget->indexOf(_ui->archiveListTab),
false);
_ui->restoreLatestArchiveButton->hide();
_ui->jobNameLabel->hide();
_ui->jobNameLineEdit->show();
_ui->jobNameLineEdit->setFocus();
}
else
{
_ui->tabWidget->setTabEnabled(_ui->tabWidget->indexOf(_ui->archiveListTab),
true);
_ui->restoreLatestArchiveButton->show();
_ui->jobNameLabel->show();
_ui->jobNameLineEdit->hide();
connect(_job.data(), &Job::changed, this, &JobWidget::updateDetails);
}
_ui->tabWidget->setCurrentWidget(_ui->jobTreeTab);
updateDetails();
_saveEnabled = true;
}
void JobWidget::save()
{
if(_saveEnabled && !_job->objectKey().isEmpty())
{
DEBUG << "SAVE JOB";
_job->setUrls(_ui->jobTreeWidget->getSelectedUrls());
_job->setOptionScheduledEnabled(
_ui->includeScheduledCheckBox->isChecked());
_job->setOptionPreservePaths(_ui->preservePathsCheckBox->isChecked());
_job->setOptionTraverseMount(_ui->traverseMountCheckBox->isChecked());
_job->setOptionFollowSymLinks(_ui->followSymLinksCheckBox->isChecked());
_job->setOptionSkipNoDump(_ui->skipNoDumpCheckBox->isChecked());
_job->setOptionSkipFilesSize(_ui->skipFilesSizeSpinBox->value());
_job->setOptionSkipFiles(_ui->skipFilesCheckBox->isChecked());
_job->setOptionSkipFilesPatterns(_ui->skipFilesLineEdit->text());
_job->save();
}
}
void JobWidget::saveNew()
{
if(canSaveNew())
{
DEBUG << "SAVE NEW JOB";
_job->setName(_ui->jobNameLineEdit->text());
_job->setUrls(_ui->jobTreeWidget->getSelectedUrls());
_job->setOptionScheduledEnabled(
_ui->includeScheduledCheckBox->isChecked());
_job->setOptionPreservePaths(_ui->preservePathsCheckBox->isChecked());
_job->setOptionTraverseMount(_ui->traverseMountCheckBox->isChecked());
_job->setOptionFollowSymLinks(_ui->followSymLinksCheckBox->isChecked());
_job->setOptionSkipNoDump(_ui->skipNoDumpCheckBox->isChecked());
_job->setOptionSkipFilesSize(_ui->skipFilesSizeSpinBox->value());
_job->setOptionSkipFiles(_ui->skipFilesCheckBox->isChecked());
_job->setOptionSkipFilesPatterns(_ui->skipFilesLineEdit->text());
_job->save();
emit jobAdded(_job);
}
}
void JobWidget::updateDetails()
{
if(_job)
{
_ui->jobNameLineEdit->setText(_job->name());
_ui->jobNameLabel->setText(_job->name());
_ui->jobTreeWidget->blockSignals(true);
_ui->jobTreeWidget->setSelectedUrls(_job->urls());
_ui->jobTreeWidget->blockSignals(false);
_ui->archiveListWidget->clear();
_ui->archiveListWidget->addArchives(_job->archives());
_ui->includeScheduledCheckBox->setChecked(_job->optionScheduledEnabled());
_ui->preservePathsCheckBox->setChecked(_job->optionPreservePaths());
_ui->traverseMountCheckBox->setChecked(_job->optionTraverseMount());
_ui->followSymLinksCheckBox->setChecked(_job->optionFollowSymLinks());
_ui->skipNoDumpCheckBox->setChecked(_job->optionSkipNoDump());
_ui->skipFilesSizeSpinBox->setValue(_job->optionSkipFilesSize());
_ui->skipFilesCheckBox->setChecked(_job->optionSkipFiles());
_ui->skipFilesLineEdit->setText(_job->optionSkipFilesPatterns());
}
}
void JobWidget::restoreLatestArchive()
{
if(_job && !_job->archives().isEmpty())
{
ArchivePtr archive = _job->archives().first();
RestoreDialog restoreDialog(archive, this);
if(QDialog::Accepted == restoreDialog.exec())
emit restoreJobArchive(archive, restoreDialog.getOptions());
}
}
bool JobWidget::canSaveNew()
{
if(_job->objectKey().isEmpty() && !_ui->jobNameLineEdit->text().isEmpty() &&
!_ui->jobTreeWidget->getSelectedUrls().isEmpty())
return true;
else
return false;
}
void JobWidget::showArchiveListMenu(const QPoint &pos)
{
QPoint globalPos = _ui->archiveListWidget->viewport()->mapToGlobal(pos);
QMenu archiveListMenu(_ui->archiveListWidget);
if(!_ui->archiveListWidget->selectedItems().isEmpty())
{
if(_ui->archiveListWidget->selectedItems().count() == 1)
{
archiveListMenu.addAction(_ui->actionInspect);
archiveListMenu.addAction(_ui->actionRestore);
}
archiveListMenu.addAction(_ui->actionDelete);
}
archiveListMenu.exec(globalPos);
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Library : Image Registration Toolkit (IRTK)
Module : $Id$
Copyright : Imperial College, Department of Computing
Visual Information Processing (VIP), 2008 onwards
Date : $Date$
Version : $Revision$
Changes : $Author$
=========================================================================*/
#include <irtkImage.h>
#include <irtkFileToImage.h>
#include <irtkTransformation.h>
char *input_name = NULL, *output_name = NULL, *dof_name = NULL, *output_matrix_name = NULL;
void usage()
{
cerr << "Usage: headertool [in] [out] <options>" << endl;
cerr << "where <options> can be one or more of the following:" << endl;
cerr << "<-size dx dy dz> Voxel size (in mm)" << endl;
cerr << "<-tsize dt> Voxel size (in ms)" << endl;
cerr << "<-orientation x1 x2 x3 y1 y2 y3 z1 z2 z3> Image orientation" << endl;
cerr << "<-origin x y z> Image spatial origin (in mm)" << endl;
cerr << "<-timeOrigin t> Image temporal origin (in ms)" << endl;
cerr << " " << endl;
cerr << "<-target image> Copy target image's orientation, origin and pixel size" << endl;
cerr << "<-targetOriginAndOrient image> Copy target image's orientation and origin)" << endl;
cerr << "<-targetOrigin image> Copy target image's origin only" << endl;
cerr << " " << endl;
cerr << "<-writeMatrix filename> Save the image to world matrix to a file" << endl;
cerr << "<-reset> Reset origin and axis orientation to default values" << endl;
cerr << " " << endl;
cerr << "<-dofin transformation> Apply transformation to axis, spacing and origin information in the" << endl;
cerr << " header. Transformation may only be rigid or affine (no shearing)." << endl;
exit(1);
}
int main(int argc, char **argv)
{
int i, ok;
double xsize, ysize, zsize, tsize, xaxis[3], yaxis[3], zaxis[3], origin[4];
irtkTransformation *transformation = NULL;
irtkImageAttributes refImageAttr;
if (argc < 3) {
usage();
}
// Parse filenames
input_name = argv[1];
argc--;
argv++;
output_name = argv[1];
argc--;
argv++;
// Read image
irtkFileToImage *reader = irtkFileToImage::New(input_name);
irtkBaseImage *image = reader->GetOutput();
while (argc > 1) {
ok = false;
if ((ok == false) && (strcmp(argv[1], "-dofin") == 0)) {
argc--;
argv++;
dof_name = argv[1];
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-writeMatrix") == 0)) {
argc--;
argv++;
output_matrix_name = argv[1];
argc--;
argv++;
// Write out matrix
irtkMatrix header(4,4);
header = image->GetImageToWorldMatrix();
header.Write(output_matrix_name);
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-target") == 0)) {
argc--;
argv++;
irtkGreyImage target(argv[1]);
argc--;
argv++;
// Take pixel size, axis orientation and spatial origin from target.
target.GetPixelSize(&xsize, &ysize, &zsize);
image->PutPixelSize(xsize, ysize, zsize);
target.GetOrientation(xaxis, yaxis, zaxis);
image->PutOrientation(xaxis, yaxis, zaxis);
target.GetOrigin(origin[0], origin[1], origin[2]);
image->PutOrigin(origin[0], origin[1], origin[2]);
ok = true;
}
if ((ok == false) && strcmp(argv[1], "-targetOriginAndOrient") == 0) {
argc--;
argv++;
irtkGreyImage target(argv[1]);
argc--;
argv++;
// Take axis orientation and spatial origin from target.
target.GetOrientation(xaxis, yaxis, zaxis);
image->PutOrientation(xaxis, yaxis, zaxis);
target.GetOrigin(origin[0], origin[1], origin[2]);
image->PutOrigin(origin[0], origin[1], origin[2]);
ok = true;
}
if ((ok == false) && strcmp(argv[1], "-targetOrigin") == 0) {
argc--;
argv++;
irtkGreyImage target(argv[1]);
argc--;
argv++;
// Take spatial origin from target.
target.GetOrigin(origin[0], origin[1], origin[2]);
image->PutOrigin(origin[0], origin[1], origin[2]);
ok = true;
}
if ((ok == false) && strcmp(argv[1], "-reset") == 0) {
argc--;
argv++;
// Reset axis and spatial origin attributes
irtkImageAttributes defaultAttr;
image->PutOrientation(defaultAttr._xaxis,defaultAttr._yaxis,defaultAttr._zaxis);
image->PutOrigin(defaultAttr._xorigin,defaultAttr._yorigin,defaultAttr._zorigin);
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-size") == 0)) {
argc--;
argv++;
xsize = atof(argv[1]);
argc--;
argv++;
ysize = atof(argv[1]);
argc--;
argv++;
zsize = atof(argv[1]);
argc--;
argv++;
ok = true;
// Set voxel size
image->PutPixelSize(xsize, ysize, zsize);
}
if ((ok == false) && (strcmp(argv[1], "-tsize") == 0)) {
argc--;
argv++;
tsize = atof(argv[1]);
argc--;
argv++;
ok = true;
// Set voxel size
image->GetPixelSize(&xsize, &ysize, &zsize);
image->PutPixelSize(xsize, ysize, zsize, tsize);
}
if ((ok == false) && (strcmp(argv[1], "-orientation") == 0)) {
argc--;
argv++;
xaxis[0] = atof(argv[1]);
argc--;
argv++;
xaxis[1] = atof(argv[1]);
argc--;
argv++;
xaxis[2] = atof(argv[1]);
argc--;
argv++;
yaxis[0] = atof(argv[1]);
argc--;
argv++;
yaxis[1] = atof(argv[1]);
argc--;
argv++;
yaxis[2] = atof(argv[1]);
argc--;
argv++;
zaxis[0] = atof(argv[1]);
argc--;
argv++;
zaxis[1] = atof(argv[1]);
argc--;
argv++;
zaxis[2] = atof(argv[1]);
argc--;
argv++;
ok = true;
// Set orientation (third argument now required)
image->PutOrientation(xaxis, yaxis, zaxis);
}
if ((ok == false) && (strcmp(argv[1], "-origin") == 0)) {
argc--;
argv++;
origin[0] = atof(argv[1]);
argc--;
argv++;
origin[1] = atof(argv[1]);
argc--;
argv++;
origin[2] = atof(argv[1]);
argc--;
argv++;
ok = true;
// Set origin
image->PutOrigin(origin[0], origin[1], origin[2]);
}
if ((ok == false) && (strcmp(argv[1], "-timeOrigin") == 0)) {
argc--;
argv++;
origin[3] = atof(argv[1]);
argc--;
argv++;
// Set temporal origin
image->GetOrigin(origin[0], origin[1], origin[2]);
image->PutOrigin(origin[0], origin[1], origin[2], origin[3]);
ok = true;
}
if (ok == false) {
cout << "Can't parse argument: " << argv[1] << endl;
usage();
}
}
// Applying a transformation to the header information
if (dof_name != NULL) {
// Read transformation
transformation = irtkTransformation::New(dof_name);
if (strcmp(transformation->NameOfClass(), "irtkAffineTransformation") == 0) {
irtkAffineTransformation *affineTransf = dynamic_cast<irtkAffineTransformation*> (transformation);
if (fabs(affineTransf->GetShearXY()) +
fabs(affineTransf->GetShearXZ()) +
fabs(affineTransf->GetShearYZ()) > 0.001){
cerr << "Affine transformation provided contains shearing : Cannot be used to modify header" << endl;
exit(1);
}
} else if (strcmp(transformation->NameOfClass(), "irtkRigidTransformation") != 0) {
cerr<<"header tool: Can only modify header with a rigid or a no-shear affine transformation"<<endl;
exit(1);
}
irtkImageAttributes attr = image->GetImageAttributes();
// Origin:
transformation->Transform(attr._xorigin, attr._yorigin, attr._zorigin);
// Grid spacings:
irtkVector v(3);
irtkVector u(3);
// Zero vector.
u.Initialize(3);
transformation->Transform(u(0), u(1), u(2));
for (i = 0; i < 3; i++){
v(i) = attr._xaxis[i];
}
transformation->Transform(v(0), v(1), v(2));
v = v - u;
attr._dx = attr._dx * v.Norm();
for (i = 0; i < 3; i++){
v(i) = attr._yaxis[i];
}
transformation->Transform(v(0), v(1), v(2));
v = v - u;
attr._dy = attr._dy * v.Norm();
for (i = 0; i < 3; i++){
v(i) = attr._zaxis[i];
}
transformation->Transform(v(0), v(1), v(2));
v = v - u;
attr._dz = attr._dz * v.Norm();
// Axes:
// Isolate rotation part of transformation.
irtkRigidTransformation rotation;
for (i = 3; i < 6; i++){
rotation.Put(i, transformation->Get(i));
}
rotation.Transform(attr._xaxis[0], attr._xaxis[1], attr._xaxis[2]);
rotation.Transform(attr._yaxis[0], attr._yaxis[1], attr._yaxis[2]);
rotation.Transform(attr._zaxis[0], attr._zaxis[1], attr._zaxis[2]);
// Grid size:
// Remains the same so no need to do anything.
// Update image attributes
image->PutOrientation(attr._xaxis,attr._yaxis,attr._zaxis);
image->PutOrigin(attr._xorigin,attr._yorigin,attr._zorigin);
image->PutPixelSize(attr._dx,attr._dy,attr._dz);
delete transformation;
}
image->Write(output_name);
delete image;
delete reader;
return 0;
}
<commit_msg>Re-format usage message to fit into 80 columns.<commit_after>/*=========================================================================
Library : Image Registration Toolkit (IRTK)
Module : $Id$
Copyright : Imperial College, Department of Computing
Visual Information Processing (VIP), 2008 onwards
Date : $Date$
Version : $Revision$
Changes : $Author$
=========================================================================*/
#include <irtkImage.h>
#include <irtkFileToImage.h>
#include <irtkTransformation.h>
char *input_name = NULL, *output_name = NULL, *dof_name = NULL, *output_matrix_name = NULL;
void usage()
{
cerr << "Usage: headertool [in] [out] <options>" << endl;
cerr << "where <options> can be one or more of the following:" << endl;
cerr << "<-size dx dy dz> Voxel size (in mm)" << endl;
cerr << "<-tsize dt> Voxel size (in ms)" << endl;
cerr << "<-orientation x1 x2 x3 y1 y2 y3 z1 z2 z3> Image orientation" << endl;
cerr << "<-origin x y z> Image spatial origin (in mm)" << endl;
cerr << "<-timeOrigin t> Image temporal origin (in ms)" << endl;
cerr << " " << endl;
cerr << "<-target image> Copy target image orientation, origin and pixel" << endl;
cerr << " spacing" << endl;
cerr << "<-targetOriginAndOrient image> Copy target image orientation and origin)" << endl;
cerr << "<-targetOrigin image> Copy target image origin only" << endl;
cerr << " " << endl;
cerr << "<-writeMatrix file> Save the image to world matrix to a file" << endl;
cerr << "<-reset> Reset origin and axis orientation to default " << endl;
cerr << " values" << endl;
cerr << " " << endl;
cerr << "<-dofin file> Apply transformation to axis, spacing and origin" << endl;
cerr << " information in the header. Transformation may " << endl;
cerr << " only be rigid or affine (no shearing)." << endl;
exit(1);
}
int main(int argc, char **argv)
{
int i, ok;
double xsize, ysize, zsize, tsize, xaxis[3], yaxis[3], zaxis[3], origin[4];
irtkTransformation *transformation = NULL;
irtkImageAttributes refImageAttr;
if (argc < 3) {
usage();
}
// Parse filenames
input_name = argv[1];
argc--;
argv++;
output_name = argv[1];
argc--;
argv++;
// Read image
irtkFileToImage *reader = irtkFileToImage::New(input_name);
irtkBaseImage *image = reader->GetOutput();
while (argc > 1) {
ok = false;
if ((ok == false) && (strcmp(argv[1], "-dofin") == 0)) {
argc--;
argv++;
dof_name = argv[1];
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-writeMatrix") == 0)) {
argc--;
argv++;
output_matrix_name = argv[1];
argc--;
argv++;
// Write out matrix
irtkMatrix header(4,4);
header = image->GetImageToWorldMatrix();
header.Write(output_matrix_name);
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-target") == 0)) {
argc--;
argv++;
irtkGreyImage target(argv[1]);
argc--;
argv++;
// Take pixel size, axis orientation and spatial origin from target.
target.GetPixelSize(&xsize, &ysize, &zsize);
image->PutPixelSize(xsize, ysize, zsize);
target.GetOrientation(xaxis, yaxis, zaxis);
image->PutOrientation(xaxis, yaxis, zaxis);
target.GetOrigin(origin[0], origin[1], origin[2]);
image->PutOrigin(origin[0], origin[1], origin[2]);
ok = true;
}
if ((ok == false) && strcmp(argv[1], "-targetOriginAndOrient") == 0) {
argc--;
argv++;
irtkGreyImage target(argv[1]);
argc--;
argv++;
// Take axis orientation and spatial origin from target.
target.GetOrientation(xaxis, yaxis, zaxis);
image->PutOrientation(xaxis, yaxis, zaxis);
target.GetOrigin(origin[0], origin[1], origin[2]);
image->PutOrigin(origin[0], origin[1], origin[2]);
ok = true;
}
if ((ok == false) && strcmp(argv[1], "-targetOrigin") == 0) {
argc--;
argv++;
irtkGreyImage target(argv[1]);
argc--;
argv++;
// Take spatial origin from target.
target.GetOrigin(origin[0], origin[1], origin[2]);
image->PutOrigin(origin[0], origin[1], origin[2]);
ok = true;
}
if ((ok == false) && strcmp(argv[1], "-reset") == 0) {
argc--;
argv++;
// Reset axis and spatial origin attributes
irtkImageAttributes defaultAttr;
image->PutOrientation(defaultAttr._xaxis,defaultAttr._yaxis,defaultAttr._zaxis);
image->PutOrigin(defaultAttr._xorigin,defaultAttr._yorigin,defaultAttr._zorigin);
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-size") == 0)) {
argc--;
argv++;
xsize = atof(argv[1]);
argc--;
argv++;
ysize = atof(argv[1]);
argc--;
argv++;
zsize = atof(argv[1]);
argc--;
argv++;
ok = true;
// Set voxel size
image->PutPixelSize(xsize, ysize, zsize);
}
if ((ok == false) && (strcmp(argv[1], "-tsize") == 0)) {
argc--;
argv++;
tsize = atof(argv[1]);
argc--;
argv++;
ok = true;
// Set voxel size
image->GetPixelSize(&xsize, &ysize, &zsize);
image->PutPixelSize(xsize, ysize, zsize, tsize);
}
if ((ok == false) && (strcmp(argv[1], "-orientation") == 0)) {
argc--;
argv++;
xaxis[0] = atof(argv[1]);
argc--;
argv++;
xaxis[1] = atof(argv[1]);
argc--;
argv++;
xaxis[2] = atof(argv[1]);
argc--;
argv++;
yaxis[0] = atof(argv[1]);
argc--;
argv++;
yaxis[1] = atof(argv[1]);
argc--;
argv++;
yaxis[2] = atof(argv[1]);
argc--;
argv++;
zaxis[0] = atof(argv[1]);
argc--;
argv++;
zaxis[1] = atof(argv[1]);
argc--;
argv++;
zaxis[2] = atof(argv[1]);
argc--;
argv++;
ok = true;
// Set orientation (third argument now required)
image->PutOrientation(xaxis, yaxis, zaxis);
}
if ((ok == false) && (strcmp(argv[1], "-origin") == 0)) {
argc--;
argv++;
origin[0] = atof(argv[1]);
argc--;
argv++;
origin[1] = atof(argv[1]);
argc--;
argv++;
origin[2] = atof(argv[1]);
argc--;
argv++;
ok = true;
// Set origin
image->PutOrigin(origin[0], origin[1], origin[2]);
}
if ((ok == false) && (strcmp(argv[1], "-timeOrigin") == 0)) {
argc--;
argv++;
origin[3] = atof(argv[1]);
argc--;
argv++;
// Set temporal origin
image->GetOrigin(origin[0], origin[1], origin[2]);
image->PutOrigin(origin[0], origin[1], origin[2], origin[3]);
ok = true;
}
if (ok == false) {
cout << "Can't parse argument: " << argv[1] << endl;
usage();
}
}
// Applying a transformation to the header information
if (dof_name != NULL) {
// Read transformation
transformation = irtkTransformation::New(dof_name);
if (strcmp(transformation->NameOfClass(), "irtkAffineTransformation") == 0) {
irtkAffineTransformation *affineTransf = dynamic_cast<irtkAffineTransformation*> (transformation);
if (fabs(affineTransf->GetShearXY()) +
fabs(affineTransf->GetShearXZ()) +
fabs(affineTransf->GetShearYZ()) > 0.001){
cerr << "Affine transformation provided contains shearing : Cannot be used to modify header" << endl;
exit(1);
}
} else if (strcmp(transformation->NameOfClass(), "irtkRigidTransformation") != 0) {
cerr<<"header tool: Can only modify header with a rigid or a no-shear affine transformation"<<endl;
exit(1);
}
irtkImageAttributes attr = image->GetImageAttributes();
// Origin:
transformation->Transform(attr._xorigin, attr._yorigin, attr._zorigin);
// Grid spacings:
irtkVector v(3);
irtkVector u(3);
// Zero vector.
u.Initialize(3);
transformation->Transform(u(0), u(1), u(2));
for (i = 0; i < 3; i++){
v(i) = attr._xaxis[i];
}
transformation->Transform(v(0), v(1), v(2));
v = v - u;
attr._dx = attr._dx * v.Norm();
for (i = 0; i < 3; i++){
v(i) = attr._yaxis[i];
}
transformation->Transform(v(0), v(1), v(2));
v = v - u;
attr._dy = attr._dy * v.Norm();
for (i = 0; i < 3; i++){
v(i) = attr._zaxis[i];
}
transformation->Transform(v(0), v(1), v(2));
v = v - u;
attr._dz = attr._dz * v.Norm();
// Axes:
// Isolate rotation part of transformation.
irtkRigidTransformation rotation;
for (i = 3; i < 6; i++){
rotation.Put(i, transformation->Get(i));
}
rotation.Transform(attr._xaxis[0], attr._xaxis[1], attr._xaxis[2]);
rotation.Transform(attr._yaxis[0], attr._yaxis[1], attr._yaxis[2]);
rotation.Transform(attr._zaxis[0], attr._zaxis[1], attr._zaxis[2]);
// Grid size:
// Remains the same so no need to do anything.
// Update image attributes
image->PutOrientation(attr._xaxis,attr._yaxis,attr._zaxis);
image->PutOrigin(attr._xorigin,attr._yorigin,attr._zorigin);
image->PutPixelSize(attr._dx,attr._dy,attr._dz);
delete transformation;
}
image->Write(output_name);
delete image;
delete reader;
return 0;
}
<|endoftext|>
|
<commit_before>#include "stunmsgfact.h"
#include <QDateTime>
StunMessageFactory::StunMessageFactory()
{
qsrand(QDateTime::currentSecsSinceEpoch() / 2 + 1);
}
StunMessageFactory::~StunMessageFactory()
{
}
STUNMessage StunMessageFactory::createRequest()
{
STUNMessage request(STUN_REQUEST);
request.setTransactionID();
return request;
}
STUNMessage StunMessageFactory::createResponse()
{
STUNMessage response(STUN_RESPONSE);
return response;
}
STUNMessage StunMessageFactory::createResponse(STUNMessage& request)
{
STUNMessage response(STUN_RESPONSE);
response.setTransactionID(request.getTransactionID());
return response;
}
bool StunMessageFactory::verifyTransactionID(STUNMessage& message)
{
return false;
}
bool StunMessageFactory::validateStunMessage(STUNMessage& message, int type)
{
if (message.getCookie() != STUN_MAGIC_COOKIE)
{
return false;
}
if (message.getType() != type)
{
return false;
}
return true;
}
bool StunMessageFactory::validateStunRequest(STUNMessage& message)
{
return this->validateStunMessage(message, STUN_REQUEST);
}
bool StunMessageFactory::validateStunResponse(STUNMessage& response, QHostAddress sender, uint16_t port)
{
if (expectedResponses_.contains(sender.toString()))
{
if (expectedResponses_[sender.toString()].contains(port))
{
auto cached = expectedResponses_[sender.toString()][port];
for (int i = 0; i < TRANSACTION_ID_SIZE; ++i)
{
if (cached[i] != response.getTransactionIDAt(i))
{
return false;
}
}
return true;
}
else
{
qDebug() << "port not reported";
}
}
// expected response address:port was not saved for whatever reason
// check the received response agains the latest request
return this->validateStunResponse(response);
}
bool StunMessageFactory::validateStunResponse(STUNMessage& response)
{
if (this->validateStunMessage(response, STUN_RESPONSE))
{
uint8_t *responseTID = response.getTransactionID();
uint8_t *requestTID = latestRequest_.getTransactionID();
for (int i = 0; i < TRANSACTION_ID_SIZE; ++i)
{
if (responseTID[i] != requestTID[i])
{
return false;
}
}
return true;
}
return false;
}
void StunMessageFactory::expectReplyFrom(STUNMessage& request, QString address, uint16_t port)
{
if (expectedResponses_.contains(address))
{
if (expectedResponses_[address].contains(port))
{
qDebug() << "Purging old entry for " << address << ":" << port;
expectedResponses_[address][port].clear();
}
}
for (int i = 0; i < TRANSACTION_ID_SIZE; ++i)
{
expectedResponses_[address][port].push_back(request.getTransactionIDAt(i));
}
}
void StunMessageFactory::cacheRequest(STUNMessage request)
{
latestRequest_ = request;
}
QByteArray StunMessageFactory::hostToNetwork(STUNMessage& message)
{
auto attrs = message.getAttributes();
const size_t MSG_SIZE = sizeof(STUNRawMessage) + message.getLength();
auto ptr = std::unique_ptr<unsigned char[]>{ new unsigned char[MSG_SIZE] };
STUNRawMessage *rawMessage = static_cast<STUNRawMessage *>(static_cast<void *>(ptr.get()));
rawMessage->type = qToBigEndian((short)message.getType());
rawMessage->length = qToBigEndian(message.getLength());
rawMessage->magicCookie = qToBigEndian(message.getCookie());
for (int i = 0; i < TRANSACTION_ID_SIZE; ++i)
{
rawMessage->transactionID[i] = qToBigEndian(message.getTransactionIDAt(i));
}
uint16_t *attrPtr = (uint16_t *)rawMessage->payload;
for (size_t i = 0, k = 0; i < attrs.size(); ++i, k += 2)
{
attrPtr[k + 0] = qToBigEndian(std::get<0>(attrs[i]));
attrPtr[k + 1] = qToBigEndian(std::get<1>(attrs[i]));
if (std::get<1>(attrs[i]) > 0)
{
((uint32_t *)attrPtr)[k + 1] = qToBigEndian(std::get<2>(attrs[i]));
k += 2;
}
}
return QByteArray(static_cast<const char *>(static_cast<void *>(ptr.get())), MSG_SIZE);
}
STUNMessage StunMessageFactory::networkToHost(QByteArray& message)
{
char *raw_data = message.data();
STUNMessage response(STUN_RESPONSE);
response.setType(qFromBigEndian(*((uint16_t *)&raw_data[0])));
response.setLength(qFromBigEndian(*((uint16_t *)&raw_data[2])));
response.setCookie(qFromBigEndian(*((uint32_t *)&raw_data[4])));
for (int i = 0; i < TRANSACTION_ID_SIZE; ++i)
{
response.getTransactionID()[i] = (uint8_t)raw_data[8 + i];
}
uint32_t *payload = (uint32_t *)((uint8_t *)raw_data + 8 + TRANSACTION_ID_SIZE);
for (size_t i = 0; i < response.getLength(); i += 4)
{
uint32_t value = qFromBigEndian(payload[i / 4]);
uint16_t attrName = (value >> 16) & 0xffff;
uint16_t attrLen = (value >> 0) & 0xffff;
switch (attrName)
{
case STUN_ATTR_XOR_MAPPED_ADDRESS:
{
auto xorMappedAddr = extractXorMappedAddress(attrLen, (uint8_t *)payload + 4);
if (xorMappedAddr.second != 0)
{
response.setXorMappedAddress(xorMappedAddr.first, xorMappedAddr.second);
}
}
break;
case STUN_ATTR_ICE_CONTROLLED:
response.addAttribute(STUN_ATTR_ICE_CONTROLLED);
break;
case STUN_ATTR_ICE_CONTROLLING:
response.addAttribute(STUN_ATTR_ICE_CONTROLLING);
break;
case STUN_ATTR_PRIORITY:
{
i += 4;
uint32_t priority = qFromBigEndian(payload[i / 4]);
response.addAttribute(STUN_ATTR_PRIORITY, priority);
}
break;
case STUN_ATTR_USE_CANDIATE:
response.addAttribute(STUN_ATTR_USE_CANDIATE);
break;
default:
// TODO handle invalid message?
break;
}
i += attrLen;
}
return response;
}
std::pair<QHostAddress, uint16_t> StunMessageFactory::extractXorMappedAddress(uint16_t payloadLen, uint8_t *payload)
{
if (payloadLen >= 8)
{
// first byte (payload[0]) ignored according to RFC 5389
if (payload[1] == 0x01) // IPv4
{
// RFC 5389 page 33
uint16_t port = qFromBigEndian(*(((uint16_t *)payload + 1))) ^ 0x2112;
uint32_t address = qFromBigEndian(*(((uint32_t *)payload + 1))) ^ STUN_MAGIC_COOKIE;
return std::make_pair(QHostAddress(address), port);
}
}
return std::make_pair(QHostAddress(""), 0);
}
<commit_msg>Use the cached requests's TransactionID for "orphan" responses<commit_after>#include "stunmsgfact.h"
#include <QDateTime>
StunMessageFactory::StunMessageFactory()
{
qsrand(QDateTime::currentSecsSinceEpoch() / 2 + 1);
}
StunMessageFactory::~StunMessageFactory()
{
}
STUNMessage StunMessageFactory::createRequest()
{
STUNMessage request(STUN_REQUEST);
request.setTransactionID();
return request;
}
STUNMessage StunMessageFactory::createResponse()
{
STUNMessage response(STUN_RESPONSE);
response.setTransactionID(latestRequest_.getTransactionID());
return response;
}
STUNMessage StunMessageFactory::createResponse(STUNMessage& request)
{
STUNMessage response(STUN_RESPONSE);
response.setTransactionID(request.getTransactionID());
return response;
}
bool StunMessageFactory::verifyTransactionID(STUNMessage& message)
{
return false;
}
bool StunMessageFactory::validateStunMessage(STUNMessage& message, int type)
{
if (message.getCookie() != STUN_MAGIC_COOKIE)
{
return false;
}
if (message.getType() != type)
{
return false;
}
return true;
}
bool StunMessageFactory::validateStunRequest(STUNMessage& message)
{
return this->validateStunMessage(message, STUN_REQUEST);
}
bool StunMessageFactory::validateStunResponse(STUNMessage& response, QHostAddress sender, uint16_t port)
{
if (expectedResponses_.contains(sender.toString()))
{
if (expectedResponses_[sender.toString()].contains(port))
{
auto cached = expectedResponses_[sender.toString()][port];
for (int i = 0; i < TRANSACTION_ID_SIZE; ++i)
{
if (cached[i] != response.getTransactionIDAt(i))
{
return false;
}
}
return true;
}
else
{
qDebug() << "port not reported";
}
}
// expected response address:port was not saved for whatever reason
// check the received response agains the latest request
return this->validateStunResponse(response);
}
bool StunMessageFactory::validateStunResponse(STUNMessage& response)
{
if (this->validateStunMessage(response, STUN_RESPONSE))
{
uint8_t *responseTID = response.getTransactionID();
uint8_t *requestTID = latestRequest_.getTransactionID();
for (int i = 0; i < TRANSACTION_ID_SIZE; ++i)
{
if (responseTID[i] != requestTID[i])
{
return false;
}
}
return true;
}
return false;
}
void StunMessageFactory::expectReplyFrom(STUNMessage& request, QString address, uint16_t port)
{
if (expectedResponses_.contains(address))
{
if (expectedResponses_[address].contains(port))
{
qDebug() << "Purging old entry for " << address << ":" << port;
expectedResponses_[address][port].clear();
}
}
for (int i = 0; i < TRANSACTION_ID_SIZE; ++i)
{
expectedResponses_[address][port].push_back(request.getTransactionIDAt(i));
}
}
void StunMessageFactory::cacheRequest(STUNMessage request)
{
latestRequest_ = request;
}
QByteArray StunMessageFactory::hostToNetwork(STUNMessage& message)
{
auto attrs = message.getAttributes();
const size_t MSG_SIZE = sizeof(STUNRawMessage) + message.getLength();
auto ptr = std::unique_ptr<unsigned char[]>{ new unsigned char[MSG_SIZE] };
STUNRawMessage *rawMessage = static_cast<STUNRawMessage *>(static_cast<void *>(ptr.get()));
rawMessage->type = qToBigEndian((short)message.getType());
rawMessage->length = qToBigEndian(message.getLength());
rawMessage->magicCookie = qToBigEndian(message.getCookie());
for (int i = 0; i < TRANSACTION_ID_SIZE; ++i)
{
rawMessage->transactionID[i] = qToBigEndian(message.getTransactionIDAt(i));
}
uint16_t *attrPtr = (uint16_t *)rawMessage->payload;
for (size_t i = 0, k = 0; i < attrs.size(); ++i, k += 2)
{
attrPtr[k + 0] = qToBigEndian(std::get<0>(attrs[i]));
attrPtr[k + 1] = qToBigEndian(std::get<1>(attrs[i]));
if (std::get<1>(attrs[i]) > 0)
{
((uint32_t *)attrPtr)[k + 1] = qToBigEndian(std::get<2>(attrs[i]));
k += 2;
}
}
return QByteArray(static_cast<const char *>(static_cast<void *>(ptr.get())), MSG_SIZE);
}
STUNMessage StunMessageFactory::networkToHost(QByteArray& message)
{
char *raw_data = message.data();
STUNMessage response(STUN_RESPONSE);
response.setType(qFromBigEndian(*((uint16_t *)&raw_data[0])));
response.setLength(qFromBigEndian(*((uint16_t *)&raw_data[2])));
response.setCookie(qFromBigEndian(*((uint32_t *)&raw_data[4])));
for (int i = 0; i < TRANSACTION_ID_SIZE; ++i)
{
response.getTransactionID()[i] = (uint8_t)raw_data[8 + i];
}
uint32_t *payload = (uint32_t *)((uint8_t *)raw_data + 8 + TRANSACTION_ID_SIZE);
for (size_t i = 0; i < response.getLength(); i += 4)
{
uint32_t value = qFromBigEndian(payload[i / 4]);
uint16_t attrName = (value >> 16) & 0xffff;
uint16_t attrLen = (value >> 0) & 0xffff;
switch (attrName)
{
case STUN_ATTR_XOR_MAPPED_ADDRESS:
{
auto xorMappedAddr = extractXorMappedAddress(attrLen, (uint8_t *)payload + 4);
if (xorMappedAddr.second != 0)
{
response.setXorMappedAddress(xorMappedAddr.first, xorMappedAddr.second);
}
}
break;
case STUN_ATTR_ICE_CONTROLLED:
response.addAttribute(STUN_ATTR_ICE_CONTROLLED);
break;
case STUN_ATTR_ICE_CONTROLLING:
response.addAttribute(STUN_ATTR_ICE_CONTROLLING);
break;
case STUN_ATTR_PRIORITY:
{
i += 4;
uint32_t priority = qFromBigEndian(payload[i / 4]);
response.addAttribute(STUN_ATTR_PRIORITY, priority);
}
break;
case STUN_ATTR_USE_CANDIATE:
response.addAttribute(STUN_ATTR_USE_CANDIATE);
break;
default:
// TODO handle invalid message?
break;
}
i += attrLen;
}
return response;
}
std::pair<QHostAddress, uint16_t> StunMessageFactory::extractXorMappedAddress(uint16_t payloadLen, uint8_t *payload)
{
if (payloadLen >= 8)
{
// first byte (payload[0]) ignored according to RFC 5389
if (payload[1] == 0x01) // IPv4
{
// RFC 5389 page 33
uint16_t port = qFromBigEndian(*(((uint16_t *)payload + 1))) ^ 0x2112;
uint32_t address = qFromBigEndian(*(((uint32_t *)payload + 1))) ^ STUN_MAGIC_COOKIE;
return std::make_pair(QHostAddress(address), port);
}
}
return std::make_pair(QHostAddress(""), 0);
}
<|endoftext|>
|
<commit_before>#include "wrapper.h"
extern "C"
{
EWXWEXPORT(void*, wxValidator_Create)()
{
return (void*) new wxValidator();
}
EWXWEXPORT(void, wxValidator_Delete)(void* _obj)
{
delete (wxValidator*)_obj;
}
EWXWEXPORT(int, wxValidator_Validate)(void* _obj, void* parent)
{
return (int)((wxValidator*)_obj)->Validate((wxWindow*)parent);
}
EWXWEXPORT(int, wxValidator_TransferToWindow)(void* _obj)
{
return (int)((wxValidator*)_obj)->TransferToWindow();
}
EWXWEXPORT(int, wxValidator_TransferFromWindow)(void* _obj)
{
return (int)((wxValidator*)_obj)->TransferFromWindow();
}
EWXWEXPORT(void*, wxValidator_GetWindow)(void* _obj)
{
return (void*)((wxValidator*)_obj)->GetWindow();
}
EWXWEXPORT(void, wxValidator_SetWindow)(void* _obj, void* win)
{
((wxValidator*)_obj)->SetWindow((wxWindowBase*)win);
}
#if (wxVERSION_NUMBER < 2800)
EWXWEXPORT(int, wxValidator_IsSilent)()
{
return (int)wxValidator::IsSilent();
}
#endif
EWXWEXPORT(void, wxValidator_SetBellOnError)(int doIt)
{
wxValidator::SetBellOnError(doIt != 0);
}
EWXWEXPORT(void*, wxTextValidator_Create)(int style, void* val)
{
return (void*) new wxTextValidator((long)style, new wxString);
}
EWXWEXPORT(int, wxTextValidator_GetStyle)(void* _obj)
{
return (int)((wxTextValidator*)_obj)->GetStyle();
}
EWXWEXPORT(void, wxTextValidator_SetStyle)(void* _obj, int style)
{
((wxTextValidator*)_obj)->SetStyle((long) style);
}
#if (wxVERSION_NUMBER < 2800)
EWXWEXPORT(void, wxTextValidator_SetIncludeList)(void* _obj, void* list, int count)
{
#if (wxVERSION_NUMBER <= 2600)
wxStringList str;
for (int i = 0; i < count; i++)
str.Add(((wxChar**)list)[i]);
((wxTextValidator*)_obj)->SetIncludeList(str);
#else
((wxTextValidator*)_obj)->SetIncludes((const wxArrayString&)list);
#endif
}
EWXWEXPORT(int, wxTextValidator_GetIncludeList)(void* _obj, void* _ref)
{
#if (wxVERSION_NUMBER <= 2600)
if (_ref)
{
for (unsigned int i = 0; i < ((wxTextValidator*)_obj)->GetIncludeList().GetCount(); i++)
((const wxChar**)_ref)[i] = wxStrdup(((wxTextValidator*)_obj)->GetIncludeList().Item(i)->GetData());
}
return ((wxTextValidator*)_obj)->GetIncludeList().GetCount();
#else
wxArrayString arr = ((wxTextValidator*)_obj)->GetIncludes();
if (_ref)
{
for (unsigned int i = 0; i < arr.GetCount(); i++)
((const wxChar**)_ref)[i] = wxStrdup (arr.Item(i).c_str());
}
return arr.GetCount();
#endif
}
EWXWEXPORT(void, wxTextValidator_SetExcludeList)(void* _obj, void* list, int count)
{
#if (wxVERSION_NUMBER <= 2600)
wxStringList str;
for (int i = 0; i < count; i++)
str.Add(((wxChar**)list)[i]);
((wxTextValidator*)_obj)->SetExcludeList(str);
#else
((wxTextValidator*)_obj)->SetExcludes((const wxArrayString&)list);
#endif
}
EWXWEXPORT(int, wxTextValidator_GetExcludeList)(void* _obj, void* _ref)
{
#if (wxVERSION_NUMBER <= 2600)
if (_ref)
{
for (unsigned int i = 0; i < ((wxTextValidator*)_obj)->GetExcludeList().GetCount(); i++)
((const wxChar**)_ref)[i] = ((wxTextValidator*)_obj)->GetExcludeList().Item(i)->GetData();
}
return ((wxTextValidator*)_obj)->GetExcludeList().GetCount();
#else
wxArrayString arr = ((wxTextValidator*)_obj)->GetExcludes();
if (_ref)
{
for (unsigned int i = 0; i < arr.GetCount(); i++)
((const wxChar**)_ref)[i] = wxStrdup (arr.Item(i).c_str());
}
return arr.GetCount();
#endif
}
#else
EWXWEXPORT(void, wxTextValidator_SetIncludes)(void* _obj, void* list, int count)
{
wxArrayString str;
for (int i = 0; i < count; i++)
str.Add(((wxChar**)list)[i]);
((wxTextValidator*)_obj)->SetIncludes(str);
}
EWXWEXPORT(void *, wxTextValidator_GetIncludes)(void* _obj, int *_nitems)
{
void *retval = NULL;
if (_nitems != NULL)
{
wxArrayString items = ((wxTextValidator*)_obj)->GetIncludes();
wxChar **items_copy = (wxChar **) malloc(sizeof(wxChar *) * items.GetCount());
for (unsigned int i = 0; i < items.GetCount(); i++)
{
#ifdef wxUSE_UNICODE
items_copy[i] = wxStrdup(items.Item(i).GetData());
#else
items_copy[i] = strdup(items.Item(i).GetData());
#endif
}
retval = (void *) items_copy;
*_nitems = items.GetCount();
}
return retval;
}
EWXWEXPORT(void, wxTextValidator_SetExcludes)(void* _obj, void* list, int count)
{
wxArrayString str;
for (int i = 0; i < count; i++)
str.Add(((wxChar**)list)[i]);
((wxTextValidator*)_obj)->SetExcludes(str);
}
EWXWEXPORT(void *, wxTextValidator_GetExcludes)(void* _obj, int* _nitems)
{
void *retval = NULL;
if (_nitems != NULL)
{
wxArrayString items = ((wxTextValidator*)_obj)->GetExcludes();
wxChar **items_copy = (wxChar **) malloc(sizeof(wxChar *) * items.GetCount());
for (unsigned int i = 0; i < items.GetCount(); i++)
{
#ifdef wxUSE_UNICODE
items_copy[i] = wxStrdup(items.Item(i).GetData());
#else
items_copy[i] = strdup(items.Item(i).GetData());
#endif
}
retval = (void *) items_copy;
*_nitems = items.GetCount();
}
return retval;
}
EWXWEXPORT(void *, wxTextValidator_Clone)(void *_obj)
{
return (void *)((wxTextValidator*)_obj)->Clone();
}
EWXWEXPORT(int, wxTextValidator_TransferToWindow)(void* _obj)
{
return (int)((wxTextValidator*)_obj)->TransferToWindow();
}
EWXWEXPORT(int, wxTextValidator_TransferFromWindow)(void* _obj)
{
return (int)((wxTextValidator*)_obj)->TransferFromWindow();
}
#endif
EWXWEXPORT(void, wxTextValidator_OnChar)(void* _obj, void* event)
{
((wxTextValidator*)_obj)->OnChar(*((wxKeyEvent*)event));
}
EWXWEXPORT(void*, ELJTextValidator_Create) (void* _obj, void* _fnc, void* _txt, long _stl)
{
return new ELJTextValidator(_obj, _fnc, _txt, _stl);
}
}
bool ELJTextValidator::Validate(wxWindow* _prt)
{
if (obj && fnc)
return fnc(obj) != 0;
else
return wxTextValidator::Validate(_prt);
}
<commit_msg>Clean up #ifdef wxUSE_UNICODE flag by wxStrdup function.<commit_after>#include "wrapper.h"
extern "C"
{
EWXWEXPORT(void*, wxValidator_Create)()
{
return (void*) new wxValidator();
}
EWXWEXPORT(void, wxValidator_Delete)(void* _obj)
{
delete (wxValidator*)_obj;
}
EWXWEXPORT(int, wxValidator_Validate)(void* _obj, void* parent)
{
return (int)((wxValidator*)_obj)->Validate((wxWindow*)parent);
}
EWXWEXPORT(int, wxValidator_TransferToWindow)(void* _obj)
{
return (int)((wxValidator*)_obj)->TransferToWindow();
}
EWXWEXPORT(int, wxValidator_TransferFromWindow)(void* _obj)
{
return (int)((wxValidator*)_obj)->TransferFromWindow();
}
EWXWEXPORT(void*, wxValidator_GetWindow)(void* _obj)
{
return (void*)((wxValidator*)_obj)->GetWindow();
}
EWXWEXPORT(void, wxValidator_SetWindow)(void* _obj, void* win)
{
((wxValidator*)_obj)->SetWindow((wxWindowBase*)win);
}
#if (wxVERSION_NUMBER < 2800)
EWXWEXPORT(int, wxValidator_IsSilent)()
{
return (int)wxValidator::IsSilent();
}
#endif
EWXWEXPORT(void, wxValidator_SetBellOnError)(int doIt)
{
wxValidator::SetBellOnError(doIt != 0);
}
EWXWEXPORT(void*, wxTextValidator_Create)(int style, void* val)
{
return (void*) new wxTextValidator((long)style, new wxString);
}
EWXWEXPORT(int, wxTextValidator_GetStyle)(void* _obj)
{
return (int)((wxTextValidator*)_obj)->GetStyle();
}
EWXWEXPORT(void, wxTextValidator_SetStyle)(void* _obj, int style)
{
((wxTextValidator*)_obj)->SetStyle((long) style);
}
#if (wxVERSION_NUMBER < 2800)
EWXWEXPORT(void, wxTextValidator_SetIncludeList)(void* _obj, void* list, int count)
{
#if (wxVERSION_NUMBER <= 2600)
wxStringList str;
for (int i = 0; i < count; i++)
str.Add(((wxChar**)list)[i]);
((wxTextValidator*)_obj)->SetIncludeList(str);
#else
((wxTextValidator*)_obj)->SetIncludes((const wxArrayString&)list);
#endif
}
EWXWEXPORT(int, wxTextValidator_GetIncludeList)(void* _obj, void* _ref)
{
#if (wxVERSION_NUMBER <= 2600)
if (_ref)
{
for (unsigned int i = 0; i < ((wxTextValidator*)_obj)->GetIncludeList().GetCount(); i++)
((const wxChar**)_ref)[i] = wxStrdup(((wxTextValidator*)_obj)->GetIncludeList().Item(i)->GetData());
}
return ((wxTextValidator*)_obj)->GetIncludeList().GetCount();
#else
wxArrayString arr = ((wxTextValidator*)_obj)->GetIncludes();
if (_ref)
{
for (unsigned int i = 0; i < arr.GetCount(); i++)
((const wxChar**)_ref)[i] = wxStrdup (arr.Item(i).c_str());
}
return arr.GetCount();
#endif
}
EWXWEXPORT(void, wxTextValidator_SetExcludeList)(void* _obj, void* list, int count)
{
#if (wxVERSION_NUMBER <= 2600)
wxStringList str;
for (int i = 0; i < count; i++)
str.Add(((wxChar**)list)[i]);
((wxTextValidator*)_obj)->SetExcludeList(str);
#else
((wxTextValidator*)_obj)->SetExcludes((const wxArrayString&)list);
#endif
}
EWXWEXPORT(int, wxTextValidator_GetExcludeList)(void* _obj, void* _ref)
{
#if (wxVERSION_NUMBER <= 2600)
if (_ref)
{
for (unsigned int i = 0; i < ((wxTextValidator*)_obj)->GetExcludeList().GetCount(); i++)
((const wxChar**)_ref)[i] = ((wxTextValidator*)_obj)->GetExcludeList().Item(i)->GetData();
}
return ((wxTextValidator*)_obj)->GetExcludeList().GetCount();
#else
wxArrayString arr = ((wxTextValidator*)_obj)->GetExcludes();
if (_ref)
{
for (unsigned int i = 0; i < arr.GetCount(); i++)
((const wxChar**)_ref)[i] = wxStrdup (arr.Item(i).c_str());
}
return arr.GetCount();
#endif
}
#else
EWXWEXPORT(void, wxTextValidator_SetIncludes)(void* _obj, void* list, int count)
{
wxArrayString str;
for (int i = 0; i < count; i++)
str.Add(((wxChar**)list)[i]);
((wxTextValidator*)_obj)->SetIncludes(str);
}
EWXWEXPORT(void *, wxTextValidator_GetIncludes)(void* _obj, int *_nitems)
{
void *retval = NULL;
if (_nitems != NULL)
{
wxArrayString items = ((wxTextValidator*)_obj)->GetIncludes();
wxChar **items_copy = (wxChar **) malloc(sizeof(wxChar *) * items.GetCount());
for (unsigned int i = 0; i < items.GetCount(); i++)
{
items_copy[i] = wxStrdup(items.Item(i).GetData());
}
retval = (void *) items_copy;
*_nitems = items.GetCount();
}
return retval;
}
EWXWEXPORT(void, wxTextValidator_SetExcludes)(void* _obj, void* list, int count)
{
wxArrayString str;
for (int i = 0; i < count; i++)
str.Add(((wxChar**)list)[i]);
((wxTextValidator*)_obj)->SetExcludes(str);
}
EWXWEXPORT(void *, wxTextValidator_GetExcludes)(void* _obj, int* _nitems)
{
void *retval = NULL;
if (_nitems != NULL)
{
wxArrayString items = ((wxTextValidator*)_obj)->GetExcludes();
wxChar **items_copy = (wxChar **) malloc(sizeof(wxChar *) * items.GetCount());
for (unsigned int i = 0; i < items.GetCount(); i++)
{
items_copy[i] = wxStrdup(items.Item(i).GetData());
}
retval = (void *) items_copy;
*_nitems = items.GetCount();
}
return retval;
}
EWXWEXPORT(void *, wxTextValidator_Clone)(void *_obj)
{
return (void *)((wxTextValidator*)_obj)->Clone();
}
EWXWEXPORT(int, wxTextValidator_TransferToWindow)(void* _obj)
{
return (int)((wxTextValidator*)_obj)->TransferToWindow();
}
EWXWEXPORT(int, wxTextValidator_TransferFromWindow)(void* _obj)
{
return (int)((wxTextValidator*)_obj)->TransferFromWindow();
}
#endif
EWXWEXPORT(void, wxTextValidator_OnChar)(void* _obj, void* event)
{
((wxTextValidator*)_obj)->OnChar(*((wxKeyEvent*)event));
}
EWXWEXPORT(void*, ELJTextValidator_Create) (void* _obj, void* _fnc, void* _txt, long _stl)
{
return new ELJTextValidator(_obj, _fnc, _txt, _stl);
}
}
bool ELJTextValidator::Validate(wxWindow* _prt)
{
if (obj && fnc)
return fnc(obj) != 0;
else
return wxTextValidator::Validate(_prt);
}
<|endoftext|>
|
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ZIPPYLOG_ENVELOPE_HPP_
#define ZIPPYLOG_ENVELOPE_HPP_
#include <zippylog/zippylog.hpp>
#include <zippylog/message.pb.h>
#include <google/protobuf/message.h>
#include <zmq.hpp>
#include <string>
// windows.h defines GetMessage() as a macro, which craps on us.
// here, we shovel shit
#if defined(WINDOWS) && defined(GetMessage)
inline BOOL GetMessage_Windows(LPMSG msg, HWND hwnd, UINT min, UINT max) {
return GetMessage(msg, hwnd, min, max);
}
#undef GetMessage
inline BOOL GetMessage(LPMSG msg, HWND hwnd, UINT min, UINT max) {
return GetMessage_Windows(msg, hwnd, min, max);
}
#endif
namespace zippylog {
class ZIPPYLOG_EXPORT Envelope {
public:
/// construct an empty envelope
Envelope();
/// Construct from serialized binary data
Envelope(const void *data, int size);
/// construct an envelope having string data
///
/// This populates the string_value field of the envelope. It does
/// not build an envelope from the serialized protocol buffer data
/// stored in the passed string
Envelope(const ::std::string &s);
~Envelope();
Envelope & operator=(const Envelope &orig);
Envelope(const Envelope &e);
// adds a protobuf messsage to the payload.
//
// message is effectively copied to the envelope. any modifications
// after adding will not be reflected. passed message can be
// deleted as soon as function returns.
//
// We require namespace and enumeration now. If we can get around
// inefficient castings, we'll likely create a new overload
bool AddMessage(::google::protobuf::Message &m, uint32 ns, uint32 enumeration);
message::Envelope envelope;
// serializes the envelope into a 0MQ message
// existing message content will be overwritten
bool ToZmqMessage(::zmq::message_t &msg);
int MessageCount();
inline uint32 MessageNamespace(int index)
{
return this->envelope.message_namespace(index);
}
inline uint32 MessageType(int index)
{
return this->envelope.message_type(index);
}
// obtain the protocol buffer message at given index
// the returned pointer is owned by the envelope instance
// the memory won't be accessible once the envelope is destroyed
// therefore, the caller should NOT free it
// if the index does not exist, NULL will be returned
::google::protobuf::Message * GetMessage(int index);
// copy a message to another envelope
bool CopyMessage(int index, Envelope &dest);
::std::string ToString();
protected:
// holds pointer to dynamic array
::google::protobuf::Message ** messages;
int message_count;
};
} // namespace
#endif<commit_msg>declare a constructor that takes a 0MQ message<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ZIPPYLOG_ENVELOPE_HPP_
#define ZIPPYLOG_ENVELOPE_HPP_
#include <zippylog/zippylog.hpp>
#include <zippylog/message.pb.h>
#include <google/protobuf/message.h>
#include <zmq.hpp>
#include <string>
// windows.h defines GetMessage() as a macro, which craps on us.
// here, we shovel shit
#if defined(WINDOWS) && defined(GetMessage)
inline BOOL GetMessage_Windows(LPMSG msg, HWND hwnd, UINT min, UINT max) {
return GetMessage(msg, hwnd, min, max);
}
#undef GetMessage
inline BOOL GetMessage(LPMSG msg, HWND hwnd, UINT min, UINT max) {
return GetMessage_Windows(msg, hwnd, min, max);
}
#endif
namespace zippylog {
class ZIPPYLOG_EXPORT Envelope {
public:
/// Construct an empty envelope
Envelope();
/// Construct from serialized binary data
Envelope(const void *data, int size);
/// Construct an envelope from a 0MQ message
///
/// This function assumes the ENTIRE content of the 0MQ message is
/// the serialized envelope. Note that for a zippylog protocol 0MQ
/// message (where the first byte is a version byte), this is NOT
/// the case. So, if you attempt to construct an envelope from one
/// of these messages, it will likely fail.
Envelope(::zmq::message_t &m);
/// Construct an envelope having string data
///
/// This populates the string_value field of the envelope. It does
/// not build an envelope from the serialized protocol buffer data
/// stored in the passed string
Envelope(const ::std::string &s);
~Envelope();
Envelope & operator=(const Envelope &orig);
Envelope(const Envelope &e);
// adds a protobuf messsage to the payload.
//
// message is effectively copied to the envelope. any modifications
// after adding will not be reflected. passed message can be
// deleted as soon as function returns.
//
// We require namespace and enumeration now. If we can get around
// inefficient castings, we'll likely create a new overload
bool AddMessage(::google::protobuf::Message &m, uint32 ns, uint32 enumeration);
message::Envelope envelope;
// serializes the envelope into a 0MQ message
// existing message content will be overwritten
bool ToZmqMessage(::zmq::message_t &msg);
int MessageCount();
inline uint32 MessageNamespace(int index)
{
return this->envelope.message_namespace(index);
}
inline uint32 MessageType(int index)
{
return this->envelope.message_type(index);
}
// obtain the protocol buffer message at given index
// the returned pointer is owned by the envelope instance
// the memory won't be accessible once the envelope is destroyed
// therefore, the caller should NOT free it
// if the index does not exist, NULL will be returned
::google::protobuf::Message * GetMessage(int index);
// copy a message to another envelope
bool CopyMessage(int index, Envelope &dest);
::std::string ToString();
protected:
// holds pointer to dynamic array
::google::protobuf::Message ** messages;
int message_count;
};
} // namespace
#endif<|endoftext|>
|
<commit_before>#pragma once
#include <cstdlib>
template <typename T>
void InsertionSortAsc(T* array, size_t count)
{
for (size_t i = 2; i < count; ++i)
{
for (size_t k = i; k > 1 && array[k] < array[k - 1]; --k)
{
T temporary = array[k];
array[k] = array[k - 1];
array[k - 1] = temporary;
}
}
}
template <typename T>
void InsertionSortDesc(T* array, size_t count)
{
for (size_t i = 2; i < count; ++i)
{
for (size_t k = i; k > 1 && array[k] > array[k - 1]; --k)
{
T temporary = array[k];
array[k] = array[k - 1];
array[k - 1] = temporary;
}
}
}
template <typename T>
void InsertionSortPred(T* array, size_t count, bool(*pred)(const T&, const T&))
{
for (size_t i = 2; i < count; ++i)
{
for (size_t k = i; k > 1 && pred(array[k], array[k - 1]); --k)
{
T temporary = array[k];
array[k] = array[k - 1];
array[k - 1] = temporary;
}
}
}
template <typename T>
void ShellSortPred(T* array, size_t count, bool(*pred)(const T&, const T&))
{
// Sort an array a[0...n-1].
size_t gaps[] = { 701, 301, 132, 57, 23, 10, 4, 1 };
// Start with the largest gap and work down to a gap of 1
for (size_t gap : gaps)
{
// Do a gapped insertion sort for this gap size.
// The first gap elements array[0..gap-1] are already in gapped order
// keep adding one more element until the entire array is gap sorted
for (size_t i = gap; i < count; ++i)
{
// add array[i] to the elements that have been gap sorted
// save array[i] in temp and make a hole at position i
T temporary = array[i];
size_t j = i;
// shift earlier gap-sorted elements up until the correct location for array[i] is found
while (j >= gap && pred(array[j - gap], temporary) == false)
{
array[j] = array[j - gap];
j -= gap;
}
// put temp (the original array[i]) in its correct location
array[j] = temporary;
}
}
}
template <typename T>
void ShellSortAsc(T* array, size_t count)
{
// Sort an array a[0...n-1].
size_t gaps[] = { 701, 301, 132, 57, 23, 10, 4, 1 };
// Start with the largest gap and work down to a gap of 1
for (size_t gap : gaps)
{
// Do a gapped insertion sort for this gap size.
// The first gap elements array[0..gap-1] are already in gapped order
// keep adding one more element until the entire array is gap sorted
for (size_t i = gap; i < count; ++i)
{
// add array[i] to the elements that have been gap sorted
// save array[i] in temp and make a hole at position i
T temporary = array[i];
size_t j = i;
// shift earlier gap-sorted elements up until the correct location for array[i] is found
while (j >= gap && (array[j - gap] < temporary) == false)
{
array[j] = array[j - gap];
j -= gap;
}
// put temp (the original array[i]) in its correct location
array[j] = temporary;
}
}
}
template <typename T>
void ShellSortDesc(T* array, size_t count)
{
// Sort an array a[0...n-1].
size_t gaps[] = { 701, 301, 132, 57, 23, 10, 4, 1 };
// Start with the largest gap and work down to a gap of 1
for (size_t gap : gaps)
{
// Do a gapped insertion sort for this gap size.
// The first gap elements array[0..gap-1] are already in gapped order
// keep adding one more element until the entire array is gap sorted
for (size_t i = gap; i < count; ++i)
{
// add array[i] to the elements that have been gap sorted
// save array[i] in temp and make a hole at position i
T temporary = array[i];
size_t j = i;
// shift earlier gap-sorted elements up until the correct location for array[i] is found
while (j >= gap && (array[j - gap] < temporary) == true)
{
array[j] = array[j - gap];
j -= gap;
}
// put temp (the original array[i]) in its correct location
array[j] = temporary;
}
}
}
<commit_msg>Fix embarrassing mistake in insertion sort algorithm<commit_after>#pragma once
#include <cstdlib>
template <typename T>
void InsertionSortAsc(T* array, size_t count)
{
for (size_t i = 1; i < count; ++i)
{
for (size_t k = i; k > 1 && array[k] < array[k - 1]; --k)
{
T temporary = array[k];
array[k] = array[k - 1];
array[k - 1] = temporary;
}
}
}
template <typename T>
void InsertionSortDesc(T* array, size_t count)
{
for (size_t i = 1; i < count; ++i)
{
for (size_t k = i; k > 1 && array[k] > array[k - 1]; --k)
{
T temporary = array[k];
array[k] = array[k - 1];
array[k - 1] = temporary;
}
}
}
template <typename T>
void InsertionSortPred(T* array, size_t count, bool(*pred)(const T&, const T&))
{
for (size_t i = 1; i < count; ++i)
{
for (size_t k = i; k > 1 && pred(array[k], array[k - 1]); --k)
{
T temporary = array[k];
array[k] = array[k - 1];
array[k - 1] = temporary;
}
}
}
template <typename T>
void ShellSortPred(T* array, size_t count, bool(*pred)(const T&, const T&))
{
// Sort an array a[0...n-1].
size_t gaps[] = { 701, 301, 132, 57, 23, 10, 4, 1 };
// Start with the largest gap and work down to a gap of 1
for (size_t gap : gaps)
{
// Do a gapped insertion sort for this gap size.
// The first gap elements array[0..gap-1] are already in gapped order
// keep adding one more element until the entire array is gap sorted
for (size_t i = gap; i < count; ++i)
{
// add array[i] to the elements that have been gap sorted
// save array[i] in temp and make a hole at position i
T temporary = array[i];
size_t j = i;
// shift earlier gap-sorted elements up until the correct location for array[i] is found
while (j >= gap && pred(array[j - gap], temporary) == false)
{
array[j] = array[j - gap];
j -= gap;
}
// put temp (the original array[i]) in its correct location
array[j] = temporary;
}
}
}
template <typename T>
void ShellSortAsc(T* array, size_t count)
{
// Sort an array a[0...n-1].
size_t gaps[] = { 701, 301, 132, 57, 23, 10, 4, 1 };
// Start with the largest gap and work down to a gap of 1
for (size_t gap : gaps)
{
// Do a gapped insertion sort for this gap size.
// The first gap elements array[0..gap-1] are already in gapped order
// keep adding one more element until the entire array is gap sorted
for (size_t i = gap; i < count; ++i)
{
// add array[i] to the elements that have been gap sorted
// save array[i] in temp and make a hole at position i
T temporary = array[i];
size_t j = i;
// shift earlier gap-sorted elements up until the correct location for array[i] is found
while (j >= gap && (array[j - gap] < temporary) == false)
{
array[j] = array[j - gap];
j -= gap;
}
// put temp (the original array[i]) in its correct location
array[j] = temporary;
}
}
}
template <typename T>
void ShellSortDesc(T* array, size_t count)
{
// Sort an array a[0...n-1].
size_t gaps[] = { 701, 301, 132, 57, 23, 10, 4, 1 };
// Start with the largest gap and work down to a gap of 1
for (size_t gap : gaps)
{
// Do a gapped insertion sort for this gap size.
// The first gap elements array[0..gap-1] are already in gapped order
// keep adding one more element until the entire array is gap sorted
for (size_t i = gap; i < count; ++i)
{
// add array[i] to the elements that have been gap sorted
// save array[i] in temp and make a hole at position i
T temporary = array[i];
size_t j = i;
// shift earlier gap-sorted elements up until the correct location for array[i] is found
while (j >= gap && (array[j - gap] < temporary) == true)
{
array[j] = array[j - gap];
j -= gap;
}
// put temp (the original array[i]) in its correct location
array[j] = temporary;
}
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2014-15 Ableton AG, Berlin
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 "CssParser.hpp"
#include "Warnings.hpp"
SUPPRESS_WARNINGS
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/support_line_pos_iterator.hpp>
RESTORE_WARNINGS
#include <fstream>
#include <iostream>
#include <sstream>
namespace
{
/*! @throw std::ios_base::failure for IO errors or if the file at @path
* could not be opened. */
std::string loadFileIntoString(const std::string& path)
{
std::stringstream result;
std::ifstream in(path.c_str(), std::ios::in | std::ios::binary);
in.exceptions(std::ifstream::failbit);
result << in.rdbuf();
return result.str();
}
} // anon namespace
// this must be outside of the anon namespace
// clang-format off
BOOST_FUSION_ADAPT_STRUCT(
aqt::stylesheets::PropertySpec,
(std::string, name)
(aqt::stylesheets::PropertyValues, values)
)
BOOST_FUSION_ADAPT_STRUCT(
aqt::stylesheets::PropertySpecSet,
(std::vector<aqt::stylesheets::Selector>, selectors)
(std::vector<aqt::stylesheets::PropertySpec>, properties)
)
BOOST_FUSION_ADAPT_STRUCT(
aqt::stylesheets::FontFaceDecl,
(std::string, url)
)
BOOST_FUSION_ADAPT_STRUCT(
aqt::stylesheets::StyleSheet,
(std::vector<aqt::stylesheets::PropertySpecSet>, propsets)
(std::vector<aqt::stylesheets::FontFaceDecl>, fontfaces)
)
BOOST_FUSION_ADAPT_STRUCT(
aqt::stylesheets::Expression,
(std::string, name)
(std::vector<std::string>, args)
)
// clang-format on
namespace
{
namespace phoenix = boost::phoenix;
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
template <typename It>
class LocationAnnotator
{
const It mFirst;
public:
// to make phoenix::function happy
template <typename>
struct result {
using type = void;
};
LocationAnnotator(It first)
: mFirst(first)
{
}
template <typename ThingWithLocation>
void operator()(ThingWithLocation& thing, It iter) const
{
thing.mSourceLoc.mByteOfs = static_cast<int>(std::distance(mFirst, iter));
thing.mSourceLoc.mLine = static_cast<int>(get_line(iter));
// The column offset is always off by one. Why? It is a mystery.
thing.mSourceLoc.mColumn = static_cast<int>(get_column(mFirst, iter)) - 1;
}
};
template <typename Iterator>
struct StyleSheetGrammar
: qi::grammar<Iterator, aqt::stylesheets::StyleSheet(), ascii::space_type> {
StyleSheetGrammar(Iterator first)
: StyleSheetGrammar::base_type(stylesheet, "stylesheet")
, locationAnnotator(first)
{
using qi::lit;
using qi::lexeme;
using qi::omit;
using ascii::char_;
using ascii::string;
using namespace qi::labels;
using phoenix::at_c;
using phoenix::push_back;
using boost::spirit::eol;
// clang-format off
cpp_comment = "//" >> omit[*(char_ - eol) >> eol];
c_comment = "/*" >> omit[*(char_ - "*/")] >> "*/";
comment = cpp_comment | c_comment;
identifier = +(qi::alnum | char_('-'));
dot_identifier = char_(".") >> identifier;
child_sel = char_(">");
sel_separator = char_(",");
sel_part = +(dot_identifier | identifier)[push_back(_val, _1)];
child_sel_part = (child_sel)[push_back(_val, _1)];
selector = +(sel_part | child_sel_part)[push_back(_val, _1)];
quoted_string = lexeme['"' >> +(char_ - '"') >> '"']
| lexeme['\'' >> +(char_ - '\'') >> '\''];
color = char_('#') >> +(qi::xdigit);
number = +(qi::digit | char_('-') | char_('.')) >> *char_('%');
atom_value = quoted_string
| number
| color
| identifier;
args = atom_value [push_back(_val, _1)]
>> *(lit(',') > atom_value [push_back(_val, _1)]);
expression = identifier[at_c<0>(_val) = _1]
>> lit('(') >> *(args[at_c<1>(_val) = _1]) >> lit(')');
value = quoted_string
| number
| color
| expression
| identifier;
values = value [push_back(_val, _1)]
>> *(lit(',') > value [push_back(_val, _1)]);
value_pair = identifier[at_c<0>(_val) = _1]
>> lit(':') >> values[at_c<1>(_val) = _1]
>> -lit(';');
propset = selector [push_back(at_c<0>(_val), _1)]
>> *((sel_separator >> selector[push_back(at_c<0>(_val), _1)])
| comment)
>> '{'
>> *(value_pair [push_back(at_c<1>(_val), _1)]
| comment)
>> '}';
fontfacedecl = "@font-face" >> -comment
>> lit('{') >> -comment
>> lit("src") >> lit(':') >> -comment
>> lit("url") >> lit('(')
>> (identifier | quoted_string)[at_c<0>(_val) = _1]
>> lit(')') >> -lit(';') >> -comment
>> lit('}');
stylesheet = *(propset[push_back(at_c<0>(_val), _1)]
| fontfacedecl[push_back(at_c<1>(_val), _1)]
| comment);
// clang-format on
// give proper names to the rules for error printing
c_comment.name("comment");
color.name("color");
comment.name("comment");
cpp_comment.name("comment");
fontfacedecl.name("fontface");
identifier.name("identifier");
dot_identifier.name("dot_identifier");
propset.name("propset");
quoted_string.name("string");
stylesheet.name("stylesheet");
sel_separator.name("selector separator");
sel_part.name("selector part");
selector.name("selector");
values.name("value");
number.name("number");
atom_value.name("atomic value");
value.name("value");
value_pair.name("key-value-pair");
child_sel.name("child");
args.name("args");
expression.name("expression");
on_success(propset, locationAnnotator(_val, _1));
on_success(value_pair, locationAnnotator(_val, _1));
}
phoenix::function<LocationAnnotator<Iterator>> locationAnnotator;
qi::rule<Iterator, std::string()> identifier;
qi::rule<Iterator, std::string()> dot_identifier;
qi::rule<Iterator, std::string()> sel_separator;
qi::rule<Iterator, std::string()> child_sel;
qi::rule<Iterator, aqt::stylesheets::SelectorParts()> child_sel_part;
qi::rule<Iterator, aqt::stylesheets::SelectorParts()> sel_part;
qi::rule<Iterator, aqt::stylesheets::Selector(), ascii::space_type> selector;
qi::rule<Iterator, std::string()> color;
qi::rule<Iterator, std::string()> number;
qi::rule<Iterator, std::string(), ascii::space_type> quoted_string;
qi::rule<Iterator, aqt::stylesheets::PropertySpec(), ascii::space_type> value_pair;
qi::rule<Iterator, std::string(), ascii::space_type> atom_value;
qi::rule<Iterator, aqt::stylesheets::PropertyValue(), ascii::space_type> value;
qi::rule<Iterator, aqt::stylesheets::PropertyValues(), ascii::space_type> values;
qi::rule<Iterator, std::vector<std::string>(), ascii::space_type> args;
qi::rule<Iterator, aqt::stylesheets::PropertySpecSet(), ascii::space_type> propset;
qi::rule<Iterator, aqt::stylesheets::FontFaceDecl(), ascii::space_type> fontfacedecl;
qi::rule<Iterator, aqt::stylesheets::StyleSheet(), ascii::space_type> stylesheet;
qi::rule<Iterator, aqt::stylesheets::Expression(), ascii::space_type> expression;
qi::rule<Iterator, boost::spirit::unused_type> cpp_comment;
qi::rule<Iterator, boost::spirit::unused_type> c_comment;
qi::rule<Iterator, boost::spirit::unused_type> comment;
};
} // anon namespace
namespace aqt
{
namespace stylesheets
{
StyleSheet parseStdString(const std::string& data)
{
StyleSheet stylesheet;
using source_iterator = boost::spirit::line_pos_iterator<std::string::const_iterator>;
using StrStyleSheetGrammar = StyleSheetGrammar<source_iterator>;
auto iter = source_iterator{data.begin()};
auto end = source_iterator{data.end()};
StrStyleSheetGrammar styleGrammar(iter);
bool retval =
phrase_parse(iter, end, styleGrammar, boost::spirit::ascii::space, stylesheet);
if (retval && iter == end) {
return stylesheet;
}
if (iter != end) {
auto errorOfs = std::distance(source_iterator{data.begin()}, iter);
auto restLen = std::distance(iter, end);
auto errorText = restLen > 128 ? data.substr(size_t(errorOfs), 128) + "..."
: data.substr(size_t(errorOfs), std::string::npos);
throw ParseException("Found unexpected tokens", errorText);
} else {
throw ParseException("Unknown error");
}
}
StyleSheet parseString(const QString& data)
{
return parseStdString(data.toStdString());
}
StyleSheet parseStyleFile(const QString& path)
{
return parseStdString(loadFileIntoString(path.toStdString()));
}
} // namespace stylesheets
} // namespace aqt
<commit_msg>Including <ios> is sufficient<commit_after>/*
Copyright (c) 2014-15 Ableton AG, Berlin
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 "CssParser.hpp"
#include "Warnings.hpp"
SUPPRESS_WARNINGS
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/support_line_pos_iterator.hpp>
RESTORE_WARNINGS
#include <fstream>
#include <ios>
#include <sstream>
namespace
{
/*! @throw std::ios_base::failure for IO errors or if the file at @path
* could not be opened. */
std::string loadFileIntoString(const std::string& path)
{
std::stringstream result;
std::ifstream in(path.c_str(), std::ios::in | std::ios::binary);
in.exceptions(std::ifstream::failbit);
result << in.rdbuf();
return result.str();
}
} // anon namespace
// this must be outside of the anon namespace
// clang-format off
BOOST_FUSION_ADAPT_STRUCT(
aqt::stylesheets::PropertySpec,
(std::string, name)
(aqt::stylesheets::PropertyValues, values)
)
BOOST_FUSION_ADAPT_STRUCT(
aqt::stylesheets::PropertySpecSet,
(std::vector<aqt::stylesheets::Selector>, selectors)
(std::vector<aqt::stylesheets::PropertySpec>, properties)
)
BOOST_FUSION_ADAPT_STRUCT(
aqt::stylesheets::FontFaceDecl,
(std::string, url)
)
BOOST_FUSION_ADAPT_STRUCT(
aqt::stylesheets::StyleSheet,
(std::vector<aqt::stylesheets::PropertySpecSet>, propsets)
(std::vector<aqt::stylesheets::FontFaceDecl>, fontfaces)
)
BOOST_FUSION_ADAPT_STRUCT(
aqt::stylesheets::Expression,
(std::string, name)
(std::vector<std::string>, args)
)
// clang-format on
namespace
{
namespace phoenix = boost::phoenix;
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
template <typename It>
class LocationAnnotator
{
const It mFirst;
public:
// to make phoenix::function happy
template <typename>
struct result {
using type = void;
};
LocationAnnotator(It first)
: mFirst(first)
{
}
template <typename ThingWithLocation>
void operator()(ThingWithLocation& thing, It iter) const
{
thing.mSourceLoc.mByteOfs = static_cast<int>(std::distance(mFirst, iter));
thing.mSourceLoc.mLine = static_cast<int>(get_line(iter));
// The column offset is always off by one. Why? It is a mystery.
thing.mSourceLoc.mColumn = static_cast<int>(get_column(mFirst, iter)) - 1;
}
};
template <typename Iterator>
struct StyleSheetGrammar
: qi::grammar<Iterator, aqt::stylesheets::StyleSheet(), ascii::space_type> {
StyleSheetGrammar(Iterator first)
: StyleSheetGrammar::base_type(stylesheet, "stylesheet")
, locationAnnotator(first)
{
using qi::lit;
using qi::lexeme;
using qi::omit;
using ascii::char_;
using ascii::string;
using namespace qi::labels;
using phoenix::at_c;
using phoenix::push_back;
using boost::spirit::eol;
// clang-format off
cpp_comment = "//" >> omit[*(char_ - eol) >> eol];
c_comment = "/*" >> omit[*(char_ - "*/")] >> "*/";
comment = cpp_comment | c_comment;
identifier = +(qi::alnum | char_('-'));
dot_identifier = char_(".") >> identifier;
child_sel = char_(">");
sel_separator = char_(",");
sel_part = +(dot_identifier | identifier)[push_back(_val, _1)];
child_sel_part = (child_sel)[push_back(_val, _1)];
selector = +(sel_part | child_sel_part)[push_back(_val, _1)];
quoted_string = lexeme['"' >> +(char_ - '"') >> '"']
| lexeme['\'' >> +(char_ - '\'') >> '\''];
color = char_('#') >> +(qi::xdigit);
number = +(qi::digit | char_('-') | char_('.')) >> *char_('%');
atom_value = quoted_string
| number
| color
| identifier;
args = atom_value [push_back(_val, _1)]
>> *(lit(',') > atom_value [push_back(_val, _1)]);
expression = identifier[at_c<0>(_val) = _1]
>> lit('(') >> *(args[at_c<1>(_val) = _1]) >> lit(')');
value = quoted_string
| number
| color
| expression
| identifier;
values = value [push_back(_val, _1)]
>> *(lit(',') > value [push_back(_val, _1)]);
value_pair = identifier[at_c<0>(_val) = _1]
>> lit(':') >> values[at_c<1>(_val) = _1]
>> -lit(';');
propset = selector [push_back(at_c<0>(_val), _1)]
>> *((sel_separator >> selector[push_back(at_c<0>(_val), _1)])
| comment)
>> '{'
>> *(value_pair [push_back(at_c<1>(_val), _1)]
| comment)
>> '}';
fontfacedecl = "@font-face" >> -comment
>> lit('{') >> -comment
>> lit("src") >> lit(':') >> -comment
>> lit("url") >> lit('(')
>> (identifier | quoted_string)[at_c<0>(_val) = _1]
>> lit(')') >> -lit(';') >> -comment
>> lit('}');
stylesheet = *(propset[push_back(at_c<0>(_val), _1)]
| fontfacedecl[push_back(at_c<1>(_val), _1)]
| comment);
// clang-format on
// give proper names to the rules for error printing
c_comment.name("comment");
color.name("color");
comment.name("comment");
cpp_comment.name("comment");
fontfacedecl.name("fontface");
identifier.name("identifier");
dot_identifier.name("dot_identifier");
propset.name("propset");
quoted_string.name("string");
stylesheet.name("stylesheet");
sel_separator.name("selector separator");
sel_part.name("selector part");
selector.name("selector");
values.name("value");
number.name("number");
atom_value.name("atomic value");
value.name("value");
value_pair.name("key-value-pair");
child_sel.name("child");
args.name("args");
expression.name("expression");
on_success(propset, locationAnnotator(_val, _1));
on_success(value_pair, locationAnnotator(_val, _1));
}
phoenix::function<LocationAnnotator<Iterator>> locationAnnotator;
qi::rule<Iterator, std::string()> identifier;
qi::rule<Iterator, std::string()> dot_identifier;
qi::rule<Iterator, std::string()> sel_separator;
qi::rule<Iterator, std::string()> child_sel;
qi::rule<Iterator, aqt::stylesheets::SelectorParts()> child_sel_part;
qi::rule<Iterator, aqt::stylesheets::SelectorParts()> sel_part;
qi::rule<Iterator, aqt::stylesheets::Selector(), ascii::space_type> selector;
qi::rule<Iterator, std::string()> color;
qi::rule<Iterator, std::string()> number;
qi::rule<Iterator, std::string(), ascii::space_type> quoted_string;
qi::rule<Iterator, aqt::stylesheets::PropertySpec(), ascii::space_type> value_pair;
qi::rule<Iterator, std::string(), ascii::space_type> atom_value;
qi::rule<Iterator, aqt::stylesheets::PropertyValue(), ascii::space_type> value;
qi::rule<Iterator, aqt::stylesheets::PropertyValues(), ascii::space_type> values;
qi::rule<Iterator, std::vector<std::string>(), ascii::space_type> args;
qi::rule<Iterator, aqt::stylesheets::PropertySpecSet(), ascii::space_type> propset;
qi::rule<Iterator, aqt::stylesheets::FontFaceDecl(), ascii::space_type> fontfacedecl;
qi::rule<Iterator, aqt::stylesheets::StyleSheet(), ascii::space_type> stylesheet;
qi::rule<Iterator, aqt::stylesheets::Expression(), ascii::space_type> expression;
qi::rule<Iterator, boost::spirit::unused_type> cpp_comment;
qi::rule<Iterator, boost::spirit::unused_type> c_comment;
qi::rule<Iterator, boost::spirit::unused_type> comment;
};
} // anon namespace
namespace aqt
{
namespace stylesheets
{
StyleSheet parseStdString(const std::string& data)
{
StyleSheet stylesheet;
using source_iterator = boost::spirit::line_pos_iterator<std::string::const_iterator>;
using StrStyleSheetGrammar = StyleSheetGrammar<source_iterator>;
auto iter = source_iterator{data.begin()};
auto end = source_iterator{data.end()};
StrStyleSheetGrammar styleGrammar(iter);
bool retval =
phrase_parse(iter, end, styleGrammar, boost::spirit::ascii::space, stylesheet);
if (retval && iter == end) {
return stylesheet;
}
if (iter != end) {
auto errorOfs = std::distance(source_iterator{data.begin()}, iter);
auto restLen = std::distance(iter, end);
auto errorText = restLen > 128 ? data.substr(size_t(errorOfs), 128) + "..."
: data.substr(size_t(errorOfs), std::string::npos);
throw ParseException("Found unexpected tokens", errorText);
} else {
throw ParseException("Unknown error");
}
}
StyleSheet parseString(const QString& data)
{
return parseStdString(data.toStdString());
}
StyleSheet parseStyleFile(const QString& path)
{
return parseStdString(loadFileIntoString(path.toStdString()));
}
} // namespace stylesheets
} // namespace aqt
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef _APP_TEMPLATE_HH
#define _APP_TEMPLATE_HH
#include <boost/program_options.hpp>
#include <fstream>
#include <cstdlib>
#include "core/reactor.hh"
#include "core/scollectd.hh"
namespace bpo = boost::program_options;
class app_template {
private:
bpo::options_description _opts;
boost::optional<bpo::variables_map> _configuration;
public:
app_template() {
_opts.add_options()
("help", "show help message")
;
_opts.add(reactor::get_options_description());
_opts.add(smp::get_options_description());
_opts.add(scollectd::get_options_description());
};
boost::program_options::options_description_easy_init add_options() {
return _opts.add_options();
}
bpo::variables_map& configuration() { return *_configuration; }
template<typename Func>
int run(int ac, char ** av, Func&& func) {
bpo::variables_map configuration;
bpo::store(bpo::command_line_parser(ac, av).options(_opts).run(), configuration);
auto home = std::getenv("HOME");
if (home) {
std::ifstream ifs(std::string(home) + "/.config/seastar/seastar.conf");
if (ifs) {
bpo::store(bpo::parse_config_file(ifs, _opts), configuration);
}
}
bpo::notify(configuration);
if (configuration.count("help")) {
std::cout << _opts << "\n";
return 1;
}
smp::configure(configuration);
scollectd::configure(configuration);
_configuration = {std::move(configuration)};
engine.when_started().then(func).rescue([] (auto get_ex) {
try {
get_ex();
} catch (std::exception& ex) {
std::cout << "program failed with uncaught exception: " << ex.what() << "\n";
engine.exit(1);
}
});
return engine.run();
};
};
#endif
<commit_msg>app template: Put options for application in app options group<commit_after>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef _APP_TEMPLATE_HH
#define _APP_TEMPLATE_HH
#include <boost/program_options.hpp>
#include <fstream>
#include <cstdlib>
#include "core/reactor.hh"
#include "core/scollectd.hh"
namespace bpo = boost::program_options;
class app_template {
private:
bpo::options_description _opts;
boost::optional<bpo::variables_map> _configuration;
public:
app_template() : _opts("App options") {
_opts.add_options()
("help", "show help message")
;
_opts.add(reactor::get_options_description());
_opts.add(smp::get_options_description());
_opts.add(scollectd::get_options_description());
};
boost::program_options::options_description_easy_init add_options() {
return _opts.add_options();
}
bpo::variables_map& configuration() { return *_configuration; }
template<typename Func>
int run(int ac, char ** av, Func&& func) {
bpo::variables_map configuration;
bpo::store(bpo::command_line_parser(ac, av).options(_opts).run(), configuration);
auto home = std::getenv("HOME");
if (home) {
std::ifstream ifs(std::string(home) + "/.config/seastar/seastar.conf");
if (ifs) {
bpo::store(bpo::parse_config_file(ifs, _opts), configuration);
}
}
bpo::notify(configuration);
if (configuration.count("help")) {
std::cout << _opts << "\n";
return 1;
}
smp::configure(configuration);
scollectd::configure(configuration);
_configuration = {std::move(configuration)};
engine.when_started().then(func).rescue([] (auto get_ex) {
try {
get_ex();
} catch (std::exception& ex) {
std::cout << "program failed with uncaught exception: " << ex.what() << "\n";
engine.exit(1);
}
});
return engine.run();
};
};
#endif
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File Stimulus.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Stimulus base class.
//
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <tinyxml/tinyxml.h>
#include <LibUtilities/BasicUtils/VmathArray.hpp>
#include <StdRegions/StdNodalTriExp.h>
#include <CardiacEPSolver/Stimuli/StimulusRect.h>
//#include <LibUtilities/LinearAlgebra/Blas.hpp>
namespace Nektar
{
std::string StimulusRect::className
= GetStimulusFactory().RegisterCreatorFunction(
"StimulusRect",
StimulusRect::create,
"Rectangular stimulus.");
/**
* @class StimulusRect
*
* The Stimulus class and derived classes implement a range of stimuli.
* The stimulus contains input stimuli that can be applied throughout the
* domain, on specified regions determined by the derived classes of Stimulus,
* at specified frequencies determined by the derived classes of Protocol.
*
*/
/**
* Stimulus base class constructor.
*/
StimulusRect::StimulusRect(const LibUtilities::SessionReaderSharedPtr& pSession,
const MultiRegions::ExpListSharedPtr& pField,
const TiXmlElement* pXml)
: Stimulus(pSession, pField, pXml)
{
m_session = pSession;
m_field = pField;
m_nq = pField->GetTotPoints();
if (!pXml)
{
return;
}
const TiXmlElement *pXmlparameter; //Declaring variable called pxml...
// See if we have parameters defined. They are optional so we go on if not.
//member variables m_p defined in StimulusRect.h
pXmlparameter = pXml->FirstChildElement("p_x1");
m_px1 = atof(pXmlparameter->GetText()); //text value within px1, convert to a floating pt and save in m_px1
pXmlparameter = pXml->FirstChildElement("p_y1");
m_py1 = atof(pXmlparameter->GetText());
pXmlparameter = pXml->FirstChildElement("p_z1");
m_pz1 = atof(pXmlparameter->GetText());
pXmlparameter = pXml->FirstChildElement("p_x2");
m_px2 = atof(pXmlparameter->GetText());
pXmlparameter = pXml->FirstChildElement("p_y2");
m_py2 = atof(pXmlparameter->GetText());
pXmlparameter = pXml->FirstChildElement("p_z2");
m_pz2 = atof(pXmlparameter->GetText());
pXmlparameter = pXml->FirstChildElement("p_is");
m_pis = atof(pXmlparameter->GetText());
pXmlparameter = pXml->FirstChildElement("p_strength");
m_strength = atof(pXmlparameter->GetText());
}
/**
* Initialise the stimulus. Allocate workspace and variable storage.
*/
void StimulusRect::Initialise()
{
}
void StimulusRect::v_Update(Array<OneD, Array<OneD, NekDouble> >&outarray,
const NekDouble time)
{
//Code to get co ordinates
int nq = m_field->GetNpoints();
Array<OneD,NekDouble> x0(nq);
Array<OneD,NekDouble> x1(nq);
Array<OneD,NekDouble> x2(nq);
NekDouble v_amp = m_Protocol->GetAmplitude(time);
// get the coordinates
m_field->GetCoords(x0,x1,x2);
for(int j=0; j<nq; j++)
{
outarray[0][j]= outarray[0][j] + m_strength * v_amp *
(-tanh( (m_pis * x0[j] - m_px1) * (m_pis * x0[j] - m_px2)) / 2.0 + 0.5) *
(-tanh( (m_pis * x1[j] - m_py1) * (m_pis * x1[j] - m_py2)) / 2.0 + 0.5) *
(-tanh( (m_pis * x2[j] - m_pz1) * (m_pis * x2[j] - m_pz2)) / 2.0 + 0.5);
}
}
void StimulusRect::v_PrintSummary(std::ostream &out)
{
}
}
<commit_msg>Fixed rectangular stimulus.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File Stimulus.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Stimulus base class.
//
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <tinyxml/tinyxml.h>
#include <LibUtilities/BasicUtils/VmathArray.hpp>
#include <StdRegions/StdNodalTriExp.h>
#include <CardiacEPSolver/Stimuli/StimulusRect.h>
//#include <LibUtilities/LinearAlgebra/Blas.hpp>
namespace Nektar
{
std::string StimulusRect::className
= GetStimulusFactory().RegisterCreatorFunction(
"StimulusRect",
StimulusRect::create,
"Rectangular stimulus.");
/**
* @class StimulusRect
*
* The Stimulus class and derived classes implement a range of stimuli.
* The stimulus contains input stimuli that can be applied throughout the
* domain, on specified regions determined by the derived classes of Stimulus,
* at specified frequencies determined by the derived classes of Protocol.
*
*/
/**
* Stimulus base class constructor.
*/
StimulusRect::StimulusRect(const LibUtilities::SessionReaderSharedPtr& pSession,
const MultiRegions::ExpListSharedPtr& pField,
const TiXmlElement* pXml)
: Stimulus(pSession, pField, pXml)
{
m_session = pSession;
m_field = pField;
m_nq = pField->GetTotPoints();
if (!pXml)
{
return;
}
const TiXmlElement *pXmlparameter; //Declaring variable called pxml...
// See if we have parameters defined. They are optional so we go on if not.
//member variables m_p defined in StimulusRect.h
pXmlparameter = pXml->FirstChildElement("p_x1");
m_px1 = atof(pXmlparameter->GetText()); //text value within px1, convert to a floating pt and save in m_px1
pXmlparameter = pXml->FirstChildElement("p_y1");
m_py1 = atof(pXmlparameter->GetText());
pXmlparameter = pXml->FirstChildElement("p_z1");
m_pz1 = atof(pXmlparameter->GetText());
pXmlparameter = pXml->FirstChildElement("p_x2");
m_px2 = atof(pXmlparameter->GetText());
pXmlparameter = pXml->FirstChildElement("p_y2");
m_py2 = atof(pXmlparameter->GetText());
pXmlparameter = pXml->FirstChildElement("p_z2");
m_pz2 = atof(pXmlparameter->GetText());
pXmlparameter = pXml->FirstChildElement("p_is");
m_pis = atof(pXmlparameter->GetText());
pXmlparameter = pXml->FirstChildElement("p_strength");
m_strength = atof(pXmlparameter->GetText());
}
/**
* Initialise the stimulus. Allocate workspace and variable storage.
*/
void StimulusRect::Initialise()
{
}
void StimulusRect::v_Update(Array<OneD, Array<OneD, NekDouble> >&outarray,
const NekDouble time)
{
if (m_field->GetNumElmts() == 0)
{
return;
}
// Get the dimension of the expansion
int dim = m_field->GetCoordim(0);
// Retrieve coordinates of quadrature points
int nq = m_field->GetNpoints();
Array<OneD,NekDouble> x0(nq);
Array<OneD,NekDouble> x1(nq);
Array<OneD,NekDouble> x2(nq);
m_field->GetCoords(x0,x1,x2);
// Get the protocol amplitude
NekDouble v_amp = m_Protocol->GetAmplitude(time) * m_strength;
switch (dim)
{
case 1:
for(int j=0; j<nq; j++)
{
outarray[0][j] += v_amp*(((tanh(m_pis*(x0[j] - m_px1)) - tanh(m_pis*(x0[j] - m_px2))))/2.0 + 0.5);
}
break;
case 2:
for(int j=0; j<nq; j++)
{
outarray[0][j] += v_amp*(((tanh(m_pis*(x0[j] - m_px1)) - tanh(m_pis*(x0[j] - m_px2)))
*(tanh(m_pis*(x1[j] - m_py1)) - tanh(m_pis*(x1[j] - m_py2))))/2.0 + 0.5);
}
break;
case 3:
for(int j=0; j<nq; j++)
{
outarray[0][j] += v_amp*(((tanh(m_pis*(x0[j] - m_px1)) - tanh(m_pis*(x0[j] - m_px2)))
*(tanh(m_pis*(x1[j] - m_py1)) - tanh(m_pis*(x1[j] - m_py2)))
*(tanh(m_pis*(x2[j] - m_pz1)) - tanh(m_pis*(x2[j] - m_pz2))))/2.0 + 0.5);
}
break;
}
}
void StimulusRect::v_PrintSummary(std::ostream &out)
{
}
}
<|endoftext|>
|
<commit_before>//******************************************************************************
// FILE : function_matrix_sum.cpp
//
// LAST MODIFIED : 1 October 2004
//
// DESCRIPTION :
//==============================================================================
#if defined (ONE_TEMPLATE_DEFINITION_IMPLEMENTED)
#include "computed_variable/function_matrix_sum_implementation.cpp"
#else // defined (ONE_TEMPLATE_DEFINITION_IMPLEMENTED)
#include "computed_variable/function_matrix_sum.hpp"
#endif // defined (ONE_TEMPLATE_DEFINITION_IMPLEMENTED)
#if !defined (AIX)
template<>
Function_handle Function_variable_matrix_sum<Scalar>::evaluate_derivative(
std::list<Function_variable_handle>& independent_variables)
//******************************************************************************
// LAST MODIFIED : 1 October 2004
//
// DESCRIPTION :
// ???DB. To be done
//==============================================================================
{
boost::intrusive_ptr< Function_matrix_sum<Scalar> > function_matrix_sum;
Function_handle result(0);
Function_size_type order;
if ((function_matrix_sum=boost::dynamic_pointer_cast<
Function_matrix_sum<Scalar>,Function>(function()))&&
(0<(order=independent_variables.size())))
{
Function_size_type number_of_columns,number_of_dependent_values,
number_of_independent_values,number_of_rows;
boost::intrusive_ptr< Function_matrix<Scalar> > derivative_1,derivative_2,
summand_1,summand_2;
if ((summand_1=boost::dynamic_pointer_cast<Function_matrix<Scalar>,
Function>(function_matrix_sum->summand_1_private->evaluate()))&&
(summand_2=boost::dynamic_pointer_cast<Function_matrix<Scalar>,Function>(
function_matrix_sum->summand_2_private->evaluate()))&&
(row_private<=(number_of_rows=summand_1->number_of_rows()))&&
(number_of_rows==summand_2->number_of_rows())&&
(column_private<=(number_of_columns=summand_1->number_of_columns()))&&
(number_of_columns==summand_2->number_of_columns())&&
(derivative_1=boost::dynamic_pointer_cast<Function_matrix<Scalar>,
Function>(function_matrix_sum->summand_1_private->
evaluate_derivative(independent_variables)))&&
(derivative_2=boost::dynamic_pointer_cast<Function_matrix<Scalar>,
Function>(function_matrix_sum->summand_2_private->
evaluate_derivative(independent_variables)))&&
(number_of_rows*number_of_columns==
(number_of_dependent_values=derivative_1->number_of_rows()))&&
(number_of_dependent_values==derivative_2->number_of_rows())&&
(derivative_1->number_of_columns()==(number_of_independent_values=
derivative_2->number_of_columns())))
{
Function_size_type dependent_row,i,j;
if (0==row_private)
{
if (0==column_private)
{
for (i=1;i<=number_of_dependent_values;i++)
{
for (j=1;j<=number_of_independent_values;j++)
{
(*derivative_1)(i,j) += (*derivative_2)(i,j);
}
}
result=derivative_1;
}
else
{
Matrix result_matrix(number_of_rows,number_of_independent_values);
dependent_row=column_private;
for (i=0;i<number_of_rows;i++)
{
for (j=1;j<=number_of_independent_values;j++)
{
result_matrix(i,j-1)=(*derivative_1)(dependent_row,j)+
(*derivative_2)(dependent_row,j);
}
dependent_row += number_of_columns;
}
result=Function_handle(new Function_matrix<Scalar>(result_matrix));
}
}
else
{
if (0==column_private)
{
Matrix result_matrix(number_of_columns,number_of_independent_values);
dependent_row=(row_private-1)*number_of_columns+1;
for (i=0;i<number_of_columns;i++)
{
for (j=1;j<=number_of_independent_values;j++)
{
result_matrix(i,j-1)=(*derivative_1)(dependent_row,j)+
(*derivative_2)(dependent_row,j);
}
dependent_row++;
}
result=Function_handle(new Function_matrix<Scalar>(result_matrix));
}
else
{
Matrix result_matrix(1,number_of_independent_values);
dependent_row=(row_private-1)*number_of_columns+column_private;
for (j=1;j<=number_of_independent_values;j++)
{
result_matrix(0,j-1)=(*derivative_1)(dependent_row,j)+
(*derivative_2)(dependent_row,j);
}
result=Function_handle(new Function_matrix<Scalar>(result_matrix));
}
}
}
}
return (result);
}
template<>
bool Function_matrix_sum<Scalar>::evaluate_derivative(Scalar& derivative,
Function_variable_handle atomic_variable,
std::list<Function_variable_handle>& atomic_independent_variables)
//******************************************************************************
// LAST MODIFIED : 1 October 2004
//
// DESCRIPTION :
//==============================================================================
{
bool result;
boost::intrusive_ptr< Function_variable_matrix_sum<Scalar> >
atomic_variable_matrix_sum;
result=false;
if ((atomic_variable_matrix_sum=boost::dynamic_pointer_cast<
Function_variable_matrix_sum<Scalar>,Function_variable>(
atomic_variable))&&equivalent(Function_handle(this),
atomic_variable_matrix_sum->function())&&
(0<atomic_variable_matrix_sum->row())&&
(0<atomic_variable_matrix_sum->column())&&
(0<atomic_independent_variables.size()))
{
boost::intrusive_ptr< Function_matrix<Scalar> > derivative_matrix=
boost::dynamic_pointer_cast<Function_matrix<Scalar>,Function>(
atomic_variable_matrix_sum->evaluate_derivative(
atomic_independent_variables));
if (derivative_matrix)
{
result=true;
derivative=(*derivative_matrix)(1,1);
}
}
return (result);
}
#if defined (OLD_CODE)
template<>
bool Function_matrix_sum<Scalar>::evaluate_derivative(Scalar& derivative,
Function_variable_handle atomic_variable,
std::list<Function_variable_handle>& atomic_independent_variables)
//******************************************************************************
// LAST MODIFIED : 1 September 2004
//
// DESCRIPTION :
//==============================================================================
{
bool result;
boost::intrusive_ptr< Function_variable_matrix_sum<Scalar> >
atomic_variable_matrix_sum;
Function_size_type column,row;
result=false;
if ((atomic_variable_matrix_sum=boost::dynamic_pointer_cast<
Function_variable_matrix_sum<Scalar>,Function_variable>(atomic_variable))&&
equivalent(Function_handle(this),atomic_variable_matrix_sum->function())&&
(0<(row=atomic_variable_matrix_sum->row()))&&
(0<(column=atomic_variable_matrix_sum->column())))
{
boost::intrusive_ptr< Function_variable_matrix<Scalar> > temp_variable;
Function_handle function;
Scalar value_1,value_2;
if ((temp_variable=(*summand_1_private)(row,column))&&
(function=temp_variable->function())&&(function->evaluate_derivative)(
value_1,temp_variable,atomic_independent_variables)&&
(temp_variable=(*summand_2_private)(row,column))&&
(function=temp_variable->function())&&(function->evaluate_derivative)(
value_2,temp_variable,atomic_independent_variables))
{
result=true;
derivative=value_1+value_2;
}
}
return (result);
}
#endif // defined (OLD_CODE)
#endif // !defined (AIX)
<commit_msg>Removed unused variable<commit_after>//******************************************************************************
// FILE : function_matrix_sum.cpp
//
// LAST MODIFIED : 18 October 2004
//
// DESCRIPTION :
//==============================================================================
#if defined (ONE_TEMPLATE_DEFINITION_IMPLEMENTED)
#include "computed_variable/function_matrix_sum_implementation.cpp"
#else // defined (ONE_TEMPLATE_DEFINITION_IMPLEMENTED)
#include "computed_variable/function_matrix_sum.hpp"
#endif // defined (ONE_TEMPLATE_DEFINITION_IMPLEMENTED)
#if !defined (AIX)
template<>
Function_handle Function_variable_matrix_sum<Scalar>::evaluate_derivative(
std::list<Function_variable_handle>& independent_variables)
//******************************************************************************
// LAST MODIFIED : 18 October 2004
//
// DESCRIPTION :
// ???DB. To be done
//==============================================================================
{
boost::intrusive_ptr< Function_matrix_sum<Scalar> > function_matrix_sum;
Function_handle result(0);
if ((function_matrix_sum=boost::dynamic_pointer_cast<
Function_matrix_sum<Scalar>,Function>(function()))&&
(0<independent_variables.size()))
{
Function_size_type number_of_columns,number_of_dependent_values,
number_of_independent_values,number_of_rows;
boost::intrusive_ptr< Function_matrix<Scalar> > derivative_1,derivative_2,
summand_1,summand_2;
if ((summand_1=boost::dynamic_pointer_cast<Function_matrix<Scalar>,
Function>(function_matrix_sum->summand_1_private->evaluate()))&&
(summand_2=boost::dynamic_pointer_cast<Function_matrix<Scalar>,Function>(
function_matrix_sum->summand_2_private->evaluate()))&&
(row_private<=(number_of_rows=summand_1->number_of_rows()))&&
(number_of_rows==summand_2->number_of_rows())&&
(column_private<=(number_of_columns=summand_1->number_of_columns()))&&
(number_of_columns==summand_2->number_of_columns())&&
(derivative_1=boost::dynamic_pointer_cast<Function_matrix<Scalar>,
Function>(function_matrix_sum->summand_1_private->
evaluate_derivative(independent_variables)))&&
(derivative_2=boost::dynamic_pointer_cast<Function_matrix<Scalar>,
Function>(function_matrix_sum->summand_2_private->
evaluate_derivative(independent_variables)))&&
(number_of_rows*number_of_columns==
(number_of_dependent_values=derivative_1->number_of_rows()))&&
(number_of_dependent_values==derivative_2->number_of_rows())&&
(derivative_1->number_of_columns()==(number_of_independent_values=
derivative_2->number_of_columns())))
{
Function_size_type dependent_row,i,j;
if (0==row_private)
{
if (0==column_private)
{
for (i=1;i<=number_of_dependent_values;i++)
{
for (j=1;j<=number_of_independent_values;j++)
{
(*derivative_1)(i,j) += (*derivative_2)(i,j);
}
}
result=derivative_1;
}
else
{
Matrix result_matrix(number_of_rows,number_of_independent_values);
dependent_row=column_private;
for (i=0;i<number_of_rows;i++)
{
for (j=1;j<=number_of_independent_values;j++)
{
result_matrix(i,j-1)=(*derivative_1)(dependent_row,j)+
(*derivative_2)(dependent_row,j);
}
dependent_row += number_of_columns;
}
result=Function_handle(new Function_matrix<Scalar>(result_matrix));
}
}
else
{
if (0==column_private)
{
Matrix result_matrix(number_of_columns,number_of_independent_values);
dependent_row=(row_private-1)*number_of_columns+1;
for (i=0;i<number_of_columns;i++)
{
for (j=1;j<=number_of_independent_values;j++)
{
result_matrix(i,j-1)=(*derivative_1)(dependent_row,j)+
(*derivative_2)(dependent_row,j);
}
dependent_row++;
}
result=Function_handle(new Function_matrix<Scalar>(result_matrix));
}
else
{
Matrix result_matrix(1,number_of_independent_values);
dependent_row=(row_private-1)*number_of_columns+column_private;
for (j=1;j<=number_of_independent_values;j++)
{
result_matrix(0,j-1)=(*derivative_1)(dependent_row,j)+
(*derivative_2)(dependent_row,j);
}
result=Function_handle(new Function_matrix<Scalar>(result_matrix));
}
}
}
}
return (result);
}
template<>
bool Function_matrix_sum<Scalar>::evaluate_derivative(Scalar& derivative,
Function_variable_handle atomic_variable,
std::list<Function_variable_handle>& atomic_independent_variables)
//******************************************************************************
// LAST MODIFIED : 1 October 2004
//
// DESCRIPTION :
//==============================================================================
{
bool result;
boost::intrusive_ptr< Function_variable_matrix_sum<Scalar> >
atomic_variable_matrix_sum;
result=false;
if ((atomic_variable_matrix_sum=boost::dynamic_pointer_cast<
Function_variable_matrix_sum<Scalar>,Function_variable>(
atomic_variable))&&equivalent(Function_handle(this),
atomic_variable_matrix_sum->function())&&
(0<atomic_variable_matrix_sum->row())&&
(0<atomic_variable_matrix_sum->column())&&
(0<atomic_independent_variables.size()))
{
boost::intrusive_ptr< Function_matrix<Scalar> > derivative_matrix=
boost::dynamic_pointer_cast<Function_matrix<Scalar>,Function>(
atomic_variable_matrix_sum->evaluate_derivative(
atomic_independent_variables));
if (derivative_matrix)
{
result=true;
derivative=(*derivative_matrix)(1,1);
}
}
return (result);
}
#if defined (OLD_CODE)
template<>
bool Function_matrix_sum<Scalar>::evaluate_derivative(Scalar& derivative,
Function_variable_handle atomic_variable,
std::list<Function_variable_handle>& atomic_independent_variables)
//******************************************************************************
// LAST MODIFIED : 1 September 2004
//
// DESCRIPTION :
//==============================================================================
{
bool result;
boost::intrusive_ptr< Function_variable_matrix_sum<Scalar> >
atomic_variable_matrix_sum;
Function_size_type column,row;
result=false;
if ((atomic_variable_matrix_sum=boost::dynamic_pointer_cast<
Function_variable_matrix_sum<Scalar>,Function_variable>(atomic_variable))&&
equivalent(Function_handle(this),atomic_variable_matrix_sum->function())&&
(0<(row=atomic_variable_matrix_sum->row()))&&
(0<(column=atomic_variable_matrix_sum->column())))
{
boost::intrusive_ptr< Function_variable_matrix<Scalar> > temp_variable;
Function_handle function;
Scalar value_1,value_2;
if ((temp_variable=(*summand_1_private)(row,column))&&
(function=temp_variable->function())&&(function->evaluate_derivative)(
value_1,temp_variable,atomic_independent_variables)&&
(temp_variable=(*summand_2_private)(row,column))&&
(function=temp_variable->function())&&(function->evaluate_derivative)(
value_2,temp_variable,atomic_independent_variables))
{
result=true;
derivative=value_1+value_2;
}
}
return (result);
}
#endif // defined (OLD_CODE)
#endif // !defined (AIX)
<|endoftext|>
|
<commit_before>#include "stdafx.h"
using std::vector;
static Decryptor* instance = nullptr;
/* static */
Decryptor*
Decryptor::Get()
{
return instance;
}
/* static */
void
Decryptor::Create(GMPDecryptorHost* aHost)
{
assert(!Get());
instance = new Decryptor(aHost);
}
Decryptor::Decryptor(GMPDecryptorHost* aHost)
: mHost(aHost)
, mNum(0)
, mDecryptNumber(0)
{
memset(&mEcount, 0, AES_BLOCK_SIZE);
}
void
Decryptor::Init(GMPDecryptorCallback* aCallback)
{
mCallback = aCallback;
}
void
Decryptor::SessionIdClient::Init(GMPRecord* aRecord, GMPTask* aContinuation)
{
mId = 0;
mRecord = aRecord;
mContinuation = aContinuation;
auto err = mRecord->Open();
assert(GMP_SUCCEEDED(err));
}
void
Decryptor::SessionIdClient::OnOpenComplete(GMPErr aStatus)
{
assert(GMP_SUCCEEDED(aStatus));
if (GMP_SUCCEEDED(aStatus)) {
mRecord->Read();
}
}
void
Decryptor::SessionIdClient::OnReadComplete(GMPErr aStatus,
const uint8_t* aData,
uint32_t aDataSize)
{
if (aDataSize == 4) {
mId = *((uint32_t*)(aData));
}
uint32_t nextId = mId + 1;
mRecord->Write((uint8_t*)&nextId, 4);
GMPRunOnMainThread(mContinuation);
mContinuation = nullptr;
}
void
Decryptor::SessionIdClient::OnWriteComplete(GMPErr aStatus)
{
mRecord->Close();
}
void
Decryptor::SessionIdReady(uint32_t aPromiseId,
uint32_t aSessionId,
const uint8_t* aInitData,
uint32_t aInitDataSize)
{
std::string sid = std::to_string(aSessionId);
mCallback->OnResolveNewSessionPromise(aPromiseId, sid.c_str(), sid.size());
mCallback->OnSessionMessage(sid.c_str(), sid.size(),
aInitData, aInitDataSize,
"", 0);
std::string msg = "Message for you sir! (Sent from my GMPTask)";
GMPTimestamp t = 0;
auto err = GMPGetCurrentTime(&t);
if (GMP_SUCCEEDED(err)) {
msg += " time=" + std::to_string(t);
}
GMPTask* task = new MessageTask(mCallback, sid, msg);
GMPSetTimer(task, 3000);
}
void
Decryptor::CreateSession(uint32_t aPromiseId,
const char* aInitDataType,
uint32_t aInitDataTypeSize,
const uint8_t* aInitData,
uint32_t aInitDataSize,
GMPSessionType aSessionType)
{
#ifdef INCREASING_SESSION_ID
static uint32_t sessionNum = 1;
SessionIdReady(aPromiseId, sessionNum++);
#else
const char* sid = "sessionid";
GMPRecord* record = nullptr;
auto err = GMPOpenRecord(sid, strlen(sid), &record, &mSessionIdClient);
if (GMP_SUCCEEDED(err)) {
auto ready = new SessionIdReadyTask(this,
aPromiseId,
&mSessionIdClient,
aInitData,
aInitDataSize);
mSessionIdClient.Init(record, ready);
}
#endif
}
void
Decryptor::LoadSession(uint32_t aPromiseId,
const char* aSessionId,
uint32_t aSessionIdLength)
{
}
void
Decryptor::UpdateSession(uint32_t aPromiseId,
const char* aSessionId,
uint32_t aSessionIdLength,
const uint8_t* aResponse,
uint32_t aResponseSize)
{
eme_key_set keys;
ExtractKeysFromJWKSet(std::string((const char*)aResponse, aResponseSize), keys);
for (auto itr = keys.begin(); itr != keys.end(); itr++) {
eme_key_id id = itr->first;
eme_key key = itr->second;
mKeySet[id] = key;
mCallback->OnKeyIdUsable(aSessionId, aSessionIdLength, (uint8_t*)id.c_str(), id.length());
}
}
void
Decryptor::CloseSession(uint32_t aPromiseId,
const char* aSessionId,
uint32_t aSessionIdLength)
{
// Drop keys for session_id.
// G. implementation:
// https://code.google.com/p/chromium/codesearch#chromium/src/media/cdm/aes_decryptor.cc&sq=package:chromium&q=ReleaseSession&l=300&type=cs
mKeySet.clear();
//mHost->OnSessionClosed(session_id);
//mActiveSessionId = ~0;
}
void
Decryptor::RemoveSession(uint32_t aPromiseId,
const char* aSessionId,
uint32_t aSessionIdLength)
{
}
void
Decryptor::SetServerCertificate(uint32_t aPromiseId,
const uint8_t* aServerCert,
uint32_t aServerCertSize)
{
}
bool
Decryptor::Decrypt(const uint8_t* aEncryptedBuffer,
const uint32_t aLength,
const GMPEncryptedBufferData* aCryptoData,
vector<uint8_t>& aOutDecrypted)
{
std::string kid((const char*)aCryptoData->KeyId(), aCryptoData->KeyIdSize());
if (mKeySet.find(kid) == mKeySet.end()) {
// No key for that id.
return false;
}
const std::string key = mKeySet[kid];
if (AES_set_encrypt_key((uint8_t*)key.c_str(), 128, &mKey)) {
LOG(L"Failed to set decryption key!\n");
return false;
}
// Make one pass copying all encrypted data into a single buffer, then
// another pass to decrypt it. Then another pass copying it into the
// output buffer.
vector<uint8_t> data;
uint32_t index = 0;
const uint32_t num_subsamples = aCryptoData->NumSubsamples();
const uint32_t* clear_bytes = aCryptoData->ClearBytes();
const uint32_t* cipher_bytes = aCryptoData->CipherBytes();
for (uint32_t i=0; i<num_subsamples; i++) {
index += clear_bytes[i];
const uint8_t* start = aEncryptedBuffer + index;
const uint8_t* end = start + cipher_bytes[i];
data.insert(data.end(), start, end);
index += cipher_bytes[i];
}
// Ensure the data length is a multiple of 16, and the extra data is
// filled with 0's
int32_t extra = (data.size() + AES_BLOCK_SIZE) % AES_BLOCK_SIZE;
data.insert(data.end(), extra, uint8_t(0));
// Decrypt the buffer.
const uint32_t iterations = data.size() / AES_BLOCK_SIZE;
vector<uint8_t> decrypted;
decrypted.resize(data.size());
uint8_t iv[AES_BLOCK_SIZE] = {0};
memcpy(iv, aCryptoData->IV(), aCryptoData->IVSize());
for (uint32_t i=0; i<iterations; i++) {
uint8_t* in = data.data() + i*AES_BLOCK_SIZE;
assert(in + AES_BLOCK_SIZE <= data.data() + data.size());
uint8_t* out = decrypted.data() + i*AES_BLOCK_SIZE;
assert(out + AES_BLOCK_SIZE <= decrypted.data() + decrypted.size());
AES_ctr128_encrypt(in,
out,
AES_BLOCK_SIZE,
&mKey,
iv,
mEcount,
&mNum);
}
// Re-assemble the decrypted buffer.
aOutDecrypted.clear();
aOutDecrypted.resize(aLength);
uint8_t* dst = aOutDecrypted.data();
const uint8_t* src = aEncryptedBuffer;
index = 0;
uint32_t decrypted_index = 0;
for (uint32_t i = 0; i < num_subsamples; i++) {
memcpy(dst+index, src+index, clear_bytes[i]);
index += clear_bytes[i];
memcpy(dst+index, decrypted.data()+decrypted_index, cipher_bytes[i]);
decrypted_index+= cipher_bytes[i];
index += cipher_bytes[i];
assert(index <= aLength);
assert(decrypted_index <= aLength);
}
mDecryptNumber++;
return true;
}
<commit_msg>Send a dummy session error when an update() comes in. To test error reporting.<commit_after>#include "stdafx.h"
using std::vector;
static Decryptor* instance = nullptr;
/* static */
Decryptor*
Decryptor::Get()
{
return instance;
}
/* static */
void
Decryptor::Create(GMPDecryptorHost* aHost)
{
assert(!Get());
instance = new Decryptor(aHost);
}
Decryptor::Decryptor(GMPDecryptorHost* aHost)
: mHost(aHost)
, mNum(0)
, mDecryptNumber(0)
{
memset(&mEcount, 0, AES_BLOCK_SIZE);
}
void
Decryptor::Init(GMPDecryptorCallback* aCallback)
{
mCallback = aCallback;
}
void
Decryptor::SessionIdClient::Init(GMPRecord* aRecord, GMPTask* aContinuation)
{
mId = 0;
mRecord = aRecord;
mContinuation = aContinuation;
auto err = mRecord->Open();
assert(GMP_SUCCEEDED(err));
}
void
Decryptor::SessionIdClient::OnOpenComplete(GMPErr aStatus)
{
assert(GMP_SUCCEEDED(aStatus));
if (GMP_SUCCEEDED(aStatus)) {
mRecord->Read();
}
}
void
Decryptor::SessionIdClient::OnReadComplete(GMPErr aStatus,
const uint8_t* aData,
uint32_t aDataSize)
{
if (aDataSize == 4) {
mId = *((uint32_t*)(aData));
}
uint32_t nextId = mId + 1;
mRecord->Write((uint8_t*)&nextId, 4);
GMPRunOnMainThread(mContinuation);
mContinuation = nullptr;
}
void
Decryptor::SessionIdClient::OnWriteComplete(GMPErr aStatus)
{
mRecord->Close();
}
void
Decryptor::SessionIdReady(uint32_t aPromiseId,
uint32_t aSessionId,
const uint8_t* aInitData,
uint32_t aInitDataSize)
{
std::string sid = std::to_string(aSessionId);
mCallback->OnResolveNewSessionPromise(aPromiseId, sid.c_str(), sid.size());
mCallback->OnSessionMessage(sid.c_str(), sid.size(),
aInitData, aInitDataSize,
"", 0);
std::string msg = "Message for you sir! (Sent from my GMPTask)";
GMPTimestamp t = 0;
auto err = GMPGetCurrentTime(&t);
if (GMP_SUCCEEDED(err)) {
msg += " time=" + std::to_string(t);
}
GMPTask* task = new MessageTask(mCallback, sid, msg);
GMPSetTimer(task, 3000);
}
void
Decryptor::CreateSession(uint32_t aPromiseId,
const char* aInitDataType,
uint32_t aInitDataTypeSize,
const uint8_t* aInitData,
uint32_t aInitDataSize,
GMPSessionType aSessionType)
{
#ifdef INCREASING_SESSION_ID
static uint32_t sessionNum = 1;
SessionIdReady(aPromiseId, sessionNum++);
#else
const char* sid = "sessionid";
GMPRecord* record = nullptr;
auto err = GMPOpenRecord(sid, strlen(sid), &record, &mSessionIdClient);
if (GMP_SUCCEEDED(err)) {
auto ready = new SessionIdReadyTask(this,
aPromiseId,
&mSessionIdClient,
aInitData,
aInitDataSize);
mSessionIdClient.Init(record, ready);
}
#endif
}
void
Decryptor::LoadSession(uint32_t aPromiseId,
const char* aSessionId,
uint32_t aSessionIdLength)
{
}
void
Decryptor::UpdateSession(uint32_t aPromiseId,
const char* aSessionId,
uint32_t aSessionIdLength,
const uint8_t* aResponse,
uint32_t aResponseSize)
{
eme_key_set keys;
ExtractKeysFromJWKSet(std::string((const char*)aResponse, aResponseSize), keys);
for (auto itr = keys.begin(); itr != keys.end(); itr++) {
eme_key_id id = itr->first;
eme_key key = itr->second;
mKeySet[id] = key;
mCallback->OnKeyIdUsable(aSessionId, aSessionIdLength, (uint8_t*)id.c_str(), id.length());
}
std::string msg = "ClearKeyGMP says UpdateSession is throwing fake error/exception";
mCallback->OnSessionError(aSessionId, aSessionIdLength,
kGMPInvalidStateError,
42,
msg.c_str(),
msg.size());
}
void
Decryptor::CloseSession(uint32_t aPromiseId,
const char* aSessionId,
uint32_t aSessionIdLength)
{
// Drop keys for session_id.
// G. implementation:
// https://code.google.com/p/chromium/codesearch#chromium/src/media/cdm/aes_decryptor.cc&sq=package:chromium&q=ReleaseSession&l=300&type=cs
mKeySet.clear();
//mHost->OnSessionClosed(session_id);
//mActiveSessionId = ~0;
}
void
Decryptor::RemoveSession(uint32_t aPromiseId,
const char* aSessionId,
uint32_t aSessionIdLength)
{
}
void
Decryptor::SetServerCertificate(uint32_t aPromiseId,
const uint8_t* aServerCert,
uint32_t aServerCertSize)
{
}
bool
Decryptor::Decrypt(const uint8_t* aEncryptedBuffer,
const uint32_t aLength,
const GMPEncryptedBufferData* aCryptoData,
vector<uint8_t>& aOutDecrypted)
{
std::string kid((const char*)aCryptoData->KeyId(), aCryptoData->KeyIdSize());
if (mKeySet.find(kid) == mKeySet.end()) {
// No key for that id.
return false;
}
const std::string key = mKeySet[kid];
if (AES_set_encrypt_key((uint8_t*)key.c_str(), 128, &mKey)) {
LOG(L"Failed to set decryption key!\n");
return false;
}
// Make one pass copying all encrypted data into a single buffer, then
// another pass to decrypt it. Then another pass copying it into the
// output buffer.
vector<uint8_t> data;
uint32_t index = 0;
const uint32_t num_subsamples = aCryptoData->NumSubsamples();
const uint32_t* clear_bytes = aCryptoData->ClearBytes();
const uint32_t* cipher_bytes = aCryptoData->CipherBytes();
for (uint32_t i=0; i<num_subsamples; i++) {
index += clear_bytes[i];
const uint8_t* start = aEncryptedBuffer + index;
const uint8_t* end = start + cipher_bytes[i];
data.insert(data.end(), start, end);
index += cipher_bytes[i];
}
// Ensure the data length is a multiple of 16, and the extra data is
// filled with 0's
int32_t extra = (data.size() + AES_BLOCK_SIZE) % AES_BLOCK_SIZE;
data.insert(data.end(), extra, uint8_t(0));
// Decrypt the buffer.
const uint32_t iterations = data.size() / AES_BLOCK_SIZE;
vector<uint8_t> decrypted;
decrypted.resize(data.size());
uint8_t iv[AES_BLOCK_SIZE] = {0};
memcpy(iv, aCryptoData->IV(), aCryptoData->IVSize());
for (uint32_t i=0; i<iterations; i++) {
uint8_t* in = data.data() + i*AES_BLOCK_SIZE;
assert(in + AES_BLOCK_SIZE <= data.data() + data.size());
uint8_t* out = decrypted.data() + i*AES_BLOCK_SIZE;
assert(out + AES_BLOCK_SIZE <= decrypted.data() + decrypted.size());
AES_ctr128_encrypt(in,
out,
AES_BLOCK_SIZE,
&mKey,
iv,
mEcount,
&mNum);
}
// Re-assemble the decrypted buffer.
aOutDecrypted.clear();
aOutDecrypted.resize(aLength);
uint8_t* dst = aOutDecrypted.data();
const uint8_t* src = aEncryptedBuffer;
index = 0;
uint32_t decrypted_index = 0;
for (uint32_t i = 0; i < num_subsamples; i++) {
memcpy(dst+index, src+index, clear_bytes[i]);
index += clear_bytes[i];
memcpy(dst+index, decrypted.data()+decrypted_index, cipher_bytes[i]);
decrypted_index+= cipher_bytes[i];
index += cipher_bytes[i];
assert(index <= aLength);
assert(decrypted_index <= aLength);
}
mDecryptNumber++;
return true;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p10/procedures/hwp/perv/p10_setup_sbe_config.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2020 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p10_setup_sbe_config.C
///
/// @brief proc setup sbe config
//------------------------------------------------------------------------------
// *HWP HW Maintainer : Anusha Reddy (anusrang@in.ibm.com)
// *HWP FW Maintainer : Raja Das (rajadas2@in.ibm.com)
// *HWP Consumed by : FSP
//------------------------------------------------------------------------------
#include <p10_setup_sbe_config.H>
#include <p10_sbe_scratch_regs.H>
#include <p10_scom_perv.H>
// description in header
fapi2::ReturnCode p10_setup_sbe_config(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
using namespace scomt::perv;
FAPI_INF("p10_setup_sbe_config:: Entering ...");
fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
// when running in Hostboot context, use SCOM to reach master only
bool l_use_scom = false;
if (fapi2::is_platform<fapi2::PLAT_HOSTBOOT>())
{
fapi2::ATTR_PROC_SBE_MASTER_CHIP_Type l_sbe_master_chip;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_SBE_MASTER_CHIP, i_target_chip, l_sbe_master_chip),
"Error from FAPI_ATTR_GET (ATTR_PROC_SBE_MASTER_CHIP");
l_use_scom = (l_sbe_master_chip == fapi2::ENUM_ATTR_PROC_SBE_MASTER_CHIP_TRUE);
}
// clear secure access bit if instructed to disable security
{
fapi2::ATTR_SECURITY_MODE_Type l_attr_security_mode;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SECURITY_MODE, FAPI_SYSTEM, l_attr_security_mode),
"Error from FAPI_ATTR_GET (ATTR_SECURITY_MODE)");
if (!l_attr_security_mode)
{
// The Secure Access Bit is only writeable on DD1 chips,
// so we won't need to put an EC level switch in here.
// Set scratch reg3 bit 6 to disable security by default now for DD1
// Set scratch reg8 bit 2 to mark scratch reg3 as valid
FAPI_DBG("Attempting to disable security");
if (l_use_scom)
{
fapi2::buffer<uint64_t> l_cbs_cs;
fapi2::buffer<uint64_t> l_read_scratch3_reg;
fapi2::buffer<uint64_t> l_read_scratch8_reg;
FAPI_TRY(fapi2::getScom(i_target_chip,
FSXCOMP_FSXLOG_CBS_CS,
l_cbs_cs),
"Error reading CBS Control/Status register (scom)");
l_cbs_cs.clearBit<FSXCOMP_FSXLOG_CBS_CS_SECURE_ACCESS_BIT>();
FAPI_TRY(fapi2::putScom(i_target_chip,
FSXCOMP_FSXLOG_CBS_CS,
l_cbs_cs),
"Error writing CBS Control/Status register (scom)");
FAPI_TRY(fapi2::getScom(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_3_RW,
l_read_scratch3_reg),
"Error reading Scratch Reg3 register");
l_read_scratch3_reg.setBit<6>();
FAPI_TRY(fapi2::putScom(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_3_RW,
l_read_scratch3_reg),
"Error writing Scratch Reg3 register");
FAPI_TRY(fapi2::getScom(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_8_RW,
l_read_scratch8_reg),
"Error reading Scratch Reg8 register");
l_read_scratch8_reg.setBit<2>();
FAPI_TRY(fapi2::putScom(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_8_RW,
l_read_scratch8_reg),
"Error writing Scratch Reg8 register");
}
else
{
fapi2::buffer<uint32_t> l_cbs_cs;
fapi2::buffer<uint32_t> l_read_scratch3_reg;
fapi2::buffer<uint32_t> l_read_scratch8_reg;
FAPI_TRY(fapi2::getCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_CBS_CS_FSI,
l_cbs_cs),
"Error reading CBS Control/Status register (cfam)");
l_cbs_cs.clearBit<FSXCOMP_FSXLOG_CBS_CS_SECURE_ACCESS_BIT>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_CBS_CS_FSI,
l_cbs_cs),
"Error writing CBS Control/Status register (cfam)");
FAPI_TRY(fapi2::getCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_3_FSI,
l_read_scratch3_reg),
"Error reading Scratch Reg3 register");
l_read_scratch3_reg.setBit<6>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_3_FSI,
l_read_scratch3_reg),
"Error writing Scratch Reg3 register");
FAPI_TRY(fapi2::getCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_8_FSI,
l_read_scratch8_reg),
"Error reading Scratch Reg8 register");
l_read_scratch8_reg.setBit<2>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_8_FSI,
l_read_scratch8_reg),
"Error writing Scratch Reg8 register");
}
}
}
// set fused mode behavior
{
fapi2::ATTR_FUSED_CORE_MODE_Type l_attr_fused_core_mode;
fapi2::ATTR_CORE_LPAR_MODE_POLICY_Type l_attr_core_lpar_mode_policy;
fapi2::ATTR_CORE_LPAR_MODE_Type l_attr_core_lpar_mode;
fapi2::buffer<uint64_t> l_perv_ctrl0;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CORE_LPAR_MODE_POLICY, FAPI_SYSTEM, l_attr_core_lpar_mode_policy),
"Error from FAPI_ATTR_GET (ATTR_CORE_LPAR_MODE_POLICY)");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FUSED_CORE_MODE, FAPI_SYSTEM, l_attr_fused_core_mode),
"Error from FAPI_ATTR_GET (ATTR_FUSED_CORE_MODE)");
if (l_attr_core_lpar_mode_policy == fapi2::ENUM_ATTR_CORE_LPAR_MODE_POLICY_FOLLOW_FUSED_STATE)
{
if (l_attr_fused_core_mode == fapi2::ENUM_ATTR_FUSED_CORE_MODE_CORE_FUSED)
{
l_attr_core_lpar_mode = fapi2::ENUM_ATTR_CORE_LPAR_MODE_LPAR_PER_CORE;
}
else
{
l_attr_core_lpar_mode = fapi2::ENUM_ATTR_CORE_LPAR_MODE_LPAR_PER_THREAD;
}
}
else if (l_attr_core_lpar_mode_policy == fapi2::ENUM_ATTR_CORE_LPAR_MODE_POLICY_LPAR_PER_CORE)
{
l_attr_core_lpar_mode = fapi2::ENUM_ATTR_CORE_LPAR_MODE_LPAR_PER_CORE;
}
else
{
l_attr_core_lpar_mode = fapi2::ENUM_ATTR_CORE_LPAR_MODE_LPAR_PER_THREAD;
}
if (l_use_scom)
{
FAPI_TRY(fapi2::getScom(i_target_chip,
FSXCOMP_FSXLOG_PERV_CTRL0_RW,
l_perv_ctrl0),
"Error reading PERV_CTRL0 (scom)");
}
else
{
fapi2::buffer<uint32_t> l_perv_ctrl0_cfam;
FAPI_TRY(fapi2::getCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_PERV_CTRL0_FSI,
l_perv_ctrl0_cfam),
"Error reading PERV_CTRL0 (cfam)");
l_perv_ctrl0.insert<0, 32, 0>(l_perv_ctrl0_cfam);
}
l_perv_ctrl0.writeBit<FSXCOMP_FSXLOG_PERV_CTRL0_TP_OTP_SCOM_FUSED_CORE_MODE>(
l_attr_fused_core_mode == fapi2::ENUM_ATTR_FUSED_CORE_MODE_CORE_FUSED);
l_perv_ctrl0.writeBit<FSXCOMP_FSXLOG_PERV_CTRL0_TP_EX_SINGLE_LPAR_EN_DC>(
l_attr_core_lpar_mode);
if (l_use_scom)
{
FAPI_TRY(fapi2::putScom(i_target_chip,
FSXCOMP_FSXLOG_PERV_CTRL0_RW,
l_perv_ctrl0),
"Error writing PERV_CTRL0 (scom)");
}
else
{
fapi2::buffer<uint32_t> l_perv_ctrl0_cfam;
l_perv_ctrl0_cfam.insert<0, 32, 0>(l_perv_ctrl0);
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_PERV_CTRL0_FSI,
l_perv_ctrl0_cfam),
"Error writing PERV_CTRL0 (cfam)");
}
// copy
if (l_use_scom)
{
FAPI_TRY(fapi2::getScom(i_target_chip,
FSXCOMP_FSXLOG_PERV_CTRL0_COPY_RW,
l_perv_ctrl0),
"Error reading PERV_CTRL0_COPY (scom)");
}
else
{
fapi2::buffer<uint32_t> l_perv_ctrl0_cfam;
FAPI_TRY(fapi2::getCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_PERV_CTRL0_COPY_FSI,
l_perv_ctrl0_cfam),
"Error reading PERV_CTRL0_COPY (cfam)");
l_perv_ctrl0.insert<0, 32, 0>(l_perv_ctrl0_cfam);
}
l_perv_ctrl0.writeBit<FSXCOMP_FSXLOG_PERV_CTRL0_TP_OTP_SCOM_FUSED_CORE_MODE>(
l_attr_fused_core_mode == fapi2::ENUM_ATTR_FUSED_CORE_MODE_CORE_FUSED);
l_perv_ctrl0.writeBit<FSXCOMP_FSXLOG_PERV_CTRL0_TP_EX_SINGLE_LPAR_EN_DC>(
l_attr_core_lpar_mode);
if (l_use_scom)
{
FAPI_TRY(fapi2::putScom(i_target_chip,
FSXCOMP_FSXLOG_PERV_CTRL0_COPY_RW,
l_perv_ctrl0),
"Error writing PERV_CTRL0_COPY (scom)");
}
else
{
fapi2::buffer<uint32_t> l_perv_ctrl0_cfam;
l_perv_ctrl0_cfam.insert<0, 32, 0>(l_perv_ctrl0);
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_PERV_CTRL0_COPY_FSI,
l_perv_ctrl0_cfam),
"Error writing PERV_CTRL0_COPY (cfam)");
}
}
// configure mailbox scratch registers
{
FAPI_TRY(p10_sbe_scratch_regs_update(i_target_chip, true, l_use_scom),
"Error from p10_sbe_scratch_regs_update");
}
fapi_try_exit:
FAPI_INF("p10_setup_sbe_config: Exiting ...");
return fapi2::current_err;
}
<commit_msg>add support for fused core testing in cache-contained mode<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p10/procedures/hwp/perv/p10_setup_sbe_config.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2021 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p10_setup_sbe_config.C
///
/// @brief proc setup sbe config
//------------------------------------------------------------------------------
// *HWP HW Maintainer : Anusha Reddy (anusrang@in.ibm.com)
// *HWP FW Maintainer : Raja Das (rajadas2@in.ibm.com)
// *HWP Consumed by : FSP
//------------------------------------------------------------------------------
#include <p10_setup_sbe_config.H>
#include <p10_sbe_scratch_regs.H>
#include <p10_scom_perv.H>
// description in header
fapi2::ReturnCode p10_setup_sbe_config(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
using namespace scomt::perv;
FAPI_INF("p10_setup_sbe_config:: Entering ...");
fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
// when running in Hostboot context, use SCOM to reach master only
bool l_use_scom = false;
if (fapi2::is_platform<fapi2::PLAT_HOSTBOOT>())
{
fapi2::ATTR_PROC_SBE_MASTER_CHIP_Type l_sbe_master_chip;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_SBE_MASTER_CHIP, i_target_chip, l_sbe_master_chip),
"Error from FAPI_ATTR_GET (ATTR_PROC_SBE_MASTER_CHIP");
l_use_scom = (l_sbe_master_chip == fapi2::ENUM_ATTR_PROC_SBE_MASTER_CHIP_TRUE);
}
// clear secure access bit if instructed to disable security
{
fapi2::ATTR_SECURITY_MODE_Type l_attr_security_mode;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SECURITY_MODE, FAPI_SYSTEM, l_attr_security_mode),
"Error from FAPI_ATTR_GET (ATTR_SECURITY_MODE)");
if (!l_attr_security_mode)
{
// The Secure Access Bit is only writeable on DD1 chips,
// so we won't need to put an EC level switch in here.
// Set scratch reg3 bit 6 to disable security by default now for DD1
// Set scratch reg8 bit 2 to mark scratch reg3 as valid
FAPI_DBG("Attempting to disable security");
if (l_use_scom)
{
fapi2::buffer<uint64_t> l_cbs_cs;
fapi2::buffer<uint64_t> l_read_scratch3_reg;
fapi2::buffer<uint64_t> l_read_scratch8_reg;
FAPI_TRY(fapi2::getScom(i_target_chip,
FSXCOMP_FSXLOG_CBS_CS,
l_cbs_cs),
"Error reading CBS Control/Status register (scom)");
l_cbs_cs.clearBit<FSXCOMP_FSXLOG_CBS_CS_SECURE_ACCESS_BIT>();
FAPI_TRY(fapi2::putScom(i_target_chip,
FSXCOMP_FSXLOG_CBS_CS,
l_cbs_cs),
"Error writing CBS Control/Status register (scom)");
FAPI_TRY(fapi2::getScom(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_3_RW,
l_read_scratch3_reg),
"Error reading Scratch Reg3 register");
l_read_scratch3_reg.setBit<6>();
FAPI_TRY(fapi2::putScom(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_3_RW,
l_read_scratch3_reg),
"Error writing Scratch Reg3 register");
FAPI_TRY(fapi2::getScom(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_8_RW,
l_read_scratch8_reg),
"Error reading Scratch Reg8 register");
l_read_scratch8_reg.setBit<2>();
FAPI_TRY(fapi2::putScom(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_8_RW,
l_read_scratch8_reg),
"Error writing Scratch Reg8 register");
}
else
{
fapi2::buffer<uint32_t> l_cbs_cs;
fapi2::buffer<uint32_t> l_read_scratch3_reg;
fapi2::buffer<uint32_t> l_read_scratch8_reg;
FAPI_TRY(fapi2::getCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_CBS_CS_FSI,
l_cbs_cs),
"Error reading CBS Control/Status register (cfam)");
l_cbs_cs.clearBit<FSXCOMP_FSXLOG_CBS_CS_SECURE_ACCESS_BIT>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_CBS_CS_FSI,
l_cbs_cs),
"Error writing CBS Control/Status register (cfam)");
FAPI_TRY(fapi2::getCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_3_FSI,
l_read_scratch3_reg),
"Error reading Scratch Reg3 register");
l_read_scratch3_reg.setBit<6>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_3_FSI,
l_read_scratch3_reg),
"Error writing Scratch Reg3 register");
FAPI_TRY(fapi2::getCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_8_FSI,
l_read_scratch8_reg),
"Error reading Scratch Reg8 register");
l_read_scratch8_reg.setBit<2>();
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_SCRATCH_REGISTER_8_FSI,
l_read_scratch8_reg),
"Error writing Scratch Reg8 register");
}
}
}
// set fused mode behavior
{
fapi2::ATTR_FUSED_CORE_MODE_Type l_attr_fused_core_mode;
fapi2::ATTR_CORE_LPAR_MODE_POLICY_Type l_attr_core_lpar_mode_policy;
fapi2::ATTR_CORE_LPAR_MODE_Type l_attr_core_lpar_mode;
fapi2::ATTR_CONTAINED_IPL_TYPE_Type l_attr_contained_ipl_type;
fapi2::buffer<uint64_t> l_perv_ctrl0;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CORE_LPAR_MODE_POLICY, FAPI_SYSTEM, l_attr_core_lpar_mode_policy),
"Error from FAPI_ATTR_GET (ATTR_CORE_LPAR_MODE_POLICY)");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FUSED_CORE_MODE, FAPI_SYSTEM, l_attr_fused_core_mode),
"Error from FAPI_ATTR_GET (ATTR_FUSED_CORE_MODE)");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CONTAINED_IPL_TYPE, FAPI_SYSTEM, l_attr_contained_ipl_type),
"Error from FAPI_ATTR_GET (ATTR_CONTAINED_IPL_TYPE)");
if (l_attr_core_lpar_mode_policy == fapi2::ENUM_ATTR_CORE_LPAR_MODE_POLICY_FOLLOW_FUSED_STATE)
{
if ((l_attr_fused_core_mode == fapi2::ENUM_ATTR_FUSED_CORE_MODE_CORE_FUSED) &&
(l_attr_contained_ipl_type != fapi2::ENUM_ATTR_CONTAINED_IPL_TYPE_CACHE))
{
l_attr_core_lpar_mode = fapi2::ENUM_ATTR_CORE_LPAR_MODE_LPAR_PER_CORE;
}
else
{
l_attr_core_lpar_mode = fapi2::ENUM_ATTR_CORE_LPAR_MODE_LPAR_PER_THREAD;
}
}
else if (l_attr_core_lpar_mode_policy == fapi2::ENUM_ATTR_CORE_LPAR_MODE_POLICY_LPAR_PER_CORE)
{
l_attr_core_lpar_mode = fapi2::ENUM_ATTR_CORE_LPAR_MODE_LPAR_PER_CORE;
}
else
{
l_attr_core_lpar_mode = fapi2::ENUM_ATTR_CORE_LPAR_MODE_LPAR_PER_THREAD;
}
if (l_use_scom)
{
FAPI_TRY(fapi2::getScom(i_target_chip,
FSXCOMP_FSXLOG_PERV_CTRL0_RW,
l_perv_ctrl0),
"Error reading PERV_CTRL0 (scom)");
}
else
{
fapi2::buffer<uint32_t> l_perv_ctrl0_cfam;
FAPI_TRY(fapi2::getCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_PERV_CTRL0_FSI,
l_perv_ctrl0_cfam),
"Error reading PERV_CTRL0 (cfam)");
l_perv_ctrl0.insert<0, 32, 0>(l_perv_ctrl0_cfam);
}
l_perv_ctrl0.writeBit<FSXCOMP_FSXLOG_PERV_CTRL0_TP_OTP_SCOM_FUSED_CORE_MODE>(
l_attr_fused_core_mode == fapi2::ENUM_ATTR_FUSED_CORE_MODE_CORE_FUSED);
l_perv_ctrl0.writeBit<FSXCOMP_FSXLOG_PERV_CTRL0_TP_EX_SINGLE_LPAR_EN_DC>(
l_attr_core_lpar_mode);
if (l_use_scom)
{
FAPI_TRY(fapi2::putScom(i_target_chip,
FSXCOMP_FSXLOG_PERV_CTRL0_RW,
l_perv_ctrl0),
"Error writing PERV_CTRL0 (scom)");
}
else
{
fapi2::buffer<uint32_t> l_perv_ctrl0_cfam;
l_perv_ctrl0_cfam.insert<0, 32, 0>(l_perv_ctrl0);
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_PERV_CTRL0_FSI,
l_perv_ctrl0_cfam),
"Error writing PERV_CTRL0 (cfam)");
}
// copy
if (l_use_scom)
{
FAPI_TRY(fapi2::getScom(i_target_chip,
FSXCOMP_FSXLOG_PERV_CTRL0_COPY_RW,
l_perv_ctrl0),
"Error reading PERV_CTRL0_COPY (scom)");
}
else
{
fapi2::buffer<uint32_t> l_perv_ctrl0_cfam;
FAPI_TRY(fapi2::getCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_PERV_CTRL0_COPY_FSI,
l_perv_ctrl0_cfam),
"Error reading PERV_CTRL0_COPY (cfam)");
l_perv_ctrl0.insert<0, 32, 0>(l_perv_ctrl0_cfam);
}
l_perv_ctrl0.writeBit<FSXCOMP_FSXLOG_PERV_CTRL0_TP_OTP_SCOM_FUSED_CORE_MODE>(
l_attr_fused_core_mode == fapi2::ENUM_ATTR_FUSED_CORE_MODE_CORE_FUSED);
l_perv_ctrl0.writeBit<FSXCOMP_FSXLOG_PERV_CTRL0_TP_EX_SINGLE_LPAR_EN_DC>(
l_attr_core_lpar_mode);
if (l_use_scom)
{
FAPI_TRY(fapi2::putScom(i_target_chip,
FSXCOMP_FSXLOG_PERV_CTRL0_COPY_RW,
l_perv_ctrl0),
"Error writing PERV_CTRL0_COPY (scom)");
}
else
{
fapi2::buffer<uint32_t> l_perv_ctrl0_cfam;
l_perv_ctrl0_cfam.insert<0, 32, 0>(l_perv_ctrl0);
FAPI_TRY(fapi2::putCfamRegister(i_target_chip,
FSXCOMP_FSXLOG_PERV_CTRL0_COPY_FSI,
l_perv_ctrl0_cfam),
"Error writing PERV_CTRL0_COPY (cfam)");
}
}
// configure mailbox scratch registers
{
FAPI_TRY(p10_sbe_scratch_regs_update(i_target_chip, true, l_use_scom),
"Error from p10_sbe_scratch_regs_update");
}
fapi_try_exit:
FAPI_INF("p10_setup_sbe_config: Exiting ...");
return fapi2::current_err;
}
<|endoftext|>
|
<commit_before>#include "Halide.h"
#include <stdio.h>
#include <future>
using namespace Halide;
template<typename A>
const char *string_of_type();
#define DECL_SOT(name) \
template<> \
const char *string_of_type<name>() {return #name;}
DECL_SOT(uint8_t);
DECL_SOT(int8_t);
DECL_SOT(uint16_t);
DECL_SOT(int16_t);
DECL_SOT(uint32_t);
DECL_SOT(int32_t);
DECL_SOT(float);
DECL_SOT(double);
template <typename T>
bool is_type_supported(int vec_width, const Target &target) {
DeviceAPI device = DeviceAPI::Default_GPU;
if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
device = DeviceAPI::Hexagon;
}
return target.supports_type(type_of<T>().with_lanes(vec_width), device);
}
template<typename A, typename B>
bool test(int vec_width, const Target &target) {
if (!is_type_supported<A>(vec_width, target) || !is_type_supported<B>(vec_width, target)) {
// Type not supported, return pass.
return true;
}
int W = 1024;
int H = 1;
Buffer<A> input(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
input(x, y) = (A)((rand()&0xffff)*0.1);
}
}
Var x, y;
Func f;
f(x, y) = cast<B>(input(x, y));
if (target.has_gpu_feature()) {
Var xo, xi;
f.gpu_tile(x, xo, xi, 64);
} else {
if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
// TODO: Non-native vector widths hang the compiler here.
//f.hexagon();
}
if (vec_width > 1) {
f.vectorize(x, vec_width);
}
}
Buffer<B> output = f.realize(W, H);
/*
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
printf("%d %d -> %d %d\n", x, y, (int)(input(x, y)), (int)(output(x, y)));
}
}
*/
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
bool ok = ((B)(input(x, y)) == output(x, y));
if (!ok) {
fprintf(stderr, "%s x %d -> %s x %d failed\n",
string_of_type<A>(), vec_width,
string_of_type<B>(), vec_width);
fprintf(stderr, "At %d %d, %f -> %f instead of %f\n",
x, y,
(double)(input(x, y)),
(double)(output(x, y)),
(double)((B)(input(x, y))));
return false;
}
}
}
return true;
}
template<typename A>
bool test_all(int vec_width, const Target &target) {
bool success = true;
success = success && test<A, float>(vec_width, target);
success = success && test<A, double>(vec_width, target);
success = success && test<A, uint8_t>(vec_width, target);
success = success && test<A, uint16_t>(vec_width, target);
success = success && test<A, uint32_t>(vec_width, target);
success = success && test<A, int8_t>(vec_width, target);
success = success && test<A, int16_t>(vec_width, target);
success = success && test<A, int32_t>(vec_width, target);
return success;
}
int main(int argc, char **argv) {
// We don't test this on windows, because float-to-int conversions
// on windows use _ftol2, which has its own unique calling
// convention, and older LLVMs (e.g. pnacl) don't do it right so
// you get clobbered registers.
#ifdef WIN32
printf("Not testing on windows\n");
return 0;
#endif
Target target = get_jit_target_from_environment();
// We only test power-of-two vector widths for now
Halide::Internal::ThreadPool<bool> pool;
std::vector<std::future<bool>> futures;
for (int vec_width = 1; vec_width <= 64; vec_width*=2) {
futures.push_back(pool.async([=]() {
bool success = true;
success = success && test_all<float>(vec_width, target);
success = success && test_all<double>(vec_width, target);
success = success && test_all<uint8_t>(vec_width, target);
success = success && test_all<uint16_t>(vec_width, target);
success = success && test_all<uint32_t>(vec_width, target);
success = success && test_all<int8_t>(vec_width, target);
success = success && test_all<int16_t>(vec_width, target);
success = success && test_all<int32_t>(vec_width, target);
return success;
}));
}
bool ok = true;
for (auto &f : futures) {
ok &= f.get();
}
if (!ok) return -1;
printf("Success!\n");
return 0;
}
<commit_msg>Fix some UB<commit_after>#include "Halide.h"
#include <stdio.h>
#include <future>
using namespace Halide;
template<typename A>
const char *string_of_type();
#define DECL_SOT(name) \
template<> \
const char *string_of_type<name>() {return #name;}
DECL_SOT(uint8_t);
DECL_SOT(int8_t);
DECL_SOT(uint16_t);
DECL_SOT(int16_t);
DECL_SOT(uint32_t);
DECL_SOT(int32_t);
DECL_SOT(float);
DECL_SOT(double);
template <typename T>
bool is_type_supported(int vec_width, const Target &target) {
DeviceAPI device = DeviceAPI::Default_GPU;
if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
device = DeviceAPI::Hexagon;
}
return target.supports_type(type_of<T>().with_lanes(vec_width), device);
}
template<typename A, typename B>
bool test(int vec_width, const Target &target) {
if (!is_type_supported<A>(vec_width, target) || !is_type_supported<B>(vec_width, target)) {
// Type not supported, return pass.
return true;
}
int W = 1024;
int H = 1;
Buffer<A> input(W, H);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
// Casting from an out-of-range float to an int is UB, so
// we have to pick our values a little carefully.
input(x, y) = (A)((rand() & 0xffff)/512.0);
}
}
Var x, y;
Func f;
f(x, y) = cast<B>(input(x, y));
if (target.has_gpu_feature()) {
Var xo, xi;
f.gpu_tile(x, xo, xi, 64);
} else {
if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
// TODO: Non-native vector widths hang the compiler here.
//f.hexagon();
}
if (vec_width > 1) {
f.vectorize(x, vec_width);
}
}
Buffer<B> output = f.realize(W, H);
/*
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
printf("%d %d -> %d %d\n", x, y, (int)(input(x, y)), (int)(output(x, y)));
}
}
*/
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
bool ok = ((B)(input(x, y)) == output(x, y));
if (!ok) {
fprintf(stderr, "%s x %d -> %s x %d failed\n",
string_of_type<A>(), vec_width,
string_of_type<B>(), vec_width);
fprintf(stderr, "At %d %d, %f -> %f instead of %f\n",
x, y,
(double)(input(x, y)),
(double)(output(x, y)),
(double)((B)(input(x, y))));
return false;
}
}
}
return true;
}
template<typename A>
bool test_all(int vec_width, const Target &target) {
bool success = true;
success = success && test<A, float>(vec_width, target);
success = success && test<A, double>(vec_width, target);
success = success && test<A, uint8_t>(vec_width, target);
success = success && test<A, uint16_t>(vec_width, target);
success = success && test<A, uint32_t>(vec_width, target);
success = success && test<A, int8_t>(vec_width, target);
success = success && test<A, int16_t>(vec_width, target);
success = success && test<A, int32_t>(vec_width, target);
return success;
}
int main(int argc, char **argv) {
// We don't test this on windows, because float-to-int conversions
// on windows use _ftol2, which has its own unique calling
// convention, and older LLVMs (e.g. pnacl) don't do it right so
// you get clobbered registers.
#ifdef WIN32
printf("Not testing on windows\n");
return 0;
#endif
Target target = get_jit_target_from_environment();
// We only test power-of-two vector widths for now
Halide::Internal::ThreadPool<bool> pool;
std::vector<std::future<bool>> futures;
for (int vec_width = 1; vec_width <= 64; vec_width*=2) {
futures.push_back(pool.async([=]() {
bool success = true;
success = success && test_all<float>(vec_width, target);
success = success && test_all<double>(vec_width, target);
success = success && test_all<uint8_t>(vec_width, target);
success = success && test_all<uint16_t>(vec_width, target);
success = success && test_all<uint32_t>(vec_width, target);
success = success && test_all<int8_t>(vec_width, target);
success = success && test_all<int16_t>(vec_width, target);
success = success && test_all<int32_t>(vec_width, target);
return success;
}));
}
bool ok = true;
for (auto &f : futures) {
ok &= f.get();
}
if (!ok) return -1;
printf("Success!\n");
return 0;
}
<|endoftext|>
|
<commit_before>#include <string>
#include "cmysql_database.h"
#include <exception>
#include <stdexcept>
#include "database.h"
namespace Core {
#ifdef USE_MYSQL_ONE_INSTANCE
IDatabasePool &databasePool = databasePoolFilename<Config::Filename>::getInstance();
#endif
bool CMySQL_Row::getString(std::string const &name, std::string &data) {
return getData<std::string>(name, data);
}
bool CMySQL_Row::getInt(std::string const &name, uint32_t &data) {
return getData<uint32_t>(name, data);
}
bool CMySQL_Row::getFloat(std::string const &name, float &data) {
return getData<float>(name, data);
}
CMySQL_Result::CMySQL_Result(const mysqlpp::StoreQueryResult &_res)
: IResult() {
for (auto const &it : _res)
rows_.emplace_back(std::unique_ptr<IRow>(new CMySQL_Row(it)));
}
bool CMySQL_Result::incrementRow() {
uint32_t tmp = current_row_;
current_row_ =
current_row_ >= rows_.size() ? rows_.size() - 1 : current_row_ + 1;
return tmp == rows_.size();
}
bool CMySQL_Result::getString(std::string const &name, std::string &data) {
return rows_[current_row_]->getString(name, data);
}
bool CMySQL_Result::getInt(std::string const &name, uint32_t &data) {
return rows_[current_row_]->getInt(name, data);
}
bool CMySQL_Result::getFloat(std::string const &name, float &data) {
return rows_[current_row_]->getFloat(name, data);
}
CMySQL_Database::CMySQL_Database()
: hostname_(""),
database_(""),
username_(""),
password_(""),
connected_(false) {
logger_ = CLog::GetLogger(log_type::DATABASE);
}
CMySQL_Database::~CMySQL_Database() {
if (auto log = logger_.lock())
log->debug() << "db shared_ptr used by " << log.use_count() - 1;
logger_.reset();
}
CMySQL_Database::CMySQL_Database(std::string _host, std::string _database,
std::string _user, std::string _password)
: hostname_(_host),
database_(_database),
username_(_user),
password_(_password),
connected_(false) {
try {
logger_ = CLog::GetLogger(log_type::DATABASE);
conn_.connect(database_.c_str(), hostname_.c_str(), username_.c_str(),
password_.c_str());
if (auto log = logger_.lock()) log->notice() << "Connected to database";
} catch (const std::exception &e) {
if (auto log = logger_.lock())
log->critical() << Color::FG_RED
<< "Error while connecting to the database: "
<< conn_.error() << Color::CL_RESET;
throw e;
}
connected_ = true;
}
void CMySQL_Database::Connect(std::string _host, std::string _database,
std::string _user, std::string _password) {
hostname_ = (_host);
database_ = (_database);
username_ = (_user);
password_ = (_password);
connected_ = false;
try {
conn_.set_option(new MultiStatementsOption(true));
conn_.connect(database_.c_str(), hostname_.c_str(), username_.c_str(),
password_.c_str());
} catch (const std::exception &e) {
if (auto log = logger_.lock())
log->critical() << Color::FG_RED
<< "Error while connecting to the database: "
<< conn_.error() << Color::CL_RESET;
throw e;
}
connected_ = true;
}
std::unique_ptr<IResult> CMySQL_Database::QStore(std::string _query) {
if (!connected_) {
if (auto log = logger_.lock())
log->critical() << Color::FG_RED
<< "Error while executing the query: " << _query.c_str()
<< ": not connected" << Color::CL_RESET;
throw std::runtime_error("Error not connected");
}
std::lock_guard<std::mutex> lock(mutex_);
conn_.thread_start(); // This is if we pass the database around different
// threads
if (auto log = logger_.lock())
log->debug() << "Executing query: " << _query.c_str();
mysqlpp::Query query = conn_.query(_query.c_str());
std::unique_ptr<IResult> result(new CMySQL_Result(query.store()));
while (query.more_results()) {
auto tmp = query.store_next();
}
return result;
}
void CMySQL_Database::QExecute(std::string _query) {
if (!connected_) {
if (auto log = logger_.lock())
log->critical() << Color::FG_RED
<< "Error while executing the query: " << _query.c_str()
<< ": not connected" << Color::CL_RESET;
throw std::runtime_error("Error not connected");
}
std::lock_guard<std::mutex> lock(mutex_);
conn_.thread_start(); // This is if we pass the database around different
// threads
if (auto log = logger_.lock())
log->debug() << "Executing query: " << _query.c_str();
auto query = conn_.query(_query.c_str());
query.exec(_query.c_str());
}
}
<commit_msg>Added namespace<commit_after>#include <string>
#include "cmysql_database.h"
#include <exception>
#include <stdexcept>
#include "database.h"
namespace Core {
#ifdef USE_MYSQL_ONE_INSTANCE
IDatabasePool &databasePool = databasePoolFilename<Config::Filename>::getInstance();
#endif
bool CMySQL_Row::getString(std::string const &name, std::string &data) {
return getData<std::string>(name, data);
}
bool CMySQL_Row::getInt(std::string const &name, uint32_t &data) {
return getData<uint32_t>(name, data);
}
bool CMySQL_Row::getFloat(std::string const &name, float &data) {
return getData<float>(name, data);
}
CMySQL_Result::CMySQL_Result(const mysqlpp::StoreQueryResult &_res)
: IResult() {
for (auto const &it : _res)
rows_.emplace_back(std::unique_ptr<IRow>(new CMySQL_Row(it)));
}
bool CMySQL_Result::incrementRow() {
uint32_t tmp = current_row_;
current_row_ =
current_row_ >= rows_.size() ? rows_.size() - 1 : current_row_ + 1;
return tmp == rows_.size();
}
bool CMySQL_Result::getString(std::string const &name, std::string &data) {
return rows_[current_row_]->getString(name, data);
}
bool CMySQL_Result::getInt(std::string const &name, uint32_t &data) {
return rows_[current_row_]->getInt(name, data);
}
bool CMySQL_Result::getFloat(std::string const &name, float &data) {
return rows_[current_row_]->getFloat(name, data);
}
CMySQL_Database::CMySQL_Database()
: hostname_(""),
database_(""),
username_(""),
password_(""),
connected_(false) {
logger_ = CLog::GetLogger(log_type::DATABASE);
}
CMySQL_Database::~CMySQL_Database() {
if (auto log = logger_.lock())
log->debug() << "db shared_ptr used by " << log.use_count() - 1;
logger_.reset();
}
CMySQL_Database::CMySQL_Database(std::string _host, std::string _database,
std::string _user, std::string _password)
: hostname_(_host),
database_(_database),
username_(_user),
password_(_password),
connected_(false) {
try {
logger_ = CLog::GetLogger(log_type::DATABASE);
conn_.connect(database_.c_str(), hostname_.c_str(), username_.c_str(),
password_.c_str());
if (auto log = logger_.lock()) log->notice() << "Connected to database";
} catch (const std::exception &e) {
if (auto log = logger_.lock())
log->critical() << Color::FG_RED
<< "Error while connecting to the database: "
<< conn_.error() << Color::CL_RESET;
throw e;
}
connected_ = true;
}
void CMySQL_Database::Connect(std::string _host, std::string _database,
std::string _user, std::string _password) {
hostname_ = (_host);
database_ = (_database);
username_ = (_user);
password_ = (_password);
connected_ = false;
try {
conn_.set_option(new mysqlpp::MultiStatementsOption(true));
conn_.connect(database_.c_str(), hostname_.c_str(), username_.c_str(),
password_.c_str());
} catch (const std::exception &e) {
if (auto log = logger_.lock())
log->critical() << Color::FG_RED
<< "Error while connecting to the database: "
<< conn_.error() << Color::CL_RESET;
throw e;
}
connected_ = true;
}
std::unique_ptr<IResult> CMySQL_Database::QStore(std::string _query) {
if (!connected_) {
if (auto log = logger_.lock())
log->critical() << Color::FG_RED
<< "Error while executing the query: " << _query.c_str()
<< ": not connected" << Color::CL_RESET;
throw std::runtime_error("Error not connected");
}
std::lock_guard<std::mutex> lock(mutex_);
conn_.thread_start(); // This is if we pass the database around different
// threads
if (auto log = logger_.lock())
log->debug() << "Executing query: " << _query.c_str();
mysqlpp::Query query = conn_.query(_query.c_str());
std::unique_ptr<IResult> result(new CMySQL_Result(query.store()));
while (query.more_results()) {
auto tmp = query.store_next();
}
return result;
}
void CMySQL_Database::QExecute(std::string _query) {
if (!connected_) {
if (auto log = logger_.lock())
log->critical() << Color::FG_RED
<< "Error while executing the query: " << _query.c_str()
<< ": not connected" << Color::CL_RESET;
throw std::runtime_error("Error not connected");
}
std::lock_guard<std::mutex> lock(mutex_);
conn_.thread_start(); // This is if we pass the database around different
// threads
if (auto log = logger_.lock())
log->debug() << "Executing query: " << _query.c_str();
auto query = conn_.query(_query.c_str());
query.exec(_query.c_str());
}
}
<|endoftext|>
|
<commit_before>#include "xchainer/python/array.h"
#include <algorithm>
#include <nonstd/optional.hpp>
#include <pybind11/numpy.h>
#include <pybind11/operators.h>
#include <pybind11/stl.h>
#include "xchainer/array.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"
// Optional type caster
// http://pybind11.readthedocs.io/en/stable/advanced/cast/stl.html
namespace pybind11 { namespace detail {
template <typename T>
struct type_caster<nonstd::optional<T>> : optional_caster<nonstd::optional<T>> {};
}}
namespace xchainer {
namespace py = pybind11;
Dtype NumpyDtypeToDtype(const py::dtype& npdtype) {
switch (npdtype.kind()) {
case 'b':
return Dtype::kBool;
case 'i':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kInt8;
case 2:
return Dtype::kInt16;
case 4:
return Dtype::kInt32;
case 8:
return Dtype::kInt64;
default:
break;
}
break;
case 'u':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kUInt8;
default:
break;
}
break;
case 'f':
switch (npdtype.itemsize()) {
case 4:
return Dtype::kFloat32;
case 8:
return Dtype::kFloat64;
default:
break;
}
break;
default:
break;
}
throw DtypeError("unsupported NumPy dtype");
}
Array MakeArray(const Shape& shape, Dtype dtype, py::list list) {
auto total_size = shape.total_size();
auto bytes = GetElementSize(dtype) * total_size;
if (static_cast<size_t>(total_size) != list.size()) {
throw DimensionError("Invalid data length");
}
// Allocate a buffer and copy data
std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes);
VisitDtype(dtype, [&](auto pt) {
using T = typename decltype(pt)::type;
std::transform(list.begin(), list.end(), static_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); });
});
return Array::FromBuffer(shape, dtype, ptr);
}
std::unique_ptr<Array> MakeArray(py::array array) {
if ((array.flags() & py::array::c_style) == 0) {
throw DimensionError("cannot convert non-contiguous NumPy array to Array");
}
Dtype dtype = NumpyDtypeToDtype(array.dtype());
py::buffer_info info = array.request();
Shape shape(info.shape);
// data holds the copy of py::array which in turn references the NumPy array and the buffer is therefore not released
std::shared_ptr<void> data(std::make_shared<py::array>(std::move(array)), array.mutable_data());
return std::make_unique<Array>(Array::FromBuffer(shape, dtype, data));
}
py::buffer_info MakeNumpyArrayFromArray(Array& self) {
if (!self.is_contiguous()) {
throw DimensionError("cannot convert non-contiguous Array to NumPy array");
}
int64_t itemsize{GetElementSize(self.dtype())};
const Shape& shape = self.shape();
// compute C-contiguous strides
size_t ndim = self.ndim();
std::vector<size_t> strides(ndim);
if (ndim > 0) {
std::partial_sum(shape.crbegin(), shape.crend() - 1, strides.rbegin() + 1, std::multiplies<size_t>());
strides.back() = 1;
std::transform(strides.crbegin(), strides.crend(), strides.rbegin(), [&itemsize](size_t item) { return item * itemsize; });
}
return py::buffer_info(self.data().get(), itemsize, std::string(1, GetCharCode(self.dtype())), ndim, shape, strides);
}
void InitXchainerArray(pybind11::module& m) {
py::class_<Array>{m, "Array", py::buffer_protocol()}
.def(py::init(py::overload_cast<const Shape&, Dtype, py::list>(&MakeArray)))
.def(py::init(py::overload_cast<py::array>(&MakeArray)))
.def_buffer(&MakeNumpyArrayFromArray)
.def("view", &Array::MakeView)
.def(py::self += py::self)
.def(py::self *= py::self)
.def(py::self + py::self)
.def(py::self * py::self)
.def("__repr__", static_cast<std::string (Array::*)() const>(&Array::ToString))
.def("cleargrad", &Array::ClearGrad)
.def_property("requires_grad", &Array::requires_grad, &Array::set_requires_grad)
.def_property("grad", &Array::grad, [](Array& self, const Array& grad) { self.set_grad(grad.MakeView()); })
.def_property_readonly("dtype", &Array::dtype)
.def_property_readonly("element_bytes", &Array::element_bytes)
.def_property_readonly("is_contiguous", &Array::is_contiguous)
.def_property_readonly("ndim", &Array::ndim)
.def_property_readonly("offset", &Array::offset)
.def_property_readonly("shape", &Array::shape)
.def_property_readonly("total_bytes", &Array::total_bytes)
.def_property_readonly("total_size", &Array::total_size)
.def_property_readonly("debug_flat_data",
[](const Array& self) { // This method is a stub for testing
py::list list;
auto size = self.total_size();
// Copy data into the list
VisitDtype(self.dtype(), [&](auto pt) {
using T = typename decltype(pt)::type;
const T& data = *std::static_pointer_cast<const T>(self.data());
for (int64_t i = 0; i < size; ++i) {
list.append((&data)[i]);
}
});
return list;
});
}
} // namespace xchainer
<commit_msg>clang-format<commit_after>#include "xchainer/python/array.h"
#include <algorithm>
#include <nonstd/optional.hpp>
#include <pybind11/numpy.h>
#include <pybind11/operators.h>
#include <pybind11/stl.h>
#include "xchainer/array.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"
// Optional type caster
// http://pybind11.readthedocs.io/en/stable/advanced/cast/stl.html
namespace pybind11 {
namespace detail {
template <typename T>
struct type_caster<nonstd::optional<T>> : optional_caster<nonstd::optional<T>> {};
}
}
namespace xchainer {
namespace py = pybind11;
Dtype NumpyDtypeToDtype(const py::dtype& npdtype) {
switch (npdtype.kind()) {
case 'b':
return Dtype::kBool;
case 'i':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kInt8;
case 2:
return Dtype::kInt16;
case 4:
return Dtype::kInt32;
case 8:
return Dtype::kInt64;
default:
break;
}
break;
case 'u':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kUInt8;
default:
break;
}
break;
case 'f':
switch (npdtype.itemsize()) {
case 4:
return Dtype::kFloat32;
case 8:
return Dtype::kFloat64;
default:
break;
}
break;
default:
break;
}
throw DtypeError("unsupported NumPy dtype");
}
Array MakeArray(const Shape& shape, Dtype dtype, py::list list) {
auto total_size = shape.total_size();
auto bytes = GetElementSize(dtype) * total_size;
if (static_cast<size_t>(total_size) != list.size()) {
throw DimensionError("Invalid data length");
}
// Allocate a buffer and copy data
std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes);
VisitDtype(dtype, [&](auto pt) {
using T = typename decltype(pt)::type;
std::transform(list.begin(), list.end(), static_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); });
});
return Array::FromBuffer(shape, dtype, ptr);
}
std::unique_ptr<Array> MakeArray(py::array array) {
if ((array.flags() & py::array::c_style) == 0) {
throw DimensionError("cannot convert non-contiguous NumPy array to Array");
}
Dtype dtype = NumpyDtypeToDtype(array.dtype());
py::buffer_info info = array.request();
Shape shape(info.shape);
// data holds the copy of py::array which in turn references the NumPy array and the buffer is therefore not released
std::shared_ptr<void> data(std::make_shared<py::array>(std::move(array)), array.mutable_data());
return std::make_unique<Array>(Array::FromBuffer(shape, dtype, data));
}
py::buffer_info MakeNumpyArrayFromArray(Array& self) {
if (!self.is_contiguous()) {
throw DimensionError("cannot convert non-contiguous Array to NumPy array");
}
int64_t itemsize{GetElementSize(self.dtype())};
const Shape& shape = self.shape();
// compute C-contiguous strides
size_t ndim = self.ndim();
std::vector<size_t> strides(ndim);
if (ndim > 0) {
std::partial_sum(shape.crbegin(), shape.crend() - 1, strides.rbegin() + 1, std::multiplies<size_t>());
strides.back() = 1;
std::transform(strides.crbegin(), strides.crend(), strides.rbegin(), [&itemsize](size_t item) { return item * itemsize; });
}
return py::buffer_info(self.data().get(), itemsize, std::string(1, GetCharCode(self.dtype())), ndim, shape, strides);
}
void InitXchainerArray(pybind11::module& m) {
py::class_<Array>{m, "Array", py::buffer_protocol()}
.def(py::init(py::overload_cast<const Shape&, Dtype, py::list>(&MakeArray)))
.def(py::init(py::overload_cast<py::array>(&MakeArray)))
.def_buffer(&MakeNumpyArrayFromArray)
.def("view", &Array::MakeView)
.def(py::self += py::self)
.def(py::self *= py::self)
.def(py::self + py::self)
.def(py::self * py::self)
.def("__repr__", static_cast<std::string (Array::*)() const>(&Array::ToString))
.def("cleargrad", &Array::ClearGrad)
.def_property("requires_grad", &Array::requires_grad, &Array::set_requires_grad)
.def_property("grad", &Array::grad,
[](Array& self, Array* grad) {
if (grad) {
self.set_grad(grad->MakeView());
} else {
self.ClearGrad();
}
})
.def_property_readonly("dtype", &Array::dtype)
.def_property_readonly("element_bytes", &Array::element_bytes)
.def_property_readonly("is_contiguous", &Array::is_contiguous)
.def_property_readonly("ndim", &Array::ndim)
.def_property_readonly("offset", &Array::offset)
.def_property_readonly("shape", &Array::shape)
.def_property_readonly("total_bytes", &Array::total_bytes)
.def_property_readonly("total_size", &Array::total_size)
.def_property_readonly("debug_flat_data",
[](const Array& self) { // This method is a stub for testing
py::list list;
auto size = self.total_size();
// Copy data into the list
VisitDtype(self.dtype(), [&](auto pt) {
using T = typename decltype(pt)::type;
const T& data = *std::static_pointer_cast<const T>(self.data());
for (int64_t i = 0; i < size; ++i) {
list.append((&data)[i]);
}
});
return list;
});
}
} // namespace xchainer
<|endoftext|>
|
<commit_before>#include <FImage.h>
#include <sys/time.h>
using namespace FImage;
template<typename A>
const char *string_of_type();
#define DECL_SOT(name) \
template<> \
const char *string_of_type<name>() {return #name;}
DECL_SOT(uint8_t);
DECL_SOT(int8_t);
DECL_SOT(uint16_t);
DECL_SOT(int16_t);
DECL_SOT(uint32_t);
DECL_SOT(int32_t);
DECL_SOT(float);
DECL_SOT(double);
double currentTime() {
timeval t;
gettimeofday(&t, NULL);
return t.tv_sec * 1000.0 + t.tv_usec / 1000.0f;
}
template<typename A>
bool test(int vec_width, int attempts = 0) {
int W = vec_width*1;
int H = 40000;
Image<A> input(W, H+20);
for (int y = 0; y < H+20; y++) {
for (int x = 0; x < W; x++) {
input(x, y) = (A)(rand()*0.125 + 1.0);
}
}
Var x, y;
Func f, g;
Expr e = input(x, y);
for (int i = 1; i < 10; i++) {
e = e + input(x, y+i);
}
for (int i = 10; i >= 0; i--) {
e = e + input(x, y+i);
}
f(x, y) = e;
g(x, y) = e;
f.vectorize(x, vec_width);
Image<A> outputg = g.realize(W, H);
Image<A> outputf = f.realize(W, H);
double t1 = currentTime();
g.realize(outputg);
double t2 = currentTime();
f.realize(outputf);
double t3 = currentTime();
printf("%g %g %g\n", t1, t2, t3);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
if (outputf(x, y) != outputg(x, y)) {
printf("%s x %d failed: %d vs %d\n",
string_of_type<A>(), vec_width,
(int)outputf(x, y),
(int)outputg(x, y)
);
return false;
}
}
}
printf("Vectorized vs scalar (%s x %d): %1.3gms %1.3gms\n", string_of_type<A>(), vec_width, (t3-t2), (t2-t1));
if ((t3 - t2) > (t2 - t1)) {
if (attempts < 1) {
if (test<A>(vec_width, attempts+1)) return true;
} else {
printf("For 5 attempts, vectorizing was slower than not vectorizing: %f vs %f\n",
t3-t2, t2-t1);
return false;
}
}
return true;
}
int main(int argc, char **argv) {
bool ok = true;
//test<uint8_t>(16);
//test<uint8_t>(16);
test<double>(2);
test<float>(4);
test<uint8_t>(16);
test<int8_t>(16);
test<uint16_t>(8);
test<int16_t>(8);
test<uint32_t>(4);
test<int32_t>(4);
return 0;
// We only support power-of-two vector widths for now
for (int vec_width = 2; vec_width < 32; vec_width*=2) {
ok = ok && test<float>(vec_width);
ok = ok && test<double>(vec_width);
ok = ok && test<uint8_t>(vec_width);
ok = ok && test<int8_t>(vec_width);
ok = ok && test<uint16_t>(vec_width);
ok = ok && test<int16_t>(vec_width);
ok = ok && test<uint32_t>(vec_width);
ok = ok && test<int32_t>(vec_width);
}
if (!ok) return -1;
printf("Success!\n");
return 0;
}
<commit_msg>Gave up on non-native vector widths for now.<commit_after>#include <FImage.h>
#include <sys/time.h>
using namespace FImage;
template<typename A>
const char *string_of_type();
#define DECL_SOT(name) \
template<> \
const char *string_of_type<name>() {return #name;}
DECL_SOT(uint8_t);
DECL_SOT(int8_t);
DECL_SOT(uint16_t);
DECL_SOT(int16_t);
DECL_SOT(uint32_t);
DECL_SOT(int32_t);
DECL_SOT(float);
DECL_SOT(double);
double currentTime() {
timeval t;
gettimeofday(&t, NULL);
return t.tv_sec * 1000.0 + t.tv_usec / 1000.0f;
}
template<typename A>
bool test(int vec_width, int attempts = 0) {
int W = vec_width*1;
int H = 40000;
Image<A> input(W, H+20);
for (int y = 0; y < H+20; y++) {
for (int x = 0; x < W; x++) {
input(x, y) = (A)(rand()*0.125 + 1.0);
}
}
Var x, y;
Func f, g;
Expr e = input(x, y);
for (int i = 1; i < 10; i++) {
e = e + input(x, y+i);
}
for (int i = 10; i >= 0; i--) {
e = e + input(x, y+i);
}
f(x, y) = e;
g(x, y) = e;
f.vectorize(x, vec_width);
Image<A> outputg = g.realize(W, H);
Image<A> outputf = f.realize(W, H);
double t1 = currentTime();
for (int i = 0; i < 10; i++) {
g.realize(outputg);
}
double t2 = currentTime();
for (int i = 0; i < 10; i++) {
f.realize(outputf);
}
double t3 = currentTime();
printf("%g %g %g\n", t1, t2, t3);
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
if (outputf(x, y) != outputg(x, y)) {
printf("%s x %d failed: %d vs %d\n",
string_of_type<A>(), vec_width,
(int)outputf(x, y),
(int)outputg(x, y)
);
return false;
}
}
}
printf("Vectorized vs scalar (%s x %d): %1.3gms %1.3gms. Speedup = %1.3f\n", string_of_type<A>(), vec_width, (t3-t2), (t2-t1), (t2-t1)/(t3-t2));
if ((t3 - t2) > (t2 - t1)) {
return false;
}
return true;
}
int main(int argc, char **argv) {
bool ok = true;
// Only native vector widths for now
ok = ok && test<float>(4);
ok = ok && test<double>(2);
ok = ok && test<uint8_t>(16);
ok = ok && test<int8_t>(16);
ok = ok && test<uint16_t>(8);
ok = ok && test<int16_t>(8);
ok = ok && test<uint32_t>(4);
ok = ok && test<int32_t>(4);
if (!ok) return -1;
printf("Success!\n");
return 0;
}
<|endoftext|>
|
<commit_before>/* cbr
* FairQueue.hpp
*
* Copyright (c) 2009, Ewen Cheslack-Postava
* 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 cbr nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _FAIR_MESSAGE_QUEUE_HPP_
#define _FAIR_MESSAGE_QUEUE_HPP_
#include "Time.hpp"
#include "Queue.hpp"
namespace CBR {
template<class MessageQueue> class Weight {
public:
template <class MessageType> uint32 operator()(MessageQueue&mq,const MessageType*nil)const {
return mq.empty()?nil->size():mq.front()->size();
}
};
template <class Message,class Key,class TQueue, class WeightFunction=Weight<TQueue > > class FairQueue {
public:
struct ServerQueueInfo {
private:
ServerQueueInfo():nextFinishTime(0) {
messageQueue=NULL;
weight=1.0;
}
public:
ServerQueueInfo(Key serverName, TQueue* queue, float w)
: messageQueue(queue), weight(w), nextFinishTime(0),mKey(serverName) {}
TQueue* messageQueue;
float weight;
Time nextFinishTime;
Key mKey;
};
typedef std::map<Key, ServerQueueInfo> ServerQueueInfoMap;
unsigned int mEmptyQueueMessageLength;
bool mRenormalizeWeight;
typedef TQueue MessageQueue;
FairQueue(unsigned int emptyQueueMessageLength, bool renormalizeWeight)
:mEmptyQueueMessageLength(emptyQueueMessageLength),
mRenormalizeWeight(renormalizeWeight),
mTotalWeight(0),
mCurrentVirtualTime(0),
mServerQueues()
{
mNullMessage = new Message(mEmptyQueueMessageLength);
}
~FairQueue() {
typename ServerQueueInfoMap::iterator it = mServerQueues.begin();
for(; it != mServerQueues.end(); it++) {
ServerQueueInfo* queue_info = &it->second;
delete queue_info->messageQueue;
}
}
void addQueue(MessageQueue *mq, Key server, float weight) {
//assert(mq->empty());
ServerQueueInfo queue_info (server, mq, weight);
mTotalWeight += weight;
mServerQueues.insert(std::pair<Key,ServerQueueInfo>(server, queue_info));
}
void setQueueWeight(Key server, float weight) {
typename ServerQueueInfoMap::iterator where=mServerQueues.find(server);
bool retval=( where != mServerQueues.end() );
if (where != mServerQueues.end()) {
mTotalWeight -= where->second.weight;
mTotalWeight += weight;
where->second.weight = weight;
}
}
float getQueueWeight(Key server) const {
typename ServerQueueInfoMap::const_iterator where=mServerQueues.find(server);
if (where != mServerQueues.end()) {
return where->second.weight;
}
return 0;
}
bool deprioritize(Key server,float factor, float affine, float minval,float maxval) {
return changepriority(server,factor,affine,minval,maxval,true);
}
bool reprioritize(Key server,float factor, float affine, float minval,float maxval) {
return changepriority(server,factor,affine,minval,maxval,false);
}
bool changepriority(Key server,float factor, float affine, float minval,float maxval, bool passOnDeprioritize) {
typename ServerQueueInfoMap::iterator where=mServerQueues.find(server);
if ( where == mServerQueues.end() )
return false;
float oldweight=where->second.weight;
oldweight*=factor;
oldweight+=affine;
if (oldweight<minval){
oldweight=minval;
}
this->setQueueWeight(server,oldweight);
return true;
}
bool removeQueue(Key server) {
typename ServerQueueInfoMap::iterator where=mServerQueues.find(server);
bool retval=( where != mServerQueues.end() );
if (retval) {
mTotalWeight -= where->second.weight;
delete where->second.messageQueue;
mServerQueues.erase(where);
}
return retval;
}
bool hasQueue(Key server) const{
return ( mServerQueues.find(server) != mServerQueues.end() );
}
unsigned int numQueues() const {
return (unsigned int)mServerQueues.size();
}
QueueEnum::PushResult push(Key dest_server, Message *msg){
typename ServerQueueInfoMap::iterator qi_it = mServerQueues.find(dest_server);
assert( qi_it != mServerQueues.end() );
ServerQueueInfo* queue_info = &qi_it->second;
if (queue_info->messageQueue->empty()) {
if (!mEmptyQueueMessageLength) {
mTotalWeight+=queue_info->weight;
}
queue_info->nextFinishTime = finishTime(msg->size(), queue_info->weight);
}
return queue_info->messageQueue->push(msg);
}
// Returns the next message to deliver, given the number of bytes available for transmission
// \param bytes number of bytes available; updated appropriately for intermediate null messages when returns
// \returns the next message, or NULL if the queue is empty or the next message cannot be handled
// given the number of bytes allocated
Message* front(uint64* bytes, Key*keyAtFront) {
Message* result = NULL;
Time vftime(0);
ServerQueueInfo* min_queue_info = NULL;
nextMessage(bytes, &result, &vftime, &min_queue_info);
if (result != NULL) {
assert( *bytes >= result->size() );
*keyAtFront=min_queue_info->mKey;
return result;
}
return NULL;
}
// Returns the next message to deliver, given the number of bytes available for transmission
// \param bytes number of bytes available; updated appropriately when returns
// \returns the next message, or NULL if the queue is empty or the next message cannot be handled
// given the number of bytes allotted
Message* pop(uint64* bytes) {
Message* result = NULL;
Time vftime(0);
ServerQueueInfo* min_queue_info = NULL;
nextMessage(bytes, &result, &vftime, &min_queue_info);
if (result != NULL) {
mCurrentVirtualTime = vftime;
assert(min_queue_info != NULL);
assert( *bytes >= result->size() );
*bytes -= result->size();
min_queue_info->messageQueue->pop();
uint32 serviceEmptyQueue = mEmptyQueueMessageLength;
// Remove the weight if the queue is now exhausted
if (min_queue_info->messageQueue->empty() && !serviceEmptyQueue)
mTotalWeight -= min_queue_info->weight;
// update the next finish time if there's anything in the queue
if (serviceEmptyQueue || !min_queue_info->messageQueue->empty())
min_queue_info->nextFinishTime = finishTime(WeightFunction()(*min_queue_info->messageQueue,mNullMessage), min_queue_info->weight);
}
return result;
}
bool empty() const {
// FIXME we could track a count ourselves instead of checking all these queues
for(typename ServerQueueInfoMap::const_iterator it = mServerQueues.begin(); it != mServerQueues.end(); it++) {
const ServerQueueInfo* queue_info = &it->second;
if (!queue_info->messageQueue->empty())
return false;
}
return true;
}
// Returns the total amount of space that can be allocated for the destination
uint32 maxSize(Key dest) const {
typename ServerQueueInfoMap::const_iterator it = mServerQueues.find(dest);
if (it == mServerQueues.end()) return 0;
return it->second.messageQueue->maxSize();
}
// Returns the total amount of space currently used for the destination
uint32 size(Key dest) const {
typename ServerQueueInfoMap::const_iterator it = mServerQueues.find(dest);
if (it == mServerQueues.end()) return 0;
return it->second.messageQueue->size();
}
protected:
// Retrieves the next message to deliver, along with its virtual finish time, given the number of bytes available
// for transmission. May update bytes for null messages, but does not update it to remove bytes to be used for
// the returned message. Returns null either if the number of bytes is not sufficient or the queue is empty.
void nextMessage(uint64* bytes, Message** result_out, Time* vftime_out, ServerQueueInfo** min_queue_info_out) {
uint32 serviceEmptyQueue = mEmptyQueueMessageLength;
Message* result = mNullMessage;
while( result == mNullMessage) {
// Find the non-empty queue with the earliest finish time
ServerQueueInfo* min_queue_info = NULL;
for(typename ServerQueueInfoMap::iterator it = mServerQueues.begin(); it != mServerQueues.end(); it++) {
ServerQueueInfo* queue_info = &it->second;
if (queue_info->messageQueue->empty()&&!serviceEmptyQueue) continue;
if (min_queue_info == NULL || queue_info->nextFinishTime < min_queue_info->nextFinishTime)
min_queue_info = queue_info;
}
// If we actually have something to deliver, deliver it
result = NULL;
if (min_queue_info) {
*min_queue_info_out = min_queue_info;
*vftime_out = min_queue_info->nextFinishTime;
result = mNullMessage;
if (!min_queue_info->messageQueue->empty()) {
if (*bytes < min_queue_info->messageQueue->front()->size())
break;
result = min_queue_info->messageQueue->front();
} else {
if (*bytes < result->size())
break;
}
if (result == mNullMessage) {
uint32 message_size = result->size();
assert (message_size <= *bytes);
*bytes -= message_size;
mCurrentVirtualTime = min_queue_info->nextFinishTime;
// update the next finish time if there's anything in the queue
if (serviceEmptyQueue)
min_queue_info->nextFinishTime = finishTime(WeightFunction()(*min_queue_info->messageQueue,mNullMessage), min_queue_info->weight);
}
}
}
if (result == mNullMessage)
*result_out = NULL;
else
*result_out = result;
}
Time finishTime(uint32 size, float weight) const{
float queue_frac = weight;
Duration transmitTime = Duration::seconds( size / queue_frac );
if (transmitTime == Duration(0)) transmitTime = Duration(1); // just make sure we take *some* time
return mCurrentVirtualTime + transmitTime;
}
protected:
uint32 mRate;
uint32 mTotalWeight;
Time mCurrentVirtualTime;
ServerQueueInfoMap mServerQueues;
Message* mNullMessage;
}; // class FairQueue
} // namespace CBR
#endif //_FAIR_MESSAGE_QUEUE_HPP_
<commit_msg>Don't track total weight in the FairQueue; it wasn't being used anywhere and shouldn't be needed.<commit_after>/* cbr
* FairQueue.hpp
*
* Copyright (c) 2009, Ewen Cheslack-Postava
* 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 cbr nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _FAIR_MESSAGE_QUEUE_HPP_
#define _FAIR_MESSAGE_QUEUE_HPP_
#include "Time.hpp"
#include "Queue.hpp"
namespace CBR {
template<class MessageQueue> class Weight {
public:
template <class MessageType> uint32 operator()(MessageQueue&mq,const MessageType*nil)const {
return mq.empty()?nil->size():mq.front()->size();
}
};
template <class Message,class Key,class TQueue, class WeightFunction=Weight<TQueue > > class FairQueue {
public:
struct ServerQueueInfo {
private:
ServerQueueInfo():nextFinishTime(0) {
messageQueue=NULL;
weight=1.0;
}
public:
ServerQueueInfo(Key serverName, TQueue* queue, float w)
: messageQueue(queue), weight(w), nextFinishTime(0),mKey(serverName) {}
TQueue* messageQueue;
float weight;
Time nextFinishTime;
Key mKey;
};
typedef std::map<Key, ServerQueueInfo> ServerQueueInfoMap;
unsigned int mEmptyQueueMessageLength;
bool mRenormalizeWeight;
typedef TQueue MessageQueue;
FairQueue(unsigned int emptyQueueMessageLength, bool renormalizeWeight)
:mEmptyQueueMessageLength(emptyQueueMessageLength),
mRenormalizeWeight(renormalizeWeight),
mCurrentVirtualTime(0),
mServerQueues()
{
mNullMessage = new Message(mEmptyQueueMessageLength);
}
~FairQueue() {
typename ServerQueueInfoMap::iterator it = mServerQueues.begin();
for(; it != mServerQueues.end(); it++) {
ServerQueueInfo* queue_info = &it->second;
delete queue_info->messageQueue;
}
}
void addQueue(MessageQueue *mq, Key server, float weight) {
//assert(mq->empty());
ServerQueueInfo queue_info (server, mq, weight);
mServerQueues.insert(std::pair<Key,ServerQueueInfo>(server, queue_info));
}
void setQueueWeight(Key server, float weight) {
typename ServerQueueInfoMap::iterator where=mServerQueues.find(server);
bool retval=( where != mServerQueues.end() );
if (where != mServerQueues.end()) {
where->second.weight = weight;
}
}
float getQueueWeight(Key server) const {
typename ServerQueueInfoMap::const_iterator where=mServerQueues.find(server);
if (where != mServerQueues.end()) {
return where->second.weight;
}
return 0;
}
bool deprioritize(Key server,float factor, float affine, float minval,float maxval) {
return changepriority(server,factor,affine,minval,maxval,true);
}
bool reprioritize(Key server,float factor, float affine, float minval,float maxval) {
return changepriority(server,factor,affine,minval,maxval,false);
}
bool changepriority(Key server,float factor, float affine, float minval,float maxval, bool passOnDeprioritize) {
typename ServerQueueInfoMap::iterator where=mServerQueues.find(server);
if ( where == mServerQueues.end() )
return false;
float oldweight=where->second.weight;
oldweight*=factor;
oldweight+=affine;
if (oldweight<minval){
oldweight=minval;
}
this->setQueueWeight(server,oldweight);
return true;
}
bool removeQueue(Key server) {
typename ServerQueueInfoMap::iterator where=mServerQueues.find(server);
bool retval=( where != mServerQueues.end() );
if (retval) {
delete where->second.messageQueue;
mServerQueues.erase(where);
}
return retval;
}
bool hasQueue(Key server) const{
return ( mServerQueues.find(server) != mServerQueues.end() );
}
unsigned int numQueues() const {
return (unsigned int)mServerQueues.size();
}
QueueEnum::PushResult push(Key dest_server, Message *msg){
typename ServerQueueInfoMap::iterator qi_it = mServerQueues.find(dest_server);
assert( qi_it != mServerQueues.end() );
ServerQueueInfo* queue_info = &qi_it->second;
if (queue_info->messageQueue->empty()) {
queue_info->nextFinishTime = finishTime(msg->size(), queue_info->weight);
}
return queue_info->messageQueue->push(msg);
}
// Returns the next message to deliver, given the number of bytes available for transmission
// \param bytes number of bytes available; updated appropriately for intermediate null messages when returns
// \returns the next message, or NULL if the queue is empty or the next message cannot be handled
// given the number of bytes allocated
Message* front(uint64* bytes, Key*keyAtFront) {
Message* result = NULL;
Time vftime(0);
ServerQueueInfo* min_queue_info = NULL;
nextMessage(bytes, &result, &vftime, &min_queue_info);
if (result != NULL) {
assert( *bytes >= result->size() );
*keyAtFront=min_queue_info->mKey;
return result;
}
return NULL;
}
// Returns the next message to deliver, given the number of bytes available for transmission
// \param bytes number of bytes available; updated appropriately when returns
// \returns the next message, or NULL if the queue is empty or the next message cannot be handled
// given the number of bytes allotted
Message* pop(uint64* bytes) {
Message* result = NULL;
Time vftime(0);
ServerQueueInfo* min_queue_info = NULL;
nextMessage(bytes, &result, &vftime, &min_queue_info);
if (result != NULL) {
mCurrentVirtualTime = vftime;
assert(min_queue_info != NULL);
assert( *bytes >= result->size() );
*bytes -= result->size();
min_queue_info->messageQueue->pop();
uint32 serviceEmptyQueue = mEmptyQueueMessageLength;
// update the next finish time if there's anything in the queue
if (serviceEmptyQueue || !min_queue_info->messageQueue->empty())
min_queue_info->nextFinishTime = finishTime(WeightFunction()(*min_queue_info->messageQueue,mNullMessage), min_queue_info->weight);
}
return result;
}
bool empty() const {
// FIXME we could track a count ourselves instead of checking all these queues
for(typename ServerQueueInfoMap::const_iterator it = mServerQueues.begin(); it != mServerQueues.end(); it++) {
const ServerQueueInfo* queue_info = &it->second;
if (!queue_info->messageQueue->empty())
return false;
}
return true;
}
// Returns the total amount of space that can be allocated for the destination
uint32 maxSize(Key dest) const {
typename ServerQueueInfoMap::const_iterator it = mServerQueues.find(dest);
if (it == mServerQueues.end()) return 0;
return it->second.messageQueue->maxSize();
}
// Returns the total amount of space currently used for the destination
uint32 size(Key dest) const {
typename ServerQueueInfoMap::const_iterator it = mServerQueues.find(dest);
if (it == mServerQueues.end()) return 0;
return it->second.messageQueue->size();
}
protected:
// Retrieves the next message to deliver, along with its virtual finish time, given the number of bytes available
// for transmission. May update bytes for null messages, but does not update it to remove bytes to be used for
// the returned message. Returns null either if the number of bytes is not sufficient or the queue is empty.
void nextMessage(uint64* bytes, Message** result_out, Time* vftime_out, ServerQueueInfo** min_queue_info_out) {
uint32 serviceEmptyQueue = mEmptyQueueMessageLength;
Message* result = mNullMessage;
while( result == mNullMessage) {
// Find the non-empty queue with the earliest finish time
ServerQueueInfo* min_queue_info = NULL;
for(typename ServerQueueInfoMap::iterator it = mServerQueues.begin(); it != mServerQueues.end(); it++) {
ServerQueueInfo* queue_info = &it->second;
if (queue_info->messageQueue->empty()&&!serviceEmptyQueue) continue;
if (min_queue_info == NULL || queue_info->nextFinishTime < min_queue_info->nextFinishTime)
min_queue_info = queue_info;
}
// If we actually have something to deliver, deliver it
result = NULL;
if (min_queue_info) {
*min_queue_info_out = min_queue_info;
*vftime_out = min_queue_info->nextFinishTime;
result = mNullMessage;
if (!min_queue_info->messageQueue->empty()) {
if (*bytes < min_queue_info->messageQueue->front()->size())
break;
result = min_queue_info->messageQueue->front();
} else {
if (*bytes < result->size())
break;
}
if (result == mNullMessage) {
uint32 message_size = result->size();
assert (message_size <= *bytes);
*bytes -= message_size;
mCurrentVirtualTime = min_queue_info->nextFinishTime;
// update the next finish time if there's anything in the queue
if (serviceEmptyQueue)
min_queue_info->nextFinishTime = finishTime(WeightFunction()(*min_queue_info->messageQueue,mNullMessage), min_queue_info->weight);
}
}
}
if (result == mNullMessage)
*result_out = NULL;
else
*result_out = result;
}
Time finishTime(uint32 size, float weight) const{
float queue_frac = weight;
Duration transmitTime = Duration::seconds( size / queue_frac );
if (transmitTime == Duration(0)) transmitTime = Duration(1); // just make sure we take *some* time
return mCurrentVirtualTime + transmitTime;
}
protected:
uint32 mRate;
Time mCurrentVirtualTime;
ServerQueueInfoMap mServerQueues;
Message* mNullMessage;
}; // class FairQueue
} // namespace CBR
#endif //_FAIR_MESSAGE_QUEUE_HPP_
<|endoftext|>
|
<commit_before>#include "xchainer/python/array.h"
#include <algorithm>
#include <cstdint>
#include <string>
#include <vector>
#include <pybind11/numpy.h>
#include <pybind11/operators.h>
#include <nonstd/optional.hpp>
#include "xchainer/array.h"
#include "xchainer/array_index.h"
#include "xchainer/backward.h"
#include "xchainer/constant.h"
#include "xchainer/context.h"
#include "xchainer/device.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"
#include "xchainer/indexable_array.h"
#include "xchainer/indexer.h"
#include "xchainer/routines/creation.h"
#include "xchainer/slice.h"
#include "xchainer/python/array_index.h"
#include "xchainer/python/common.h"
#include "xchainer/python/device.h"
#include "xchainer/python/shape.h"
#include "xchainer/python/strides.h"
namespace xchainer {
namespace python {
namespace internal {
namespace py = pybind11;
namespace {
Dtype NumpyDtypeToDtype(const py::dtype& npdtype) {
switch (npdtype.kind()) {
case 'b':
return Dtype::kBool;
case 'i':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kInt8;
case 2:
return Dtype::kInt16;
case 4:
return Dtype::kInt32;
case 8:
return Dtype::kInt64;
default:
break;
}
break;
case 'u':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kUInt8;
default:
break;
}
break;
case 'f':
switch (npdtype.itemsize()) {
case 4:
return Dtype::kFloat32;
case 8:
return Dtype::kFloat64;
default:
break;
}
break;
default:
break;
}
throw DtypeError("unsupported NumPy dtype");
}
ArrayBodyPtr MakeArray(const py::tuple& shape_tup, Dtype dtype, const py::list& list, const nonstd::optional<std::string>& device_id) {
Shape shape = ToShape(shape_tup);
auto total_size = shape.GetTotalSize();
auto bytes = GetElementSize(dtype) * total_size;
if (static_cast<size_t>(total_size) != list.size()) {
throw DimensionError("Invalid data length");
}
// Allocate a buffer and copy data
std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes);
VisitDtype(dtype, [&](auto pt) {
using T = typename decltype(pt)::type;
std::transform(list.begin(), list.end(), static_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); });
});
return Array::FromBuffer(shape, dtype, ptr, GetDevice(device_id)).move_body();
}
ArrayBodyPtr MakeArray(py::array array, const nonstd::optional<std::string>& device_id) {
Dtype dtype = NumpyDtypeToDtype(array.dtype());
const py::buffer_info& info = array.request();
Shape shape{info.shape};
Strides strides{info.strides};
// data holds the copy of py::array which in turn references the NumPy array and the buffer is therefore not released
void* underlying_data = array.mutable_data();
std::shared_ptr<void> data{std::make_shared<py::array>(std::move(array)), underlying_data};
return xchainer::internal::FromBuffer(shape, dtype, data, strides, GetDevice(device_id)).move_body();
}
py::buffer_info MakeNumpyArrayFromArray(ArrayBody& self) {
// Used as a temporary accessor
Array array{ArrayBodyPtr(&self, [](ArrayBody* ptr) {
(void)ptr; // unused
})};
return py::buffer_info(
array.data().get(),
array.element_bytes(),
std::string(1, GetCharCode(array.dtype())),
array.ndim(),
array.shape(),
array.strides());
}
} // namespace
void InitXchainerArray(pybind11::module& m) {
py::class_<ArrayBody, ArrayBodyPtr> c{m, "Array", py::buffer_protocol()};
c.def(py::init(py::overload_cast<const py::tuple&, Dtype, const py::list&, const nonstd::optional<std::string>&>(&MakeArray)),
py::arg("shape"),
py::arg("dtype"),
py::arg("data"),
py::arg("device") = nullptr);
c.def(py::init(py::overload_cast<py::array, const nonstd::optional<std::string>&>(&MakeArray)),
py::arg("data"),
py::arg("device") = nullptr);
c.def_buffer(&MakeNumpyArrayFromArray);
c.def("view", [](const ArrayBodyPtr& self) {
// Duplicate the array body
return std::make_shared<ArrayBody>(*self);
});
c.def("__repr__", [](const ArrayBodyPtr& self) { return Array{self}.ToString(); });
c.def("to_device", [](const ArrayBodyPtr& self, Device& device) { return Array{self}.ToDevice(device).move_body(); });
c.def("to_device", [](const ArrayBodyPtr& self, const std::string& device_name) {
Device& device = GetDefaultContext().GetDevice({device_name});
return Array{self}.ToDevice(device).move_body();
});
c.def("to_device", [](const ArrayBodyPtr& self, const std::string& backend_name, int index) {
Device& device = GetDefaultContext().GetDevice({backend_name, index});
return Array{self}.ToDevice(device).move_body();
});
c.def("as_constant",
[](const ArrayBodyPtr& self, bool copy) { return Array{self}.AsConstant(copy ? CopyKind::kCopy : CopyKind::kView).move_body(); },
py::arg("copy") = false);
c.def("as_constant",
[](const ArrayBodyPtr& self, const std::vector<GraphId>& graph_ids, bool copy) {
return Array{self}.AsConstant(graph_ids, copy ? CopyKind::kCopy : CopyKind::kView).move_body();
},
py::arg().noconvert(),
py::arg("copy") = false);
// creation instance methods
c.def("copy", [](const ArrayBodyPtr& self) { return Array{self}.Copy().move_body(); });
// indexing instance methods
c.def("__getitem__", [](const ArrayBodyPtr& self, py::handle handle) {
return Array{self}.At(python::internal::MakeArrayIndices(handle)).move_body();
});
// manipulation instance methods
c.def("transpose", [](const ArrayBodyPtr& self) { return Array{self}.Transpose().move_body(); });
c.def("reshape", [](const ArrayBodyPtr& self, py::tuple shape) { return Array{self}.Reshape(ToShape(shape)).move_body(); });
c.def("reshape", [](const ArrayBodyPtr& self, const std::vector<int64_t>& shape) {
return Array{self}.Reshape({shape.begin(), shape.end()}).move_body();
});
c.def("reshape", [](const ArrayBodyPtr& self, py::args args) {
auto shape = py::cast<std::vector<int64_t>>(args);
return Array{self}.Reshape({shape.begin(), shape.end()}).move_body();
});
// math instance methods
c.def("__iadd__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} += Array{rhs}).move_body(); });
c.def("__imul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} *= Array{rhs}).move_body(); });
c.def("__add__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} + Array{rhs}).move_body(); });
c.def("__mul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} * Array{rhs}).move_body(); });
c.def("sum",
[](const ArrayBodyPtr& self, int8_t axis, bool keepdims) {
return Array{self}.Sum(std::vector<int8_t>{axis}, keepdims).move_body();
},
py::arg("axis"),
py::arg("keepdims") = false);
c.def("sum",
[](const ArrayBodyPtr& self, nonstd::optional<std::vector<int8_t>> axis, bool keepdims) {
return Array{self}.Sum(axis, keepdims).move_body();
},
py::arg("axis") = nullptr,
py::arg("keepdims") = false);
c.def("require_grad",
[](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.RequireGrad(graph_id).move_body(); },
py::arg("graph_id") = kDefaultGraphId);
c.def("is_grad_required",
[](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.IsGradRequired(graph_id); },
py::arg("graph_id") = kDefaultGraphId);
c.def("get_grad",
[](const ArrayBodyPtr& self, const GraphId& graph_id) -> ConstArrayBodyPtr {
const nonstd::optional<Array>& grad = Array{self}.GetGrad(graph_id);
if (!grad.has_value()) {
return nullptr;
}
return grad->body();
},
py::arg("graph_id") = kDefaultGraphId);
c.def("set_grad",
[](const ArrayBodyPtr& self, const ArrayBodyPtr& grad, const GraphId& graph_id) {
auto array = Array{self};
if (grad) {
array.SetGrad(Array{grad}, graph_id);
} else {
array.ClearGrad(graph_id);
}
},
py::arg("grad"),
py::arg("graph_id") = kDefaultGraphId);
c.def("backward",
[](const ArrayBodyPtr& self, const GraphId& graph_id, bool enable_double_backprop) {
Array array{self};
auto double_backprop = enable_double_backprop ? DoubleBackpropOption::kEnable : DoubleBackpropOption::kDisable;
Backward(array, graph_id, double_backprop);
},
py::arg("graph_id") = kDefaultGraphId,
py::arg("enable_double_backprop") = false);
c.def_property(
"grad",
[](const ArrayBodyPtr& self) -> ConstArrayBodyPtr {
const nonstd::optional<Array>& grad = Array{self}.GetGrad(kDefaultGraphId);
if (!grad.has_value()) {
return nullptr;
}
return grad->body();
},
[](const ArrayBodyPtr& self, const ArrayBodyPtr& grad) {
auto array = Array{self};
if (grad) {
array.SetGrad(Array{grad}, kDefaultGraphId);
} else {
array.ClearGrad(kDefaultGraphId);
}
});
c.def("cleargrad",
[](const ArrayBodyPtr& self, const GraphId& graph_id) { Array{self}.ClearGrad(graph_id); },
py::arg("graph_id") = kDefaultGraphId);
c.def_property_readonly(
"device", [](const ArrayBodyPtr& self) -> Device& { return Array{self}.device(); }, py::return_value_policy::reference);
c.def_property_readonly("dtype", [](const ArrayBodyPtr& self) { return Array{self}.dtype(); });
c.def_property_readonly("element_bytes", [](const ArrayBodyPtr& self) { return Array{self}.element_bytes(); });
c.def_property_readonly("is_contiguous", [](const ArrayBodyPtr& self) { return Array{self}.IsContiguous(); });
c.def_property_readonly("ndim", [](const ArrayBodyPtr& self) { return Array{self}.ndim(); });
c.def_property_readonly("offset", [](const ArrayBodyPtr& self) { return Array{self}.offset(); });
c.def_property_readonly("shape", [](const ArrayBodyPtr& self) { return ToTuple(Array{self}.shape()); });
c.def_property_readonly("strides", [](const ArrayBodyPtr& self) { return ToTuple(Array{self}.strides()); });
c.def_property_readonly("total_bytes", [](const ArrayBodyPtr& self) { return Array{self}.GetTotalBytes(); });
c.def_property_readonly("total_size", [](const ArrayBodyPtr& self) { return Array{self}.GetTotalSize(); });
c.def_property_readonly("T", [](const ArrayBodyPtr& self) { return Array{self}.Transpose().move_body(); });
c.def_property_readonly(
"_debug_data_memory_address", // These methods starting with `_debug_` are stubs for testing
[](const ArrayBodyPtr& self) -> intptr_t {
const void* ptr = Array{self}.data().get();
return reinterpret_cast<intptr_t>(ptr); // NOLINT: reinterpret_cast
});
c.def_property_readonly("_debug_flat_data", [](const ArrayBodyPtr& self) {
py::list list;
Array array{self};
array.device().Synchronize();
// Copy data into the list
VisitDtype(array.dtype(), [&array, &list](auto pt) {
using T = typename decltype(pt)::type;
IndexableArray<const T> iarray{array};
Indexer<> indexer{array.shape()};
for (int64_t i = 0; i < indexer.total_size(); ++i) {
indexer.Set(i);
list.append(iarray[indexer]);
}
});
return list;
});
}
} // namespace internal
} // namespace python
} // namespace xchainer
<commit_msg>Remove comments: instance methods<commit_after>#include "xchainer/python/array.h"
#include <algorithm>
#include <cstdint>
#include <string>
#include <vector>
#include <pybind11/numpy.h>
#include <pybind11/operators.h>
#include <nonstd/optional.hpp>
#include "xchainer/array.h"
#include "xchainer/array_index.h"
#include "xchainer/backward.h"
#include "xchainer/constant.h"
#include "xchainer/context.h"
#include "xchainer/device.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"
#include "xchainer/indexable_array.h"
#include "xchainer/indexer.h"
#include "xchainer/routines/creation.h"
#include "xchainer/slice.h"
#include "xchainer/python/array_index.h"
#include "xchainer/python/common.h"
#include "xchainer/python/device.h"
#include "xchainer/python/shape.h"
#include "xchainer/python/strides.h"
namespace xchainer {
namespace python {
namespace internal {
namespace py = pybind11;
namespace {
Dtype NumpyDtypeToDtype(const py::dtype& npdtype) {
switch (npdtype.kind()) {
case 'b':
return Dtype::kBool;
case 'i':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kInt8;
case 2:
return Dtype::kInt16;
case 4:
return Dtype::kInt32;
case 8:
return Dtype::kInt64;
default:
break;
}
break;
case 'u':
switch (npdtype.itemsize()) {
case 1:
return Dtype::kUInt8;
default:
break;
}
break;
case 'f':
switch (npdtype.itemsize()) {
case 4:
return Dtype::kFloat32;
case 8:
return Dtype::kFloat64;
default:
break;
}
break;
default:
break;
}
throw DtypeError("unsupported NumPy dtype");
}
ArrayBodyPtr MakeArray(const py::tuple& shape_tup, Dtype dtype, const py::list& list, const nonstd::optional<std::string>& device_id) {
Shape shape = ToShape(shape_tup);
auto total_size = shape.GetTotalSize();
auto bytes = GetElementSize(dtype) * total_size;
if (static_cast<size_t>(total_size) != list.size()) {
throw DimensionError("Invalid data length");
}
// Allocate a buffer and copy data
std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes);
VisitDtype(dtype, [&](auto pt) {
using T = typename decltype(pt)::type;
std::transform(list.begin(), list.end(), static_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); });
});
return Array::FromBuffer(shape, dtype, ptr, GetDevice(device_id)).move_body();
}
ArrayBodyPtr MakeArray(py::array array, const nonstd::optional<std::string>& device_id) {
Dtype dtype = NumpyDtypeToDtype(array.dtype());
const py::buffer_info& info = array.request();
Shape shape{info.shape};
Strides strides{info.strides};
// data holds the copy of py::array which in turn references the NumPy array and the buffer is therefore not released
void* underlying_data = array.mutable_data();
std::shared_ptr<void> data{std::make_shared<py::array>(std::move(array)), underlying_data};
return xchainer::internal::FromBuffer(shape, dtype, data, strides, GetDevice(device_id)).move_body();
}
py::buffer_info MakeNumpyArrayFromArray(ArrayBody& self) {
// Used as a temporary accessor
Array array{ArrayBodyPtr(&self, [](ArrayBody* ptr) {
(void)ptr; // unused
})};
return py::buffer_info(
array.data().get(),
array.element_bytes(),
std::string(1, GetCharCode(array.dtype())),
array.ndim(),
array.shape(),
array.strides());
}
} // namespace
void InitXchainerArray(pybind11::module& m) {
py::class_<ArrayBody, ArrayBodyPtr> c{m, "Array", py::buffer_protocol()};
c.def(py::init(py::overload_cast<const py::tuple&, Dtype, const py::list&, const nonstd::optional<std::string>&>(&MakeArray)),
py::arg("shape"),
py::arg("dtype"),
py::arg("data"),
py::arg("device") = nullptr);
c.def(py::init(py::overload_cast<py::array, const nonstd::optional<std::string>&>(&MakeArray)),
py::arg("data"),
py::arg("device") = nullptr);
c.def_buffer(&MakeNumpyArrayFromArray);
c.def("view", [](const ArrayBodyPtr& self) {
// Duplicate the array body
return std::make_shared<ArrayBody>(*self);
});
c.def("__repr__", [](const ArrayBodyPtr& self) { return Array{self}.ToString(); });
c.def("to_device", [](const ArrayBodyPtr& self, Device& device) { return Array{self}.ToDevice(device).move_body(); });
c.def("to_device", [](const ArrayBodyPtr& self, const std::string& device_name) {
Device& device = GetDefaultContext().GetDevice({device_name});
return Array{self}.ToDevice(device).move_body();
});
c.def("to_device", [](const ArrayBodyPtr& self, const std::string& backend_name, int index) {
Device& device = GetDefaultContext().GetDevice({backend_name, index});
return Array{self}.ToDevice(device).move_body();
});
c.def("as_constant",
[](const ArrayBodyPtr& self, bool copy) { return Array{self}.AsConstant(copy ? CopyKind::kCopy : CopyKind::kView).move_body(); },
py::arg("copy") = false);
c.def("as_constant",
[](const ArrayBodyPtr& self, const std::vector<GraphId>& graph_ids, bool copy) {
return Array{self}.AsConstant(graph_ids, copy ? CopyKind::kCopy : CopyKind::kView).move_body();
},
py::arg().noconvert(),
py::arg("copy") = false);
c.def("copy", [](const ArrayBodyPtr& self) { return Array{self}.Copy().move_body(); });
c.def("__getitem__", [](const ArrayBodyPtr& self, py::handle handle) {
return Array{self}.At(python::internal::MakeArrayIndices(handle)).move_body();
});
c.def("transpose", [](const ArrayBodyPtr& self) { return Array{self}.Transpose().move_body(); });
c.def("reshape", [](const ArrayBodyPtr& self, py::tuple shape) { return Array{self}.Reshape(ToShape(shape)).move_body(); });
c.def("reshape", [](const ArrayBodyPtr& self, const std::vector<int64_t>& shape) {
return Array{self}.Reshape({shape.begin(), shape.end()}).move_body();
});
c.def("reshape", [](const ArrayBodyPtr& self, py::args args) {
auto shape = py::cast<std::vector<int64_t>>(args);
return Array{self}.Reshape({shape.begin(), shape.end()}).move_body();
});
c.def("__iadd__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} += Array{rhs}).move_body(); });
c.def("__imul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} *= Array{rhs}).move_body(); });
c.def("__add__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} + Array{rhs}).move_body(); });
c.def("__mul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} * Array{rhs}).move_body(); });
c.def("sum",
[](const ArrayBodyPtr& self, int8_t axis, bool keepdims) {
return Array{self}.Sum(std::vector<int8_t>{axis}, keepdims).move_body();
},
py::arg("axis"),
py::arg("keepdims") = false);
c.def("sum",
[](const ArrayBodyPtr& self, nonstd::optional<std::vector<int8_t>> axis, bool keepdims) {
return Array{self}.Sum(axis, keepdims).move_body();
},
py::arg("axis") = nullptr,
py::arg("keepdims") = false);
c.def("require_grad",
[](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.RequireGrad(graph_id).move_body(); },
py::arg("graph_id") = kDefaultGraphId);
c.def("is_grad_required",
[](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.IsGradRequired(graph_id); },
py::arg("graph_id") = kDefaultGraphId);
c.def("get_grad",
[](const ArrayBodyPtr& self, const GraphId& graph_id) -> ConstArrayBodyPtr {
const nonstd::optional<Array>& grad = Array{self}.GetGrad(graph_id);
if (!grad.has_value()) {
return nullptr;
}
return grad->body();
},
py::arg("graph_id") = kDefaultGraphId);
c.def("set_grad",
[](const ArrayBodyPtr& self, const ArrayBodyPtr& grad, const GraphId& graph_id) {
auto array = Array{self};
if (grad) {
array.SetGrad(Array{grad}, graph_id);
} else {
array.ClearGrad(graph_id);
}
},
py::arg("grad"),
py::arg("graph_id") = kDefaultGraphId);
c.def("backward",
[](const ArrayBodyPtr& self, const GraphId& graph_id, bool enable_double_backprop) {
Array array{self};
auto double_backprop = enable_double_backprop ? DoubleBackpropOption::kEnable : DoubleBackpropOption::kDisable;
Backward(array, graph_id, double_backprop);
},
py::arg("graph_id") = kDefaultGraphId,
py::arg("enable_double_backprop") = false);
c.def_property(
"grad",
[](const ArrayBodyPtr& self) -> ConstArrayBodyPtr {
const nonstd::optional<Array>& grad = Array{self}.GetGrad(kDefaultGraphId);
if (!grad.has_value()) {
return nullptr;
}
return grad->body();
},
[](const ArrayBodyPtr& self, const ArrayBodyPtr& grad) {
auto array = Array{self};
if (grad) {
array.SetGrad(Array{grad}, kDefaultGraphId);
} else {
array.ClearGrad(kDefaultGraphId);
}
});
c.def("cleargrad",
[](const ArrayBodyPtr& self, const GraphId& graph_id) { Array{self}.ClearGrad(graph_id); },
py::arg("graph_id") = kDefaultGraphId);
c.def_property_readonly(
"device", [](const ArrayBodyPtr& self) -> Device& { return Array{self}.device(); }, py::return_value_policy::reference);
c.def_property_readonly("dtype", [](const ArrayBodyPtr& self) { return Array{self}.dtype(); });
c.def_property_readonly("element_bytes", [](const ArrayBodyPtr& self) { return Array{self}.element_bytes(); });
c.def_property_readonly("is_contiguous", [](const ArrayBodyPtr& self) { return Array{self}.IsContiguous(); });
c.def_property_readonly("ndim", [](const ArrayBodyPtr& self) { return Array{self}.ndim(); });
c.def_property_readonly("offset", [](const ArrayBodyPtr& self) { return Array{self}.offset(); });
c.def_property_readonly("shape", [](const ArrayBodyPtr& self) { return ToTuple(Array{self}.shape()); });
c.def_property_readonly("strides", [](const ArrayBodyPtr& self) { return ToTuple(Array{self}.strides()); });
c.def_property_readonly("total_bytes", [](const ArrayBodyPtr& self) { return Array{self}.GetTotalBytes(); });
c.def_property_readonly("total_size", [](const ArrayBodyPtr& self) { return Array{self}.GetTotalSize(); });
c.def_property_readonly("T", [](const ArrayBodyPtr& self) { return Array{self}.Transpose().move_body(); });
c.def_property_readonly(
"_debug_data_memory_address", // These methods starting with `_debug_` are stubs for testing
[](const ArrayBodyPtr& self) -> intptr_t {
const void* ptr = Array{self}.data().get();
return reinterpret_cast<intptr_t>(ptr); // NOLINT: reinterpret_cast
});
c.def_property_readonly("_debug_flat_data", [](const ArrayBodyPtr& self) {
py::list list;
Array array{self};
array.device().Synchronize();
// Copy data into the list
VisitDtype(array.dtype(), [&array, &list](auto pt) {
using T = typename decltype(pt)::type;
IndexableArray<const T> iarray{array};
Indexer<> indexer{array.shape()};
for (int64_t i = 0; i < indexer.total_size(); ++i) {
indexer.Set(i);
list.append(iarray[indexer]);
}
});
return list;
});
}
} // namespace internal
} // namespace python
} // namespace xchainer
<|endoftext|>
|
<commit_before>#include "xchainer/python/shape.h"
#include "xchainer/python/shape.h"
#include <algorithm>
#include <pybind11/operators.h>
#include "xchainer/shape.h"
namespace xchainer {
namespace py = pybind11;
void InitXchainerShape(pybind11::module& m) {
py::class_<Shape>{m, "Shape"}
.def(py::init([](py::tuple tup) { // __init__ by a tuple
std::vector<int64_t> v;
std::transform(tup.begin(), tup.end(), std::back_inserter(v), [](auto& item) { return py::cast<int64_t>(item); });
return Shape(v);
}))
.def(py::self == py::self)
.def("__eq__", // Equality with a tuple
[](const Shape& self, const py::tuple& tup) {
if (static_cast<size_t>(self.ndim()) != tup.size()) {
return false;
}
try {
return std::equal(self.begin(), self.end(), tup.begin(), tup.end(), [](const auto& dim, const auto& item) {
int64_t dim2 = py::cast<int64_t>(item);
return dim == dim2;
});
} catch (const py::cast_error& e) {
return false;
}
})
.def("__repr__", [](const Shape& shape) { return shape.ToString(); })
.def_property_readonly("ndim", &Shape::ndim)
.def_property_readonly("size", &Shape::size)
.def_property_readonly("total_size", &Shape::total_size);
py::implicitly_convertible<py::tuple, Shape>();
}
} // namespace xchainer
<commit_msg>Lambda to function pointer<commit_after>#include "xchainer/python/shape.h"
#include "xchainer/python/shape.h"
#include <algorithm>
#include <pybind11/operators.h>
#include "xchainer/shape.h"
namespace xchainer {
namespace py = pybind11;
void InitXchainerShape(pybind11::module& m) {
py::class_<Shape>{m, "Shape"}
.def(py::init([](py::tuple tup) { // __init__ by a tuple
std::vector<int64_t> v;
std::transform(tup.begin(), tup.end(), std::back_inserter(v), [](auto& item) { return py::cast<int64_t>(item); });
return Shape(v);
}))
.def(py::self == py::self)
.def("__eq__", // Equality with a tuple
[](const Shape& self, const py::tuple& tup) {
if (static_cast<size_t>(self.ndim()) != tup.size()) {
return false;
}
try {
return std::equal(self.begin(), self.end(), tup.begin(), tup.end(), [](const auto& dim, const auto& item) {
int64_t dim2 = py::cast<int64_t>(item);
return dim == dim2;
});
} catch (const py::cast_error& e) {
return false;
}
})
.def("__repr__", static_cast<std::string (Shape::*)() const>(&Shape::ToString))
.def_property_readonly("ndim", &Shape::ndim)
.def_property_readonly("size", &Shape::size)
.def_property_readonly("total_size", &Shape::total_size);
py::implicitly_convertible<py::tuple, Shape>();
}
} // namespace xchainer
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_proc_gettracearray.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_proc_gettracearray.H
///
/// @brief Collect contents of specified trace array via SCOM.
///
/// Collects contents of specified trace array via SCOM. Optionally
/// manages chiplet domain trace engine state (start/stop/reset) around
/// trace array data collection. Trace array data can be collected only
/// when its controlling chiplet trace engine is stopped.
///
/// Trace array entries will be packed into data buffer from
/// oldest->youngest entry.
///
/// Calling code is expected to pass the proper target type based on the
/// desired trace resource; a convenience function is provided to find out
/// the expected target type for a given trace resource.
//------------------------------------------------------------------------------
// *HWP HW Owner : Joachim Fenkes <fenkes@de.ibm.com>
// *HWP HW Backup Owner : Joe McGill <jmcgill@us.ibm.com>
// *HWP FW Owner : Shakeeb Pasha <shakeebbk@in.ibm.com>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : FSP
//------------------------------------------------------------------------------
#ifndef _PROC_GETTRACEARRAY_H_
#define _PROC_GETTRACEARRAY_H_
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <fapi2.H>
#include "p9_tracearray_defs.H"
#include "p9_sbe_tracearray.H"
static const fapi2::TargetType PROC_GETTRACEARRAY_TARGET_TYPES =
fapi2::TARGET_TYPE_PROC_CHIP |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MCBIST |
fapi2::TARGET_TYPE_EX |
fapi2::TARGET_TYPE_CORE;
// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode
(*p9_proc_gettracearray_FP_t)(const fapi2::Target<PROC_GETTRACEARRAY_TARGET_TYPES>&,
const proc_gettracearray_args&,
fapi2::variable_buffer& o_ta_data);
extern "C"
{
/**
* @brief Return the target type needed to access a given trace array
* @param ta_id The trace array / trace bus ID requested.
* @return The type of target to hand to proc_gettracearray to clearly identify the array instance.
*/
static inline fapi2::TargetType proc_gettracearray_target_type(p9_tracearray_bus_id i_trace_bus)
{
if (i_trace_bus <= _PROC_TB_LAST_PROC_TARGET)
{
return fapi2::TARGET_TYPE_PROC_CHIP;
}
else if (i_trace_bus <= _PROC_TB_LAST_OBUS_TARGET)
{
return fapi2::TARGET_TYPE_OBUS;
}
else if (i_trace_bus <= _PROC_TB_LAST_MC_TARGET)
{
return fapi2::TARGET_TYPE_MCBIST;
}
else if (i_trace_bus <= _PROC_TB_LAST_EX_TARGET)
{
return fapi2::TARGET_TYPE_EX;
}
else
{
return fapi2::TARGET_TYPE_CORE;
}
}
//------------------------------------------------------------------------------
// Function prototype
//------------------------------------------------------------------------------
/**
* @brief Retrieve trace array data from selected trace array via SCOM,
* optionally performing trace stop (prior to dump) and/or
* trace restart (after dump)
*
* @param i_target Chip or chiplet target. The necessary target type can be
* queried through proc_gettracearray_target_type().
* @param i_args Argument structure with additional parameters
* @param o_ta_data Trace array data. Will contain all trace entries read
* from the array concatenated, starting with the oldest trace
* entry and ending with the newest.
* @return FAPI2_RC_SUCCESS
* if trace array dump sequence completes successfully,
* RC_PROC_GETTRACEARRAY_INVALID_BUS
* if an invalid trace bus ID has been requested
* RC_PROC_GETTRACEARRAY_INVALID_TARGET
* if the supplied target type does not match the requested trace bus
* RC_PROC_GETTRACEARRAY_CORE_NOT_DUMPABLE
* if a core trace array has been requested but the chip's core
* is not dumpable via SCOM -> use fastarray instead
* RC_PROC_GETTRACEARRAY_TRACE_RUNNING
* if trace array is running when dump collection is attempted,
* RC_PROC_GETTRACEARRAY_TRACE_MUX_INCORRECT
* if the primary trace mux is not set up to trace the requested bus,
* else FAPI getscom/putscom return code for failing operation
*/
fapi2::ReturnCode p9_proc_gettracearray(const fapi2::Target<PROC_GETTRACEARRAY_TARGET_TYPES>& i_target,
const proc_gettracearray_args& i_args,
fapi2::variable_buffer& o_ta_data);
} // extern "C"
#endif // _PROC_GETTRACEARRAY_H_
<commit_msg>P9 L2err line delete HWP<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_proc_gettracearray.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_proc_gettracearray.H
///
/// @brief Collect contents of specified trace array via SCOM.
///
/// Collects contents of specified trace array via SCOM. Optionally
/// manages chiplet domain trace engine state (start/stop/reset) around
/// trace array data collection. Trace array data can be collected only
/// when its controlling chiplet trace engine is stopped.
///
/// Trace array entries will be packed into data buffer from
/// oldest->youngest entry.
///
/// Calling code is expected to pass the proper target type based on the
/// desired trace resource; a convenience function is provided to find out
/// the expected target type for a given trace resource.
//------------------------------------------------------------------------------
// *HWP HW Owner : Joachim Fenkes <fenkes@de.ibm.com>
// *HWP HW Backup Owner : Joe McGill <jmcgill@us.ibm.com>
// *HWP FW Owner : Shakeeb Pasha <shakeebbk@in.ibm.com>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : FSP
//------------------------------------------------------------------------------
#ifndef _PROC_GETTRACEARRAY_H_
#define _PROC_GETTRACEARRAY_H_
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <fapi2.H>
#include "p9_tracearray_defs.H"
#include "p9_sbe_tracearray.H"
static const fapi2::TargetType PROC_GETTRACEARRAY_TARGET_TYPES =
fapi2::TARGET_TYPE_PROC_CHIP |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MCBIST |
fapi2::TARGET_TYPE_EX |
fapi2::TARGET_TYPE_CORE;
// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode
(*p9_proc_gettracearray_FP_t)(const fapi2::Target<PROC_GETTRACEARRAY_TARGET_TYPES>&,
const proc_gettracearray_args&,
fapi2::variable_buffer& o_ta_data);
extern "C"
{
/**
* @brief Return the target type needed to access a given trace array
* @param ta_id The trace array / trace bus ID requested.
* @return The type of target to hand to proc_gettracearray to clearly identify the array instance.
*/
static inline fapi2::TargetType proc_gettracearray_target_type(p9_tracearray_bus_id i_trace_bus)
{
if (i_trace_bus <= _PROC_TB_LAST_PROC_TARGET)
{
return fapi2::TARGET_TYPE_PROC_CHIP;
}
else if (i_trace_bus <= _PROC_TB_LAST_OBUS_TARGET)
{
return fapi2::TARGET_TYPE_OBUS;
}
else if (i_trace_bus <= _PROC_TB_LAST_MC_TARGET)
{
return fapi2::TARGET_TYPE_MCBIST;
}
else if (i_trace_bus <= _PROC_TB_LAST_EX_TARGET)
{
return fapi2::TARGET_TYPE_EX;
}
else
{
return fapi2::TARGET_TYPE_CORE;
}
}
/**
* @brief Determine whether a trace entry is a start marker
* @param[in] i_buffer a buffer containing the trace entry
* @param[in] i_offset the bit offset of the entry inside the buffer, defaults to 0 if omitted
* @return FAPI2_RC_SUCCESS if the entry _is_ a start marker
* FAPI2_RC_FALSE if the entry is _not_ a start marker
* FAPI2_RC_OVERFLOW if the buffer did not contain enough bits
*/
static inline fapi2::ReturnCodes p9_tracearray_is_trace_start_marker(
const fapi2::variable_buffer i_buffer, uint32_t i_offset = 0)
{
uint32_t l_magic = 0;
uint64_t l_zeros = 0;
fapi2::ReturnCodes l_rc;
l_rc = i_buffer.extract(l_magic, i_offset, 32);
if (l_rc != fapi2::FAPI2_RC_SUCCESS)
{
return l_rc;
}
l_rc = i_buffer.extract(l_zeros, i_offset + 32, 64);
if (l_rc != fapi2::FAPI2_RC_SUCCESS)
{
return l_rc;
}
return (l_magic == 0xBA55A1E0 && l_zeros == 0) ?
fapi2::FAPI2_RC_SUCCESS : fapi2::FAPI2_RC_FALSE;
}
//------------------------------------------------------------------------------
// Function prototype
//------------------------------------------------------------------------------
/**
* @brief Retrieve trace array data from selected trace array via SCOM,
* optionally performing trace stop (prior to dump) and/or
* trace restart (after dump)
*
* @param i_target Chip or chiplet target. The necessary target type can be
* queried through proc_gettracearray_target_type().
* @param i_args Argument structure with additional parameters
* @param o_ta_data Trace array data. Will contain all trace entries read
* from the array concatenated, starting with the oldest trace
* entry and ending with the newest.
* @return FAPI2_RC_SUCCESS
* if trace array dump sequence completes successfully,
* RC_PROC_GETTRACEARRAY_INVALID_BUS
* if an invalid trace bus ID has been requested
* RC_PROC_GETTRACEARRAY_INVALID_TARGET
* if the supplied target type does not match the requested trace bus
* RC_PROC_GETTRACEARRAY_CORE_NOT_DUMPABLE
* if a core trace array has been requested but the chip's core
* is not dumpable via SCOM -> use fastarray instead
* RC_PROC_GETTRACEARRAY_TRACE_RUNNING
* if trace array is running when dump collection is attempted,
* RC_PROC_GETTRACEARRAY_TRACE_MUX_INCORRECT
* if the primary trace mux is not set up to trace the requested bus,
* else FAPI getscom/putscom return code for failing operation
*/
fapi2::ReturnCode p9_proc_gettracearray(const fapi2::Target<PROC_GETTRACEARRAY_TARGET_TYPES>& i_target,
const proc_gettracearray_args& i_args,
fapi2::variable_buffer& o_ta_data);
} // extern "C"
#endif // _PROC_GETTRACEARRAY_H_
<|endoftext|>
|
<commit_before>// Internal Includes
#include <osvr/PluginKit/PluginKit.h>
#include <osvr/PluginKit/TrackerInterfaceC.h>
// Generated JSON header file
#include "je_nourish_openhmd_json.h"
// Library/third-party includes
#include <openhmd.h>
// Standard includes
#include <stdlib.h>
#include <iostream>
#include <string>
#include <list>
namespace {
class OculusHMD {
public:
OculusHMD(OSVR_PluginRegContext ctx, ohmd_context* ohmd_ctx, int i) : m_context(ohmd_ctx) {
std::string name ("Oculus ");
name.append(ohmd_list_gets(m_context, i, OHMD_PRODUCT));
m_device = ohmd_list_open_device(m_context, i);
OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx);
osvrDeviceTrackerConfigure(opts, &m_tracker);
m_dev.initAsync(ctx, name.c_str(), opts);
m_dev.sendJsonDescriptor(je_nourish_openhmd_json);
m_dev.registerUpdateCallback(this);
osvrQuatSetIdentity(&m_state);
}
~OculusHMD() {
ohmd_close_device(m_device);
}
OSVR_ReturnCode update() {
ohmd_ctx_update(m_context);
float quat[4];
ohmd_device_getf(m_device, OHMD_ROTATION_QUAT, quat);
osvrQuatSetX(&m_state, quat[0]);
osvrQuatSetY(&m_state, quat[1]);
osvrQuatSetZ(&m_state, quat[2]);
osvrQuatSetW(&m_state, quat[3]);
osvrDeviceTrackerSendOrientation(m_dev, m_tracker, &m_state, 0);
return OSVR_RETURN_SUCCESS;
}
private:
osvr::pluginkit::DeviceToken m_dev;
OSVR_TrackerDeviceInterface m_tracker;
OSVR_Quaternion m_state;
ohmd_context* m_context;
ohmd_device* m_device;
};
class HardwareDetection {
public:
HardwareDetection() : m_found(false) {
ohmd_ctx = ohmd_ctx_create();
}
~HardwareDetection() {
ohmd_ctx_destroy(ohmd_ctx);
}
OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) {
if (!m_found) {
int num_devices = ohmd_ctx_probe(ohmd_ctx);
if (num_devices < 0) {
std::cout << "OpenHMD failed to probe devices: " << ohmd_ctx_get_error(ohmd_ctx) << std::endl;
return OSVR_RETURN_FAILURE;
}
std::string path;
std::string product;
for (int i = 0; i < num_devices; i++) {
product = ohmd_list_gets(ohmd_ctx, i, OHMD_PRODUCT);
if (product.compare("Rift (Devkit)") == 0) {
osvr::pluginkit::registerObjectForDeletion(
ctx, new OculusHMD(ctx, ohmd_ctx, i));
m_found = true;
}
}
}
return OSVR_RETURN_SUCCESS;
}
private:
ohmd_context* ohmd_ctx;
bool m_found;
};
} // namespace
OSVR_PLUGIN(je_nourish_openhmd) {
osvr::pluginkit::PluginContext context(ctx);
context.registerHardwareDetectCallback(new HardwareDetection());
return OSVR_RETURN_SUCCESS;
}
<commit_msg>Device whitelist -> blacklist<commit_after>// Internal Includes
#include <osvr/PluginKit/PluginKit.h>
#include <osvr/PluginKit/TrackerInterfaceC.h>
// Generated JSON header file
#include "je_nourish_openhmd_json.h"
// Library/third-party includes
#include <openhmd.h>
// Standard includes
#include <stdlib.h>
#include <iostream>
#include <string>
#include <list>
namespace {
class OculusHMD {
public:
OculusHMD(OSVR_PluginRegContext ctx, ohmd_context* ohmd_ctx, int i) : m_context(ohmd_ctx) {
std::string name ("Oculus ");
name.append(ohmd_list_gets(m_context, i, OHMD_PRODUCT));
m_device = ohmd_list_open_device(m_context, i);
OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx);
osvrDeviceTrackerConfigure(opts, &m_tracker);
m_dev.initAsync(ctx, name.c_str(), opts);
m_dev.sendJsonDescriptor(je_nourish_openhmd_json);
m_dev.registerUpdateCallback(this);
osvrQuatSetIdentity(&m_state);
}
~OculusHMD() {
ohmd_close_device(m_device);
}
OSVR_ReturnCode update() {
ohmd_ctx_update(m_context);
float quat[4];
ohmd_device_getf(m_device, OHMD_ROTATION_QUAT, quat);
osvrQuatSetX(&m_state, quat[0]);
osvrQuatSetY(&m_state, quat[1]);
osvrQuatSetZ(&m_state, quat[2]);
osvrQuatSetW(&m_state, quat[3]);
osvrDeviceTrackerSendOrientation(m_dev, m_tracker, &m_state, 0);
return OSVR_RETURN_SUCCESS;
}
private:
osvr::pluginkit::DeviceToken m_dev;
OSVR_TrackerDeviceInterface m_tracker;
OSVR_Quaternion m_state;
ohmd_context* m_context;
ohmd_device* m_device;
};
class HardwareDetection {
public:
HardwareDetection() : m_found(false) {
ohmd_ctx = ohmd_ctx_create();
}
~HardwareDetection() {
ohmd_ctx_destroy(ohmd_ctx);
}
OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) {
if (!m_found) {
int num_devices = ohmd_ctx_probe(ohmd_ctx);
if (num_devices < 0) {
std::cout << "OpenHMD failed to probe devices: " << ohmd_ctx_get_error(ohmd_ctx) << std::endl;
return OSVR_RETURN_FAILURE;
}
std::string product;
for (int i = 0; i < num_devices; i++) {
product = ohmd_list_gets(ohmd_ctx, i, OHMD_PRODUCT);
if (product.compare("Dummy Device") != 0) {
osvr::pluginkit::registerObjectForDeletion(
ctx, new OculusHMD(ctx, ohmd_ctx, i));
m_found = true;
}
}
}
return OSVR_RETURN_SUCCESS;
}
private:
ohmd_context* ohmd_ctx;
bool m_found;
};
} // namespace
OSVR_PLUGIN(je_nourish_openhmd) {
osvr::pluginkit::PluginContext context(ctx);
context.registerHardwareDetectCallback(new HardwareDetection());
return OSVR_RETURN_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2015-2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <grpc++/server_builder.h>
#include <grpc++/impl/service_type.h>
#include <grpc++/server.h>
#include <grpc/support/cpu.h>
#include <grpc/support/log.h>
#include "src/cpp/server/thread_pool_interface.h"
namespace grpc {
static std::vector<std::unique_ptr<ServerBuilderPlugin> (*)()>*
g_plugin_factory_list;
static gpr_once once_init_plugin_list = GPR_ONCE_INIT;
static void do_plugin_list_init(void) {
g_plugin_factory_list =
new std::vector<std::unique_ptr<ServerBuilderPlugin> (*)()>();
}
ServerBuilder::ServerBuilder()
: max_message_size_(-1), generic_service_(nullptr) {
grpc_compression_options_init(&compression_options_);
gpr_once_init(&once_init_plugin_list, do_plugin_list_init);
for (auto factory : (*g_plugin_factory_list)) {
std::unique_ptr<ServerBuilderPlugin> plugin = factory();
plugins_[plugin->name()] = std::move(plugin);
}
}
std::unique_ptr<ServerCompletionQueue> ServerBuilder::AddCompletionQueue(
bool is_frequently_polled) {
ServerCompletionQueue* cq = new ServerCompletionQueue(is_frequently_polled);
cqs_.push_back(cq);
return std::unique_ptr<ServerCompletionQueue>(cq);
}
void ServerBuilder::RegisterService(Service* service) {
services_.emplace_back(new NamedService(service));
}
void ServerBuilder::RegisterService(const grpc::string& addr,
Service* service) {
services_.emplace_back(new NamedService(addr, service));
}
void ServerBuilder::RegisterAsyncGenericService(AsyncGenericService* service) {
if (generic_service_) {
gpr_log(GPR_ERROR,
"Adding multiple AsyncGenericService is unsupported for now. "
"Dropping the service %p",
service);
return;
}
generic_service_ = service;
}
void ServerBuilder::SetOption(std::unique_ptr<ServerBuilderOption> option) {
options_.push_back(std::move(option));
}
void ServerBuilder::AddListeningPort(const grpc::string& addr,
std::shared_ptr<ServerCredentials> creds,
int* selected_port) {
Port port = {addr, creds, selected_port};
ports_.push_back(port);
}
std::unique_ptr<Server> ServerBuilder::BuildAndStart() {
std::unique_ptr<ThreadPoolInterface> thread_pool;
for (auto it = services_.begin(); it != services_.end(); ++it) {
if ((*it)->service->has_synchronous_methods()) {
if (thread_pool == nullptr) {
thread_pool.reset(CreateDefaultThreadPool());
break;
}
}
}
ChannelArguments args;
for (auto option = options_.begin(); option != options_.end(); ++option) {
(*option)->UpdateArguments(&args);
(*option)->UpdatePlugins(&plugins_);
}
if (thread_pool == nullptr) {
for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) {
if ((*plugin).second->has_sync_methods()) {
thread_pool.reset(CreateDefaultThreadPool());
break;
}
}
}
if (max_message_size_ > 0) {
args.SetInt(GRPC_ARG_MAX_MESSAGE_LENGTH, max_message_size_);
}
args.SetInt(GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET,
compression_options_.enabled_algorithms_bitset);
std::unique_ptr<Server> server(
new Server(thread_pool.release(), true, max_message_size_, &args));
ServerInitializer* initializer = server->initializer();
// If the server has atleast one sync methods, we know that this is a Sync
// server or a Hybrid server and the completion queue (server->cq_) would be
// frequently polled.
int num_frequently_polled_cqs = (thread_pool != nullptr) ? 1 : 0;
for (auto cq = cqs_.begin(); cq != cqs_.end(); ++cq) {
// A completion queue that is not polled frequently (by calling Next() or
// AsyncNext()) is not safe to use for listening to incoming channels.
// Register all such completion queues as non-listening completion queues
// with the GRPC core library.
if ((*cq)->IsFrequentlyPolled()) {
grpc_server_register_completion_queue(server->server_, (*cq)->cq(),
nullptr);
num_frequently_polled_cqs++;
} else {
grpc_server_register_non_listening_completion_queue(server->server_,
(*cq)->cq(), nullptr);
}
}
if (num_frequently_polled_cqs == 0) {
gpr_log(GPR_ERROR,
"At least one of the completion queues must be frequently polled");
return nullptr;
}
for (auto service = services_.begin(); service != services_.end();
service++) {
if (!server->RegisterService((*service)->host.get(), (*service)->service)) {
return nullptr;
}
}
for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) {
(*plugin).second->InitServer(initializer);
}
if (generic_service_) {
server->RegisterAsyncGenericService(generic_service_);
} else {
for (auto it = services_.begin(); it != services_.end(); ++it) {
if ((*it)->service->has_generic_methods()) {
gpr_log(GPR_ERROR,
"Some methods were marked generic but there is no "
"generic service registered.");
return nullptr;
}
}
}
for (auto port = ports_.begin(); port != ports_.end(); port++) {
int r = server->AddListeningPort(port->addr, port->creds.get());
if (!r) return nullptr;
if (port->selected_port != nullptr) {
*port->selected_port = r;
}
}
auto cqs_data = cqs_.empty() ? nullptr : &cqs_[0];
if (!server->Start(cqs_data, cqs_.size())) {
return nullptr;
}
for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) {
(*plugin).second->Finish(initializer);
}
return server;
}
void ServerBuilder::InternalAddPluginFactory(
std::unique_ptr<ServerBuilderPlugin> (*CreatePlugin)()) {
gpr_once_init(&once_init_plugin_list, do_plugin_list_init);
(*g_plugin_factory_list).push_back(CreatePlugin);
}
} // namespace grpc
<commit_msg>Fix crash<commit_after>/*
*
* Copyright 2015-2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <grpc++/server_builder.h>
#include <grpc++/impl/service_type.h>
#include <grpc++/server.h>
#include <grpc/support/cpu.h>
#include <grpc/support/log.h>
#include "src/cpp/server/thread_pool_interface.h"
namespace grpc {
static std::vector<std::unique_ptr<ServerBuilderPlugin> (*)()>*
g_plugin_factory_list;
static gpr_once once_init_plugin_list = GPR_ONCE_INIT;
static void do_plugin_list_init(void) {
g_plugin_factory_list =
new std::vector<std::unique_ptr<ServerBuilderPlugin> (*)()>();
}
ServerBuilder::ServerBuilder()
: max_message_size_(-1), generic_service_(nullptr) {
grpc_compression_options_init(&compression_options_);
gpr_once_init(&once_init_plugin_list, do_plugin_list_init);
for (auto factory : (*g_plugin_factory_list)) {
std::unique_ptr<ServerBuilderPlugin> plugin = factory();
plugins_[plugin->name()] = std::move(plugin);
}
}
std::unique_ptr<ServerCompletionQueue> ServerBuilder::AddCompletionQueue(
bool is_frequently_polled) {
ServerCompletionQueue* cq = new ServerCompletionQueue(is_frequently_polled);
cqs_.push_back(cq);
return std::unique_ptr<ServerCompletionQueue>(cq);
}
void ServerBuilder::RegisterService(Service* service) {
services_.emplace_back(new NamedService(service));
}
void ServerBuilder::RegisterService(const grpc::string& addr,
Service* service) {
services_.emplace_back(new NamedService(addr, service));
}
void ServerBuilder::RegisterAsyncGenericService(AsyncGenericService* service) {
if (generic_service_) {
gpr_log(GPR_ERROR,
"Adding multiple AsyncGenericService is unsupported for now. "
"Dropping the service %p",
service);
return;
}
generic_service_ = service;
}
void ServerBuilder::SetOption(std::unique_ptr<ServerBuilderOption> option) {
options_.push_back(std::move(option));
}
void ServerBuilder::AddListeningPort(const grpc::string& addr,
std::shared_ptr<ServerCredentials> creds,
int* selected_port) {
Port port = {addr, creds, selected_port};
ports_.push_back(port);
}
std::unique_ptr<Server> ServerBuilder::BuildAndStart() {
std::unique_ptr<ThreadPoolInterface> thread_pool;
bool has_sync_methods = false;
for (auto it = services_.begin(); it != services_.end(); ++it) {
if ((*it)->service->has_synchronous_methods()) {
if (thread_pool == nullptr) {
thread_pool.reset(CreateDefaultThreadPool());
has_sync_methods = true;
break;
}
}
}
ChannelArguments args;
for (auto option = options_.begin(); option != options_.end(); ++option) {
(*option)->UpdateArguments(&args);
(*option)->UpdatePlugins(&plugins_);
}
if (thread_pool == nullptr) {
for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) {
if ((*plugin).second->has_sync_methods()) {
thread_pool.reset(CreateDefaultThreadPool());
break;
}
}
}
if (max_message_size_ > 0) {
args.SetInt(GRPC_ARG_MAX_MESSAGE_LENGTH, max_message_size_);
}
args.SetInt(GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET,
compression_options_.enabled_algorithms_bitset);
std::unique_ptr<Server> server(
new Server(thread_pool.release(), true, max_message_size_, &args));
ServerInitializer* initializer = server->initializer();
// If the server has atleast one sync methods, we know that this is a Sync
// server or a Hybrid server and the completion queue (server->cq_) would be
// frequently polled.
int num_frequently_polled_cqs = has_sync_methods ? 1 : 0;
for (auto cq = cqs_.begin(); cq != cqs_.end(); ++cq) {
// A completion queue that is not polled frequently (by calling Next() or
// AsyncNext()) is not safe to use for listening to incoming channels.
// Register all such completion queues as non-listening completion queues
// with the GRPC core library.
if ((*cq)->IsFrequentlyPolled()) {
grpc_server_register_completion_queue(server->server_, (*cq)->cq(),
nullptr);
num_frequently_polled_cqs++;
} else {
grpc_server_register_non_listening_completion_queue(server->server_,
(*cq)->cq(), nullptr);
}
}
if (num_frequently_polled_cqs == 0) {
gpr_log(GPR_ERROR,
"At least one of the completion queues must be frequently polled");
return nullptr;
}
for (auto service = services_.begin(); service != services_.end();
service++) {
if (!server->RegisterService((*service)->host.get(), (*service)->service)) {
return nullptr;
}
}
for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) {
(*plugin).second->InitServer(initializer);
}
if (generic_service_) {
server->RegisterAsyncGenericService(generic_service_);
} else {
for (auto it = services_.begin(); it != services_.end(); ++it) {
if ((*it)->service->has_generic_methods()) {
gpr_log(GPR_ERROR,
"Some methods were marked generic but there is no "
"generic service registered.");
return nullptr;
}
}
}
for (auto port = ports_.begin(); port != ports_.end(); port++) {
int r = server->AddListeningPort(port->addr, port->creds.get());
if (!r) return nullptr;
if (port->selected_port != nullptr) {
*port->selected_port = r;
}
}
auto cqs_data = cqs_.empty() ? nullptr : &cqs_[0];
if (!server->Start(cqs_data, cqs_.size())) {
return nullptr;
}
for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) {
(*plugin).second->Finish(initializer);
}
return server;
}
void ServerBuilder::InternalAddPluginFactory(
std::unique_ptr<ServerBuilderPlugin> (*CreatePlugin)()) {
gpr_once_init(&once_init_plugin_list, do_plugin_list_init);
(*g_plugin_factory_list).push_back(CreatePlugin);
}
} // namespace grpc
<|endoftext|>
|
<commit_before>#include "JeuxState.h"
using namespace Ogre;
using namespace Forests;
JeuxState::JeuxState()
: m_Loader(0),
m_TerrainImported(false),
m_SceneFile(Ogre::StringUtil::BLANK)
{
m_MoveSpeed = 1.0f;
m_RotateSpeed = 0.3f;
m_bQuit = false;
m_bLMouseDown = false;
m_bRMouseDown = false;
inputManager = InputManager::getSingletonPtr();
keyboardMap = KeyboardMap::getInstance();
}
void JeuxState::enter()
{
inputManager->addKeyListener(this,"Game1");
inputManager->addMouseListener(this,"Game2");
XsiliumFramework::getInstance()->m_pLog->logMessage("Entering JeuxState...");
createScene();
buildGUI();
}
bool JeuxState::pause()
{
XsiliumFramework::getInstance()->m_pLog->logMessage("Pausing JeuxState...");
return true;
}
void JeuxState::resume()
{
XsiliumFramework::getInstance()->m_pLog->logMessage("Resuming JeuxState...");
XsiliumFramework::getInstance()->m_pViewport->setCamera(m_pCamera);
m_bQuit = false;
}
void JeuxState::exit()
{
XsiliumFramework::getInstance()->m_pLog->logMessage("Leaving JeuxState...");
delete chat;
delete gestionnaireMeteo;
m_pSceneMgr->destroyCamera(m_pCamera);
if(m_pSceneMgr)
XsiliumFramework::getInstance()->m_pRoot->destroySceneManager(m_pSceneMgr);
inputManager->removeKeyListener(this);
inputManager->removeMouseListener(this);
}
void JeuxState::buildGUI()
{
chat = new Chat();
XsiliumFramework::getInstance()->m_pLog->logMessage("test");
}
void JeuxState::createScene()
{
m_pSceneMgr = XsiliumFramework::getInstance()->m_pRoot->createSceneManager(ST_GENERIC, "GameSceneMgr");
m_Loader = new DotSceneLoader();
m_Loader->parseDotScene("test-terrain.scene", "General", m_pSceneMgr);
// Loop through all cameras and grab their name and set their debug representation
Ogre::SceneManager::CameraIterator cameras = m_pSceneMgr->getCameraIterator();
while (cameras.hasMoreElements())
{
Ogre::Camera* camera = cameras.getNext();
mCamNames.push_back(camera->getName());
Ogre::Entity* debugEnt = m_pSceneMgr->createEntity(camera->getName() + Ogre::String("_debug"), "scbCamera.mesh");
Ogre::SceneNode* pNode = m_pSceneMgr->getRootSceneNode()->createChildSceneNode(camera->getName());
pNode->setPosition(camera->getPosition());
pNode->setOrientation(camera->getOrientation());
pNode->attachObject(debugEnt);
pNode->scale(0.5, 0.5, 0.5);
}
// Grab the first available camera, for now
Ogre::String cameraName = mCamNames[0];
try
{
m_pCamera = m_pSceneMgr->getCamera(cameraName);
XsiliumFramework::getInstance()->m_pRenderWnd->getViewport(0)->setCamera(m_pCamera);
// mCameraMan->setCamera(m_pCamera);
m_pSceneMgr->getEntity(m_pCamera->getName() + Ogre::String("_debug"))->setVisible(false);
for(unsigned int ij = 0;ij < m_Loader->mPGHandles.size();ij++)
{
m_Loader->mPGHandles[ij]->setCamera(m_pCamera);
}
}
catch (Ogre::Exception& e)
{
Ogre::LogManager::getSingleton().logMessage("SampleApp::createScene : setting the active camera to (\"" +
cameraName + ") failed: " + e.getFullDescription());
}
// gestionnaireMeteo = new GestionnaireMeteo(m_pSceneMgr,m_pCamera,m_Loader->getTerrainGroup());
// gestionnaireMeteo->create();
}
void JeuxState::update(double timeSinceLastFrame)
{
m_FrameEvent.timeSinceLastFrame = timeSinceLastFrame;
CEGUI::System& gui_system(CEGUI::System::getSingleton());
gui_system.injectTimePulse(timeSinceLastFrame);
gui_system.getDefaultGUIContext().injectTimePulse(timeSinceLastFrame);
if(m_bQuit == true)
{
popGameState();
return;
}
m_MoveScale = m_MoveSpeed * timeSinceLastFrame;
m_RotScale = m_RotateSpeed * timeSinceLastFrame;
m_TranslateVector = Ogre::Vector3::ZERO;
if(!chat->isActive())
getInput();
m_pCamera->moveRelative(m_TranslateVector / 10);
}
void JeuxState::getInput()
{
if(inputManager->getKeyboard()->isKeyDown(keyboardMap->checkKey("GAUCHE")))
m_TranslateVector.x = -m_MoveScale;
if(inputManager->getKeyboard()->isKeyDown(keyboardMap->checkKey("DROITE") ))
m_TranslateVector.x = m_MoveScale;
if(inputManager->getKeyboard()->isKeyDown(keyboardMap->checkKey("AVANCER")))
m_TranslateVector.z = -m_MoveScale;
if(inputManager->getKeyboard()->isKeyDown(keyboardMap->checkKey("RECULER")))
m_TranslateVector.z = m_MoveScale;
if(inputManager->getKeyboard()->isKeyDown(OIS::KC_0))
{
m_pCamera = m_pSceneMgr->getCamera("Camera#0");
XsiliumFramework::getInstance()->m_pRenderWnd->getViewport(0)->setCamera(m_pCamera);
}
if(inputManager->getKeyboard()->isKeyDown(OIS::KC_1))
{
m_pCamera = m_pSceneMgr->getCamera("Camera#1");
XsiliumFramework::getInstance()->m_pRenderWnd->getViewport(0)->setCamera(m_pCamera);
}
if(inputManager->getKeyboard()->isKeyDown(OIS::KC_2))
{
m_pCamera = m_pSceneMgr->getCamera("Camera#2");
XsiliumFramework::getInstance()->m_pRenderWnd->getViewport(0)->setCamera(m_pCamera);
}
}
bool JeuxState::keyPressed(const OIS::KeyEvent &keyEventRef)
{
switch(keyEventRef.key)
{
case OIS::KC_ESCAPE:
m_bQuit = true;
break;
case OIS::KC_LSHIFT:
m_pCamera->moveRelative(m_TranslateVector);
break;
default:
break;
}
return true;
}
bool JeuxState::keyReleased(const OIS::KeyEvent &keyEventRef)
{
return true;
}
bool JeuxState::mouseMoved( const OIS::MouseEvent &event )
{
if(m_bLMouseDown)
{
m_pCamera->yaw(Degree(event.state.X.rel * -0.1f));
m_pCamera->pitch(Degree(event.state.Y.rel * -0.1f));
}
return true;
}
bool JeuxState::mousePressed( const OIS::MouseEvent &event, OIS::MouseButtonID id )
{
if(id == OIS::MB_Left)
{
m_bLMouseDown = true;
}
else if(id == OIS::MB_Right)
{
m_bRMouseDown = true;
}
return true;
}
bool JeuxState::mouseReleased( const OIS::MouseEvent &event, OIS::MouseButtonID id )
{
if(id == OIS::MB_Left)
{
m_bLMouseDown = false;
}
else if(id == OIS::MB_Right)
{
m_bRMouseDown = false;
}
return true;
}
<commit_msg>Correction du bug lorsque l'on quitte le jeu<commit_after>#include "JeuxState.h"
using namespace Ogre;
using namespace Forests;
JeuxState::JeuxState()
: m_Loader(0),
m_TerrainImported(false),
m_SceneFile(Ogre::StringUtil::BLANK)
{
m_MoveSpeed = 1.0f;
m_RotateSpeed = 0.3f;
m_bQuit = false;
m_bLMouseDown = false;
m_bRMouseDown = false;
inputManager = InputManager::getSingletonPtr();
keyboardMap = KeyboardMap::getInstance();
}
void JeuxState::enter()
{
inputManager->addKeyListener(this,"Game1");
inputManager->addMouseListener(this,"Game2");
XsiliumFramework::getInstance()->m_pLog->logMessage("Entering JeuxState...");
createScene();
buildGUI();
}
bool JeuxState::pause()
{
XsiliumFramework::getInstance()->m_pLog->logMessage("Pausing JeuxState...");
return true;
}
void JeuxState::resume()
{
XsiliumFramework::getInstance()->m_pLog->logMessage("Resuming JeuxState...");
XsiliumFramework::getInstance()->m_pViewport->setCamera(m_pCamera);
m_bQuit = false;
}
void JeuxState::exit()
{
XsiliumFramework::getInstance()->m_pLog->logMessage("Leaving JeuxState...");
delete chat;
//delete gestionnaireMeteo;
m_pSceneMgr->destroyCamera(m_pCamera);
if(m_pSceneMgr)
XsiliumFramework::getInstance()->m_pRoot->destroySceneManager(m_pSceneMgr);
inputManager->removeKeyListener(this);
inputManager->removeMouseListener(this);
}
void JeuxState::buildGUI()
{
chat = new Chat();
XsiliumFramework::getInstance()->m_pLog->logMessage("test");
}
void JeuxState::createScene()
{
m_pSceneMgr = XsiliumFramework::getInstance()->m_pRoot->createSceneManager(ST_GENERIC, "GameSceneMgr");
m_Loader = new DotSceneLoader();
m_Loader->parseDotScene("test-terrain.scene", "General", m_pSceneMgr);
// Loop through all cameras and grab their name and set their debug representation
Ogre::SceneManager::CameraIterator cameras = m_pSceneMgr->getCameraIterator();
while (cameras.hasMoreElements())
{
Ogre::Camera* camera = cameras.getNext();
mCamNames.push_back(camera->getName());
Ogre::Entity* debugEnt = m_pSceneMgr->createEntity(camera->getName() + Ogre::String("_debug"), "scbCamera.mesh");
Ogre::SceneNode* pNode = m_pSceneMgr->getRootSceneNode()->createChildSceneNode(camera->getName());
pNode->setPosition(camera->getPosition());
pNode->setOrientation(camera->getOrientation());
pNode->attachObject(debugEnt);
pNode->scale(0.5, 0.5, 0.5);
}
// Grab the first available camera, for now
Ogre::String cameraName = mCamNames[0];
try
{
m_pCamera = m_pSceneMgr->getCamera(cameraName);
XsiliumFramework::getInstance()->m_pRenderWnd->getViewport(0)->setCamera(m_pCamera);
// mCameraMan->setCamera(m_pCamera);
m_pSceneMgr->getEntity(m_pCamera->getName() + Ogre::String("_debug"))->setVisible(false);
for(unsigned int ij = 0;ij < m_Loader->mPGHandles.size();ij++)
{
m_Loader->mPGHandles[ij]->setCamera(m_pCamera);
}
}
catch (Ogre::Exception& e)
{
Ogre::LogManager::getSingleton().logMessage("SampleApp::createScene : setting the active camera to (\"" +
cameraName + ") failed: " + e.getFullDescription());
}
// gestionnaireMeteo = new GestionnaireMeteo(m_pSceneMgr,m_pCamera,m_Loader->getTerrainGroup());
// gestionnaireMeteo->create();
}
void JeuxState::update(double timeSinceLastFrame)
{
m_FrameEvent.timeSinceLastFrame = timeSinceLastFrame;
CEGUI::System& gui_system(CEGUI::System::getSingleton());
gui_system.injectTimePulse(timeSinceLastFrame);
gui_system.getDefaultGUIContext().injectTimePulse(timeSinceLastFrame);
if(m_bQuit == true)
{
popGameState();
return;
}
m_MoveScale = m_MoveSpeed * timeSinceLastFrame;
m_RotScale = m_RotateSpeed * timeSinceLastFrame;
m_TranslateVector = Ogre::Vector3::ZERO;
if(!chat->isActive())
getInput();
m_pCamera->moveRelative(m_TranslateVector / 10);
}
void JeuxState::getInput()
{
if(inputManager->getKeyboard()->isKeyDown(keyboardMap->checkKey("GAUCHE")))
m_TranslateVector.x = -m_MoveScale;
if(inputManager->getKeyboard()->isKeyDown(keyboardMap->checkKey("DROITE") ))
m_TranslateVector.x = m_MoveScale;
if(inputManager->getKeyboard()->isKeyDown(keyboardMap->checkKey("AVANCER")))
m_TranslateVector.z = -m_MoveScale;
if(inputManager->getKeyboard()->isKeyDown(keyboardMap->checkKey("RECULER")))
m_TranslateVector.z = m_MoveScale;
if(inputManager->getKeyboard()->isKeyDown(OIS::KC_0))
{
m_pCamera = m_pSceneMgr->getCamera("Camera#0");
XsiliumFramework::getInstance()->m_pRenderWnd->getViewport(0)->setCamera(m_pCamera);
}
if(inputManager->getKeyboard()->isKeyDown(OIS::KC_1))
{
m_pCamera = m_pSceneMgr->getCamera("Camera#1");
XsiliumFramework::getInstance()->m_pRenderWnd->getViewport(0)->setCamera(m_pCamera);
}
if(inputManager->getKeyboard()->isKeyDown(OIS::KC_2))
{
m_pCamera = m_pSceneMgr->getCamera("Camera#2");
XsiliumFramework::getInstance()->m_pRenderWnd->getViewport(0)->setCamera(m_pCamera);
}
}
bool JeuxState::keyPressed(const OIS::KeyEvent &keyEventRef)
{
switch(keyEventRef.key)
{
case OIS::KC_ESCAPE:
m_bQuit = true;
break;
case OIS::KC_LSHIFT:
m_pCamera->moveRelative(m_TranslateVector);
break;
default:
break;
}
return true;
}
bool JeuxState::keyReleased(const OIS::KeyEvent &keyEventRef)
{
return true;
}
bool JeuxState::mouseMoved( const OIS::MouseEvent &event )
{
if(m_bLMouseDown)
{
m_pCamera->yaw(Degree(event.state.X.rel * -0.1f));
m_pCamera->pitch(Degree(event.state.Y.rel * -0.1f));
}
return true;
}
bool JeuxState::mousePressed( const OIS::MouseEvent &event, OIS::MouseButtonID id )
{
if(id == OIS::MB_Left)
{
m_bLMouseDown = true;
}
else if(id == OIS::MB_Right)
{
m_bRMouseDown = true;
}
return true;
}
bool JeuxState::mouseReleased( const OIS::MouseEvent &event, OIS::MouseButtonID id )
{
if(id == OIS::MB_Left)
{
m_bLMouseDown = false;
}
else if(id == OIS::MB_Right)
{
m_bRMouseDown = false;
}
return true;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 1999-2000,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/Janitor.hpp>
#include "ICUMsgLoader.hpp"
#include "unicode/putil.h"
#include "unicode/uloc.h"
#include "unicode/udata.h"
#include "string.h"
#include <stdio.h>
#include <stdlib.h>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Local static methods
// ---------------------------------------------------------------------------
/*
* Resource Data Reference.
*
* The data is packaged as a dll (or .so or whatever, depending on the platform) that exports a data symbol.
* The application (thic *.cpp) references that symbol here, and will pass the data address to ICU, which
* will then be able to fetch resources from the data.
*/
#if defined(_WIN32) || defined(WIN32)
extern "C" void U_IMPORT *XercesMessages2_6_dat;
#else
extern "C" void U_IMPORT *XercesMessages2_6_0_dat;
#endif
/*
* Tell ICU where our resource data is located in memory. The data lives in the XercesMessages dll, and we just
* pass the address of an exported symbol from that library to ICU.
*/
static bool setAppDataOK = false;
static void setAppData()
{
static bool setAppDataDone = false;
if (setAppDataDone)
{
return;
}
else
{
setAppDataDone = true;
UErrorCode err = U_ZERO_ERROR;
#if defined(_WIN32) || defined(WIN32)
udata_setAppData("XercesMessages2_6", &XercesMessages2_6_dat, &err);
#else
udata_setAppData("XercesMessages2_6_0", &XercesMessages2_6_0_dat, &err);
#endif
if (U_SUCCESS(err))
{
setAppDataOK = true;
}
}
}
// ---------------------------------------------------------------------------
// Public Constructors and Destructor
// ---------------------------------------------------------------------------
ICUMsgLoader::ICUMsgLoader(const XMLCh* const msgDomain)
:fLocaleBundle(0)
,fDomainBundle(0)
{
/***
Validate msgDomain
***/
if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain) &&
!XMLString::equals(msgDomain, XMLUni::fgExceptDomain) &&
!XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain) &&
!XMLString::equals(msgDomain, XMLUni::fgValidityDomain) )
{
XMLPlatformUtils::panic(PanicHandler::Panic_UnknownMsgDomain);
}
/***
Resolve domainName
***/
int index = XMLString::lastIndexOf(msgDomain, chForwardSlash);
char* domainName = XMLString::transcode(&(msgDomain[index + 1]), XMLPlatformUtils::fgMemoryManager);
ArrayJanitor<char> jan1(domainName, XMLPlatformUtils::fgMemoryManager);
/***
Location resolution priority
1. XMLMsgLoader::getNLSHome(), set by user through
XMLPlatformUtils::Initialize(), which provides user-specified
location where the message loader shall retrieve error messages.
2. envrionment var: XERCESC_NLS_HOME
3. path $XERCESCROOT/msg
***/
char locationBuf[1024];
memset(locationBuf, 0, sizeof locationBuf);
const char *nlsHome = XMLMsgLoader::getNLSHome();
if (nlsHome)
{
strcpy(locationBuf, nlsHome);
strcat(locationBuf, U_FILE_SEP_STRING);
}
else
{
nlsHome = getenv("XERCESC_NLS_HOME");
if (nlsHome)
{
strcpy(locationBuf, nlsHome);
strcat(locationBuf, U_FILE_SEP_STRING);
}
else
{
nlsHome = getenv("XERCESCROOT");
if (nlsHome)
{
strcpy(locationBuf, nlsHome);
strcat(locationBuf, U_FILE_SEP_STRING);
strcat(locationBuf, "msg");
strcat(locationBuf, U_FILE_SEP_STRING);
}
else
{
/***
leave it to ICU to decide where to search
for the error message.
***/
setAppData();
}
}
}
/***
Open the locale-specific resource bundle
***/
#if defined(_WIN32) || defined(WIN32)
strcat(locationBuf, "XercesMessages2_6");
#else
strcat(locationBuf, "XercesMessages2_6_0");
#endif
UErrorCode err = U_ZERO_ERROR;
uloc_setDefault("en_US", &err); // in case user-specified locale unavailable
err = U_ZERO_ERROR;
fLocaleBundle = ures_open(locationBuf, XMLMsgLoader::getLocale(), &err);
if (!U_SUCCESS(err) || fLocaleBundle == NULL)
{
/***
in case user specified location does not work
try the dll
***/
#if defined(_WIN32) || defined(WIN32)
if (strcmp(locationBuf, "XercesMessages2_6") !=0 )
#else
if (strcmp(locationBuf, "XercesMessages2_6_0") !=0 )
#endif
{
setAppData();
err = U_ZERO_ERROR;
#if defined(_WIN32) || defined(WIN32)
fLocaleBundle = ures_open("XercesMessages2_6", XMLMsgLoader::getLocale(), &err);
#else
fLocaleBundle = ures_open("XercesMessages2_6_0", XMLMsgLoader::getLocale(), &err);
#endif
if (!U_SUCCESS(err) || fLocaleBundle == NULL)
{
XMLPlatformUtils::panic(PanicHandler::Panic_CantLoadMsgDomain);
}
}
else
{
XMLPlatformUtils::panic(PanicHandler::Panic_CantLoadMsgDomain);
}
}
/***
Open the domain specific resource bundle within
the locale-specific resource bundle
***/
err = U_ZERO_ERROR;
fDomainBundle = ures_getByKey(fLocaleBundle, domainName, NULL, &err);
if (!U_SUCCESS(err) || fDomainBundle == NULL)
{
XMLPlatformUtils::panic(PanicHandler::Panic_CantLoadMsgDomain);
}
}
ICUMsgLoader::~ICUMsgLoader()
{
ures_close(fDomainBundle);
ures_close(fLocaleBundle);
}
// ---------------------------------------------------------------------------
// Implementation of the virtual message loader API
// ---------------------------------------------------------------------------
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars)
{
UErrorCode err = U_ZERO_ERROR;
int32_t strLen = 0;
// Assuming array format
const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err);
if (!U_SUCCESS(err) || (name == NULL))
{
return false;
}
int retStrLen = strLen > (int32_t)maxChars ? maxChars : strLen;
if (sizeof(UChar)==sizeof(XMLCh))
{
XMLString::moveChars(toFill, (XMLCh*)name, retStrLen);
toFill[retStrLen] = (XMLCh) 0;
}
else
{
XMLCh* retStr = toFill;
const UChar *srcPtr = name;
while (retStrLen--)
*retStr++ = *srcPtr++;
*retStr = 0;
}
return true;
}
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const XMLCh* const repText1
, const XMLCh* const repText2
, const XMLCh* const repText3
, const XMLCh* const repText4
, MemoryManager* const manager )
{
// Call the other version to load up the message
if (!loadMsg(msgToLoad, toFill, maxChars))
return false;
// And do the token replacement
XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4, manager);
return true;
}
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const char* const repText1
, const char* const repText2
, const char* const repText3
, const char* const repText4
, MemoryManager * const manager)
{
//
// Transcode the provided parameters and call the other version,
// which will do the replacement work.
//
XMLCh* tmp1 = 0;
XMLCh* tmp2 = 0;
XMLCh* tmp3 = 0;
XMLCh* tmp4 = 0;
bool bRet = false;
if (repText1)
tmp1 = XMLString::transcode(repText1, manager);
if (repText2)
tmp2 = XMLString::transcode(repText2, manager);
if (repText3)
tmp3 = XMLString::transcode(repText3, manager);
if (repText4)
tmp4 = XMLString::transcode(repText4, manager);
bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4, manager);
if (tmp1)
manager->deallocate(tmp1);//delete [] tmp1;
if (tmp2)
manager->deallocate(tmp2);//delete [] tmp2;
if (tmp3)
manager->deallocate(tmp3);//delete [] tmp3;
if (tmp4)
manager->deallocate(tmp4);//delete [] tmp4;
return bRet;
}
XERCES_CPP_NAMESPACE_END
<commit_msg>Reduced number of #ifdef<commit_after>/*
* Copyright 1999-2000,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/Janitor.hpp>
#include "ICUMsgLoader.hpp"
#include "unicode/putil.h"
#include "unicode/uloc.h"
#include "unicode/udata.h"
#include "string.h"
#include <stdio.h>
#include <stdlib.h>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Local static methods
// ---------------------------------------------------------------------------
/*
* Resource Data Reference.
*
* The data is packaged as a dll (or .so or whatever, depending on the platform) that exports a data symbol.
* The application (this *.cpp) references that symbol here, and will pass the data address to ICU, which
* will then be able to fetch resources from the data.
*/
#if defined(_WIN32) || defined(WIN32)
extern "C" void U_IMPORT *XercesMessages2_6_dat;
#define BUNDLE_NAME "XercesMessages2_6"
#else
extern "C" void U_IMPORT *XercesMessages2_6_0_dat;
#define BUNDLE_NAME "XercesMessages2_6_0"
#endif
/*
* Tell ICU where our resource data is located in memory. The data lives in the XercesMessages dll, and we just
* pass the address of an exported symbol from that library to ICU.
*/
static bool setAppDataOK = false;
static void setAppData()
{
static bool setAppDataDone = false;
if (setAppDataDone)
{
return;
}
else
{
setAppDataDone = true;
UErrorCode err = U_ZERO_ERROR;
udata_setAppData(BUNDLE_NAME, &XercesMessages2_6_dat, &err);
if (U_SUCCESS(err))
{
setAppDataOK = true;
}
}
}
// ---------------------------------------------------------------------------
// Public Constructors and Destructor
// ---------------------------------------------------------------------------
ICUMsgLoader::ICUMsgLoader(const XMLCh* const msgDomain)
:fLocaleBundle(0)
,fDomainBundle(0)
{
/***
Validate msgDomain
***/
if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain) &&
!XMLString::equals(msgDomain, XMLUni::fgExceptDomain) &&
!XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain) &&
!XMLString::equals(msgDomain, XMLUni::fgValidityDomain) )
{
XMLPlatformUtils::panic(PanicHandler::Panic_UnknownMsgDomain);
}
/***
Resolve domainName
***/
int index = XMLString::lastIndexOf(msgDomain, chForwardSlash);
char* domainName = XMLString::transcode(&(msgDomain[index + 1]), XMLPlatformUtils::fgMemoryManager);
ArrayJanitor<char> jan1(domainName, XMLPlatformUtils::fgMemoryManager);
/***
Location resolution priority
1. XMLMsgLoader::getNLSHome(), set by user through
XMLPlatformUtils::Initialize(), which provides user-specified
location where the message loader shall retrieve error messages.
2. environment var: XERCESC_NLS_HOME
3. path $XERCESCROOT/msg
***/
char locationBuf[1024];
memset(locationBuf, 0, sizeof locationBuf);
const char *nlsHome = XMLMsgLoader::getNLSHome();
if (nlsHome)
{
strcpy(locationBuf, nlsHome);
strcat(locationBuf, U_FILE_SEP_STRING);
}
else
{
nlsHome = getenv("XERCESC_NLS_HOME");
if (nlsHome)
{
strcpy(locationBuf, nlsHome);
strcat(locationBuf, U_FILE_SEP_STRING);
}
else
{
nlsHome = getenv("XERCESCROOT");
if (nlsHome)
{
strcpy(locationBuf, nlsHome);
strcat(locationBuf, U_FILE_SEP_STRING);
strcat(locationBuf, "msg");
strcat(locationBuf, U_FILE_SEP_STRING);
}
else
{
/***
leave it to ICU to decide where to search
for the error message.
***/
setAppData();
}
}
}
/***
Open the locale-specific resource bundle
***/
strcat(locationBuf, BUNDLE_NAME);
UErrorCode err = U_ZERO_ERROR;
uloc_setDefault("en_US", &err); // in case user-specified locale unavailable
err = U_ZERO_ERROR;
fLocaleBundle = ures_open(locationBuf, XMLMsgLoader::getLocale(), &err);
if (!U_SUCCESS(err) || fLocaleBundle == NULL)
{
/***
in case user specified location does not work
try the dll
***/
if (strcmp(locationBuf, BUNDLE_NAME) !=0 )
{
setAppData();
err = U_ZERO_ERROR;
fLocaleBundle = ures_open(BUNDLE_NAME, XMLMsgLoader::getLocale(), &err);
if (!U_SUCCESS(err) || fLocaleBundle == NULL)
{
XMLPlatformUtils::panic(PanicHandler::Panic_CantLoadMsgDomain);
}
}
else
{
XMLPlatformUtils::panic(PanicHandler::Panic_CantLoadMsgDomain);
}
}
/***
Open the domain specific resource bundle within
the locale-specific resource bundle
***/
err = U_ZERO_ERROR;
fDomainBundle = ures_getByKey(fLocaleBundle, domainName, NULL, &err);
if (!U_SUCCESS(err) || fDomainBundle == NULL)
{
XMLPlatformUtils::panic(PanicHandler::Panic_CantLoadMsgDomain);
}
}
ICUMsgLoader::~ICUMsgLoader()
{
ures_close(fDomainBundle);
ures_close(fLocaleBundle);
}
// ---------------------------------------------------------------------------
// Implementation of the virtual message loader API
// ---------------------------------------------------------------------------
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars)
{
UErrorCode err = U_ZERO_ERROR;
int32_t strLen = 0;
// Assuming array format
const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err);
if (!U_SUCCESS(err) || (name == NULL))
{
return false;
}
int retStrLen = strLen > (int32_t)maxChars ? maxChars : strLen;
if (sizeof(UChar)==sizeof(XMLCh))
{
XMLString::moveChars(toFill, (XMLCh*)name, retStrLen);
toFill[retStrLen] = (XMLCh) 0;
}
else
{
XMLCh* retStr = toFill;
const UChar *srcPtr = name;
while (retStrLen--)
*retStr++ = *srcPtr++;
*retStr = 0;
}
return true;
}
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const XMLCh* const repText1
, const XMLCh* const repText2
, const XMLCh* const repText3
, const XMLCh* const repText4
, MemoryManager* const manager )
{
// Call the other version to load up the message
if (!loadMsg(msgToLoad, toFill, maxChars))
return false;
// And do the token replacement
XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4, manager);
return true;
}
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const char* const repText1
, const char* const repText2
, const char* const repText3
, const char* const repText4
, MemoryManager * const manager)
{
//
// Transcode the provided parameters and call the other version,
// which will do the replacement work.
//
XMLCh* tmp1 = 0;
XMLCh* tmp2 = 0;
XMLCh* tmp3 = 0;
XMLCh* tmp4 = 0;
bool bRet = false;
if (repText1)
tmp1 = XMLString::transcode(repText1, manager);
if (repText2)
tmp2 = XMLString::transcode(repText2, manager);
if (repText3)
tmp3 = XMLString::transcode(repText3, manager);
if (repText4)
tmp4 = XMLString::transcode(repText4, manager);
bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4, manager);
if (tmp1)
manager->deallocate(tmp1);//delete [] tmp1;
if (tmp2)
manager->deallocate(tmp2);//delete [] tmp2;
if (tmp3)
manager->deallocate(tmp3);//delete [] tmp3;
if (tmp4)
manager->deallocate(tmp4);//delete [] tmp4;
return bRet;
}
XERCES_CPP_NAMESPACE_END
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.8 2002/11/20 20:28:17 peiyongz
* fix to warning C4018: '>' : signed/unsigned mismatch
*
* Revision 1.7 2002/11/12 17:27:49 tng
* DOM Message: add new domain for DOM Messages.
*
* Revision 1.6 2002/11/04 22:24:43 peiyongz
* Locale setting for message loader
*
* Revision 1.5 2002/11/04 15:10:40 tng
* C++ Namespace Support.
*
* Revision 1.4 2002/10/10 21:07:55 peiyongz
* load resource files using environement vars and base name
*
* Revision 1.3 2002/10/02 17:08:50 peiyongz
* XMLString::equals() to replace XMLString::compareString()
*
* Revision 1.2 2002/09/30 22:20:40 peiyongz
* Build with ICU MsgLoader
*
* Revision 1.1.1.1 2002/02/01 22:22:19 peiyongz
* sane_include
*
* Revision 1.7 2002/01/21 14:52:25 tng
* [Bug 5847] ICUMsgLoader can't be compiled with gcc 3.0.3 and ICU2. And also fix the memory leak introduced by Bug 2730 fix.
*
* Revision 1.6 2001/11/01 23:39:18 jasons
* 2001-11-01 Jason E. Stewart <jason@openinformatics.com>
*
* * src/util/MsgLoaders/ICU/ICUMsgLoader.hpp (Repository):
* * src/util/MsgLoaders/ICU/ICUMsgLoader.cpp (Repository):
* Updated to compile with ICU-1.8.1
*
* Revision 1.5 2000/03/02 19:55:14 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.4 2000/02/06 07:48:21 rahulj
* Year 2K copyright swat.
*
* Revision 1.3 2000/01/19 00:58:38 roddey
* Update to support new ICU 1.4 release.
*
* Revision 1.2 1999/11/19 21:24:03 aruna1
* incorporated ICU 1.3.1 related changes int he file
*
* Revision 1.1.1.1 1999/11/09 01:07:23 twl
* Initial checkin
*
* Revision 1.4 1999/11/08 20:45:26 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/Janitor.hpp>
#include "ICUMsgLoader.hpp"
#include "string.h"
#include <stdio.h>
#include <stdlib.h>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Local static methods
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Public Constructors and Destructor
// ---------------------------------------------------------------------------
ICUMsgLoader::ICUMsgLoader(const XMLCh* const msgDomain)
:fLocaleBundle(0)
,fDomainBundle(0)
{
/***
Validate msgDomain
***/
if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain) &&
!XMLString::equals(msgDomain, XMLUni::fgExceptDomain) &&
!XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain) &&
!XMLString::equals(msgDomain, XMLUni::fgValidityDomain) )
{
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);
}
/***
Resolve domainName
***/
int index = XMLString::lastIndexOf(msgDomain, chForwardSlash);
char* domainName = XMLString::transcode(&(msgDomain[index + 1]));
ArrayJanitor<char> jan1(domainName);
/***
Resolve location
REVISIT: another approach would be: through some system API
which returns the directory of the XercescLib and
that directory would be used to locate the
resource bundle
***/
char locationBuf[1024];
memset(locationBuf, 0, sizeof locationBuf);
char *nlsHome = getenv("XERCESC_NLS_HOME");
if (nlsHome)
{
strcpy(locationBuf, nlsHome);
strcat(locationBuf, U_FILE_SEP_STRING);
}
strcat(locationBuf, "XercescErrMsg");
/***
Open the locale-specific resource bundle
***/
UErrorCode err = U_ZERO_ERROR;
fLocaleBundle = ures_open(locationBuf, XMLMsgLoader::getLocale(), &err);
if (!U_SUCCESS(err) || fLocaleBundle == NULL)
{
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
}
/***
Open the domain specific resource bundle within
the locale-specific resource bundle
***/
err = U_ZERO_ERROR;
fDomainBundle = ures_getByKey(fLocaleBundle, domainName, NULL, &err);
if (!U_SUCCESS(err) || fDomainBundle == NULL)
{
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
}
}
ICUMsgLoader::~ICUMsgLoader()
{
ures_close(fDomainBundle);
ures_close(fLocaleBundle);
}
// ---------------------------------------------------------------------------
// Implementation of the virtual message loader API
// ---------------------------------------------------------------------------
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars)
{
UErrorCode err = U_ZERO_ERROR;
int32_t strLen = 0;
// Assuming array format
const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err);
if (!U_SUCCESS(err) || (name == NULL))
{
return false;
}
int retStrLen = strLen > (int32_t)maxChars ? maxChars : strLen;
if (sizeof(UChar)==sizeof(XMLCh))
{
XMLString::moveChars(toFill, (XMLCh*)name, retStrLen);
toFill[retStrLen] = (XMLCh) 0;
}
else
{
XMLCh* retStr = toFill;
const UChar *srcPtr = name;
while (retStrLen--)
*retStr++ = *srcPtr++;
*retStr = 0;
}
return true;
}
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const XMLCh* const repText1
, const XMLCh* const repText2
, const XMLCh* const repText3
, const XMLCh* const repText4)
{
// Call the other version to load up the message
if (!loadMsg(msgToLoad, toFill, maxChars))
return false;
// And do the token replacement
XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);
return true;
}
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const char* const repText1
, const char* const repText2
, const char* const repText3
, const char* const repText4)
{
//
// Transcode the provided parameters and call the other version,
// which will do the replacement work.
//
XMLCh* tmp1 = 0;
XMLCh* tmp2 = 0;
XMLCh* tmp3 = 0;
XMLCh* tmp4 = 0;
bool bRet = false;
if (repText1)
tmp1 = XMLString::transcode(repText1);
if (repText2)
tmp2 = XMLString::transcode(repText2);
if (repText3)
tmp3 = XMLString::transcode(repText3);
if (repText4)
tmp4 = XMLString::transcode(repText4);
bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);
if (tmp1)
delete [] tmp1;
if (tmp2)
delete [] tmp2;
if (tmp3)
delete [] tmp3;
if (tmp4)
delete [] tmp4;
return bRet;
}
XERCES_CPP_NAMESPACE_END
<commit_msg>use $XERCESCROOT to search for icu resource bundle if XERCESC_NLS_HOME undefined<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.9 2002/12/04 18:11:23 peiyongz
* use $XERCESCROOT to search for icu resource bundle if XERCESC_NLS_HOME
* undefined
*
* Revision 1.8 2002/11/20 20:28:17 peiyongz
* fix to warning C4018: '>' : signed/unsigned mismatch
*
* Revision 1.7 2002/11/12 17:27:49 tng
* DOM Message: add new domain for DOM Messages.
*
* Revision 1.6 2002/11/04 22:24:43 peiyongz
* Locale setting for message loader
*
* Revision 1.5 2002/11/04 15:10:40 tng
* C++ Namespace Support.
*
* Revision 1.4 2002/10/10 21:07:55 peiyongz
* load resource files using environement vars and base name
*
* Revision 1.3 2002/10/02 17:08:50 peiyongz
* XMLString::equals() to replace XMLString::compareString()
*
* Revision 1.2 2002/09/30 22:20:40 peiyongz
* Build with ICU MsgLoader
*
* Revision 1.1.1.1 2002/02/01 22:22:19 peiyongz
* sane_include
*
* Revision 1.7 2002/01/21 14:52:25 tng
* [Bug 5847] ICUMsgLoader can't be compiled with gcc 3.0.3 and ICU2. And also fix the memory leak introduced by Bug 2730 fix.
*
* Revision 1.6 2001/11/01 23:39:18 jasons
* 2001-11-01 Jason E. Stewart <jason@openinformatics.com>
*
* * src/util/MsgLoaders/ICU/ICUMsgLoader.hpp (Repository):
* * src/util/MsgLoaders/ICU/ICUMsgLoader.cpp (Repository):
* Updated to compile with ICU-1.8.1
*
* Revision 1.5 2000/03/02 19:55:14 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.4 2000/02/06 07:48:21 rahulj
* Year 2K copyright swat.
*
* Revision 1.3 2000/01/19 00:58:38 roddey
* Update to support new ICU 1.4 release.
*
* Revision 1.2 1999/11/19 21:24:03 aruna1
* incorporated ICU 1.3.1 related changes int he file
*
* Revision 1.1.1.1 1999/11/09 01:07:23 twl
* Initial checkin
*
* Revision 1.4 1999/11/08 20:45:26 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/Janitor.hpp>
#include "ICUMsgLoader.hpp"
#include "string.h"
#include <stdio.h>
#include <stdlib.h>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Local static methods
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Public Constructors and Destructor
// ---------------------------------------------------------------------------
ICUMsgLoader::ICUMsgLoader(const XMLCh* const msgDomain)
:fLocaleBundle(0)
,fDomainBundle(0)
{
/***
Validate msgDomain
***/
if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain) &&
!XMLString::equals(msgDomain, XMLUni::fgExceptDomain) &&
!XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain) &&
!XMLString::equals(msgDomain, XMLUni::fgValidityDomain) )
{
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);
}
/***
Resolve domainName
***/
int index = XMLString::lastIndexOf(msgDomain, chForwardSlash);
char* domainName = XMLString::transcode(&(msgDomain[index + 1]));
ArrayJanitor<char> jan1(domainName);
/***
Resolve location
REVISIT: another approach would be: through some system API
which returns the directory of the XercescLib and
that directory would be used to locate the
resource bundle
***/
char locationBuf[1024];
memset(locationBuf, 0, sizeof locationBuf);
char *nlsHome = getenv("XERCESC_NLS_HOME");
if (nlsHome)
{
strcpy(locationBuf, nlsHome);
strcat(locationBuf, U_FILE_SEP_STRING);
}
else
{
char *altHome = getenv("XERCESCROOT");
if (altHome)
{
strcpy(locationBuf, altHome);
strcat(locationBuf, U_FILE_SEP_STRING);
strcat(locationBuf, "lib");
strcat(locationBuf, U_FILE_SEP_STRING);
}
}
strcat(locationBuf, "XercescErrMsg");
/***
Open the locale-specific resource bundle
***/
UErrorCode err = U_ZERO_ERROR;
fLocaleBundle = ures_open(locationBuf, XMLMsgLoader::getLocale(), &err);
if (!U_SUCCESS(err) || fLocaleBundle == NULL)
{
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
}
/***
Open the domain specific resource bundle within
the locale-specific resource bundle
***/
err = U_ZERO_ERROR;
fDomainBundle = ures_getByKey(fLocaleBundle, domainName, NULL, &err);
if (!U_SUCCESS(err) || fDomainBundle == NULL)
{
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);
}
}
ICUMsgLoader::~ICUMsgLoader()
{
ures_close(fDomainBundle);
ures_close(fLocaleBundle);
}
// ---------------------------------------------------------------------------
// Implementation of the virtual message loader API
// ---------------------------------------------------------------------------
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars)
{
UErrorCode err = U_ZERO_ERROR;
int32_t strLen = 0;
// Assuming array format
const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err);
if (!U_SUCCESS(err) || (name == NULL))
{
return false;
}
int retStrLen = strLen > (int32_t)maxChars ? maxChars : strLen;
if (sizeof(UChar)==sizeof(XMLCh))
{
XMLString::moveChars(toFill, (XMLCh*)name, retStrLen);
toFill[retStrLen] = (XMLCh) 0;
}
else
{
XMLCh* retStr = toFill;
const UChar *srcPtr = name;
while (retStrLen--)
*retStr++ = *srcPtr++;
*retStr = 0;
}
return true;
}
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const XMLCh* const repText1
, const XMLCh* const repText2
, const XMLCh* const repText3
, const XMLCh* const repText4)
{
// Call the other version to load up the message
if (!loadMsg(msgToLoad, toFill, maxChars))
return false;
// And do the token replacement
XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);
return true;
}
bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const char* const repText1
, const char* const repText2
, const char* const repText3
, const char* const repText4)
{
//
// Transcode the provided parameters and call the other version,
// which will do the replacement work.
//
XMLCh* tmp1 = 0;
XMLCh* tmp2 = 0;
XMLCh* tmp3 = 0;
XMLCh* tmp4 = 0;
bool bRet = false;
if (repText1)
tmp1 = XMLString::transcode(repText1);
if (repText2)
tmp2 = XMLString::transcode(repText2);
if (repText3)
tmp3 = XMLString::transcode(repText3);
if (repText4)
tmp4 = XMLString::transcode(repText4);
bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);
if (tmp1)
delete [] tmp1;
if (tmp2)
delete [] tmp2;
if (tmp3)
delete [] tmp3;
if (tmp4)
delete [] tmp4;
return bRet;
}
XERCES_CPP_NAMESPACE_END
<|endoftext|>
|
<commit_before>/*
**
* BEGIN_COPYRIGHT
*
* load_tools is a plugin for SciDB. Copyright (C) 2008-2014 SciDB, Inc.
*
* load_tools is free software: you can redistribute it and/or modify
* it under the terms of the AFFERO GNU General Public License as published by
* the Free Software Foundation.
*
* load_tools is distributed "AS-IS" AND WITHOUT ANY WARRANTY OF ANY KIND,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* NON-INFRINGEMENT, OR FITNESS FOR A PARTICULAR PURPOSE. See
* the AFFERO GNU General Public License for the complete license terms.
*
* You should have received a copy of the AFFERO GNU General Public License
* along with load_tools. If not, see <http://www.gnu.org/licenses/agpl-3.0.html>
*
* END_COPYRIGHT
*/
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <vector>
#include <boost/lexical_cast.hpp>
#include <boost/assign.hpp>
#include "query/FunctionLibrary.h"
#include "query/FunctionDescription.h"
#include "system/ErrorsLibrary.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace scidb;
/**
* DCAST: cast with default, does not throw an error. Tries to cast input to the appropriate type. If the cast fails,
* returns the supplied default.
*/
template <typename T>
static void dcast(const Value** args, Value *res, void*)
{
if(args[0]->isNull())
{
res->setNull(args[0]->getMissingReason());
return;
}
const char* s = args[0]->getString();
try
{
T result = lexical_cast<T>(s);
res->set<T>(result);
}
catch(...)
{
Value const* def = args[1];
if(def->isNull())
{
res->setNull( def->getMissingReason());
}
else
{
res->set<T>(def->get<T>());
}
}
}
static scidb::UserDefinedFunction dcast_uint64 (scidb::FunctionDescription("dcast", list_of("string")("uint64"), "uint64", &dcast<uint64_t> ));
static scidb::UserDefinedFunction dcast_int64 (scidb::FunctionDescription("dcast", list_of("string")("int64"), "int64" , &dcast<int64_t>));
static scidb::UserDefinedFunction dcast_double (scidb::FunctionDescription("dcast", list_of("string")("double"), "double", &dcast<double> ));
/**
* first argument: the string to trim
* second argument: a set of characters to trim, represented as another string {S}
* returns: the first argument with all occurrences of any of the characters in S removed from the beginning or end of the string
*/
static void trim (const Value** args, Value *res, void*)
{
if(args[0]->isNull())
{
res->setNull(args[0]->getMissingReason());
return;
}
const char* input = args[0]->getString();
size_t inputLen = args[0]->size();
const char* chars = args[1]->getString();
size_t charsLen = args[1]->size();
if (charsLen == 0 || (charsLen ==1 && chars[0]==0))
{
res->setSize(inputLen);
memcpy(res->data(), input, inputLen);
return;
}
const char* start = input;
for(size_t i=0; i<inputLen; ++i)
{
char ch = input[i];
if(ch==0)
{
break;
}
bool match = false;
for(size_t j=0; j<charsLen; ++j)
{
if(ch == chars[j])
{
match =true;
break;
}
}
if(!match)
{
break;
}
++start;
}
const char* end = input + inputLen - 1;
for(ssize_t i = inputLen-1; i>=0; --i)
{
char ch = input[i];
if(ch==0)
{
continue;
}
bool match = false;
for(size_t j=0; j<charsLen; ++j)
{
if(ch == chars[j])
{
match =true;
break;
}
}
if(!match)
{
break;
}
--end;
}
if (inputLen == 0 || (inputLen ==1 && input[0]==0) || start >= end)
{
res->setSize(1);
((char *) res->data())[0]=0;
return;
}
size_t size = end - start + 1;
res->setSize(size);
memcpy(res->data(), start, (end-start));
((char*)res->data())[size-1]=0;
}
static scidb::UserDefinedFunction trim_str (scidb::FunctionDescription("trim", list_of("string")("string"), "string", &trim ));
static void int_to_char (const Value** args, Value *res, void*)
{
if(args[0]->isNull())
{
res->setNull(args[0]->getMissingReason());
return;
}
uint8_t input = args[0]->getUint8();
res->setChar(input);
}
static scidb::UserDefinedFunction int_to_c (scidb::FunctionDescription("int_to_char", list_of("uint8"), "char", &int_to_char ));
static scidb::UserDefinedFunction c_to_int (scidb::FunctionDescription("char_to_int", list_of("char"), "uint8", &int_to_char ));
static void codify (const Value** args, Value *res, void*)
{
if(args[0]->isNull())
{
res->setNull(args[0]->getMissingReason());
return;
}
const char* input = args[0]->getString();
size_t inputLen = args[0]->size();
ostringstream out;
for (size_t i=0; i< inputLen; ++i)
{
char c = input[i];
int32_t res = c;
out<<res<<"|";
}
res->setString(out.str().c_str());
}
static scidb::UserDefinedFunction asciify_str (scidb::FunctionDescription("codify", list_of("string"), "string", &codify ));
<commit_msg>Added a few more types to dmetric<commit_after>/*
**
* BEGIN_COPYRIGHT
*
* load_tools is a plugin for SciDB. Copyright (C) 2008-2014 SciDB, Inc.
*
* load_tools is free software: you can redistribute it and/or modify
* it under the terms of the AFFERO GNU General Public License as published by
* the Free Software Foundation.
*
* load_tools is distributed "AS-IS" AND WITHOUT ANY WARRANTY OF ANY KIND,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* NON-INFRINGEMENT, OR FITNESS FOR A PARTICULAR PURPOSE. See
* the AFFERO GNU General Public License for the complete license terms.
*
* You should have received a copy of the AFFERO GNU General Public License
* along with load_tools. If not, see <http://www.gnu.org/licenses/agpl-3.0.html>
*
* END_COPYRIGHT
*/
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <vector>
#include <boost/lexical_cast.hpp>
#include <boost/assign.hpp>
#include "query/FunctionLibrary.h"
#include "query/FunctionDescription.h"
#include "system/ErrorsLibrary.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace scidb;
/**
* DCAST: cast with default, does not throw an error. Tries to cast input to the appropriate type. If the cast fails,
* returns the supplied default.
*/
template <typename T>
static void dcast(const Value** args, Value *res, void*)
{
if(args[0]->isNull())
{
res->setNull(args[0]->getMissingReason());
return;
}
const char* s = args[0]->getString();
try
{
T result = lexical_cast<T>(s);
res->set<T>(result);
}
catch(...)
{
Value const* def = args[1];
if(def->isNull())
{
res->setNull( def->getMissingReason());
}
else
{
res->set<T>(def->get<T>());
}
}
}
static scidb::UserDefinedFunction dcast_double (scidb::FunctionDescription("dcast", list_of("string")("double"), "double", &dcast<double> ));
static scidb::UserDefinedFunction dcast_float (scidb::FunctionDescription("dcast", list_of("string")("float"), "float", &dcast<float> ));
static scidb::UserDefinedFunction dcast_bool (scidb::FunctionDescription("dcast", list_of("string")("bool"), "bool", &dcast<bool> ));
static scidb::UserDefinedFunction dcast_int64 (scidb::FunctionDescription("dcast", list_of("string")("int64"), "int64" , &dcast<int64_t>));
static scidb::UserDefinedFunction dcast_int32 (scidb::FunctionDescription("dcast", list_of("string")("int32"), "int32", &dcast<int32_t> ));
static scidb::UserDefinedFunction dcast_int16 (scidb::FunctionDescription("dcast", list_of("string")("int16"), "int16", &dcast<int16_t> ));
static scidb::UserDefinedFunction dcast_int8 (scidb::FunctionDescription("dcast", list_of("string")("int8"), "int8", &dcast<int8_t> ));
static scidb::UserDefinedFunction dcast_uint64 (scidb::FunctionDescription("dcast", list_of("string")("uint64"), "uint64", &dcast<uint64_t> ));
static scidb::UserDefinedFunction dcast_uint32 (scidb::FunctionDescription("dcast", list_of("string")("uint32"), "uint32", &dcast<uint32_t> ));
static scidb::UserDefinedFunction dcast_uint16 (scidb::FunctionDescription("dcast", list_of("string")("uint16"), "uint16", &dcast<uint16_t> ));
static scidb::UserDefinedFunction dcast_uint8 (scidb::FunctionDescription("dcast", list_of("string")("uint8"), "uint8", &dcast<uint8_t> ));
// XXX How to add datetime conversion here? The naive approach:
//static scidb::UserDefinedFunction dcast_datetimetz (scidb::FunctionDescription("dcast", list_of("string")("datetimetz"), "datetimetz", &dcast<datetimetz> ));
// doesn't work!
/**
* first argument: the string to trim
* second argument: a set of characters to trim, represented as another string {S}
* returns: the first argument with all occurrences of any of the characters in S removed from the beginning or end of the string
*/
static void trim (const Value** args, Value *res, void*)
{
if(args[0]->isNull())
{
res->setNull(args[0]->getMissingReason());
return;
}
const char* input = args[0]->getString();
size_t inputLen = args[0]->size();
const char* chars = args[1]->getString();
size_t charsLen = args[1]->size();
if (charsLen == 0 || (charsLen ==1 && chars[0]==0))
{
res->setSize(inputLen);
memcpy(res->data(), input, inputLen);
return;
}
const char* start = input;
for(size_t i=0; i<inputLen; ++i)
{
char ch = input[i];
if(ch==0)
{
break;
}
bool match = false;
for(size_t j=0; j<charsLen; ++j)
{
if(ch == chars[j])
{
match =true;
break;
}
}
if(!match)
{
break;
}
++start;
}
const char* end = input + inputLen - 1;
for(ssize_t i = inputLen-1; i>=0; --i)
{
char ch = input[i];
if(ch==0)
{
continue;
}
bool match = false;
for(size_t j=0; j<charsLen; ++j)
{
if(ch == chars[j])
{
match =true;
break;
}
}
if(!match)
{
break;
}
--end;
}
if (inputLen == 0 || (inputLen ==1 && input[0]==0) || start >= end)
{
res->setSize(1);
((char *) res->data())[0]=0;
return;
}
size_t size = end - start + 1;
res->setSize(size);
memcpy(res->data(), start, (end-start));
((char*)res->data())[size-1]=0;
}
static scidb::UserDefinedFunction trim_str (scidb::FunctionDescription("trim", list_of("string")("string"), "string", &trim ));
static void int_to_char (const Value** args, Value *res, void*)
{
if(args[0]->isNull())
{
res->setNull(args[0]->getMissingReason());
return;
}
uint8_t input = args[0]->getUint8();
res->setChar(input);
}
static scidb::UserDefinedFunction int_to_c (scidb::FunctionDescription("int_to_char", list_of("uint8"), "char", &int_to_char ));
static scidb::UserDefinedFunction c_to_int (scidb::FunctionDescription("char_to_int", list_of("char"), "uint8", &int_to_char ));
static void codify (const Value** args, Value *res, void*)
{
if(args[0]->isNull())
{
res->setNull(args[0]->getMissingReason());
return;
}
const char* input = args[0]->getString();
size_t inputLen = args[0]->size();
ostringstream out;
for (size_t i=0; i< inputLen; ++i)
{
char c = input[i];
int32_t res = c;
out<<res<<"|";
}
res->setString(out.str().c_str());
}
static scidb::UserDefinedFunction asciify_str (scidb::FunctionDescription("codify", list_of("string"), "string", &codify ));
<|endoftext|>
|
<commit_before>/*********************************************************************
*
* Copyright (c) 2017, Saurav Agarwal
* All rights reserved.
*
*********************************************************************/
#include "G2OSolver.h"
#include "g2o/core/block_solver.h"
#include "g2o/core/factory.h"
#include "g2o/core/robust_kernel_impl.h"
#include "g2o/core/optimization_algorithm_factory.h"
#include "g2o/core/optimization_algorithm_levenberg.h"
#include "g2o/types/slam2d/types_slam2d.h"
#include "g2o/solvers/cholmod/linear_solver_cholmod.h"
#include <open_karto/Karto.h>
#include <ros/console.h>
typedef g2o::BlockSolver< g2o::BlockSolverTraits<-1, -1> > SlamBlockSolver;
typedef g2o::LinearSolverCholmod<SlamBlockSolver::PoseMatrixType> SlamLinearSolver;
G2OSolver::G2OSolver()
{
// Initialize the SparseOptimizer
auto linearSolver = g2o::make_unique<SlamLinearSolver>();
linearSolver->setBlockOrdering(false);
auto blockSolver = g2o::make_unique<SlamBlockSolver>(std::move(linearSolver));
optimizer_.setAlgorithm(new g2o::OptimizationAlgorithmLevenberg(blockSolver));
latestNodeID_ = 0;
useRobustKernel_ = true;
}
G2OSolver::~G2OSolver()
{
// destroy all the singletons
g2o::Factory::destroy();
g2o::OptimizationAlgorithmFactory::destroy();
g2o::HyperGraphActionLibrary::destroy();
}
void G2OSolver::Clear()
{
corrections_.clear();
}
const karto::ScanSolver::IdPoseVector& G2OSolver::GetCorrections() const
{
return corrections_;
}
void G2OSolver::Compute()
{
corrections_.clear();
// Fix the first node in the graph to hold the map in place
g2o::OptimizableGraph::Vertex* first = optimizer_.vertex(0);
if(!first)
{
ROS_ERROR("[g2o] No Node with ID 0 found!");
return;
}
first->setFixed(true);
// Do the graph optimization
optimizer_.initializeOptimization();
int iter = optimizer_.optimize(500);
if (iter > 0)
{
ROS_INFO("[g2o] Optimization finished after %d iterations.", iter);
}
else
{
ROS_ERROR("[g2o] Optimization failed, result might be invalid!");
return;
}
// Write the result so it can be used by the mapper
g2o::SparseOptimizer::VertexContainer nodes = optimizer_.activeVertices();
for (g2o::SparseOptimizer::VertexContainer::const_iterator n = nodes.begin(); n != nodes.end(); n++)
{
double estimate[3];
if((*n)->getEstimateData(estimate))
{
karto::Pose2 pose(estimate[0], estimate[1], estimate[2]);
corrections_.push_back(std::make_pair((*n)->id(), pose));
}
else
{
ROS_ERROR("[g2o] Could not get estimated pose from Optimizer!");
}
}
}
void G2OSolver::AddNode(karto::Vertex<karto::LocalizedRangeScan>* pVertex)
{
karto::Pose2 odom = pVertex->GetObject()->GetCorrectedPose();
g2o::VertexSE2* poseVertex = new g2o::VertexSE2;
poseVertex->setEstimate(g2o::SE2(odom.GetX(), odom.GetY(), odom.GetHeading()));
poseVertex->setId(pVertex->GetObject()->GetUniqueId());
optimizer_.addVertex(poseVertex);
latestNodeID_ = pVertex->GetObject()->GetUniqueId();
ROS_DEBUG("[g2o] Adding node %d.", pVertex->GetObject()->GetUniqueId());
}
void G2OSolver::AddConstraint(karto::Edge<karto::LocalizedRangeScan>* pEdge)
{
// Create a new edge
g2o::EdgeSE2* odometry = new g2o::EdgeSE2;
// Set source and target
int sourceID = pEdge->GetSource()->GetObject()->GetUniqueId();
int targetID = pEdge->GetTarget()->GetObject()->GetUniqueId();
odometry->vertices()[0] = optimizer_.vertex(sourceID);
odometry->vertices()[1] = optimizer_.vertex(targetID);
if(odometry->vertices()[0] == NULL)
{
ROS_ERROR("[g2o] Source vertex with id %d does not exist!", sourceID);
delete odometry;
return;
}
if(odometry->vertices()[0] == NULL)
{
ROS_ERROR("[g2o] Target vertex with id %d does not exist!", targetID);
delete odometry;
return;
}
// Set the measurement (odometry distance between vertices)
karto::LinkInfo* pLinkInfo = (karto::LinkInfo*)(pEdge->GetLabel());
karto::Pose2 diff = pLinkInfo->GetPoseDifference();
g2o::SE2 measurement(diff.GetX(), diff.GetY(), diff.GetHeading());
odometry->setMeasurement(measurement);
// Set the covariance of the measurement
karto::Matrix3 precisionMatrix = pLinkInfo->GetCovariance().Inverse();
Eigen::Matrix<double,3,3> info;
info(0,0) = precisionMatrix(0,0);
info(0,1) = info(1,0) = precisionMatrix(0,1);
info(0,2) = info(2,0) = precisionMatrix(0,2);
info(1,1) = precisionMatrix(1,1);
info(1,2) = info(2,1) = precisionMatrix(1,2);
info(2,2) = precisionMatrix(2,2);
odometry->setInformation(info);
if(useRobustKernel_)
{
g2o::RobustKernelDCS* rk = new g2o::RobustKernelDCS;
odometry->setRobustKernel(rk);
}
// Add the constraint to the optimizer
ROS_DEBUG("[g2o] Adding Edge from node %d to node %d.", sourceID, targetID);
optimizer_.addEdge(odometry);
}
void G2OSolver::getGraph(std::vector<Eigen::Vector2d> &nodes, std::vector<std::pair<Eigen::Vector2d, Eigen::Vector2d> > &edges)
{
using namespace g2o;
//HyperGraph::VertexIDMap vertexMap = optimizer_.vertices();
//HyperGraph::EdgeSet edgeSet = optimizer_.edges();
double *data = new double[3];
for (SparseOptimizer::VertexIDMap::iterator it = optimizer_.vertices().begin(); it != optimizer_.vertices().end(); ++it)
{
VertexSE2* v = dynamic_cast<VertexSE2*>(it->second);
if(v)
{
v->getEstimateData(data);
Eigen::Vector2d pose(data[0], data[1]);
nodes.push_back(pose);
}
}
double *data1 = new double[3];
double *data2 = new double[3];
// for (SparseOptimizer::EdgeSet::iterator it = optimizer_.edges().begin(); it != optimizer_.edges().end(); ++it)
// {
// EdgeSE2* e = dynamic_cast<EdgeSE2*>(*it);
// if(e)
// {
// VertexSE2* v1 = dynamic_cast<VertexSE2*>(e->vertices()[0]);
// v1->getEstimateData(data1);
// Eigen::Vector2d poseFrom(data1[0], data1[1]);
// VertexSE2* v2 = dynamic_cast<VertexSE2*>(e->vertices()[1]);
// v2->getEstimateData(data2);
// Eigen::Vector2d poseTo(data2[0], data2[1]);
// edges.push_back(std::make_pair(poseFrom, poseTo));
// }
// }
delete data;
delete data1;
delete data2;
}
<commit_msg>Update G2OSolver.cpp<commit_after>/*********************************************************************
*
* Copyright (c) 2017, Saurav Agarwal
* All rights reserved.
*
*********************************************************************/
#include "G2OSolver.h"
#include "g2o/core/block_solver.h"
#include "g2o/core/factory.h"
#include "g2o/core/robust_kernel_impl.h"
#include "g2o/core/optimization_algorithm_factory.h"
#include "g2o/core/optimization_algorithm_levenberg.h"
#include "g2o/types/slam2d/types_slam2d.h"
#include "g2o/solvers/cholmod/linear_solver_cholmod.h"
#include <open_karto/Karto.h>
#include <ros/console.h>
typedef g2o::BlockSolver< g2o::BlockSolverTraits<-1, -1> > SlamBlockSolver;
typedef g2o::LinearSolverCholmod<SlamBlockSolver::PoseMatrixType> SlamLinearSolver;
G2OSolver::G2OSolver()
{
// Initialize the SparseOptimizer
auto linearSolver = g2o::make_unique<SlamLinearSolver>();
linearSolver->setBlockOrdering(false);
auto blockSolver = g2o::make_unique<SlamBlockSolver>(std::move(linearSolver));
optimizer_.setAlgorithm(new g2o::OptimizationAlgorithmLevenberg(std::move(blockSolver)));
latestNodeID_ = 0;
useRobustKernel_ = true;
}
G2OSolver::~G2OSolver()
{
// destroy all the singletons
g2o::Factory::destroy();
g2o::OptimizationAlgorithmFactory::destroy();
g2o::HyperGraphActionLibrary::destroy();
}
void G2OSolver::Clear()
{
corrections_.clear();
}
const karto::ScanSolver::IdPoseVector& G2OSolver::GetCorrections() const
{
return corrections_;
}
void G2OSolver::Compute()
{
corrections_.clear();
// Fix the first node in the graph to hold the map in place
g2o::OptimizableGraph::Vertex* first = optimizer_.vertex(0);
if(!first)
{
ROS_ERROR("[g2o] No Node with ID 0 found!");
return;
}
first->setFixed(true);
// Do the graph optimization
optimizer_.initializeOptimization();
int iter = optimizer_.optimize(500);
if (iter > 0)
{
ROS_INFO("[g2o] Optimization finished after %d iterations.", iter);
}
else
{
ROS_ERROR("[g2o] Optimization failed, result might be invalid!");
return;
}
// Write the result so it can be used by the mapper
g2o::SparseOptimizer::VertexContainer nodes = optimizer_.activeVertices();
for (g2o::SparseOptimizer::VertexContainer::const_iterator n = nodes.begin(); n != nodes.end(); n++)
{
double estimate[3];
if((*n)->getEstimateData(estimate))
{
karto::Pose2 pose(estimate[0], estimate[1], estimate[2]);
corrections_.push_back(std::make_pair((*n)->id(), pose));
}
else
{
ROS_ERROR("[g2o] Could not get estimated pose from Optimizer!");
}
}
}
void G2OSolver::AddNode(karto::Vertex<karto::LocalizedRangeScan>* pVertex)
{
karto::Pose2 odom = pVertex->GetObject()->GetCorrectedPose();
g2o::VertexSE2* poseVertex = new g2o::VertexSE2;
poseVertex->setEstimate(g2o::SE2(odom.GetX(), odom.GetY(), odom.GetHeading()));
poseVertex->setId(pVertex->GetObject()->GetUniqueId());
optimizer_.addVertex(poseVertex);
latestNodeID_ = pVertex->GetObject()->GetUniqueId();
ROS_DEBUG("[g2o] Adding node %d.", pVertex->GetObject()->GetUniqueId());
}
void G2OSolver::AddConstraint(karto::Edge<karto::LocalizedRangeScan>* pEdge)
{
// Create a new edge
g2o::EdgeSE2* odometry = new g2o::EdgeSE2;
// Set source and target
int sourceID = pEdge->GetSource()->GetObject()->GetUniqueId();
int targetID = pEdge->GetTarget()->GetObject()->GetUniqueId();
odometry->vertices()[0] = optimizer_.vertex(sourceID);
odometry->vertices()[1] = optimizer_.vertex(targetID);
if(odometry->vertices()[0] == NULL)
{
ROS_ERROR("[g2o] Source vertex with id %d does not exist!", sourceID);
delete odometry;
return;
}
if(odometry->vertices()[0] == NULL)
{
ROS_ERROR("[g2o] Target vertex with id %d does not exist!", targetID);
delete odometry;
return;
}
// Set the measurement (odometry distance between vertices)
karto::LinkInfo* pLinkInfo = (karto::LinkInfo*)(pEdge->GetLabel());
karto::Pose2 diff = pLinkInfo->GetPoseDifference();
g2o::SE2 measurement(diff.GetX(), diff.GetY(), diff.GetHeading());
odometry->setMeasurement(measurement);
// Set the covariance of the measurement
karto::Matrix3 precisionMatrix = pLinkInfo->GetCovariance().Inverse();
Eigen::Matrix<double,3,3> info;
info(0,0) = precisionMatrix(0,0);
info(0,1) = info(1,0) = precisionMatrix(0,1);
info(0,2) = info(2,0) = precisionMatrix(0,2);
info(1,1) = precisionMatrix(1,1);
info(1,2) = info(2,1) = precisionMatrix(1,2);
info(2,2) = precisionMatrix(2,2);
odometry->setInformation(info);
if(useRobustKernel_)
{
g2o::RobustKernelDCS* rk = new g2o::RobustKernelDCS;
odometry->setRobustKernel(rk);
}
// Add the constraint to the optimizer
ROS_DEBUG("[g2o] Adding Edge from node %d to node %d.", sourceID, targetID);
optimizer_.addEdge(odometry);
}
void G2OSolver::getGraph(std::vector<Eigen::Vector2d> &nodes, std::vector<std::pair<Eigen::Vector2d, Eigen::Vector2d> > &edges)
{
using namespace g2o;
//HyperGraph::VertexIDMap vertexMap = optimizer_.vertices();
//HyperGraph::EdgeSet edgeSet = optimizer_.edges();
double *data = new double[3];
for (SparseOptimizer::VertexIDMap::iterator it = optimizer_.vertices().begin(); it != optimizer_.vertices().end(); ++it)
{
VertexSE2* v = dynamic_cast<VertexSE2*>(it->second);
if(v)
{
v->getEstimateData(data);
Eigen::Vector2d pose(data[0], data[1]);
nodes.push_back(pose);
}
}
double *data1 = new double[3];
double *data2 = new double[3];
// for (SparseOptimizer::EdgeSet::iterator it = optimizer_.edges().begin(); it != optimizer_.edges().end(); ++it)
// {
// EdgeSE2* e = dynamic_cast<EdgeSE2*>(*it);
// if(e)
// {
// VertexSE2* v1 = dynamic_cast<VertexSE2*>(e->vertices()[0]);
// v1->getEstimateData(data1);
// Eigen::Vector2d poseFrom(data1[0], data1[1]);
// VertexSE2* v2 = dynamic_cast<VertexSE2*>(e->vertices()[1]);
// v2->getEstimateData(data2);
// Eigen::Vector2d poseTo(data2[0], data2[1]);
// edges.push_back(std::make_pair(poseFrom, poseTo));
// }
// }
delete data;
delete data1;
delete data2;
}
<|endoftext|>
|
<commit_before>// Copyright 2021 The XLS Authors
//
// 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 "xls/dslx/evaluate_sym.h"
#include "xls/common/status/ret_check.h"
#include "xls/common/status/status_macros.h"
#include "xls/dslx/evaluate.h"
#include "xls/dslx/interp_bindings.h"
#include "xls/dslx/interp_value.h"
#include "xls/dslx/symbolic_type.h"
namespace xls::dslx {
#define DISPATCH_DEF(__expr_type) \
absl::StatusOr<InterpValue> EvaluateSym##__expr_type( \
__expr_type* expr, InterpBindings* bindings, ConcreteType* type_context, \
AbstractInterpreter* interp) { \
return Evaluate##__expr_type(expr, bindings, type_context, interp); \
}
DISPATCH_DEF(Array)
DISPATCH_DEF(Attr)
DISPATCH_DEF(Carry)
DISPATCH_DEF(Cast)
DISPATCH_DEF(ColonRef)
DISPATCH_DEF(ConstRef)
DISPATCH_DEF(For)
DISPATCH_DEF(Index)
DISPATCH_DEF(Let)
DISPATCH_DEF(Match)
DISPATCH_DEF(NameRef)
DISPATCH_DEF(Number)
DISPATCH_DEF(SplatStructInstance)
DISPATCH_DEF(String)
DISPATCH_DEF(StructInstance)
DISPATCH_DEF(Ternary)
DISPATCH_DEF(Unop)
DISPATCH_DEF(While)
DISPATCH_DEF(XlsTuple)
#undef DISPATCH_DEF
template <typename... Args>
InterpValue AddSymToValue(InterpValue concrete_value, InterpBindings* bindings,
Args&&... args) {
auto sym_ptr =
std::make_unique<SymbolicType>(SymbolicType(std::forward<Args>(args)...));
InterpValue sym_value = concrete_value.UpdateWithSym(sym_ptr.get());
bindings->AddSymValues(std::move(sym_ptr));
return sym_value;
}
absl::StatusOr<InterpValue> EvaluateSymFunction(
Function* f, absl::Span<const InterpValue> args, const Span& span,
const SymbolicBindings& symbolic_bindings, AbstractInterpreter* interp) {
XLS_RET_CHECK_EQ(f->owner(), interp->GetCurrentTypeInfo()->module());
XLS_VLOG(5) << "Evaluating function: " << f->identifier()
<< " symbolic_bindings: " << symbolic_bindings;
if (args.size() != f->params().size()) {
return absl::InternalError(
absl::StrFormat("EvaluateError: %s Argument arity mismatch for "
"invocation; want %d got %d",
span.ToString(), f->params().size(), args.size()));
}
Module* m = f->owner();
XLS_ASSIGN_OR_RETURN(const InterpBindings* top_level_bindings,
GetOrCreateTopLevelBindings(m, interp));
XLS_VLOG(5) << "Evaluated top level bindings for module: " << m->name()
<< "; keys: {"
<< absl::StrJoin(top_level_bindings->GetKeys(), ", ") << "}";
InterpBindings fn_bindings(/*parent=*/top_level_bindings);
XLS_RETURN_IF_ERROR(EvaluateDerivedParametrics(f, &fn_bindings, interp,
symbolic_bindings.ToMap()));
fn_bindings.set_fn_ctx(FnCtx{m->name(), f->identifier(), symbolic_bindings});
for (int64_t i = 0; i < f->params().size(); ++i) {
fn_bindings.AddValue(f->params()[i]->identifier(),
AddSymToValue(args[i], &fn_bindings, f->params()[i]));
}
return interp->Eval(f->body(), &fn_bindings);
}
absl::StatusOr<InterpValue> EvaluateSymShift(Binop* expr,
InterpBindings* bindings,
ConcreteType* type_context,
AbstractInterpreter* interp) {
XLS_VLOG(6) << "EvaluateShift: " << expr->ToString() << " @ " << expr->span();
XLS_ASSIGN_OR_RETURN(InterpValue lhs, interp->Eval(expr->lhs(), bindings));
// Optionally Retrieve a type context for the right hand side as an
// un-type-annotated literal number is permitted.
std::unique_ptr<ConcreteType> rhs_type = nullptr;
absl::optional<ConcreteType*> rhs_item =
interp->GetCurrentTypeInfo()->GetItem(expr->rhs());
if (rhs_item.has_value()) {
rhs_type = rhs_item.value()->CloneToUnique();
}
XLS_ASSIGN_OR_RETURN(InterpValue rhs, interp->Eval(expr->rhs(), bindings,
std::move(rhs_type)));
BinopKind binop = expr->binop_kind();
switch (binop) {
case BinopKind::kShl: {
XLS_ASSIGN_OR_RETURN(InterpValue result, lhs.Shl(rhs));
return AddSymToValue(result, bindings,
SymbolicType::Nodes{lhs.sym(), rhs.sym()}, binop);
}
case BinopKind::kShr: {
if (lhs.IsSigned()) {
XLS_ASSIGN_OR_RETURN(InterpValue result, lhs.Shra(rhs));
return AddSymToValue(result, bindings,
SymbolicType::Nodes{lhs.sym(), rhs.sym()}, binop);
}
XLS_ASSIGN_OR_RETURN(InterpValue result, lhs.Shrl(rhs));
return AddSymToValue(result, bindings,
SymbolicType::Nodes{lhs.sym(), rhs.sym()}, binop);
}
default:
// Not an exhaustive list: this function only handles the shift operators.
break;
}
return absl::InternalError(absl::StrCat("Invalid shift operation kind: ",
static_cast<int64_t>(expr->kind())));
}
absl::StatusOr<InterpValue> EvaluateSymBinop(Binop* expr,
InterpBindings* bindings,
ConcreteType* type_context,
AbstractInterpreter* interp) {
if (GetBinopShifts().contains(expr->binop_kind())) {
return EvaluateSymShift(expr, bindings, type_context, interp);
}
XLS_ASSIGN_OR_RETURN(InterpValue result,
EvaluateBinop(expr, bindings, type_context, interp));
XLS_ASSIGN_OR_RETURN(InterpValue lhs, interp->Eval(expr->lhs(), bindings));
XLS_ASSIGN_OR_RETURN(InterpValue rhs, interp->Eval(expr->rhs(), bindings));
if (lhs.sym() == nullptr || rhs.sym() == nullptr)
return absl::InternalError(
absl::StrFormat("Node %s cannot be evaluated symbolically",
lhs.sym() == nullptr ? TagToString(lhs.tag())
: TagToString(rhs.tag())));
return AddSymToValue(result, bindings,
SymbolicType::Nodes{lhs.sym(), rhs.sym()},
expr->binop_kind());
}
} // namespace xls::dslx
<commit_msg>Added symbolic evaluation support for literal numbers.<commit_after>// Copyright 2021 The XLS Authors
//
// 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 "xls/dslx/evaluate_sym.h"
#include "xls/common/status/ret_check.h"
#include "xls/common/status/status_macros.h"
#include "xls/dslx/evaluate.h"
#include "xls/dslx/interp_bindings.h"
#include "xls/dslx/interp_value.h"
#include "xls/dslx/symbolic_type.h"
namespace xls::dslx {
#define DISPATCH_DEF(__expr_type) \
absl::StatusOr<InterpValue> EvaluateSym##__expr_type( \
__expr_type* expr, InterpBindings* bindings, ConcreteType* type_context, \
AbstractInterpreter* interp) { \
return Evaluate##__expr_type(expr, bindings, type_context, interp); \
}
DISPATCH_DEF(Array)
DISPATCH_DEF(Attr)
DISPATCH_DEF(Carry)
DISPATCH_DEF(Cast)
DISPATCH_DEF(ColonRef)
DISPATCH_DEF(ConstRef)
DISPATCH_DEF(For)
DISPATCH_DEF(Index)
DISPATCH_DEF(Let)
DISPATCH_DEF(Match)
DISPATCH_DEF(NameRef)
DISPATCH_DEF(SplatStructInstance)
DISPATCH_DEF(String)
DISPATCH_DEF(StructInstance)
DISPATCH_DEF(Ternary)
DISPATCH_DEF(Unop)
DISPATCH_DEF(While)
DISPATCH_DEF(XlsTuple)
#undef DISPATCH_DEF
template <typename... Args>
InterpValue AddSymToValue(InterpValue concrete_value, InterpBindings* bindings,
Args&&... args) {
auto sym_ptr =
std::make_unique<SymbolicType>(SymbolicType(std::forward<Args>(args)...));
InterpValue sym_value = concrete_value.UpdateWithSym(sym_ptr.get());
bindings->AddSymValues(std::move(sym_ptr));
return sym_value;
}
absl::StatusOr<InterpValue> EvaluateSymNumber(Number* expr,
InterpBindings* bindings,
ConcreteType* type_context,
AbstractInterpreter* interp) {
XLS_ASSIGN_OR_RETURN(InterpValue result,
EvaluateNumber(expr, bindings, type_context, interp));
XLS_ASSIGN_OR_RETURN(Bits result_bits, result.GetBits());
return AddSymToValue(result, bindings, result_bits);
}
absl::StatusOr<InterpValue> EvaluateSymFunction(
Function* f, absl::Span<const InterpValue> args, const Span& span,
const SymbolicBindings& symbolic_bindings, AbstractInterpreter* interp) {
XLS_RET_CHECK_EQ(f->owner(), interp->GetCurrentTypeInfo()->module());
XLS_VLOG(5) << "Evaluating function: " << f->identifier()
<< " symbolic_bindings: " << symbolic_bindings;
if (args.size() != f->params().size()) {
return absl::InternalError(
absl::StrFormat("EvaluateError: %s Argument arity mismatch for "
"invocation; want %d got %d",
span.ToString(), f->params().size(), args.size()));
}
Module* m = f->owner();
XLS_ASSIGN_OR_RETURN(const InterpBindings* top_level_bindings,
GetOrCreateTopLevelBindings(m, interp));
XLS_VLOG(5) << "Evaluated top level bindings for module: " << m->name()
<< "; keys: {"
<< absl::StrJoin(top_level_bindings->GetKeys(), ", ") << "}";
InterpBindings fn_bindings(/*parent=*/top_level_bindings);
XLS_RETURN_IF_ERROR(EvaluateDerivedParametrics(f, &fn_bindings, interp,
symbolic_bindings.ToMap()));
fn_bindings.set_fn_ctx(FnCtx{m->name(), f->identifier(), symbolic_bindings});
for (int64_t i = 0; i < f->params().size(); ++i) {
fn_bindings.AddValue(f->params()[i]->identifier(),
AddSymToValue(args[i], &fn_bindings, f->params()[i]));
}
return interp->Eval(f->body(), &fn_bindings);
}
absl::StatusOr<InterpValue> EvaluateSymShift(Binop* expr,
InterpBindings* bindings,
ConcreteType* type_context,
AbstractInterpreter* interp) {
XLS_VLOG(6) << "EvaluateShift: " << expr->ToString() << " @ " << expr->span();
XLS_ASSIGN_OR_RETURN(InterpValue lhs, interp->Eval(expr->lhs(), bindings));
// Optionally Retrieve a type context for the right hand side as an
// un-type-annotated literal number is permitted.
std::unique_ptr<ConcreteType> rhs_type = nullptr;
absl::optional<ConcreteType*> rhs_item =
interp->GetCurrentTypeInfo()->GetItem(expr->rhs());
if (rhs_item.has_value()) {
rhs_type = rhs_item.value()->CloneToUnique();
}
XLS_ASSIGN_OR_RETURN(InterpValue rhs, interp->Eval(expr->rhs(), bindings,
std::move(rhs_type)));
BinopKind binop = expr->binop_kind();
switch (binop) {
case BinopKind::kShl: {
XLS_ASSIGN_OR_RETURN(InterpValue result, lhs.Shl(rhs));
return AddSymToValue(result, bindings,
SymbolicType::Nodes{lhs.sym(), rhs.sym()}, binop);
}
case BinopKind::kShr: {
if (lhs.IsSigned()) {
XLS_ASSIGN_OR_RETURN(InterpValue result, lhs.Shra(rhs));
return AddSymToValue(result, bindings,
SymbolicType::Nodes{lhs.sym(), rhs.sym()}, binop);
}
XLS_ASSIGN_OR_RETURN(InterpValue result, lhs.Shrl(rhs));
return AddSymToValue(result, bindings,
SymbolicType::Nodes{lhs.sym(), rhs.sym()}, binop);
}
default:
// Not an exhaustive list: this function only handles the shift operators.
break;
}
return absl::InternalError(absl::StrCat("Invalid shift operation kind: ",
static_cast<int64_t>(expr->kind())));
}
absl::StatusOr<InterpValue> EvaluateSymBinop(Binop* expr,
InterpBindings* bindings,
ConcreteType* type_context,
AbstractInterpreter* interp) {
if (GetBinopShifts().contains(expr->binop_kind())) {
return EvaluateSymShift(expr, bindings, type_context, interp);
}
XLS_ASSIGN_OR_RETURN(InterpValue result,
EvaluateBinop(expr, bindings, type_context, interp));
XLS_ASSIGN_OR_RETURN(InterpValue lhs, interp->Eval(expr->lhs(), bindings));
XLS_ASSIGN_OR_RETURN(InterpValue rhs, interp->Eval(expr->rhs(), bindings));
if (lhs.sym() == nullptr || rhs.sym() == nullptr)
return absl::InternalError(
absl::StrFormat("Node %s cannot be evaluated symbolically",
lhs.sym() == nullptr ? TagToString(lhs.tag())
: TagToString(rhs.tag())));
return AddSymToValue(result, bindings,
SymbolicType::Nodes{lhs.sym(), rhs.sym()},
expr->binop_kind());
}
} // namespace xls::dslx
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: imexp.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: dbo $ $Date: 2001-05-10 09:20:42 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include <stdio.h>
#include <rtl/memory.h>
#include <xmlscript/xmldlg_imexp.hxx>
#include <xmlscript/xml_helper.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <cppuhelper/implbase2.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/regpathhelper.hxx>
#include <tools/debug.hxx>
#include <vcl/svapp.hxx>
#include <svtools/unoiface.hxx> // InitExtToolkit
#include <com/sun/star/io/XActiveDataSource.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/registry/XSimpleRegistry.hpp>
#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>
#include <com/sun/star/awt/XToolkit.hpp>
#include <com/sun/star/awt/XControlModel.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
Reference< lang::XMultiServiceFactory > createApplicationServiceManager()
{
Reference< XComponentContext > xContext;
try
{
::rtl::OUString localRegistry = ::comphelper::getPathToUserRegistry();
::rtl::OUString systemRegistry = ::comphelper::getPathToSystemRegistry();
Reference< registry::XSimpleRegistry > xLocalRegistry( ::cppu::createSimpleRegistry() );
Reference< registry::XSimpleRegistry > xSystemRegistry( ::cppu::createSimpleRegistry() );
if ( xLocalRegistry.is() && (localRegistry.getLength() > 0) )
{
try
{
xLocalRegistry->open( localRegistry, sal_False, sal_True);
}
catch ( registry::InvalidRegistryException& )
{
}
if ( !xLocalRegistry->isValid() )
xLocalRegistry->open(localRegistry, sal_True, sal_True);
}
if ( xSystemRegistry.is() && (systemRegistry.getLength() > 0) )
xSystemRegistry->open( systemRegistry, sal_True, sal_False);
if ( (xLocalRegistry.is() && xLocalRegistry->isValid()) &&
(xSystemRegistry.is() && xSystemRegistry->isValid()) )
{
Reference < registry::XSimpleRegistry > xReg( ::cppu::createNestedRegistry() );
Sequence< Any > seqAnys(2);
seqAnys[0] <<= xLocalRegistry ;
seqAnys[1] <<= xSystemRegistry ;
Reference< lang::XInitialization > xInit( xReg, UNO_QUERY );
xInit->initialize( seqAnys );
xContext = ::cppu::bootstrap_InitialComponentContext( xReg );
}
else
{
throw Exception(
OUString( RTL_CONSTASCII_USTRINGPARAM("no registry!") ),
Reference< XInterface >() );
}
Reference < registry::XImplementationRegistration > xReg(
xContext->getServiceManager()->createInstanceWithContext(
OUString::createFromAscii( "com.sun.star.registry.ImplementationRegistration" ), xContext ), UNO_QUERY );
#ifdef SAL_W32
OUString aDllName = OUString::createFromAscii( "sax.dll" );
#else
OUString aDllName = OUString::createFromAscii( "libsax.so" );
#endif
xReg->registerImplementation(
OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
aDllName, Reference< registry::XSimpleRegistry > () );
#ifdef SAL_W32
aDllName = OUString::createFromAscii( "tk" );
aDllName += OUString::valueOf( (sal_Int32)SUPD );
aDllName += OUString::createFromAscii( "mi.dll" );
#else
aDllName = OUString::createFromAscii( "libtk" );
aDllName += OUString::valueOf( (sal_Int32)SUPD );
aDllName += OUString::createFromAscii( ".so" );
#endif
xReg->registerImplementation(
OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
aDllName, Reference< registry::XSimpleRegistry > () );
#ifdef SAL_W32
aDllName = OUString::createFromAscii( "svt" );
aDllName += OUString::valueOf( (sal_Int32)SUPD );
aDllName += OUString::createFromAscii( "mi.dll" );
#else
aDllName = OUString::createFromAscii( "libsvt" );
aDllName += OUString::valueOf( (sal_Int32)SUPD );
aDllName += OUString::createFromAscii( ".so" );
#endif
xReg->registerImplementation(
OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
aDllName, Reference< registry::XSimpleRegistry > () );
#ifdef SAL_W32
aDllName = OUString::createFromAscii( "i18n" );
aDllName += OUString::valueOf( (sal_Int32)SUPD );
aDllName += OUString::createFromAscii( "mi.dll" );
#else
aDllName = OUString::createFromAscii( "libi18n" );
aDllName += OUString::valueOf( (sal_Int32)SUPD );
aDllName += OUString::createFromAscii( ".so" );
#endif
xReg->registerImplementation(
OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
aDllName, Reference< registry::XSimpleRegistry > () );
}
catch( Exception& rExc )
{
OString aStr( OUStringToOString( rExc.Message, RTL_TEXTENCODING_ASCII_US ) );
OSL_ENSURE( 0, aStr.getStr() );
}
return Reference< lang::XMultiServiceFactory >( xContext->getServiceManager(), UNO_QUERY );
}
// -----------------------------------------------------------------------
Reference< container::XNameContainer > importFile(
char const * fname )
{
// create the input stream
FILE *f = ::fopen( fname, "rb" );
if (f)
{
::fseek( f, 0 ,SEEK_END );
int nLength = ::ftell( f );
::fseek( f, 0, SEEK_SET );
ByteSequence bytes( nLength );
::fread( bytes.getArray(), nLength, 1, f );
::fclose( f );
Reference< lang::XMultiServiceFactory > xSMgr( ::comphelper::getProcessServiceFactory() );
Reference< container::XNameContainer > xModel( xSMgr->createInstance(
OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.awt.UnoControlDialogModel" ) ) ), UNO_QUERY );
::xmlscript::importDialogModel( ::xmlscript::createInputStream( bytes ), xModel );
return xModel;
}
else
{
throw Exception( OUString( RTL_CONSTASCII_USTRINGPARAM("### Cannot read file!") ),
Reference< XInterface >() );
}
}
void exportToFile(
char const * fname,
Reference< container::XNameContainer > const & xModel )
{
Reference< io::XInputStreamProvider > xProvider( ::xmlscript::exportDialogModel( xModel ) );
Reference< io::XInputStream > xStream( xProvider->createInputStream() );
Sequence< sal_Int8 > bytes;
sal_Int32 nRead = xStream->readBytes( bytes, xStream->available() );
for (;;)
{
Sequence< sal_Int8 > readBytes;
nRead = xStream->readBytes( readBytes, 1024 );
if (! nRead)
break;
OSL_ASSERT( readBytes.getLength() >= nRead );
sal_Int32 nPos = bytes.getLength();
bytes.realloc( nPos + nRead );
::rtl_copyMemory( bytes.getArray() + nPos, readBytes.getConstArray(), (sal_uInt32)nRead );
}
FILE * f = ::fopen( fname, "w" );
::fwrite( bytes.getConstArray(), 1, bytes.getLength(), f );
::fflush( f );
::fclose( f );
}
class MyApp : public Application
{
public:
void Main();
};
MyApp aMyApp;
// -----------------------------------------------------------------------
void MyApp::Main()
{
if (GetCommandLineParamCount() < 1)
{
OSL_ENSURE( 0, "usage: imexp inputfile [outputfile]\n" );
return;
}
Reference< lang::XMultiServiceFactory > xMSF = createApplicationServiceManager();
try
{
::comphelper::setProcessServiceFactory( xMSF );
Reference< awt::XToolkit> xToolkit( xMSF->createInstance(
OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.awt.ExtToolkit" ) ) ), UNO_QUERY );
// import dialogs
OString aParam1( OUStringToOString( OUString( GetCommandLineParam( 0 ) ), RTL_TEXTENCODING_ASCII_US ) );
Reference< container::XNameContainer > xModel( importFile( aParam1.getStr() ) );
OSL_ASSERT( xModel.is() );
Reference< awt::XControl > xDlg( xMSF->createInstance(
OUString(RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.awt.UnoControlDialog" ) ) ), UNO_QUERY );
xDlg->setModel( Reference< awt::XControlModel >::query( xModel ) );
xDlg->createPeer( xToolkit, 0 );
Reference< awt::XDialog > xD( xDlg, UNO_QUERY );
xD->execute();
if (GetCommandLineParamCount() == 2)
{
// write modified dialogs
OString aParam2( OUStringToOString( OUString( GetCommandLineParam( 1 ) ), RTL_TEXTENCODING_ASCII_US ) );
exportToFile( aParam2.getStr(), xModel );
}
}
catch (xml::sax::SAXException & rExc)
{
OString aStr( OUStringToOString( rExc.Message, RTL_TEXTENCODING_ASCII_US ) );
uno::Exception exc;
if (rExc.WrappedException >>= exc)
{
aStr += OString( " >>> " );
aStr += OUStringToOString( exc.Message, RTL_TEXTENCODING_ASCII_US );
}
OSL_ENSURE( 0, aStr.getStr() );
}
catch (uno::Exception & rExc)
{
OString aStr( OUStringToOString( rExc.Message, RTL_TEXTENCODING_ASCII_US ) );
OSL_ENSURE( 0, aStr.getStr() );
}
Reference< lang::XComponent > xComp( xMSF, UNO_QUERY );
if (xComp.is())
{
xComp->dispose();
}
}
<commit_msg>disposing context<commit_after>/*************************************************************************
*
* $RCSfile: imexp.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: dbo $ $Date: 2001-05-11 13:53:34 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include <stdio.h>
#include <rtl/memory.h>
#include <xmlscript/xmldlg_imexp.hxx>
#include <xmlscript/xml_helper.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <cppuhelper/implbase2.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/regpathhelper.hxx>
#include <tools/debug.hxx>
#include <vcl/svapp.hxx>
#include <svtools/unoiface.hxx> // InitExtToolkit
#include <com/sun/star/io/XActiveDataSource.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/registry/XSimpleRegistry.hpp>
#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>
#include <com/sun/star/awt/XToolkit.hpp>
#include <com/sun/star/awt/XControlModel.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
using namespace ::rtl;
using namespace ::cppu;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
Reference< lang::XMultiServiceFactory > createApplicationServiceManager()
{
Reference< XComponentContext > xContext;
try
{
::rtl::OUString localRegistry = ::comphelper::getPathToUserRegistry();
::rtl::OUString systemRegistry = ::comphelper::getPathToSystemRegistry();
Reference< registry::XSimpleRegistry > xLocalRegistry( ::cppu::createSimpleRegistry() );
Reference< registry::XSimpleRegistry > xSystemRegistry( ::cppu::createSimpleRegistry() );
if ( xLocalRegistry.is() && (localRegistry.getLength() > 0) )
{
try
{
xLocalRegistry->open( localRegistry, sal_False, sal_True);
}
catch ( registry::InvalidRegistryException& )
{
}
if ( !xLocalRegistry->isValid() )
xLocalRegistry->open(localRegistry, sal_True, sal_True);
}
if ( xSystemRegistry.is() && (systemRegistry.getLength() > 0) )
xSystemRegistry->open( systemRegistry, sal_True, sal_False);
if ( (xLocalRegistry.is() && xLocalRegistry->isValid()) &&
(xSystemRegistry.is() && xSystemRegistry->isValid()) )
{
Reference < registry::XSimpleRegistry > xReg( ::cppu::createNestedRegistry() );
Sequence< Any > seqAnys(2);
seqAnys[0] <<= xLocalRegistry ;
seqAnys[1] <<= xSystemRegistry ;
Reference< lang::XInitialization > xInit( xReg, UNO_QUERY );
xInit->initialize( seqAnys );
xContext = ::cppu::bootstrap_InitialComponentContext( xReg );
}
else
{
throw Exception(
OUString( RTL_CONSTASCII_USTRINGPARAM("no registry!") ),
Reference< XInterface >() );
}
Reference < registry::XImplementationRegistration > xReg(
xContext->getServiceManager()->createInstanceWithContext(
OUString::createFromAscii( "com.sun.star.registry.ImplementationRegistration" ), xContext ), UNO_QUERY );
#ifdef SAL_W32
OUString aDllName = OUString::createFromAscii( "sax.dll" );
#else
OUString aDllName = OUString::createFromAscii( "libsax.so" );
#endif
xReg->registerImplementation(
OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
aDllName, Reference< registry::XSimpleRegistry > () );
#ifdef SAL_W32
aDllName = OUString::createFromAscii( "tk" );
aDllName += OUString::valueOf( (sal_Int32)SUPD );
aDllName += OUString::createFromAscii( "mi.dll" );
#else
aDllName = OUString::createFromAscii( "libtk" );
aDllName += OUString::valueOf( (sal_Int32)SUPD );
aDllName += OUString::createFromAscii( ".so" );
#endif
xReg->registerImplementation(
OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
aDllName, Reference< registry::XSimpleRegistry > () );
#ifdef SAL_W32
aDllName = OUString::createFromAscii( "svt" );
aDllName += OUString::valueOf( (sal_Int32)SUPD );
aDllName += OUString::createFromAscii( "mi.dll" );
#else
aDllName = OUString::createFromAscii( "libsvt" );
aDllName += OUString::valueOf( (sal_Int32)SUPD );
aDllName += OUString::createFromAscii( ".so" );
#endif
xReg->registerImplementation(
OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
aDllName, Reference< registry::XSimpleRegistry > () );
#ifdef SAL_W32
aDllName = OUString::createFromAscii( "i18n" );
aDllName += OUString::valueOf( (sal_Int32)SUPD );
aDllName += OUString::createFromAscii( "mi.dll" );
#else
aDllName = OUString::createFromAscii( "libi18n" );
aDllName += OUString::valueOf( (sal_Int32)SUPD );
aDllName += OUString::createFromAscii( ".so" );
#endif
xReg->registerImplementation(
OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
aDllName, Reference< registry::XSimpleRegistry > () );
}
catch( Exception& rExc )
{
OString aStr( OUStringToOString( rExc.Message, RTL_TEXTENCODING_ASCII_US ) );
OSL_ENSURE( 0, aStr.getStr() );
}
return Reference< lang::XMultiServiceFactory >( xContext->getServiceManager(), UNO_QUERY );
}
// -----------------------------------------------------------------------
Reference< container::XNameContainer > importFile(
char const * fname )
{
// create the input stream
FILE *f = ::fopen( fname, "rb" );
if (f)
{
::fseek( f, 0 ,SEEK_END );
int nLength = ::ftell( f );
::fseek( f, 0, SEEK_SET );
ByteSequence bytes( nLength );
::fread( bytes.getArray(), nLength, 1, f );
::fclose( f );
Reference< lang::XMultiServiceFactory > xSMgr( ::comphelper::getProcessServiceFactory() );
Reference< container::XNameContainer > xModel( xSMgr->createInstance(
OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.awt.UnoControlDialogModel" ) ) ), UNO_QUERY );
::xmlscript::importDialogModel( ::xmlscript::createInputStream( bytes ), xModel );
return xModel;
}
else
{
throw Exception( OUString( RTL_CONSTASCII_USTRINGPARAM("### Cannot read file!") ),
Reference< XInterface >() );
}
}
void exportToFile(
char const * fname,
Reference< container::XNameContainer > const & xModel )
{
Reference< io::XInputStreamProvider > xProvider( ::xmlscript::exportDialogModel( xModel ) );
Reference< io::XInputStream > xStream( xProvider->createInputStream() );
Sequence< sal_Int8 > bytes;
sal_Int32 nRead = xStream->readBytes( bytes, xStream->available() );
for (;;)
{
Sequence< sal_Int8 > readBytes;
nRead = xStream->readBytes( readBytes, 1024 );
if (! nRead)
break;
OSL_ASSERT( readBytes.getLength() >= nRead );
sal_Int32 nPos = bytes.getLength();
bytes.realloc( nPos + nRead );
::rtl_copyMemory( bytes.getArray() + nPos, readBytes.getConstArray(), (sal_uInt32)nRead );
}
FILE * f = ::fopen( fname, "w" );
::fwrite( bytes.getConstArray(), 1, bytes.getLength(), f );
::fflush( f );
::fclose( f );
}
class MyApp : public Application
{
public:
void Main();
};
MyApp aMyApp;
// -----------------------------------------------------------------------
void MyApp::Main()
{
if (GetCommandLineParamCount() < 1)
{
OSL_ENSURE( 0, "usage: imexp inputfile [outputfile]\n" );
return;
}
Reference< lang::XMultiServiceFactory > xMSF = createApplicationServiceManager();
try
{
::comphelper::setProcessServiceFactory( xMSF );
Reference< awt::XToolkit> xToolkit( xMSF->createInstance(
OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.awt.ExtToolkit" ) ) ), UNO_QUERY );
// import dialogs
OString aParam1( OUStringToOString( OUString( GetCommandLineParam( 0 ) ), RTL_TEXTENCODING_ASCII_US ) );
Reference< container::XNameContainer > xModel( importFile( aParam1.getStr() ) );
OSL_ASSERT( xModel.is() );
Reference< awt::XControl > xDlg( xMSF->createInstance(
OUString(RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.awt.UnoControlDialog" ) ) ), UNO_QUERY );
xDlg->setModel( Reference< awt::XControlModel >::query( xModel ) );
xDlg->createPeer( xToolkit, 0 );
Reference< awt::XDialog > xD( xDlg, UNO_QUERY );
xD->execute();
if (GetCommandLineParamCount() == 2)
{
// write modified dialogs
OString aParam2( OUStringToOString( OUString( GetCommandLineParam( 1 ) ), RTL_TEXTENCODING_ASCII_US ) );
exportToFile( aParam2.getStr(), xModel );
}
}
catch (xml::sax::SAXException & rExc)
{
OString aStr( OUStringToOString( rExc.Message, RTL_TEXTENCODING_ASCII_US ) );
uno::Exception exc;
if (rExc.WrappedException >>= exc)
{
aStr += OString( " >>> " );
aStr += OUStringToOString( exc.Message, RTL_TEXTENCODING_ASCII_US );
}
OSL_ENSURE( 0, aStr.getStr() );
}
catch (uno::Exception & rExc)
{
OString aStr( OUStringToOString( rExc.Message, RTL_TEXTENCODING_ASCII_US ) );
OSL_ENSURE( 0, aStr.getStr() );
}
// dispose component context
Reference< beans::XPropertySet > xProps( xMSF, UNO_QUERY );
if (xProps.is())
{
try
{
Reference< lang::XComponent > xComp;
if (xProps->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("DefaultContext") ) ) >>= xComp)
{
xComp->dispose();
}
}
catch (beans::UnknownPropertyException &)
{
}
}
}
<|endoftext|>
|
<commit_before>//===--- CGComplexExpr.cpp - Emit LLVM Code for Complex Exprs -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code to emit Expr nodes with complex types as LLVM code.
//
//===----------------------------------------------------------------------===//
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "clang/AST/AST.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Support/Compiler.h"
using namespace clang;
using namespace CodeGen;
//===----------------------------------------------------------------------===//
// Complex Expression Emitter
//===----------------------------------------------------------------------===//
typedef CodeGenFunction::ComplexPairTy ComplexPairTy;
namespace {
class VISIBILITY_HIDDEN ComplexExprEmitter
: public StmtVisitor<ComplexExprEmitter, ComplexPairTy> {
CodeGenFunction &CGF;
llvm::LLVMBuilder &Builder;
public:
ComplexExprEmitter(CodeGenFunction &cgf) : CGF(cgf), Builder(CGF.Builder) {
}
//===--------------------------------------------------------------------===//
// Utilities
//===--------------------------------------------------------------------===//
/// EmitLoadOfLValue - Given an expression with complex type that represents a
/// value l-value, this method emits the address of the l-value, then loads
/// and returns the result.
ComplexPairTy EmitLoadOfLValue(const Expr *E) {
LValue LV = CGF.EmitLValue(E);
// FIXME: Volatile
return EmitLoadOfComplex(LV.getAddress(), false);
}
/// EmitLoadOfComplex - Given a pointer to a complex value, emit code to load
/// the real and imaginary pieces.
ComplexPairTy EmitLoadOfComplex(llvm::Value *SrcPtr, bool isVolatile);
/// EmitStoreOfComplex - Store the specified real/imag parts into the
/// specified value pointer.
void EmitStoreOfComplex(ComplexPairTy Val, llvm::Value *ResPtr, bool isVol);
//===--------------------------------------------------------------------===//
// Visitor Methods
//===--------------------------------------------------------------------===//
ComplexPairTy VisitStmt(Stmt *S) {
S->dump();
assert(0 && "Stmt can't have complex result type!");
return ComplexPairTy();
}
ComplexPairTy VisitExpr(Expr *S);
ComplexPairTy VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr());}
// l-values.
ComplexPairTy VisitDeclRefExpr(Expr *E) { return EmitLoadOfLValue(E); }
ComplexPairTy VisitArraySubscriptExpr(Expr *E) { return EmitLoadOfLValue(E); }
// Operators.
// case Expr::UnaryOperatorClass:
// case Expr::ImplicitCastExprClass:
// case Expr::CastExprClass:
// case Expr::CallExprClass:
ComplexPairTy VisitBinMul (const BinaryOperator *E);
ComplexPairTy VisitBinAdd (const BinaryOperator *E);
// FIXME: div/rem
// GCC rejects and/or/xor for integer complex.
// Logical and/or always return int, never complex.
// No comparisons produce a complex result.
ComplexPairTy VisitBinAssign (const BinaryOperator *E);
ComplexPairTy VisitBinComma (const BinaryOperator *E);
ComplexPairTy VisitConditionalOperator(const ConditionalOperator *CO);
// case Expr::ChooseExprClass:
};
} // end anonymous namespace.
//===----------------------------------------------------------------------===//
// Utilities
//===----------------------------------------------------------------------===//
/// EmitLoadOfComplex - Given an RValue reference for a complex, emit code to
/// load the real and imaginary pieces, returning them as Real/Imag.
ComplexPairTy ComplexExprEmitter::EmitLoadOfComplex(llvm::Value *SrcPtr,
bool isVolatile) {
llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
// FIXME: It would be nice to make this "Ptr->getName()+realp"
llvm::Value *RealPtr = Builder.CreateGEP(SrcPtr, Zero, Zero, "realp");
llvm::Value *ImagPtr = Builder.CreateGEP(SrcPtr, Zero, One, "imagp");
// FIXME: It would be nice to make this "Ptr->getName()+real"
llvm::Value *Real = Builder.CreateLoad(RealPtr, isVolatile, "real");
llvm::Value *Imag = Builder.CreateLoad(ImagPtr, isVolatile, "imag");
return ComplexPairTy(Real, Imag);
}
/// EmitStoreOfComplex - Store the specified real/imag parts into the
/// specified value pointer.
void ComplexExprEmitter::EmitStoreOfComplex(ComplexPairTy Val, llvm::Value *Ptr,
bool isVolatile) {
llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
llvm::Value *RealPtr = Builder.CreateGEP(Ptr, Zero, Zero, "real");
llvm::Value *ImagPtr = Builder.CreateGEP(Ptr, Zero, One, "imag");
Builder.CreateStore(Val.first, RealPtr, isVolatile);
Builder.CreateStore(Val.second, ImagPtr, isVolatile);
}
//===----------------------------------------------------------------------===//
// Visitor Methods
//===----------------------------------------------------------------------===//
ComplexPairTy ComplexExprEmitter::VisitExpr(Expr *E) {
fprintf(stderr, "Unimplemented complex expr!\n");
E->dump();
const llvm::Type *EltTy =
CGF.ConvertType(E->getType()->getAsComplexType()->getElementType());
llvm::Value *U = llvm::UndefValue::get(EltTy);
return ComplexPairTy(U, U);
}
ComplexPairTy ComplexExprEmitter::VisitBinAdd(const BinaryOperator *E) {
ComplexPairTy LHS = Visit(E->getLHS());
ComplexPairTy RHS = Visit(E->getRHS());
llvm::Value *ResR = Builder.CreateAdd(LHS.first, RHS.first, "add.r");
llvm::Value *ResI = Builder.CreateAdd(LHS.second, RHS.second, "add.i");
return ComplexPairTy(ResR, ResI);
}
ComplexPairTy ComplexExprEmitter::VisitBinMul(const BinaryOperator *E) {
ComplexPairTy LHS = Visit(E->getLHS());
ComplexPairTy RHS = Visit(E->getRHS());
llvm::Value *ResRl = Builder.CreateMul(LHS.first, RHS.first, "mul.rl");
llvm::Value *ResRr = Builder.CreateMul(LHS.second, RHS.second, "mul.rr");
llvm::Value *ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
llvm::Value *ResIl = Builder.CreateMul(LHS.second, RHS.first, "mul.il");
llvm::Value *ResIr = Builder.CreateMul(LHS.first, RHS.second, "mul.ir");
llvm::Value *ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
return ComplexPairTy(ResR, ResI);
}
ComplexPairTy ComplexExprEmitter::VisitBinAssign(const BinaryOperator *E) {
assert(E->getLHS()->getType().getCanonicalType() ==
E->getRHS()->getType().getCanonicalType() && "Invalid assignment");
// Emit the RHS.
ComplexPairTy Val = Visit(E->getRHS());
// Compute the address to store into.
LValue LHS = CGF.EmitLValue(E->getLHS());
// Store into it.
// FIXME: Volatility!
EmitStoreOfComplex(Val, LHS.getAddress(), false);
return Val;
}
ComplexPairTy ComplexExprEmitter::VisitBinComma(const BinaryOperator *E) {
CGF.EmitStmt(E->getLHS());
return Visit(E->getRHS());
}
ComplexPairTy ComplexExprEmitter::
VisitConditionalOperator(const ConditionalOperator *E) {
llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
CGF.EmitBlock(LHSBlock);
// Handle the GNU extension for missing LHS.
assert(E->getLHS() && "Must have LHS for complex value");
ComplexPairTy LHS = Visit(E->getLHS());
Builder.CreateBr(ContBlock);
LHSBlock = Builder.GetInsertBlock();
CGF.EmitBlock(RHSBlock);
ComplexPairTy RHS = Visit(E->getRHS());
Builder.CreateBr(ContBlock);
RHSBlock = Builder.GetInsertBlock();
CGF.EmitBlock(ContBlock);
// Create a PHI node for the real part.
llvm::PHINode *RealPN = Builder.CreatePHI(LHS.first->getType(), "cond.r");
RealPN->reserveOperandSpace(2);
RealPN->addIncoming(LHS.first, LHSBlock);
RealPN->addIncoming(RHS.first, RHSBlock);
// Create a PHI node for the imaginary part.
llvm::PHINode *ImagPN = Builder.CreatePHI(LHS.first->getType(), "cond.i");
ImagPN->reserveOperandSpace(2);
ImagPN->addIncoming(LHS.second, LHSBlock);
ImagPN->addIncoming(RHS.second, RHSBlock);
return ComplexPairTy(RealPN, ImagPN);
}
//===----------------------------------------------------------------------===//
// Entry Point into this File
//===----------------------------------------------------------------------===//
/// EmitComplexExpr - Emit the computation of the specified expression of
/// complex type, ignoring the result.
ComplexPairTy CodeGenFunction::EmitComplexExpr(const Expr *E) {
assert(E && E->getType()->isComplexType() &&
"Invalid complex expression to emit");
return ComplexExprEmitter(*this).Visit(const_cast<Expr*>(E));
}
<commit_msg>implement codegen for complex unary +/-<commit_after>//===--- CGComplexExpr.cpp - Emit LLVM Code for Complex Exprs -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code to emit Expr nodes with complex types as LLVM code.
//
//===----------------------------------------------------------------------===//
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "clang/AST/AST.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Support/Compiler.h"
using namespace clang;
using namespace CodeGen;
//===----------------------------------------------------------------------===//
// Complex Expression Emitter
//===----------------------------------------------------------------------===//
typedef CodeGenFunction::ComplexPairTy ComplexPairTy;
namespace {
class VISIBILITY_HIDDEN ComplexExprEmitter
: public StmtVisitor<ComplexExprEmitter, ComplexPairTy> {
CodeGenFunction &CGF;
llvm::LLVMBuilder &Builder;
public:
ComplexExprEmitter(CodeGenFunction &cgf) : CGF(cgf), Builder(CGF.Builder) {
}
//===--------------------------------------------------------------------===//
// Utilities
//===--------------------------------------------------------------------===//
/// EmitLoadOfLValue - Given an expression with complex type that represents a
/// value l-value, this method emits the address of the l-value, then loads
/// and returns the result.
ComplexPairTy EmitLoadOfLValue(const Expr *E) {
LValue LV = CGF.EmitLValue(E);
// FIXME: Volatile
return EmitLoadOfComplex(LV.getAddress(), false);
}
/// EmitLoadOfComplex - Given a pointer to a complex value, emit code to load
/// the real and imaginary pieces.
ComplexPairTy EmitLoadOfComplex(llvm::Value *SrcPtr, bool isVolatile);
/// EmitStoreOfComplex - Store the specified real/imag parts into the
/// specified value pointer.
void EmitStoreOfComplex(ComplexPairTy Val, llvm::Value *ResPtr, bool isVol);
//===--------------------------------------------------------------------===//
// Visitor Methods
//===--------------------------------------------------------------------===//
ComplexPairTy VisitStmt(Stmt *S) {
S->dump();
assert(0 && "Stmt can't have complex result type!");
return ComplexPairTy();
}
ComplexPairTy VisitExpr(Expr *S);
ComplexPairTy VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr());}
// l-values.
ComplexPairTy VisitDeclRefExpr(Expr *E) { return EmitLoadOfLValue(E); }
ComplexPairTy VisitArraySubscriptExpr(Expr *E) { return EmitLoadOfLValue(E); }
// Operators.
ComplexPairTy VisitUnaryPlus (const UnaryOperator *E) {
return Visit(E->getSubExpr());
}
ComplexPairTy VisitUnaryMinus (const UnaryOperator *E);
// case Expr::ImplicitCastExprClass:
// case Expr::CastExprClass:
// case Expr::CallExprClass:
ComplexPairTy VisitBinMul (const BinaryOperator *E);
ComplexPairTy VisitBinAdd (const BinaryOperator *E);
// FIXME: div/rem
// GCC rejects and/or/xor for integer complex.
// Logical and/or always return int, never complex.
// No comparisons produce a complex result.
ComplexPairTy VisitBinAssign (const BinaryOperator *E);
ComplexPairTy VisitBinComma (const BinaryOperator *E);
ComplexPairTy VisitConditionalOperator(const ConditionalOperator *CO);
// case Expr::ChooseExprClass:
};
} // end anonymous namespace.
//===----------------------------------------------------------------------===//
// Utilities
//===----------------------------------------------------------------------===//
/// EmitLoadOfComplex - Given an RValue reference for a complex, emit code to
/// load the real and imaginary pieces, returning them as Real/Imag.
ComplexPairTy ComplexExprEmitter::EmitLoadOfComplex(llvm::Value *SrcPtr,
bool isVolatile) {
llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
// FIXME: It would be nice to make this "Ptr->getName()+realp"
llvm::Value *RealPtr = Builder.CreateGEP(SrcPtr, Zero, Zero, "realp");
llvm::Value *ImagPtr = Builder.CreateGEP(SrcPtr, Zero, One, "imagp");
// FIXME: It would be nice to make this "Ptr->getName()+real"
llvm::Value *Real = Builder.CreateLoad(RealPtr, isVolatile, "real");
llvm::Value *Imag = Builder.CreateLoad(ImagPtr, isVolatile, "imag");
return ComplexPairTy(Real, Imag);
}
/// EmitStoreOfComplex - Store the specified real/imag parts into the
/// specified value pointer.
void ComplexExprEmitter::EmitStoreOfComplex(ComplexPairTy Val, llvm::Value *Ptr,
bool isVolatile) {
llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
llvm::Value *RealPtr = Builder.CreateGEP(Ptr, Zero, Zero, "real");
llvm::Value *ImagPtr = Builder.CreateGEP(Ptr, Zero, One, "imag");
Builder.CreateStore(Val.first, RealPtr, isVolatile);
Builder.CreateStore(Val.second, ImagPtr, isVolatile);
}
//===----------------------------------------------------------------------===//
// Visitor Methods
//===----------------------------------------------------------------------===//
ComplexPairTy ComplexExprEmitter::VisitExpr(Expr *E) {
fprintf(stderr, "Unimplemented complex expr!\n");
E->dump();
const llvm::Type *EltTy =
CGF.ConvertType(E->getType()->getAsComplexType()->getElementType());
llvm::Value *U = llvm::UndefValue::get(EltTy);
return ComplexPairTy(U, U);
}
ComplexPairTy ComplexExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
ComplexPairTy Op = Visit(E->getSubExpr());
llvm::Value *ResR = Builder.CreateNeg(Op.first, "neg.r");
llvm::Value *ResI = Builder.CreateNeg(Op.second, "neg.i");
return ComplexPairTy(ResR, ResI);
}
ComplexPairTy ComplexExprEmitter::VisitBinAdd(const BinaryOperator *E) {
ComplexPairTy LHS = Visit(E->getLHS());
ComplexPairTy RHS = Visit(E->getRHS());
llvm::Value *ResR = Builder.CreateAdd(LHS.first, RHS.first, "add.r");
llvm::Value *ResI = Builder.CreateAdd(LHS.second, RHS.second, "add.i");
return ComplexPairTy(ResR, ResI);
}
ComplexPairTy ComplexExprEmitter::VisitBinMul(const BinaryOperator *E) {
ComplexPairTy LHS = Visit(E->getLHS());
ComplexPairTy RHS = Visit(E->getRHS());
llvm::Value *ResRl = Builder.CreateMul(LHS.first, RHS.first, "mul.rl");
llvm::Value *ResRr = Builder.CreateMul(LHS.second, RHS.second, "mul.rr");
llvm::Value *ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
llvm::Value *ResIl = Builder.CreateMul(LHS.second, RHS.first, "mul.il");
llvm::Value *ResIr = Builder.CreateMul(LHS.first, RHS.second, "mul.ir");
llvm::Value *ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
return ComplexPairTy(ResR, ResI);
}
ComplexPairTy ComplexExprEmitter::VisitBinAssign(const BinaryOperator *E) {
assert(E->getLHS()->getType().getCanonicalType() ==
E->getRHS()->getType().getCanonicalType() && "Invalid assignment");
// Emit the RHS.
ComplexPairTy Val = Visit(E->getRHS());
// Compute the address to store into.
LValue LHS = CGF.EmitLValue(E->getLHS());
// Store into it.
// FIXME: Volatility!
EmitStoreOfComplex(Val, LHS.getAddress(), false);
return Val;
}
ComplexPairTy ComplexExprEmitter::VisitBinComma(const BinaryOperator *E) {
CGF.EmitStmt(E->getLHS());
return Visit(E->getRHS());
}
ComplexPairTy ComplexExprEmitter::
VisitConditionalOperator(const ConditionalOperator *E) {
llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
CGF.EmitBlock(LHSBlock);
// Handle the GNU extension for missing LHS.
assert(E->getLHS() && "Must have LHS for complex value");
ComplexPairTy LHS = Visit(E->getLHS());
Builder.CreateBr(ContBlock);
LHSBlock = Builder.GetInsertBlock();
CGF.EmitBlock(RHSBlock);
ComplexPairTy RHS = Visit(E->getRHS());
Builder.CreateBr(ContBlock);
RHSBlock = Builder.GetInsertBlock();
CGF.EmitBlock(ContBlock);
// Create a PHI node for the real part.
llvm::PHINode *RealPN = Builder.CreatePHI(LHS.first->getType(), "cond.r");
RealPN->reserveOperandSpace(2);
RealPN->addIncoming(LHS.first, LHSBlock);
RealPN->addIncoming(RHS.first, RHSBlock);
// Create a PHI node for the imaginary part.
llvm::PHINode *ImagPN = Builder.CreatePHI(LHS.first->getType(), "cond.i");
ImagPN->reserveOperandSpace(2);
ImagPN->addIncoming(LHS.second, LHSBlock);
ImagPN->addIncoming(RHS.second, RHSBlock);
return ComplexPairTy(RealPN, ImagPN);
}
//===----------------------------------------------------------------------===//
// Entry Point into this File
//===----------------------------------------------------------------------===//
/// EmitComplexExpr - Emit the computation of the specified expression of
/// complex type, ignoring the result.
ComplexPairTy CodeGenFunction::EmitComplexExpr(const Expr *E) {
assert(E && E->getType()->isComplexType() &&
"Invalid complex expression to emit");
return ComplexExprEmitter(*this).Visit(const_cast<Expr*>(E));
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2016 Shanghai Jiao Tong University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* For more about this software visit:
*
* http://ipads.se.sjtu.edu.cn/projects/wukong
*
*/
#pragma once
#ifdef USE_JEMALLOC
#include <jemalloc/jemalloc.h>
#include "mm/malloc_interface.hpp"
class JeMalloc : public MAInterface {
private:
vector<unsigned> arena_inds;
vector<unsigned> tcache_inds;
uint64_t memsize;
extent_hooks_t *new_hooks;
public:
static char *start_ptr;
static char *end_ptr;
static char *top_of_heap;
static pthread_spinlock_t jelock;
// custom extent hooks which comprises function pointers
extent_hooks_t hooks = {
JeMalloc::extent_alloc_hook,
JeMalloc::extent_dalloc_hook,
JeMalloc::extent_destroy_hook,
JeMalloc::extent_commit_hook,
JeMalloc::extent_decommit_hook,
JeMalloc::extent_purge_lazy_hook,
JeMalloc::extent_purge_forced_hook,
JeMalloc::extent_split_hook,
JeMalloc::extent_merge_hook
};
// hook functions which manage extent lifetime
static void *extent_alloc_hook(extent_hooks_t *extent_hooks, void *new_addr, size_t size,
size_t alignment, bool *zero, bool *commit, unsigned arena_ind) {
logstream(LOG_DEBUG) << "(extent_hooks = " << extent_hooks
<< " , new_addr = " << new_addr << " , size = " << size
<< " , alignment = " << alignment
<< " , *zero = " << *zero << " , *commit = " << *commit
<< " , arena_ind = " << arena_ind << ")" << LOG_endl;
pthread_spin_lock(&jelock);
char *ret = (char*)top_of_heap;
// align the return address
if ((uintptr_t)ret % alignment != 0)
ret = ret + (alignment - (uintptr_t)ret % alignment);
if ((char*)ret + size >= (char*)end_ptr) {
logstream(LOG_ERROR) << "Out of memory, cannot allocate any extent." << LOG_endl;
ASSERT(false);
pthread_spin_unlock(&jelock);
return NULL;
}
top_of_heap = ret + size;
pthread_spin_unlock(&jelock);
if (*zero) // extent should be zeroed
memset(ret, size, 0);
if ((uintptr_t)ret % alignment != 0)
logstream(LOG_ERROR) << "Alignment error." << LOG_endl;
return ret;
}
static bool extent_dalloc_hook(extent_hooks_t *extent_hooks, void *addr, size_t size,
bool committed, unsigned arena_ind) {
return true; // opt out
}
static void extent_destroy_hook(extent_hooks_t *extent_hooks, void *addr, size_t size,
bool committed, unsigned arena_ind) {
return;
}
static bool extent_commit_hook(extent_hooks_t *extent_hooks, void *addr, size_t size,
size_t offset, size_t length, unsigned arena_ind) {
return false; // commit should always succeed
}
static bool extent_decommit_hook(extent_hooks_t *extent_hooks, void *addr, size_t size,
size_t offset, size_t length, unsigned arena_ind) {
return false; // decommit should always succeed
}
static bool extent_purge_lazy_hook(extent_hooks_t *extent_hooks, void *addr, size_t size,
size_t offset, size_t length, unsigned arena_ind) {
return true; // opt out
}
static bool extent_purge_forced_hook(extent_hooks_t *extent_hooks, void *addr, size_t size,
size_t offset, size_t length, unsigned arena_ind) {
return true; // opt out
}
static bool extent_split_hook(extent_hooks_t *extent_hooks, void *addr, size_t size,
size_t size_a, size_t size_b, bool committed, unsigned arena_ind) {
return false; // split should always succeed
}
static bool extent_merge_hook(extent_hooks_t *extent_hooks, void *addr_a, size_t size_a,
void *addr_b, size_t size_b, bool committed, unsigned arena_ind) {
return false; // merge should always succeed
}
void init(void *start, uint64_t size, uint64_t n) {
start_ptr = top_of_heap = (char*)start;
memsize = size;
end_ptr = start_ptr + memsize;
pthread_spin_init(&jelock, 0);
size_t hooks_len = sizeof(extent_hooks_t *);
size_t sz = sizeof(unsigned);
arena_inds.resize(n);
tcache_inds.resize(n);
new_hooks = &hooks;
// create new arena for each engine and install custom extent hooks on it
for (int i = 0; i < n; i++)
mallctl("arenas.create", (void *)&arena_inds[i], &sz,
(void *)&new_hooks, sizeof(extent_hooks_t *));
// create thread-specific cache for each engine
for (int i = 0; i < n; i++)
mallctl("tcache.create", (void *)&tcache_inds[i], &sz, NULL, 0);
}
uint64_t malloc(uint64_t size, int64_t tid) {
// malloc from engine's own arena and tcache
void *ptr = mallocx(size, MALLOCX_ARENA(arena_inds[tid]) | MALLOCX_TCACHE(tcache_inds[tid]));
if ((char*)ptr < start_ptr || (char*)ptr + size > end_ptr) {
logstream(LOG_ERROR) << "memory range false" << LOG_endl;
ASSERT(false);
}
uint64_t ret = (uint64_t)((char*)ptr - start_ptr);
return ret;
}
void free(uint64_t idx) {
void* ptr = (void*)(start_ptr + idx);
dallocx(ptr, 0); // make the memory be available for future allocations
return;
}
uint64_t sz_to_blksz(uint64_t size) { return (uint64_t)nallocx(size, 0); }
//to be suited with buddy malloc
void merge_freelists() { return; }
void print_memory_usage() {
uint64_t allocated_size = ((char*)top_of_heap - (char*)start_ptr) / (1024 * 1024);
logstream(LOG_INFO) << "graph_storage edge memory status:" << LOG_endl;
logstream(LOG_INFO) << "allocated " << allocated_size << " MB" << LOG_endl;
return;
}
};
// needed to provide a definition for static member variables
char* JeMalloc::start_ptr = NULL;
char* JeMalloc::end_ptr = NULL;
char* JeMalloc::top_of_heap = NULL;
pthread_spinlock_t JeMalloc::jelock;
#endif
<commit_msg>a hided bug fix on jemalloc<commit_after>/*
* Copyright (c) 2016 Shanghai Jiao Tong University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* For more about this software visit:
*
* http://ipads.se.sjtu.edu.cn/projects/wukong
*
*/
#pragma once
#ifdef USE_JEMALLOC
#include <jemalloc/jemalloc.h>
#include "mm/malloc_interface.hpp"
class JeMalloc : public MAInterface {
private:
vector<unsigned> arena_inds;
vector<unsigned> tcache_inds;
uint64_t memsize;
extent_hooks_t *new_hooks;
public:
static char *start_ptr;
static char *end_ptr;
static char *top_of_heap;
static pthread_spinlock_t jelock;
// custom extent hooks which comprises function pointers
extent_hooks_t hooks = {
JeMalloc::extent_alloc_hook,
JeMalloc::extent_dalloc_hook,
JeMalloc::extent_destroy_hook,
JeMalloc::extent_commit_hook,
JeMalloc::extent_decommit_hook,
JeMalloc::extent_purge_lazy_hook,
JeMalloc::extent_purge_forced_hook,
JeMalloc::extent_split_hook,
JeMalloc::extent_merge_hook
};
// hook functions which manage extent lifetime
static void *extent_alloc_hook(extent_hooks_t *extent_hooks, void *new_addr, size_t size,
size_t alignment, bool *zero, bool *commit, unsigned arena_ind) {
logstream(LOG_DEBUG) << "(extent_hooks = " << extent_hooks
<< " , new_addr = " << new_addr << " , size = " << size
<< " , alignment = " << alignment
<< " , *zero = " << *zero << " , *commit = " << *commit
<< " , arena_ind = " << arena_ind << ")" << LOG_endl;
pthread_spin_lock(&jelock);
char *ret = (char*)top_of_heap;
// align the return address
if ((uintptr_t)ret % alignment != 0)
ret = ret + (alignment - (uintptr_t)ret % alignment);
if ((char*)ret + size >= (char*)end_ptr) {
logstream(LOG_ERROR) << "Out of memory, cannot allocate any extent." << LOG_endl;
ASSERT(false);
pthread_spin_unlock(&jelock);
return NULL;
}
top_of_heap = ret + size;
pthread_spin_unlock(&jelock);
if (*zero) // extent should be zeroed
memset(ret, 0, size);
if ((uintptr_t)ret % alignment != 0)
logstream(LOG_ERROR) << "Alignment error." << LOG_endl;
return ret;
}
static bool extent_dalloc_hook(extent_hooks_t *extent_hooks, void *addr, size_t size,
bool committed, unsigned arena_ind) {
return true; // opt out
}
static void extent_destroy_hook(extent_hooks_t *extent_hooks, void *addr, size_t size,
bool committed, unsigned arena_ind) {
return;
}
static bool extent_commit_hook(extent_hooks_t *extent_hooks, void *addr, size_t size,
size_t offset, size_t length, unsigned arena_ind) {
return false; // commit should always succeed
}
static bool extent_decommit_hook(extent_hooks_t *extent_hooks, void *addr, size_t size,
size_t offset, size_t length, unsigned arena_ind) {
return false; // decommit should always succeed
}
static bool extent_purge_lazy_hook(extent_hooks_t *extent_hooks, void *addr, size_t size,
size_t offset, size_t length, unsigned arena_ind) {
return true; // opt out
}
static bool extent_purge_forced_hook(extent_hooks_t *extent_hooks, void *addr, size_t size,
size_t offset, size_t length, unsigned arena_ind) {
return true; // opt out
}
static bool extent_split_hook(extent_hooks_t *extent_hooks, void *addr, size_t size,
size_t size_a, size_t size_b, bool committed, unsigned arena_ind) {
return false; // split should always succeed
}
static bool extent_merge_hook(extent_hooks_t *extent_hooks, void *addr_a, size_t size_a,
void *addr_b, size_t size_b, bool committed, unsigned arena_ind) {
return false; // merge should always succeed
}
void init(void *start, uint64_t size, uint64_t n) {
start_ptr = top_of_heap = (char*)start;
memsize = size;
end_ptr = start_ptr + memsize;
pthread_spin_init(&jelock, 0);
size_t hooks_len = sizeof(extent_hooks_t *);
size_t sz = sizeof(unsigned);
arena_inds.resize(n);
tcache_inds.resize(n);
new_hooks = &hooks;
// create new arena for each engine and install custom extent hooks on it
for (int i = 0; i < n; i++)
mallctl("arenas.create", (void *)&arena_inds[i], &sz,
(void *)&new_hooks, sizeof(extent_hooks_t *));
// create thread-specific cache for each engine
for (int i = 0; i < n; i++)
mallctl("tcache.create", (void *)&tcache_inds[i], &sz, NULL, 0);
}
uint64_t malloc(uint64_t size, int64_t tid) {
// malloc from engine's own arena and tcache
void *ptr = mallocx(size, MALLOCX_ARENA(arena_inds[tid]) | MALLOCX_TCACHE(tcache_inds[tid]));
if ((char*)ptr < start_ptr || (char*)ptr + size > end_ptr) {
logstream(LOG_ERROR) << "memory range false" << LOG_endl;
ASSERT(false);
}
uint64_t ret = (uint64_t)((char*)ptr - start_ptr);
return ret;
}
void free(uint64_t idx) {
void* ptr = (void*)(start_ptr + idx);
dallocx(ptr, 0); // make the memory be available for future allocations
return;
}
uint64_t sz_to_blksz(uint64_t size) { return (uint64_t)nallocx(size, 0); }
//to be suited with buddy malloc
void merge_freelists() { return; }
void print_memory_usage() {
uint64_t allocated_size = ((char*)top_of_heap - (char*)start_ptr) / (1024 * 1024);
logstream(LOG_INFO) << "graph_storage edge memory status:" << LOG_endl;
logstream(LOG_INFO) << "allocated " << allocated_size << " MB" << LOG_endl;
return;
}
};
// needed to provide a definition for static member variables
char* JeMalloc::start_ptr = NULL;
char* JeMalloc::end_ptr = NULL;
char* JeMalloc::top_of_heap = NULL;
pthread_spinlock_t JeMalloc::jelock;
#endif
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkStringArray.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright 2004 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
license for use of this work by or on behalf of the
U.S. Government. Redistribution and use in source and binary forms, with
or without modification, are permitted provided that this Notice and any
statement of authorship are reproduced on all copies.
=========================================================================*/
// We do not provide a definition for the copy constructor or
// operator=. Block the warning.
#ifdef _MSC_VER
# pragma warning (disable: 4661)
#endif
#include <vtkObjectFactory.h>
#include "vtkStringArray.h"
#include "vtkStdString.h"
#include "vtkCharArray.h"
#include "vtkIdList.h"
#include "vtkIdTypeArray.h"
vtkCxxRevisionMacro(vtkStringArray, "1.4");
vtkStandardNewMacro(vtkStringArray);
//----------------------------------------------------------------------------
vtkStringArray::vtkStringArray(vtkIdType numComp) :
vtkAbstractArray( numComp )
{
this->Array = NULL;
this->SaveUserArray = 0;
}
//----------------------------------------------------------------------------
vtkStringArray::~vtkStringArray()
{
if ((this->Array) && (!this->SaveUserArray))
{
delete [] this->Array;
}
}
//----------------------------------------------------------------------------
// This method lets the user specify data to be held by the array. The
// array argument is a pointer to the data. size is the size of
// the array supplied by the user. Set save to 1 to keep the class
// from deleting the array when it cleans up or reallocates memory.
// The class uses the actual array provided; it does not copy the data
// from the suppled array.
void vtkStringArray::SetArray(vtkStdString *array, vtkIdType size, int save)
{
if ((this->Array) && (!this->SaveUserArray))
{
vtkDebugMacro (<< "Deleting the array...");
delete [] this->Array;
}
else
{
vtkDebugMacro (<<"Warning, array not deleted, but will point to new array.");
}
vtkDebugMacro(<<"Setting array to: " << array);
this->Array = array;
this->Size = size;
this->MaxId = size-1;
this->SaveUserArray = save;
}
//----------------------------------------------------------------------------
// Allocate memory for this array. Delete old storage only if necessary.
int vtkStringArray::Allocate(vtkIdType sz, vtkIdType)
{
if(sz > this->Size)
{
if(this->Array && !this->SaveUserArray)
{
delete [] this->Array;
}
this->Size = ( sz > 0 ? sz : 1);
this->Array = new vtkStdString[this->Size];
if(!this->Array)
{
return 0;
}
this->SaveUserArray = 0;
}
this->MaxId = -1;
return 1;
}
//----------------------------------------------------------------------------
// Release storage and reset array to initial state.
void vtkStringArray::Initialize()
{
if(this->Array && !this->SaveUserArray)
{
delete [] this->Array;
}
this->Array = 0;
this->Size = 0;
this->MaxId = -1;
this->SaveUserArray = 0;
}
//----------------------------------------------------------------------------
// Deep copy of another string array.
void vtkStringArray::DeepCopy(vtkAbstractArray* aa)
{
// Do nothing on a NULL input.
if(!aa)
{
return;
}
// Avoid self-copy.
if(this == aa)
{
return;
}
// If data type does not match, we can't copy.
if(aa->GetDataType() != this->GetDataType())
{
vtkErrorMacro(<< "Incompatible types: tried to copy an array of type "
<< aa->GetDataTypeAsString()
<< " into a string array ");
return;
}
vtkStringArray *fa = vtkStringArray::SafeDownCast( aa );
if ( fa == NULL )
{
vtkErrorMacro(<< "Shouldn't Happen: Couldn't downcast array into a vtkStringArray." );
return;
}
// Free our previous memory.
if(this->Array && !this->SaveUserArray)
{
delete [] this->Array;
}
// Copy the given array into new memory.
this->MaxId = fa->GetMaxId();
this->Size = fa->GetSize();
this->SaveUserArray = 0;
this->Array = new vtkStdString[this->Size];
for (int i = 0; i < this->Size; ++i)
{
this->Array[i] = fa->Array[i];
}
}
//----------------------------------------------------------------------------
void vtkStringArray::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
if(this->Array)
{
os << indent << "Array: " << this->Array << "\n";
}
else
{
os << indent << "Array: (null)\n";
}
}
//----------------------------------------------------------------------------
// Protected function does "reallocate"
vtkStdString * vtkStringArray::ResizeAndExtend(vtkIdType sz)
{
vtkStdString * newArray;
vtkIdType newSize;
if(sz > this->Size)
{
// Requested size is bigger than current size. Allocate enough
// memory to fit the requested size and be more than double the
// currently allocated memory.
newSize = this->Size + sz;
}
else if (sz == this->Size)
{
// Requested size is equal to current size. Do nothing.
return this->Array;
}
else
{
// Requested size is smaller than current size. Squeeze the
// memory.
newSize = sz;
}
if(newSize <= 0)
{
this->Initialize();
return 0;
}
newArray = new vtkStdString[newSize];
if(!newArray)
{
vtkErrorMacro("Cannot allocate memory\n");
return 0;
}
if(this->Array)
{
// can't use memcpy here
int numCopy = (newSize < this->Size ? newSize : this->Size);
for (int i = 0; i < numCopy; ++i)
{
newArray[i] = this->Array[i];
}
if(!this->SaveUserArray)
{
delete [] this->Array;
}
}
if(newSize < this->Size)
{
this->MaxId = newSize-1;
}
this->Size = newSize;
this->Array = newArray;
this->SaveUserArray = 0;
return this->Array;
}
//----------------------------------------------------------------------------
void vtkStringArray::Resize(vtkIdType sz)
{
vtkStdString * newArray;
vtkIdType newSize = sz;
if(newSize == this->Size)
{
return;
}
if(newSize <= 0)
{
this->Initialize();
return;
}
newArray = new vtkStdString[newSize];
if(!newArray)
{
vtkErrorMacro(<< "Cannot allocate memory\n");
return;
}
if(this->Array)
{
int numCopy = (newSize < this->Size ? newSize : this->Size);
for (int i = 0; i < numCopy; ++i)
{
newArray[i] = this->Array[i];
}
if(!this->SaveUserArray)
{
delete[] this->Array;
}
}
if(newSize < this->Size)
{
this->MaxId = newSize-1;
}
this->Size = newSize;
this->Array = newArray;
this->SaveUserArray = 0;
}
//----------------------------------------------------------------------------
void vtkStringArray::SetNumberOfValues(vtkIdType number)
{
this->Allocate(number);
this->MaxId = number - 1;
}
//----------------------------------------------------------------------------
vtkStdString * vtkStringArray::WritePointer(vtkIdType id,
vtkIdType number)
{
vtkIdType newSize=id+number;
if ( newSize > this->Size )
{
this->ResizeAndExtend(newSize);
}
if ( (--newSize) > this->MaxId )
{
this->MaxId = newSize;
}
return this->Array + id;
}
//----------------------------------------------------------------------------
void vtkStringArray::InsertValue(vtkIdType id, vtkStdString f)
{
if ( id >= this->Size )
{
this->ResizeAndExtend(id+1);
}
this->Array[id] = f;
if ( id > this->MaxId )
{
this->MaxId = id;
}
}
//----------------------------------------------------------------------------
vtkIdType vtkStringArray::InsertNextValue(vtkStdString f)
{
this->InsertValue (++this->MaxId,f);
return this->MaxId;
}
// ----------------------------------------------------------------------
int
vtkStringArray::GetDataTypeSize( void )
{ return static_cast<int>(sizeof(vtkStdString)); }
// ----------------------------------------------------------------------
unsigned long
vtkStringArray::GetActualMemorySize( void )
{
unsigned long totalSize = 0;
unsigned long numPrims = this->GetSize();
for (unsigned long i = 0; i < numPrims; ++i)
{
totalSize += sizeof( vtkStdString );
totalSize += this->Array[i].size() * sizeof( vtkStdString::value_type );
}
return (unsigned long) ceil( totalSize / 1000.0 ); // kilobytes
}
// ----------------------------------------------------------------------
vtkStdString &
vtkStringArray::GetValue( vtkIdType id )
{
return this->Array[id];
}
// ----------------------------------------------------------------------
void
vtkStringArray::GetValues(vtkIdList *indices, vtkAbstractArray *aa)
{
if (aa == NULL)
{
vtkErrorMacro(<<"GetValues: Output array is null!");
return;
}
vtkStringArray *output = vtkStringArray::SafeDownCast(aa);
if (output == NULL)
{
vtkErrorMacro(<< "Can't copy values from a string array into an array "
<< "of type " << aa->GetDataTypeAsString());
return;
}
for (vtkIdType i = 0; i < indices->GetNumberOfIds(); ++i)
{
vtkIdType index = indices->GetId(i);
output->SetValue(i, this->GetValue(index));
}
}
// ----------------------------------------------------------------------
void
vtkStringArray::GetValues(vtkIdType startIndex,
vtkIdType endIndex,
vtkAbstractArray *aa)
{
if (aa == NULL)
{
vtkErrorMacro(<<"GetValues: Output array is null!");
return;
}
vtkStringArray *output = vtkStringArray::SafeDownCast(aa);
if (output == NULL)
{
vtkErrorMacro(<< "Can't copy values from a string array into an array "
<< "of type " << aa->GetDataTypeAsString());
return;
}
for (vtkIdType i = 0; i < (endIndex - startIndex) + 1; ++i)
{
vtkIdType index = startIndex + i;
output->SetValue(i, this->GetValue(index));
}
}
// ----------------------------------------------------------------------
void
vtkStringArray::CopyValue(int toIndex, int fromIndex,
vtkAbstractArray *source)
{
if (source == NULL)
{
vtkErrorMacro(<<"CopyValue: Input array is null!");
return;
}
vtkStringArray *realSource = vtkStringArray::SafeDownCast(source);
if (realSource == NULL)
{
vtkErrorMacro(<< "Can't copy values from an array of type "
<< source->GetDataTypeAsString()
<< " into a string array!");
return;
}
this->SetValue(toIndex, realSource->GetValue(fromIndex));
}
// ----------------------------------------------------------------------
void
vtkStringArray::ConvertToContiguous(vtkDataArray **Data,
vtkIdTypeArray **Offsets)
{
vtkCharArray *data = vtkCharArray::New();
vtkIdTypeArray *offsets = vtkIdTypeArray::New();
int currentPosition = 0;
for (vtkIdType i = 0; i < this->GetNumberOfValues(); ++i)
{
vtkStdString thisString = this->Array[i];
for (unsigned int j = 0; j < this->Array[i].length(); ++j)
{
data->InsertNextValue(thisString[j]);
++currentPosition;
}
offsets->InsertNextValue(currentPosition);
}
*Data = data;
*Offsets = offsets;
}
// ----------------------------------------------------------------------
// This will work with any sort of data array, but if you call it with
// anything other than a char array you might get strange results.
// You have been warned...
void
vtkStringArray::ConvertFromContiguous(vtkDataArray *Data,
vtkIdTypeArray *Offsets)
{
this->Reset();
vtkIdType currentStringStart = 0;
for (vtkIdType i = 0; i < Offsets->GetNumberOfTuples(); ++i)
{
// YOU ARE HERE
vtkStdString newString;
vtkIdType stringEnd = Offsets->GetValue(i);
for (vtkIdType here = currentStringStart;
here < stringEnd;
++here)
{
newString += static_cast<char>(Data->GetTuple1(here));
}
this->InsertNextValue(newString);
currentStringStart = stringEnd;
}
}
// ----------------------------------------------------------------------
//
//
// Below here are interface methods to allow values to be inserted as
// const char * instead of vtkStdString. Yes, they're trivial. The
// wrapper code needs them.
//
//
void
vtkStringArray::SetValue( vtkIdType id, const char *value )
{
this->SetValue( id, vtkStdString(value) );
}
void
vtkStringArray::InsertValue( vtkIdType id, const char *value )
{
this->InsertValue( id, vtkStdString( value ) );
}
vtkIdType
vtkStringArray::InsertNextValue( const char *value )
{
return this->InsertNextValue( vtkStdString( value ) );
}
// ----------------------------------------------------------------------
<commit_msg>ENH: Merge changes from main tree into VTK-5-0 branch. (cvs -q up -j1.4 -j1.5 Common/vtkStringArray.cxx)<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkStringArray.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright 2004 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
license for use of this work by or on behalf of the
U.S. Government. Redistribution and use in source and binary forms, with
or without modification, are permitted provided that this Notice and any
statement of authorship are reproduced on all copies.
=========================================================================*/
// We do not provide a definition for the copy constructor or
// operator=. Block the warning.
#ifdef _MSC_VER
# pragma warning (disable: 4661)
#endif
#include <vtkObjectFactory.h>
#include "vtkStringArray.h"
#include "vtkStdString.h"
#include "vtkCharArray.h"
#include "vtkIdList.h"
#include "vtkIdTypeArray.h"
vtkCxxRevisionMacro(vtkStringArray, "1.4.6.1");
vtkStandardNewMacro(vtkStringArray);
//----------------------------------------------------------------------------
vtkStringArray::vtkStringArray(vtkIdType numComp) :
vtkAbstractArray( numComp )
{
this->Array = NULL;
this->SaveUserArray = 0;
}
//----------------------------------------------------------------------------
vtkStringArray::~vtkStringArray()
{
if ((this->Array) && (!this->SaveUserArray))
{
delete [] this->Array;
}
}
//----------------------------------------------------------------------------
// This method lets the user specify data to be held by the array. The
// array argument is a pointer to the data. size is the size of
// the array supplied by the user. Set save to 1 to keep the class
// from deleting the array when it cleans up or reallocates memory.
// The class uses the actual array provided; it does not copy the data
// from the suppled array.
void vtkStringArray::SetArray(vtkStdString *array, vtkIdType size, int save)
{
if ((this->Array) && (!this->SaveUserArray))
{
vtkDebugMacro (<< "Deleting the array...");
delete [] this->Array;
}
else
{
vtkDebugMacro (<<"Warning, array not deleted, but will point to new array.");
}
vtkDebugMacro(<<"Setting array to: " << array);
this->Array = array;
this->Size = size;
this->MaxId = size-1;
this->SaveUserArray = save;
}
//----------------------------------------------------------------------------
// Allocate memory for this array. Delete old storage only if necessary.
int vtkStringArray::Allocate(vtkIdType sz, vtkIdType)
{
if(sz > this->Size)
{
if(this->Array && !this->SaveUserArray)
{
delete [] this->Array;
}
this->Size = ( sz > 0 ? sz : 1);
this->Array = new vtkStdString[this->Size];
if(!this->Array)
{
return 0;
}
this->SaveUserArray = 0;
}
this->MaxId = -1;
return 1;
}
//----------------------------------------------------------------------------
// Release storage and reset array to initial state.
void vtkStringArray::Initialize()
{
if(this->Array && !this->SaveUserArray)
{
delete [] this->Array;
}
this->Array = 0;
this->Size = 0;
this->MaxId = -1;
this->SaveUserArray = 0;
}
//----------------------------------------------------------------------------
// Deep copy of another string array.
void vtkStringArray::DeepCopy(vtkAbstractArray* aa)
{
// Do nothing on a NULL input.
if(!aa)
{
return;
}
// Avoid self-copy.
if(this == aa)
{
return;
}
// If data type does not match, we can't copy.
if(aa->GetDataType() != this->GetDataType())
{
vtkErrorMacro(<< "Incompatible types: tried to copy an array of type "
<< aa->GetDataTypeAsString()
<< " into a string array ");
return;
}
vtkStringArray *fa = vtkStringArray::SafeDownCast( aa );
if ( fa == NULL )
{
vtkErrorMacro(<< "Shouldn't Happen: Couldn't downcast array into a vtkStringArray." );
return;
}
// Free our previous memory.
if(this->Array && !this->SaveUserArray)
{
delete [] this->Array;
}
// Copy the given array into new memory.
this->MaxId = fa->GetMaxId();
this->Size = fa->GetSize();
this->SaveUserArray = 0;
this->Array = new vtkStdString[this->Size];
for (int i = 0; i < this->Size; ++i)
{
this->Array[i] = fa->Array[i];
}
}
//----------------------------------------------------------------------------
void vtkStringArray::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
if(this->Array)
{
os << indent << "Array: " << this->Array << "\n";
}
else
{
os << indent << "Array: (null)\n";
}
}
//----------------------------------------------------------------------------
// Protected function does "reallocate"
vtkStdString * vtkStringArray::ResizeAndExtend(vtkIdType sz)
{
vtkStdString * newArray;
vtkIdType newSize;
if(sz > this->Size)
{
// Requested size is bigger than current size. Allocate enough
// memory to fit the requested size and be more than double the
// currently allocated memory.
newSize = this->Size + sz;
}
else if (sz == this->Size)
{
// Requested size is equal to current size. Do nothing.
return this->Array;
}
else
{
// Requested size is smaller than current size. Squeeze the
// memory.
newSize = sz;
}
if(newSize <= 0)
{
this->Initialize();
return 0;
}
newArray = new vtkStdString[newSize];
if(!newArray)
{
vtkErrorMacro("Cannot allocate memory\n");
return 0;
}
if(this->Array)
{
// can't use memcpy here
int numCopy = (newSize < this->Size ? newSize : this->Size);
for (int i = 0; i < numCopy; ++i)
{
newArray[i] = this->Array[i];
}
if(!this->SaveUserArray)
{
delete [] this->Array;
}
}
if(newSize < this->Size)
{
this->MaxId = newSize-1;
}
this->Size = newSize;
this->Array = newArray;
this->SaveUserArray = 0;
return this->Array;
}
//----------------------------------------------------------------------------
int vtkStringArray::Resize(vtkIdType sz)
{
vtkStdString * newArray;
vtkIdType newSize = sz;
if(newSize == this->Size)
{
return 1;
}
if(newSize <= 0)
{
this->Initialize();
return 1;
}
newArray = new vtkStdString[newSize];
if(!newArray)
{
vtkErrorMacro(<< "Cannot allocate memory\n");
return 0;
}
if(this->Array)
{
int numCopy = (newSize < this->Size ? newSize : this->Size);
for (int i = 0; i < numCopy; ++i)
{
newArray[i] = this->Array[i];
}
if(!this->SaveUserArray)
{
delete[] this->Array;
}
}
if(newSize < this->Size)
{
this->MaxId = newSize-1;
}
this->Size = newSize;
this->Array = newArray;
this->SaveUserArray = 0;
return 1;
}
//----------------------------------------------------------------------------
void vtkStringArray::SetNumberOfValues(vtkIdType number)
{
this->Allocate(number);
this->MaxId = number - 1;
}
//----------------------------------------------------------------------------
vtkStdString * vtkStringArray::WritePointer(vtkIdType id,
vtkIdType number)
{
vtkIdType newSize=id+number;
if ( newSize > this->Size )
{
this->ResizeAndExtend(newSize);
}
if ( (--newSize) > this->MaxId )
{
this->MaxId = newSize;
}
return this->Array + id;
}
//----------------------------------------------------------------------------
void vtkStringArray::InsertValue(vtkIdType id, vtkStdString f)
{
if ( id >= this->Size )
{
this->ResizeAndExtend(id+1);
}
this->Array[id] = f;
if ( id > this->MaxId )
{
this->MaxId = id;
}
}
//----------------------------------------------------------------------------
vtkIdType vtkStringArray::InsertNextValue(vtkStdString f)
{
this->InsertValue (++this->MaxId,f);
return this->MaxId;
}
// ----------------------------------------------------------------------
int
vtkStringArray::GetDataTypeSize( void )
{ return static_cast<int>(sizeof(vtkStdString)); }
// ----------------------------------------------------------------------
unsigned long
vtkStringArray::GetActualMemorySize( void )
{
unsigned long totalSize = 0;
unsigned long numPrims = this->GetSize();
for (unsigned long i = 0; i < numPrims; ++i)
{
totalSize += sizeof( vtkStdString );
totalSize += this->Array[i].size() * sizeof( vtkStdString::value_type );
}
return (unsigned long) ceil( totalSize / 1000.0 ); // kilobytes
}
// ----------------------------------------------------------------------
vtkStdString &
vtkStringArray::GetValue( vtkIdType id )
{
return this->Array[id];
}
// ----------------------------------------------------------------------
void
vtkStringArray::GetValues(vtkIdList *indices, vtkAbstractArray *aa)
{
if (aa == NULL)
{
vtkErrorMacro(<<"GetValues: Output array is null!");
return;
}
vtkStringArray *output = vtkStringArray::SafeDownCast(aa);
if (output == NULL)
{
vtkErrorMacro(<< "Can't copy values from a string array into an array "
<< "of type " << aa->GetDataTypeAsString());
return;
}
for (vtkIdType i = 0; i < indices->GetNumberOfIds(); ++i)
{
vtkIdType index = indices->GetId(i);
output->SetValue(i, this->GetValue(index));
}
}
// ----------------------------------------------------------------------
void
vtkStringArray::GetValues(vtkIdType startIndex,
vtkIdType endIndex,
vtkAbstractArray *aa)
{
if (aa == NULL)
{
vtkErrorMacro(<<"GetValues: Output array is null!");
return;
}
vtkStringArray *output = vtkStringArray::SafeDownCast(aa);
if (output == NULL)
{
vtkErrorMacro(<< "Can't copy values from a string array into an array "
<< "of type " << aa->GetDataTypeAsString());
return;
}
for (vtkIdType i = 0; i < (endIndex - startIndex) + 1; ++i)
{
vtkIdType index = startIndex + i;
output->SetValue(i, this->GetValue(index));
}
}
// ----------------------------------------------------------------------
void
vtkStringArray::CopyValue(int toIndex, int fromIndex,
vtkAbstractArray *source)
{
if (source == NULL)
{
vtkErrorMacro(<<"CopyValue: Input array is null!");
return;
}
vtkStringArray *realSource = vtkStringArray::SafeDownCast(source);
if (realSource == NULL)
{
vtkErrorMacro(<< "Can't copy values from an array of type "
<< source->GetDataTypeAsString()
<< " into a string array!");
return;
}
this->SetValue(toIndex, realSource->GetValue(fromIndex));
}
// ----------------------------------------------------------------------
void
vtkStringArray::ConvertToContiguous(vtkDataArray **Data,
vtkIdTypeArray **Offsets)
{
vtkCharArray *data = vtkCharArray::New();
vtkIdTypeArray *offsets = vtkIdTypeArray::New();
int currentPosition = 0;
for (vtkIdType i = 0; i < this->GetNumberOfValues(); ++i)
{
vtkStdString thisString = this->Array[i];
for (unsigned int j = 0; j < this->Array[i].length(); ++j)
{
data->InsertNextValue(thisString[j]);
++currentPosition;
}
offsets->InsertNextValue(currentPosition);
}
*Data = data;
*Offsets = offsets;
}
// ----------------------------------------------------------------------
// This will work with any sort of data array, but if you call it with
// anything other than a char array you might get strange results.
// You have been warned...
void
vtkStringArray::ConvertFromContiguous(vtkDataArray *Data,
vtkIdTypeArray *Offsets)
{
this->Reset();
vtkIdType currentStringStart = 0;
for (vtkIdType i = 0; i < Offsets->GetNumberOfTuples(); ++i)
{
// YOU ARE HERE
vtkStdString newString;
vtkIdType stringEnd = Offsets->GetValue(i);
for (vtkIdType here = currentStringStart;
here < stringEnd;
++here)
{
newString += static_cast<char>(Data->GetTuple1(here));
}
this->InsertNextValue(newString);
currentStringStart = stringEnd;
}
}
// ----------------------------------------------------------------------
//
//
// Below here are interface methods to allow values to be inserted as
// const char * instead of vtkStdString. Yes, they're trivial. The
// wrapper code needs them.
//
//
void
vtkStringArray::SetValue( vtkIdType id, const char *value )
{
this->SetValue( id, vtkStdString(value) );
}
void
vtkStringArray::InsertValue( vtkIdType id, const char *value )
{
this->InsertValue( id, vtkStdString( value ) );
}
vtkIdType
vtkStringArray::InsertNextValue( const char *value )
{
return this->InsertNextValue( vtkStdString( value ) );
}
// ----------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#ifndef _Stroika_Foundation_Time_Duration_inl_
#define _Stroika_Foundation_Time_Duration_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika::Foundation::Time {
/*
********************************************************************************
************************************ Duration **********************************
********************************************************************************
*/
template <typename DURATION_REP, typename DURATION_PERIOD>
constexpr Duration::Duration (const chrono::duration<DURATION_REP, DURATION_PERIOD>& d)
: fRepType_ (eNumeric_)
, fNonStringRep_{}
, fNumericRepOrCache_ (chrono::duration<InternalNumericFormatType_> (d).count ())
{
}
constexpr Duration::Duration ()
: fRepType_ (eEmpty_)
, fNonStringRep_{}
{
}
inline Duration::Duration (const Duration& src)
: fRepType_ (src.fRepType_)
, fNumericRepOrCache_ (src.fNumericRepOrCache_)
{
if (fRepType_ == eString_) {
Assert (not src.fStringRep_.empty ());
new (&fStringRep_) string (src.fStringRep_);
}
}
inline Duration::Duration (Duration&& src)
: fRepType_ (src.fRepType_)
, fNumericRepOrCache_ (src.fNumericRepOrCache_)
{
if (src.fRepType_ == eString_) {
Assert (fRepType_ == eString_);
new (&fStringRep_) string (move (src.fStringRep_));
}
src.fRepType_ = eEmpty_;
}
inline Duration::Duration (const string& durationStr)
: fNonStringRep_{}
{
Assert (fRepType_ == eEmpty_);
if (not durationStr.empty ()) {
fNumericRepOrCache_ = ParseTime_ (durationStr);
new (&fStringRep_) string (durationStr);
fRepType_ = eString_;
}
}
constexpr Duration::Duration (int duration)
: fRepType_ (eNumeric_)
, fNonStringRep_{}
, fNumericRepOrCache_ (duration)
{
}
constexpr Duration::Duration (long duration)
: fRepType_ (eNumeric_)
, fNonStringRep_{}
, fNumericRepOrCache_ (duration)
{
}
constexpr Duration::Duration (long long duration)
: fRepType_ (eNumeric_)
, fNonStringRep_{}
, fNumericRepOrCache_ (static_cast<InternalNumericFormatType_> (duration))
{
}
constexpr Duration::Duration (float duration)
: fRepType_ (eNumeric_)
, fNonStringRep_{}
, fNumericRepOrCache_ (duration)
{
//Require (not isnan (duration)); // inf is allowed
}
constexpr Duration::Duration (double duration)
: fRepType_ (eNumeric_)
, fNonStringRep_{}
, fNumericRepOrCache_ (duration)
{
//Require (not isnan (duration)); // inf is allowed
}
constexpr Duration::Duration (long double duration)
: fRepType_ (eNumeric_)
, fNonStringRep_{}
, fNumericRepOrCache_ (static_cast<InternalNumericFormatType_> (duration))
{
//Require (not isnan (duration)); // inf is allowed
}
inline string Duration::AsUTF8 () const
{
return As<Characters::String> ().AsUTF8 ();
}
inline Duration::~Duration ()
{
destroy_ ();
}
inline void Duration::clear ()
{
destroy_ ();
}
constexpr bool Duration::empty () const
{
// on construction with an empty string, this produces type eEmpty_
return fRepType_ == eEmpty_;
}
inline Duration& Duration::operator= (const Duration& rhs)
{
if (this != &rhs) {
if (fRepType_ == rhs.fRepType_) {
if (rhs.fRepType_ == eString_) {
// if both unions have string active - just assign
fStringRep_ = rhs.fStringRep_;
}
}
else {
// if reps differnt, destroy any strings
destroy_ ();
if (rhs.fRepType_ == eString_) {
new (&fStringRep_) string (rhs.fStringRep_);
// fRepType_ = eString_; done at end of procedure
}
}
fNumericRepOrCache_ = rhs.fNumericRepOrCache_;
fRepType_ = rhs.fRepType_;
}
return *this;
}
inline Duration& Duration::operator= (Duration&& rhs)
{
if (this != &rhs) {
if (fRepType_ == rhs.fRepType_) {
// if both unions have string active - just move assign
if (rhs.fRepType_ == eString_) {
fStringRep_ = move (rhs.fStringRep_);
// setting our type, and STEALING type of rhs at bottom of procedure
}
}
else {
destroy_ ();
if (rhs.fRepType_ == eString_) {
new (&fStringRep_) string (move (rhs.fStringRep_));
}
}
fNumericRepOrCache_ = rhs.fNumericRepOrCache_;
fRepType_ = rhs.fRepType_;
rhs.fRepType_ = eEmpty_;
}
return *this;
}
inline void Duration::destroy_ ()
{
if (fRepType_ == eString_) {
fStringRep_.~basic_string ();
}
fRepType_ = eEmpty_;
}
template <>
inline int Duration::As () const
{
return static_cast<int> (fNumericRepOrCache_);
}
template <>
inline long int Duration::As () const
{
return static_cast<long int> (fNumericRepOrCache_);
}
template <>
inline long long int Duration::As () const
{
return static_cast<long long int> (fNumericRepOrCache_);
}
template <>
inline float Duration::As () const
{
return static_cast<float> (fNumericRepOrCache_);
}
template <>
inline double Duration::As () const
{
return fNumericRepOrCache_;
}
template <>
inline long double Duration::As () const
{
return fNumericRepOrCache_;
}
template <>
inline chrono::duration<double> Duration::As () const
{
return chrono::duration<double> (fNumericRepOrCache_);
}
template <>
inline chrono::seconds Duration::As () const
{
return chrono::seconds (static_cast<chrono::seconds::rep> (fNumericRepOrCache_));
}
template <>
inline chrono::milliseconds Duration::As () const
{
return chrono::milliseconds (static_cast<chrono::milliseconds::rep> (fNumericRepOrCache_ * 1000));
}
template <>
inline chrono::microseconds Duration::As () const
{
return chrono::microseconds (static_cast<chrono::microseconds::rep> (fNumericRepOrCache_ * 1000 * 1000));
}
template <>
inline chrono::nanoseconds Duration::As () const
{
return chrono::nanoseconds (static_cast<chrono::nanoseconds::rep> (fNumericRepOrCache_ * 1000.0 * 1000.0 * 1000.0));
}
template <>
inline Characters::String Duration::As () const
{
using Characters::String;
switch (fRepType_) {
case eEmpty_:
return String{};
case eString_:
return String::FromASCII (fStringRep_);
case eNumeric_:
return String::FromASCII (UnParseTime_ (fNumericRepOrCache_));
}
AssertNotReached ();
return String{};
}
inline Characters::String Duration::Format (const PrettyPrintInfo& prettyPrintInfo) const
{
return PrettyPrint (prettyPrintInfo);
}
inline Characters::String Duration::ToString () const
{
return Format ();
}
inline int Duration::Compare (const Duration& rhs) const
{
Duration::InternalNumericFormatType_ n = As<Duration::InternalNumericFormatType_> () - rhs.As<Duration::InternalNumericFormatType_> ();
if (n < 0) {
return -1;
}
if (n > 0) {
return 1;
}
return 0;
}
/*
********************************************************************************
***************************** Duration operators *******************************
********************************************************************************
*/
inline bool operator< (const Duration& lhs, const Duration& rhs)
{
return lhs.Compare (rhs) < 0;
}
inline bool operator<= (const Duration& lhs, const Duration& rhs)
{
return lhs.Compare (rhs) <= 0;
}
inline bool operator== (const Duration& lhs, const Duration& rhs)
{
return lhs.Compare (rhs) == 0;
}
inline bool operator!= (const Duration& lhs, const Duration& rhs)
{
return lhs.Compare (rhs) != 0;
}
inline bool operator>= (const Duration& lhs, const Duration& rhs)
{
return lhs.Compare (rhs) >= 0;
}
inline bool operator> (const Duration& lhs, const Duration& rhs)
{
return lhs.Compare (rhs) > 0;
}
inline Duration operator/ (const Duration& lhs, long double rhs)
{
Require (rhs != 0);
return lhs * (1 / rhs);
}
inline Duration operator+ (const Duration& lhs, const Duration& rhs)
{
return Duration (lhs.As<Time::DurationSecondsType> () + rhs.As<DurationSecondsType> ());
}
inline Duration operator- (const Duration& lhs, const Duration& rhs)
{
return Duration (lhs.As<Time::DurationSecondsType> () - rhs.As<DurationSecondsType> ());
}
inline Duration operator* (const Duration& lhs, long double rhs)
{
return Duration (lhs.As<Time::DurationSecondsType> () * rhs);
}
inline Duration operator* (long double lhs, const Duration& rhs)
{
return Duration (rhs.As<Time::DurationSecondsType> () * lhs);
}
namespace Private_ {
struct Duration_ModuleData_ {
Duration_ModuleData_ ();
Duration fMin;
Duration fMax;
};
}
}
namespace {
Stroika::Foundation::Execution::ModuleInitializer<Stroika::Foundation::Time::Private_::Duration_ModuleData_> _Stroika_Foundation_Time_Duration_ModuleData_; // this object constructed for the CTOR/DTOR per-module side-effects
}
#endif /*_Stroika_Foundation_Time_Duration_inl_*/
<commit_msg>cosmetic/docs<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#ifndef _Stroika_Foundation_Time_Duration_inl_
#define _Stroika_Foundation_Time_Duration_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika::Foundation::Time {
/*
********************************************************************************
************************************ Duration **********************************
********************************************************************************
*/
template <typename DURATION_REP, typename DURATION_PERIOD>
constexpr Duration::Duration (const chrono::duration<DURATION_REP, DURATION_PERIOD>& d)
: fRepType_ (eNumeric_)
, fNonStringRep_{}
, fNumericRepOrCache_ (chrono::duration<InternalNumericFormatType_> (d).count ())
{
}
constexpr Duration::Duration ()
: fRepType_ (eEmpty_)
, fNonStringRep_{}
{
}
inline Duration::Duration (const Duration& src)
: fRepType_ (src.fRepType_)
, fNumericRepOrCache_ (src.fNumericRepOrCache_)
{
if (fRepType_ == eString_) {
Assert (not src.fStringRep_.empty ());
new (&fStringRep_) string (src.fStringRep_);
}
}
inline Duration::Duration (Duration&& src)
: fRepType_ (src.fRepType_)
, fNumericRepOrCache_ (src.fNumericRepOrCache_)
{
if (src.fRepType_ == eString_) {
Assert (fRepType_ == eString_);
new (&fStringRep_) string (move (src.fStringRep_));
}
src.fRepType_ = eEmpty_;
}
inline Duration::Duration (const string& durationStr)
: fNonStringRep_{}
{
Assert (fRepType_ == eEmpty_);
if (not durationStr.empty ()) {
fNumericRepOrCache_ = ParseTime_ (durationStr);
new (&fStringRep_) string (durationStr);
fRepType_ = eString_;
}
}
constexpr Duration::Duration (int duration)
: fRepType_ (eNumeric_)
, fNonStringRep_{}
, fNumericRepOrCache_ (duration)
{
}
constexpr Duration::Duration (long duration)
: fRepType_ (eNumeric_)
, fNonStringRep_{}
, fNumericRepOrCache_ (duration)
{
}
constexpr Duration::Duration (long long duration)
: fRepType_ (eNumeric_)
, fNonStringRep_{}
, fNumericRepOrCache_ (static_cast<InternalNumericFormatType_> (duration))
{
}
constexpr Duration::Duration (float duration)
: fRepType_ (eNumeric_)
, fNonStringRep_{}
, fNumericRepOrCache_ (duration)
{
//Require (not isnan (duration)); // inf is allowed
}
constexpr Duration::Duration (double duration)
: fRepType_ (eNumeric_)
, fNonStringRep_{}
, fNumericRepOrCache_ (duration)
{
//Require (not isnan (duration)); // inf is allowed
}
constexpr Duration::Duration (long double duration)
: fRepType_ (eNumeric_)
, fNonStringRep_{}
, fNumericRepOrCache_ (static_cast<InternalNumericFormatType_> (duration))
{
//Require (not isnan (duration)); // inf is allowed
}
inline string Duration::AsUTF8 () const
{
return As<Characters::String> ().AsUTF8 ();
}
inline Duration::~Duration ()
{
destroy_ ();
}
inline void Duration::clear ()
{
destroy_ ();
}
constexpr bool Duration::empty () const
{
// on construction with an empty string, this produces type eEmpty_
return fRepType_ == eEmpty_;
}
inline Duration& Duration::operator= (const Duration& rhs)
{
if (this != &rhs) {
if (fRepType_ == rhs.fRepType_) {
if (rhs.fRepType_ == eString_) {
// if both unions have string active - just assign
fStringRep_ = rhs.fStringRep_;
}
}
else {
// if reps different, destroy in case this is string type
destroy_ ();
if (rhs.fRepType_ == eString_) {
new (&fStringRep_) string (rhs.fStringRep_);
// fRepType_ = eString_; done at end of procedure
}
}
fNumericRepOrCache_ = rhs.fNumericRepOrCache_;
fRepType_ = rhs.fRepType_;
}
return *this;
}
inline Duration& Duration::operator= (Duration&& rhs)
{
if (this != &rhs) {
if (fRepType_ == rhs.fRepType_) {
// if both unions have string active - just move assign
if (rhs.fRepType_ == eString_) {
fStringRep_ = move (rhs.fStringRep_);
// setting our type, and STEALING type of rhs at bottom of procedure
}
}
else {
// if reps different, destroy in case this is string type
destroy_ ();
if (rhs.fRepType_ == eString_) {
new (&fStringRep_) string (move (rhs.fStringRep_));
}
}
fNumericRepOrCache_ = rhs.fNumericRepOrCache_;
fRepType_ = rhs.fRepType_;
rhs.fRepType_ = eEmpty_;
}
return *this;
}
inline void Duration::destroy_ ()
{
if (fRepType_ == eString_) {
fStringRep_.~basic_string ();
}
fRepType_ = eEmpty_;
}
template <>
inline int Duration::As () const
{
return static_cast<int> (fNumericRepOrCache_);
}
template <>
inline long int Duration::As () const
{
return static_cast<long int> (fNumericRepOrCache_);
}
template <>
inline long long int Duration::As () const
{
return static_cast<long long int> (fNumericRepOrCache_);
}
template <>
inline float Duration::As () const
{
return static_cast<float> (fNumericRepOrCache_);
}
template <>
inline double Duration::As () const
{
return fNumericRepOrCache_;
}
template <>
inline long double Duration::As () const
{
return fNumericRepOrCache_;
}
template <>
inline chrono::duration<double> Duration::As () const
{
return chrono::duration<double> (fNumericRepOrCache_);
}
template <>
inline chrono::seconds Duration::As () const
{
return chrono::seconds (static_cast<chrono::seconds::rep> (fNumericRepOrCache_));
}
template <>
inline chrono::milliseconds Duration::As () const
{
return chrono::milliseconds (static_cast<chrono::milliseconds::rep> (fNumericRepOrCache_ * 1000));
}
template <>
inline chrono::microseconds Duration::As () const
{
return chrono::microseconds (static_cast<chrono::microseconds::rep> (fNumericRepOrCache_ * 1000 * 1000));
}
template <>
inline chrono::nanoseconds Duration::As () const
{
return chrono::nanoseconds (static_cast<chrono::nanoseconds::rep> (fNumericRepOrCache_ * 1000.0 * 1000.0 * 1000.0));
}
template <>
inline Characters::String Duration::As () const
{
using Characters::String;
switch (fRepType_) {
case eEmpty_:
return String{};
case eString_:
return String::FromASCII (fStringRep_);
case eNumeric_:
return String::FromASCII (UnParseTime_ (fNumericRepOrCache_));
}
AssertNotReached ();
return String{};
}
inline Characters::String Duration::Format (const PrettyPrintInfo& prettyPrintInfo) const
{
return PrettyPrint (prettyPrintInfo);
}
inline Characters::String Duration::ToString () const
{
return Format ();
}
inline int Duration::Compare (const Duration& rhs) const
{
Duration::InternalNumericFormatType_ n = As<Duration::InternalNumericFormatType_> () - rhs.As<Duration::InternalNumericFormatType_> ();
if (n < 0) {
return -1;
}
if (n > 0) {
return 1;
}
return 0;
}
/*
********************************************************************************
***************************** Duration operators *******************************
********************************************************************************
*/
inline bool operator< (const Duration& lhs, const Duration& rhs)
{
return lhs.Compare (rhs) < 0;
}
inline bool operator<= (const Duration& lhs, const Duration& rhs)
{
return lhs.Compare (rhs) <= 0;
}
inline bool operator== (const Duration& lhs, const Duration& rhs)
{
return lhs.Compare (rhs) == 0;
}
inline bool operator!= (const Duration& lhs, const Duration& rhs)
{
return lhs.Compare (rhs) != 0;
}
inline bool operator>= (const Duration& lhs, const Duration& rhs)
{
return lhs.Compare (rhs) >= 0;
}
inline bool operator> (const Duration& lhs, const Duration& rhs)
{
return lhs.Compare (rhs) > 0;
}
inline Duration operator/ (const Duration& lhs, long double rhs)
{
Require (rhs != 0);
return lhs * (1 / rhs);
}
inline Duration operator+ (const Duration& lhs, const Duration& rhs)
{
return Duration (lhs.As<Time::DurationSecondsType> () + rhs.As<DurationSecondsType> ());
}
inline Duration operator- (const Duration& lhs, const Duration& rhs)
{
return Duration (lhs.As<Time::DurationSecondsType> () - rhs.As<DurationSecondsType> ());
}
inline Duration operator* (const Duration& lhs, long double rhs)
{
return Duration (lhs.As<Time::DurationSecondsType> () * rhs);
}
inline Duration operator* (long double lhs, const Duration& rhs)
{
return Duration (rhs.As<Time::DurationSecondsType> () * lhs);
}
namespace Private_ {
struct Duration_ModuleData_ {
Duration_ModuleData_ ();
Duration fMin;
Duration fMax;
};
}
}
namespace {
Stroika::Foundation::Execution::ModuleInitializer<Stroika::Foundation::Time::Private_::Duration_ModuleData_> _Stroika_Foundation_Time_Duration_ModuleData_; // this object constructed for the CTOR/DTOR per-module side-effects
}
#endif /*_Stroika_Foundation_Time_Duration_inl_*/
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $
Version: $Revision: 7837 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkClaronTrackingDevice.h"
#include "mitkClaronTool.h"
#include "mitkTestingMacros.h"
#include "mitkStandardFileLocations.h"
class mitkClaronTrackingDeviceTestClass
{
public:
static bool TestIsMicronTrackerInstalled()
{
mitk::ClaronTrackingDevice::Pointer myClaronTrackingDevice = mitk::ClaronTrackingDevice::New();
bool returnValue = myClaronTrackingDevice->IsMicronTrackerInstalled();
if (returnValue) {MITK_TEST_OUTPUT(<< "MicronTracker is installed on this system!")}
else {MITK_TEST_OUTPUT(<< "MicronTracker is not installed on this system!")}
return returnValue;
}
static void TestInstantiation()
{
// let's create an object of our class
mitk::ClaronTrackingDevice::Pointer testInstance;
testInstance = mitk::ClaronTrackingDevice::New();
MITK_TEST_CONDITION_REQUIRED(testInstance.IsNotNull(),"Testing instantiation:")
}
static void TestToolConfiguration()
{
std::string toolFileName = mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool", "Modules/IGT/Testing/Data/");
MITK_TEST_CONDITION(toolFileName.empty() == false, "Check if tool calibration file exists");
mitk::ClaronTrackingDevice::Pointer testInstance = mitk::ClaronTrackingDevice::New();
MITK_TEST_CONDITION(testInstance->AddTool("Tool1", toolFileName.c_str()) != NULL, "Testing AddTool() for tool 1");
MITK_TEST_CONDITION(testInstance->GetToolCount() == 1, "Testing adding tool 1");
MITK_TEST_CONDITION(testInstance->AddTool("Tool2", toolFileName.c_str()) != NULL, "Testing AddTool() for tool 2");
MITK_TEST_CONDITION(testInstance->GetToolCount() == 2, "Testing adding tool 2");
MITK_TEST_CONDITION(testInstance->AddTool("Tool3", toolFileName.c_str()) != NULL, "Testing AddTool() for tool 3");
MITK_TEST_CONDITION(testInstance->GetToolCount() == 3, "Testing adding tool 3");
//std::vector<mitk::ClaronTool::Pointer> myTools = testInstance->GetAllTools();
MITK_TEST_CONDITION(testInstance->GetTool(0)->GetToolName() == std::string("Tool1"), "Testing GetTool() for tool 1");
MITK_TEST_CONDITION(testInstance->GetTool(1)->GetToolName() == std::string("Tool2"), "Testing GetTool() for tool 2");
MITK_TEST_CONDITION(testInstance->GetTool(2)->GetToolName() == std::string("Tool3"), "Testing GetTool() for tool 3");
//Testing 100 tools (maximum by MicronTracker)
testInstance = NULL;
testInstance = mitk::ClaronTrackingDevice::New();
for (unsigned int i = 0; i < 100; i++)
testInstance->AddTool("Tool", toolFileName.c_str());
MITK_TEST_CONDITION(testInstance->GetToolCount() == 100, "Testing adding 100 tools");
bool failed = false;
unsigned int max = 100;
testInstance = mitk::ClaronTrackingDevice::New();
for (int i = 0; i < max; i++)
testInstance->AddTool("Tool", toolFileName.c_str());
if ((testInstance->GetToolCount() != max))
failed = true;
MITK_TEST_CONDITION(!failed, "Testing tool configuration (maximum of 100 tools):");
}
static void TestAllMethodsOnSystemsWithoutMicronTracker()
{
//In this case we won't receive valid data but defined invalid return values.
//initialize
mitk::ClaronTrackingDevice::Pointer myClaronTrackingDevice = mitk::ClaronTrackingDevice::New();
//OpenConnection
MITK_TEST_CONDITION( (!myClaronTrackingDevice->OpenConnection()), "Testing behavior of method OpenConnection() (Errors should occur because MicronTracker is not activated).\n");
std::string toolFileName = mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool", "Testing/Data/");
MITK_TEST_CONDITION(toolFileName.empty() == false, "Check if tool calibration file exists");
//add a few tools
myClaronTrackingDevice->AddTool("Tool1", toolFileName.c_str());
myClaronTrackingDevice->AddTool("Tool2", toolFileName.c_str());
myClaronTrackingDevice->AddTool("Tool3", toolFileName.c_str());
//test IsMicronTrackerInstalled
MITK_TEST_CONDITION(!myClaronTrackingDevice->IsMicronTrackerInstalled(),"Testing method IsMicronTrackerInstalled().\n")
//test getToolCount
int toolCount = myClaronTrackingDevice->GetToolCount();
MITK_TEST_CONDITION((toolCount==3), "Testing method GetToolCount().\n");
//test getTool
mitk::TrackingTool* myTool = myClaronTrackingDevice->GetTool(2);
MITK_TEST_CONDITION((std::string(myTool->GetToolName()) == "Tool3"), "Testing method GetTool().\n");
//StartTracking
MITK_TEST_CONDITION( (!myClaronTrackingDevice->StartTracking()), "Testing behavior of method StartTracking().\n");
//StopTracking
MITK_TEST_CONDITION( (myClaronTrackingDevice->StopTracking()), "Testing behavior of method StopTracking().\n");
//CloseConnection
MITK_TEST_CONDITION( (myClaronTrackingDevice->CloseConnection()), "Testing behavior of method CloseConnection().\n");
}
};
/**
* This function is testing the Class ClaronTrackingDevice. For most tests we would need the MicronTracker hardware, so only a few
* simple tests, which can run without the hardware are implemented yet (2009, January, 23rd). As soon as there is a working
* concept to test the tracking classes which are very close to the hardware on all systems more tests are needed here.
*/
int mitkClaronTrackingDeviceTest(int /* argc */, char* /*argv*/[])
{
MITK_TEST_BEGIN("ClaronTrackingDevice");
mitkClaronTrackingDeviceTestClass::TestInstantiation();
mitkClaronTrackingDeviceTestClass::TestToolConfiguration();
/* The following tests don't run under linux environments. This is or could be caused by the fact that the MicronTracker interface
* is developed under windows and not tested under linux yet (26.2.2009). So - in my opinion - the best approach is to first test
* the MicronTracker code under linux (and make the necessary changes of course) and in parallel write the linux tests or make this
* tests runnable under linux.
*/
#ifdef WIN32
if (mitkClaronTrackingDeviceTestClass::TestIsMicronTrackerInstalled())
{
MITK_TEST_OUTPUT(<< "... MicronTracker is installed on your System, so we don't run any further tests. (All tests run on systems without MicronTracker)");
}
else
{
MITK_TEST_OUTPUT(<< ".Test");
mitkClaronTrackingDeviceTestClass::TestAllMethodsOnSystemsWithoutMicronTracker();
}
#endif
MITK_TEST_END();
}<commit_msg>COMP: fix warning<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $
Version: $Revision: 7837 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkClaronTrackingDevice.h"
#include "mitkClaronTool.h"
#include "mitkTestingMacros.h"
#include "mitkStandardFileLocations.h"
class mitkClaronTrackingDeviceTestClass
{
public:
static bool TestIsMicronTrackerInstalled()
{
mitk::ClaronTrackingDevice::Pointer myClaronTrackingDevice = mitk::ClaronTrackingDevice::New();
bool returnValue = myClaronTrackingDevice->IsMicronTrackerInstalled();
if (returnValue) {MITK_TEST_OUTPUT(<< "MicronTracker is installed on this system!")}
else {MITK_TEST_OUTPUT(<< "MicronTracker is not installed on this system!")}
return returnValue;
}
static void TestInstantiation()
{
// let's create an object of our class
mitk::ClaronTrackingDevice::Pointer testInstance;
testInstance = mitk::ClaronTrackingDevice::New();
MITK_TEST_CONDITION_REQUIRED(testInstance.IsNotNull(),"Testing instantiation:")
}
static void TestToolConfiguration()
{
std::string toolFileName = mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool", "Modules/IGT/Testing/Data/");
MITK_TEST_CONDITION(toolFileName.empty() == false, "Check if tool calibration file exists");
mitk::ClaronTrackingDevice::Pointer testInstance = mitk::ClaronTrackingDevice::New();
MITK_TEST_CONDITION(testInstance->AddTool("Tool1", toolFileName.c_str()) != NULL, "Testing AddTool() for tool 1");
MITK_TEST_CONDITION(testInstance->GetToolCount() == 1, "Testing adding tool 1");
MITK_TEST_CONDITION(testInstance->AddTool("Tool2", toolFileName.c_str()) != NULL, "Testing AddTool() for tool 2");
MITK_TEST_CONDITION(testInstance->GetToolCount() == 2, "Testing adding tool 2");
MITK_TEST_CONDITION(testInstance->AddTool("Tool3", toolFileName.c_str()) != NULL, "Testing AddTool() for tool 3");
MITK_TEST_CONDITION(testInstance->GetToolCount() == 3, "Testing adding tool 3");
//std::vector<mitk::ClaronTool::Pointer> myTools = testInstance->GetAllTools();
MITK_TEST_CONDITION(testInstance->GetTool(0)->GetToolName() == std::string("Tool1"), "Testing GetTool() for tool 1");
MITK_TEST_CONDITION(testInstance->GetTool(1)->GetToolName() == std::string("Tool2"), "Testing GetTool() for tool 2");
MITK_TEST_CONDITION(testInstance->GetTool(2)->GetToolName() == std::string("Tool3"), "Testing GetTool() for tool 3");
//Testing 100 tools (maximum by MicronTracker)
testInstance = NULL;
testInstance = mitk::ClaronTrackingDevice::New();
for (unsigned int i = 0; i < 100; i++)
testInstance->AddTool("Tool", toolFileName.c_str());
MITK_TEST_CONDITION(testInstance->GetToolCount() == 100, "Testing adding 100 tools");
bool failed = false;
unsigned int max = 100;
testInstance = mitk::ClaronTrackingDevice::New();
for (unsigned int i = 0; i < max; i++)
testInstance->AddTool("Tool", toolFileName.c_str());
if ((testInstance->GetToolCount() != max))
failed = true;
MITK_TEST_CONDITION(!failed, "Testing tool configuration (maximum of 100 tools):");
}
static void TestAllMethodsOnSystemsWithoutMicronTracker()
{
//In this case we won't receive valid data but defined invalid return values.
//initialize
mitk::ClaronTrackingDevice::Pointer myClaronTrackingDevice = mitk::ClaronTrackingDevice::New();
//OpenConnection
MITK_TEST_CONDITION( (!myClaronTrackingDevice->OpenConnection()), "Testing behavior of method OpenConnection() (Errors should occur because MicronTracker is not activated).\n");
std::string toolFileName = mitk::StandardFileLocations::GetInstance()->FindFile("ClaronTool", "Testing/Data/");
MITK_TEST_CONDITION(toolFileName.empty() == false, "Check if tool calibration file exists");
//add a few tools
myClaronTrackingDevice->AddTool("Tool1", toolFileName.c_str());
myClaronTrackingDevice->AddTool("Tool2", toolFileName.c_str());
myClaronTrackingDevice->AddTool("Tool3", toolFileName.c_str());
//test IsMicronTrackerInstalled
MITK_TEST_CONDITION(!myClaronTrackingDevice->IsMicronTrackerInstalled(),"Testing method IsMicronTrackerInstalled().\n")
//test getToolCount
int toolCount = myClaronTrackingDevice->GetToolCount();
MITK_TEST_CONDITION((toolCount==3), "Testing method GetToolCount().\n");
//test getTool
mitk::TrackingTool* myTool = myClaronTrackingDevice->GetTool(2);
MITK_TEST_CONDITION((std::string(myTool->GetToolName()) == "Tool3"), "Testing method GetTool().\n");
//StartTracking
MITK_TEST_CONDITION( (!myClaronTrackingDevice->StartTracking()), "Testing behavior of method StartTracking().\n");
//StopTracking
MITK_TEST_CONDITION( (myClaronTrackingDevice->StopTracking()), "Testing behavior of method StopTracking().\n");
//CloseConnection
MITK_TEST_CONDITION( (myClaronTrackingDevice->CloseConnection()), "Testing behavior of method CloseConnection().\n");
}
};
/**
* This function is testing the Class ClaronTrackingDevice. For most tests we would need the MicronTracker hardware, so only a few
* simple tests, which can run without the hardware are implemented yet (2009, January, 23rd). As soon as there is a working
* concept to test the tracking classes which are very close to the hardware on all systems more tests are needed here.
*/
int mitkClaronTrackingDeviceTest(int /* argc */, char* /*argv*/[])
{
MITK_TEST_BEGIN("ClaronTrackingDevice");
mitkClaronTrackingDeviceTestClass::TestInstantiation();
mitkClaronTrackingDeviceTestClass::TestToolConfiguration();
/* The following tests don't run under linux environments. This is or could be caused by the fact that the MicronTracker interface
* is developed under windows and not tested under linux yet (26.2.2009). So - in my opinion - the best approach is to first test
* the MicronTracker code under linux (and make the necessary changes of course) and in parallel write the linux tests or make this
* tests runnable under linux.
*/
#ifdef WIN32
if (mitkClaronTrackingDeviceTestClass::TestIsMicronTrackerInstalled())
{
MITK_TEST_OUTPUT(<< "... MicronTracker is installed on your System, so we don't run any further tests. (All tests run on systems without MicronTracker)");
}
else
{
MITK_TEST_OUTPUT(<< ".Test");
mitkClaronTrackingDeviceTestClass::TestAllMethodsOnSystemsWithoutMicronTracker();
}
#endif
MITK_TEST_END();
}<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2009-05-13 14:52:01 +0200 (Mi, 13. Mai 2009) $
Version: $Revision: 17230 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkNavigationDataPlayer.h"
#include "mitkNavigationData.h"
#include "mitkTestingMacros.h"
#include "mitkStandardFileLocations.h"
#include "mitkTimeStamp.h"
#include <iostream>
#include <sstream>
class mitkNavigationDataPlayerTestClass
{
public:
static void TestInstantiation()
{
// let's create an object of our class
mitk::NavigationDataPlayer::Pointer player = mitk::NavigationDataPlayer::New();
// first test: did this work?
// using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since
// it makes no sense to continue without an object.
MITK_TEST_CONDITION_REQUIRED(player.IsNotNull(), "Testing instantiation");
}
static void TestSimpleDataPlay()
{
std::string tmp = "";
// let's create an object of our class
mitk::NavigationDataPlayer::Pointer player = mitk::NavigationDataPlayer::New();
std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("NavigationDataTestData.xml", "Modules/IGT/Testing/Data");
player->SetFileName( file );
MITK_TEST_CONDITION_REQUIRED( strcmp(player->GetFileName(), file.c_str()) == 0, "Testing SetFileName and GetFileName");
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
player->StartPlaying();
player->Update();
player->StopPlaying();
mitk::NavigationData::Pointer nd = player->GetOutput();
mitk::Point3D pnt;
pnt[0] = 1;
pnt[1] = 0;
pnt[2] = 3;
MITK_TEST_CONDITION_REQUIRED( nd->GetPosition() == pnt, "Testing position of replayed NavigaionData" );
player = mitk::NavigationDataPlayer::New();
player->SetFileName( file );
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
std::vector<double> times, refTimes;
refTimes.resize(5);
refTimes[0] = 3.9;
refTimes[1] = 83.6;
refTimes[2] = 174.4;
refTimes[3] = 275.0;
refTimes[4] = 385.39;
std::vector<mitk::Point3D> points, refPoints;
refPoints.resize(5);
refPoints[0][0] = 1; refPoints[0][1] = 0; refPoints[0][2] = 3;
refPoints[1][0] = 2; refPoints[1][1] = 1; refPoints[1][2] = 4;
refPoints[2][0] = 3; refPoints[2][1] = 2; refPoints[2][2] = 5;
refPoints[3][0] = 4; refPoints[3][1] = 3; refPoints[3][2] = 6;
refPoints[4][0] = 5; refPoints[4][1] = 4; refPoints[4][2] = 7;
mitk::TimeStamp::Pointer timer = mitk::TimeStamp::GetInstance();
timer->Initialize();
itk::Object::Pointer obj = itk::Object::New();
mitk::Point3D oldPos;
oldPos[0] = 1;
oldPos[1] = 0;
oldPos[2] = 3;
timer->Start( obj );
player->StartPlaying();
while( times.size()<5 )
{
player->Update();
pnt = player->GetOutput()->GetPosition();
if ( pnt != oldPos )
{
times.push_back( timer->GetElapsed(obj) );
points.push_back(oldPos);
oldPos = pnt;
}
}
player->StopPlaying();
// if this test fails, it may be because the dartclient runs on a virtual machine.
// Under these circumstances, it may be impossible to achieve a time-accuracy of 10ms
for ( int i=0;i<5;i++ )
{
if ((times[i]>refTimes[i]-150 && times[i]<refTimes[i]+150)) {MITK_TEST_OUTPUT(<< "ref: " << refTimes[i] << " / time elapsed: " << times[i]);}
MITK_TEST_CONDITION_REQUIRED( (times[i]>refTimes[i]-150 && times[i]<refTimes[i]+150), "checking for more or less correct time-line" );
MITK_TEST_CONDITION_REQUIRED(points[i] == refPoints[i], "checking if the point coordinates are correct")
}
}
static void TestPauseAndResume()
{
std::string tmp = "";
// let's create an object of our class
mitk::NavigationDataPlayer::Pointer player = mitk::NavigationDataPlayer::New();
std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("NavigationDataTestData.xml", "Modules/IGT/Testing/Data");
player->SetFileName( file );
MITK_TEST_CONDITION_REQUIRED( strcmp(player->GetFileName(), file.c_str()) == 0, "Testing SetFileName and GetFileName");
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
player->StartPlaying();
player->Update();
MITK_TEST_OUTPUT(<<"Test double call of Pause() method!");
player->Pause(); //test pause method
player->Pause(); //call again to see if this causes an error
MITK_TEST_OUTPUT(<<"Test double call of Resume() method!");
player->Resume(); //test resume method
player->Resume(); //call again to see if this causes an error
player->Update();
player->StopPlaying();
mitk::NavigationData::Pointer nd = player->GetOutput();
mitk::Point3D pnt;
pnt[0] = 1;
pnt[1] = 0;
pnt[2] = 3;
MITK_TEST_CONDITION_REQUIRED( nd->GetPosition() == pnt, "Testing position of replayed NavigaionData" );
player = mitk::NavigationDataPlayer::New();
player->SetFileName( file );
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
std::vector<double> times, refTimes;
refTimes.resize(5);
refTimes[0] = 3.9;
refTimes[1] = 83.6;
refTimes[2] = 174.4;
refTimes[3] = 275.0;
refTimes[4] = 385.39;
std::vector<mitk::Point3D> points, refPoints;
refPoints.resize(5);
refPoints[0][0] = 1; refPoints[0][1] = 0; refPoints[0][2] = 3;
refPoints[1][0] = 2; refPoints[1][1] = 1; refPoints[1][2] = 4;
refPoints[2][0] = 3; refPoints[2][1] = 2; refPoints[2][2] = 5;
refPoints[3][0] = 4; refPoints[3][1] = 3; refPoints[3][2] = 6;
refPoints[4][0] = 5; refPoints[4][1] = 4; refPoints[4][2] = 7;
mitk::TimeStamp::Pointer timer = mitk::TimeStamp::GetInstance();
timer->Initialize();
itk::Object::Pointer obj = itk::Object::New();
mitk::Point3D oldPos;
oldPos[0] = 1;
oldPos[1] = 0;
oldPos[2] = 3;
timer->Start( obj );
player->StartPlaying();
MITK_TEST_CONDITION_REQUIRED(!player->IsAtEnd(), "Testing method IsAtEnd() #0");
while( times.size()<3 )
{
player->Update();
pnt = player->GetOutput()->GetPosition();
if ( pnt != oldPos )
{
times.push_back( timer->GetElapsed(obj) );
points.push_back(oldPos);
oldPos = pnt;
}
}
MITK_TEST_OUTPUT(<<"Test pause method!");
player->Pause();
MITK_TEST_CONDITION_REQUIRED(!player->IsAtEnd(), "Testing method IsAtEnd() #1");
MITK_TEST_OUTPUT(<<"Test resume method!");
player->Resume();
while( times.size()<5 )
{
player->Update();
pnt = player->GetOutput()->GetPosition();
if ( pnt != oldPos )
{
times.push_back( timer->GetElapsed(obj) );
points.push_back(oldPos);
oldPos = pnt;
}
}
player->StopPlaying();
// if this test fails, it may be because the dartclient runs on a virtual machine.
// Under these circumstances, it may be impossible to achieve a time-accuracy of 10ms
for ( int i=0;i<5;i++ )
{
if ((times[i]>refTimes[i]-150 && times[i]<refTimes[i]+150)) {MITK_TEST_OUTPUT(<< "ref: " << refTimes[i] << " / time elapsed: " << times[i]);}
MITK_TEST_CONDITION_REQUIRED( (times[i]>refTimes[i]-150 && times[i]<refTimes[i]+150), "checking for more or less correct time-line" );
MITK_TEST_CONDITION_REQUIRED(points[i] == refPoints[i], "checking if the point coordinates are correct")
}
MITK_TEST_CONDITION_REQUIRED(player->IsAtEnd(), "Testing method IsAtEnd() #2");
}
static void TestInvalidStream()
{
MITK_TEST_OUTPUT(<<"#### Testing invalid input data: errors are expected. ####");
//declarate test variables
mitk::NavigationDataPlayer::Pointer player;
std::string file;
//case 0: stream not set
player = mitk::NavigationDataPlayer::New();
player->SetStream( mitk::NavigationDataPlayer::ZipFile );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#0: Tested stream not set. Application should not crash.");
//case 1: non-existing file
player = mitk::NavigationDataPlayer::New();
player->SetFileName( "ffdsd" );
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#1: Tested non-existing file. Application should not crash.");
//case 2: wrong file format
player = mitk::NavigationDataPlayer::New();
file = mitk::StandardFileLocations::GetInstance()->FindFile("SROMFile.rom", "Modules/IGT/Testing/Data");
player->SetFileName( file );
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#2: Tested wrong file format. Application should not crash.");
//case 3: wrong file version
player = mitk::NavigationDataPlayer::New();
file = mitk::StandardFileLocations::GetInstance()->FindFile("InvalidVersionNavigationDataTestData.xml", "Modules/IGT/Testing/Data");
player->SetFileName( file );
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#3: Tested wrong file version. Application should not crash.");
//case 4: wrong file
player = mitk::NavigationDataPlayer::New();
player->SetFileName( "cs:\fsd/$%ffdsd" );
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#4: Tested wrong file. Application should not crash.");
//case 5: null stream
player = mitk::NavigationDataPlayer::New();
player->SetStream( NULL );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#5: Tested null stream. Application should not crash.");
//case 6: empty stream
player = mitk::NavigationDataPlayer::New();
player->SetStream( new std::ifstream("") );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#6: Tested empty stream. Application should not crash.");
//case 7: wrong stream
player = mitk::NavigationDataPlayer::New();
file = mitk::StandardFileLocations::GetInstance()->FindFile("SROMFile.rom", "Modules/IGT/Testing/Data");
player->SetStream( new std::ifstream(file.c_str()) );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#7: Tested wrong stream. Application should not crash.");
//case 8: invalid
player = mitk::NavigationDataPlayer::New();
file = mitk::StandardFileLocations::GetInstance()->FindFile("InvalidDataNavigationDataTestData.xml", "Modules/IGT/Testing/Data");
player->SetFileName( file );
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#8: Tested invalid file version. Application should not crash.");
}
};
/**Documentation
* test for the class "NavigationDataPlayer".
*/
int mitkNavigationDataPlayerTest(int /* argc */, char* /*argv*/[])
{
MITK_TEST_BEGIN("NavigationDataPlayer");
std::string tmp = "";
mitkNavigationDataPlayerTestClass::TestInstantiation();
mitkNavigationDataPlayerTestClass::TestSimpleDataPlay();
mitkNavigationDataPlayerTestClass::TestPauseAndResume();
mitkNavigationDataPlayerTestClass::TestInvalidStream();
// always end with this!
MITK_TEST_END();
}
<commit_msg>COMP: fixed instantiation of ifstream<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2009-05-13 14:52:01 +0200 (Mi, 13. Mai 2009) $
Version: $Revision: 17230 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html 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 "mitkNavigationDataPlayer.h"
#include "mitkNavigationData.h"
#include "mitkTestingMacros.h"
#include "mitkStandardFileLocations.h"
#include "mitkTimeStamp.h"
#include <iostream>
#include <sstream>
class mitkNavigationDataPlayerTestClass
{
public:
static void TestInstantiation()
{
// let's create an object of our class
mitk::NavigationDataPlayer::Pointer player = mitk::NavigationDataPlayer::New();
// first test: did this work?
// using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since
// it makes no sense to continue without an object.
MITK_TEST_CONDITION_REQUIRED(player.IsNotNull(), "Testing instantiation");
}
static void TestSimpleDataPlay()
{
std::string tmp = "";
// let's create an object of our class
mitk::NavigationDataPlayer::Pointer player = mitk::NavigationDataPlayer::New();
std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("NavigationDataTestData.xml", "Modules/IGT/Testing/Data");
player->SetFileName( file );
MITK_TEST_CONDITION_REQUIRED( strcmp(player->GetFileName(), file.c_str()) == 0, "Testing SetFileName and GetFileName");
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
player->StartPlaying();
player->Update();
player->StopPlaying();
mitk::NavigationData::Pointer nd = player->GetOutput();
mitk::Point3D pnt;
pnt[0] = 1;
pnt[1] = 0;
pnt[2] = 3;
MITK_TEST_CONDITION_REQUIRED( nd->GetPosition() == pnt, "Testing position of replayed NavigaionData" );
player = mitk::NavigationDataPlayer::New();
player->SetFileName( file );
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
std::vector<double> times, refTimes;
refTimes.resize(5);
refTimes[0] = 3.9;
refTimes[1] = 83.6;
refTimes[2] = 174.4;
refTimes[3] = 275.0;
refTimes[4] = 385.39;
std::vector<mitk::Point3D> points, refPoints;
refPoints.resize(5);
refPoints[0][0] = 1; refPoints[0][1] = 0; refPoints[0][2] = 3;
refPoints[1][0] = 2; refPoints[1][1] = 1; refPoints[1][2] = 4;
refPoints[2][0] = 3; refPoints[2][1] = 2; refPoints[2][2] = 5;
refPoints[3][0] = 4; refPoints[3][1] = 3; refPoints[3][2] = 6;
refPoints[4][0] = 5; refPoints[4][1] = 4; refPoints[4][2] = 7;
mitk::TimeStamp::Pointer timer = mitk::TimeStamp::GetInstance();
timer->Initialize();
itk::Object::Pointer obj = itk::Object::New();
mitk::Point3D oldPos;
oldPos[0] = 1;
oldPos[1] = 0;
oldPos[2] = 3;
timer->Start( obj );
player->StartPlaying();
while( times.size()<5 )
{
player->Update();
pnt = player->GetOutput()->GetPosition();
if ( pnt != oldPos )
{
times.push_back( timer->GetElapsed(obj) );
points.push_back(oldPos);
oldPos = pnt;
}
}
player->StopPlaying();
// if this test fails, it may be because the dartclient runs on a virtual machine.
// Under these circumstances, it may be impossible to achieve a time-accuracy of 10ms
for ( int i=0;i<5;i++ )
{
if ((times[i]>refTimes[i]-150 && times[i]<refTimes[i]+150)) {MITK_TEST_OUTPUT(<< "ref: " << refTimes[i] << " / time elapsed: " << times[i]);}
MITK_TEST_CONDITION_REQUIRED( (times[i]>refTimes[i]-150 && times[i]<refTimes[i]+150), "checking for more or less correct time-line" );
MITK_TEST_CONDITION_REQUIRED(points[i] == refPoints[i], "checking if the point coordinates are correct")
}
}
static void TestPauseAndResume()
{
std::string tmp = "";
// let's create an object of our class
mitk::NavigationDataPlayer::Pointer player = mitk::NavigationDataPlayer::New();
std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("NavigationDataTestData.xml", "Modules/IGT/Testing/Data");
player->SetFileName( file );
MITK_TEST_CONDITION_REQUIRED( strcmp(player->GetFileName(), file.c_str()) == 0, "Testing SetFileName and GetFileName");
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
player->StartPlaying();
player->Update();
MITK_TEST_OUTPUT(<<"Test double call of Pause() method!");
player->Pause(); //test pause method
player->Pause(); //call again to see if this causes an error
MITK_TEST_OUTPUT(<<"Test double call of Resume() method!");
player->Resume(); //test resume method
player->Resume(); //call again to see if this causes an error
player->Update();
player->StopPlaying();
mitk::NavigationData::Pointer nd = player->GetOutput();
mitk::Point3D pnt;
pnt[0] = 1;
pnt[1] = 0;
pnt[2] = 3;
MITK_TEST_CONDITION_REQUIRED( nd->GetPosition() == pnt, "Testing position of replayed NavigaionData" );
player = mitk::NavigationDataPlayer::New();
player->SetFileName( file );
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
std::vector<double> times, refTimes;
refTimes.resize(5);
refTimes[0] = 3.9;
refTimes[1] = 83.6;
refTimes[2] = 174.4;
refTimes[3] = 275.0;
refTimes[4] = 385.39;
std::vector<mitk::Point3D> points, refPoints;
refPoints.resize(5);
refPoints[0][0] = 1; refPoints[0][1] = 0; refPoints[0][2] = 3;
refPoints[1][0] = 2; refPoints[1][1] = 1; refPoints[1][2] = 4;
refPoints[2][0] = 3; refPoints[2][1] = 2; refPoints[2][2] = 5;
refPoints[3][0] = 4; refPoints[3][1] = 3; refPoints[3][2] = 6;
refPoints[4][0] = 5; refPoints[4][1] = 4; refPoints[4][2] = 7;
mitk::TimeStamp::Pointer timer = mitk::TimeStamp::GetInstance();
timer->Initialize();
itk::Object::Pointer obj = itk::Object::New();
mitk::Point3D oldPos;
oldPos[0] = 1;
oldPos[1] = 0;
oldPos[2] = 3;
timer->Start( obj );
player->StartPlaying();
MITK_TEST_CONDITION_REQUIRED(!player->IsAtEnd(), "Testing method IsAtEnd() #0");
while( times.size()<3 )
{
player->Update();
pnt = player->GetOutput()->GetPosition();
if ( pnt != oldPos )
{
times.push_back( timer->GetElapsed(obj) );
points.push_back(oldPos);
oldPos = pnt;
}
}
MITK_TEST_OUTPUT(<<"Test pause method!");
player->Pause();
MITK_TEST_CONDITION_REQUIRED(!player->IsAtEnd(), "Testing method IsAtEnd() #1");
MITK_TEST_OUTPUT(<<"Test resume method!");
player->Resume();
while( times.size()<5 )
{
player->Update();
pnt = player->GetOutput()->GetPosition();
if ( pnt != oldPos )
{
times.push_back( timer->GetElapsed(obj) );
points.push_back(oldPos);
oldPos = pnt;
}
}
player->StopPlaying();
// if this test fails, it may be because the dartclient runs on a virtual machine.
// Under these circumstances, it may be impossible to achieve a time-accuracy of 10ms
for ( int i=0;i<5;i++ )
{
if ((times[i]>refTimes[i]-150 && times[i]<refTimes[i]+150)) {MITK_TEST_OUTPUT(<< "ref: " << refTimes[i] << " / time elapsed: " << times[i]);}
MITK_TEST_CONDITION_REQUIRED( (times[i]>refTimes[i]-150 && times[i]<refTimes[i]+150), "checking for more or less correct time-line" );
MITK_TEST_CONDITION_REQUIRED(points[i] == refPoints[i], "checking if the point coordinates are correct")
}
MITK_TEST_CONDITION_REQUIRED(player->IsAtEnd(), "Testing method IsAtEnd() #2");
}
static void TestInvalidStream()
{
MITK_TEST_OUTPUT(<<"#### Testing invalid input data: errors are expected. ####");
//declarate test variables
mitk::NavigationDataPlayer::Pointer player;
std::string file;
//case 0: stream not set
player = mitk::NavigationDataPlayer::New();
player->SetStream( mitk::NavigationDataPlayer::ZipFile );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#0: Tested stream not set. Application should not crash.");
//case 1: non-existing file
player = mitk::NavigationDataPlayer::New();
player->SetFileName( "ffdsd" );
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#1: Tested non-existing file. Application should not crash.");
//case 2: wrong file format
player = mitk::NavigationDataPlayer::New();
file = mitk::StandardFileLocations::GetInstance()->FindFile("SROMFile.rom", "Modules/IGT/Testing/Data");
player->SetFileName( file );
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#2: Tested wrong file format. Application should not crash.");
//case 3: wrong file version
player = mitk::NavigationDataPlayer::New();
file = mitk::StandardFileLocations::GetInstance()->FindFile("InvalidVersionNavigationDataTestData.xml", "Modules/IGT/Testing/Data");
player->SetFileName( file );
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#3: Tested wrong file version. Application should not crash.");
//case 4: wrong file
player = mitk::NavigationDataPlayer::New();
player->SetFileName( "cs:\fsd/$%ffdsd" );
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#4: Tested wrong file. Application should not crash.");
//case 5: null stream
player = mitk::NavigationDataPlayer::New();
player->SetStream( NULL );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#5: Tested null stream. Application should not crash.");
//case 6: empty stream
player = mitk::NavigationDataPlayer::New();
std::ifstream myEmptyStream = std::ifstream("");
player->SetStream( &myEmptyStream );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#6: Tested empty stream. Application should not crash.");
//case 7: wrong stream
player = mitk::NavigationDataPlayer::New();
file = mitk::StandardFileLocations::GetInstance()->FindFile("SROMFile.rom", "Modules/IGT/Testing/Data");
std::ifstream myWrongStream = std::ifstream(file.c_str());
player->SetStream( &myWrongStream );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#7: Tested wrong stream. Application should not crash.");
//case 8: invalid
player = mitk::NavigationDataPlayer::New();
file = mitk::StandardFileLocations::GetInstance()->FindFile("InvalidDataNavigationDataTestData.xml", "Modules/IGT/Testing/Data");
player->SetFileName( file );
player->SetStream( mitk::NavigationDataPlayer::NormalFile );
player->StartPlaying();
player->Update();
player->StopPlaying();
MITK_TEST_OUTPUT(<<"#8: Tested invalid file version. Application should not crash.");
}
};
/**Documentation
* test for the class "NavigationDataPlayer".
*/
int mitkNavigationDataPlayerTest(int /* argc */, char* /*argv*/[])
{
MITK_TEST_BEGIN("NavigationDataPlayer");
std::string tmp = "";
mitkNavigationDataPlayerTestClass::TestInstantiation();
mitkNavigationDataPlayerTestClass::TestSimpleDataPlay();
mitkNavigationDataPlayerTestClass::TestPauseAndResume();
mitkNavigationDataPlayerTestClass::TestInvalidStream();
// always end with this!
MITK_TEST_END();
}<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the
//
// Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor,
// Boston, MA
// 02110-1301
// USA
//
////////////////////////////////////////////////////////////////////////////////
#include <sstream>
#include <ViewText.h>
#include <Context.h>
#include <Color.h>
#include <text.h>
#include <i18n.h>
#include <CmdColor.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
CmdColor::CmdColor ()
{
_keyword = "colors";
_usage = "task colors [sample | legend]";
_description = "Displays all possible colors, a named sample, or a legend "
"containing all currently defined colors.";
_read_only = true;
_displays_id = false;
}
////////////////////////////////////////////////////////////////////////////////
int CmdColor::execute (std::string& output)
{
int rc = 0;
// Get the non-attribute, non-fancy command line arguments.
bool legend = false;
Arguments words = context.args.extract_simple_words ();
std::vector <Triple>::iterator word;
for (word = words.begin (); word != words.end (); ++word)
if (closeEnough ("legend", word->_first))
legend = true;
std::stringstream out;
if (context.color ())
{
// If the description contains 'legend', show all the colors currently in
// use.
if (legend)
{
out << "\nHere are the colors currently in use:\n";
std::vector <std::string> all;
context.config.all (all);
ViewText view;
view.width (context.getWidth ());
view.add (Column::factory ("string", "Color"));
view.add (Column::factory ("string", "Definition"));
std::vector <std::string>::iterator item;
for (item = all.begin (); item != all.end (); ++item)
{
// Skip items with 'color' in their name, that are not referring to
// actual colors.
if (*item != "_forcecolor" &&
*item != "color" &&
item->find ("color") == 0)
{
Color color (context.config.get (*item));
int row = view.addRow ();
view.set (row, 0, *item, color);
view.set (row, 1, context.config.get (*item), color);
}
}
out << view.render ()
<< "\n";
}
// If there is something in the description, then assume that is a color,
// and display it as a sample.
else if (words.size ())
{
Color one ("black on bright yellow");
Color two ("underline cyan on bright blue");
Color three ("color214 on color202");
Color four ("rgb150 on rgb020");
Color five ("underline grey10 on grey3");
Color six ("red on color173");
std::string swatch;
for (word = words.begin (); word != words.end (); ++word)
{
if (word != words.begin ())
swatch += " ";
swatch += word->_first;
}
Color sample (swatch);
out << "\n"
<< "Use this command to see how colors are displayed by your terminal.\n\n"
<< "\n"
<< "16-color usage (supports underline, bold text, bright background):\n"
<< " " << one.colorize ("task color black on bright yellow") << "\n"
<< " " << two.colorize ("task color underline cyan on bright blue") << "\n"
<< "\n"
<< "256-color usage (supports underline):\n"
<< " " << three.colorize ("task color color214 on color202") << "\n"
<< " " << four.colorize ("task color rgb150 on rgb020") << "\n"
<< " " << five.colorize ("task color underline grey10 on grey3") << "\n"
<< " " << six.colorize ("task color red on color173") << "\n"
<< "\n"
<< "Your sample:" << "\n"
<< " " << sample.colorize ("task color " + swatch) << "\n\n";
}
// Show all supported colors. Possibly show some unsupported ones too.
else
{
out << "\n"
<< "Basic colors"
<< "\n"
<< " " << Color::colorize (" black ", "black")
<< " " << Color::colorize (" red ", "red")
<< " " << Color::colorize (" blue ", "blue")
<< " " << Color::colorize (" green ", "green")
<< " " << Color::colorize (" magenta ", "magenta")
<< " " << Color::colorize (" cyan ", "cyan")
<< " " << Color::colorize (" yellow ", "yellow")
<< " " << Color::colorize (" white ", "white")
<< "\n"
<< " " << Color::colorize (" black ", "white on black")
<< " " << Color::colorize (" red ", "white on red")
<< " " << Color::colorize (" blue ", "white on blue")
<< " " << Color::colorize (" green ", "black on green")
<< " " << Color::colorize (" magenta ", "black on magenta")
<< " " << Color::colorize (" cyan ", "black on cyan")
<< " " << Color::colorize (" yellow ", "black on yellow")
<< " " << Color::colorize (" white ", "black on white")
<< "\n\n";
out << "Effects"
<< "\n"
<< " " << Color::colorize (" red ", "red")
<< " " << Color::colorize (" bold red ", "bold red")
<< " " << Color::colorize (" underline on blue ", "underline on blue")
<< " " << Color::colorize (" on green ", "black on green")
<< " " << Color::colorize (" on bright green ", "black on bright green")
<< " " << Color::colorize (" inverse ", "inverse")
<< "\n\n";
// 16 system colors.
out << "color0 - color15"
<< "\n"
<< " 0 1 2 . . .\n";
for (int r = 0; r < 2; ++r)
{
out << " ";
for (int c = 0; c < 8; ++c)
{
std::stringstream s;
s << "on color" << (r*8 + c);
out << Color::colorize (" ", s.str ());
}
out << "\n";
}
out << " . . . 15\n\n";
// Color cube.
out << "Color cube rgb"
<< Color::colorize ("0", "bold red")
<< Color::colorize ("0", "bold green")
<< Color::colorize ("0", "bold blue")
<< " - rgb"
<< Color::colorize ("5", "bold red")
<< Color::colorize ("5", "bold green")
<< Color::colorize ("5", "bold blue")
<< " (also color16 - color231)"
<< "\n"
<< " " << Color::colorize ("0 "
"1 "
"2 "
"3 "
"4 "
"5", "bold red")
<< "\n"
<< " " << Color::colorize ("0 1 2 3 4 5 "
"0 1 2 3 4 5 "
"0 1 2 3 4 5 "
"0 1 2 3 4 5 "
"0 1 2 3 4 5 "
"0 1 2 3 4 5", "bold blue")
<< "\n";
char label [12];
for (int g = 0; g < 6; ++g)
{
sprintf (label, " %d", g);
out << Color::colorize (label, "bold green");
for (int r = 0; r < 6; ++r)
{
for (int b = 0; b < 6; ++b)
{
std::stringstream s;
s << "on rgb" << r << g << b;
out << Color::colorize (" ", s.str ());
}
out << " ";
}
out << "\n";
}
out << "\n";
// Grey ramp.
out << "Gray ramp gray0 - gray23 (also color232 - color255)\n"
<< " 0 1 2 . . . . . . 23\n"
<< " ";
for (int g = 0; g < 24; ++g)
{
std::stringstream s;
s << "on gray" << g;
out << Color::colorize (" ", s.str ());
}
out << "\n\nTry running 'task color white on red'.\n\n";
}
}
else
{
out << "Color is currently turned off in your .taskrc file. To enable "
"color, remove the line 'color=off', or change the 'off' to 'on'.\n";
rc = 1;
}
output = out.str ();
return rc;
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Arguments<commit_after>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the
//
// Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor,
// Boston, MA
// 02110-1301
// USA
//
////////////////////////////////////////////////////////////////////////////////
#include <sstream>
#include <ViewText.h>
#include <Context.h>
#include <Color.h>
#include <text.h>
#include <i18n.h>
#include <CmdColor.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
CmdColor::CmdColor ()
{
_keyword = "colors";
_usage = "task colors [sample | legend]";
_description = "Displays all possible colors, a named sample, or a legend "
"containing all currently defined colors.";
_read_only = true;
_displays_id = false;
}
////////////////////////////////////////////////////////////////////////////////
int CmdColor::execute (std::string& output)
{
int rc = 0;
// Get the non-attribute, non-fancy command line arguments.
bool legend = false;
std::vector <std::string> words = context.a3.extract_words ();
std::vector <std::string>::iterator word;
for (word = words.begin (); word != words.end (); ++word)
if (closeEnough ("legend", *word))
legend = true;
std::stringstream out;
if (context.color ())
{
// If the description contains 'legend', show all the colors currently in
// use.
if (legend)
{
out << "\nHere are the colors currently in use:\n";
std::vector <std::string> all;
context.config.all (all);
ViewText view;
view.width (context.getWidth ());
view.add (Column::factory ("string", "Color"));
view.add (Column::factory ("string", "Definition"));
std::vector <std::string>::iterator item;
for (item = all.begin (); item != all.end (); ++item)
{
// Skip items with 'color' in their name, that are not referring to
// actual colors.
if (*item != "_forcecolor" &&
*item != "color" &&
item->find ("color") == 0)
{
Color color (context.config.get (*item));
int row = view.addRow ();
view.set (row, 0, *item, color);
view.set (row, 1, context.config.get (*item), color);
}
}
out << view.render ()
<< "\n";
}
// If there is something in the description, then assume that is a color,
// and display it as a sample.
else if (words.size ())
{
Color one ("black on bright yellow");
Color two ("underline cyan on bright blue");
Color three ("color214 on color202");
Color four ("rgb150 on rgb020");
Color five ("underline grey10 on grey3");
Color six ("red on color173");
std::string swatch;
for (word = words.begin (); word != words.end (); ++word)
{
if (word != words.begin ())
swatch += " ";
swatch += *word;
}
Color sample (swatch);
out << "\n"
<< "Use this command to see how colors are displayed by your terminal.\n\n"
<< "\n"
<< "16-color usage (supports underline, bold text, bright background):\n"
<< " " << one.colorize ("task color black on bright yellow") << "\n"
<< " " << two.colorize ("task color underline cyan on bright blue") << "\n"
<< "\n"
<< "256-color usage (supports underline):\n"
<< " " << three.colorize ("task color color214 on color202") << "\n"
<< " " << four.colorize ("task color rgb150 on rgb020") << "\n"
<< " " << five.colorize ("task color underline grey10 on grey3") << "\n"
<< " " << six.colorize ("task color red on color173") << "\n"
<< "\n"
<< "Your sample:" << "\n"
<< " " << sample.colorize ("task color " + swatch) << "\n\n";
}
// Show all supported colors. Possibly show some unsupported ones too.
else
{
out << "\n"
<< "Basic colors"
<< "\n"
<< " " << Color::colorize (" black ", "black")
<< " " << Color::colorize (" red ", "red")
<< " " << Color::colorize (" blue ", "blue")
<< " " << Color::colorize (" green ", "green")
<< " " << Color::colorize (" magenta ", "magenta")
<< " " << Color::colorize (" cyan ", "cyan")
<< " " << Color::colorize (" yellow ", "yellow")
<< " " << Color::colorize (" white ", "white")
<< "\n"
<< " " << Color::colorize (" black ", "white on black")
<< " " << Color::colorize (" red ", "white on red")
<< " " << Color::colorize (" blue ", "white on blue")
<< " " << Color::colorize (" green ", "black on green")
<< " " << Color::colorize (" magenta ", "black on magenta")
<< " " << Color::colorize (" cyan ", "black on cyan")
<< " " << Color::colorize (" yellow ", "black on yellow")
<< " " << Color::colorize (" white ", "black on white")
<< "\n\n";
out << "Effects"
<< "\n"
<< " " << Color::colorize (" red ", "red")
<< " " << Color::colorize (" bold red ", "bold red")
<< " " << Color::colorize (" underline on blue ", "underline on blue")
<< " " << Color::colorize (" on green ", "black on green")
<< " " << Color::colorize (" on bright green ", "black on bright green")
<< " " << Color::colorize (" inverse ", "inverse")
<< "\n\n";
// 16 system colors.
out << "color0 - color15"
<< "\n"
<< " 0 1 2 . . .\n";
for (int r = 0; r < 2; ++r)
{
out << " ";
for (int c = 0; c < 8; ++c)
{
std::stringstream s;
s << "on color" << (r*8 + c);
out << Color::colorize (" ", s.str ());
}
out << "\n";
}
out << " . . . 15\n\n";
// Color cube.
out << "Color cube rgb"
<< Color::colorize ("0", "bold red")
<< Color::colorize ("0", "bold green")
<< Color::colorize ("0", "bold blue")
<< " - rgb"
<< Color::colorize ("5", "bold red")
<< Color::colorize ("5", "bold green")
<< Color::colorize ("5", "bold blue")
<< " (also color16 - color231)"
<< "\n"
<< " " << Color::colorize ("0 "
"1 "
"2 "
"3 "
"4 "
"5", "bold red")
<< "\n"
<< " " << Color::colorize ("0 1 2 3 4 5 "
"0 1 2 3 4 5 "
"0 1 2 3 4 5 "
"0 1 2 3 4 5 "
"0 1 2 3 4 5 "
"0 1 2 3 4 5", "bold blue")
<< "\n";
char label [12];
for (int g = 0; g < 6; ++g)
{
sprintf (label, " %d", g);
out << Color::colorize (label, "bold green");
for (int r = 0; r < 6; ++r)
{
for (int b = 0; b < 6; ++b)
{
std::stringstream s;
s << "on rgb" << r << g << b;
out << Color::colorize (" ", s.str ());
}
out << " ";
}
out << "\n";
}
out << "\n";
// Grey ramp.
out << "Gray ramp gray0 - gray23 (also color232 - color255)\n"
<< " 0 1 2 . . . . . . 23\n"
<< " ";
for (int g = 0; g < 24; ++g)
{
std::stringstream s;
s << "on gray" << g;
out << Color::colorize (" ", s.str ());
}
out << "\n\nTry running 'task color white on red'.\n\n";
}
}
else
{
out << "Color is currently turned off in your .taskrc file. To enable "
"color, remove the line 'color=off', or change the 'off' to 'on'.\n";
rc = 1;
}
output = out.str ();
return rc;
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>//
// file : fnv1a.hpp
// in : file:///home/tim/projects/ntools/hash/fnv1a.hpp
//
// created by : Timothée Feuillet
// date: Mon May 22 2017 16:30:57 GMT-0400 (EDT)
//
//
// Copyright (c) 2017 Timothée Feuillet
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#ifndef __N_1298911746129055067_381318754_FNV1A_HPP__
#define __N_1298911746129055067_381318754_FNV1A_HPP__
#include <cstdint>
#include <cstddef>
#include "../ct_list.hpp"
#include "../embed.hpp"
namespace neam
{
namespace ct
{
namespace hash
{
namespace internal
{
using fnv_return_types = type_list<uint32_t, uint64_t>;
template<typename T> static constexpr T fnv_offset_basis = T();
template<> constexpr uint64_t fnv_offset_basis<uint64_t> = 0xcbf29ce484222325ul;
template<> constexpr uint32_t fnv_offset_basis<uint32_t> = 0x811c9dc5u;
template<typename T> static constexpr T fnv_prime = T();
template<> constexpr uint64_t fnv_prime<uint64_t> = 0x100000001b3ul;
template<> constexpr uint32_t fnv_prime<uint32_t> = 0x01000193u;
} // namespace internal
template<size_t BitCount, typename T>
static constexpr auto fnv1a(const T *const data, size_t len) -> auto
{
static_assert(BitCount == 32 || BitCount == 64, "We only support 32 and 64bit FNV-1a hash function");
constexpr size_t index = BitCount / 32 - 1;
using type = list::get_type<internal::fnv_return_types, index>;
static_assert(sizeof(T) == 1, "Input type must be 8bit");
static_assert(internal::fnv_offset_basis<type> != 0, "Invalid offset basis (are you using a supported type ?)");
static_assert(internal::fnv_prime<type> != 0, "Invalid prime (are you using a supported type ?)");
type hash = internal::fnv_offset_basis<type>;
for (size_t i = 0; i < len; ++i)
hash = ((uint8_t)(data)[i] ^ hash) * internal::fnv_prime<type>;
return hash;
}
template<size_t BitCount, size_t StrLen>
static constexpr auto fnv1a(const char (&str)[StrLen]) -> auto
{
static_assert(BitCount == 32 || BitCount == 64, "We only support 32 and 64bit FNV-1a hash function");
constexpr size_t index = BitCount / 32 - 1;
using type = list::get_type<internal::fnv_return_types, index>;
static_assert(internal::fnv_offset_basis<type> != 0, "Invalid offset basis (are you using a supported type ?)");
static_assert(internal::fnv_prime<type> != 0, "Invalid prime (are you using a supported type ?)");
type hash = internal::fnv_offset_basis<type>;
// StrLen - 1 is to skip the ending \0
for (size_t i = 0; i < StrLen - 1; ++i)
hash = ((uint8_t)(str[i]) ^ hash) * internal::fnv_prime<type>;
return hash;
}
template<size_t BitCount, typename T>
static constexpr auto fnv1a_continue(list::get_type<internal::fnv_return_types, BitCount / 32 - 1> initial,
const T* const data, size_t len) -> auto
{
static_assert(BitCount == 32 || BitCount == 64, "We only support 32 and 64bit FNV-1a hash function");
using type = list::get_type<internal::fnv_return_types, BitCount / 32 - 1>;
static_assert(sizeof(T) == 1, "Input type must be 8bit");
static_assert(internal::fnv_prime<type> != 0, "Invalid prime (are you using a supported type ?)");
type hash = initial;
// StrLen - 1 is to skip the ending \0
for (size_t i = 0; i < len - 1; ++i)
hash = ((uint8_t)(data[i]) ^ hash) * internal::fnv_prime<type>;
return hash;
}
template<size_t BitCount, size_t StrLen>
static constexpr auto fnv1a_continue(list::get_type<internal::fnv_return_types, BitCount / 32 - 1> initial,
const char (&str)[StrLen]) -> auto
{
static_assert(BitCount == 32 || BitCount == 64, "We only support 32 and 64bit FNV-1a hash function");
using type = list::get_type<internal::fnv_return_types, BitCount / 32 - 1>;
static_assert(internal::fnv_prime<type> != 0, "Invalid prime (are you using a supported type ?)");
type hash = initial;
// StrLen - 1 is to skip the ending \0
for (size_t i = 0; i < StrLen - 1; ++i)
hash = ((uint8_t)(str[i]) ^ hash) * internal::fnv_prime<type>;
return hash;
}
} // namespace hash
} // namespace ct
} // namespace neam
#endif // __N_1298911746129055067_381318754_FNV1A_HPP__
<commit_msg>fix out-of-bound access<commit_after>//
// file : fnv1a.hpp
// in : file:///home/tim/projects/ntools/hash/fnv1a.hpp
//
// created by : Timothée Feuillet
// date: Mon May 22 2017 16:30:57 GMT-0400 (EDT)
//
//
// Copyright (c) 2017 Timothée Feuillet
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#ifndef __N_1298911746129055067_381318754_FNV1A_HPP__
#define __N_1298911746129055067_381318754_FNV1A_HPP__
#include <cstdint>
#include <cstddef>
#include "../ct_list.hpp"
#include "../embed.hpp"
namespace neam
{
namespace ct
{
namespace hash
{
namespace internal
{
using fnv_return_types = type_list<uint32_t, uint64_t>;
template<typename T> static constexpr T fnv_offset_basis = T();
template<> constexpr uint64_t fnv_offset_basis<uint64_t> = 0xcbf29ce484222325ul;
template<> constexpr uint32_t fnv_offset_basis<uint32_t> = 0x811c9dc5u;
template<typename T> static constexpr T fnv_prime = T();
template<> constexpr uint64_t fnv_prime<uint64_t> = 0x100000001b3ul;
template<> constexpr uint32_t fnv_prime<uint32_t> = 0x01000193u;
} // namespace internal
template<size_t BitCount, typename T>
static constexpr auto fnv1a(const T *const data, size_t len) -> auto
{
static_assert(BitCount == 32 || BitCount == 64, "We only support 32 and 64bit FNV-1a hash function");
constexpr size_t index = BitCount / 32 - 1;
using type = list::get_type<internal::fnv_return_types, index>;
static_assert(sizeof(T) == 1, "Input type must be 8bit");
static_assert(internal::fnv_offset_basis<type> != 0, "Invalid offset basis (are you using a supported type ?)");
static_assert(internal::fnv_prime<type> != 0, "Invalid prime (are you using a supported type ?)");
type hash = internal::fnv_offset_basis<type>;
for (size_t i = 0; i < len; ++i)
hash = ((uint8_t)(data)[i] ^ hash) * internal::fnv_prime<type>;
return hash;
}
template<size_t BitCount, size_t StrLen>
static constexpr auto fnv1a(const char (&str)[StrLen]) -> auto
{
static_assert(BitCount == 32 || BitCount == 64, "We only support 32 and 64bit FNV-1a hash function");
constexpr size_t index = BitCount / 32 - 1;
using type = list::get_type<internal::fnv_return_types, index>;
static_assert(internal::fnv_offset_basis<type> != 0, "Invalid offset basis (are you using a supported type ?)");
static_assert(internal::fnv_prime<type> != 0, "Invalid prime (are you using a supported type ?)");
type hash = internal::fnv_offset_basis<type>;
// StrLen - 1 is to skip the ending \0
for (size_t i = 0; i < StrLen - 1; ++i)
hash = ((uint8_t)(str[i]) ^ hash) * internal::fnv_prime<type>;
return hash;
}
template<size_t BitCount, typename T>
static constexpr auto fnv1a_continue(list::get_type<internal::fnv_return_types, BitCount / 32 - 1> initial,
const T* const data, size_t len) -> auto
{
static_assert(BitCount == 32 || BitCount == 64, "We only support 32 and 64bit FNV-1a hash function");
using type = list::get_type<internal::fnv_return_types, BitCount / 32 - 1>;
static_assert(sizeof(T) == 1, "Input type must be 8bit");
static_assert(internal::fnv_prime<type> != 0, "Invalid prime (are you using a supported type ?)");
type hash = initial;
for (size_t i = 0; i < len; ++i)
hash = ((uint8_t)(data[i]) ^ hash) * internal::fnv_prime<type>;
return hash;
}
template<size_t BitCount, size_t StrLen>
static constexpr auto fnv1a_continue(list::get_type<internal::fnv_return_types, BitCount / 32 - 1> initial,
const char (&str)[StrLen]) -> auto
{
static_assert(BitCount == 32 || BitCount == 64, "We only support 32 and 64bit FNV-1a hash function");
using type = list::get_type<internal::fnv_return_types, BitCount / 32 - 1>;
static_assert(internal::fnv_prime<type> != 0, "Invalid prime (are you using a supported type ?)");
type hash = initial;
// StrLen - 1 is to skip the ending \0
for (size_t i = 0; i < StrLen - 1; ++i)
hash = ((uint8_t)(str[i]) ^ hash) * internal::fnv_prime<type>;
return hash;
}
} // namespace hash
} // namespace ct
} // namespace neam
#endif // __N_1298911746129055067_381318754_FNV1A_HPP__
<|endoftext|>
|
<commit_before>// mykytea.cpp
#include <iostream>
#include <cstring>
#include "mykytea.hpp"
const int MAX_LEN = 256;
int split_argv(char* input, const char* configs[]){
int len;
char *cp;
const char *delim = " ";
cp = input;
configs[0] = "";
for(len = 0; len < MAX_LEN; len++){
if((configs[len + 1] = std::strtok(cp, delim)) == NULL )
break;
cp = NULL;
}
return len + 1;
}
Mykytea::Mykytea(char* str)
{
const char* configs[MAX_LEN + 1];
int len = split_argv(str, configs);
config = new KyteaConfig;
config->setDebug(0);
config->setOnTraining(false);
config->parseRunCommandLine(len, configs);
kytea = new Kytea(config);
kytea->readModel(config->getModelFile().c_str());
util = kytea->getStringUtil();
}
Mykytea::~Mykytea()
{
if(kytea != NULL) delete kytea;
}
vector<string>* Mykytea::getWS(string str){
vector<string>* vec = new vector<string>;
KyteaString surface_string = util->mapString(str);
KyteaSentence sentence(surface_string, util->normalize(surface_string));
kytea->calculateWS(sentence);
const KyteaSentence::Words & words = sentence.words;
for(int i = 0; i < (int)words.size(); i++) {
(*vec).push_back(util->showString(words[i].surface));
}
return vec;
}
vector<Tags>* Mykytea::getTags(string str){
vector<Tags>* ret_words = new vector<Tags>;
KyteaString surface_string = util->mapString(str);
KyteaSentence sentence(surface_string, util->normalize(surface_string));
kytea->calculateWS(sentence);
for(int i = 0; i < config->getNumTags(); i++)
kytea->calculateTags(sentence,i);
const KyteaSentence::Words & words = sentence.words;
for(int i = 0; i < (int)words.size(); i++) {
tags vec_tag;
for(int j = 0; j < (int)words[i].tags.size(); j++) {
vector< pair<string, double> > vec_tmp;
for(int k = 0; k < 1; k++) {
vec_tmp.push_back( make_pair(util->showString(words[i].tags[j][k].first), words[i].tags[j][k].second) );
}
vec_tag.push_back( vec_tmp );
}
struct Tags t = { util->showString(words[i].surface), vec_tag };
(*ret_words).push_back( t );
}
return ret_words;
}
vector<Tags>* Mykytea::getAllTags(string str){
vector<Tags>* ret_words = new vector<Tags>;
KyteaString surface_string = util->mapString(str);
KyteaSentence sentence(surface_string, util->normalize(surface_string));
kytea->calculateWS(sentence);
for(int i = 0; i < config->getNumTags(); i++)
kytea->calculateTags(sentence,i);
const KyteaSentence::Words & words = sentence.words;
for(int i = 0; i < (int)words.size(); i++) {
tags vec_tag;
for(int j = 0; j < (int)words[i].tags.size(); j++) {
vector< pair<string, double> > vec_tmp;
for(int k = 0; k < (int)words[i].tags[j].size(); k++) {
vec_tmp.push_back( make_pair(util->showString(words[i].tags[j][k].first), words[i].tags[j][k].second) );
}
vec_tag.push_back( vec_tmp );
}
struct Tags t = { util->showString(words[i].surface), vec_tag };
(*ret_words).push_back( t );
}
return ret_words;
}
string Mykytea::getTagsToString(string str)
{
KyteaString surface_string = util->mapString(str);
KyteaSentence sentence(surface_string, util->normalize(surface_string));
kytea->calculateWS(sentence);
for(int i = 0; i < config->getNumTags(); i++)
kytea->calculateTags(sentence,i);
const KyteaSentence::Words & words = sentence.words;
string ret_str;
for(int i = 0; i < (int)words.size(); i++) {
ret_str += util->showString(words[i].surface);
for(int j = 0; j < (int)words[i].tags.size(); j++) {
for(int k = 0; k < 1; k++) {
ret_str += "/";
ret_str += util->showString(words[i].tags[j][k].first);
}
}
ret_str += " ";
}
return ret_str;
}
<commit_msg>Fix option copy prepend to be broken by strok()<commit_after>// mykytea.cpp
#include <iostream>
#include <cstring>
#include "mykytea.hpp"
const int MAX_LEN = 256;
int split_argv(char* input, const char* configs[]){
int len;
const char *delim = " ";
char *cp = (char *)malloc(strlen(input) + 1);
strcpy(cp, input);
configs[0] = "";
for(len = 0; len < MAX_LEN; len++){
if((configs[len + 1] = std::strtok(cp, delim)) == NULL )
break;
cp = NULL;
}
return len + 1;
}
Mykytea::Mykytea(char* str)
{
const char* configs[MAX_LEN + 1];
int len = split_argv(str, configs);
config = new KyteaConfig;
config->setDebug(0);
config->setOnTraining(false);
config->parseRunCommandLine(len, configs);
kytea = new Kytea(config);
kytea->readModel(config->getModelFile().c_str());
util = kytea->getStringUtil();
}
Mykytea::~Mykytea()
{
if(kytea != NULL) delete kytea;
}
vector<string>* Mykytea::getWS(string str){
vector<string>* vec = new vector<string>;
KyteaString surface_string = util->mapString(str);
KyteaSentence sentence(surface_string, util->normalize(surface_string));
kytea->calculateWS(sentence);
const KyteaSentence::Words & words = sentence.words;
for(int i = 0; i < (int)words.size(); i++) {
(*vec).push_back(util->showString(words[i].surface));
}
return vec;
}
vector<Tags>* Mykytea::getTags(string str){
vector<Tags>* ret_words = new vector<Tags>;
KyteaString surface_string = util->mapString(str);
KyteaSentence sentence(surface_string, util->normalize(surface_string));
kytea->calculateWS(sentence);
for(int i = 0; i < config->getNumTags(); i++)
kytea->calculateTags(sentence,i);
const KyteaSentence::Words & words = sentence.words;
for(int i = 0; i < (int)words.size(); i++) {
tags vec_tag;
for(int j = 0; j < (int)words[i].tags.size(); j++) {
vector< pair<string, double> > vec_tmp;
for(int k = 0; k < 1; k++) {
vec_tmp.push_back( make_pair(util->showString(words[i].tags[j][k].first), words[i].tags[j][k].second) );
}
vec_tag.push_back( vec_tmp );
}
struct Tags t = { util->showString(words[i].surface), vec_tag };
(*ret_words).push_back( t );
}
return ret_words;
}
vector<Tags>* Mykytea::getAllTags(string str){
vector<Tags>* ret_words = new vector<Tags>;
KyteaString surface_string = util->mapString(str);
KyteaSentence sentence(surface_string, util->normalize(surface_string));
kytea->calculateWS(sentence);
for(int i = 0; i < config->getNumTags(); i++)
kytea->calculateTags(sentence,i);
const KyteaSentence::Words & words = sentence.words;
for(int i = 0; i < (int)words.size(); i++) {
tags vec_tag;
for(int j = 0; j < (int)words[i].tags.size(); j++) {
vector< pair<string, double> > vec_tmp;
for(int k = 0; k < (int)words[i].tags[j].size(); k++) {
vec_tmp.push_back( make_pair(util->showString(words[i].tags[j][k].first), words[i].tags[j][k].second) );
}
vec_tag.push_back( vec_tmp );
}
struct Tags t = { util->showString(words[i].surface), vec_tag };
(*ret_words).push_back( t );
}
return ret_words;
}
string Mykytea::getTagsToString(string str)
{
KyteaString surface_string = util->mapString(str);
KyteaSentence sentence(surface_string, util->normalize(surface_string));
kytea->calculateWS(sentence);
for(int i = 0; i < config->getNumTags(); i++)
kytea->calculateTags(sentence,i);
const KyteaSentence::Words & words = sentence.words;
string ret_str;
for(int i = 0; i < (int)words.size(); i++) {
ret_str += util->showString(words[i].surface);
for(int j = 0; j < (int)words[i].tags.size(); j++) {
for(int k = 0; k < 1; k++) {
ret_str += "/";
ret_str += util->showString(words[i].tags[j][k].first);
}
}
ret_str += " ";
}
return ret_str;
}
<|endoftext|>
|
<commit_before>#include "ResourceView.hpp"
#include <Engine/Geometry/Model.hpp>
#include <Engine/Texture/TextureAsset.hpp>
#include <Engine/Audio/SoundBuffer.hpp>
#include <Engine/Script/ScriptFile.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <Editor/Util/EditorSettings.hpp>
#include <Engine/Hymn.hpp>
#include <Engine/Entity/Entity.hpp>
#include <Engine/MainWindow.hpp>
#include <imgui.h>
#include <limits>
#include "../ImGui/Splitter.hpp"
#include "../Resources.hpp"
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <cstdio>
#include <Utility/Log.hpp>
using namespace GUI;
using namespace std;
ResourceView::ResourceView() {
}
void ResourceView::Show() {
ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);
// Splitter.
ImGui::VerticalSplitter(ImVec2(sceneWidth, size.y - resourceHeight), size.x - sceneWidth - editorWidth, splitterSize, resourceHeight, resourceResize, 20, size.y - 20);
if (resourceResize)
resourceHeight = size.y - resourceHeight;
ImGui::SetNextWindowPos(ImVec2(sceneWidth, size.y - resourceHeight));
ImGui::SetNextWindowSize(ImVec2(size.x - sceneWidth - editorWidth, resourceHeight));
ImGui::Begin("Resources", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);
// Scenes.
if (ImGui::TreeNode("Scenes")) {
if (ImGui::Button("Add scene"))
Resources().scenes.push_back("Scene #" + std::to_string(Resources().scenes.size()));
for (std::size_t i = 0; i < Resources().scenes.size(); ++i) {
if (ImGui::Selectable(Resources().scenes[i].c_str())) {
// Sets to dont save when opening first scene.
if (sceneIndex == -1) {
changeScene = true;
sceneIndex = i;
savePromptWindow.SetVisible(false);
savePromptWindow.SetDecision(1);
} else {
// Does so that the prompt window wont show if you select active scene.
if (Resources().scenes[i] != Resources().scenes[Resources().activeScene]) {
changeScene = true;
sceneIndex = i;
savePromptWindow.SetTitle("Save before you switch scene?");
}
}
}
if (ImGui::BeginPopupContextItem(Resources().scenes[i].c_str())) {
if (ImGui::Selectable("Delete")) {
Resources().scenes.erase(Resources().scenes.begin() + i);
ImGui::EndPopup();
if (Resources().activeScene >= i) {
if (Resources().activeScene > 0)
Resources().activeScene = Resources().activeScene - 1;
sceneEditor.SetScene(Resources().activeScene);
}
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
if (changeScene) {
if (Hymn().GetPath() != "") {
savePromptWindow.SetVisible(true);
savePromptWindow.Show();
switch (savePromptWindow.GetDecision())
{
case 0:
sceneEditor.Save();
sceneEditor.SetVisible(true);
sceneEditor.SetScene(sceneIndex);
Resources().activeScene = sceneIndex;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + FileSystem::DELIMITER + "Scenes" + FileSystem::DELIMITER + Resources().scenes[sceneIndex] + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
break;
case 1:
sceneEditor.SetVisible(true);
sceneEditor.SetScene(sceneIndex);
Resources().activeScene = sceneIndex;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + FileSystem::DELIMITER + "Scenes" + FileSystem::DELIMITER + Resources().scenes[sceneIndex] + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
break;
default:
break;
}
}
}
}
// Models.
bool modelPressed = false;
if (ImGui::TreeNode("Models")) {
if (ImGui::Button("Add model")) {
Geometry::Model* model = new Geometry::Model();
model->name = "Model #" + std::to_string(Resources().modelNumber++);
Resources().models.push_back(model);
}
for (auto it = Resources().models.begin(); it != Resources().models.end(); ++it) {
Geometry::Model* model = *it;
if (ImGui::Selectable(model->name.c_str())) {
modelPressed = true;
modelEditor.SetModel(model);
}
if (ImGui::BeginPopupContextItem(model->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (modelEditor.GetModel() == model)
modelEditor.SetVisible(false);
delete model;
Resources().models.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Textures.
bool texturePressed = false;
if (ImGui::TreeNode("Textures")) {
if (ImGui::Button("Add texture")) {
TextureAsset* texture = new TextureAsset();
texture->name = "Texture #" + std::to_string(Resources().textureNumber++);
Resources().textures.push_back(texture);
}
for (auto it = Resources().textures.begin(); it != Resources().textures.end(); ++it) {
TextureAsset* texture = *it;
if (ImGui::Selectable(texture->name.c_str())) {
texturePressed = true;
textureEditor.SetTexture(texture);
}
if (ImGui::BeginPopupContextItem(texture->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (Managers().resourceManager->GetTextureAssetInstanceCount(texture) > 1) {
Log() << "This texture is in use. Remove all references to the texture first.\n";
} else {
if (textureEditor.GetTexture() == texture)
textureEditor.SetVisible(false);
// Remove files.
remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".png").c_str());
remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".json").c_str());
Managers().resourceManager->FreeTextureAsset(texture);
Resources().textures.erase(it);
}
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Scripts.
bool scriptPressed = false;
if (ImGui::TreeNode("Scripts")) {
if (ImGui::Button("Add script")) {
ScriptFile* scriptFile = new ScriptFile();
scriptFile->name = "Script #" + std::to_string(Hymn().scriptNumber++);
Hymn().scripts.push_back(scriptFile);
}
for (auto it = Hymn().scripts.begin(); it != Hymn().scripts.end(); ++it) {
ScriptFile* script = *it;
std::string name = script->name;
if (ImGui::Selectable(name.c_str())) {
scriptPressed = true;
scriptEditor.SetScript(script);
}
if (ImGui::BeginPopupContextItem(name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (scriptEditor.GetScript() == script)
scriptEditor.SetVisible(false);
delete script;
Hymn().scripts.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Sounds.
bool soundPressed = false;
if (ImGui::TreeNode("Sounds")) {
if (ImGui::Button("Add sound")) {
Audio::SoundBuffer* sound = new Audio::SoundBuffer();
sound->name = "Sound #" + std::to_string(Resources().soundNumber++);
Resources().sounds.push_back(sound);
}
for (auto it = Resources().sounds.begin(); it != Resources().sounds.end(); ++it) {
Audio::SoundBuffer* sound = *it;
if (ImGui::Selectable(sound->name.c_str())) {
soundPressed = true;
soundEditor.SetSound(sound);
}
if (ImGui::BeginPopupContextItem(sound->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (soundEditor.GetSound() == sound)
soundEditor.SetVisible(false);
delete sound;
Resources().sounds.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
if (sceneEditor.entityPressed || scriptPressed || texturePressed || modelPressed || soundPressed) {
sceneEditor.entityEditor.SetVisible(sceneEditor.entityPressed);
scriptEditor.SetVisible(scriptPressed);
textureEditor.SetVisible(texturePressed);
modelEditor.SetVisible(modelPressed);
soundEditor.SetVisible(soundPressed);
}
if (sceneEditor.IsVisible()) {
ImGui::HorizontalSplitter(ImVec2(sceneWidth, 20), size.y - 20, splitterSize, sceneWidth, sceneResize, 20, size.x - editorWidth - 20);
ImGui::SetNextWindowPos(ImVec2(0, 20));
ImGui::SetNextWindowSize(ImVec2(sceneWidth, size.y - 20));
sceneEditor.Show();
}
if (sceneEditor.entityEditor.IsVisible() || scriptEditor.IsVisible() || textureEditor.IsVisible() || modelEditor.IsVisible() || soundEditor.IsVisible()) {
editorWidth = size.x - editorWidth;
ImGui::HorizontalSplitter(ImVec2(editorWidth, 20), size.y - 20, splitterSize, editorWidth, editorResize, sceneWidth + 20, size.x - 20);
editorWidth = size.x - editorWidth;
ImGui::SetNextWindowPos(ImVec2(size.x - editorWidth, 20));
ImGui::SetNextWindowSize(ImVec2(editorWidth, size.y - 20));
}
if (sceneEditor.entityEditor.IsVisible())
sceneEditor.entityEditor.Show();
if (scriptEditor.IsVisible())
scriptEditor.Show();
if (textureEditor.IsVisible())
textureEditor.Show();
if (modelEditor.IsVisible())
modelEditor.Show();
if (soundEditor.IsVisible())
soundEditor.Show();
ImGui::End();
}
bool ResourceView::IsVisible() const {
return visible;
}
void ResourceView::SetVisible(bool visible) {
this->visible = visible;
}
void ResourceView::HideEditors() {
sceneEditor.SetVisible(false);
sceneEditor.entityEditor.SetVisible(false);
scriptEditor.SetVisible(false);
modelEditor.SetVisible(false);
textureEditor.SetVisible(false);
soundEditor.SetVisible(false);
}
void ResourceView::SaveScene() const {
sceneEditor.Save();
}
#undef max
void ResourceView::ResetScene() {
sceneEditor.SetScene(std::numeric_limits<std::size_t>::max());
sceneEditor.SetVisible(false);
}
SceneEditor& ResourceView::GetScene() {
return sceneEditor;
}
<commit_msg>Sneaky one-line fix.<commit_after>#include "ResourceView.hpp"
#include <Engine/Geometry/Model.hpp>
#include <Engine/Texture/TextureAsset.hpp>
#include <Engine/Audio/SoundBuffer.hpp>
#include <Engine/Script/ScriptFile.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <Editor/Util/EditorSettings.hpp>
#include <Engine/Hymn.hpp>
#include <DefaultAlbedo.png.hpp>
#include <Engine/MainWindow.hpp>
#include <imgui.h>
#include <limits>
#include "../ImGui/Splitter.hpp"
#include "../Resources.hpp"
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <cstdio>
#include <Utility/Log.hpp>
using namespace GUI;
using namespace std;
ResourceView::ResourceView() {
}
void ResourceView::Show() {
ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);
// Splitter.
ImGui::VerticalSplitter(ImVec2(sceneWidth, size.y - resourceHeight), size.x - sceneWidth - editorWidth, splitterSize, resourceHeight, resourceResize, 20, size.y - 20);
if (resourceResize)
resourceHeight = size.y - resourceHeight;
ImGui::SetNextWindowPos(ImVec2(sceneWidth, size.y - resourceHeight));
ImGui::SetNextWindowSize(ImVec2(size.x - sceneWidth - editorWidth, resourceHeight));
ImGui::Begin("Resources", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);
// Scenes.
if (ImGui::TreeNode("Scenes")) {
if (ImGui::Button("Add scene"))
Resources().scenes.push_back("Scene #" + std::to_string(Resources().scenes.size()));
for (std::size_t i = 0; i < Resources().scenes.size(); ++i) {
if (ImGui::Selectable(Resources().scenes[i].c_str())) {
// Sets to dont save when opening first scene.
if (sceneIndex == -1) {
changeScene = true;
sceneIndex = i;
savePromptWindow.SetVisible(false);
savePromptWindow.SetDecision(1);
} else {
// Does so that the prompt window wont show if you select active scene.
if (Resources().scenes[i] != Resources().scenes[Resources().activeScene]) {
changeScene = true;
sceneIndex = i;
savePromptWindow.SetTitle("Save before you switch scene?");
}
}
}
if (ImGui::BeginPopupContextItem(Resources().scenes[i].c_str())) {
if (ImGui::Selectable("Delete")) {
Resources().scenes.erase(Resources().scenes.begin() + i);
ImGui::EndPopup();
if (Resources().activeScene >= i) {
if (Resources().activeScene > 0)
Resources().activeScene = Resources().activeScene - 1;
sceneEditor.SetScene(Resources().activeScene);
}
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
if (changeScene) {
if (Hymn().GetPath() != "") {
savePromptWindow.SetVisible(true);
savePromptWindow.Show();
switch (savePromptWindow.GetDecision())
{
case 0:
sceneEditor.Save();
sceneEditor.SetVisible(true);
sceneEditor.SetScene(sceneIndex);
Resources().activeScene = sceneIndex;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + FileSystem::DELIMITER + "Scenes" + FileSystem::DELIMITER + Resources().scenes[sceneIndex] + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
break;
case 1:
sceneEditor.SetVisible(true);
sceneEditor.SetScene(sceneIndex);
Resources().activeScene = sceneIndex;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + FileSystem::DELIMITER + "Scenes" + FileSystem::DELIMITER + Resources().scenes[sceneIndex] + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
break;
default:
break;
}
}
}
}
// Models.
bool modelPressed = false;
if (ImGui::TreeNode("Models")) {
if (ImGui::Button("Add model")) {
Geometry::Model* model = new Geometry::Model();
model->name = "Model #" + std::to_string(Resources().modelNumber++);
Resources().models.push_back(model);
}
for (auto it = Resources().models.begin(); it != Resources().models.end(); ++it) {
Geometry::Model* model = *it;
if (ImGui::Selectable(model->name.c_str())) {
modelPressed = true;
modelEditor.SetModel(model);
}
if (ImGui::BeginPopupContextItem(model->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (modelEditor.GetModel() == model)
modelEditor.SetVisible(false);
delete model;
Resources().models.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Textures.
bool texturePressed = false;
if (ImGui::TreeNode("Textures")) {
if (ImGui::Button("Add texture")) {
string name = "Texture #" + std::to_string(Resources().textureNumber++);
TextureAsset* texture = Managers().resourceManager->CreateTextureAsset(name, Managers().resourceManager->CreateTexture2D(DEFAULTALBEDO_PNG, DEFAULTALBEDO_PNG_LENGTH));
Resources().textures.push_back(texture);
}
for (auto it = Resources().textures.begin(); it != Resources().textures.end(); ++it) {
TextureAsset* texture = *it;
if (ImGui::Selectable(texture->name.c_str())) {
texturePressed = true;
textureEditor.SetTexture(texture);
}
if (ImGui::BeginPopupContextItem(texture->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (Managers().resourceManager->GetTextureAssetInstanceCount(texture) > 1) {
Log() << "This texture is in use. Remove all references to the texture first.\n";
} else {
if (textureEditor.GetTexture() == texture)
textureEditor.SetVisible(false);
// Remove files.
remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".png").c_str());
remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".json").c_str());
Managers().resourceManager->FreeTextureAsset(texture);
Resources().textures.erase(it);
}
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Scripts.
bool scriptPressed = false;
if (ImGui::TreeNode("Scripts")) {
if (ImGui::Button("Add script")) {
ScriptFile* scriptFile = new ScriptFile();
scriptFile->name = "Script #" + std::to_string(Hymn().scriptNumber++);
Hymn().scripts.push_back(scriptFile);
}
for (auto it = Hymn().scripts.begin(); it != Hymn().scripts.end(); ++it) {
ScriptFile* script = *it;
std::string name = script->name;
if (ImGui::Selectable(name.c_str())) {
scriptPressed = true;
scriptEditor.SetScript(script);
}
if (ImGui::BeginPopupContextItem(name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (scriptEditor.GetScript() == script)
scriptEditor.SetVisible(false);
delete script;
Hymn().scripts.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Sounds.
bool soundPressed = false;
if (ImGui::TreeNode("Sounds")) {
if (ImGui::Button("Add sound")) {
Audio::SoundBuffer* sound = new Audio::SoundBuffer();
sound->name = "Sound #" + std::to_string(Resources().soundNumber++);
Resources().sounds.push_back(sound);
}
for (auto it = Resources().sounds.begin(); it != Resources().sounds.end(); ++it) {
Audio::SoundBuffer* sound = *it;
if (ImGui::Selectable(sound->name.c_str())) {
soundPressed = true;
soundEditor.SetSound(sound);
}
if (ImGui::BeginPopupContextItem(sound->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (soundEditor.GetSound() == sound)
soundEditor.SetVisible(false);
delete sound;
Resources().sounds.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
if (sceneEditor.entityPressed || scriptPressed || texturePressed || modelPressed || soundPressed) {
sceneEditor.entityEditor.SetVisible(sceneEditor.entityPressed);
scriptEditor.SetVisible(scriptPressed);
textureEditor.SetVisible(texturePressed);
modelEditor.SetVisible(modelPressed);
soundEditor.SetVisible(soundPressed);
}
if (sceneEditor.IsVisible()) {
ImGui::HorizontalSplitter(ImVec2(sceneWidth, 20), size.y - 20, splitterSize, sceneWidth, sceneResize, 20, size.x - editorWidth - 20);
ImGui::SetNextWindowPos(ImVec2(0, 20));
ImGui::SetNextWindowSize(ImVec2(sceneWidth, size.y - 20));
sceneEditor.Show();
}
if (sceneEditor.entityEditor.IsVisible() || scriptEditor.IsVisible() || textureEditor.IsVisible() || modelEditor.IsVisible() || soundEditor.IsVisible()) {
editorWidth = size.x - editorWidth;
ImGui::HorizontalSplitter(ImVec2(editorWidth, 20), size.y - 20, splitterSize, editorWidth, editorResize, sceneWidth + 20, size.x - 20);
editorWidth = size.x - editorWidth;
ImGui::SetNextWindowPos(ImVec2(size.x - editorWidth, 20));
ImGui::SetNextWindowSize(ImVec2(editorWidth, size.y - 20));
}
if (sceneEditor.entityEditor.IsVisible())
sceneEditor.entityEditor.Show();
if (scriptEditor.IsVisible())
scriptEditor.Show();
if (textureEditor.IsVisible())
textureEditor.Show();
if (modelEditor.IsVisible())
modelEditor.Show();
if (soundEditor.IsVisible())
soundEditor.Show();
ImGui::End();
}
bool ResourceView::IsVisible() const {
return visible;
}
void ResourceView::SetVisible(bool visible) {
this->visible = visible;
}
void ResourceView::HideEditors() {
sceneEditor.SetVisible(false);
sceneEditor.entityEditor.SetVisible(false);
scriptEditor.SetVisible(false);
modelEditor.SetVisible(false);
textureEditor.SetVisible(false);
soundEditor.SetVisible(false);
}
void ResourceView::SaveScene() const {
sceneEditor.Save();
}
#undef max
void ResourceView::ResetScene() {
sceneEditor.SetScene(std::numeric_limits<std::size_t>::max());
sceneEditor.SetVisible(false);
}
SceneEditor& ResourceView::GetScene() {
return sceneEditor;
}
<|endoftext|>
|
<commit_before>#include "ResourceView.hpp"
#include <Engine/Geometry/Model.hpp>
#include <Engine/Texture/TextureAsset.hpp>
#include <Engine/Audio/SoundBuffer.hpp>
#include <Engine/Script/ScriptFile.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <Editor/Util/EditorSettings.hpp>
#include <Engine/Hymn.hpp>
#include <DefaultAlbedo.png.hpp>
#include <Engine/MainWindow.hpp>
#include <imgui.h>
#include <limits>
#include "../ImGui/Splitter.hpp"
#include "../Resources.hpp"
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <cstdio>
#include <Utility/Log.hpp>
using namespace GUI;
using namespace std;
ResourceView::ResourceView() {
savePromptWindow.SetTitle("Save before you switch scene?");
savePromptWindow.ResetDecision();
}
void ResourceView::Show() {
ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);
// Splitter.
ImGui::VerticalSplitter(ImVec2(sceneWidth, size.y - resourceHeight), size.x - sceneWidth - editorWidth, splitterSize, resourceHeight, resourceResize, 20, size.y - 20);
if (resourceResize)
resourceHeight = size.y - resourceHeight;
ImGui::SetNextWindowPos(ImVec2(sceneWidth, size.y - resourceHeight));
ImGui::SetNextWindowSize(ImVec2(size.x - sceneWidth - editorWidth, resourceHeight));
ImGui::Begin("Resources", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);
// Scenes.
if (ImGui::TreeNode("Scenes")) {
if (ImGui::Button("Add scene"))
Resources().scenes.push_back("Scene #" + std::to_string(Resources().scenes.size()));
for (std::size_t i = 0; i < Resources().scenes.size(); ++i) {
if (ImGui::Selectable(Resources().scenes[i].c_str())) {
// Sets to dont save when opening first scene.
if (sceneIndex == -1) {
changeScene = true;
sceneIndex = i;
savePromptWindow.SetVisible(false);
savePromptWindow.SetDecision(1);
} else {
// Does so that the prompt window wont show if you select active scene.
if (Resources().scenes[i] != Resources().scenes[Resources().activeScene]) {
changeScene = true;
sceneIndex = i;
}
}
}
if (ImGui::BeginPopupContextItem(Resources().scenes[i].c_str())) {
if (ImGui::Selectable("Delete")) {
Resources().scenes.erase(Resources().scenes.begin() + i);
ImGui::EndPopup();
if (Resources().activeScene >= i) {
if (Resources().activeScene > 0)
Resources().activeScene = Resources().activeScene - 1;
sceneEditor.SetScene(Resources().activeScene);
}
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
if (changeScene) {
if (Hymn().GetPath() != "") {
if (!HasMadeChanges()) {
SwitchScene(sceneIndex);
} else {
savePromptWindow.SetVisible(true);
savePromptWindow.ResetDecision();
savePromptWindow.Show();
switch (savePromptWindow.GetDecision())
{
case 0:
sceneEditor.Save();
SwitchScene(sceneIndex);
break;
case 1:
SwitchScene(sceneIndex);
break;
case 2:
changeScene = false;
savePromptWindow.ResetDecision();
savePromptWindow.SetVisible(false);
break;
default:
break;
}
}
}
}
}
// Models.
bool modelPressed = false;
if (ImGui::TreeNode("Models")) {
if (ImGui::Button("Add model")) {
Geometry::Model* model = new Geometry::Model();
model->name = "Model #" + std::to_string(Resources().modelNumber++);
Resources().models.push_back(model);
}
for (auto it = Resources().models.begin(); it != Resources().models.end(); ++it) {
Geometry::Model* model = *it;
if (ImGui::Selectable(model->name.c_str())) {
modelPressed = true;
modelEditor.SetModel(model);
}
if (ImGui::BeginPopupContextItem(model->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (modelEditor.GetModel() == model)
modelEditor.SetVisible(false);
delete model;
Resources().models.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Textures.
bool texturePressed = false;
if (ImGui::TreeNode("Textures")) {
if (ImGui::Button("Add texture")) {
TextureAsset* texture = new TextureAsset();
texture->name = "Texture #" + std::to_string(Resources().textureNumber++);
Resources().textures.push_back(texture);
}
for (auto it = Resources().textures.begin(); it != Resources().textures.end(); ++it) {
TextureAsset* texture = *it;
if (ImGui::Selectable(texture->name.c_str())) {
texturePressed = true;
textureEditor.SetTexture(texture);
}
if (ImGui::BeginPopupContextItem(texture->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (Managers().resourceManager->GetTextureAssetInstanceCount(texture) > 1) {
Log() << "This texture is in use. Remove all references to the texture first.\n";
} else {
if (textureEditor.GetTexture() == texture)
textureEditor.SetVisible(false);
// Remove files.
remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".png").c_str());
// Remove meta file
remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".json").c_str());
Managers().resourceManager->FreeTextureAsset(texture);
Resources().textures.erase(it);
}
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Scripts.
bool scriptPressed = false;
if (ImGui::TreeNode("Scripts")) {
if (ImGui::Button("Add script")) {
ScriptFile* scriptFile = new ScriptFile();
scriptFile->name = "Script #" + std::to_string(Hymn().scriptNumber++);
Hymn().scripts.push_back(scriptFile);
}
for (auto it = Hymn().scripts.begin(); it != Hymn().scripts.end(); ++it) {
ScriptFile* script = *it;
std::string name = script->name;
if (ImGui::Selectable(name.c_str())) {
scriptPressed = true;
scriptEditor.SetScript(script);
}
if (ImGui::BeginPopupContextItem(name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (scriptEditor.GetScript() == script)
scriptEditor.SetVisible(false);
delete script;
Hymn().scripts.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Sounds.
bool soundPressed = false;
if (ImGui::TreeNode("Sounds")) {
if (ImGui::Button("Add sound")) {
Audio::SoundBuffer* sound = new Audio::SoundBuffer();
sound->name = "Sound #" + std::to_string(Resources().soundNumber++);
Resources().sounds.push_back(sound);
}
for (auto it = Resources().sounds.begin(); it != Resources().sounds.end(); ++it) {
Audio::SoundBuffer* sound = *it;
if (ImGui::Selectable(sound->name.c_str())) {
soundPressed = true;
soundEditor.SetSound(sound);
}
if (ImGui::BeginPopupContextItem(sound->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (soundEditor.GetSound() == sound)
soundEditor.SetVisible(false);
delete sound;
Resources().sounds.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
if (sceneEditor.entityPressed || scriptPressed || texturePressed || modelPressed || soundPressed) {
sceneEditor.entityEditor.SetVisible(sceneEditor.entityPressed);
scriptEditor.SetVisible(scriptPressed);
textureEditor.SetVisible(texturePressed);
modelEditor.SetVisible(modelPressed);
soundEditor.SetVisible(soundPressed);
}
if (sceneEditor.IsVisible()) {
ImGui::HorizontalSplitter(ImVec2(sceneWidth, 20), size.y - 20, splitterSize, sceneWidth, sceneResize, 20, size.x - editorWidth - 20);
ImGui::SetNextWindowPos(ImVec2(0, 20));
ImGui::SetNextWindowSize(ImVec2(sceneWidth, size.y - 20));
sceneEditor.Show();
}
if (sceneEditor.entityEditor.IsVisible() || scriptEditor.IsVisible() || textureEditor.IsVisible() || modelEditor.IsVisible() || soundEditor.IsVisible()) {
editorWidth = size.x - editorWidth;
ImGui::HorizontalSplitter(ImVec2(editorWidth, 20), size.y - 20, splitterSize, editorWidth, editorResize, sceneWidth + 20, size.x - 20);
editorWidth = size.x - editorWidth;
ImGui::SetNextWindowPos(ImVec2(size.x - editorWidth, 20));
ImGui::SetNextWindowSize(ImVec2(editorWidth, size.y - 20));
}
if (sceneEditor.entityEditor.IsVisible())
sceneEditor.entityEditor.Show();
if (scriptEditor.IsVisible())
scriptEditor.Show();
if (textureEditor.IsVisible())
textureEditor.Show();
if (modelEditor.IsVisible())
modelEditor.Show();
if (soundEditor.IsVisible())
soundEditor.Show();
ImGui::End();
}
bool ResourceView::HasMadeChanges() const{
std::string* sceneFilename = new std::string();
Json::Value sceneJson = sceneEditor.GetSaveFileJson(sceneFilename);
// Load Json document from file.
Json::Value reference;
std::ifstream file(*sceneFilename);
if (!file.good())
return true;
file >> reference;
file.close();
std::string hymnJsonString = sceneJson.toStyledString();
std::string referenceString = reference.toStyledString();
int response = referenceString.compare(hymnJsonString);
if (response != 0)
return true;
return false;
}
bool ResourceView::IsVisible() const {
return visible;
}
void ResourceView::SetVisible(bool visible) {
this->visible = visible;
}
void ResourceView::HideEditors() {
sceneEditor.SetVisible(false);
sceneEditor.entityEditor.SetVisible(false);
scriptEditor.SetVisible(false);
modelEditor.SetVisible(false);
textureEditor.SetVisible(false);
soundEditor.SetVisible(false);
}
void ResourceView::SaveScene() const {
sceneEditor.Save();
}
Json::Value ResourceView::GetSceneJson(std::string* filename) const {
return sceneEditor.GetSaveFileJson(filename);
}
void ResourceView::SwitchScene(int index) {
sceneEditor.SetVisible(true);
sceneEditor.SetScene(index);
Resources().activeScene = index;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + FileSystem::DELIMITER + "Scenes" + FileSystem::DELIMITER + Resources().scenes[index] + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
}
#undef max
void ResourceView::ResetScene() {
sceneEditor.SetScene(std::numeric_limits<std::size_t>::max());
sceneEditor.SetVisible(false);
}
SceneEditor& ResourceView::GetScene() {
return sceneEditor;
}
<commit_msg>Removed default albedo include in resource view.<commit_after>#include "ResourceView.hpp"
#include <Engine/Geometry/Model.hpp>
#include <Engine/Texture/TextureAsset.hpp>
#include <Engine/Audio/SoundBuffer.hpp>
#include <Engine/Script/ScriptFile.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <Editor/Util/EditorSettings.hpp>
#include <Engine/Hymn.hpp>
#include <Engine/MainWindow.hpp>
#include <imgui.h>
#include <limits>
#include "../ImGui/Splitter.hpp"
#include "../Resources.hpp"
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <cstdio>
#include <Utility/Log.hpp>
using namespace GUI;
using namespace std;
ResourceView::ResourceView() {
savePromptWindow.SetTitle("Save before you switch scene?");
savePromptWindow.ResetDecision();
}
void ResourceView::Show() {
ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);
// Splitter.
ImGui::VerticalSplitter(ImVec2(sceneWidth, size.y - resourceHeight), size.x - sceneWidth - editorWidth, splitterSize, resourceHeight, resourceResize, 20, size.y - 20);
if (resourceResize)
resourceHeight = size.y - resourceHeight;
ImGui::SetNextWindowPos(ImVec2(sceneWidth, size.y - resourceHeight));
ImGui::SetNextWindowSize(ImVec2(size.x - sceneWidth - editorWidth, resourceHeight));
ImGui::Begin("Resources", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);
// Scenes.
if (ImGui::TreeNode("Scenes")) {
if (ImGui::Button("Add scene"))
Resources().scenes.push_back("Scene #" + std::to_string(Resources().scenes.size()));
for (std::size_t i = 0; i < Resources().scenes.size(); ++i) {
if (ImGui::Selectable(Resources().scenes[i].c_str())) {
// Sets to dont save when opening first scene.
if (sceneIndex == -1) {
changeScene = true;
sceneIndex = i;
savePromptWindow.SetVisible(false);
savePromptWindow.SetDecision(1);
} else {
// Does so that the prompt window wont show if you select active scene.
if (Resources().scenes[i] != Resources().scenes[Resources().activeScene]) {
changeScene = true;
sceneIndex = i;
}
}
}
if (ImGui::BeginPopupContextItem(Resources().scenes[i].c_str())) {
if (ImGui::Selectable("Delete")) {
Resources().scenes.erase(Resources().scenes.begin() + i);
ImGui::EndPopup();
if (Resources().activeScene >= i) {
if (Resources().activeScene > 0)
Resources().activeScene = Resources().activeScene - 1;
sceneEditor.SetScene(Resources().activeScene);
}
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
if (changeScene) {
if (Hymn().GetPath() != "") {
if (!HasMadeChanges()) {
SwitchScene(sceneIndex);
} else {
savePromptWindow.SetVisible(true);
savePromptWindow.ResetDecision();
savePromptWindow.Show();
switch (savePromptWindow.GetDecision())
{
case 0:
sceneEditor.Save();
SwitchScene(sceneIndex);
break;
case 1:
SwitchScene(sceneIndex);
break;
case 2:
changeScene = false;
savePromptWindow.ResetDecision();
savePromptWindow.SetVisible(false);
break;
default:
break;
}
}
}
}
}
// Models.
bool modelPressed = false;
if (ImGui::TreeNode("Models")) {
if (ImGui::Button("Add model")) {
Geometry::Model* model = new Geometry::Model();
model->name = "Model #" + std::to_string(Resources().modelNumber++);
Resources().models.push_back(model);
}
for (auto it = Resources().models.begin(); it != Resources().models.end(); ++it) {
Geometry::Model* model = *it;
if (ImGui::Selectable(model->name.c_str())) {
modelPressed = true;
modelEditor.SetModel(model);
}
if (ImGui::BeginPopupContextItem(model->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (modelEditor.GetModel() == model)
modelEditor.SetVisible(false);
delete model;
Resources().models.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Textures.
bool texturePressed = false;
if (ImGui::TreeNode("Textures")) {
if (ImGui::Button("Add texture")) {
TextureAsset* texture = new TextureAsset();
texture->name = "Texture #" + std::to_string(Resources().textureNumber++);
Resources().textures.push_back(texture);
}
for (auto it = Resources().textures.begin(); it != Resources().textures.end(); ++it) {
TextureAsset* texture = *it;
if (ImGui::Selectable(texture->name.c_str())) {
texturePressed = true;
textureEditor.SetTexture(texture);
}
if (ImGui::BeginPopupContextItem(texture->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (Managers().resourceManager->GetTextureAssetInstanceCount(texture) > 1) {
Log() << "This texture is in use. Remove all references to the texture first.\n";
} else {
if (textureEditor.GetTexture() == texture)
textureEditor.SetVisible(false);
// Remove files.
remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".png").c_str());
// Remove meta file
remove((Hymn().GetPath() + FileSystem::DELIMITER + "Textures" + FileSystem::DELIMITER + texture->name + ".json").c_str());
Managers().resourceManager->FreeTextureAsset(texture);
Resources().textures.erase(it);
}
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Scripts.
bool scriptPressed = false;
if (ImGui::TreeNode("Scripts")) {
if (ImGui::Button("Add script")) {
ScriptFile* scriptFile = new ScriptFile();
scriptFile->name = "Script #" + std::to_string(Hymn().scriptNumber++);
Hymn().scripts.push_back(scriptFile);
}
for (auto it = Hymn().scripts.begin(); it != Hymn().scripts.end(); ++it) {
ScriptFile* script = *it;
std::string name = script->name;
if (ImGui::Selectable(name.c_str())) {
scriptPressed = true;
scriptEditor.SetScript(script);
}
if (ImGui::BeginPopupContextItem(name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (scriptEditor.GetScript() == script)
scriptEditor.SetVisible(false);
delete script;
Hymn().scripts.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Sounds.
bool soundPressed = false;
if (ImGui::TreeNode("Sounds")) {
if (ImGui::Button("Add sound")) {
Audio::SoundBuffer* sound = new Audio::SoundBuffer();
sound->name = "Sound #" + std::to_string(Resources().soundNumber++);
Resources().sounds.push_back(sound);
}
for (auto it = Resources().sounds.begin(); it != Resources().sounds.end(); ++it) {
Audio::SoundBuffer* sound = *it;
if (ImGui::Selectable(sound->name.c_str())) {
soundPressed = true;
soundEditor.SetSound(sound);
}
if (ImGui::BeginPopupContextItem(sound->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (soundEditor.GetSound() == sound)
soundEditor.SetVisible(false);
delete sound;
Resources().sounds.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
if (sceneEditor.entityPressed || scriptPressed || texturePressed || modelPressed || soundPressed) {
sceneEditor.entityEditor.SetVisible(sceneEditor.entityPressed);
scriptEditor.SetVisible(scriptPressed);
textureEditor.SetVisible(texturePressed);
modelEditor.SetVisible(modelPressed);
soundEditor.SetVisible(soundPressed);
}
if (sceneEditor.IsVisible()) {
ImGui::HorizontalSplitter(ImVec2(sceneWidth, 20), size.y - 20, splitterSize, sceneWidth, sceneResize, 20, size.x - editorWidth - 20);
ImGui::SetNextWindowPos(ImVec2(0, 20));
ImGui::SetNextWindowSize(ImVec2(sceneWidth, size.y - 20));
sceneEditor.Show();
}
if (sceneEditor.entityEditor.IsVisible() || scriptEditor.IsVisible() || textureEditor.IsVisible() || modelEditor.IsVisible() || soundEditor.IsVisible()) {
editorWidth = size.x - editorWidth;
ImGui::HorizontalSplitter(ImVec2(editorWidth, 20), size.y - 20, splitterSize, editorWidth, editorResize, sceneWidth + 20, size.x - 20);
editorWidth = size.x - editorWidth;
ImGui::SetNextWindowPos(ImVec2(size.x - editorWidth, 20));
ImGui::SetNextWindowSize(ImVec2(editorWidth, size.y - 20));
}
if (sceneEditor.entityEditor.IsVisible())
sceneEditor.entityEditor.Show();
if (scriptEditor.IsVisible())
scriptEditor.Show();
if (textureEditor.IsVisible())
textureEditor.Show();
if (modelEditor.IsVisible())
modelEditor.Show();
if (soundEditor.IsVisible())
soundEditor.Show();
ImGui::End();
}
bool ResourceView::HasMadeChanges() const{
std::string* sceneFilename = new std::string();
Json::Value sceneJson = sceneEditor.GetSaveFileJson(sceneFilename);
// Load Json document from file.
Json::Value reference;
std::ifstream file(*sceneFilename);
if (!file.good())
return true;
file >> reference;
file.close();
std::string hymnJsonString = sceneJson.toStyledString();
std::string referenceString = reference.toStyledString();
int response = referenceString.compare(hymnJsonString);
if (response != 0)
return true;
return false;
}
bool ResourceView::IsVisible() const {
return visible;
}
void ResourceView::SetVisible(bool visible) {
this->visible = visible;
}
void ResourceView::HideEditors() {
sceneEditor.SetVisible(false);
sceneEditor.entityEditor.SetVisible(false);
scriptEditor.SetVisible(false);
modelEditor.SetVisible(false);
textureEditor.SetVisible(false);
soundEditor.SetVisible(false);
}
void ResourceView::SaveScene() const {
sceneEditor.Save();
}
Json::Value ResourceView::GetSceneJson(std::string* filename) const {
return sceneEditor.GetSaveFileJson(filename);
}
void ResourceView::SwitchScene(int index) {
sceneEditor.SetVisible(true);
sceneEditor.SetScene(index);
Resources().activeScene = index;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + FileSystem::DELIMITER + "Scenes" + FileSystem::DELIMITER + Resources().scenes[index] + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
}
#undef max
void ResourceView::ResetScene() {
sceneEditor.SetScene(std::numeric_limits<std::size_t>::max());
sceneEditor.SetVisible(false);
}
SceneEditor& ResourceView::GetScene() {
return sceneEditor;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (c) 2020 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file gpio_test.cpp
* @author Julian Kent <julian@auterion.com>
*
* GPIO read and write tool
*/
#include <px4_platform_common/log.h>
#include <px4_platform_common/module.h>
#include <px4_platform_common/px4_config.h>
#include <nuttx/ioexpander/gpio.h>
#include <fcntl.h>
static void usage(const char *reason);
static int handle_board_ports(bool is_read, int argc, char *argv[]);
static int handle_device_ports(bool is_read, int argc, char *argv[]);
extern "C" __EXPORT int gpio_main(int argc, char *argv[])
{
if (argc < 3) {
usage("not enough arguments");
return -1;
}
const char *command = argv[1];
bool is_read = false;
if (strcmp(command, "read") == 0) {
is_read = true;
} else if (strcmp(command, "write") == 0) {
if (argc < 4) {
usage("not enough arguments");
return -1;
}
} else {
usage("command not read or write");
return -1;
}
if (argv[2][0] == '/') {
return handle_device_ports(is_read, argc, argv);
} else {
return handle_board_ports(is_read, argc, argv);
}
}
int handle_device_ports(bool is_read, int argc, char *argv[])
{
#ifdef CONFIG_DEV_GPIO
const char *device = argv[2];
int fd = open(device, O_RDWR);
if (fd < 0) {
usage("Opening the device failed");
return -1;
}
char *end;
if (is_read) {
gpio_pintype_e pin_type = GPIO_INPUT_PIN;
if (argc >= 4) {
const char *extra = argv[3];
if (strcasecmp(extra, "PULLUP") == 0) {
pin_type = GPIO_INPUT_PIN_PULLUP;
} else if (strcasecmp(extra, "PULLDOWN") == 0) {
pin_type = GPIO_INPUT_PIN_PULLDOWN;
} else {
usage("extra read argument not PULLUP or PULLDOWN");
goto exit_failure;
}
}
int ret = ioctl(fd, GPIOC_SETPINTYPE, pin_type);
if (ret != 0) {
PX4_ERR("ioctl GPIOC_SETPINTYPE failed: %i", ret);
goto exit_failure;
}
bool value;
ret = ioctl(fd, GPIOC_READ, (long)&value);
if (ret != 0) {
PX4_ERR("ioctl GPIOC_READ failed: %i", ret);
goto exit_failure;
}
printf("%d OK\n", (int)value);
} else {
gpio_pintype_e pin_type = GPIO_OUTPUT_PIN;
int32_t value = strtol(argv[3], &end, 10);
if (errno != 0 || *end != '\0' || (value != 0 && value != 1)) {
usage("value not 0 or 1");
goto exit_failure;
}
if (argc >= 5) {
const char *extra = argv[4];
if (strcasecmp(extra, "PUSHPULL") == 0) {
pin_type = GPIO_OUTPUT_PIN;
} else if (strcasecmp(extra, "OPENDRAIN") == 0) {
pin_type = GPIO_OUTPUT_PIN_OPENDRAIN;
} else {
usage("extra write argument not PUSHPULL or OPENDRAIN");
goto exit_failure;
}
}
int ret = ioctl(fd, GPIOC_SETPINTYPE, pin_type);
if (ret != 0) {
PX4_ERR("ioctl GPIOC_SETPINTYPE failed: %i", ret);
goto exit_failure;
}
ret = ioctl(fd, GPIOC_WRITE, value);
if (ret != 0) {
PX4_ERR("ioctl GPIOC_WRITE failed: %i", ret);
goto exit_failure;
}
printf("OK\n");
}
close(fd);
return 0;
exit_failure:
close(fd);
return -1;
#else
usage("not supported");
return -1;
#endif
}
int handle_board_ports(bool is_read, int argc, char *argv[])
{
const char *port_string = argv[2];
char port = port_string[0];
uint32_t mask = is_read ? GPIO_INPUT : GPIO_OUTPUT;
if ('A' <= port && port <= 'K') {
mask |= ((port - 'A') << GPIO_PORT_SHIFT) & GPIO_PORT_MASK;
} else if ('a' <= port && port <= 'k') {
mask |= ((port - 'a') << GPIO_PORT_SHIFT) & GPIO_PORT_MASK;
} else {
usage("invalid port");
return -1;
}
char *end;
int32_t pin = strtol(argv[2] + 1, &end, 10);
if (errno == 0 && *end == '\0' && 0 <= pin && pin <= 15) {
mask |= (pin << GPIO_PIN_SHIFT) & GPIO_PIN_MASK;;
} else {
usage("invalid pin");
return -1;
}
PX4_DEBUG("port=%c, pin=%i", port, pin);
bool matches_default_config = false;
#if defined(PX4_GPIO_INIT_LIST)
const uint32_t default_gpios[] = PX4_GPIO_INIT_LIST;
// check that GPIO matches initialization list for port/pin and input/output
for (uint32_t i = 0; i < arraySize(default_gpios); i++) {
if ((((default_gpios[i] & GPIO_INPUT) == (mask & GPIO_INPUT)) ||
((default_gpios[i] & GPIO_OUTPUT) == (mask & GPIO_OUTPUT)))
&& ((default_gpios[i] & GPIO_PORT_MASK) == (mask & GPIO_PORT_MASK))
&& ((default_gpios[i] & GPIO_PIN_MASK) == (mask & GPIO_PIN_MASK))
) {
matches_default_config = true;
}
}
#endif // PX4_GPIO_INIT_LIST
bool force_apply = strcasecmp(argv[argc - 1], "--force") == 0;
if (!matches_default_config && !force_apply) {
usage("does not match board initialization list, and --force not specified");
return -1;
}
if (is_read) {
if (argc >= 4) {
const char *extra = argv[3];
if (strcasecmp(extra, "PULLUP") == 0) {
mask |= GPIO_PULLUP;
} else if (strcasecmp(extra, "PULLDOWN") == 0) {
mask |= GPIO_PULLDOWN;
} else if (argc == 4 && !force_apply) {
usage("extra read argument not PULLUP or PULLDOWN");
return -1;
}
}
px4_arch_configgpio(mask);
int value = px4_arch_gpioread(mask);
printf("%d OK\n", value);
} else {
int32_t value = strtol(argv[3], &end, 10);
if (errno != 0 || *end != '\0' || (value != 0 && value != 1)) {
usage("value not 0 or 1");
return -1;
}
if (argc >= 5) {
const char *extra = argv[4];
if (strcasecmp(extra, "PUSHPULL") == 0) {
mask |= GPIO_PUSHPULL;
} else if (strcasecmp(extra, "OPENDRAIN") == 0) {
mask |= GPIO_OPENDRAIN;
} else if (argc == 5 && !force_apply) {
usage("extra write argument not PUSHPULL or OPENDRAIN");
return -1;
}
}
px4_arch_configgpio(mask);
px4_arch_gpiowrite(mask, value);
printf("OK\n");
}
return 0;
}
void usage(const char *reason)
{
printf("FAIL\n");
if (reason != nullptr) {
PX4_WARN("%s", reason);
}
PRINT_MODULE_DESCRIPTION(
R"DESCR_STR(
### Description
This command is used to read and write GPIOs
gpio read <PORT><PIN>/<DEVICE> [PULLDOWN|PULLUP] [--force]
gpio write <PORT><PIN>/<DEVICE> <VALUE> [PUSHPULL|OPENDRAIN] [--force]
### Examples
Read the value on port H pin 4 configured as pullup, and it is high
$ gpio read H4 PULLUP
1 OK
Set the output value on Port E pin 7 to high
$ gpio write E7 1 --force
Set the output value on device /dev/gpin1 to high
$ gpio write /dev/gpin1 1
)DESCR_STR");
PRINT_MODULE_USAGE_NAME_SIMPLE("gpio", "command");
PRINT_MODULE_USAGE_COMMAND("read");
PRINT_MODULE_USAGE_ARG("<PORT><PIN>/<DEVICE>", "GPIO port and pin or device", false);
PRINT_MODULE_USAGE_ARG("PULLDOWN|PULLUP", "Pulldown/Pullup", true);
PRINT_MODULE_USAGE_ARG("--force", "Force (ignore board gpio list)", true);
PRINT_MODULE_USAGE_COMMAND("write");
PRINT_MODULE_USAGE_ARG("<PORT> <PIN>", "GPIO port and pin", false);
PRINT_MODULE_USAGE_ARG("<VALUE>", "Value to write", false);
PRINT_MODULE_USAGE_ARG("PUSHPULL|OPENDRAIN", "Pushpull/Opendrain", true);
PRINT_MODULE_USAGE_ARG("--force", "Force (ignore board gpio list)", true);
}
<commit_msg>gpio.cpp: Add backticks around gpio command docs<commit_after>/****************************************************************************
*
* Copyright (c) 2020 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file gpio_test.cpp
* @author Julian Kent <julian@auterion.com>
*
* GPIO read and write tool
*/
#include <px4_platform_common/log.h>
#include <px4_platform_common/module.h>
#include <px4_platform_common/px4_config.h>
#include <nuttx/ioexpander/gpio.h>
#include <fcntl.h>
static void usage(const char *reason);
static int handle_board_ports(bool is_read, int argc, char *argv[]);
static int handle_device_ports(bool is_read, int argc, char *argv[]);
extern "C" __EXPORT int gpio_main(int argc, char *argv[])
{
if (argc < 3) {
usage("not enough arguments");
return -1;
}
const char *command = argv[1];
bool is_read = false;
if (strcmp(command, "read") == 0) {
is_read = true;
} else if (strcmp(command, "write") == 0) {
if (argc < 4) {
usage("not enough arguments");
return -1;
}
} else {
usage("command not read or write");
return -1;
}
if (argv[2][0] == '/') {
return handle_device_ports(is_read, argc, argv);
} else {
return handle_board_ports(is_read, argc, argv);
}
}
int handle_device_ports(bool is_read, int argc, char *argv[])
{
#ifdef CONFIG_DEV_GPIO
const char *device = argv[2];
int fd = open(device, O_RDWR);
if (fd < 0) {
usage("Opening the device failed");
return -1;
}
char *end;
if (is_read) {
gpio_pintype_e pin_type = GPIO_INPUT_PIN;
if (argc >= 4) {
const char *extra = argv[3];
if (strcasecmp(extra, "PULLUP") == 0) {
pin_type = GPIO_INPUT_PIN_PULLUP;
} else if (strcasecmp(extra, "PULLDOWN") == 0) {
pin_type = GPIO_INPUT_PIN_PULLDOWN;
} else {
usage("extra read argument not PULLUP or PULLDOWN");
goto exit_failure;
}
}
int ret = ioctl(fd, GPIOC_SETPINTYPE, pin_type);
if (ret != 0) {
PX4_ERR("ioctl GPIOC_SETPINTYPE failed: %i", ret);
goto exit_failure;
}
bool value;
ret = ioctl(fd, GPIOC_READ, (long)&value);
if (ret != 0) {
PX4_ERR("ioctl GPIOC_READ failed: %i", ret);
goto exit_failure;
}
printf("%d OK\n", (int)value);
} else {
gpio_pintype_e pin_type = GPIO_OUTPUT_PIN;
int32_t value = strtol(argv[3], &end, 10);
if (errno != 0 || *end != '\0' || (value != 0 && value != 1)) {
usage("value not 0 or 1");
goto exit_failure;
}
if (argc >= 5) {
const char *extra = argv[4];
if (strcasecmp(extra, "PUSHPULL") == 0) {
pin_type = GPIO_OUTPUT_PIN;
} else if (strcasecmp(extra, "OPENDRAIN") == 0) {
pin_type = GPIO_OUTPUT_PIN_OPENDRAIN;
} else {
usage("extra write argument not PUSHPULL or OPENDRAIN");
goto exit_failure;
}
}
int ret = ioctl(fd, GPIOC_SETPINTYPE, pin_type);
if (ret != 0) {
PX4_ERR("ioctl GPIOC_SETPINTYPE failed: %i", ret);
goto exit_failure;
}
ret = ioctl(fd, GPIOC_WRITE, value);
if (ret != 0) {
PX4_ERR("ioctl GPIOC_WRITE failed: %i", ret);
goto exit_failure;
}
printf("OK\n");
}
close(fd);
return 0;
exit_failure:
close(fd);
return -1;
#else
usage("not supported");
return -1;
#endif
}
int handle_board_ports(bool is_read, int argc, char *argv[])
{
const char *port_string = argv[2];
char port = port_string[0];
uint32_t mask = is_read ? GPIO_INPUT : GPIO_OUTPUT;
if ('A' <= port && port <= 'K') {
mask |= ((port - 'A') << GPIO_PORT_SHIFT) & GPIO_PORT_MASK;
} else if ('a' <= port && port <= 'k') {
mask |= ((port - 'a') << GPIO_PORT_SHIFT) & GPIO_PORT_MASK;
} else {
usage("invalid port");
return -1;
}
char *end;
int32_t pin = strtol(argv[2] + 1, &end, 10);
if (errno == 0 && *end == '\0' && 0 <= pin && pin <= 15) {
mask |= (pin << GPIO_PIN_SHIFT) & GPIO_PIN_MASK;;
} else {
usage("invalid pin");
return -1;
}
PX4_DEBUG("port=%c, pin=%i", port, pin);
bool matches_default_config = false;
#if defined(PX4_GPIO_INIT_LIST)
const uint32_t default_gpios[] = PX4_GPIO_INIT_LIST;
// check that GPIO matches initialization list for port/pin and input/output
for (uint32_t i = 0; i < arraySize(default_gpios); i++) {
if ((((default_gpios[i] & GPIO_INPUT) == (mask & GPIO_INPUT)) ||
((default_gpios[i] & GPIO_OUTPUT) == (mask & GPIO_OUTPUT)))
&& ((default_gpios[i] & GPIO_PORT_MASK) == (mask & GPIO_PORT_MASK))
&& ((default_gpios[i] & GPIO_PIN_MASK) == (mask & GPIO_PIN_MASK))
) {
matches_default_config = true;
}
}
#endif // PX4_GPIO_INIT_LIST
bool force_apply = strcasecmp(argv[argc - 1], "--force") == 0;
if (!matches_default_config && !force_apply) {
usage("does not match board initialization list, and --force not specified");
return -1;
}
if (is_read) {
if (argc >= 4) {
const char *extra = argv[3];
if (strcasecmp(extra, "PULLUP") == 0) {
mask |= GPIO_PULLUP;
} else if (strcasecmp(extra, "PULLDOWN") == 0) {
mask |= GPIO_PULLDOWN;
} else if (argc == 4 && !force_apply) {
usage("extra read argument not PULLUP or PULLDOWN");
return -1;
}
}
px4_arch_configgpio(mask);
int value = px4_arch_gpioread(mask);
printf("%d OK\n", value);
} else {
int32_t value = strtol(argv[3], &end, 10);
if (errno != 0 || *end != '\0' || (value != 0 && value != 1)) {
usage("value not 0 or 1");
return -1;
}
if (argc >= 5) {
const char *extra = argv[4];
if (strcasecmp(extra, "PUSHPULL") == 0) {
mask |= GPIO_PUSHPULL;
} else if (strcasecmp(extra, "OPENDRAIN") == 0) {
mask |= GPIO_OPENDRAIN;
} else if (argc == 5 && !force_apply) {
usage("extra write argument not PUSHPULL or OPENDRAIN");
return -1;
}
}
px4_arch_configgpio(mask);
px4_arch_gpiowrite(mask, value);
printf("OK\n");
}
return 0;
}
void usage(const char *reason)
{
printf("FAIL\n");
if (reason != nullptr) {
PX4_WARN("%s", reason);
}
PRINT_MODULE_DESCRIPTION(
R"DESCR_STR(
### Description
This command is used to read and write GPIOs
```
gpio read <PORT><PIN>/<DEVICE> [PULLDOWN|PULLUP] [--force]
gpio write <PORT><PIN>/<DEVICE> <VALUE> [PUSHPULL|OPENDRAIN] [--force]
```
### Examples
Read the value on port H pin 4 configured as pullup, and it is high
$ gpio read H4 PULLUP
1 OK
Set the output value on Port E pin 7 to high
$ gpio write E7 1 --force
Set the output value on device /dev/gpin1 to high
$ gpio write /dev/gpin1 1
)DESCR_STR");
PRINT_MODULE_USAGE_NAME_SIMPLE("gpio", "command");
PRINT_MODULE_USAGE_COMMAND("read");
PRINT_MODULE_USAGE_ARG("<PORT><PIN>/<DEVICE>", "GPIO port and pin or device", false);
PRINT_MODULE_USAGE_ARG("PULLDOWN|PULLUP", "Pulldown/Pullup", true);
PRINT_MODULE_USAGE_ARG("--force", "Force (ignore board gpio list)", true);
PRINT_MODULE_USAGE_COMMAND("write");
PRINT_MODULE_USAGE_ARG("<PORT> <PIN>", "GPIO port and pin", false);
PRINT_MODULE_USAGE_ARG("<VALUE>", "Value to write", false);
PRINT_MODULE_USAGE_ARG("PUSHPULL|OPENDRAIN", "Pushpull/Opendrain", true);
PRINT_MODULE_USAGE_ARG("--force", "Force (ignore board gpio list)", true);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "CoreUtils.h"
#ifdef _WIN32
// clang-format off
#include <cguid.h> // IWYU pragma: keep
#include <combaseapi.h> // IWYU pragma: keep
// clang-format on
#endif
#include <time.h>
#include <memory>
#ifdef _WIN32
std::string GetLastErrorAsString() {
// Get the error message, if any.
DWORD errorMessageID = ::GetLastError();
if (errorMessageID == 0) return "No error message has been recorded";
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0,
NULL);
std::string message(messageBuffer, size);
// Free the buffer.
LocalFree(messageBuffer);
return message;
}
#include "dde.h"
struct AFX_MAP_MESSAGE {
UINT nMsg;
LPCSTR lpszMsg;
};
#define DEFINE_MESSAGE(wm) \
{ wm, #wm }
static const AFX_MAP_MESSAGE allMessages[] = {
DEFINE_MESSAGE(WM_CREATE),
DEFINE_MESSAGE(WM_DESTROY),
DEFINE_MESSAGE(WM_MOVE),
DEFINE_MESSAGE(WM_SIZE),
DEFINE_MESSAGE(WM_ACTIVATE),
DEFINE_MESSAGE(WM_SETFOCUS),
DEFINE_MESSAGE(WM_KILLFOCUS),
DEFINE_MESSAGE(WM_ENABLE),
DEFINE_MESSAGE(WM_SETREDRAW),
DEFINE_MESSAGE(WM_SETTEXT),
DEFINE_MESSAGE(WM_GETTEXT),
DEFINE_MESSAGE(WM_GETTEXTLENGTH),
DEFINE_MESSAGE(WM_PAINT),
DEFINE_MESSAGE(WM_CLOSE),
DEFINE_MESSAGE(WM_QUERYENDSESSION),
DEFINE_MESSAGE(WM_QUIT),
DEFINE_MESSAGE(WM_QUERYOPEN),
DEFINE_MESSAGE(WM_ERASEBKGND),
DEFINE_MESSAGE(WM_SYSCOLORCHANGE),
DEFINE_MESSAGE(WM_ENDSESSION),
DEFINE_MESSAGE(WM_SHOWWINDOW),
DEFINE_MESSAGE(WM_CTLCOLORMSGBOX),
DEFINE_MESSAGE(WM_CTLCOLOREDIT),
DEFINE_MESSAGE(WM_CTLCOLORLISTBOX),
DEFINE_MESSAGE(WM_CTLCOLORBTN),
DEFINE_MESSAGE(WM_CTLCOLORDLG),
DEFINE_MESSAGE(WM_CTLCOLORSCROLLBAR),
DEFINE_MESSAGE(WM_CTLCOLORSTATIC),
DEFINE_MESSAGE(WM_WININICHANGE),
DEFINE_MESSAGE(WM_SETTINGCHANGE),
DEFINE_MESSAGE(WM_DEVMODECHANGE),
DEFINE_MESSAGE(WM_ACTIVATEAPP),
DEFINE_MESSAGE(WM_FONTCHANGE),
DEFINE_MESSAGE(WM_TIMECHANGE),
DEFINE_MESSAGE(WM_CANCELMODE),
DEFINE_MESSAGE(WM_SETCURSOR),
DEFINE_MESSAGE(WM_MOUSEACTIVATE),
DEFINE_MESSAGE(WM_CHILDACTIVATE),
DEFINE_MESSAGE(WM_QUEUESYNC),
DEFINE_MESSAGE(WM_GETMINMAXINFO),
DEFINE_MESSAGE(WM_ICONERASEBKGND),
DEFINE_MESSAGE(WM_NEXTDLGCTL),
DEFINE_MESSAGE(WM_SPOOLERSTATUS),
DEFINE_MESSAGE(WM_DRAWITEM),
DEFINE_MESSAGE(WM_MEASUREITEM),
DEFINE_MESSAGE(WM_DELETEITEM),
DEFINE_MESSAGE(WM_VKEYTOITEM),
DEFINE_MESSAGE(WM_CHARTOITEM),
DEFINE_MESSAGE(WM_SETFONT),
DEFINE_MESSAGE(WM_GETFONT),
DEFINE_MESSAGE(WM_QUERYDRAGICON),
DEFINE_MESSAGE(WM_COMPAREITEM),
DEFINE_MESSAGE(WM_COMPACTING),
DEFINE_MESSAGE(WM_NCCREATE),
DEFINE_MESSAGE(WM_NCDESTROY),
DEFINE_MESSAGE(WM_NCCALCSIZE),
DEFINE_MESSAGE(WM_NCHITTEST),
DEFINE_MESSAGE(WM_NCPAINT),
DEFINE_MESSAGE(WM_NCACTIVATE),
DEFINE_MESSAGE(WM_GETDLGCODE),
DEFINE_MESSAGE(WM_NCMOUSEMOVE),
DEFINE_MESSAGE(WM_NCLBUTTONDOWN),
DEFINE_MESSAGE(WM_NCLBUTTONUP),
DEFINE_MESSAGE(WM_NCLBUTTONDBLCLK),
DEFINE_MESSAGE(WM_NCRBUTTONDOWN),
DEFINE_MESSAGE(WM_NCRBUTTONUP),
DEFINE_MESSAGE(WM_NCRBUTTONDBLCLK),
DEFINE_MESSAGE(WM_NCMBUTTONDOWN),
DEFINE_MESSAGE(WM_NCMBUTTONUP),
DEFINE_MESSAGE(WM_NCMBUTTONDBLCLK),
DEFINE_MESSAGE(WM_KEYDOWN),
DEFINE_MESSAGE(WM_KEYUP),
DEFINE_MESSAGE(WM_CHAR),
DEFINE_MESSAGE(WM_DEADCHAR),
DEFINE_MESSAGE(WM_SYSKEYDOWN),
DEFINE_MESSAGE(WM_SYSKEYUP),
DEFINE_MESSAGE(WM_SYSCHAR),
DEFINE_MESSAGE(WM_SYSDEADCHAR),
DEFINE_MESSAGE(WM_KEYLAST),
DEFINE_MESSAGE(WM_INITDIALOG),
DEFINE_MESSAGE(WM_COMMAND),
DEFINE_MESSAGE(WM_SYSCOMMAND),
DEFINE_MESSAGE(WM_TIMER),
DEFINE_MESSAGE(WM_HSCROLL),
DEFINE_MESSAGE(WM_VSCROLL),
DEFINE_MESSAGE(WM_INITMENU),
DEFINE_MESSAGE(WM_INITMENUPOPUP),
DEFINE_MESSAGE(WM_MENUSELECT),
DEFINE_MESSAGE(WM_MENUCHAR),
DEFINE_MESSAGE(WM_ENTERIDLE),
DEFINE_MESSAGE(WM_MOUSEWHEEL),
DEFINE_MESSAGE(WM_MOUSEMOVE),
DEFINE_MESSAGE(WM_LBUTTONDOWN),
DEFINE_MESSAGE(WM_LBUTTONUP),
DEFINE_MESSAGE(WM_LBUTTONDBLCLK),
DEFINE_MESSAGE(WM_RBUTTONDOWN),
DEFINE_MESSAGE(WM_RBUTTONUP),
DEFINE_MESSAGE(WM_RBUTTONDBLCLK),
DEFINE_MESSAGE(WM_MBUTTONDOWN),
DEFINE_MESSAGE(WM_MBUTTONUP),
DEFINE_MESSAGE(WM_MBUTTONDBLCLK),
DEFINE_MESSAGE(WM_PARENTNOTIFY),
DEFINE_MESSAGE(WM_MDICREATE),
DEFINE_MESSAGE(WM_MDIDESTROY),
DEFINE_MESSAGE(WM_MDIACTIVATE),
DEFINE_MESSAGE(WM_MDIRESTORE),
DEFINE_MESSAGE(WM_MDINEXT),
DEFINE_MESSAGE(WM_MDIMAXIMIZE),
DEFINE_MESSAGE(WM_MDITILE),
DEFINE_MESSAGE(WM_MDICASCADE),
DEFINE_MESSAGE(WM_MDIICONARRANGE),
DEFINE_MESSAGE(WM_MDIGETACTIVE),
DEFINE_MESSAGE(WM_MDISETMENU),
DEFINE_MESSAGE(WM_CUT),
DEFINE_MESSAGE(WM_COPYDATA),
DEFINE_MESSAGE(WM_COPY),
DEFINE_MESSAGE(WM_PASTE),
DEFINE_MESSAGE(WM_CLEAR),
DEFINE_MESSAGE(WM_UNDO),
DEFINE_MESSAGE(WM_RENDERFORMAT),
DEFINE_MESSAGE(WM_RENDERALLFORMATS),
DEFINE_MESSAGE(WM_DESTROYCLIPBOARD),
DEFINE_MESSAGE(WM_DRAWCLIPBOARD),
DEFINE_MESSAGE(WM_PAINTCLIPBOARD),
DEFINE_MESSAGE(WM_VSCROLLCLIPBOARD),
DEFINE_MESSAGE(WM_SIZECLIPBOARD),
DEFINE_MESSAGE(WM_ASKCBFORMATNAME),
DEFINE_MESSAGE(WM_CHANGECBCHAIN),
DEFINE_MESSAGE(WM_HSCROLLCLIPBOARD),
DEFINE_MESSAGE(WM_QUERYNEWPALETTE),
DEFINE_MESSAGE(WM_PALETTEISCHANGING),
DEFINE_MESSAGE(WM_PALETTECHANGED),
DEFINE_MESSAGE(WM_DDE_INITIATE),
DEFINE_MESSAGE(WM_DDE_TERMINATE),
DEFINE_MESSAGE(WM_DDE_ADVISE),
DEFINE_MESSAGE(WM_DDE_UNADVISE),
DEFINE_MESSAGE(WM_DDE_ACK),
DEFINE_MESSAGE(WM_DDE_DATA),
DEFINE_MESSAGE(WM_DDE_REQUEST),
DEFINE_MESSAGE(WM_DDE_POKE),
DEFINE_MESSAGE(WM_DDE_EXECUTE),
DEFINE_MESSAGE(WM_DROPFILES),
DEFINE_MESSAGE(WM_POWER),
DEFINE_MESSAGE(WM_WINDOWPOSCHANGED),
DEFINE_MESSAGE(WM_WINDOWPOSCHANGING),
// MFC specific messages
/*DEFINE_MESSAGE(WM_SIZEPARENT),
DEFINE_MESSAGE(WM_SETMESSAGESTRING),
DEFINE_MESSAGE(WM_IDLEUPDATECMDUI),
DEFINE_MESSAGE(WM_INITIALUPDATE),
DEFINE_MESSAGE(WM_COMMANDHELP),
DEFINE_MESSAGE(WM_HELPHITTEST),
DEFINE_MESSAGE(WM_EXITHELPMODE),*/
DEFINE_MESSAGE(WM_HELP),
DEFINE_MESSAGE(WM_NOTIFY),
DEFINE_MESSAGE(WM_CONTEXTMENU),
DEFINE_MESSAGE(WM_TCARD),
DEFINE_MESSAGE(WM_MDIREFRESHMENU),
DEFINE_MESSAGE(WM_MOVING),
DEFINE_MESSAGE(WM_STYLECHANGED),
DEFINE_MESSAGE(WM_STYLECHANGING),
DEFINE_MESSAGE(WM_SIZING),
DEFINE_MESSAGE(WM_SETHOTKEY),
DEFINE_MESSAGE(WM_PRINT),
DEFINE_MESSAGE(WM_PRINTCLIENT),
DEFINE_MESSAGE(WM_POWERBROADCAST),
DEFINE_MESSAGE(WM_HOTKEY),
DEFINE_MESSAGE(WM_GETICON),
DEFINE_MESSAGE(WM_EXITMENULOOP),
DEFINE_MESSAGE(WM_ENTERMENULOOP),
DEFINE_MESSAGE(WM_DISPLAYCHANGE),
DEFINE_MESSAGE(WM_STYLECHANGED),
DEFINE_MESSAGE(WM_STYLECHANGING),
DEFINE_MESSAGE(WM_GETICON),
DEFINE_MESSAGE(WM_SETICON),
DEFINE_MESSAGE(WM_SIZING),
DEFINE_MESSAGE(WM_MOVING),
DEFINE_MESSAGE(WM_CAPTURECHANGED),
DEFINE_MESSAGE(WM_DEVICECHANGE),
DEFINE_MESSAGE(WM_PRINT),
DEFINE_MESSAGE(WM_PRINTCLIENT),
{
0,
NULL,
} // end of message list
};
std::string CWindowsMessageToString::GetStringFromMsg(DWORD dwMessage, bool bShowFrequentMessages) {
if (!bShowFrequentMessages &&
(dwMessage == WM_MOUSEMOVE || dwMessage == WM_NCMOUSEMOVE || dwMessage == WM_NCHITTEST ||
dwMessage == WM_SETCURSOR || dwMessage == WM_CTLCOLORBTN || dwMessage == WM_CTLCOLORDLG ||
dwMessage == WM_CTLCOLOREDIT || dwMessage == WM_CTLCOLORLISTBOX ||
dwMessage == WM_CTLCOLORMSGBOX || dwMessage == WM_CTLCOLORSCROLLBAR ||
dwMessage == WM_CTLCOLORSTATIC || dwMessage == WM_ENTERIDLE || dwMessage == WM_CANCELMODE ||
dwMessage == 0x0118)) // WM_SYSTIMER (caret blink)
{
// don't report very frequently sent messages
return "";
}
const AFX_MAP_MESSAGE* pMapMsg = allMessages;
for (/*null*/; pMapMsg->lpszMsg != NULL; pMapMsg++) {
if (pMapMsg->nMsg == dwMessage) {
return pMapMsg->lpszMsg;
}
}
return std::to_string(dwMessage);
}
#else
std::string GetLastErrorAsString() { return ""; }
#endif
std::string orbit_core::FormatTime(absl::Time time) {
return absl::FormatTime("%Y_%m_%d_%H_%M_%S", time, absl::LocalTimeZone());
}
<commit_msg>Remove unused GetLastErrorAsString<commit_after>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "CoreUtils.h"
std::string orbit_core::FormatTime(absl::Time time) {
return absl::FormatTime("%Y_%m_%d_%H_%M_%S", time, absl::LocalTimeZone());
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 <thread>
#include <vector>
#include "paddle/framework/executor.h"
#include "paddle/framework/op_registry.h"
namespace paddle {
namespace operators {
constexpr char kInputs[] = "inputs";
constexpr char kParameters[] = "parameters";
constexpr char kPlaces[] = "places";
constexpr char kOutputs[] = "outputs";
constexpr char kParallelScopes[] = "parallel_scopes";
constexpr char kParallelBlock[] = "sub_block";
// using ParallelScopeVar = std::vector<framework::Scope *>;
using LoDTensor = framework::LoDTensor;
using OperatorBase = framework::OperatorBase;
void SplitTensorAndMoveTensorToScopes(
const framework::Scope &scope,
const std::vector<framework::Scope *> &sub_scopes,
const std::vector<platform::Place> &places,
const std::vector<std::string> &names) {
for (auto &argu : names) {
auto *var = scope.FindVar(argu);
const auto &tensor = var->Get<LoDTensor>();
auto lod_tensors = tensor.SplitLoDTensor(places);
for (auto &lod : lod_tensors) {
VLOG(3) << lod.dims();
}
for (size_t i = 0; i < sub_scopes.size(); ++i) {
*sub_scopes[i]->Var(argu)->GetMutable<LoDTensor>() = lod_tensors[i];
}
}
}
class ParallelDoOp : public framework::OperatorBase {
public:
ParallelDoOp(const std::string &type,
const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorBase(type, inputs, outputs, attrs) {}
void Run(const framework::Scope &scope,
const platform::Place &place) const override {
// get device context from pool
platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
auto &dev_ctx = *pool.Get(place);
auto *block = Attr<framework::BlockDesc *>(kParallelBlock);
auto *program = block->Program();
// TODO(tonyyang-svail): get places from input
std::vector<platform::Place> places;
places.emplace_back(platform::CPUPlace());
places.emplace_back(platform::CPUPlace());
auto &sub_scopes = *scope.FindVar(Output(kParallelScopes))
->GetMutable<std::vector<framework::Scope *>>();
for (size_t place_idx = 0; place_idx < places.size(); ++place_idx) {
sub_scopes.push_back(&scope.NewScope());
}
SplitTensorAndMoveTensorToScopes(scope, sub_scopes, places,
Inputs(kInputs));
std::vector<std::thread> workers;
for (size_t place_idx = 0; place_idx < places.size(); ++place_idx) {
VLOG(3) << "Run " << place_idx;
auto &place = places[place_idx];
auto *cur_scope = sub_scopes[place_idx];
// copy parameter
if (dev_ctx.GetPlace() != place) {
PADDLE_THROW("Not Implemented");
}
// execute
workers.push_back(std::thread([program, cur_scope, place, block] {
auto executor = framework::Executor(place);
executor.Run(*program, cur_scope, block->ID(),
false /*create_local_scope*/);
}));
}
for (auto &worker : workers) {
worker.join();
}
// merge output
for (auto &o_name : Outputs(kOutputs)) {
std::vector<const framework::LoDTensor *> lod_tensors;
for (auto *sub_scope : sub_scopes) {
lod_tensors.push_back(&sub_scope->FindVar(o_name)->Get<LoDTensor>());
}
auto *lod_tensor_to_be_merged =
scope.FindVar(o_name)->GetMutable<LoDTensor>();
lod_tensor_to_be_merged->MergeLoDTensor(lod_tensors, dev_ctx.GetPlace());
}
}
};
class ParallelDoOpProtoMaker : public framework::OpProtoAndCheckerMaker {
public:
ParallelDoOpProtoMaker(OpProto *proto, framework::OpAttrChecker *op_checker)
: OpProtoAndCheckerMaker(proto, op_checker) {
AddInput(kInputs, "").AsDuplicable();
AddInput(kParameters, "").AsDuplicable();
AddInput(kPlaces, "");
AddOutput(kOutputs, "").AsDuplicable();
AddOutput(kParallelScopes, "");
AddAttr<framework::BlockDesc *>(kParallelBlock, "");
AddComment(R"DOC(
ParallelDo Operator.
)DOC");
}
};
class ParallelDoGradOp : public OperatorBase {
public:
ParallelDoGradOp(const std::string &type,
const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorBase(type, inputs, outputs, attrs) {}
void Run(const framework::Scope &scope,
const platform::Place &place) const override {
// // get device context from pool
// platform::DeviceContextPool &pool =
// platform::DeviceContextPool::Instance();
// auto &dev_ctx = *pool.Get(place);
auto *block = Attr<framework::BlockDesc *>(kParallelBlock);
auto *program = block->Program();
auto &sub_scopes = scope.FindVar(Input(kParallelScopes))
->Get<std::vector<framework::Scope *>>();
// TODO(tonyyang-svail): get places from input
std::vector<platform::Place> places;
places.emplace_back(platform::CPUPlace());
places.emplace_back(platform::CPUPlace());
// feed output@grad
SplitTensorAndMoveTensorToScopes(scope, sub_scopes, places,
Inputs(framework::GradVarName(kOutputs)));
for (auto &s : Inputs(framework::GradVarName(kOutputs))) {
VLOG(3) << s;
VLOG(3) << scope.FindVar(s)->Get<LoDTensor>();
for (auto *sub_scope : sub_scopes) {
VLOG(3) << sub_scope->FindVar(s)->Get<LoDTensor>();
}
}
// exe run
std::vector<std::thread> workers;
for (size_t place_idx = 0; place_idx < places.size(); ++place_idx) {
VLOG(3) << "Run " << place_idx;
auto &place = places[place_idx];
auto *cur_scope = sub_scopes[place_idx];
// execute
workers.push_back(std::thread([program, cur_scope, place, block] {
auto executor = framework::Executor(place);
executor.Run(*program, cur_scope, block->ID(),
false /*create_local_scope*/);
}));
}
for (auto &worker : workers) {
worker.join();
}
// merge grad
for (auto &s : Outputs(framework::GradVarName(kParameters))) {
VLOG(3) << s;
auto &t = sub_scopes[0]->FindVar(s)->Get<LoDTensor>();
VLOG(3) << t;
std::string s_buf = s + "@BUF";
auto *t_buf = sub_scopes[0]->Var(s_buf)->GetMutable<LoDTensor>();
for (size_t place_idx = 1; place_idx < places.size(); ++place_idx) {
auto &tt = sub_scopes[place_idx]->FindVar(s)->Get<LoDTensor>();
VLOG(3) << place_idx;
VLOG(3) << tt;
framework::CopyFrom(tt, places[0], t_buf);
auto sum_op = framework::OpRegistry::CreateOp(
"sum", {{"X", {s, s_buf}}}, {{"Out", {s}}},
framework::AttributeMap{});
sum_op->Run(*sub_scopes[0], place);
}
VLOG(3) << t;
framework::CopyFrom(t, place, scope.FindVar(s)->GetMutable<LoDTensor>());
}
}
};
class ParallelDoGradOpDescMaker : public framework::SingleGradOpDescMaker {
public:
using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;
protected:
virtual std::unique_ptr<framework::OpDesc> Apply() const {
auto *grad = new framework::OpDesc();
grad->SetType("parallel_do_grad");
for (auto &input_param : this->InputNames()) {
VLOG(3) << input_param;
grad->SetInput(input_param, this->Input(input_param));
grad->SetOutput(framework::GradVarName(input_param),
this->InputGrad(input_param, false));
}
for (auto &output_param : this->OutputNames()) {
if (output_param == kParallelScopes) {
grad->SetInput(output_param, this->Output(output_param));
grad->SetInput(framework::GradVarName(output_param),
this->Output(output_param));
} else {
grad->SetInput(output_param, this->Output(output_param));
grad->SetInput(framework::GradVarName(output_param),
this->OutputGrad(output_param));
}
}
grad->SetAttrMap(this->Attrs());
grad->SetBlockAttr(kParallelBlock, *grad_block_[0]);
return std::unique_ptr<framework::OpDesc>(grad);
}
};
class ParallelDoGradOpShapeInference : public framework::InferShapeBase {
public:
void operator()(framework::InferShapeContext *ctx) const override {
std::vector<std::string> input{kParameters, kInputs};
std::vector<std::string> output{kOutputs};
for (auto &s : input) {
PADDLE_ENFORCE(ctx->HasInputs(s));
PADDLE_ENFORCE(ctx->HasOutputs(framework::GradVarName(s)),
"Cannot find the gradient variable %s",
framework::GradVarName(s));
}
for (auto &s : output) {
PADDLE_ENFORCE(ctx->HasInputs(s));
}
for (auto &s : input) {
ctx->SetOutputsDim(framework::GradVarName(s), ctx->GetInputsDim(s));
}
if (ctx->HasInputs(kParameters)) {
PADDLE_ENFORCE(ctx->HasOutputs(framework::GradVarName(kParameters)));
ctx->SetOutputsDim(framework::GradVarName(kParameters),
ctx->GetInputsDim(kParameters));
}
}
};
} // namespace operators
} // namespace paddle
REGISTER_OPERATOR(parallel_do, paddle::operators::ParallelDoOp,
paddle::operators::ParallelDoOpProtoMaker,
paddle::operators::ParallelDoGradOpDescMaker);
REGISTER_OPERATOR(parallel_do_grad, paddle::operators::ParallelDoGradOp,
paddle::operators::ParallelDoGradOpShapeInference);
<commit_msg>licence update<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 <thread>
#include <vector>
#include "paddle/framework/executor.h"
#include "paddle/framework/op_registry.h"
namespace paddle {
namespace operators {
constexpr char kInputs[] = "inputs";
constexpr char kParameters[] = "parameters";
constexpr char kPlaces[] = "places";
constexpr char kOutputs[] = "outputs";
constexpr char kParallelScopes[] = "parallel_scopes";
constexpr char kParallelBlock[] = "sub_block";
// using ParallelScopeVar = std::vector<framework::Scope *>;
using LoDTensor = framework::LoDTensor;
using OperatorBase = framework::OperatorBase;
void SplitTensorAndMoveTensorToScopes(
const framework::Scope &scope,
const std::vector<framework::Scope *> &sub_scopes,
const std::vector<platform::Place> &places,
const std::vector<std::string> &names) {
for (auto &argu : names) {
auto *var = scope.FindVar(argu);
const auto &tensor = var->Get<LoDTensor>();
auto lod_tensors = tensor.SplitLoDTensor(places);
for (auto &lod : lod_tensors) {
VLOG(3) << lod.dims();
}
for (size_t i = 0; i < sub_scopes.size(); ++i) {
*sub_scopes[i]->Var(argu)->GetMutable<LoDTensor>() = lod_tensors[i];
}
}
}
class ParallelDoOp : public framework::OperatorBase {
public:
ParallelDoOp(const std::string &type,
const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorBase(type, inputs, outputs, attrs) {}
void Run(const framework::Scope &scope,
const platform::Place &place) const override {
// get device context from pool
platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
auto &dev_ctx = *pool.Get(place);
auto *block = Attr<framework::BlockDesc *>(kParallelBlock);
auto *program = block->Program();
// TODO(tonyyang-svail): get places from input
std::vector<platform::Place> places;
places.emplace_back(platform::CPUPlace());
places.emplace_back(platform::CPUPlace());
auto &sub_scopes = *scope.FindVar(Output(kParallelScopes))
->GetMutable<std::vector<framework::Scope *>>();
for (size_t place_idx = 0; place_idx < places.size(); ++place_idx) {
sub_scopes.push_back(&scope.NewScope());
}
SplitTensorAndMoveTensorToScopes(scope, sub_scopes, places,
Inputs(kInputs));
std::vector<std::thread> workers;
for (size_t place_idx = 0; place_idx < places.size(); ++place_idx) {
VLOG(3) << "Run " << place_idx;
auto &place = places[place_idx];
auto *cur_scope = sub_scopes[place_idx];
// copy parameter
if (dev_ctx.GetPlace() != place) {
PADDLE_THROW("Not Implemented");
}
// execute
workers.push_back(std::thread([program, cur_scope, place, block] {
auto executor = framework::Executor(place);
executor.Run(*program, cur_scope, block->ID(),
false /*create_local_scope*/);
}));
}
for (auto &worker : workers) {
worker.join();
}
// merge output
for (auto &o_name : Outputs(kOutputs)) {
std::vector<const framework::LoDTensor *> lod_tensors;
for (auto *sub_scope : sub_scopes) {
lod_tensors.push_back(&sub_scope->FindVar(o_name)->Get<LoDTensor>());
}
auto *lod_tensor_to_be_merged =
scope.FindVar(o_name)->GetMutable<LoDTensor>();
lod_tensor_to_be_merged->MergeLoDTensor(lod_tensors, dev_ctx.GetPlace());
}
}
};
class ParallelDoOpProtoMaker : public framework::OpProtoAndCheckerMaker {
public:
ParallelDoOpProtoMaker(OpProto *proto, framework::OpAttrChecker *op_checker)
: OpProtoAndCheckerMaker(proto, op_checker) {
AddInput(kInputs, "").AsDuplicable();
AddInput(kParameters, "").AsDuplicable();
AddInput(kPlaces, "");
AddOutput(kOutputs, "").AsDuplicable();
AddOutput(kParallelScopes, "");
AddAttr<framework::BlockDesc *>(kParallelBlock, "");
AddComment(R"DOC(
ParallelDo Operator.
)DOC");
}
};
class ParallelDoGradOp : public OperatorBase {
public:
ParallelDoGradOp(const std::string &type,
const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorBase(type, inputs, outputs, attrs) {}
void Run(const framework::Scope &scope,
const platform::Place &place) const override {
// // get device context from pool
// platform::DeviceContextPool &pool =
// platform::DeviceContextPool::Instance();
// auto &dev_ctx = *pool.Get(place);
auto *block = Attr<framework::BlockDesc *>(kParallelBlock);
auto *program = block->Program();
auto &sub_scopes = scope.FindVar(Input(kParallelScopes))
->Get<std::vector<framework::Scope *>>();
// TODO(tonyyang-svail): get places from input
std::vector<platform::Place> places;
places.emplace_back(platform::CPUPlace());
places.emplace_back(platform::CPUPlace());
// feed output@grad
SplitTensorAndMoveTensorToScopes(scope, sub_scopes, places,
Inputs(framework::GradVarName(kOutputs)));
for (auto &s : Inputs(framework::GradVarName(kOutputs))) {
VLOG(3) << s;
VLOG(3) << scope.FindVar(s)->Get<LoDTensor>();
for (auto *sub_scope : sub_scopes) {
VLOG(3) << sub_scope->FindVar(s)->Get<LoDTensor>();
}
}
// exe run
std::vector<std::thread> workers;
for (size_t place_idx = 0; place_idx < places.size(); ++place_idx) {
VLOG(3) << "Run " << place_idx;
auto &place = places[place_idx];
auto *cur_scope = sub_scopes[place_idx];
// execute
workers.push_back(std::thread([program, cur_scope, place, block] {
auto executor = framework::Executor(place);
executor.Run(*program, cur_scope, block->ID(),
false /*create_local_scope*/);
}));
}
for (auto &worker : workers) {
worker.join();
}
// merge grad
for (auto &s : Outputs(framework::GradVarName(kParameters))) {
VLOG(3) << s;
auto &t = sub_scopes[0]->FindVar(s)->Get<LoDTensor>();
VLOG(3) << t;
std::string s_buf = s + "@BUF";
auto *t_buf = sub_scopes[0]->Var(s_buf)->GetMutable<LoDTensor>();
for (size_t place_idx = 1; place_idx < places.size(); ++place_idx) {
auto &tt = sub_scopes[place_idx]->FindVar(s)->Get<LoDTensor>();
VLOG(3) << place_idx;
VLOG(3) << tt;
framework::CopyFrom(tt, places[0], t_buf);
auto sum_op = framework::OpRegistry::CreateOp(
"sum", {{"X", {s, s_buf}}}, {{"Out", {s}}},
framework::AttributeMap{});
sum_op->Run(*sub_scopes[0], place);
}
VLOG(3) << t;
framework::CopyFrom(t, place, scope.FindVar(s)->GetMutable<LoDTensor>());
}
}
};
class ParallelDoGradOpDescMaker : public framework::SingleGradOpDescMaker {
public:
using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;
protected:
virtual std::unique_ptr<framework::OpDesc> Apply() const {
auto *grad = new framework::OpDesc();
grad->SetType("parallel_do_grad");
for (auto &input_param : this->InputNames()) {
VLOG(3) << input_param;
grad->SetInput(input_param, this->Input(input_param));
grad->SetOutput(framework::GradVarName(input_param),
this->InputGrad(input_param, false));
}
for (auto &output_param : this->OutputNames()) {
if (output_param == kParallelScopes) {
grad->SetInput(output_param, this->Output(output_param));
grad->SetInput(framework::GradVarName(output_param),
this->Output(output_param));
} else {
grad->SetInput(output_param, this->Output(output_param));
grad->SetInput(framework::GradVarName(output_param),
this->OutputGrad(output_param));
}
}
grad->SetAttrMap(this->Attrs());
grad->SetBlockAttr(kParallelBlock, *grad_block_[0]);
return std::unique_ptr<framework::OpDesc>(grad);
}
};
class ParallelDoGradOpShapeInference : public framework::InferShapeBase {
public:
void operator()(framework::InferShapeContext *ctx) const override {
std::vector<std::string> input{kParameters, kInputs};
std::vector<std::string> output{kOutputs};
for (auto &s : input) {
PADDLE_ENFORCE(ctx->HasInputs(s));
PADDLE_ENFORCE(ctx->HasOutputs(framework::GradVarName(s)),
"Cannot find the gradient variable %s",
framework::GradVarName(s));
}
for (auto &s : output) {
PADDLE_ENFORCE(ctx->HasInputs(s));
}
for (auto &s : input) {
ctx->SetOutputsDim(framework::GradVarName(s), ctx->GetInputsDim(s));
}
if (ctx->HasInputs(kParameters)) {
PADDLE_ENFORCE(ctx->HasOutputs(framework::GradVarName(kParameters)));
ctx->SetOutputsDim(framework::GradVarName(kParameters),
ctx->GetInputsDim(kParameters));
}
}
};
} // namespace operators
} // namespace paddle
REGISTER_OPERATOR(parallel_do, paddle::operators::ParallelDoOp,
paddle::operators::ParallelDoOpProtoMaker,
paddle::operators::ParallelDoGradOpDescMaker);
REGISTER_OPERATOR(parallel_do_grad, paddle::operators::ParallelDoGradOp,
paddle::operators::ParallelDoGradOpShapeInference);
<|endoftext|>
|
<commit_before>#if ((defined(_MSC_VER) && _MSC_VER >= 1700) || (__cplusplus >= 201103L && HAS_BOOST)) && !defined(__CYGWIN__)
#include "../test.h"
#define _NO_ASYNCRTIMP 1
#include "casablanca/Release/src/pch/stdafx.h"
#include "casablanca/Release/src/json/json.cpp"
#include "casablanca/Release/src/json/json_parsing.cpp"
#include "casablanca/Release/src/json/json_serialization.cpp"
#include "casablanca/Release/src/utilities/asyncrt_utils.cpp"
#include "casablanca/Release/src/http/common/http_msg.cpp"
#include "casablanca/Release/src/http/common/http_helpers.cpp"
#include "casablanca/Release/src/http/client/http_msg_client.cpp"
#include "casablanca/Release/src/uri/uri.cpp"
#include "casablanca/Release/src/uri/uri_builder.cpp"
#include "casablanca/Release/src/uri/uri_parser.cpp"
#include <strstream>
#include <sstream>
using namespace web::json;
//using namespace utility::conversions;
static void GenStat(Stat& stat, const value& v) {
switch (v.type()) {
case value::value_type::Array:
for (auto const& element : v.as_array())
GenStat(stat, element);
stat.arrayCount++;
stat.elementCount += v.size();
break;
case value::value_type::Object:
for (auto const& kv : v.as_object()) {
GenStat(stat, kv.second);
stat.stringLength += kv.first.size();
}
stat.objectCount++;
stat.memberCount += v.size();
stat.stringCount += v.size(); // member names
break;
case value::value_type::String:
stat.stringCount++;
stat.stringLength += v.as_string().size();
break;
case value::value_type::Number:
stat.numberCount++;
break;
case value::value_type::Boolean:
if (v.as_bool())
stat.trueCount++;
else
stat.falseCount++;
break;
case value::value_type::Null:
stat.nullCount++;
break;
}
}
class CasablancaParseResult : public ParseResultBase {
public:
value root;
};
class CasablancaStringResult : public StringResultBase {
public:
virtual const char* c_str() const { return s.c_str(); }
std::string s;
};
class CasablancaTest : public TestBase {
public:
#if TEST_INFO
virtual const char* GetName() const { return "Casablanca (C++11)"; }
virtual const char* GetFilename() const { return __FILE__; }
#endif
#if TEST_PARSE
virtual ParseResultBase* Parse(const char* json, size_t length) const {
(void)length;
CasablancaParseResult* pr = new CasablancaParseResult;
std::istrstream is (json);
try {
pr->root = value::parse(is);
}
catch (web::json::json_exception& e) {
printf("Parse error '%s'\n", e.what());
delete pr;
pr = 0;
}
return pr;
}
#endif
#if TEST_STRINGIFY
virtual StringResultBase* Stringify(const ParseResultBase* parseResult) const {
const CasablancaParseResult* pr = static_cast<const CasablancaParseResult*>(parseResult);
CasablancaStringResult* sr = new CasablancaStringResult;
std::ostringstream os;
pr->root.serialize(os);
sr->s = os.str();
return sr;
}
#endif
#if TEST_STATISTICS
virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const {
const CasablancaParseResult* pr = static_cast<const CasablancaParseResult*>(parseResult);
memset(stat, 0, sizeof(Stat));
GenStat(*stat, pr->root);
return true;
}
#endif
};
REGISTER_TEST(CasablancaTest);
#endif<commit_msg>Handle other casablanca exceptions<commit_after>#if ((defined(_MSC_VER) && _MSC_VER >= 1700) || (__cplusplus >= 201103L && HAS_BOOST)) && !defined(__CYGWIN__)
#include "../test.h"
#define _NO_ASYNCRTIMP 1
#include "casablanca/Release/src/pch/stdafx.h"
#include "casablanca/Release/src/json/json.cpp"
#include "casablanca/Release/src/json/json_parsing.cpp"
#include "casablanca/Release/src/json/json_serialization.cpp"
#include "casablanca/Release/src/utilities/asyncrt_utils.cpp"
#include "casablanca/Release/src/http/common/http_msg.cpp"
#include "casablanca/Release/src/http/common/http_helpers.cpp"
#include "casablanca/Release/src/http/client/http_msg_client.cpp"
#include "casablanca/Release/src/uri/uri.cpp"
#include "casablanca/Release/src/uri/uri_builder.cpp"
#include "casablanca/Release/src/uri/uri_parser.cpp"
#include <strstream>
#include <sstream>
using namespace web::json;
//using namespace utility::conversions;
static void GenStat(Stat& stat, const value& v) {
switch (v.type()) {
case value::value_type::Array:
for (auto const& element : v.as_array())
GenStat(stat, element);
stat.arrayCount++;
stat.elementCount += v.size();
break;
case value::value_type::Object:
for (auto const& kv : v.as_object()) {
GenStat(stat, kv.second);
stat.stringLength += kv.first.size();
}
stat.objectCount++;
stat.memberCount += v.size();
stat.stringCount += v.size(); // member names
break;
case value::value_type::String:
stat.stringCount++;
stat.stringLength += v.as_string().size();
break;
case value::value_type::Number:
stat.numberCount++;
break;
case value::value_type::Boolean:
if (v.as_bool())
stat.trueCount++;
else
stat.falseCount++;
break;
case value::value_type::Null:
stat.nullCount++;
break;
}
}
class CasablancaParseResult : public ParseResultBase {
public:
value root;
};
class CasablancaStringResult : public StringResultBase {
public:
virtual const char* c_str() const { return s.c_str(); }
std::string s;
};
class CasablancaTest : public TestBase {
public:
#if TEST_INFO
virtual const char* GetName() const { return "Casablanca (C++11)"; }
virtual const char* GetFilename() const { return __FILE__; }
#endif
#if TEST_PARSE
virtual ParseResultBase* Parse(const char* json, size_t length) const {
(void)length;
CasablancaParseResult* pr = new CasablancaParseResult;
std::istrstream is (json);
try {
pr->root = value::parse(is);
}
catch (web::json::json_exception& e) {
printf("Parse error '%s'\n", e.what());
delete pr;
pr = 0;
}
catch (...) {
delete pr;
pr = 0;
}
return pr;
}
#endif
#if TEST_STRINGIFY
virtual StringResultBase* Stringify(const ParseResultBase* parseResult) const {
const CasablancaParseResult* pr = static_cast<const CasablancaParseResult*>(parseResult);
CasablancaStringResult* sr = new CasablancaStringResult;
std::ostringstream os;
pr->root.serialize(os);
sr->s = os.str();
return sr;
}
#endif
#if TEST_STATISTICS
virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const {
const CasablancaParseResult* pr = static_cast<const CasablancaParseResult*>(parseResult);
memset(stat, 0, sizeof(Stat));
GenStat(*stat, pr->root);
return true;
}
#endif
};
REGISTER_TEST(CasablancaTest);
#endif<|endoftext|>
|
<commit_before>#include "Graph.hpp"
/*
template <typename Weight>
void add_edge(Graph<Weight> &g, int src, int to) {
g[src].push_back(Edge<Weight>(to));
g[to].push_back(Edge<Weight>(src));
}
*/
class LCA {
int V, LOG_V;
vector<vector<int>> parent;
vector<int> depth;
template<typename T>
void dfs(const Graph<T> &g, int v, int p, int d) {
parent[0][v] = p; depth[v] = d;
for (const Edge<T> &e: g[v]) {
if (e.to != p) dfs(g, e.to, v, d + 1);
}
}
public:
template<typename T>
LCA(const Graph<T> &g, int root) : V(g.size()), LOG_V(0), depth(V, 0) {
for (int v = V; v > 0; v >>= 1) ++LOG_V;
parent.assign(LOG_V, vector<int>(V, 0));
dfs(g, root, -1, 0);
for (int k = 0; k < LOG_V - 1; ++k) {
for (int v = 0; v < V; ++v) {
if (parent[k][v] < 0) parent[k + 1][v] = -1;
else parent[k + 1][v] = parent[k][parent[k][v]];
}
}
}
int query(int u, int v) {
if (depth[u] > depth[v]) swap(u, v);
for (int k = 0; k < LOG_V; ++k)
if (((depth[v] - depth[u]) >> k) & 1) v = parent[k][v];
if (u == v) return u;
for (int k = LOG_V - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
};
// Verified : AOJ GRL_5_C (Lowest Common Ancestor)
/*
int main() {
int n, q;
cin >> n;
Graph<int> g(n);
for (int i = 0; i < n; ++i) {
int k, c;
cin >> k;
while (k--) {
cin >> c;
add_edge(g, i, c);
}
}
LCA lca(g, 0);
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << lca.query(u, v) << endl;
}
return 0;
}
*/
<commit_msg>modify lca<commit_after>#include "Graph.hpp"
class LCA {
int V, LOG_V;
vector<vector<int>> parent;
vector<int> depth;
void dfs(const Graph &g, int v, int p, int d) {
parent[0][v] = p; depth[v] = d;
for (const Edge &e: g[v]) {
if (e.to != p) dfs(g, e.to, v, d + 1);
}
}
public:
LCA(const Graph &g, int root) : V(g.size()), LOG_V(0), depth(V, 0) {
for (int v = V; v > 0; v >>= 1) ++LOG_V;
parent.assign(LOG_V, vector<int>(V, 0));
dfs(g, root, -1, 0);
for (int k = 0; k < LOG_V - 1; ++k) {
for (int v = 0; v < V; ++v) {
if (parent[k][v] < 0) parent[k + 1][v] = -1;
else parent[k + 1][v] = parent[k][parent[k][v]];
}
}
}
int query(int u, int v) {
if (depth[u] > depth[v]) swap(u, v);
for (int k = 0; k < LOG_V; ++k)
if (((depth[v] - depth[u]) >> k) & 1) v = parent[k][v];
if (u == v) return u;
for (int k = LOG_V - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
};
// Verified : AOJ GRL_5_C (Lowest Common Ancestor)
/*
int main() {
int n, q;
cin >> n;
Graph g(n);
for (int i = 0; i < n; ++i) {
int k, c;
cin >> k;
while (k--) {
cin >> c;
add_edge(g, i, c);
}
}
LCA lca(g, 0);
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
cout << lca.query(u, v) << endl;
}
return 0;
}
*/
<|endoftext|>
|
<commit_before><commit_msg>deleted helloWorld.cpp<commit_after><|endoftext|>
|
<commit_before>#include <iostream>
using namespace std;
int main() {
cout << "Hello World" << endl; //Print out Hello World
cout << "Aaron Skomra" << endl; //Edit Hello World to print out your name
//Printing "David Snyder" to the command line
cout << "David Snyder" << endl;
cout << "Ben Huddle" << endl; // Printing out Ben Huddle
// This is a change I've made
cout << "Jess VanDerwalker" << endl;
return 0;
}
<commit_msg>A change on head<commit_after>#include <iostream>
using namespace std;
int main() {
cout << "Hello World" << endl; //Print out Hello World
cout << "Aaron Skomra" << endl; //Edit Hello World to print out your name
//Printing "David Snyder" to the command line
cout << "David Snyder" << endl;
cout << "Ben Huddle" << endl; // Printing out Ben Huddle
// Okay, this one really is on the head
cout << "Here is another change" << endl;
// This is a change I've made
cout << "Jess VanDerwalker" << endl;
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2008-2011 The QXmpp developers
*
* Author:
* Jeremy Lainé
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include <QDomElement>
#include "QXmppConstants.h"
#include "QXmppStreamFeatures.h"
QXmppStreamFeatures::QXmppStreamFeatures()
: m_bindMode(Disabled),
m_sessionMode(Disabled),
m_nonSaslAuthMode(Disabled),
m_tlsMode(Disabled)
{
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::bindMode() const
{
return m_bindMode;
}
void QXmppStreamFeatures::setBindMode(QXmppStreamFeatures::Mode mode)
{
m_bindMode = mode;
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::sessionMode() const
{
return m_sessionMode;
}
void QXmppStreamFeatures::setSessionMode(Mode mode)
{
m_sessionMode = mode;
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::nonSaslAuthMode() const
{
return m_nonSaslAuthMode;
}
void QXmppStreamFeatures::setNonSaslAuthMode(QXmppStreamFeatures::Mode mode)
{
m_nonSaslAuthMode = mode;
}
QList<QXmppConfiguration::SASLAuthMechanism> QXmppStreamFeatures::authMechanisms() const
{
return m_authMechanisms;
}
void QXmppStreamFeatures::setAuthMechanisms(QList<QXmppConfiguration::SASLAuthMechanism> &mechanisms)
{
m_authMechanisms = mechanisms;
}
QList<QXmppConfiguration::CompressionMethod> QXmppStreamFeatures::compressionMethods() const
{
return m_compressionMethods;
}
void QXmppStreamFeatures::setCompressionMethods(QList<QXmppConfiguration::CompressionMethod> &methods)
{
m_compressionMethods = methods;
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::tlsMode() const
{
return m_tlsMode;
}
void QXmppStreamFeatures::setTlsMode(QXmppStreamFeatures::Mode mode)
{
m_tlsMode = mode;
}
bool QXmppStreamFeatures::isStreamFeatures(const QDomElement &element)
{
return element.namespaceURI() == ns_stream &&
element.tagName() == "features";
}
static QXmppStreamFeatures::Mode readFeature(const QDomElement &element, const char *tagName, const char *tagNs)
{
QDomElement subElement = element.firstChildElement(tagName);
if (subElement.namespaceURI() == tagNs)
{
if (!subElement.firstChildElement("required").isNull())
return QXmppStreamFeatures::Required;
else
return QXmppStreamFeatures::Enabled;
} else {
return QXmppStreamFeatures::Disabled;
}
}
void QXmppStreamFeatures::parse(const QDomElement &element)
{
m_bindMode = readFeature(element, "bind", ns_bind);
m_sessionMode = readFeature(element, "session", ns_session);
m_nonSaslAuthMode = readFeature(element, "auth", ns_authFeature);
m_tlsMode = readFeature(element, "starttls", ns_tls);
// parse advertised compression methods
QDomElement compression = element.firstChildElement("compression");
if (compression.namespaceURI() == ns_compressFeature)
{
QDomElement subElement = compression.firstChildElement("method");
while(!subElement.isNull())
{
if (subElement.text() == QLatin1String("zlib"))
m_compressionMethods << QXmppConfiguration::ZlibCompression;
subElement = subElement.nextSiblingElement("method");
}
}
// parse advertised SASL Authentication mechanisms
QDomElement mechs = element.firstChildElement("mechanisms");
if (mechs.namespaceURI() == ns_sasl)
{
QDomElement subElement = mechs.firstChildElement("mechanism");
while(!subElement.isNull())
{
if (subElement.text() == QLatin1String("PLAIN"))
m_authMechanisms << QXmppConfiguration::SASLPlain;
else if (subElement.text() == QLatin1String("DIGEST-MD5"))
m_authMechanisms << QXmppConfiguration::SASLDigestMD5;
else if (subElement.text() == QLatin1String("ANONYMOUS"))
m_authMechanisms << QXmppConfiguration::SASLAnonymous;
subElement = subElement.nextSiblingElement("mechanism");
}
}
}
static void writeFeature(QXmlStreamWriter *writer, const char *tagName, const char *tagNs, QXmppStreamFeatures::Mode mode)
{
if (mode != QXmppStreamFeatures::Disabled)
{
writer->writeStartElement(tagName);
writer->writeAttribute("xmlns", tagNs);
if (mode == QXmppStreamFeatures::Required)
writer->writeEmptyElement("required");
writer->writeEndElement();
}
}
void QXmppStreamFeatures::toXml(QXmlStreamWriter *writer) const
{
writer->writeStartElement("stream:features");
writeFeature(writer, "bind", ns_bind, m_bindMode);
writeFeature(writer, "session", ns_session, m_sessionMode);
writeFeature(writer, "auth", ns_authFeature, m_nonSaslAuthMode);
writeFeature(writer, "starttls", ns_tls, m_tlsMode);
if (!m_compressionMethods.isEmpty())
{
writer->writeStartElement("compression");
writer->writeAttribute("xmlns", ns_compressFeature);
for (int i = 0; i < m_compressionMethods.size(); i++)
{
writer->writeStartElement("method");
switch (m_compressionMethods[i])
{
case QXmppConfiguration::ZlibCompression:
writer->writeCharacters("zlib");
break;
}
writer->writeEndElement();
}
writer->writeEndElement();
}
if (!m_authMechanisms.isEmpty())
{
writer->writeStartElement("mechanisms");
writer->writeAttribute("xmlns", ns_sasl);
for (int i = 0; i < m_authMechanisms.size(); i++)
{
writer->writeStartElement("mechanism");
switch (m_authMechanisms[i])
{
case QXmppConfiguration::SASLPlain:
writer->writeCharacters("PLAIN");
break;
case QXmppConfiguration::SASLDigestMD5:
writer->writeCharacters("DIGEST-MD5");
break;
case QXmppConfiguration::SASLAnonymous:
writer->writeCharacters("ANONYMOUS");
break;
}
writer->writeEndElement();
}
writer->writeEndElement();
}
writer->writeEndElement();
}
<commit_msg>recognise X-FACEBOOK-PLATFORM in stream features<commit_after>/*
* Copyright (C) 2008-2011 The QXmpp developers
*
* Author:
* Jeremy Lainé
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include <QDomElement>
#include "QXmppConstants.h"
#include "QXmppStreamFeatures.h"
QXmppStreamFeatures::QXmppStreamFeatures()
: m_bindMode(Disabled),
m_sessionMode(Disabled),
m_nonSaslAuthMode(Disabled),
m_tlsMode(Disabled)
{
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::bindMode() const
{
return m_bindMode;
}
void QXmppStreamFeatures::setBindMode(QXmppStreamFeatures::Mode mode)
{
m_bindMode = mode;
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::sessionMode() const
{
return m_sessionMode;
}
void QXmppStreamFeatures::setSessionMode(Mode mode)
{
m_sessionMode = mode;
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::nonSaslAuthMode() const
{
return m_nonSaslAuthMode;
}
void QXmppStreamFeatures::setNonSaslAuthMode(QXmppStreamFeatures::Mode mode)
{
m_nonSaslAuthMode = mode;
}
QList<QXmppConfiguration::SASLAuthMechanism> QXmppStreamFeatures::authMechanisms() const
{
return m_authMechanisms;
}
void QXmppStreamFeatures::setAuthMechanisms(QList<QXmppConfiguration::SASLAuthMechanism> &mechanisms)
{
m_authMechanisms = mechanisms;
}
QList<QXmppConfiguration::CompressionMethod> QXmppStreamFeatures::compressionMethods() const
{
return m_compressionMethods;
}
void QXmppStreamFeatures::setCompressionMethods(QList<QXmppConfiguration::CompressionMethod> &methods)
{
m_compressionMethods = methods;
}
QXmppStreamFeatures::Mode QXmppStreamFeatures::tlsMode() const
{
return m_tlsMode;
}
void QXmppStreamFeatures::setTlsMode(QXmppStreamFeatures::Mode mode)
{
m_tlsMode = mode;
}
bool QXmppStreamFeatures::isStreamFeatures(const QDomElement &element)
{
return element.namespaceURI() == ns_stream &&
element.tagName() == "features";
}
static QXmppStreamFeatures::Mode readFeature(const QDomElement &element, const char *tagName, const char *tagNs)
{
QDomElement subElement = element.firstChildElement(tagName);
if (subElement.namespaceURI() == tagNs)
{
if (!subElement.firstChildElement("required").isNull())
return QXmppStreamFeatures::Required;
else
return QXmppStreamFeatures::Enabled;
} else {
return QXmppStreamFeatures::Disabled;
}
}
void QXmppStreamFeatures::parse(const QDomElement &element)
{
m_bindMode = readFeature(element, "bind", ns_bind);
m_sessionMode = readFeature(element, "session", ns_session);
m_nonSaslAuthMode = readFeature(element, "auth", ns_authFeature);
m_tlsMode = readFeature(element, "starttls", ns_tls);
// parse advertised compression methods
QDomElement compression = element.firstChildElement("compression");
if (compression.namespaceURI() == ns_compressFeature)
{
QDomElement subElement = compression.firstChildElement("method");
while(!subElement.isNull())
{
if (subElement.text() == QLatin1String("zlib"))
m_compressionMethods << QXmppConfiguration::ZlibCompression;
subElement = subElement.nextSiblingElement("method");
}
}
// parse advertised SASL Authentication mechanisms
QDomElement mechs = element.firstChildElement("mechanisms");
if (mechs.namespaceURI() == ns_sasl)
{
QDomElement subElement = mechs.firstChildElement("mechanism");
while(!subElement.isNull())
{
if (subElement.text() == QLatin1String("PLAIN"))
m_authMechanisms << QXmppConfiguration::SASLPlain;
else if (subElement.text() == QLatin1String("DIGEST-MD5"))
m_authMechanisms << QXmppConfiguration::SASLDigestMD5;
else if (subElement.text() == QLatin1String("ANONYMOUS"))
m_authMechanisms << QXmppConfiguration::SASLAnonymous;
else if (subElement.text() == QLatin1String("X-FACEBOOK-PLATFORM"))
m_authMechanisms << QXmppConfiguration::SASLXFacebookPlatform;
subElement = subElement.nextSiblingElement("mechanism");
}
}
}
static void writeFeature(QXmlStreamWriter *writer, const char *tagName, const char *tagNs, QXmppStreamFeatures::Mode mode)
{
if (mode != QXmppStreamFeatures::Disabled)
{
writer->writeStartElement(tagName);
writer->writeAttribute("xmlns", tagNs);
if (mode == QXmppStreamFeatures::Required)
writer->writeEmptyElement("required");
writer->writeEndElement();
}
}
void QXmppStreamFeatures::toXml(QXmlStreamWriter *writer) const
{
writer->writeStartElement("stream:features");
writeFeature(writer, "bind", ns_bind, m_bindMode);
writeFeature(writer, "session", ns_session, m_sessionMode);
writeFeature(writer, "auth", ns_authFeature, m_nonSaslAuthMode);
writeFeature(writer, "starttls", ns_tls, m_tlsMode);
if (!m_compressionMethods.isEmpty())
{
writer->writeStartElement("compression");
writer->writeAttribute("xmlns", ns_compressFeature);
for (int i = 0; i < m_compressionMethods.size(); i++)
{
writer->writeStartElement("method");
switch (m_compressionMethods[i])
{
case QXmppConfiguration::ZlibCompression:
writer->writeCharacters("zlib");
break;
}
writer->writeEndElement();
}
writer->writeEndElement();
}
if (!m_authMechanisms.isEmpty())
{
writer->writeStartElement("mechanisms");
writer->writeAttribute("xmlns", ns_sasl);
for (int i = 0; i < m_authMechanisms.size(); i++)
{
writer->writeStartElement("mechanism");
switch (m_authMechanisms[i])
{
case QXmppConfiguration::SASLPlain:
writer->writeCharacters("PLAIN");
break;
case QXmppConfiguration::SASLDigestMD5:
writer->writeCharacters("DIGEST-MD5");
break;
case QXmppConfiguration::SASLAnonymous:
writer->writeCharacters("ANONYMOUS");
break;
case QXmppConfiguration::SASLXFacebookPlatform:
writer->writeCharacters("X-FACEBOOK-PLATFORM");
break;
}
writer->writeEndElement();
}
writer->writeEndElement();
}
writer->writeEndElement();
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE calculator_test
#include "../../include/votca/tools/calculator.h"
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <fstream>
using namespace ::votca;
BOOST_AUTO_TEST_SUITE(calculator_test)
BOOST_AUTO_TEST_CASE(load_defaults_test) {
class TestCalc : public tools::Calculator {
public:
std::string Identify() override { return "testcalc"; }
void Initialize(const tools::Property &user_options) override {
// Create folder for test
const char dir_path[] = "calculators";
boost::filesystem::path dir(dir_path);
boost::filesystem::create_directory(dir);
dir.append("xml");
boost::filesystem::create_directory(dir);
std::ofstream defaults("calculators/xml/testcalc.xml");
defaults
<< "<options>\n"
<< "<testcalc>\n"
<< "<option0 default=\"foo\" choices=\"foo,bar\"></option0>\n"
<< "<option1 default=\"0\" choices=\"int+\"></option1>\n"
<< "<option2 default=\"-3.141592\" choices=\"float\"></option2>\n"
<< "<option4 default=\"3.141592\" choices=\"float+\"></option4>\n"
<< "<option5 default=\"true\" choices=\"bool\"></option5>\n"
<< "<option6 default=\"1,3\" choices=\"[1,2,3]\"></option6>\n"
<< "<option7>\n"
<< "<option71 default=\"none\" choices=\"some,none\"></option71>\n"
<< "</option7>\n"
<< "</testcalc>\n"
<< "</options>";
defaults.close();
// Load and check the options
tools::Property final_opt =
LoadDefaultsAndUpdateWithUserOptions("calculators", user_options);
std::string prop0 = final_opt.get("option0").as<std::string>();
Index prop1 = final_opt.get("option1").as<votca::Index>();
double prop2 = final_opt.get("option2").as<double>();
std::string prop3 = final_opt.get("option3.nested").as<std::string>();
double prop4 = final_opt.get("option4").as<double>();
bool prop5 = final_opt.get("option5").as<bool>();
std::string prop6 = final_opt.get("option6").as<std::string>();
const tools::Property &prop7 = final_opt.get("option7");
std::string prop71 = prop7.get("option71").as<std::string>();
Index prop8 = final_opt.get("option8").as<Index>();
BOOST_CHECK_EQUAL(prop0, "foo");
BOOST_CHECK_EQUAL(prop1, 42);
BOOST_CHECK_CLOSE(prop2, -3.141592, 0.00001);
BOOST_CHECK_EQUAL(prop3, "nested_value");
BOOST_CHECK_CLOSE(prop4, 3.141592, 0.00001);
BOOST_CHECK_EQUAL(prop5, true);
BOOST_CHECK_EQUAL(prop6, "1,3");
BOOST_CHECK_EQUAL(prop71, "none");
BOOST_CHECK_EQUAL(prop8, 8);
}
};
setenv("VOTCASHARE", ".", 1);
char buff[FILENAME_MAX];
std::cout << "WARNING: the VOTCASHARE env. variable has been updated to "
<< getcwd(buff, FILENAME_MAX) << "\n";
// Generate user options
tools::Property user_options;
tools::Property &opt = user_options.add("options", "");
tools::Property &opt_test = opt.add("testcalc", "");
opt_test.add("option1", "42");
tools::Property &new_prop = opt_test.add("option3", "");
new_prop.add("nested", "nested_value");
new_prop = opt_test.add("option8", "8");
TestCalc test_calc;
test_calc.Initialize(user_options);
}
BOOST_AUTO_TEST_CASE(test_choices) {
class TestChoices : public tools::Calculator {
std::string _line;
public:
std::string Identify() override { return "testchoices"; }
void SetOption(const std::string &line) { _line = line; }
void Initialize(const tools::Property &user_options) override {
// Create folder for test
const char dir_path[] = "calculators";
boost::filesystem::path dir(dir_path);
boost::filesystem::create_directory(dir);
dir.append("xml");
boost::filesystem::create_directory(dir);
std::ofstream defaults("calculators/xml/testchoices.xml");
defaults << "<options>\n"
<< "<testchoices>\n"
<< _line << "</testchoices>\n"
<< "</options>";
defaults.close();
// Load and check the options
tools::Property final_opt =
LoadDefaultsAndUpdateWithUserOptions("calculators", user_options);
std::cout << final_opt << "\n";
}
};
setenv("VOTCASHARE", ".", 1);
char buff[FILENAME_MAX];
std::cout << "WARNING: the VOTCASHARE env. variable has been updated to "
<< getcwd(buff, FILENAME_MAX) << "\n";
// Generate user options
tools::Property user_options;
tools::Property &opt = user_options.add("options", "");
opt.add("testchoices", "");
TestChoices test1, test2, test3, test4, test5, test6;
test1.SetOption("<option1 choices=\"foo, bar, baz, qux\">boom</option1>\n");
test2.SetOption("<option2 choices =\"float\">some</option2>\n");
test3.SetOption("<option3 choices=\"int\">3.14</option3>\n");
test4.SetOption("<option4 choices=\"int+\">-2</option4>\n");
test5.SetOption("<option5 choices=\"float+\">-3.14</option5>\n");
test6.SetOption("<option6 choices=\"[foo,bar,qux]\">tux</option6>\n");
BOOST_CHECK_THROW(test1.Initialize(user_options), std::runtime_error);
BOOST_CHECK_THROW(test2.Initialize(user_options), std::runtime_error);
BOOST_CHECK_THROW(test3.Initialize(user_options), std::runtime_error);
BOOST_CHECK_THROW(test4.Initialize(user_options), std::runtime_error);
BOOST_CHECK_THROW(test5.Initialize(user_options), std::runtime_error);
BOOST_CHECK_THROW(test6.Initialize(user_options), std::runtime_error);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>add another test #242<commit_after>/*
* Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE calculator_test
#include "../../include/votca/tools/calculator.h"
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <fstream>
using namespace ::votca;
BOOST_AUTO_TEST_SUITE(calculator_test)
BOOST_AUTO_TEST_CASE(load_defaults_test) {
class TestCalc : public tools::Calculator {
public:
std::string Identify() override { return "testcalc"; }
void Initialize(const tools::Property &user_options) override {
// Create folder for test
const char dir_path[] = "calculators";
boost::filesystem::path dir(dir_path);
boost::filesystem::create_directory(dir);
dir.append("xml");
boost::filesystem::create_directory(dir);
std::ofstream defaults("calculators/xml/testcalc.xml");
defaults
<< "<options>\n"
<< "<testcalc>\n"
<< "<option0 default=\"foo\" choices=\"foo,bar\"></option0>\n"
<< "<option1 default=\"0\" choices=\"int+\"></option1>\n"
<< "<option2 default=\"-3.141592\" choices=\"float\"></option2>\n"
<< "<option4 default=\"3.141592\" choices=\"float+\"></option4>\n"
<< "<option5 default=\"true\" choices=\"bool\"></option5>\n"
<< "<option6 default=\"1,3\" choices=\"[1,2,3]\"></option6>\n"
<< "<option7>\n"
<< "<option71 default=\"none\" choices=\"some,none\"></option71>\n"
<< "</option7>\n"
<< "<option8 default=\"8\" choices=\"int+\"></option8>\n"
<< "</testcalc>\n"
<< "</options>";
defaults.close();
// Load and check the options
tools::Property final_opt =
LoadDefaultsAndUpdateWithUserOptions("calculators", user_options);
std::string prop0 = final_opt.get("option0").as<std::string>();
Index prop1 = final_opt.get("option1").as<votca::Index>();
double prop2 = final_opt.get("option2").as<double>();
std::string prop3 = final_opt.get("option3.nested").as<std::string>();
double prop4 = final_opt.get("option4").as<double>();
bool prop5 = final_opt.get("option5").as<bool>();
std::string prop6 = final_opt.get("option6").as<std::string>();
const tools::Property &prop7 = final_opt.get("option7");
std::string prop71 = prop7.get("option71").as<std::string>();
Index prop9 = final_opt.get("option9").as<Index>();
BOOST_CHECK_EQUAL(prop0, "foo");
BOOST_CHECK_EQUAL(prop1, 42);
BOOST_CHECK_CLOSE(prop2, -3.141592, 0.00001);
BOOST_CHECK_EQUAL(prop3, "nested_value");
BOOST_CHECK_CLOSE(prop4, 3.141592, 0.00001);
BOOST_CHECK_EQUAL(prop5, true);
BOOST_CHECK_EQUAL(prop6, "1,3");
BOOST_CHECK_EQUAL(prop71, "none");
BOOST_CHECK_EQUAL(prop8, 8);
BOOST_CHECK_EQUAL(prop9, 9);
}
};
setenv("VOTCASHARE", ".", 1);
char buff[FILENAME_MAX];
std::cout << "WARNING: the VOTCASHARE env. variable has been updated to "
<< getcwd(buff, FILENAME_MAX) << "\n";
// Generate user options
tools::Property user_options;
tools::Property &opt = user_options.add("options", "");
tools::Property &opt_test = opt.add("testcalc", "");
opt_test.add("option1", "42");
tools::Property &new_prop = opt_test.add("option3", "");
new_prop.add("nested", "nested_value");
opt_test.add("option8", "");
opt_test.add("option9", "9");
TestCalc test_calc;
test_calc.Initialize(user_options);
}
BOOST_AUTO_TEST_CASE(test_choices) {
class TestChoices : public tools::Calculator {
std::string _line;
public:
std::string Identify() override { return "testchoices"; }
void SetOption(const std::string &line) { _line = line; }
void Initialize(const tools::Property &user_options) override {
// Create folder for test
const char dir_path[] = "calculators";
boost::filesystem::path dir(dir_path);
boost::filesystem::create_directory(dir);
dir.append("xml");
boost::filesystem::create_directory(dir);
std::ofstream defaults("calculators/xml/testchoices.xml");
defaults << "<options>\n"
<< "<testchoices>\n"
<< _line << "</testchoices>\n"
<< "</options>";
defaults.close();
// Load and check the options
tools::Property final_opt =
LoadDefaultsAndUpdateWithUserOptions("calculators", user_options);
std::cout << final_opt << "\n";
}
};
setenv("VOTCASHARE", ".", 1);
char buff[FILENAME_MAX];
std::cout << "WARNING: the VOTCASHARE env. variable has been updated to "
<< getcwd(buff, FILENAME_MAX) << "\n";
// Generate user options
tools::Property user_options;
tools::Property &opt = user_options.add("options", "");
opt.add("testchoices", "");
TestChoices test1, test2, test3, test4, test5, test6;
test1.SetOption("<option1 choices=\"foo, bar, baz, qux\">boom</option1>\n");
test2.SetOption("<option2 choices =\"float\">some</option2>\n");
test3.SetOption("<option3 choices=\"int\">3.14</option3>\n");
test4.SetOption("<option4 choices=\"int+\">-2</option4>\n");
test5.SetOption("<option5 choices=\"float+\">-3.14</option5>\n");
test6.SetOption("<option6 choices=\"[foo,bar,qux]\">tux</option6>\n");
BOOST_CHECK_THROW(test1.Initialize(user_options), std::runtime_error);
BOOST_CHECK_THROW(test2.Initialize(user_options), std::runtime_error);
BOOST_CHECK_THROW(test3.Initialize(user_options), std::runtime_error);
BOOST_CHECK_THROW(test4.Initialize(user_options), std::runtime_error);
BOOST_CHECK_THROW(test5.Initialize(user_options), std::runtime_error);
BOOST_CHECK_THROW(test6.Initialize(user_options), std::runtime_error);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#if defined(_MSC_VER)
#pragma warning(4:4503)
#endif
#include "KeyManager.h"
#include <assert.h>
#include <ctype.h>
// initialize the singleton
template <>
KeyManager* Singleton<KeyManager>::_instance = (KeyManager*)0;
const char* KeyManager::buttonNames[] = {
"???",
"Pause",
"Home",
"End",
"Left Arrow",
"Right Arrow",
"Up Arrow",
"Down Arrow",
"Page Up",
"Page Down",
"Insert",
"Delete",
"F1",
"F2",
"F3",
"F4",
"F5",
"F6",
"F7",
"F8",
"F9",
"F10",
"F11",
"F12",
"Left Mouse",
"Middle Mouse",
"Right Mouse"
};
const char* KeyManager::asciiNames[][2] = {
{ "Tab", "\t" },
{ "Backspace", "\b" },
{ "Enter", "\r" },
{ "Space", " " }
};
KeyManager::KeyManager()
{
unsigned int i;
// prep string to key map
BzfKeyEvent key;
key.ascii = 0;
key.shift = 0;
for (i = BzfKeyEvent::Pause; i <= BzfKeyEvent::RightMouse; ++i) {
key.button = static_cast<BzfKeyEvent::Button>(i);
stringToEvent.insert(std::make_pair(std::string(buttonNames[i]), key));
}
key.button = BzfKeyEvent::NoButton;
for (i = 0; i < countof(asciiNames); ++i) {
key.ascii = asciiNames[i][1][0];
stringToEvent.insert(std::make_pair(std::string(asciiNames[i][0]), key));
}
char buffer[2];
buffer[1] = 0;
for (i = 0x21; i < 0x7f; ++i) {
buffer[0] = key.ascii = static_cast<char>(i);
stringToEvent.insert(std::make_pair(std::string(buffer), key));
}
}
KeyManager::~KeyManager()
{
}
void KeyManager::bind(const BzfKeyEvent& key,
bool press, const std::string& cmd)
{
if (press) {
pressEventToCommand.erase(key);
pressEventToCommand.insert(std::make_pair(key, cmd));
} else {
releaseEventToCommand.erase(key);
releaseEventToCommand.insert(std::make_pair(key, cmd));
}
notify(key, press, cmd);
}
void KeyManager::unbind(const BzfKeyEvent& key,
bool press)
{
if (press)
pressEventToCommand.erase(key);
else
releaseEventToCommand.erase(key);
notify(key, press, "");
}
std::string KeyManager::get(const BzfKeyEvent& key,
bool press) const
{
const EventToCommandMap* map = press ? &pressEventToCommand :
&releaseEventToCommand;
EventToCommandMap::const_iterator index = map->find(key);
if (index == map->end())
return "";
else
return index->second;
}
std::vector<std::string> KeyManager::getKeysFromCommand(std::string command, bool press) const
{
std::vector<std::string> keys;
EventToCommandMap::const_iterator index;
if (press) {
for (index = pressEventToCommand.begin(); index != pressEventToCommand.end(); ++index) {
if (index->second == command) {
keys.push_back(this->keyEventToString(index->first));
}
}
} else {
for (index = releaseEventToCommand.begin(); index != releaseEventToCommand.end(); ++index) {
if (index->second == command) {
keys.push_back(this->keyEventToString(index->first));
}
}
}
return keys;
}
std::string KeyManager::keyEventToString(
const BzfKeyEvent& key) const
{
std::string name;
if (key.shift & BzfKeyEvent::ShiftKey)
name += "Shift+";
if (key.shift & BzfKeyEvent::ControlKey)
name += "Ctrl+";
if (key.shift & BzfKeyEvent::AltKey)
name += "Alt+";
switch (key.ascii) {
case 0:
return name + buttonNames[key.button];
case '\b':
return name + "Backspace";
case '\t':
return name + "Tab";
case '\r':
return name + "Enter";
case ' ':
return name + "Space";
default:
if (!isspace(key.ascii))
return name + std::string(&key.ascii, 1);
return name + "???";
}
}
bool KeyManager::stringToKeyEvent(
const std::string& name, BzfKeyEvent& key) const
{
// find last + in name
const char* shiftDelimiter = strrchr(name.c_str(), '+');
// split name into shift part and key name part
std::string shiftPart, keyPart;
if (shiftDelimiter == NULL) {
keyPart = name;
} else {
shiftPart = "+";
shiftPart += name.substr(0, shiftDelimiter - name.c_str() + 1);
keyPart = shiftDelimiter + 1;
}
// find key name
StringToEventMap::const_iterator index = stringToEvent.find(keyPart);
if (index == stringToEvent.end())
return false;
// get key event sans shift state
key = index->second;
// apply shift state
if (strstr(shiftPart.c_str(), "+Shift+") != NULL ||
strstr(shiftPart.c_str(), "+shift+") != NULL)
key.shift |= BzfKeyEvent::ShiftKey;
if (strstr(shiftPart.c_str(), "+Ctrl+") != NULL ||
strstr(shiftPart.c_str(), "+ctrl+") != NULL)
key.shift |= BzfKeyEvent::ControlKey;
if (strstr(shiftPart.c_str(), "+Alt+") != NULL ||
strstr(shiftPart.c_str(), "+alt+") != NULL)
key.shift |= BzfKeyEvent::AltKey;
// success
return true;
}
void KeyManager::iterate(
IterateCallback callback, void* userData)
{
assert(callback != NULL);
EventToCommandMap::const_iterator index;
for (index = pressEventToCommand.begin(); index != pressEventToCommand.end(); ++index)
(*callback)(keyEventToString(index->first), true, index->second, userData);
for (index = releaseEventToCommand.begin(); index != releaseEventToCommand.end(); ++index)
(*callback)(keyEventToString(index->first), false, index->second, userData);
}
void KeyManager::addCallback(
ChangeCallback callback, void* userData)
{
callbacks.add(callback, userData);
}
void KeyManager::removeCallback(
ChangeCallback callback, void* userData)
{
callbacks.remove(callback, userData);
}
void KeyManager::notify(
const BzfKeyEvent& key,
bool press, const std::string& cmd)
{
CallbackInfo info;
info.name = keyEventToString(key);
info.press = press;
info.cmd = cmd;
callbacks.iterate(&onCallback, &info);
}
bool KeyManager::onCallback(
ChangeCallback callback,
void* userData,
void* vinfo)
{
CallbackInfo* info = reinterpret_cast<CallbackInfo*>(vinfo);
callback(info->name, info->press, info->cmd, userData);
return true;
}
bool KeyManager::KeyEventLess::operator()(
const BzfKeyEvent& a,
const BzfKeyEvent& b) const
{
if (a.ascii == 0 && b.ascii == 0) {
if (a.button < b.button)
return true;
if (a.button > b.button)
return false;
// check shift
if (a.shift < b.shift)
return true;
} else if (a.ascii == 0 && b.ascii != 0) {
return true;
} else if (a.ascii != 0 && b.ascii == 0) {
return false;
} else {
if (toupper(a.ascii) < toupper(b.ascii))
return true;
if (toupper(a.ascii) > toupper(b.ascii))
return false;
// check shift state without shift key
if ((a.shift & ~BzfKeyEvent::ShiftKey) < (b.shift & ~BzfKeyEvent::ShiftKey))
return true;
}
return false;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Initialize the joystick buttons, add names for them.<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#if defined(_MSC_VER)
#pragma warning(4:4503)
#endif
#include "KeyManager.h"
#include <assert.h>
#include <ctype.h>
// initialize the singleton
template <>
KeyManager* Singleton<KeyManager>::_instance = (KeyManager*)0;
const char* KeyManager::buttonNames[] = {
"???",
"Pause",
"Home",
"End",
"Left Arrow",
"Right Arrow",
"Up Arrow",
"Down Arrow",
"Page Up",
"Page Down",
"Insert",
"Delete",
"F1",
"F2",
"F3",
"F4",
"F5",
"F6",
"F7",
"F8",
"F9",
"F10",
"F11",
"F12",
"Left Mouse",
"Middle Mouse",
"Right Mouse",
"Joystick Button 27",
"Joystick Button 28",
"Joystick Button 29",
"Joystick Button 30",
"Joystick Button 31",
"Joystick Button 32",
"Joystick Button 33"
};
const char* KeyManager::asciiNames[][2] = {
{ "Tab", "\t" },
{ "Backspace", "\b" },
{ "Enter", "\r" },
{ "Space", " " }
};
KeyManager::KeyManager()
{
unsigned int i;
// prep string to key map
BzfKeyEvent key;
key.ascii = 0;
key.shift = 0;
for (i = BzfKeyEvent::Pause; i <= BzfKeyEvent::Tab; ++i) {
key.button = static_cast<BzfKeyEvent::Button>(i);
stringToEvent.insert(std::make_pair(std::string(buttonNames[i]), key));
}
key.button = BzfKeyEvent::NoButton;
for (i = 0; i < countof(asciiNames); ++i) {
key.ascii = asciiNames[i][1][0];
stringToEvent.insert(std::make_pair(std::string(asciiNames[i][0]), key));
}
char buffer[2];
buffer[1] = 0;
for (i = 0x21; i < 0x7f; ++i) {
buffer[0] = key.ascii = static_cast<char>(i);
stringToEvent.insert(std::make_pair(std::string(buffer), key));
}
}
KeyManager::~KeyManager()
{
}
void KeyManager::bind(const BzfKeyEvent& key,
bool press, const std::string& cmd)
{
if (press) {
pressEventToCommand.erase(key);
pressEventToCommand.insert(std::make_pair(key, cmd));
} else {
releaseEventToCommand.erase(key);
releaseEventToCommand.insert(std::make_pair(key, cmd));
}
notify(key, press, cmd);
}
void KeyManager::unbind(const BzfKeyEvent& key,
bool press)
{
if (press)
pressEventToCommand.erase(key);
else
releaseEventToCommand.erase(key);
notify(key, press, "");
}
std::string KeyManager::get(const BzfKeyEvent& key,
bool press) const
{
const EventToCommandMap* map = press ? &pressEventToCommand :
&releaseEventToCommand;
EventToCommandMap::const_iterator index = map->find(key);
if (index == map->end())
return "";
else
return index->second;
}
std::vector<std::string> KeyManager::getKeysFromCommand(std::string command, bool press) const
{
std::vector<std::string> keys;
EventToCommandMap::const_iterator index;
if (press) {
for (index = pressEventToCommand.begin(); index != pressEventToCommand.end(); ++index) {
if (index->second == command) {
keys.push_back(this->keyEventToString(index->first));
}
}
} else {
for (index = releaseEventToCommand.begin(); index != releaseEventToCommand.end(); ++index) {
if (index->second == command) {
keys.push_back(this->keyEventToString(index->first));
}
}
}
return keys;
}
std::string KeyManager::keyEventToString(
const BzfKeyEvent& key) const
{
std::string name;
if (key.shift & BzfKeyEvent::ShiftKey)
name += "Shift+";
if (key.shift & BzfKeyEvent::ControlKey)
name += "Ctrl+";
if (key.shift & BzfKeyEvent::AltKey)
name += "Alt+";
switch (key.ascii) {
case 0:
return name + buttonNames[key.button];
case '\b':
return name + "Backspace";
case '\t':
return name + "Tab";
case '\r':
return name + "Enter";
case ' ':
return name + "Space";
default:
if (!isspace(key.ascii))
return name + std::string(&key.ascii, 1);
return name + "???";
}
}
bool KeyManager::stringToKeyEvent(
const std::string& name, BzfKeyEvent& key) const
{
// find last + in name
const char* shiftDelimiter = strrchr(name.c_str(), '+');
// split name into shift part and key name part
std::string shiftPart, keyPart;
if (shiftDelimiter == NULL) {
keyPart = name;
} else {
shiftPart = "+";
shiftPart += name.substr(0, shiftDelimiter - name.c_str() + 1);
keyPart = shiftDelimiter + 1;
}
// find key name
StringToEventMap::const_iterator index = stringToEvent.find(keyPart);
if (index == stringToEvent.end())
return false;
// get key event sans shift state
key = index->second;
// apply shift state
if (strstr(shiftPart.c_str(), "+Shift+") != NULL ||
strstr(shiftPart.c_str(), "+shift+") != NULL)
key.shift |= BzfKeyEvent::ShiftKey;
if (strstr(shiftPart.c_str(), "+Ctrl+") != NULL ||
strstr(shiftPart.c_str(), "+ctrl+") != NULL)
key.shift |= BzfKeyEvent::ControlKey;
if (strstr(shiftPart.c_str(), "+Alt+") != NULL ||
strstr(shiftPart.c_str(), "+alt+") != NULL)
key.shift |= BzfKeyEvent::AltKey;
// success
return true;
}
void KeyManager::iterate(
IterateCallback callback, void* userData)
{
assert(callback != NULL);
EventToCommandMap::const_iterator index;
for (index = pressEventToCommand.begin(); index != pressEventToCommand.end(); ++index)
(*callback)(keyEventToString(index->first), true, index->second, userData);
for (index = releaseEventToCommand.begin(); index != releaseEventToCommand.end(); ++index)
(*callback)(keyEventToString(index->first), false, index->second, userData);
}
void KeyManager::addCallback(
ChangeCallback callback, void* userData)
{
callbacks.add(callback, userData);
}
void KeyManager::removeCallback(
ChangeCallback callback, void* userData)
{
callbacks.remove(callback, userData);
}
void KeyManager::notify(
const BzfKeyEvent& key,
bool press, const std::string& cmd)
{
CallbackInfo info;
info.name = keyEventToString(key);
info.press = press;
info.cmd = cmd;
callbacks.iterate(&onCallback, &info);
}
bool KeyManager::onCallback(
ChangeCallback callback,
void* userData,
void* vinfo)
{
CallbackInfo* info = reinterpret_cast<CallbackInfo*>(vinfo);
callback(info->name, info->press, info->cmd, userData);
return true;
}
bool KeyManager::KeyEventLess::operator()(
const BzfKeyEvent& a,
const BzfKeyEvent& b) const
{
if (a.ascii == 0 && b.ascii == 0) {
if (a.button < b.button)
return true;
if (a.button > b.button)
return false;
// check shift
if (a.shift < b.shift)
return true;
} else if (a.ascii == 0 && b.ascii != 0) {
return true;
} else if (a.ascii != 0 && b.ascii == 0) {
return false;
} else {
if (toupper(a.ascii) < toupper(b.ascii))
return true;
if (toupper(a.ascii) > toupper(b.ascii))
return false;
// check shift state without shift key
if ((a.shift & ~BzfKeyEvent::ShiftKey) < (b.shift & ~BzfKeyEvent::ShiftKey))
return true;
}
return false;
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2003 by *
* Unai Garro (ugarro@users.sourceforge.net) *
* Cyril Bosselut (bosselut@b1project.com) *
* Jason Kivlighn (mizunoami44@users.sourceforge.net) *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "dietwizarddialog.h"
#include "DBBackend/recipedb.h"
#include "editbox.h"
#include <qheader.h>
#include <qlayout.h>
#include <qpainter.h>
#include <kapp.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <klocale.h>
DietWizardDialog::DietWizardDialog(QWidget *parent,RecipeDB *db):QVBox(parent)
{
// Initialize internal variables
database=db;
mealNumber=1;
//Design the dialog
setSpacing(10);
// Options Box
optionsBox=new QHBox(this);
sliderBox=new QVGroupBox(i18n("Meals per day"),optionsBox);
mealNumberLabel=new QLabel(sliderBox);
mealNumberLabel->setText("- 1 -");
mealNumberLabel->setAlignment(Qt::AlignHCenter);
mealNumberSelector=new QSlider(sliderBox);
mealNumberSelector->setOrientation(Qt::Horizontal);
mealNumberSelector->setRange(1,10);
mealNumberSelector->setSteps(1,1);
mealNumberSelector->setTickmarks(QSlider::Below);
mealNumberSelector->setFixedWidth(100);
// Tabs
mealTabs=new QTabWidget(this);
mealTabs->setMargin(20);
// Button bar
KIconLoader il;
buttonBox=new QHBox(this);
okButton=new QPushButton(buttonBox);
okButton->setIconSet(il.loadIconSet("button_ok", KIcon::Small));
okButton->setText(i18n("Create the diet"));
// Create Tabs
newTab(i18n("Meal 1"));
// Initialize data
reload();
// Signals & Slots
connect(mealNumberSelector,SIGNAL(valueChanged(int)),this,SLOT(changeMealNumber(int)));
}
DietWizardDialog::~DietWizardDialog()
{
}
void DietWizardDialog::reload(void)
{
database->loadCategories(&categoriesList);
database->loadProperties(&constraintList);
int pgcount=0;
for (MealInput *tab=(MealInput *) (mealTabs->page(pgcount));pgcount<mealTabs->count(); pgcount++)
tab->reload(categoriesList,constraintList);
}
void DietWizardDialog::newTab(const QString &name)
{
mealTab=new MealInput(mealTabs);
mealTab->reload(categoriesList,constraintList);
mealTabs->addTab(mealTab,name);
mealTabs->setCurrentPage(mealTabs->indexOf(mealTab));
}
void DietWizardDialog::changeMealNumber(int mn)
{
if (mn>mealNumber)
{
newTab(i18n("Meal %1").arg(mn));
mealNumber++;
mealNumberLabel->setText(QString("- %1 -").arg(mn));
}
}
class ConstraintsListItem:public QCheckListItem{
public:
ConstraintsListItem(QListView* klv, IngredientProperty *ip ):QCheckListItem(klv,QString::null,QCheckListItem::CheckBox){ ipStored=new IngredientProperty(ip);}
private:
IngredientProperty *ipStored;
public:
virtual QString text(int column) const
{
if (column==1) return(QString("0.0"));
else if (column==2) return(ipStored->name);
else if (column==3) return(QString("0.0"));
else return(QString::null);
}
~ConstraintsListItem(void)
{
delete ipStored;
}
};
class CategoriesListItem:public QCheckListItem{
public:
CategoriesListItem(QListView* klv, QString name ):QCheckListItem(klv,QString::null,QCheckListItem::CheckBox){nameStored=name;}
~CategoriesListItem(void){}
virtual QString text(int column) const
{
if (column==1) return(nameStored);
else return(QString::null);
}
private: QString nameStored;
};
MealInput::MealInput(QWidget *parent):QWidget(parent)
{
// Initialize data
categoriesListLocalCache.clear();
constraintListLocalCache.clear();
// Design the dialog
QVBoxLayout *layout=new QVBoxLayout(this);
layout->setSpacing(20);
// Options box
mealOptions=new QHBox(this);
mealOptions->setSpacing(10);
layout->addWidget(mealOptions);
// Number of dishes input
dishNumberBox=new QHBox(mealOptions); dishNumberBox->setSpacing(10);
dishNumberLabel=new QLabel(i18n("No. of dishes: "),dishNumberBox);
dishNumberInput=new QSpinBox(dishNumberBox); dishNumberInput->setMinValue(1); dishNumberInput->setMaxValue(10);
dishNumberBox->setSizePolicy(QSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum));
// Toolbar
toolBar=new QHGroupBox(mealOptions);
toolBar->setFrameStyle (QFrame::Panel | QFrame::Sunken);
toolBar->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Minimum));
// Next dish/ Previous dish buttons
KIconLoader il;
buttonPrev=new QToolButton(toolBar);
buttonPrev->setUsesTextLabel(true);
buttonPrev->setTextLabel(i18n("Previous Dish"));
buttonPrev->setIconSet(il.loadIconSet("back", KIcon::Small));
buttonPrev->setTextPosition(QToolButton::BelowIcon);
buttonNext=new QToolButton(toolBar);
buttonNext->setUsesTextLabel(true);
buttonNext->setTextLabel(i18n("Next Dish"));
buttonNext->setIconSet(il.loadIconSet("forward", KIcon::Small));
buttonNext->setTextPosition(QToolButton::BelowIcon);
// Dish widgets
dishStack= new QWidgetStack(this);
layout->addWidget(dishStack);
// Add default dishes
DishInput *newDish=new DishInput(this,i18n("1st Course")); dishStack->addWidget(newDish); dishInputList.append(newDish);
newDish=new DishInput(this,i18n("2nd Course")); dishStack->addWidget(newDish); dishInputList.append(newDish);
newDish=new DishInput(this,i18n("Dessert")); dishStack->addWidget(newDish); dishInputList.append(newDish);
dishNumber=1;
// Signals & Slots
connect(dishNumberInput,SIGNAL(valueChanged(int)),this,SLOT(changeDishNumber(int)));
connect(buttonPrev,SIGNAL(clicked()),this,SLOT(prevDish()));
connect(buttonNext,SIGNAL(clicked()),this,SLOT(nextDish()));
}
MealInput::~MealInput()
{
}
// reload from outside with new data
void MealInput::reload(ElementList &categoriesList,IngredientPropertyList &constraintList)
{
int pgcount=0;
QValueList<DishInput*>::iterator it;
categoriesListLocalCache.clear();
constraintListLocalCache.clear();
// Cache the data into the internal lists so it can be reused when creating new dishes
//Cache the possible constraints (properties) list
for (IngredientProperty *ip=constraintList.getFirst(); ip; ip=constraintList.getNext())
{
constraintListLocalCache.add(*ip);
}
//Cache the categories list
for (Element *el=categoriesList.getFirst(); el; el=categoriesList.getNext())
{
categoriesListLocalCache.add(*el);
}
reload(); //load from the cache now
}
// reload internally with the cached data
void MealInput::reload()
{
int pgcount=0;
QValueList<DishInput*>::iterator it;
for (it=dishInputList.begin(); it != dishInputList.end();it++)
{
DishInput *di; di=(*it);
di->reload(&categoriesListLocalCache,&constraintListLocalCache);
}
}
void MealInput::changeDishNumber(int dn)
{
if (dn>dishNumber)
{
DishInput *newDish=new DishInput(this,QString(i18n("Dish %1")).arg(dishNumber+1));
newDish->reload(&categoriesListLocalCache,&constraintListLocalCache);
dishStack->addWidget(newDish);
dishInputList.append(newDish);
dishStack->raiseWidget(newDish);
dishNumber++;
}
}
void MealInput::nextDish(void)
{
// First get the place of the current dish input in the list
QValueList <DishInput*>::iterator it=dishInputList.find((DishInput*)(dishStack->visibleWidget()));
//Show the next dish if it exists
it++;
if (it!=dishInputList.end())
{
dishStack->raiseWidget(*it);
}
}
void MealInput::prevDish(void)
{
// First get the place of the current dish input in the list
QValueList <DishInput*>::iterator it=dishInputList.find((DishInput*)(dishStack->visibleWidget()));
//Show the previous dish if it exists
it--;
if (it!=dishInputList.end())
{
dishStack->raiseWidget(*it);
}
}
DishInput::DishInput(QWidget* parent,const QString &title):QWidget(parent)
{
QVBoxLayout *layout=new QVBoxLayout(this);
layout->setSpacing(20);
//Horizontal Box to hold the KListView's
listBox=new QHGroupBox(i18n("Dish Characteristics"),this);
layout->addWidget(listBox);
// Dish id
dishTitle=new DishTitle(listBox,title);
//Categories list
categoriesView=new KListView(listBox);
categoriesView->addColumn("*");
categoriesView->addColumn(i18n("Category"));
//Constraints list
constraintsView=new KListView(listBox);
constraintsView->addColumn(i18n("Enabled"));
constraintsView->addColumn(i18n("Min. Value"));
constraintsView->addColumn(i18n("Property"));
constraintsView->addColumn(i18n("Max. Value"));
// KDoubleInput based edit boxes
constraintsEditBox1=new EditBox(this);
constraintsEditBox1->hide();
constraintsEditBox2=new EditBox(this);
constraintsEditBox2->hide();
// Connect Signals & Slots
connect(constraintsView,SIGNAL(executed(QListViewItem*)),this,SLOT(insertConstraintsEditBoxes(QListViewItem*)));
}
DishInput::~DishInput()
{
}
void DishInput::reload(ElementList *categoryList, IngredientPropertyList *constraintList)
{
categoriesView->clear();
constraintsView->clear();
//Load the possible constraints (properties) list
for (IngredientProperty *ip=constraintList->getFirst();ip; ip=constraintList->getNext())
{
ConstraintsListItem *it=new ConstraintsListItem(constraintsView,ip);
constraintsView->insertItem(it);
}
//Load the categories list
for (Element *el=categoryList->getFirst(); el; el=categoryList->getNext())
{
CategoriesListItem *it=new CategoriesListItem(categoriesView,el->name);
categoriesView->insertItem(it);
}
}
void DishInput::insertConstraintsEditBoxes(QListViewItem* it)
{
QRect r;
// Constraints Box1
r=constraintsView->header()->sectionRect(1); //Set column's size() and position with at adistance equal to the distance between the qlistview and the header;
r.moveBy(this->pos().x()+constraintsView->pos().x(),this->pos().y()+constraintsView->pos().y()); // Move to the position of qlistview header in that column
r.moveBy(0,r.height()+constraintsView->itemRect(it).y()); //Move down to the item, note that its height is same as header's right now.
r.setHeight(it->height()); // Set the item's height
constraintsEditBox1->setGeometry(r);
//Constraints Box2
r=constraintsView->header()->sectionRect(3); //Set column's size() and position with at adistance equal to the distance between the qlistview and the header;
r.moveBy(this->pos().x()+constraintsView->pos().x(),this->pos().y()+constraintsView->pos().y()); // Move to the position of qlistview
r.moveBy(0,r.height()+constraintsView->itemRect(it).y()); //Move down to the item, note that its height is same as header's right now.
r.setHeight(it->height()); // Set the item's height
constraintsEditBox2->setGeometry(r);
// Show Boxes
constraintsEditBox1->show();
constraintsEditBox2->show();
}
DishTitle::DishTitle(QWidget *parent,const QString &title):QWidget(parent)
{
titleText=title;
}
DishTitle::~DishTitle()
{
}
void DishTitle::paintEvent(QPaintEvent *p )
{
QPainter painter(this);
// First draw the decoration
painter.setPen(KGlobalSettings::activeTitleColor());
painter.setBrush(QBrush(KGlobalSettings::activeTitleColor()));
painter.drawRoundRect(0,20,30,height()-40,50,50.0/(height()-40)*35.0);
// Now draw the text
QFont titleFont=KGlobalSettings::windowTitleFont ();
titleFont.setPointSize(15);
painter.setFont(titleFont);
painter.rotate(-90);
painter.setPen(QColor(0x00,0x00,0x00));
painter.drawText(0,0,-height(),30,AlignCenter,titleText);
painter.setPen(QColor(0xFF,0xFF,0xFF));
painter.drawText(-1,-1,-height()-1,29,AlignCenter,titleText);
painter.end();
}
QSize DishTitle::sizeHint () const
{
return(QSize(40,200));
}
QSize DishTitle::minimumSizeHint() const
{
return(QSize(40,200));
}
<commit_msg>Fix editor positioning. Pixel perfect again :)<commit_after>/***************************************************************************
* Copyright (C) 2003 by *
* Unai Garro (ugarro@users.sourceforge.net) *
* Cyril Bosselut (bosselut@b1project.com) *
* Jason Kivlighn (mizunoami44@users.sourceforge.net) *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "dietwizarddialog.h"
#include "DBBackend/recipedb.h"
#include "editbox.h"
#include <qheader.h>
#include <qlayout.h>
#include <qpainter.h>
#include <kapp.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <klocale.h>
DietWizardDialog::DietWizardDialog(QWidget *parent,RecipeDB *db):QVBox(parent)
{
// Initialize internal variables
database=db;
mealNumber=1;
//Design the dialog
setSpacing(10);
// Options Box
optionsBox=new QHBox(this);
sliderBox=new QVGroupBox(i18n("Meals per day"),optionsBox);
mealNumberLabel=new QLabel(sliderBox);
mealNumberLabel->setText("- 1 -");
mealNumberLabel->setAlignment(Qt::AlignHCenter);
mealNumberSelector=new QSlider(sliderBox);
mealNumberSelector->setOrientation(Qt::Horizontal);
mealNumberSelector->setRange(1,10);
mealNumberSelector->setSteps(1,1);
mealNumberSelector->setTickmarks(QSlider::Below);
mealNumberSelector->setFixedWidth(100);
// Tabs
mealTabs=new QTabWidget(this);
mealTabs->setMargin(20);
// Button bar
KIconLoader il;
buttonBox=new QHBox(this);
okButton=new QPushButton(buttonBox);
okButton->setIconSet(il.loadIconSet("button_ok", KIcon::Small));
okButton->setText(i18n("Create the diet"));
// Create Tabs
newTab(i18n("Meal 1"));
// Initialize data
reload();
// Signals & Slots
connect(mealNumberSelector,SIGNAL(valueChanged(int)),this,SLOT(changeMealNumber(int)));
}
DietWizardDialog::~DietWizardDialog()
{
}
void DietWizardDialog::reload(void)
{
database->loadCategories(&categoriesList);
database->loadProperties(&constraintList);
int pgcount=0;
for (MealInput *tab=(MealInput *) (mealTabs->page(pgcount));pgcount<mealTabs->count(); pgcount++)
tab->reload(categoriesList,constraintList);
}
void DietWizardDialog::newTab(const QString &name)
{
mealTab=new MealInput(mealTabs);
mealTab->reload(categoriesList,constraintList);
mealTabs->addTab(mealTab,name);
mealTabs->setCurrentPage(mealTabs->indexOf(mealTab));
}
void DietWizardDialog::changeMealNumber(int mn)
{
if (mn>mealNumber)
{
newTab(i18n("Meal %1").arg(mn));
mealNumber++;
mealNumberLabel->setText(QString("- %1 -").arg(mn));
}
}
class ConstraintsListItem:public QCheckListItem{
public:
ConstraintsListItem(QListView* klv, IngredientProperty *ip ):QCheckListItem(klv,QString::null,QCheckListItem::CheckBox){ ipStored=new IngredientProperty(ip);}
private:
IngredientProperty *ipStored;
public:
virtual QString text(int column) const
{
if (column==1) return(QString("0.0"));
else if (column==2) return(ipStored->name);
else if (column==3) return(QString("0.0"));
else return(QString::null);
}
~ConstraintsListItem(void)
{
delete ipStored;
}
};
class CategoriesListItem:public QCheckListItem{
public:
CategoriesListItem(QListView* klv, QString name ):QCheckListItem(klv,QString::null,QCheckListItem::CheckBox){nameStored=name;}
~CategoriesListItem(void){}
virtual QString text(int column) const
{
if (column==1) return(nameStored);
else return(QString::null);
}
private: QString nameStored;
};
MealInput::MealInput(QWidget *parent):QWidget(parent)
{
// Initialize data
categoriesListLocalCache.clear();
constraintListLocalCache.clear();
// Design the dialog
QVBoxLayout *layout=new QVBoxLayout(this);
layout->setSpacing(20);
// Options box
mealOptions=new QHBox(this);
mealOptions->setSpacing(10);
layout->addWidget(mealOptions);
// Number of dishes input
dishNumberBox=new QHBox(mealOptions); dishNumberBox->setSpacing(10);
dishNumberLabel=new QLabel(i18n("No. of dishes: "),dishNumberBox);
dishNumberInput=new QSpinBox(dishNumberBox); dishNumberInput->setMinValue(1); dishNumberInput->setMaxValue(10);
dishNumberBox->setSizePolicy(QSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum));
// Toolbar
toolBar=new QHGroupBox(mealOptions);
toolBar->setFrameStyle (QFrame::Panel | QFrame::Sunken);
toolBar->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Minimum));
// Next dish/ Previous dish buttons
KIconLoader il;
buttonPrev=new QToolButton(toolBar);
buttonPrev->setUsesTextLabel(true);
buttonPrev->setTextLabel(i18n("Previous Dish"));
buttonPrev->setIconSet(il.loadIconSet("back", KIcon::Small));
buttonPrev->setTextPosition(QToolButton::BelowIcon);
buttonNext=new QToolButton(toolBar);
buttonNext->setUsesTextLabel(true);
buttonNext->setTextLabel(i18n("Next Dish"));
buttonNext->setIconSet(il.loadIconSet("forward", KIcon::Small));
buttonNext->setTextPosition(QToolButton::BelowIcon);
// Dish widgets
dishStack= new QWidgetStack(this);
layout->addWidget(dishStack);
// Add default dishes
DishInput *newDish=new DishInput(this,i18n("1st Course")); dishStack->addWidget(newDish); dishInputList.append(newDish);
newDish=new DishInput(this,i18n("2nd Course")); dishStack->addWidget(newDish); dishInputList.append(newDish);
newDish=new DishInput(this,i18n("Dessert")); dishStack->addWidget(newDish); dishInputList.append(newDish);
dishNumber=1;
// Signals & Slots
connect(dishNumberInput,SIGNAL(valueChanged(int)),this,SLOT(changeDishNumber(int)));
connect(buttonPrev,SIGNAL(clicked()),this,SLOT(prevDish()));
connect(buttonNext,SIGNAL(clicked()),this,SLOT(nextDish()));
}
MealInput::~MealInput()
{
}
// reload from outside with new data
void MealInput::reload(ElementList &categoriesList,IngredientPropertyList &constraintList)
{
int pgcount=0;
QValueList<DishInput*>::iterator it;
categoriesListLocalCache.clear();
constraintListLocalCache.clear();
// Cache the data into the internal lists so it can be reused when creating new dishes
//Cache the possible constraints (properties) list
for (IngredientProperty *ip=constraintList.getFirst(); ip; ip=constraintList.getNext())
{
constraintListLocalCache.add(*ip);
}
//Cache the categories list
for (Element *el=categoriesList.getFirst(); el; el=categoriesList.getNext())
{
categoriesListLocalCache.add(*el);
}
reload(); //load from the cache now
}
// reload internally with the cached data
void MealInput::reload()
{
int pgcount=0;
QValueList<DishInput*>::iterator it;
for (it=dishInputList.begin(); it != dishInputList.end();it++)
{
DishInput *di; di=(*it);
di->reload(&categoriesListLocalCache,&constraintListLocalCache);
}
}
void MealInput::changeDishNumber(int dn)
{
if (dn>dishNumber)
{
DishInput *newDish=new DishInput(this,QString(i18n("Dish %1")).arg(dishNumber+1));
newDish->reload(&categoriesListLocalCache,&constraintListLocalCache);
dishStack->addWidget(newDish);
dishInputList.append(newDish);
dishStack->raiseWidget(newDish);
dishNumber++;
}
}
void MealInput::nextDish(void)
{
// First get the place of the current dish input in the list
QValueList <DishInput*>::iterator it=dishInputList.find((DishInput*)(dishStack->visibleWidget()));
//Show the next dish if it exists
it++;
if (it!=dishInputList.end())
{
dishStack->raiseWidget(*it);
}
}
void MealInput::prevDish(void)
{
// First get the place of the current dish input in the list
QValueList <DishInput*>::iterator it=dishInputList.find((DishInput*)(dishStack->visibleWidget()));
//Show the previous dish if it exists
it--;
if (it!=dishInputList.end())
{
dishStack->raiseWidget(*it);
}
}
DishInput::DishInput(QWidget* parent,const QString &title):QWidget(parent)
{
QVBoxLayout *layout=new QVBoxLayout(this);
layout->setSpacing(20);
//Horizontal Box to hold the KListView's
listBox=new QHGroupBox(i18n("Dish Characteristics"),this);
layout->addWidget(listBox);
// Dish id
dishTitle=new DishTitle(listBox,title);
//Categories list
categoriesView=new KListView(listBox);
categoriesView->addColumn("*");
categoriesView->addColumn(i18n("Category"));
//Constraints list
constraintsView=new KListView(listBox);
constraintsView->addColumn(i18n("Enabled"));
constraintsView->addColumn(i18n("Min. Value"));
constraintsView->addColumn(i18n("Property"));
constraintsView->addColumn(i18n("Max. Value"));
// KDoubleInput based edit boxes
constraintsEditBox1=new EditBox(this);
constraintsEditBox1->hide();
constraintsEditBox2=new EditBox(this);
constraintsEditBox2->hide();
// Connect Signals & Slots
connect(constraintsView,SIGNAL(executed(QListViewItem*)),this,SLOT(insertConstraintsEditBoxes(QListViewItem*)));
}
DishInput::~DishInput()
{
}
void DishInput::reload(ElementList *categoryList, IngredientPropertyList *constraintList)
{
categoriesView->clear();
constraintsView->clear();
//Load the possible constraints (properties) list
for (IngredientProperty *ip=constraintList->getFirst();ip; ip=constraintList->getNext())
{
ConstraintsListItem *it=new ConstraintsListItem(constraintsView,ip);
constraintsView->insertItem(it);
}
//Load the categories list
for (Element *el=categoryList->getFirst(); el; el=categoryList->getNext())
{
CategoriesListItem *it=new CategoriesListItem(categoriesView,el->name);
categoriesView->insertItem(it);
}
}
void DishInput::insertConstraintsEditBoxes(QListViewItem* it)
{
QRect r;
// Constraints Box1
r.setTopLeft(this->pos());r.setSize(QSize(30,30));
r.moveBy(listBox->pos().x()+constraintsView->pos().x()+constraintsView->header()->pos().x(),listBox->pos().y()+constraintsView->pos().y()+constraintsView->header()->pos().y()); // Place it on top of the header of the list view
r.moveBy(constraintsView->header()->sectionRect(1).x(),0); // Move it to column no 1
r.moveBy(0,constraintsView->header()->sectionRect(1).height()+constraintsView->itemRect(it).y()); //Move down to the item, note that its height is same as header's right now.
r.setHeight(it->height()); // Set the item's height
r.setWidth(constraintsView->header()->sectionRect(1).width()); // and width
constraintsEditBox1->setGeometry(r);
//Constraints Box2
r.setTopLeft(this->pos());r.setSize(QSize(30,30));
r.moveBy(listBox->pos().x()+constraintsView->pos().x()+constraintsView->header()->pos().x(),listBox->pos().y()+constraintsView->pos().y()+constraintsView->header()->pos().y()); // Place it on top of the header of the list view
r.moveBy(constraintsView->header()->sectionRect(3).x(),0); // Move it to column no 1
r.moveBy(0,constraintsView->header()->sectionRect(3).height()+constraintsView->itemRect(it).y()); //Move down to the item, note that its height is same as header's right now.
r.setHeight(it->height()); // Set the item's height
r.setWidth(constraintsView->header()->sectionRect(3).width()); // and width
constraintsEditBox2->setGeometry(r);
// Show Boxes
constraintsEditBox1->show();
constraintsEditBox2->show();
}
DishTitle::DishTitle(QWidget *parent,const QString &title):QWidget(parent)
{
titleText=title;
}
DishTitle::~DishTitle()
{
}
void DishTitle::paintEvent(QPaintEvent *p )
{
QPainter painter(this);
// First draw the decoration
painter.setPen(KGlobalSettings::activeTitleColor());
painter.setBrush(QBrush(KGlobalSettings::activeTitleColor()));
painter.drawRoundRect(0,20,30,height()-40,50,50.0/(height()-40)*35.0);
// Now draw the text
QFont titleFont=KGlobalSettings::windowTitleFont ();
titleFont.setPointSize(15);
painter.setFont(titleFont);
painter.rotate(-90);
painter.setPen(QColor(0x00,0x00,0x00));
painter.drawText(0,0,-height(),30,AlignCenter,titleText);
painter.setPen(QColor(0xFF,0xFF,0xFF));
painter.drawText(-1,-1,-height()-1,29,AlignCenter,titleText);
painter.end();
}
QSize DishTitle::sizeHint () const
{
return(QSize(40,200));
}
QSize DishTitle::minimumSizeHint() const
{
return(QSize(40,200));
}
<|endoftext|>
|
<commit_before><commit_msg>Changes to allow international input on GTK+ 2.<commit_after><|endoftext|>
|
<commit_before>Bool_t isAOD=kTRUE;
Bool_t hasMC=kFALSE;
Int_t iPeriod=-1;
enum { k10b=0, k10c, k10d, k10e, k10f, k10h, k11a, k11d, k11h, k12h, k13b, k13c, k13d, k13e, k13f };
AliAnalysisTask* AddTaskJpsi_zzhou_PbPb(
TString cfg="ConfigJpsi_zzhou_lowpt",
Bool_t gridconf=kTRUE,
TString prod="",
Bool_t isMC=kFALSE)
{
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTaskJpsi_zzhou_PbPb", "No analysis manager found.");
return 0;
}
//Do we have an MC handler?
Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);
//AOD input?
Bool_t isAOD=mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class();
if(isAOD) hasMC=isMC;
//Get the current train configuration
// TString trainConfig=gSystem->Getenv("CONFIG_FILE");
//TString list=gSystem->Getenv("LIST");
//if( list.IsNull()) list=prod;
// selected period
if( !prod.CompareTo("LHC10h") ) iPeriod = k10h;
else if( !prod.CompareTo("LHC11h") ) iPeriod = k11h;
//Do
// // aod monte carlo
// if( list.Contains("LHC11a10") ||
// list.Contains("LHC11b10") ||
// list.Contains("LHC12a17") ||
// list.Contains("fix")
// ) hasMC=kTRUE;
//create task and add it to the manager
AliAnalysisTaskMultiDielectron *task=new AliAnalysisTaskMultiDielectron("Jpsi_zzhouPbPb");
if (!hasMC) task->UsePhysicsSelection();
// add special triggers
switch(iPeriod) {
case k11h: task->SetTriggerMask(AliVEvent::kMB+AliVEvent::kCentral+AliVEvent::kSemiCentral); break;
}
mgr->AddTask(task);
AliDielectronEventCuts *eventCuts=new AliDielectronEventCuts("eventCuts","Vertex Track && |vtxZ|<10 && ncontrib>0");
if(isAOD) eventCuts->SetVertexType(AliDielectronEventCuts::kVtxAny);
eventCuts->SetRequireVertex();
eventCuts->SetMinVtxContributors(1);
eventCuts->SetVertexZ(-10.,10.);
// task->SetTriggerOnV0AND();
task->SetEventFilter(eventCuts);
task->SetRejectPileup();
gROOT->LoadMacro("ConfigJpsi_zzhou_lowpt.C");
//add dielectron analysis with different cuts to the task
for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file
AliDielectron *jpsi=ConfigJpsi_zzhou_lowpt(i);
if (!jpsi) continue;
jpsi->SetHasMC(hasMC);
task->AddDielectron(jpsi);
}
// task->SetTriggerOnV0AND();
// if ( trainConfig=="pp" ) task->SetRejectPileup();
//create output container
AliAnalysisDataContainer *coutput1 =
mgr->CreateContainer("jpsi_Default_tree",
TTree::Class(),
AliAnalysisManager::kExchangeContainer,
"jpsi_Default_default");
AliAnalysisDataContainer *cOutputHist1 =
mgr->CreateContainer("jpsi_Default_QA",
TList::Class(),
AliAnalysisManager::kOutputContainer,
"AnalysisResults.root");
AliAnalysisDataContainer *cOutputHist2 =
mgr->CreateContainer("jpsi_Default_CF",
TList::Class(),
AliAnalysisManager::kOutputContainer,
"AnalysisResults.root");
AliAnalysisDataContainer *cOutputHist3 =
mgr->CreateContainer("jpsi_Default_EventStat",
TH1D::Class(),
AliAnalysisManager::kOutputContainer,
"AnalysisResults.root");
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 0, coutput1 );
mgr->ConnectOutput(task, 1, cOutputHist1);
mgr->ConnectOutput(task, 2, cOutputHist2);
mgr->ConnectOutput(task, 3, cOutputHist3);
return task;
}
<commit_msg>update AddTask for zzhou. Take correct Config.<commit_after>Bool_t isAOD=kTRUE;
Bool_t hasMC=kFALSE;
Int_t iPeriod=-1;
enum { k10b=0, k10c, k10d, k10e, k10f, k10h, k11a, k11d, k11h, k12h, k13b, k13c, k13d, k13e, k13f };
AliAnalysisTask* AddTaskJpsi_zzhou_PbPb(
TString cfg="ConfigJpsi_zzhou_lowpt",
Bool_t gridconf=kTRUE,
TString prod="",
Bool_t isMC=kFALSE)
{
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTaskJpsi_zzhou_PbPb", "No analysis manager found.");
return 0;
}
//Do we have an MC handler?
Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);
//AOD input?
Bool_t isAOD=mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class();
if(isAOD) hasMC=isMC;
//Get the current train configuration
// TString trainConfig=gSystem->Getenv("CONFIG_FILE");
//TString list=gSystem->Getenv("LIST");
//if( list.IsNull()) list=prod;
// selected period
if( !prod.CompareTo("LHC10h") ) iPeriod = k10h;
else if( !prod.CompareTo("LHC11h") ) iPeriod = k11h;
//Do
// // aod monte carlo
// if( list.Contains("LHC11a10") ||
// list.Contains("LHC11b10") ||
// list.Contains("LHC12a17") ||
// list.Contains("fix")
// ) hasMC=kTRUE;
//create task and add it to the manager
AliAnalysisTaskMultiDielectron *task=new AliAnalysisTaskMultiDielectron("Jpsi_zzhouPbPb");
if (!hasMC) task->UsePhysicsSelection();
// add special triggers
switch(iPeriod) {
case k11h: task->SetTriggerMask(AliVEvent::kMB+AliVEvent::kCentral+AliVEvent::kSemiCentral); break;
}
mgr->AddTask(task);
AliDielectronEventCuts *eventCuts=new AliDielectronEventCuts("eventCuts","Vertex Track && |vtxZ|<10 && ncontrib>0");
if(isAOD) eventCuts->SetVertexType(AliDielectronEventCuts::kVtxAny);
eventCuts->SetRequireVertex();
eventCuts->SetMinVtxContributors(1);
eventCuts->SetVertexZ(-10.,10.);
// task->SetTriggerOnV0AND();
task->SetEventFilter(eventCuts);
task->SetRejectPileup();
gROOT->LoadMacro( cfg.Data() );
//add dielectron analysis with different cuts to the task
for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file
AliDielectron *jpsi=ConfigJpsi_zzhou_lowpt(i);
if (!jpsi) continue;
jpsi->SetHasMC(hasMC);
task->AddDielectron(jpsi);
}
// task->SetTriggerOnV0AND();
// if ( trainConfig=="pp" ) task->SetRejectPileup();
//create output container
AliAnalysisDataContainer *coutput1 =
mgr->CreateContainer("jpsi_Default_tree",
TTree::Class(),
AliAnalysisManager::kExchangeContainer,
"jpsi_Default_default");
AliAnalysisDataContainer *cOutputHist1 =
mgr->CreateContainer("jpsi_Default_QA",
TList::Class(),
AliAnalysisManager::kOutputContainer,
"AnalysisResults.root");
AliAnalysisDataContainer *cOutputHist2 =
mgr->CreateContainer("jpsi_Default_CF",
TList::Class(),
AliAnalysisManager::kOutputContainer,
"AnalysisResults.root");
AliAnalysisDataContainer *cOutputHist3 =
mgr->CreateContainer("jpsi_Default_EventStat",
TH1D::Class(),
AliAnalysisManager::kOutputContainer,
"AnalysisResults.root");
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 0, coutput1 );
mgr->ConnectOutput(task, 1, cOutputHist1);
mgr->ConnectOutput(task, 2, cOutputHist2);
mgr->ConnectOutput(task, 3, cOutputHist3);
return task;
}
<|endoftext|>
|
<commit_before><commit_msg>Changed default drag action to move.<commit_after><|endoftext|>
|
<commit_before>AliEmcalPicoTrackMaker* AddTaskEmcalPicoTrackMaker(
const char *name = "PicoTracks",
const char *inname = "tracks",
const char *runPeriod = "LHC11h",
AliESDtrackCuts *cuts = 0
)
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskEmcalPicoTrackMaker", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskEmcalPicoTrackMaker", "This task requires an input event handler");
return NULL;
}
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
// Add aod track filter task.
AliEmcalPicoTrackMaker *eTask = new AliEmcalPicoTrackMaker();
eTask->SetTracksOutName(name);
eTask->SetTracksInName(inname);
if (!strcmp(runPeriod, "LHC11h")) {
eTask->SetAODfilterBits(256,512,1024); // hybrid tracks for LHC11h
}
else {
AliWarning(Form("Run period %s not known. AOD filter bit not set.", renPeriod));
}
eTask->SetESDtrackCuts(cuts);
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask(eTask);
// Create containers for input/output
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
mgr->ConnectInput (eTask, 0, cinput1 );
return eTask;
}
<commit_msg>aod mode<commit_after>// $Id$
AliEmcalPicoTrackMaker* AddTaskEmcalPicoTrackMaker(
const char *name = "PicoTracks",
const char *inname = "tracks",
const char *runPeriod = "LHC11h",
AliESDtrackCuts *cuts = 0
)
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskEmcalPicoTrackMaker", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskEmcalPicoTrackMaker", "This task requires an input event handler");
return NULL;
}
//-------------------------------------------------------
// Init the task and do settings
//-------------------------------------------------------
AliEmcalPicoTrackMaker *eTask = new AliEmcalPicoTrackMaker();
eTask->SetTracksOutName(name);
eTask->SetTracksInName(inname);
if (!strcmp(runPeriod, "LHC11h")) {
eTask->SetAODfilterBits(256,512); // hybrid tracks for LHC11h
}
else {
AliWarning(Form("Run period %s not known. AOD filter bit not set.", renPeriod));
}
eTask->SetESDtrackCuts(cuts);
//-------------------------------------------------------
// Final settings, pass to manager and set the containers
//-------------------------------------------------------
mgr->AddTask(eTask);
// Create containers for input/output
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
mgr->ConnectInput (eTask, 0, cinput1 );
return eTask;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: defaultproperties.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 20:05:09 $
*
* 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 _SDR_PROPERTIES_DEFAULTPROPERTIES_HXX
#define _SDR_PROPERTIES_DEFAULTPROPERTIES_HXX
#ifndef _SDR_PROPERTIES_PROPERTIES_HXX
#include <svx/sdr/properties/properties.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace properties
{
class SVX_DLLPUBLIC DefaultProperties : public BaseProperties
{
protected:
// the to be used ItemSet
SfxItemSet* mpItemSet;
// create a new itemset
virtual SfxItemSet& CreateObjectSpecificItemSet(SfxItemPool& rPool);
// test changeability for a single item
virtual sal_Bool AllowItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem = 0) const;
// Do the ItemChange, may do special handling
virtual void ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem = 0);
// Called after ItemChange() is done for all items.
virtual void PostItemChange(const sal_uInt16 nWhich);
// react on ItemSet changes
virtual void ItemSetChanged(const SfxItemSet& rSet);
public:
// basic constructor
DefaultProperties(SdrObject& rObj);
// constructor for copying, but using new object
DefaultProperties(const DefaultProperties& rProps, SdrObject& rObj);
// destructor
virtual ~DefaultProperties();
// Clone() operator, normally just calls the local copy constructor
virtual BaseProperties& Clone(SdrObject& rObj) const;
// get itemset
virtual const SfxItemSet& GetObjectItemSet() const;
// set single item
virtual void SetObjectItem(const SfxPoolItem& rItem);
// set single item direct, do not do any notifies or things like that
virtual void SetObjectItemDirect(const SfxPoolItem& rItem);
// clear single item
virtual void ClearObjectItem(const sal_uInt16 nWhich = 0);
// clear single item direct, do not do any notifies or things like that.
// Also supports complete deleteion of items when default parameter 0 is used.
virtual void ClearObjectItemDirect(const sal_uInt16 nWhich = 0);
// set complete item set
virtual void SetObjectItemSet(const SfxItemSet& rSet);
// set a new StyleSheet and broadcast
virtual void SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr);
// get the installed StyleSheet
virtual SfxStyleSheet* GetStyleSheet() const;
// pre/post-process saving
//BFS01virtual void PreProcessSave();
//BFS01virtual void PostProcessSave();
// force default attributes for a specific object type, called from
// DefaultProperties::GetObjectItemSet() if a new ItemSet is created.
// Default implementation does nothing.
virtual void ForceDefaultAttributes();
// Scale the included ItemSet.
virtual void Scale(const Fraction& rScale);
};
} // end of namespace properties
} // end of namespace sdr
#endif //_SDR_PROPERTIES_DEFAULTPROPERTIES_HXX
// eof
<commit_msg>INTEGRATION: CWS aw024 (1.3.140); FILE MERGED 2005/09/18 01:43:00 aw 1.3.140.3: RESYNC: (1.4-1.5); FILE MERGED 2005/03/23 23:43:55 aw 1.3.140.2: RESYNC: (1.3-1.4); FILE MERGED 2004/12/23 16:50:49 aw 1.3.140.1: #i39525<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: defaultproperties.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 13:10:16 $
*
* 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 _SDR_PROPERTIES_DEFAULTPROPERTIES_HXX
#define _SDR_PROPERTIES_DEFAULTPROPERTIES_HXX
#ifndef _SDR_PROPERTIES_PROPERTIES_HXX
#include <svx/sdr/properties/properties.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace properties
{
class SVX_DLLPUBLIC DefaultProperties : public BaseProperties
{
protected:
// the to be used ItemSet
SfxItemSet* mpItemSet;
// create a new itemset
virtual SfxItemSet& CreateObjectSpecificItemSet(SfxItemPool& rPool);
// test changeability for a single item
virtual sal_Bool AllowItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem = 0) const;
// Do the ItemChange, may do special handling
virtual void ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem = 0);
// Called after ItemChange() is done for all items.
virtual void PostItemChange(const sal_uInt16 nWhich);
// react on ItemSet changes
virtual void ItemSetChanged(const SfxItemSet& rSet);
public:
// basic constructor
DefaultProperties(SdrObject& rObj);
// constructor for copying, but using new object
DefaultProperties(const DefaultProperties& rProps, SdrObject& rObj);
// destructor
virtual ~DefaultProperties();
// Clone() operator, normally just calls the local copy constructor
virtual BaseProperties& Clone(SdrObject& rObj) const;
// get itemset
virtual const SfxItemSet& GetObjectItemSet() const;
// set single item
virtual void SetObjectItem(const SfxPoolItem& rItem);
// set single item direct, do not do any notifies or things like that
virtual void SetObjectItemDirect(const SfxPoolItem& rItem);
// clear single item
virtual void ClearObjectItem(const sal_uInt16 nWhich = 0);
// clear single item direct, do not do any notifies or things like that.
// Also supports complete deleteion of items when default parameter 0 is used.
virtual void ClearObjectItemDirect(const sal_uInt16 nWhich = 0);
// set complete item set
virtual void SetObjectItemSet(const SfxItemSet& rSet);
// set a new StyleSheet and broadcast
virtual void SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr);
// get the installed StyleSheet
virtual SfxStyleSheet* GetStyleSheet() const;
// force default attributes for a specific object type, called from
// DefaultProperties::GetObjectItemSet() if a new ItemSet is created.
// Default implementation does nothing.
virtual void ForceDefaultAttributes();
// Scale the included ItemSet.
virtual void Scale(const Fraction& rScale);
};
} // end of namespace properties
} // end of namespace sdr
#endif //_SDR_PROPERTIES_DEFAULTPROPERTIES_HXX
// eof
<|endoftext|>
|
<commit_before>#include "Statue_Enemy.h"
Statue_Enemy::Statue_Enemy() :Enemy(enemyType::statue_enemy)
{
this->sprites_vector = App->enemy->enemy_statue_perf->sprites_vector;
this->entity_texture = App->enemy->enemy_statue_perf->entity_texture;
this->ChangeAnimation(1);
}
Statue_Enemy::Statue_Enemy(const Statue_Enemy &g_enemy) :Enemy(enemyType::statue_enemy)
{
this->collider = g_enemy.collider;
this->logic_height = g_enemy.logic_height;
this->sprites_vector = App->enemy->enemy_statue_perf->sprites_vector;
}
Statue_Enemy::~Statue_Enemy()
{
}
void Statue_Enemy::Action()
{
tile_pos.x = pix_world_pos.x / 16;
tile_pos.y = pix_world_pos.y / 16;
if (player_in_range == nullptr) {
iPoint actual_tile = pix_world_pos;
if (passedtile == true) {
temp_point = array_pos;
array_pos = App->enemy->CalculatePath(this);
if (array_pos == temp_point) {
Path_Enemy.clear();
}
}
int x = ((array_pos.x) - temp_point.x);
int y = ((array_pos.y) - temp_point.y);
pix_world_pos.x += x;
pix_world_pos.y += y;
if (x == 1) {
Enemy_Orientation = OrientationEnemy::right_enemy;
}
else if (x == -1) {
Enemy_Orientation = OrientationEnemy::left_enemy;
}
else if (y == 1) {
Enemy_Orientation = OrientationEnemy::down_enemy;
}
else if (y == -1) {
Enemy_Orientation = OrientationEnemy::up_enemy;
}
if ((actual_tile.x / 16) == array_pos.x && (actual_tile.y / 16) == array_pos.y) {
passedtile = true;
}
else {
passedtile = false;
}
}
else {
if (!enemy_doing_script) {
if (this->state != jumping) {
first_point = pix_world_pos;
max_heigh_jump.y = pix_world_pos.y - 50;
if (player_in_range->pos.x < pix_world_pos.x) {
last_point.x = pix_world_pos.x - 50;
}
else {
last_point.x = pix_world_pos.x + 50;
}
last_point.y = (player_in_range->pos.y + pix_world_pos.y) / 2;
}
if (abs(first_point.x - last_point.x) > abs(first_point.y - last_point.y)) {
if (first_point.x < last_point.x) {
Enemy_Orientation = OrientationEnemy::right_enemy;
}
else {
Enemy_Orientation = OrientationEnemy::left_enemy;
}
}
else {
if (first_point.y < last_point.y) {
Enemy_Orientation = OrientationEnemy::down_enemy;
}
else {
Enemy_Orientation = OrientationEnemy::up_enemy;
}
}
pix_world_pos.y = (1 - t)*(1 - t)*first_point.y + 2 * t*(1 - t)*max_heigh_jump.y + t*t*last_point.y;
if (t < 1) {
t += (float)1 / 50;
if (t<=0.5) {
this->logic_height = 1;
}
else {
this->logic_height = 0;
}
}
else {
t = 0;
this->logic_height = 0;
first_point = last_point;
if (player_in_range->pos.x < pix_world_pos.x) {
last_point.x = pix_world_pos.x - 50;
}
else {
last_point.x = pix_world_pos.x + 50;
}
max_heigh_jump.y = pix_world_pos.y - 50;
last_point.y = (player_in_range->pos.y + pix_world_pos.y) / 2;
}
}
else {
if (script_timer.Read() > 1000)
enemy_doing_script = false;
}
}
}
<commit_msg>enemy timing fixed<commit_after>#include "Statue_Enemy.h"
Statue_Enemy::Statue_Enemy() :Enemy(enemyType::statue_enemy)
{
this->sprites_vector = App->enemy->enemy_statue_perf->sprites_vector;
this->entity_texture = App->enemy->enemy_statue_perf->entity_texture;
this->ChangeAnimation(1);
}
Statue_Enemy::Statue_Enemy(const Statue_Enemy &g_enemy) :Enemy(enemyType::statue_enemy)
{
this->collider = g_enemy.collider;
this->logic_height = g_enemy.logic_height;
this->sprites_vector = App->enemy->enemy_statue_perf->sprites_vector;
}
Statue_Enemy::~Statue_Enemy()
{
}
void Statue_Enemy::Action()
{
tile_pos.x = pix_world_pos.x / 16;
tile_pos.y = pix_world_pos.y / 16;
if (player_in_range == nullptr) {
iPoint actual_tile = pix_world_pos;
if (passedtile == true) {
temp_point = array_pos;
array_pos = App->enemy->CalculatePath(this);
if (array_pos == temp_point) {
Path_Enemy.clear();
}
}
int x = ((array_pos.x) - temp_point.x);
int y = ((array_pos.y) - temp_point.y);
pix_world_pos.x += x;
pix_world_pos.y += y;
if (x == 1) {
Enemy_Orientation = OrientationEnemy::right_enemy;
}
else if (x == -1) {
Enemy_Orientation = OrientationEnemy::left_enemy;
}
else if (y == 1) {
Enemy_Orientation = OrientationEnemy::down_enemy;
}
else if (y == -1) {
Enemy_Orientation = OrientationEnemy::up_enemy;
}
if ((actual_tile.x / 16) == array_pos.x && (actual_tile.y / 16) == array_pos.y) {
passedtile = true;
}
else {
passedtile = false;
}
}
else {
if (!enemy_doing_script) {
if (this->state != jumping) {
first_point = pix_world_pos;
max_heigh_jump.y = pix_world_pos.y - 50;
if (player_in_range->pos.x < pix_world_pos.x) {
last_point.x = pix_world_pos.x - 50;
}
else {
last_point.x = pix_world_pos.x + 50;
}
last_point.y = (player_in_range->pos.y + pix_world_pos.y) / 2;
}
if (abs(first_point.x - last_point.x) > abs(first_point.y - last_point.y)) {
if (first_point.x < last_point.x) {
Enemy_Orientation = OrientationEnemy::right_enemy;
}
else {
Enemy_Orientation = OrientationEnemy::left_enemy;
}
}
else {
if (first_point.y < last_point.y) {
Enemy_Orientation = OrientationEnemy::down_enemy;
}
else {
Enemy_Orientation = OrientationEnemy::up_enemy;
}
}
pix_world_pos.y = (1 - t)*(1 - t)*first_point.y + 2 * t*(1 - t)*max_heigh_jump.y + t*t*last_point.y;
if (t < 1) {
t += (float)1 / 50;
if (t<=0.25 || t >= 0.75) {
this->logic_height = 0;
}
else {
this->logic_height = 1;
}
}
else {
t = 0;
this->logic_height = 0;
first_point = last_point;
if (player_in_range->pos.x < pix_world_pos.x) {
last_point.x = pix_world_pos.x - 50;
}
else {
last_point.x = pix_world_pos.x + 50;
}
max_heigh_jump.y = pix_world_pos.y - 50;
last_point.y = (player_in_range->pos.y + pix_world_pos.y) / 2;
}
}
else {
if (script_timer.Read() > 1000)
enemy_doing_script = false;
}
}
}
<|endoftext|>
|
<commit_before>#include "Utilities.h"
#include <algorithm>
#include <vector>
using namespace PBD;
using namespace std;
std::string Utilities::getFilePath(const std::string &path)
{
std::string npath = normalizePath(path);
std::string result = npath;
size_t i = result.rfind('.', result.length());
if (i != std::string::npos)
{
result = result.substr(0, i);
}
size_t p1 = result.rfind('\\', result.length());
size_t p2 = result.rfind('/', result.length());
if ((p1 != std::string::npos) && (p2 != std::string::npos))
result = result.substr(0, std::max(p1, p2));
else if (p1 != std::string::npos)
result = result.substr(0, p1);
else if (p2 != std::string::npos)
result = result.substr(0, p2);
return result;
}
std::string Utilities::getFileName(const std::string &path)
{
std::string npath = normalizePath(path);
std::string result = npath;
size_t i = result.rfind('.', result.length());
if (i != std::string::npos)
{
result = result.substr(0, i);
}
size_t p1 = result.rfind('\\', result.length());
size_t p2 = result.rfind('/', result.length());
if ((p1 != std::string::npos) && (p2 != std::string::npos))
result = result.substr(std::max(p1, p2)+1, result.length());
else if (p1 != std::string::npos)
result = result.substr(p1+1, result.length());
else if (p2 != std::string::npos)
result = result.substr(p2+1, result.length());
return result;
}
bool Utilities::isRelativePath(const std::string &path)
{
std::string npath = normalizePath(path);
// Windows
size_t i = npath.find(':', npath.length());
if (i != std::string::npos)
return false;
else if (npath[0] == '/')
return false;
return true;
}
std::string Utilities::normalizePath(const std::string &path)
{
std::string result = path;
std::replace(result.begin(), result.end(), '\\', '/');
std::vector<std::string> tokens;
tokenize(result, tokens, "/");
unsigned int index = 0;
while (index < tokens.size())
{
if ((tokens[index] == "..") && (index > 0))
{
tokens.erase(tokens.begin() + index-1, tokens.begin() + index + 1);
index--;
}
index++;
}
result = tokens[0];
for (unsigned int i = 1; i < tokens.size(); i++)
result = result + "/" + tokens[i];
return result;
}
void Utilities::tokenize(const string& str, vector<string>& tokens, const string& delimiters)
{
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
tokens.push_back(str.substr(lastPos, pos - lastPos));
lastPos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, lastPos);
}
}
<commit_msg>- bugfix<commit_after>#include "Utilities.h"
#include <algorithm>
#include <vector>
using namespace PBD;
using namespace std;
std::string Utilities::getFilePath(const std::string &path)
{
std::string npath = normalizePath(path);
std::string result = npath;
size_t i = result.rfind('.', result.length());
if (i != std::string::npos)
{
result = result.substr(0, i);
}
size_t p1 = result.rfind('\\', result.length());
size_t p2 = result.rfind('/', result.length());
if ((p1 != std::string::npos) && (p2 != std::string::npos))
result = result.substr(0, std::max(p1, p2));
else if (p1 != std::string::npos)
result = result.substr(0, p1);
else if (p2 != std::string::npos)
result = result.substr(0, p2);
return result;
}
std::string Utilities::getFileName(const std::string &path)
{
std::string npath = normalizePath(path);
std::string result = npath;
size_t i = result.rfind('.', result.length());
if (i != std::string::npos)
{
result = result.substr(0, i);
}
size_t p1 = result.rfind('\\', result.length());
size_t p2 = result.rfind('/', result.length());
if ((p1 != std::string::npos) && (p2 != std::string::npos))
result = result.substr(std::max(p1, p2)+1, result.length());
else if (p1 != std::string::npos)
result = result.substr(p1+1, result.length());
else if (p2 != std::string::npos)
result = result.substr(p2+1, result.length());
return result;
}
bool Utilities::isRelativePath(const std::string &path)
{
std::string npath = normalizePath(path);
// Windows
size_t i = npath.find(':', npath.length());
if (i != std::string::npos)
return false;
else if (npath[0] == '/')
return false;
return true;
}
std::string Utilities::normalizePath(const std::string &path)
{
std::string result = path;
std::replace(result.begin(), result.end(), '\\', '/');
std::vector<std::string> tokens;
tokenize(result, tokens, "/");
unsigned int index = 0;
while (index < tokens.size())
{
if ((tokens[index] == "..") && (index > 0))
{
tokens.erase(tokens.begin() + index-1, tokens.begin() + index + 1);
index--;
}
index++;
}
result = "";
if (path[0] == '/')
result = "/";
result = result + tokens[0];
for (unsigned int i = 1; i < tokens.size(); i++)
result = result + "/" + tokens[i];
return result;
}
void Utilities::tokenize(const string& str, vector<string>& tokens, const string& delimiters)
{
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
tokens.push_back(str.substr(lastPos, pos - lastPos));
lastPos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, lastPos);
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <istream>
#include <iterator>
#include <cstdlib>
#include "GzStream.h"
#include "util.h"
__attribute__((noreturn)) void Usage() {
std::cerr << "usage: " << ::progname << " mode\n";
std::cerr << " Where \"mode\" has to be either \"compress\" or \"decompress\".\n";
std::cerr << " Data is either read from (compress) or wtritten to (decompress) stdout.\n";
std::cerr << " The compressed or uncompressed data is then written to stdout.\n";
std::exit(EXIT_FAILURE);
}
// Read stdin until EOF.
std::string SnarfUpStdin() {
std::cin >> std::noskipws;
std::istream_iterator<char> it(std::cin);
std::istream_iterator<char> end;
return std::string(it, end);
}
void Compress() {
const std::string uncompressed_data(SnarfUpStdin());
std::cout << GzStream::CompressString(uncompressed_data);
}
void Decompress() {
const std::string compressed_data(SnarfUpStdin());
std::cout << GzStream::DecompressString(compressed_data);
}
int main(int argc, char *argv[]) {
::progname = argv[0];
if (argc != 2)
Usage();
const std::string mode(argv[1]);
if (mode == "compress")
Compress();
else if (mode == "decompress")
Decompress();
else
Usage();
}
<commit_msg>Fixed a typo in the help text.<commit_after>#include <iostream>
#include <istream>
#include <iterator>
#include <cstdlib>
#include "GzStream.h"
#include "util.h"
__attribute__((noreturn)) void Usage() {
std::cerr << "usage: " << ::progname << " mode\n";
std::cerr << " Where \"mode\" has to be either \"compress\" or \"decompress\".\n";
std::cerr << " Data is either read from (compress) or written to (decompress) stdout.\n";
std::cerr << " The compressed or uncompressed data is then written to stdout.\n";
std::exit(EXIT_FAILURE);
}
// Read stdin until EOF.
std::string SnarfUpStdin() {
std::cin >> std::noskipws;
std::istream_iterator<char> it(std::cin);
std::istream_iterator<char> end;
return std::string(it, end);
}
void Compress() {
const std::string uncompressed_data(SnarfUpStdin());
std::cout << GzStream::CompressString(uncompressed_data);
}
void Decompress() {
const std::string compressed_data(SnarfUpStdin());
std::cout << GzStream::DecompressString(compressed_data);
}
int main(int argc, char *argv[]) {
::progname = argv[0];
if (argc != 2)
Usage();
const std::string mode(argv[1]);
if (mode == "compress")
Compress();
else if (mode == "decompress")
Decompress();
else
Usage();
}
<|endoftext|>
|
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2010-2011 Dreamhost
*
* This 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. See file COPYING.
*
*/
#include "auth/AuthSupported.h"
#include "auth/KeyRing.h"
#include "common/DoutStreambuf.h"
#include "common/Thread.h"
#include "common/ceph_argparse.h"
#include "common/ceph_crypto.h"
#include "common/code_environment.h"
#include "common/common_init.h"
#include "common/config.h"
#include "common/errno.h"
#include "common/pidfile.h"
#include "common/safe_io.h"
#include "common/signal.h"
#include "common/version.h"
#include "include/color.h"
#include "common/Thread.h"
#include "common/pidfile.h"
#include <errno.h>
#include <deque>
#include <syslog.h>
#define _STR(x) #x
#define STRINGIFY(x) _STR(x)
int keyring_init(md_config_t *conf)
{
if (!is_supported_auth(CEPH_AUTH_CEPHX))
return 0;
int ret = 0;
string filename;
if (ceph_resolve_file_search(conf->keyring, filename)) {
ret = g_keyring.load(filename);
}
if (!conf->key.empty()) {
EntityAuth ea;
ea.key.decode_base64(conf->key);
g_keyring.add(conf->name, ea);
ret = 0;
} else if (!conf->keyfile.empty()) {
char buf[100];
int fd = ::open(conf->keyfile.c_str(), O_RDONLY);
if (fd < 0) {
int err = errno;
derr << "unable to open " << conf->keyfile << ": "
<< cpp_strerror(err) << dendl;
ceph_abort();
}
memset(buf, 0, sizeof(buf));
int len = safe_read(fd, buf, sizeof(buf) - 1);
if (len < 0) {
derr << "unable to read key from " << conf->keyfile << ": "
<< cpp_strerror(len) << dendl;
TEMP_FAILURE_RETRY(::close(fd));
ceph_abort();
}
TEMP_FAILURE_RETRY(::close(fd));
buf[len] = 0;
string k = buf;
EntityAuth ea;
ea.key.decode_base64(k);
g_keyring.add(conf->name, ea);
ret = 0;
}
if (ret)
derr << "keyring_init: failed to load " << filename << dendl;
return ret;
}
md_config_t *common_preinit(const CephInitParameters &iparams,
enum code_environment_t code_env, int flags)
{
// set code environment
g_code_env = code_env;
// Create a configuration object
// TODO: de-globalize
md_config_t *conf = &g_conf; //new md_config_t();
// add config observers here
// Set up our entity name.
conf->name = iparams.name;
// Set some defaults based on code type
switch (code_env) {
case CODE_ENVIRONMENT_DAEMON:
conf->daemonize = true;
if (!(flags & CINIT_FLAG_UNPRIVILEGED_DAEMON_DEFAULTS)) {
conf->set_val_or_die("pid_file", "/var/run/ceph/$type.$id.pid");
}
conf->set_val_or_die("log_to_stderr", STRINGIFY(LOG_TO_STDERR_SOME));
break;
default:
conf->set_val_or_die("daemonize", "false");
break;
}
ceph::crypto::init();
return conf;
}
void complain_about_parse_errors(std::deque<std::string> *parse_errors)
{
if (parse_errors->empty())
return;
derr << "Errors while parsing config file!" << dendl;
int cur_err = 0;
static const int MAX_PARSE_ERRORS = 20;
for (std::deque<std::string>::const_iterator p = parse_errors->begin();
p != parse_errors->end(); ++p)
{
derr << *p << dendl;
if (cur_err == MAX_PARSE_ERRORS) {
derr << "Suppressed " << (parse_errors->size() - MAX_PARSE_ERRORS)
<< " more errors." << dendl;
break;
}
++cur_err;
}
}
void common_init(std::vector < const char* >& args,
uint32_t module_type, code_environment_t code_env, int flags)
{
CephInitParameters iparams =
ceph_argparse_early_args(args, module_type, flags);
md_config_t *conf = common_preinit(iparams, code_env, flags);
std::deque<std::string> parse_errors;
int ret = conf->parse_config_files(iparams.get_conf_files(), &parse_errors);
if (ret == -EDOM) {
dout_emergency("common_init: error parsing config file.\n");
_exit(1);
}
else if (ret == -EINVAL) {
if (!(flags & CINIT_FLAG_NO_DEFAULT_CONFIG_FILE)) {
dout_emergency("common_init: unable to open config file.\n");
_exit(1);
}
}
else if (ret) {
dout_emergency("common_init: error reading config file.\n");
_exit(1);
}
conf->parse_env(); // environment variables override
conf->parse_argv(args); // argv override
if (code_env == CODE_ENVIRONMENT_DAEMON) {
if (conf->log_dir.empty() && conf->log_file.empty()) {
conf->set_val_or_die("log_file", "/var/log/ceph/$name.log");
}
}
// Expand metavariables. Invoke configuration observers.
conf->apply_changes();
// Now we're ready to complain about config file parse errors
complain_about_parse_errors(&parse_errors);
// signal stuff
int siglist[] = { SIGPIPE, 0 };
block_signals(NULL, siglist);
install_standard_sighandlers();
if (code_env == CODE_ENVIRONMENT_DAEMON) {
cout << TEXT_YELLOW << " ** WARNING: Ceph is still under heavy development, "
<< "and is only suitable for **" << TEXT_NORMAL << std::endl;
cout << TEXT_YELLOW << " ** testing and review. Do not trust it "
<< "with important data. **" << TEXT_NORMAL << std::endl;
output_ceph_version();
}
}
// TODO: until this is exposed to libceph/librados somehow, the
// library users cannot fork and expect to keep using the library
void common_prefork() {
// NSS is evil and breaks in forked children; shut it down properly
// and re-init in both parent and child, after the fork
ceph::crypto::shutdown();
}
void common_postfork() {
ceph::crypto::init();
}
static void pidfile_remove_void(void)
{
pidfile_remove();
}
// callers that fork must either use common_init_daemonize for that, or
// call common_prefork/common_postfork around the bit where they fork
void common_init_daemonize(const md_config_t *conf)
{
common_prefork();
int num_threads = Thread::get_num_threads();
if (num_threads > 1) {
derr << "common_init_daemonize: BUG: there are " << num_threads - 1
<< " child threads already started that will now die!" << dendl;
exit(1);
}
int ret = daemon(1, 0);
if (ret) {
ret = errno;
derr << "common_init_daemonize: BUG: daemon error: "
<< cpp_strerror(ret) << dendl;
exit(1);
}
if (!conf->chdir.empty()) {
if (::chdir(conf->chdir.c_str())) {
int err = errno;
derr << "common_init_daemonize: failed to chdir to directory: '"
<< conf->chdir << "': " << cpp_strerror(err) << dendl;
}
}
if (atexit(pidfile_remove_void)) {
derr << "common_init_daemonize: failed to set pidfile_remove function "
<< "to run at exit." << dendl;
}
// move these things into observers.
pidfile_write(&g_conf);
dout_handle_daemonize(&g_conf);
dout(1) << "finished common_init_daemonize" << dendl;
common_postfork();
}
<commit_msg>common: be a little less scary in our startup warning<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2010-2011 Dreamhost
*
* This 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. See file COPYING.
*
*/
#include "auth/AuthSupported.h"
#include "auth/KeyRing.h"
#include "common/DoutStreambuf.h"
#include "common/Thread.h"
#include "common/ceph_argparse.h"
#include "common/ceph_crypto.h"
#include "common/code_environment.h"
#include "common/common_init.h"
#include "common/config.h"
#include "common/errno.h"
#include "common/pidfile.h"
#include "common/safe_io.h"
#include "common/signal.h"
#include "common/version.h"
#include "include/color.h"
#include "common/Thread.h"
#include "common/pidfile.h"
#include <errno.h>
#include <deque>
#include <syslog.h>
#define _STR(x) #x
#define STRINGIFY(x) _STR(x)
int keyring_init(md_config_t *conf)
{
if (!is_supported_auth(CEPH_AUTH_CEPHX))
return 0;
int ret = 0;
string filename;
if (ceph_resolve_file_search(conf->keyring, filename)) {
ret = g_keyring.load(filename);
}
if (!conf->key.empty()) {
EntityAuth ea;
ea.key.decode_base64(conf->key);
g_keyring.add(conf->name, ea);
ret = 0;
} else if (!conf->keyfile.empty()) {
char buf[100];
int fd = ::open(conf->keyfile.c_str(), O_RDONLY);
if (fd < 0) {
int err = errno;
derr << "unable to open " << conf->keyfile << ": "
<< cpp_strerror(err) << dendl;
ceph_abort();
}
memset(buf, 0, sizeof(buf));
int len = safe_read(fd, buf, sizeof(buf) - 1);
if (len < 0) {
derr << "unable to read key from " << conf->keyfile << ": "
<< cpp_strerror(len) << dendl;
TEMP_FAILURE_RETRY(::close(fd));
ceph_abort();
}
TEMP_FAILURE_RETRY(::close(fd));
buf[len] = 0;
string k = buf;
EntityAuth ea;
ea.key.decode_base64(k);
g_keyring.add(conf->name, ea);
ret = 0;
}
if (ret)
derr << "keyring_init: failed to load " << filename << dendl;
return ret;
}
md_config_t *common_preinit(const CephInitParameters &iparams,
enum code_environment_t code_env, int flags)
{
// set code environment
g_code_env = code_env;
// Create a configuration object
// TODO: de-globalize
md_config_t *conf = &g_conf; //new md_config_t();
// add config observers here
// Set up our entity name.
conf->name = iparams.name;
// Set some defaults based on code type
switch (code_env) {
case CODE_ENVIRONMENT_DAEMON:
conf->daemonize = true;
if (!(flags & CINIT_FLAG_UNPRIVILEGED_DAEMON_DEFAULTS)) {
conf->set_val_or_die("pid_file", "/var/run/ceph/$type.$id.pid");
}
conf->set_val_or_die("log_to_stderr", STRINGIFY(LOG_TO_STDERR_SOME));
break;
default:
conf->set_val_or_die("daemonize", "false");
break;
}
ceph::crypto::init();
return conf;
}
void complain_about_parse_errors(std::deque<std::string> *parse_errors)
{
if (parse_errors->empty())
return;
derr << "Errors while parsing config file!" << dendl;
int cur_err = 0;
static const int MAX_PARSE_ERRORS = 20;
for (std::deque<std::string>::const_iterator p = parse_errors->begin();
p != parse_errors->end(); ++p)
{
derr << *p << dendl;
if (cur_err == MAX_PARSE_ERRORS) {
derr << "Suppressed " << (parse_errors->size() - MAX_PARSE_ERRORS)
<< " more errors." << dendl;
break;
}
++cur_err;
}
}
void common_init(std::vector < const char* >& args,
uint32_t module_type, code_environment_t code_env, int flags)
{
CephInitParameters iparams =
ceph_argparse_early_args(args, module_type, flags);
md_config_t *conf = common_preinit(iparams, code_env, flags);
std::deque<std::string> parse_errors;
int ret = conf->parse_config_files(iparams.get_conf_files(), &parse_errors);
if (ret == -EDOM) {
dout_emergency("common_init: error parsing config file.\n");
_exit(1);
}
else if (ret == -EINVAL) {
if (!(flags & CINIT_FLAG_NO_DEFAULT_CONFIG_FILE)) {
dout_emergency("common_init: unable to open config file.\n");
_exit(1);
}
}
else if (ret) {
dout_emergency("common_init: error reading config file.\n");
_exit(1);
}
conf->parse_env(); // environment variables override
conf->parse_argv(args); // argv override
if (code_env == CODE_ENVIRONMENT_DAEMON) {
if (conf->log_dir.empty() && conf->log_file.empty()) {
conf->set_val_or_die("log_file", "/var/log/ceph/$name.log");
}
}
// Expand metavariables. Invoke configuration observers.
conf->apply_changes();
// Now we're ready to complain about config file parse errors
complain_about_parse_errors(&parse_errors);
// signal stuff
int siglist[] = { SIGPIPE, 0 };
block_signals(NULL, siglist);
install_standard_sighandlers();
if (code_env == CODE_ENVIRONMENT_DAEMON) {
cout << TEXT_YELLOW
<< " ** WARNING: Ceph is still under development. Any feedback can be directed **"
<< TEXT_NORMAL << "\n" << TEXT_YELLOW
<< " ** at ceph-devel@vger.kernel.org or http://ceph.newdream.net/. **"
<< TEXT_NORMAL << std::endl;
output_ceph_version();
}
}
// TODO: until this is exposed to libceph/librados somehow, the
// library users cannot fork and expect to keep using the library
void common_prefork() {
// NSS is evil and breaks in forked children; shut it down properly
// and re-init in both parent and child, after the fork
ceph::crypto::shutdown();
}
void common_postfork() {
ceph::crypto::init();
}
static void pidfile_remove_void(void)
{
pidfile_remove();
}
// callers that fork must either use common_init_daemonize for that, or
// call common_prefork/common_postfork around the bit where they fork
void common_init_daemonize(const md_config_t *conf)
{
common_prefork();
int num_threads = Thread::get_num_threads();
if (num_threads > 1) {
derr << "common_init_daemonize: BUG: there are " << num_threads - 1
<< " child threads already started that will now die!" << dendl;
exit(1);
}
int ret = daemon(1, 0);
if (ret) {
ret = errno;
derr << "common_init_daemonize: BUG: daemon error: "
<< cpp_strerror(ret) << dendl;
exit(1);
}
if (!conf->chdir.empty()) {
if (::chdir(conf->chdir.c_str())) {
int err = errno;
derr << "common_init_daemonize: failed to chdir to directory: '"
<< conf->chdir << "': " << cpp_strerror(err) << dendl;
}
}
if (atexit(pidfile_remove_void)) {
derr << "common_init_daemonize: failed to set pidfile_remove function "
<< "to run at exit." << dendl;
}
// move these things into observers.
pidfile_write(&g_conf);
dout_handle_daemonize(&g_conf);
dout(1) << "finished common_init_daemonize" << dendl;
common_postfork();
}
<|endoftext|>
|
<commit_before>/*
* simple_tree.cpp
*
* Created on: Aug 12, 2010
* Author: programmer
*/
#include "../system/discursive_system.h"
#include "./initial_agents.h"
#include "repository_access.h"
#include <Magick++.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "../model/surrogate_tree_node.h"
#include "../dec/spatial_displacement.h"
#include "../draw/scanline_artist.h"
#include "../gen/space_colonizer.h"
using namespace Magick;
int debugLevel;
// display our command usage
void display_usage( void )
{
std::string usage_string = "\nsimple_tree [option] [optionstringorint] \n";
usage_string += "where option can be any of the following";
usage_string += "\n-g option - expects ~/Projects/source_tree_vis\n";
usage_string += "\n-G option - expects gitHubusername:gitHubprojectname\n";
usage_string += "\n-S option - expects http://hkit.googlecode.com/svn/trunk/\n";
usage_string += "\n-C option - expects pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd\n";
usage_string += "\n-i option - interactive mode (asks you questions) \n";
usage_string += "\n-d option - debug level, defaults to 1\n";
usage_string += "\n-O option - output file name, defaults to tree.jpg\n";
usage_string += "\n-m option - output the creation of the current tree one step at a time via many .jpgs in sequence\n";
usage_string += "\n--------------also expects the following start:stop:step i.e. 1:400:5 \n";
usage_string += "\n----------------start number for many jpg tree rendering, default is 3\n";
usage_string += "\n----------------finish number for many jpg tree rendering, default is treesize\n";
usage_string += "\n----------------step value for many jpg tree rendering, default is 1\n";
usage_string += "\n-r option - output the creation of the current tree one revision at a time via many .jpgs in sequence\n";
usage_string += "\n--------------also expects the following start:stop:step i.e. 1:400:5 \n";
usage_string += "\n----------------start number for many jpg tree rendering, default is 3\n";
usage_string += "\n----------------finish number for many jpg tree rendering, default is currentrevision\n";
usage_string += "\n----------------step value for many jpg tree rendering, default is 1\n";
usage_string += "\n-W option - spatial displacement scaling width level, defaults to .9\n";
usage_string += "\n-H option - spatial displacement scaling height level, defaults to .85\n";
DiscursivePrint("%s",usage_string.c_str());
DiscursiveError("Copyright Discursive Labs LLC, 2010");
}
int main(int argc, char **argv)
{
// set the debug level
SetDiscursiveDebugLevel(0);
// agentName equates to the passed command line parameter argument string
char *agentName = NULL;
// type of agent to use, ie command line options or interactive
int agentType = 0;
// scaling factors to use for spatial displacement
double scaleHeight = 0.85;
double scaleWidth = 0.9;
// our filename for output file
std::string fileName = "tree.jpg";
// should we make many jpgs?
int manyJpgs = 0;
// options for many jpgs
int jpgStep = 1;
int jpgStart = 3;
int jpgStop = 10000;
// should we output a jpg per revision?
int revJpgs = 0;
// options for jpg per revison
int revStep = 1;
int revStart = 2;
int revStop = 10000;
// our option string
static const char *optString = "g:G:S:C:H:W:O:m:R:ridh?";
// loop over our command options in the normal unix way
int opt;
opt = getopt( argc, argv, optString );
while( opt != -1 ) {
switch( opt ) {
case 'g':
agentName = optarg;
agentType = 1;
break;
case 'G':
agentName = optarg;
agentType = 2;
break;
case 'S':
agentName = optarg;
agentType = 3;
break;
case 'C':
agentName = optarg;
agentType = 4;
break;
case 'W':
scaleWidth = atof(optarg);
break;
case 'm':
manyJpgs = 1;
sscanf("%d:%d:%d",optarg,jpgStart,jpgStop,jpgStep);
if(jpgStart < 3)
{
jpgStart = 3;
}
break;
case 'R':
revJpgs = 1;
sscanf("%d:%d:%d",optarg,revStart,revStop,revStep);
if(revStart < 3)
{
revStart = 3;
}
break;
case 'r':
revJpgs = 1;
revStart = 3;
revStop = 100000;
revStep = 1;
break;
case 'H':
scaleHeight = atof(optarg);
break;
case 'O':
fileName = optarg;
break;
case 'd':
// set the debug level
SetDiscursiveDebugLevel(1);
break;
case 'i':
// set the interactivity level
agentType = 5;
break;
case 'h': /* fall-through is intentional */
case '?':
display_usage();
break;
default:
DiscursiveError("bad cli, bad!");
break;
}
// get the next Command Line option
opt = getopt( argc, argv, optString );
}
// Tree Generation pipeline
// create an abstract method for repository access
RepositoryAccess* git;
// let an interactive or command line agent create the repository access type
switch(agentType)
{
case 5:
git = interactive_agent();
break;
case 1:
case 2:
case 3:
case 4:
printf("%s\n",agentName);
git = noninteractive_agent(agentType, agentName);
break;
case 0:
display_usage();
break;
default:
/* You won't actually get here. */
DiscursiveError("an impossibility occured in error processing");
break;
}
// set our repository single or manyjpg options
git->snapshotJpgs = manyJpgs;
git->jpgIndex = 1000;
git->scaleHeight = scaleHeight;
git->scaleWidth = scaleWidth;
git->fileName = (char*)fileName.c_str();
git->globalInserts = 0;
git->localInserts = 0;
git->insertTarget = 0;
git->revJpgs = revJpgs;
git->globalRevs = 0;
git->localRevs = 0;
git->revTarget = 0;
git->currentTreeSize = 0;
git->logGenerated = 0;
// retrieve our source tree
git->source = git->retrieve();
// output tree info
DiscursivePrint("Source tree name is %s\n", git->source->data["name"].c_str());
DiscursivePrint("Source tree has %d revisions which require %d tree inserts\n",git->globalRevs,git->globalInserts);
// loop over a bunch of increasingly large trees for debug tree generation
if(manyJpgs && (git->globalInserts > 2))
{
if (jpgStop >= git->globalInserts)
{
jpgStop = git->globalInserts-1;
}
// use our user-set parameters to define our step
for(int i = jpgStart; i<jpgStop;i+= jpgStep)
{
// reset our insert variables
git->localInserts = 0;
git->insertTarget = i;
// retrieve our source tree
git->source = git->retrieve();
// init libmagick
//InitializeMagick("/");
DiscursivePrint("Decorating surrogate trees %d out of %d step value %d\n",i,jpgStop,jpgStep);
// Decorate surrogate tree nodes with locations
SpatialDisplacement* disp = new SpatialDisplacement(500,500,scaleWidth,scaleHeight);
disp->decorate(git->source);
DiscursivePrint("Digitizing decorated surrogate trees into line segment trees %d out of %d step value %d\n",i,jpgStop,jpgStep);
// Digitize decorated surrogate tree into line segment tree
SpaceColonizer* digitizer = new SpaceColonizer(2);
DrawableData* lines = digitizer->digitize(git->source);
// Transform
// Draw tree
DiscursivePrint("Drawing Tree %d out of %d step value %d",i,jpgStop,jpgStep);
Image canvas(Geometry(500,500),"white");
ScanlineArtist* artist = new ScanlineArtist();
artist->draw(canvas, lines);
// actually generate a tree
DiscursivePrint("Writing Tree %d out of %d step value %d\n\n",i,jpgStop,jpgStep);
git->WriteJPGFromCanvas(&canvas);
}
}
// loop over a bunch of increasingly large trees by revsion
if(revJpgs)
{
if (revStop >= git->globalRevs)
{
revStop = git->globalRevs-1;
}
// use our user-set parameters to define our step
for(int i = revStart; i<revStop;i+=revStep)
{
// reset our insert variables
git->localRevs = 0;
git->revTarget = i;
// retrieve our source tree
git->source = git->retrieve();
// init libmagick
//InitializeMagick("/");
std::string sourceTreeNameOutput = "Source tree name is";
sourceTreeNameOutput += git->source->data["name"].c_str();
DiscursiveDebugPrint(sourceTreeNameOutput);
DiscursivePrint("Decorating surrogate trees %d out of %d step value %d\n",i,revStop,revStep);
// Decorate surrogate tree nodes with locations
SpatialDisplacement* disp = new SpatialDisplacement(500,500,scaleWidth,scaleHeight);
disp->decorate(git->source);
DiscursivePrint("Digitizing decorated surrogate trees into line segment trees %d out of %d step value %d\n",i,revStop,revStep);
// Digitize decorated surrogate tree into line segment tree
SpaceColonizer* digitizer = new SpaceColonizer(2);
DrawableData* lines = digitizer->digitize(git->source);
// Transform
// Draw tree
DiscursivePrint("Drawing Tree %d out of %d step value %d",i,revStop,revStep);
Image canvas(Geometry(500,500),"white");
ScanlineArtist* artist = new ScanlineArtist();
artist->draw(canvas, lines);
// actually generate a tree
DiscursivePrint("Writing Tree %d out of %d step value %d\n\n",i,revStop,revStep);
git->WriteJPGFromCanvas(&canvas);
}
}
// init libmagick
//InitializeMagick("/");
std::string sourceTreeNameOutput = "Source tree name is";
sourceTreeNameOutput += git->source->data["name"].c_str();
DiscursiveDebugPrint(sourceTreeNameOutput);
// Decorate surrogate tree nodes with locations
DiscursivePrint("Decorating surrogate trees\n");
SpatialDisplacement* disp = new SpatialDisplacement(500,500,scaleWidth,scaleHeight);
disp->decorate(git->source);
// Digitize decorated surrogate tree into line segment tree
DiscursivePrint("Digitizing decorated surrogate trees into line segment trees\n");
SpaceColonizer* digitizer = new SpaceColonizer(2);
DrawableData* lines = digitizer->digitize(git->source);
// Transform
// Draw tree
DiscursivePrint("Drawing Tree\n");
Image canvas(Geometry(500,500),"white");
ScanlineArtist* artist = new ScanlineArtist();
artist->draw(canvas, lines);
// actually generate a tree (or the final tree if many)
DiscursivePrint("Writing Final Tree\n");
git->WriteJPGFromCanvas(&canvas);
return 0;
}
<commit_msg>updated options so -r and -R work<commit_after>/*
* simple_tree.cpp
*
* Created on: Aug 12, 2010
* Author: programmer
*/
#include "../system/discursive_system.h"
#include "./initial_agents.h"
#include "repository_access.h"
#include <Magick++.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "../model/surrogate_tree_node.h"
#include "../dec/spatial_displacement.h"
#include "../draw/scanline_artist.h"
#include "../gen/space_colonizer.h"
using namespace Magick;
int debugLevel;
// display our command usage
void display_usage( void )
{
std::string usage_string = "\nsimple_tree [option] [optionstringorint] \n";
usage_string += "where option can be any of the following";
usage_string += "\n-g option - expects ~/Projects/source_tree_vis\n";
usage_string += "\n-G option - expects gitHubusername:gitHubprojectname\n";
usage_string += "\n-S option - expects http://hkit.googlecode.com/svn/trunk/\n";
usage_string += "\n-C option - expects pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd\n";
usage_string += "\n-i option - interactive mode (asks you questions) \n";
usage_string += "\n-d option - debug level, defaults to 1\n";
usage_string += "\n-O option - output file name, defaults to tree.jpg\n";
usage_string += "\n-m option - output the creation of the current tree one step at a time via many .jpgs in sequence\n";
usage_string += "\n--------------also expects the following start:stop:step i.e. 1:400:5 \n";
usage_string += "\n----------------start number for many jpg tree rendering, default is 3\n";
usage_string += "\n----------------finish number for many jpg tree rendering, default is treesize\n";
usage_string += "\n----------------step value for many jpg tree rendering, default is 1\n";
usage_string += "\n-R and -r option -output the creation of the current tree one revision at a time via many .jpgs in sequence\n";
usage_string += "\n-------------- -R also expects the following start:stop:step i.e. 1:400:5 \n";
usage_string += "\n----------------start number for many jpg tree rendering, default is 3\n";
usage_string += "\n----------------finish number for many jpg tree rendering, default is currentrevision\n";
usage_string += "\n----------------step value for many jpg tree rendering, default is 1\n";
usage_string += "\n-W option - spatial displacement scaling width level, defaults to .9\n";
usage_string += "\n-H option - spatial displacement scaling height level, defaults to .85\n";
DiscursivePrint("%s",usage_string.c_str());
DiscursiveError("Copyright Discursive Labs LLC, 2010");
}
int main(int argc, char **argv)
{
// set the debug level
SetDiscursiveDebugLevel(0);
// agentName equates to the passed command line parameter argument string
char *agentName = NULL;
// type of agent to use, ie command line options or interactive
int agentType = 0;
// scaling factors to use for spatial displacement
double scaleHeight = 0.85;
double scaleWidth = 0.9;
// our filename for output file
std::string fileName = "tree.jpg";
// should we make many jpgs?
int manyJpgs = 0;
// options for many jpgs
int jpgStep = 1;
int jpgStart = 3;
int jpgStop = 10000;
// should we output a jpg per revision?
int revJpgs = 0;
// options for jpg per revison
int revStep = 1;
int revStart = 2;
int revStop = 10000;
// our option string
static const char *optString = "g:G:S:C:H:W:O:m:R:ridh?";
// loop over our command options in the normal unix way
int opt;
opt = getopt( argc, argv, optString );
while( opt != -1 ) {
switch( opt ) {
case 'g':
agentName = optarg;
agentType = 1;
break;
case 'G':
agentName = optarg;
agentType = 2;
break;
case 'S':
agentName = optarg;
agentType = 3;
break;
case 'C':
agentName = optarg;
agentType = 4;
break;
case 'W':
scaleWidth = atof(optarg);
break;
case 'm':
manyJpgs = 1;
sscanf("%d:%d:%d",optarg,jpgStart,jpgStop,jpgStep);
if(jpgStart < 3)
{
jpgStart = 3;
}
break;
case 'R':
revJpgs = 1;
sscanf("%d:%d:%d",optarg,revStart,revStop,revStep);
if(revStart < 3)
{
revStart = 3;
}
break;
case 'r':
revJpgs = 1;
revStart = 3;
revStop = 100000;
revStep = 1;
break;
case 'H':
scaleHeight = atof(optarg);
break;
case 'O':
fileName = optarg;
break;
case 'd':
// set the debug level
SetDiscursiveDebugLevel(1);
break;
case 'i':
// set the interactivity level
agentType = 5;
break;
case 'h': /* fall-through is intentional */
case '?':
display_usage();
break;
default:
DiscursiveError("bad cli, bad!");
break;
}
// get the next Command Line option
opt = getopt( argc, argv, optString );
}
// Tree Generation pipeline
// create an abstract method for repository access
RepositoryAccess* git;
// let an interactive or command line agent create the repository access type
switch(agentType)
{
case 5:
git = interactive_agent();
break;
case 1:
case 2:
case 3:
case 4:
printf("%s\n",agentName);
git = noninteractive_agent(agentType, agentName);
break;
case 0:
display_usage();
break;
default:
/* You won't actually get here. */
DiscursiveError("an impossibility occured in error processing");
break;
}
// set our repository single or manyjpg options
git->snapshotJpgs = manyJpgs;
git->jpgIndex = 1000;
git->scaleHeight = scaleHeight;
git->scaleWidth = scaleWidth;
git->fileName = (char*)fileName.c_str();
git->globalInserts = 0;
git->localInserts = 0;
git->insertTarget = 0;
git->revJpgs = revJpgs;
git->globalRevs = 0;
git->localRevs = 0;
git->revTarget = 0;
git->currentTreeSize = 0;
git->logGenerated = 0;
// retrieve our source tree
git->source = git->retrieve();
// output tree info
DiscursivePrint("Source tree name is %s\n", git->source->data["name"].c_str());
DiscursivePrint("Source tree has %d revisions which require %d tree inserts\n",git->globalRevs,git->globalInserts);
// loop over a bunch of increasingly large trees for debug tree generation
if(manyJpgs && (git->globalInserts > 2))
{
if (jpgStop >= git->globalInserts)
{
jpgStop = git->globalInserts-1;
}
// use our user-set parameters to define our step
for(int i = jpgStart; i<jpgStop;i+= jpgStep)
{
// reset our insert variables
git->localInserts = 0;
git->insertTarget = i;
// retrieve our source tree
git->source = git->retrieve();
// init libmagick
//InitializeMagick("/");
DiscursivePrint("Decorating surrogate trees %d out of %d step value %d\n",i,jpgStop,jpgStep);
// Decorate surrogate tree nodes with locations
SpatialDisplacement* disp = new SpatialDisplacement(500,500,scaleWidth,scaleHeight);
disp->decorate(git->source);
DiscursivePrint("Digitizing decorated surrogate trees into line segment trees %d out of %d step value %d\n",i,jpgStop,jpgStep);
// Digitize decorated surrogate tree into line segment tree
SpaceColonizer* digitizer = new SpaceColonizer(2);
DrawableData* lines = digitizer->digitize(git->source);
// Transform
// Draw tree
DiscursivePrint("Drawing Tree %d out of %d step value %d",i,jpgStop,jpgStep);
Image canvas(Geometry(500,500),"white");
ScanlineArtist* artist = new ScanlineArtist();
artist->draw(canvas, lines);
// actually generate a tree
DiscursivePrint("Writing Tree %d out of %d step value %d\n\n",i,jpgStop,jpgStep);
git->WriteJPGFromCanvas(&canvas);
}
}
// loop over a bunch of increasingly large trees by revsion
if(revJpgs)
{
if (revStop >= git->globalRevs)
{
revStop = git->globalRevs-1;
}
// use our user-set parameters to define our step
for(int i = revStart; i<revStop;i+=revStep)
{
// reset our insert variables
git->localRevs = 0;
git->revTarget = i;
// retrieve our source tree
git->source = git->retrieve();
// init libmagick
//InitializeMagick("/");
std::string sourceTreeNameOutput = "Source tree name is";
sourceTreeNameOutput += git->source->data["name"].c_str();
DiscursiveDebugPrint(sourceTreeNameOutput);
DiscursivePrint("Decorating surrogate trees %d out of %d step value %d\n",i,revStop,revStep);
// Decorate surrogate tree nodes with locations
SpatialDisplacement* disp = new SpatialDisplacement(500,500,scaleWidth,scaleHeight);
disp->decorate(git->source);
DiscursivePrint("Digitizing decorated surrogate trees into line segment trees %d out of %d step value %d\n",i,revStop,revStep);
// Digitize decorated surrogate tree into line segment tree
SpaceColonizer* digitizer = new SpaceColonizer(2);
DrawableData* lines = digitizer->digitize(git->source);
// Transform
// Draw tree
DiscursivePrint("Drawing Tree %d out of %d step value %d",i,revStop,revStep);
Image canvas(Geometry(500,500),"white");
ScanlineArtist* artist = new ScanlineArtist();
artist->draw(canvas, lines);
// actually generate a tree
DiscursivePrint("Writing Tree %d out of %d step value %d\n\n",i,revStop,revStep);
git->WriteJPGFromCanvas(&canvas);
}
}
// init libmagick
//InitializeMagick("/");
std::string sourceTreeNameOutput = "Source tree name is";
sourceTreeNameOutput += git->source->data["name"].c_str();
DiscursiveDebugPrint(sourceTreeNameOutput);
// Decorate surrogate tree nodes with locations
DiscursivePrint("Decorating surrogate trees\n");
SpatialDisplacement* disp = new SpatialDisplacement(500,500,scaleWidth,scaleHeight);
disp->decorate(git->source);
// Digitize decorated surrogate tree into line segment tree
DiscursivePrint("Digitizing decorated surrogate trees into line segment trees\n");
SpaceColonizer* digitizer = new SpaceColonizer(2);
DrawableData* lines = digitizer->digitize(git->source);
// Transform
// Draw tree
DiscursivePrint("Drawing Tree\n");
Image canvas(Geometry(500,500),"white");
ScanlineArtist* artist = new ScanlineArtist();
artist->draw(canvas, lines);
// actually generate a tree (or the final tree if many)
DiscursivePrint("Writing Final Tree\n");
git->WriteJPGFromCanvas(&canvas);
return 0;
}
<|endoftext|>
|
<commit_before>//
// References to arrays, C++98.
//
// http://stackoverflow.com/a/10008405
// http://c-faq.com/decl/spiral.anderson.html
// http://unixwiz.net/techtips/reading-cdecl.html
//
#include <iostream>
namespace
{
void pass_array_ref(int (&ra)[100])
{
ra[0] = -456;
}
int (&get_array_ref())[55]
{
static int a2[55];
return a2;
}
} // unnamed namespace
int main()
{
int a[100];
int (&ra)[100] = a;
const int (&cra)[100] = a;
//int (&ra2)[55] = a; // compilation error
int (&ra2)[55] = get_array_ref();
ra[0] = 234;
//cra[0] = 234; // compilation error
std::cout << "before calling `pass_array_ref()`:\n";
std::cout << "a[0] == " << a[0] << '\n';
std::cout << "ra[0] == " << ra[0] << '\n';
std::cout << "cra[0] == " << cra[0] << std::endl;
pass_array_ref(a);
//pass_array_ref(ra); // OK but unnecessary
//pass_array_ref(ra2); // compilation error
std::cout << "after calling `pass_array_ref()`:\n";
std::cout << "a[0] == " << a[0] << '\n';
std::cout << "ra[0] == " << ra[0] << '\n';
std::cout << "cra[0] == " << cra[0] << std::endl;
std::cout << "before changing `get_array_ref()[3]`:\n";
std::cout << "ra2[3] == " << ra2[3] << '\n';
get_array_ref()[3] = -1;
std::cout << "after changing `get_array_ref()[3]`:\n";
std::cout << "ra2[3] == " << ra2[3] << std::endl;
}
<commit_msg>Update ref_to_array.cpp<commit_after>//
// References to arrays, C++98.
//
// http://stackoverflow.com/a/10008405
// http://c-faq.com/decl/spiral.anderson.html
// http://unixwiz.net/techtips/reading-cdecl.html
//
#include <iostream>
namespace
{
void pass_array_ref(int (&ra)[100])
{
ra[0] = -456;
}
int (&get_array_ref())[55]
{
static int a2[55];
return a2;
}
} // unnamed namespace
int main()
{
int a[100];
int (&ra)[100] = a;
const int (&cra)[100] = a;
//int (&ra2)[55] = a; // compilation error
int (&ra2)[55] = get_array_ref();
ra[0] = 234;
//cra[0] = 234; // compilation error
std::cout << "before calling `pass_array_ref()`:\n";
std::cout << "a[0] == " << a[0] << '\n';
std::cout << "ra[0] == " << ra[0] << '\n';
std::cout << "cra[0] == " << cra[0] << std::endl;
pass_array_ref(a);
//pass_array_ref(ra); // OK but unnecessary
//pass_array_ref(cra); // compilation error
//pass_array_ref(ra2); // compilation error
std::cout << "after calling `pass_array_ref()`:\n";
std::cout << "a[0] == " << a[0] << '\n';
std::cout << "ra[0] == " << ra[0] << '\n';
std::cout << "cra[0] == " << cra[0] << std::endl;
std::cout << "before changing `get_array_ref()[3]`:\n";
std::cout << "ra2[3] == " << ra2[3] << '\n';
get_array_ref()[3] = -1;
std::cout << "after changing `get_array_ref()[3]`:\n";
std::cout << "ra2[3] == " << ra2[3] << std::endl;
}
<|endoftext|>
|
<commit_before>/** \brief Handles crawling as well as RSS feeds.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <memory>
#include <unordered_map>
#include <cstdlib>
#include "DbConnection.h"
#include "IniFile.h"
#include "MARC.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "util.h"
#include "Zotero.h"
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << " [--verbosity=log_level] [--ignore-robots-dot-txt] config_file_path [section1 section2 .. sectionN]\n"
<< " Possible log levels are ERROR, WARNING, INFO, and DEBUG with the default being WARNING.\n"
<< " If any section names have been provided, only those will be processed o/w all sections will be processed.\n\n";
std::exit(EXIT_FAILURE);
}
UnsignedPair ProcessRSSFeed(const IniFile::Section §ion, const std::shared_ptr<Zotero::HarvestParams> &harvest_params,
Zotero::AugmentParams * const augment_params, DbConnection * const db_connection)
{
augment_params->override_ISSN_ = section.getString("issn", "");
augment_params->strptime_format_ = section.getString("strptime_format", "");
const std::string feed_url(section.getString("feed"));
LOG_DEBUG("feed_url: " + feed_url);
return Zotero::HarvestSyndicationURL(Zotero::RSSHarvestMode::NORMAL, feed_url, harvest_params, augment_params, db_connection);
}
void InitSiteDescFromIniFileSection(const IniFile::Section §ion, SimpleCrawler::SiteDesc * const site_desc) {
site_desc->start_url_ = section.getString("base_url");
site_desc->max_crawl_depth_ = section.getUnsigned("max_crawl_depth");
site_desc->url_regex_matcher_.reset(RegexMatcher::FactoryOrDie(section.getString("extraction_regex")));
}
UnsignedPair ProcessCrawl(const IniFile::Section §ion, const std::shared_ptr<Zotero::HarvestParams> &harvest_params,
Zotero::AugmentParams * const augment_params, const SimpleCrawler::Params &crawler_params,
const std::shared_ptr<RegexMatcher> &supported_urls_regex)
{
augment_params->override_ISSN_ = section.getString("issn", "");
augment_params->strptime_format_ = section.getString("strptime_format", "");
SimpleCrawler::SiteDesc site_desc;
InitSiteDescFromIniFileSection(section, &site_desc);
return Zotero::HarvestSite(site_desc, crawler_params, supported_urls_regex, harvest_params, augment_params);
}
std::string GetMarcFormat(const std::string &output_filename) {
switch (MARC::GuessFileType(output_filename)) {
case MARC::FileType::BINARY:
return "marc21";
case MARC::FileType::XML:
return "marcxml";
default:
LOG_ERROR("can't determine output format from MARC output filename \"" + output_filename + "\"!");
}
}
const std::string RSS_HARVESTER_CONF_FILE_PATH("/usr/local/var/lib/tuelib/rss_harvester.conf");
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc < 2)
Usage();
bool ignore_robots_dot_txt(false);
if (std::strcmp(argv[1], "--ignore-robots-dot-txt") == 0) {
ignore_robots_dot_txt = true;
++argc, --argv;
if (argc < 2)
Usage();
}
IniFile ini_file(argv[1]);
std::shared_ptr<Zotero::HarvestParams> harvest_params(new Zotero::HarvestParams);
harvest_params->zts_server_url_ = Url(ini_file.getString("", "zts_server_url"));
std::string map_directory_path(ini_file.getString("", "map_directory_path"));
if (not StringUtil::EndsWith(map_directory_path, '/'))
map_directory_path += '/';
Zotero::AugmentMaps augment_maps(map_directory_path);
Zotero::AugmentParams augment_params(&augment_maps);
const std::shared_ptr<RegexMatcher> supported_urls_regex(Zotero::LoadSupportedURLsRegex(map_directory_path));
std::unique_ptr<DbConnection> db_connection;
const IniFile rss_ini_file(RSS_HARVESTER_CONF_FILE_PATH);
const std::string sql_database(rss_ini_file.getString("Database", "sql_database"));
const std::string sql_username(rss_ini_file.getString("Database", "sql_username"));
const std::string sql_password(rss_ini_file.getString("Database", "sql_password"));
db_connection.reset(new DbConnection(sql_database, sql_username, sql_password));
const std::string MARC_OUTPUT_FILE(ini_file.getString("", "marc_output_file"));
harvest_params->format_handler_ = Zotero::FormatHandler::Factory(GetMarcFormat(MARC_OUTPUT_FILE), MARC_OUTPUT_FILE,
&augment_params, harvest_params);
SimpleCrawler::Params crawler_params;
crawler_params.ignore_robots_dot_txt_ = ignore_robots_dot_txt;
crawler_params.min_url_processing_time_ = Zotero::DEFAULT_MIN_URL_PROCESSING_TIME;
crawler_params.timeout_ = Zotero::DEFAULT_TIMEOUT;
std::unordered_map<std::string, bool> section_name_to_found_flag_map;
for (int arg_no(2); arg_no < argc; ++arg_no)
section_name_to_found_flag_map.emplace(argv[arg_no], false);
enum Type { RSS, CRAWL };
const std::map<std::string, int> string_to_value_map{ {"RSS", RSS }, { "CRAWL", CRAWL } };
unsigned processed_section_count(0);
UnsignedPair total_record_count_and_previously_downloaded_record_count;
for (const auto §ion : ini_file) {
if (not section_name_to_found_flag_map.empty()) {
const auto section_name_and_found_flag(section_name_to_found_flag_map.find(section.first));
if (section_name_and_found_flag == section_name_to_found_flag_map.end())
continue;
section_name_and_found_flag->second = true;
}
++processed_section_count;
LOG_INFO("Processing section \"" + section.first + "\".");
const Type type(static_cast<Type>(section.second.getEnum("type", string_to_value_map)));
if (type == RSS)
total_record_count_and_previously_downloaded_record_count += ProcessRSSFeed(section.second, harvest_params, &augment_params,
db_connection.get());
else
total_record_count_and_previously_downloaded_record_count +=
ProcessCrawl(section.second, harvest_params, &augment_params, crawler_params, supported_urls_regex);
}
LOG_INFO("Extracted metadata from "
+ std::to_string(total_record_count_and_previously_downloaded_record_count.first
- total_record_count_and_previously_downloaded_record_count.second) + " page(s).");
if (section_name_to_found_flag_map.size() > processed_section_count) {
std::cerr << "The following sections were specified but not processed:\n";
for (const auto §ion_name_and_found_flag : section_name_to_found_flag_map)
std::cerr << '\t' << section_name_and_found_flag.first << '\n';
}
return EXIT_SUCCESS;
}
<commit_msg>Fill in the time string format in the site descriptor before pasing it to Zotero::HarvestSite<commit_after>/** \brief Handles crawling as well as RSS feeds.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <memory>
#include <unordered_map>
#include <cstdlib>
#include "DbConnection.h"
#include "IniFile.h"
#include "MARC.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "util.h"
#include "Zotero.h"
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << " [--verbosity=log_level] [--ignore-robots-dot-txt] config_file_path [section1 section2 .. sectionN]\n"
<< " Possible log levels are ERROR, WARNING, INFO, and DEBUG with the default being WARNING.\n"
<< " If any section names have been provided, only those will be processed o/w all sections will be processed.\n\n";
std::exit(EXIT_FAILURE);
}
UnsignedPair ProcessRSSFeed(const IniFile::Section §ion, const std::shared_ptr<Zotero::HarvestParams> &harvest_params,
Zotero::AugmentParams * const augment_params, DbConnection * const db_connection)
{
augment_params->override_ISSN_ = section.getString("issn", "");
augment_params->strptime_format_ = section.getString("strptime_format", "");
const std::string feed_url(section.getString("feed"));
LOG_DEBUG("feed_url: " + feed_url);
return Zotero::HarvestSyndicationURL(Zotero::RSSHarvestMode::NORMAL, feed_url, harvest_params, augment_params, db_connection);
}
void InitSiteDescFromIniFileSection(const IniFile::Section §ion, SimpleCrawler::SiteDesc * const site_desc) {
site_desc->start_url_ = section.getString("base_url");
site_desc->max_crawl_depth_ = section.getUnsigned("max_crawl_depth");
site_desc->url_regex_matcher_.reset(RegexMatcher::FactoryOrDie(section.getString("extraction_regex")));
site_desc->strptime_format_ = section.getString("strptime_format", "");
}
UnsignedPair ProcessCrawl(const IniFile::Section §ion, const std::shared_ptr<Zotero::HarvestParams> &harvest_params,
Zotero::AugmentParams * const augment_params, const SimpleCrawler::Params &crawler_params,
const std::shared_ptr<RegexMatcher> &supported_urls_regex)
{
augment_params->override_ISSN_ = section.getString("issn", "");
augment_params->strptime_format_ = section.getString("strptime_format", "");
SimpleCrawler::SiteDesc site_desc;
InitSiteDescFromIniFileSection(section, &site_desc);
return Zotero::HarvestSite(site_desc, crawler_params, supported_urls_regex, harvest_params, augment_params);
}
std::string GetMarcFormat(const std::string &output_filename) {
switch (MARC::GuessFileType(output_filename)) {
case MARC::FileType::BINARY:
return "marc21";
case MARC::FileType::XML:
return "marcxml";
default:
LOG_ERROR("can't determine output format from MARC output filename \"" + output_filename + "\"!");
}
}
const std::string RSS_HARVESTER_CONF_FILE_PATH("/usr/local/var/lib/tuelib/rss_harvester.conf");
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc < 2)
Usage();
bool ignore_robots_dot_txt(false);
if (std::strcmp(argv[1], "--ignore-robots-dot-txt") == 0) {
ignore_robots_dot_txt = true;
++argc, --argv;
if (argc < 2)
Usage();
}
IniFile ini_file(argv[1]);
std::shared_ptr<Zotero::HarvestParams> harvest_params(new Zotero::HarvestParams);
harvest_params->zts_server_url_ = Url(ini_file.getString("", "zts_server_url"));
std::string map_directory_path(ini_file.getString("", "map_directory_path"));
if (not StringUtil::EndsWith(map_directory_path, '/'))
map_directory_path += '/';
Zotero::AugmentMaps augment_maps(map_directory_path);
Zotero::AugmentParams augment_params(&augment_maps);
const std::shared_ptr<RegexMatcher> supported_urls_regex(Zotero::LoadSupportedURLsRegex(map_directory_path));
std::unique_ptr<DbConnection> db_connection;
const IniFile rss_ini_file(RSS_HARVESTER_CONF_FILE_PATH);
const std::string sql_database(rss_ini_file.getString("Database", "sql_database"));
const std::string sql_username(rss_ini_file.getString("Database", "sql_username"));
const std::string sql_password(rss_ini_file.getString("Database", "sql_password"));
db_connection.reset(new DbConnection(sql_database, sql_username, sql_password));
const std::string MARC_OUTPUT_FILE(ini_file.getString("", "marc_output_file"));
harvest_params->format_handler_ = Zotero::FormatHandler::Factory(GetMarcFormat(MARC_OUTPUT_FILE), MARC_OUTPUT_FILE,
&augment_params, harvest_params);
SimpleCrawler::Params crawler_params;
crawler_params.ignore_robots_dot_txt_ = ignore_robots_dot_txt;
crawler_params.min_url_processing_time_ = Zotero::DEFAULT_MIN_URL_PROCESSING_TIME;
crawler_params.timeout_ = Zotero::DEFAULT_TIMEOUT;
std::unordered_map<std::string, bool> section_name_to_found_flag_map;
for (int arg_no(2); arg_no < argc; ++arg_no)
section_name_to_found_flag_map.emplace(argv[arg_no], false);
enum Type { RSS, CRAWL };
const std::map<std::string, int> string_to_value_map{ {"RSS", RSS }, { "CRAWL", CRAWL } };
unsigned processed_section_count(0);
UnsignedPair total_record_count_and_previously_downloaded_record_count;
for (const auto §ion : ini_file) {
if (not section_name_to_found_flag_map.empty()) {
const auto section_name_and_found_flag(section_name_to_found_flag_map.find(section.first));
if (section_name_and_found_flag == section_name_to_found_flag_map.end())
continue;
section_name_and_found_flag->second = true;
}
++processed_section_count;
LOG_INFO("Processing section \"" + section.first + "\".");
const Type type(static_cast<Type>(section.second.getEnum("type", string_to_value_map)));
if (type == RSS)
total_record_count_and_previously_downloaded_record_count += ProcessRSSFeed(section.second, harvest_params, &augment_params,
db_connection.get());
else
total_record_count_and_previously_downloaded_record_count +=
ProcessCrawl(section.second, harvest_params, &augment_params, crawler_params, supported_urls_regex);
}
LOG_INFO("Extracted metadata from "
+ std::to_string(total_record_count_and_previously_downloaded_record_count.first
- total_record_count_and_previously_downloaded_record_count.second) + " page(s).");
if (section_name_to_found_flag_map.size() > processed_section_count) {
std::cerr << "The following sections were specified but not processed:\n";
for (const auto §ion_name_and_found_flag : section_name_to_found_flag_map)
std::cerr << '\t' << section_name_and_found_flag.first << '\n';
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <boost/test/unit_test.hpp>
#include "indexed_sam_reader.h"
#include "test_utils.h"
using namespace std;
using namespace gamgee;
using namespace gamgee::utils;
BOOST_AUTO_TEST_CASE( indexed_single_readers_intervals )
{
for (const auto& filename : {"testdata/test_simple.bam"}) {
auto read_counter = 0u;
const auto interval_list = vector<string>{"chr1:201-257", "chr1:30001-40000", "chr1:59601-70000", "chr1:94001"};
for (const auto& sam : IndexedSingleSamReader{filename, interval_list}) {
BOOST_CHECK_EQUAL(sam.name().substr(0, 15), "30PPJAAXX090125");
BOOST_CHECK_EQUAL(sam.chromosome(), 0);
++read_counter;
}
BOOST_CHECK_EQUAL(read_counter, 15u);
const auto interval_read_counts = vector<int>{3, 4, 4, 4};
auto interval_number = 0u;
for (const auto& interval : interval_list) {
auto interval_read_counter = 0u;
for (const auto& sam : IndexedSingleSamReader{filename, vector<string>{interval}}) {
BOOST_CHECK_EQUAL(sam.name().substr(0, 15), "30PPJAAXX090125");
BOOST_CHECK_EQUAL(sam.chromosome(), 0);
++interval_read_counter;
}
BOOST_CHECK_EQUAL(interval_read_counter, interval_read_counts[interval_number]);
++interval_number;
}
}
}
BOOST_AUTO_TEST_CASE( indexed_single_readers_entire_file )
{
const auto entire_file = vector<string>{"."};
for (const auto& filename : {"testdata/test_simple.bam"}) {
auto read_counter = 0u;
for (const auto& sam : IndexedSingleSamReader{filename, entire_file}) {
BOOST_CHECK_EQUAL(sam.name().substr(0, 15), "30PPJAAXX090125");
BOOST_CHECK_EQUAL(sam.chromosome(), 0);
++read_counter;
}
BOOST_CHECK_EQUAL(read_counter, 33u);
}
}
BOOST_AUTO_TEST_CASE( indexed_single_readers_unmapped )
{
const auto unmapped_reads = vector<string>{"*"};
for (const auto& filename : {"testdata/test_simple.bam"}) {
auto read_counter = 0u;
for (const auto& sam : IndexedSingleSamReader{filename, unmapped_reads}) {
BOOST_CHECK_EQUAL(sam.name().substr(0, 15), "30PPJAAXX090125");
BOOST_CHECK_EQUAL(sam.chromosome(), 0);
++read_counter;
}
BOOST_CHECK_EQUAL(read_counter, 0u);
}
}
BOOST_AUTO_TEST_CASE( indexed_single_readers_empty )
{
const auto empty_list = vector<string>{};
for (const auto& filename : {"testdata/test_simple.bam"}) {
auto read_counter = 0u;
for (const auto& sam : IndexedSingleSamReader{filename, empty_list}) {
BOOST_CHECK_EQUAL(sam.name().substr(0, 15), "30PPJAAXX090125");
BOOST_CHECK_EQUAL(sam.chromosome(), 0);
++read_counter;
}
BOOST_CHECK_EQUAL(read_counter, 0u);
}
}
BOOST_AUTO_TEST_CASE( indexed_single_readers_move_constructor_and_assignment ) {
auto r0 = IndexedSingleSamReader{"testdata/test_simple.bam", vector<string>{"."}};
auto m1 = check_move_constructor(r0);
auto m2 = IndexedSingleSamReader{"testdata/test_simple.bam", vector<string>{"."}};
BOOST_CHECK_EQUAL((*(m1.begin())).alignment_start(), (*(m2.begin())).alignment_start());
}
BOOST_AUTO_TEST_CASE( indexed_single_readers_begin_always_restarts ) {
auto reader1 = IndexedSingleSamReader{"testdata/test_simple.bam", vector<string>{"."}};
auto it1 = reader1.begin();
++it1;
auto it2 = reader1.begin();
BOOST_CHECK_NE((*it1).alignment_start(), (*it2).alignment_start());
++it2;
BOOST_CHECK_EQUAL((*it1).alignment_start(), (*it2).alignment_start());
}
<commit_msg>Add IndexedSamIterator check_move_constructor test<commit_after>#include <boost/test/unit_test.hpp>
#include "indexed_sam_reader.h"
#include "test_utils.h"
using namespace std;
using namespace gamgee;
using namespace gamgee::utils;
BOOST_AUTO_TEST_CASE( indexed_single_readers_intervals )
{
for (const auto& filename : {"testdata/test_simple.bam"}) {
auto read_counter = 0u;
const auto interval_list = vector<string>{"chr1:201-257", "chr1:30001-40000", "chr1:59601-70000", "chr1:94001"};
for (const auto& sam : IndexedSingleSamReader{filename, interval_list}) {
BOOST_CHECK_EQUAL(sam.name().substr(0, 15), "30PPJAAXX090125");
BOOST_CHECK_EQUAL(sam.chromosome(), 0);
++read_counter;
}
BOOST_CHECK_EQUAL(read_counter, 15u);
const auto interval_read_counts = vector<int>{3, 4, 4, 4};
auto interval_number = 0u;
for (const auto& interval : interval_list) {
auto interval_read_counter = 0u;
for (const auto& sam : IndexedSingleSamReader{filename, vector<string>{interval}}) {
BOOST_CHECK_EQUAL(sam.name().substr(0, 15), "30PPJAAXX090125");
BOOST_CHECK_EQUAL(sam.chromosome(), 0);
++interval_read_counter;
}
BOOST_CHECK_EQUAL(interval_read_counter, interval_read_counts[interval_number]);
++interval_number;
}
}
}
BOOST_AUTO_TEST_CASE( indexed_single_readers_entire_file )
{
const auto entire_file = vector<string>{"."};
for (const auto& filename : {"testdata/test_simple.bam"}) {
auto read_counter = 0u;
for (const auto& sam : IndexedSingleSamReader{filename, entire_file}) {
BOOST_CHECK_EQUAL(sam.name().substr(0, 15), "30PPJAAXX090125");
BOOST_CHECK_EQUAL(sam.chromosome(), 0);
++read_counter;
}
BOOST_CHECK_EQUAL(read_counter, 33u);
}
}
BOOST_AUTO_TEST_CASE( indexed_single_readers_unmapped )
{
const auto unmapped_reads = vector<string>{"*"};
for (const auto& filename : {"testdata/test_simple.bam"}) {
auto read_counter = 0u;
for (const auto& sam : IndexedSingleSamReader{filename, unmapped_reads}) {
BOOST_CHECK_EQUAL(sam.name().substr(0, 15), "30PPJAAXX090125");
BOOST_CHECK_EQUAL(sam.chromosome(), 0);
++read_counter;
}
BOOST_CHECK_EQUAL(read_counter, 0u);
}
}
BOOST_AUTO_TEST_CASE( indexed_single_readers_empty )
{
const auto empty_list = vector<string>{};
for (const auto& filename : {"testdata/test_simple.bam"}) {
auto read_counter = 0u;
for (const auto& sam : IndexedSingleSamReader{filename, empty_list}) {
BOOST_CHECK_EQUAL(sam.name().substr(0, 15), "30PPJAAXX090125");
BOOST_CHECK_EQUAL(sam.chromosome(), 0);
++read_counter;
}
BOOST_CHECK_EQUAL(read_counter, 0u);
}
}
BOOST_AUTO_TEST_CASE( indexed_single_readers_move_constructor_and_assignment ) {
auto r0 = IndexedSingleSamReader{"testdata/test_simple.bam", vector<string>{"."}};
auto m1 = check_move_constructor(r0);
auto m2 = IndexedSingleSamReader{"testdata/test_simple.bam", vector<string>{"."}};
BOOST_CHECK_EQUAL((*(m1.begin())).alignment_start(), (*(m2.begin())).alignment_start());
}
BOOST_AUTO_TEST_CASE( indexed_single_readers_begin_always_restarts ) {
auto reader1 = IndexedSingleSamReader{"testdata/test_simple.bam", vector<string>{"."}};
auto it1 = reader1.begin();
++it1;
auto it2 = reader1.begin();
BOOST_CHECK_NE((*it1).alignment_start(), (*it2).alignment_start());
++it2;
BOOST_CHECK_EQUAL((*it1).alignment_start(), (*it2).alignment_start());
}
BOOST_AUTO_TEST_CASE( indexed_sam_iterator_move_test ) {
auto reader0 = IndexedSingleSamReader{"testdata/test_simple.bam", vector<string>{"."}};
auto iter0 = reader0.begin();
auto reader1 = IndexedSingleSamReader{"testdata/test_simple.bam", vector<string>{"."}};
auto iter1 = reader1.begin();
auto moved = check_move_constructor(iter1);
auto record0 = *iter0;
auto moved_record = *moved;
BOOST_CHECK_EQUAL(record0.name(), moved_record.name());
BOOST_CHECK_EQUAL(record0.chromosome(), moved_record.chromosome());
}
<|endoftext|>
|
<commit_before>#include <pd_view.h>
#include <pd_backend.h>
#include <stdlib.h>
#include <stdio.h>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct RegistersData
{
int dummy;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void* createInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc)
{
(void)serviceFunc;
RegistersData* userData = (RegistersData*)malloc(sizeof(RegistersData));
(void)uiFuncs;
(void)serviceFunc;
// static const char* headers[] = { "Register", "Value", 0 };
// userData->registerList = PDUIListView_create(uiFuncs, headers, 0);
//PDUIListView_itemAdd(uiFuncs, userData->registerList, meh);
return userData;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void destroyInstance(void* userData)
{
free(userData);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TODO: Support floats
/*
static void getRegisterString(char* value, PDReader* reader, PDReaderIterator it)
{
uint64_t regValue;
uint32_t type = PDRead_findU64(reader, ®Value, "register", it);
switch (type & PDReadStatus_typeMask)
{
case PDReadType_u8: sprintf(value, "0x%02x", (uint8_t)regValue); break;
case PDReadType_s8: sprintf(value, "0x%02x", (int8_t)regValue); break;
case PDReadType_u16: sprintf(value, "0x%04x", (uint16_t)regValue); break;
case PDReadType_s16: sprintf(value, "0x%04x", (int16_t)regValue); break;
case PDReadType_u32: sprintf(value, "0x%08x", (uint32_t)regValue); break;
case PDReadType_s32: sprintf(value, "0x%08x", (int32_t)regValue); break;
}
}
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void showInUI(RegistersData* data, PDReader* reader, PDUI* uiFuncs)
{
PDReaderIterator it;
if (PDRead_findArray(reader, &it, "registers", 0) == PDReadStatus_notFound)
return;
(void)data;
(void)uiFuncs;
/*
PDUIListView_clear(uiFuncs, data->registerList);
while (PDRead_getNextEntry(reader, &it))
{
uint64_t regValue;
const char* name = "";
char registerValue[128];
PDRead_findString(reader, &name, "name", it);
getRegisterString(registerValue, reader, it);
const char* values[] = { name, registerValue, 0 };
PDUIListView_itemAdd(uiFuncs, data->registerList, values);
}
*/
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int update(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* outEvents)
{
uint32_t event;
RegistersData* data = (RegistersData*)userData;
// Loop over all the in events
while ((event = PDRead_getEvent(inEvents)) != 0)
{
switch (event)
{
case PDEventType_setRegisters:
showInUI(data, inEvents, uiFuncs); break;
}
}
//(void)userData;
//(void)inEvents;
(void)outEvents;
//(void)uiFuncs;
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDViewPlugin plugin =
{
"Registers",
createInstance,
destroyInstance,
update,
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
extern "C"
{
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData)
{
registerPlugin(PD_VIEW_API_VERSION, &plugin, privateData);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
<commit_msg>Renamed to Registers View<commit_after>#include <pd_view.h>
#include <pd_backend.h>
#include <stdlib.h>
#include <stdio.h>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct RegistersData
{
int dummy;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void* createInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc)
{
(void)serviceFunc;
RegistersData* userData = (RegistersData*)malloc(sizeof(RegistersData));
(void)uiFuncs;
(void)serviceFunc;
// static const char* headers[] = { "Register", "Value", 0 };
// userData->registerList = PDUIListView_create(uiFuncs, headers, 0);
//PDUIListView_itemAdd(uiFuncs, userData->registerList, meh);
return userData;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void destroyInstance(void* userData)
{
free(userData);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TODO: Support floats
/*
static void getRegisterString(char* value, PDReader* reader, PDReaderIterator it)
{
uint64_t regValue;
uint32_t type = PDRead_findU64(reader, ®Value, "register", it);
switch (type & PDReadStatus_typeMask)
{
case PDReadType_u8: sprintf(value, "0x%02x", (uint8_t)regValue); break;
case PDReadType_s8: sprintf(value, "0x%02x", (int8_t)regValue); break;
case PDReadType_u16: sprintf(value, "0x%04x", (uint16_t)regValue); break;
case PDReadType_s16: sprintf(value, "0x%04x", (int16_t)regValue); break;
case PDReadType_u32: sprintf(value, "0x%08x", (uint32_t)regValue); break;
case PDReadType_s32: sprintf(value, "0x%08x", (int32_t)regValue); break;
}
}
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void showInUI(RegistersData* data, PDReader* reader, PDUI* uiFuncs)
{
PDReaderIterator it;
if (PDRead_findArray(reader, &it, "registers", 0) == PDReadStatus_notFound)
return;
(void)data;
(void)uiFuncs;
/*
PDUIListView_clear(uiFuncs, data->registerList);
while (PDRead_getNextEntry(reader, &it))
{
uint64_t regValue;
const char* name = "";
char registerValue[128];
PDRead_findString(reader, &name, "name", it);
getRegisterString(registerValue, reader, it);
const char* values[] = { name, registerValue, 0 };
PDUIListView_itemAdd(uiFuncs, data->registerList, values);
}
*/
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int update(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* outEvents)
{
uint32_t event;
RegistersData* data = (RegistersData*)userData;
// Loop over all the in events
while ((event = PDRead_getEvent(inEvents)) != 0)
{
switch (event)
{
case PDEventType_setRegisters:
showInUI(data, inEvents, uiFuncs); break;
}
}
//(void)userData;
//(void)inEvents;
(void)outEvents;
//(void)uiFuncs;
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDViewPlugin plugin =
{
"Registers View",
createInstance,
destroyInstance,
update,
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
extern "C"
{
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData)
{
registerPlugin(PD_VIEW_API_VERSION, &plugin, privateData);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
<|endoftext|>
|
<commit_before>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2010 Emmanuel Benazera, ebenazer@seeks-project.info
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "dynamic_renderer.h"
#include "static_renderer.h"
#include "cgi.h"
#include "seeks_proxy.h"
#include "plugin_manager.h"
#include "websearch.h"
#include "errlog.h"
using sp::cgi;
using sp::seeks_proxy;
using sp::plugin_manager;
using sp::errlog;
namespace seeks_plugins
{
void dynamic_renderer::render_rpp(const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters,
hash_map<const char*,const char*,hash<const char*>,eqstr> *exports)
{
const char *rpp_str = miscutil::lookup(parameters,"rpp");
if (rpp_str)
miscutil::add_map_entry(exports,"$xxrpp",1,rpp_str,1);
else miscutil::add_map_entry(exports,"$xxrpp",1,miscutil::to_string(websearch::_wconfig->_Nr).c_str(),1);
}
sp_err dynamic_renderer::render_result_page(client_state *csp, http_response *rsp,
const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters)
{
static const char *result_tmpl_name = "websearch/templates/seeks_result_template_dyn.html";
return dynamic_renderer::render_result_page(csp,rsp,parameters,result_tmpl_name);
}
sp_err dynamic_renderer::render_result_page(client_state *csp, http_response *rsp,
const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters,
const std::string &result_tmpl_name,
const std::string &cgi_base,
const std::vector<std::pair<std::string,std::string> > *param_exports)
{
hash_map<const char*,const char*,hash<const char*>,eqstr> *exports
= static_renderer::websearch_exports(csp,param_exports);
// query.
std::string html_encoded_query;
std::string url_encoded_query;
static_renderer::render_query(parameters,exports,html_encoded_query,
url_encoded_query);
// clean query.
std::string query_clean;
static_renderer::render_clean_query(html_encoded_query,
exports,query_clean);
// results per page.
dynamic_renderer::render_rpp(parameters,exports);
// rendering.
sp_err err = cgi::template_fill_for_cgi(csp,result_tmpl_name.c_str(),
(seeks_proxy::_datadir.empty() ? plugin_manager::_plugin_repository.c_str()
: std::string(seeks_proxy::_datadir + "plugins/").c_str()),
exports,rsp);
return err;
}
} /* end of namespace. */
<commit_msg>added personalization variable to dynamic rendering page<commit_after>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2010 Emmanuel Benazera, ebenazer@seeks-project.info
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "dynamic_renderer.h"
#include "static_renderer.h"
#include "cgi.h"
#include "seeks_proxy.h"
#include "plugin_manager.h"
#include "websearch.h"
#include "errlog.h"
using sp::cgi;
using sp::seeks_proxy;
using sp::plugin_manager;
using sp::errlog;
namespace seeks_plugins
{
void dynamic_renderer::render_rpp(const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters,
hash_map<const char*,const char*,hash<const char*>,eqstr> *exports)
{
const char *rpp_str = miscutil::lookup(parameters,"rpp");
if (rpp_str)
miscutil::add_map_entry(exports,"$xxrpp",1,rpp_str,1);
else miscutil::add_map_entry(exports,"$xxrpp",1,miscutil::to_string(websearch::_wconfig->_Nr).c_str(),1);
}
sp_err dynamic_renderer::render_result_page(client_state *csp, http_response *rsp,
const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters)
{
static const char *result_tmpl_name = "websearch/templates/seeks_result_template_dyn.html";
return dynamic_renderer::render_result_page(csp,rsp,parameters,result_tmpl_name);
}
sp_err dynamic_renderer::render_result_page(client_state *csp, http_response *rsp,
const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters,
const std::string &result_tmpl_name,
const std::string &cgi_base,
const std::vector<std::pair<std::string,std::string> > *param_exports)
{
hash_map<const char*,const char*,hash<const char*>,eqstr> *exports
= static_renderer::websearch_exports(csp,param_exports);
// query.
std::string html_encoded_query;
std::string url_encoded_query;
static_renderer::render_query(parameters,exports,html_encoded_query,
url_encoded_query);
// clean query.
std::string query_clean;
static_renderer::render_clean_query(html_encoded_query,
exports,query_clean);
// results per page.
dynamic_renderer::render_rpp(parameters,exports);
// personalization.
const char *prs = miscutil::lookup(parameters,"prs");
if (!prs)
prs = websearch::_wconfig->_personalization ? "on" : "off";
miscutil::add_map_entry(exports,"$xxpers",1,prs,1);
// rendering.
sp_err err = cgi::template_fill_for_cgi(csp,result_tmpl_name.c_str(),
(seeks_proxy::_datadir.empty() ? plugin_manager::_plugin_repository.c_str()
: std::string(seeks_proxy::_datadir + "plugins/").c_str()),
exports,rsp);
return err;
}
} /* end of namespace. */
<|endoftext|>
|
<commit_before>
#include "otbWrapperInputProcessXMLParameter.h"
#include "otbWrapperChoiceParameter.h"
#include "otbWrapperListViewParameter.h"
#include "otbWrapperDirectoryParameter.h"
#include "otbWrapperEmptyParameter.h"
#include "otbWrapperInputFilenameParameter.h"
#include "otbWrapperInputFilenameListParameter.h"
#include "otbWrapperOutputFilenameParameter.h"
#include "otbWrapperInputVectorDataParameter.h"
#include "otbWrapperInputVectorDataListParameter.h"
#include "otbWrapperNumericalParameter.h"
#include "otbWrapperOutputVectorDataParameter.h"
#include "otbWrapperRadiusParameter.h"
#include "otbWrapperStringParameter.h"
#include "otbWrapperStringListParameter.h"
#include "otbWrapperInputImageParameter.h"
#include "otbWrapperInputImageListParameter.h"
#include "otbWrapperComplexInputImageParameter.h"
#include "otbWrapperOutputImageParameter.h"
#include "otbWrapperComplexOutputImageParameter.h"
#include "otbWrapperRAMParameter.h"
#include "itksys/SystemTools.hxx"
namespace otb
{
namespace Wrapper
{
InputProcessXMLParameter::InputProcessXMLParameter()
{
this->SetKey("inxml");
this->SetName("Load otb application from xml file");
this->SetDescription("Load otb application from xml file");
this->SetMandatory(false);
this->SetActive(false);
this->SetRole(Role_Input);
}
InputProcessXMLParameter::~InputProcessXMLParameter()
{
}
ImagePixelType
InputProcessXMLParameter::GetPixelTypeFromString(std::string strType)
{
if(strType == "uint8")
{
return ImagePixelType_uint8;
}
else if (strType == "int16")
{
return ImagePixelType_int16;
}
else if (strType == "uint16")
{
return ImagePixelType_uint16;
}
else if(strType == "int32")
{
return ImagePixelType_int32;
}
else if(strType == "uint32")
{
return ImagePixelType_uint32;
}
else if(strType == "float")
{
return ImagePixelType_float;
}
else if(strType == "double")
{
return ImagePixelType_double;
}
else
{
/*by default return float. Eg: if strType is emtpy because of no pixtype
node in xml which was the case earlier
*/
return ImagePixelType_float;
}
}
void
InputProcessXMLParameter::otbAppLogInfo(Application::Pointer app, std::string info)
{
app->GetLogger()->Write(itk::LoggerBase::INFO, info );
}
/* copied from Utilities/tinyXMLlib/tinyxml.cpp. Must have a FIX inside tinyxml.cpp */
FILE*
InputProcessXMLParameter::TiXmlFOpen( const char* filename, const char* mode )
{
#if defined(_MSC_VER) && (_MSC_VER >= 1400 )
FILE* fp = 0;
errno_t err = fopen_s( &fp, filename, mode );
if ( !err && fp )
return fp;
return 0;
#else
return fopen( filename, mode );
#endif
}
const std::string
InputProcessXMLParameter::GetChildNodeTextOf(TiXmlElement *parentElement, std::string key)
{
std::string value="";
if(parentElement)
{
TiXmlElement* childElement = 0;
childElement = parentElement->FirstChildElement(key.c_str());
//same as childElement->GetText() does but that call is failing if there is
//no such node.
//but the below code works and is a replacement for GetText()
if(childElement)
{
const TiXmlNode* child = childElement->FirstChild();
if ( child )
{
const TiXmlText* childText = child->ToText();
if ( childText )
{
value = childText->Value();
}
}
}
}
return value;
}
int
InputProcessXMLParameter::Read(Application::Pointer this_)
{
// Check if the filename is not empty
if(m_FileName.empty())
itkExceptionMacro(<<"The XML input FileName is empty, please set the filename via the method SetFileName");
// Check that the right extension is given : expected .xml
if (itksys::SystemTools::GetFilenameLastExtension(m_FileName) != ".xml")
{
itkExceptionMacro(<<itksys::SystemTools::GetFilenameLastExtension(m_FileName) << " " << m_FileName << " "
<<" is a wrong Extension FileName : Expected .xml");
}
// Open the xml file
TiXmlDocument doc;
FILE* fp = TiXmlFOpen( m_FileName.c_str (), "rb" );
if (!doc.LoadFile(fp , TIXML_ENCODING_UTF8))
{
itkExceptionMacro(<< "Can't open file " << m_FileName);
}
TiXmlHandle handle(&doc);
TiXmlElement *n_OTB;
n_OTB = handle.FirstChild("OTB").Element();
if(!n_OTB)
{
std::string info = "Input XML file " + std::string(this->GetFileName()) + " is invalid.";
//this->otbAppLogInfo(app,info);
}
std::string otb_Version;
otb_Version = GetChildNodeTextOf(n_OTB,"version");
if(otb_Version != OTB_VERSION_STRING)
otbMsgDebugMacro( << "Input XML was generated with a different version of OTB (" <<
otb_Version << ") and current version is OTB (" << OTB_VERSION_STRING << ")" );
/*
std::string otb_Version, otb_Build, otb_Platform;
otb_Version = this_->GetChildNodeTextOf(n_OTB,"version");
otb_Build = GetChildNodeTextOf(n_OTB, "build");
otb_Platform = this_->GetChildNodeTextOf(n_OTB, "platform");
*/
int ret = 0;
TiXmlElement *n_AppNode = n_OTB->FirstChildElement("application");
std::string app_Name;
app_Name = GetChildNodeTextOf(n_AppNode, "name");
/*
AddMetaData("appname", app_Name);
app_Descr = this_->GetChildNodeTextOf(n_AppNode, "descr");
AddMetaData("appdescr", app_Descr);
TiXmlElement* n_Doc = n_AppNode->FirstChildElement("doc");
std::string doc_Name, doc_Descr, doc_Author, doc_Limitation, doc_SeeAlso;
doc_Name = this_->GetChildNodeTextOf(n_Doc, "name");
AddMetaData("docname", doc_Name);
doc_Descr = this_->GetChildNodeTextOf(n_Doc, "longdescr");
AddMetaData("doclongdescr", doc_Descr);
doc_Author = this_->GetChildNodeTextOf(n_Doc, "authors");
AddMetaData("docauthors", doc_Author);
doc_Limitation = this_->GetChildNodeTextOf(n_Doc, "limitations");
AddMetaData("doclimitations", doc_Limitation);
doc_SeeAlso = this_->GetChildNodeTextOf(n_Doc, "seealso");
AddMetaData("docseealso", doc_SeeAlso);
*/
if(this_->GetName() != app_Name)
{
//hopefully shouldn't reach here ...
/*
std::string message = "Input XML was generated for a different application( "
+ app_Name + ") while application loaded is:" + this_->GetName();
std::cerr << message << "\n\n";
*/
itkWarningMacro( << "Input XML was generated for a different application( " <<
app_Name << ") while application loaded is:" <<this_->GetName());
return -1;
}
ParameterGroup::Pointer paramGroup = this_->GetParameterList();
// Iterate through the parameter list
for( TiXmlElement* n_Parameter = n_AppNode->FirstChildElement("parameter"); n_Parameter != NULL;
n_Parameter = n_Parameter->NextSiblingElement() )
{
std::string key,typeAsString, value, paramName;
std::vector<std::string> values;
key = GetChildNodeTextOf(n_Parameter, "key");
typeAsString = GetChildNodeTextOf(n_Parameter, "type");
value = GetChildNodeTextOf(n_Parameter, "value");
paramName = GetChildNodeTextOf(n_Parameter, "name");
ParameterType type = paramGroup->GetParameterTypeFromString(typeAsString);
Parameter* param = this_->GetParameterByKey(key);
bool updateFromXML = true;
if(param->HasUserValue())
updateFromXML = false;
if(updateFromXML)
{
param->SetUserValue(true);
TiXmlElement* n_Values = NULL;
n_Values = n_Parameter->FirstChildElement("values");
if(n_Values)
{
for(TiXmlElement* n_Value = n_Values->FirstChildElement("value"); n_Value != NULL;
n_Value = n_Value->NextSiblingElement())
{
values.push_back(n_Value->GetText());
}
}
if ( type == ParameterType_OutputFilename || type == ParameterType_OutputVectorData ||
type == ParameterType_String || type == ParameterType_Choice || type == ParameterType_RAM)
{
this_->SetParameterString(key, value);
}
else if (type == ParameterType_OutputImage)
{
OutputImageParameter *paramDown = dynamic_cast<OutputImageParameter*>(param);
paramDown->SetFileName(value);
std::string pixTypeAsString = GetChildNodeTextOf(n_Parameter, "pixtype");
ImagePixelType outPixType = GetPixelTypeFromString(pixTypeAsString);
paramDown->SetPixelType(outPixType);
}
else if (type == ParameterType_ComplexOutputImage)
{
ComplexOutputImageParameter* paramDown = dynamic_cast<ComplexOutputImageParameter*>(param);
paramDown->SetFileName(value);
}
else if (type == ParameterType_Directory)
{
DirectoryParameter* paramDown = dynamic_cast<DirectoryParameter*>(param);
paramDown->SetValue(value);
}
else if (type == ParameterType_InputFilename)
{
InputFilenameParameter* paramDown = dynamic_cast<InputFilenameParameter*>(param);
paramDown->SetValue(value);
}
else if (type == ParameterType_InputImage)
{
if(itksys::SystemTools::FileExists(value.c_str()))
{
InputImageParameter* paramDown = dynamic_cast<InputImageParameter*>(param);
paramDown->SetFromFileName(value);
if (!paramDown->SetFromFileName(value))
{
ret= -1;
}
}
else
{
otbMsgDevMacro( << "InputImageFile saved in InputXML does not exists" );
}
}
else if (type == ParameterType_ComplexInputImage)
{
if(itksys::SystemTools::FileExists(value.c_str()))
{
ComplexInputImageParameter* paramDown = dynamic_cast<ComplexInputImageParameter*>(param);
paramDown->SetFromFileName(value);
}
}
else if (dynamic_cast<InputVectorDataParameter*>(param))
{
if(itksys::SystemTools::FileExists(value.c_str()))
{
InputVectorDataParameter* paramDown = dynamic_cast<InputVectorDataParameter*>(param);
paramDown->SetFromFileName(value);
if ( !paramDown->SetFromFileName(value) )
{
ret = -1;
}
}
}
else if (dynamic_cast<InputImageListParameter*>(param))
{
InputImageListParameter* paramDown = dynamic_cast<InputImageListParameter*>(param);
paramDown->SetListFromFileName(values);
if ( !paramDown->SetListFromFileName(values) )
{
ret = -1;
}
}
else if (dynamic_cast<InputVectorDataListParameter*>(param))
{
InputVectorDataListParameter* paramDown = dynamic_cast<InputVectorDataListParameter*>(param);
paramDown->SetListFromFileName(values);
if ( !paramDown->SetListFromFileName(values) )
{
ret = -1;
}
}
else if (dynamic_cast<InputFilenameListParameter*>(param))
{
InputFilenameListParameter* paramDown = dynamic_cast<InputFilenameListParameter*>(param);
paramDown->SetListFromFileName(values);
if ( !paramDown->SetListFromFileName(values) )
{
ret= -1;
}
}
else if (type == ParameterType_Radius || type == ParameterType_Int ||
typeAsString == "rand" )
{
int intValue;
std::stringstream(value) >> intValue;
this_->SetParameterInt(key, intValue);
}
else if (type == ParameterType_Float)
{
float floatValue;
std::stringstream(value) >> floatValue;
this_->SetParameterFloat(key, floatValue);
}
else if (type == ParameterType_Empty)
{
bool emptyValue = false;
if( value == "true")
{
emptyValue = true;
}
this_->SetParameterEmpty(key, emptyValue);
}
else if (type == ParameterType_StringList || type == ParameterType_ListView)
{
if(values.empty())
itkWarningMacro(<< key << " has null values");
this_->SetParameterStringList(key, values);
}
} //end updateFromXML
//choice also comes as setint and setstring why??
}
ret = 0; //resetting return to zero, we dont use it anyway for now.
}
} //end namespace wrapper
} //end namespace otb
<commit_msg>WRG: return statement missing<commit_after>
#include "otbWrapperInputProcessXMLParameter.h"
#include "otbWrapperChoiceParameter.h"
#include "otbWrapperListViewParameter.h"
#include "otbWrapperDirectoryParameter.h"
#include "otbWrapperEmptyParameter.h"
#include "otbWrapperInputFilenameParameter.h"
#include "otbWrapperInputFilenameListParameter.h"
#include "otbWrapperOutputFilenameParameter.h"
#include "otbWrapperInputVectorDataParameter.h"
#include "otbWrapperInputVectorDataListParameter.h"
#include "otbWrapperNumericalParameter.h"
#include "otbWrapperOutputVectorDataParameter.h"
#include "otbWrapperRadiusParameter.h"
#include "otbWrapperStringParameter.h"
#include "otbWrapperStringListParameter.h"
#include "otbWrapperInputImageParameter.h"
#include "otbWrapperInputImageListParameter.h"
#include "otbWrapperComplexInputImageParameter.h"
#include "otbWrapperOutputImageParameter.h"
#include "otbWrapperComplexOutputImageParameter.h"
#include "otbWrapperRAMParameter.h"
#include "itksys/SystemTools.hxx"
namespace otb
{
namespace Wrapper
{
InputProcessXMLParameter::InputProcessXMLParameter()
{
this->SetKey("inxml");
this->SetName("Load otb application from xml file");
this->SetDescription("Load otb application from xml file");
this->SetMandatory(false);
this->SetActive(false);
this->SetRole(Role_Input);
}
InputProcessXMLParameter::~InputProcessXMLParameter()
{
}
ImagePixelType
InputProcessXMLParameter::GetPixelTypeFromString(std::string strType)
{
if(strType == "uint8")
{
return ImagePixelType_uint8;
}
else if (strType == "int16")
{
return ImagePixelType_int16;
}
else if (strType == "uint16")
{
return ImagePixelType_uint16;
}
else if(strType == "int32")
{
return ImagePixelType_int32;
}
else if(strType == "uint32")
{
return ImagePixelType_uint32;
}
else if(strType == "float")
{
return ImagePixelType_float;
}
else if(strType == "double")
{
return ImagePixelType_double;
}
else
{
/*by default return float. Eg: if strType is emtpy because of no pixtype
node in xml which was the case earlier
*/
return ImagePixelType_float;
}
}
void
InputProcessXMLParameter::otbAppLogInfo(Application::Pointer app, std::string info)
{
app->GetLogger()->Write(itk::LoggerBase::INFO, info );
}
/* copied from Utilities/tinyXMLlib/tinyxml.cpp. Must have a FIX inside tinyxml.cpp */
FILE*
InputProcessXMLParameter::TiXmlFOpen( const char* filename, const char* mode )
{
#if defined(_MSC_VER) && (_MSC_VER >= 1400 )
FILE* fp = 0;
errno_t err = fopen_s( &fp, filename, mode );
if ( !err && fp )
return fp;
return 0;
#else
return fopen( filename, mode );
#endif
}
const std::string
InputProcessXMLParameter::GetChildNodeTextOf(TiXmlElement *parentElement, std::string key)
{
std::string value="";
if(parentElement)
{
TiXmlElement* childElement = 0;
childElement = parentElement->FirstChildElement(key.c_str());
//same as childElement->GetText() does but that call is failing if there is
//no such node.
//but the below code works and is a replacement for GetText()
if(childElement)
{
const TiXmlNode* child = childElement->FirstChild();
if ( child )
{
const TiXmlText* childText = child->ToText();
if ( childText )
{
value = childText->Value();
}
}
}
}
return value;
}
int
InputProcessXMLParameter::Read(Application::Pointer this_)
{
// Check if the filename is not empty
if(m_FileName.empty())
itkExceptionMacro(<<"The XML input FileName is empty, please set the filename via the method SetFileName");
// Check that the right extension is given : expected .xml
if (itksys::SystemTools::GetFilenameLastExtension(m_FileName) != ".xml")
{
itkExceptionMacro(<<itksys::SystemTools::GetFilenameLastExtension(m_FileName) << " " << m_FileName << " "
<<" is a wrong Extension FileName : Expected .xml");
}
// Open the xml file
TiXmlDocument doc;
FILE* fp = TiXmlFOpen( m_FileName.c_str (), "rb" );
if (!doc.LoadFile(fp , TIXML_ENCODING_UTF8))
{
itkExceptionMacro(<< "Can't open file " << m_FileName);
}
TiXmlHandle handle(&doc);
TiXmlElement *n_OTB;
n_OTB = handle.FirstChild("OTB").Element();
if(!n_OTB)
{
std::string info = "Input XML file " + std::string(this->GetFileName()) + " is invalid.";
//this->otbAppLogInfo(app,info);
}
std::string otb_Version;
otb_Version = GetChildNodeTextOf(n_OTB,"version");
if(otb_Version != OTB_VERSION_STRING)
otbMsgDebugMacro( << "Input XML was generated with a different version of OTB (" <<
otb_Version << ") and current version is OTB (" << OTB_VERSION_STRING << ")" );
/*
std::string otb_Version, otb_Build, otb_Platform;
otb_Version = this_->GetChildNodeTextOf(n_OTB,"version");
otb_Build = GetChildNodeTextOf(n_OTB, "build");
otb_Platform = this_->GetChildNodeTextOf(n_OTB, "platform");
*/
int ret = 0;
TiXmlElement *n_AppNode = n_OTB->FirstChildElement("application");
std::string app_Name;
app_Name = GetChildNodeTextOf(n_AppNode, "name");
/*
AddMetaData("appname", app_Name);
app_Descr = this_->GetChildNodeTextOf(n_AppNode, "descr");
AddMetaData("appdescr", app_Descr);
TiXmlElement* n_Doc = n_AppNode->FirstChildElement("doc");
std::string doc_Name, doc_Descr, doc_Author, doc_Limitation, doc_SeeAlso;
doc_Name = this_->GetChildNodeTextOf(n_Doc, "name");
AddMetaData("docname", doc_Name);
doc_Descr = this_->GetChildNodeTextOf(n_Doc, "longdescr");
AddMetaData("doclongdescr", doc_Descr);
doc_Author = this_->GetChildNodeTextOf(n_Doc, "authors");
AddMetaData("docauthors", doc_Author);
doc_Limitation = this_->GetChildNodeTextOf(n_Doc, "limitations");
AddMetaData("doclimitations", doc_Limitation);
doc_SeeAlso = this_->GetChildNodeTextOf(n_Doc, "seealso");
AddMetaData("docseealso", doc_SeeAlso);
*/
if(this_->GetName() != app_Name)
{
//hopefully shouldn't reach here ...
/*
std::string message = "Input XML was generated for a different application( "
+ app_Name + ") while application loaded is:" + this_->GetName();
std::cerr << message << "\n\n";
*/
itkWarningMacro( << "Input XML was generated for a different application( " <<
app_Name << ") while application loaded is:" <<this_->GetName());
return -1;
}
ParameterGroup::Pointer paramGroup = this_->GetParameterList();
// Iterate through the parameter list
for( TiXmlElement* n_Parameter = n_AppNode->FirstChildElement("parameter"); n_Parameter != NULL;
n_Parameter = n_Parameter->NextSiblingElement() )
{
std::string key,typeAsString, value, paramName;
std::vector<std::string> values;
key = GetChildNodeTextOf(n_Parameter, "key");
typeAsString = GetChildNodeTextOf(n_Parameter, "type");
value = GetChildNodeTextOf(n_Parameter, "value");
paramName = GetChildNodeTextOf(n_Parameter, "name");
ParameterType type = paramGroup->GetParameterTypeFromString(typeAsString);
Parameter* param = this_->GetParameterByKey(key);
bool updateFromXML = true;
if(param->HasUserValue())
updateFromXML = false;
if(updateFromXML)
{
param->SetUserValue(true);
TiXmlElement* n_Values = NULL;
n_Values = n_Parameter->FirstChildElement("values");
if(n_Values)
{
for(TiXmlElement* n_Value = n_Values->FirstChildElement("value"); n_Value != NULL;
n_Value = n_Value->NextSiblingElement())
{
values.push_back(n_Value->GetText());
}
}
if ( type == ParameterType_OutputFilename || type == ParameterType_OutputVectorData ||
type == ParameterType_String || type == ParameterType_Choice || type == ParameterType_RAM)
{
this_->SetParameterString(key, value);
}
else if (type == ParameterType_OutputImage)
{
OutputImageParameter *paramDown = dynamic_cast<OutputImageParameter*>(param);
paramDown->SetFileName(value);
std::string pixTypeAsString = GetChildNodeTextOf(n_Parameter, "pixtype");
ImagePixelType outPixType = GetPixelTypeFromString(pixTypeAsString);
paramDown->SetPixelType(outPixType);
}
else if (type == ParameterType_ComplexOutputImage)
{
ComplexOutputImageParameter* paramDown = dynamic_cast<ComplexOutputImageParameter*>(param);
paramDown->SetFileName(value);
}
else if (type == ParameterType_Directory)
{
DirectoryParameter* paramDown = dynamic_cast<DirectoryParameter*>(param);
paramDown->SetValue(value);
}
else if (type == ParameterType_InputFilename)
{
InputFilenameParameter* paramDown = dynamic_cast<InputFilenameParameter*>(param);
paramDown->SetValue(value);
}
else if (type == ParameterType_InputImage)
{
if(itksys::SystemTools::FileExists(value.c_str()))
{
InputImageParameter* paramDown = dynamic_cast<InputImageParameter*>(param);
paramDown->SetFromFileName(value);
if (!paramDown->SetFromFileName(value))
{
ret= -1;
}
}
else
{
otbMsgDevMacro( << "InputImageFile saved in InputXML does not exists" );
}
}
else if (type == ParameterType_ComplexInputImage)
{
if(itksys::SystemTools::FileExists(value.c_str()))
{
ComplexInputImageParameter* paramDown = dynamic_cast<ComplexInputImageParameter*>(param);
paramDown->SetFromFileName(value);
}
}
else if (dynamic_cast<InputVectorDataParameter*>(param))
{
if(itksys::SystemTools::FileExists(value.c_str()))
{
InputVectorDataParameter* paramDown = dynamic_cast<InputVectorDataParameter*>(param);
paramDown->SetFromFileName(value);
if ( !paramDown->SetFromFileName(value) )
{
ret = -1;
}
}
}
else if (dynamic_cast<InputImageListParameter*>(param))
{
InputImageListParameter* paramDown = dynamic_cast<InputImageListParameter*>(param);
paramDown->SetListFromFileName(values);
if ( !paramDown->SetListFromFileName(values) )
{
ret = -1;
}
}
else if (dynamic_cast<InputVectorDataListParameter*>(param))
{
InputVectorDataListParameter* paramDown = dynamic_cast<InputVectorDataListParameter*>(param);
paramDown->SetListFromFileName(values);
if ( !paramDown->SetListFromFileName(values) )
{
ret = -1;
}
}
else if (dynamic_cast<InputFilenameListParameter*>(param))
{
InputFilenameListParameter* paramDown = dynamic_cast<InputFilenameListParameter*>(param);
paramDown->SetListFromFileName(values);
if ( !paramDown->SetListFromFileName(values) )
{
ret= -1;
}
}
else if (type == ParameterType_Radius || type == ParameterType_Int ||
typeAsString == "rand" )
{
int intValue;
std::stringstream(value) >> intValue;
this_->SetParameterInt(key, intValue);
}
else if (type == ParameterType_Float)
{
float floatValue;
std::stringstream(value) >> floatValue;
this_->SetParameterFloat(key, floatValue);
}
else if (type == ParameterType_Empty)
{
bool emptyValue = false;
if( value == "true")
{
emptyValue = true;
}
this_->SetParameterEmpty(key, emptyValue);
}
else if (type == ParameterType_StringList || type == ParameterType_ListView)
{
if(values.empty())
itkWarningMacro(<< key << " has null values");
this_->SetParameterStringList(key, values);
}
} //end updateFromXML
//choice also comes as setint and setstring why??
}
ret = 0; //resetting return to zero, we dont use it anyway for now.
return ret;
}
} //end namespace wrapper
} //end namespace otb
<|endoftext|>
|
<commit_before>/*!
* @file File componentMovement.cpp
* @brief Implementation of the class of component movements present in the game
*
* The class implemented here provides to the game the speed and type
* of movement that a given element can perform
*
* Auxiliary documentation
* @sa componentMovement.hpp
*
* @warning All variables are initialized
*/
#include <componentMovement.hpp>
#include <gameObject.hpp>
#include <game.hpp>
#include <assert.h>
//! Functions to be called by the methods in order to perform actions
void CompMovement::chooseTypeComponentMovement(float time){
assert(time > 0.0 and time < 60.0 ); // CPPCheck avalia a condição da assertiva (Se está sempre true)
UNUSED(time);
GO(entity)->pos += move;
if (mType == moveType::t_bullet){
GO(entity)->rotation = speed.angle();
}
else {
//Nothing to do
}
}
/*!
@fn CompMovement::CompMovement()
@brief Constructor method for CompMovement
@params const Vec2& sprite, moveType move_type
*/
CompMovement::CompMovement(const Vec2& sprite, moveType move_type): mType{move_type},speed{sprite} {
LOG_METHOD_START('CompMovement::CompMovement');
LOG_METHOD_CLOSE('CompMovement::CompMovement', "constructor");
}
/*!
@fn CompMovement::~CompMovement()
@brief Desstructor method for CompMovement
@params No params
*/
CompMovement::~CompMovement() {
LOG_METHOD_START('CompMovement::~CompMovement');
LOG_METHOD_CLOSE('CompMovement::~CompMovement', "destructor");
// Method body its empty
}
/*!
@fn void CompMovement::update(float time)
@brief Method that update element movement
@return The execution of this method returns no value
@warning Method that requires review of comment
@param float time
*/
void CompMovement::update(float time) {
LOG_METHOD_START('CompMovement::update');
LOG_VARIABLE("CompMovement::update", "time");
assert(time >= 0);
chooseTypeComponentMovement(time);
LOG_METHOD_CLOSE('CompMovement::update', "void");
assert(time > 0.0 and time < 60.0 );
}
/*!
@fn void CompMovement::render()
@brief Method that render the new element movement
@return The execution of this method returns no value
@warning Method that requires review of comment
*/
void CompMovement::render() {
//! Non renderizable component
LOG_METHOD_START('CompMovement::render');
LOG_METHOD_CLOSE('CompMovement::render', "void");
}
/*!
@fn Component::type CompMovement::get_type()
@brief Method that sets the type of movement
@return Component class object
@warning Method that requires review of comment
*/
Component::type CompMovement::get_type()const{
LOG_METHOD_START('CompMovement::get_type');
return Component::type::t_movement;
}
<commit_msg>Removing portuguese comment<commit_after>/*!
* @file File componentMovement.cpp
* @brief Implementation of the class of component movements present in the game
*
* The class implemented here provides to the game the speed and type
* of movement that a given element can perform
*
* Auxiliary documentation
* @sa componentMovement.hpp
*
* @warning All variables are initialized
*/
#include <componentMovement.hpp>
#include <gameObject.hpp>
#include <game.hpp>
#include <assert.h>
//! Functions to be called by the methods in order to perform actions
void CompMovement::chooseTypeComponentMovement(float time){
assert(time > 0.0 and time < 60.0 ); // CPPCheck engine checks if the assertive condition (Always true)
UNUSED(time);
GO(entity)->pos += move;
if (mType == moveType::t_bullet){
GO(entity)->rotation = speed.angle();
}
else {
//Nothing to do
}
}
/*!
@fn CompMovement::CompMovement()
@brief Constructor method for CompMovement
@params const Vec2& sprite, moveType move_type
*/
CompMovement::CompMovement(const Vec2& sprite, moveType move_type): mType{move_type},speed{sprite} {
LOG_METHOD_START('CompMovement::CompMovement');
LOG_METHOD_CLOSE('CompMovement::CompMovement', "constructor");
}
/*!
@fn CompMovement::~CompMovement()
@brief Desstructor method for CompMovement
@params No params
*/
CompMovement::~CompMovement() {
LOG_METHOD_START('CompMovement::~CompMovement');
LOG_METHOD_CLOSE('CompMovement::~CompMovement', "destructor");
// Method body its empty
}
/*!
@fn void CompMovement::update(float time)
@brief Method that update element movement
@return The execution of this method returns no value
@warning Method that requires review of comment
@param float time
*/
void CompMovement::update(float time) {
LOG_METHOD_START('CompMovement::update');
LOG_VARIABLE("CompMovement::update", "time");
assert(time >= 0);
chooseTypeComponentMovement(time);
LOG_METHOD_CLOSE('CompMovement::update', "void");
assert(time > 0.0 and time < 60.0 );
}
/*!
@fn void CompMovement::render()
@brief Method that render the new element movement
@return The execution of this method returns no value
@warning Method that requires review of comment
*/
void CompMovement::render() {
//! Non renderizable component
LOG_METHOD_START('CompMovement::render');
LOG_METHOD_CLOSE('CompMovement::render', "void");
}
/*!
@fn Component::type CompMovement::get_type()
@brief Method that sets the type of movement
@return Component class object
@warning Method that requires review of comment
*/
Component::type CompMovement::get_type()const{
LOG_METHOD_START('CompMovement::get_type');
return Component::type::t_movement;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
/*
* @file admin-api.cpp
* @author Lukasz Wojciechowski <l.wojciechow@partner.samsung.com>
* @version 1.0
* @brief Implementation of external libcynara-admin API
*/
#include <map>
#include <new>
#include <string>
#include <vector>
#include <common.h>
#include <types/Policy.h>
#include <types/PolicyBucketId.h>
#include <types/PolicyKey.h>
#include <types/PolicyResult.h>
#include <types/PolicyType.h>
#include <cynara-admin.h>
#include <api/ApiInterface.h>
#include <logic/Logic.h>
struct cynara_admin {
Cynara::ApiInterface *impl;
cynara_admin(Cynara::ApiInterface *_impl) : impl(_impl) {
}
~cynara_admin() {
delete impl;
}
};
CYNARA_API
int cynara_admin_initialize(struct cynara_admin **pp_cynara_admin) {
if (!pp_cynara_admin)
return CYNARA_ADMIN_API_INVALID_PARAM;
try {
*pp_cynara_admin = new cynara_admin(new Cynara::Logic);
} catch (const std::bad_alloc &ex) {
return CYNARA_ADMIN_API_OUT_OF_MEMORY;
}
return CYNARA_ADMIN_API_SUCCESS;
}
CYNARA_API
int cynara_admin_finish(struct cynara_admin *p_cynara_admin) {
delete p_cynara_admin;
return CYNARA_ADMIN_API_SUCCESS;
}
CYNARA_API
int cynara_admin_set_policies(struct cynara_admin *p_cynara_admin,
const cynara_admin_policy *const *policies) {
if (!p_cynara_admin || !p_cynara_admin->impl)
return CYNARA_ADMIN_API_INVALID_PARAM;
if (!policies)
return CYNARA_ADMIN_API_INVALID_PARAM;
std::map<Cynara::PolicyBucketId, std::vector<Cynara::Policy>> insertOrUpdate;
std::map<Cynara::PolicyBucketId, std::vector<Cynara::PolicyKey>> remove;
auto key = ([](const cynara_admin_policy *i)->Cynara::PolicyKey {
std::string wildcard(CYNARA_ADMIN_WILDCARD);
auto feature = ([&wildcard] (const char *str)->Cynara::PolicyKeyFeature {
if (wildcard.compare(str))
return Cynara::PolicyKeyFeature::create(str);
else
return Cynara::PolicyKeyFeature::createWildcard();
});
return Cynara::PolicyKey(feature(i->client), feature(i->user), feature(i->privilege));
});
try {
for (auto i = policies; *i; i++) {
if(!(*i)->bucket || !(*i)->client || !(*i)->user || !(*i)->privilege)
return CYNARA_ADMIN_API_INVALID_PARAM;
switch ((*i)->result) {
case CYNARA_ADMIN_DELETE:
remove[(*i)->bucket].push_back(key(*i));
break;
case CYNARA_ADMIN_DENY:
insertOrUpdate[(*i)->bucket].push_back(Cynara::Policy(key(*i),
Cynara::PredefinedPolicyType::DENY));
break;
case CYNARA_ADMIN_ALLOW:
insertOrUpdate[(*i)->bucket].push_back(Cynara::Policy(key(*i),
Cynara::PredefinedPolicyType::ALLOW));
break;
case CYNARA_ADMIN_BUCKET:
insertOrUpdate[(*i)->bucket].push_back(Cynara::Policy(key(*i),
Cynara::PolicyResult(
Cynara::PredefinedPolicyType::BUCKET,
(*i)->result_extra ? (*i)->result_extra
: "")));
break;
default:
return CYNARA_ADMIN_API_INVALID_PARAM;
}
}
} catch (std::bad_alloc ex) {
return CYNARA_ADMIN_API_OUT_OF_MEMORY;
}
return p_cynara_admin->impl->setPolicies(insertOrUpdate, remove);
}
CYNARA_API
int cynara_admin_set_bucket(struct cynara_admin *p_cynara_admin, const char *bucket,
int operation, const char *extra) {
if (!p_cynara_admin || !p_cynara_admin->impl)
return CYNARA_ADMIN_API_INVALID_PARAM;
if (!bucket)
return CYNARA_ADMIN_API_INVALID_PARAM;
std::string extraStr;
try {
extraStr = extra ? extra : "";
} catch (std::bad_alloc ex) {
return CYNARA_ADMIN_API_OUT_OF_MEMORY;
}
switch (operation) {
case CYNARA_ADMIN_DELETE:
return p_cynara_admin->impl->removeBucket(bucket);
case CYNARA_ADMIN_DENY:
return p_cynara_admin->impl->insertOrUpdateBucket(bucket,
Cynara::PolicyResult(Cynara::PredefinedPolicyType::DENY, extraStr));
case CYNARA_ADMIN_ALLOW:
return p_cynara_admin->impl->insertOrUpdateBucket(bucket,
Cynara::PolicyResult(Cynara::PredefinedPolicyType::ALLOW, extraStr));
case CYNARA_ADMIN_BUCKET:
default:
return CYNARA_ADMIN_API_INVALID_PARAM;
}
}
<commit_msg>Fix parameter checking when setting bucket-pointing policy<commit_after>/*
* Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
/*
* @file admin-api.cpp
* @author Lukasz Wojciechowski <l.wojciechow@partner.samsung.com>
* @version 1.0
* @brief Implementation of external libcynara-admin API
*/
#include <map>
#include <new>
#include <string>
#include <vector>
#include <common.h>
#include <types/Policy.h>
#include <types/PolicyBucketId.h>
#include <types/PolicyKey.h>
#include <types/PolicyResult.h>
#include <types/PolicyType.h>
#include <cynara-admin.h>
#include <api/ApiInterface.h>
#include <logic/Logic.h>
struct cynara_admin {
Cynara::ApiInterface *impl;
cynara_admin(Cynara::ApiInterface *_impl) : impl(_impl) {
}
~cynara_admin() {
delete impl;
}
};
CYNARA_API
int cynara_admin_initialize(struct cynara_admin **pp_cynara_admin) {
if (!pp_cynara_admin)
return CYNARA_ADMIN_API_INVALID_PARAM;
try {
*pp_cynara_admin = new cynara_admin(new Cynara::Logic);
} catch (const std::bad_alloc &ex) {
return CYNARA_ADMIN_API_OUT_OF_MEMORY;
}
return CYNARA_ADMIN_API_SUCCESS;
}
CYNARA_API
int cynara_admin_finish(struct cynara_admin *p_cynara_admin) {
delete p_cynara_admin;
return CYNARA_ADMIN_API_SUCCESS;
}
CYNARA_API
int cynara_admin_set_policies(struct cynara_admin *p_cynara_admin,
const cynara_admin_policy *const *policies) {
if (!p_cynara_admin || !p_cynara_admin->impl)
return CYNARA_ADMIN_API_INVALID_PARAM;
if (!policies)
return CYNARA_ADMIN_API_INVALID_PARAM;
std::map<Cynara::PolicyBucketId, std::vector<Cynara::Policy>> insertOrUpdate;
std::map<Cynara::PolicyBucketId, std::vector<Cynara::PolicyKey>> remove;
auto key = ([](const cynara_admin_policy *i)->Cynara::PolicyKey {
std::string wildcard(CYNARA_ADMIN_WILDCARD);
auto feature = ([&wildcard] (const char *str)->Cynara::PolicyKeyFeature {
if (wildcard.compare(str))
return Cynara::PolicyKeyFeature::create(str);
else
return Cynara::PolicyKeyFeature::createWildcard();
});
return Cynara::PolicyKey(feature(i->client), feature(i->user), feature(i->privilege));
});
try {
for (auto i = policies; *i; i++) {
if(!(*i)->bucket || !(*i)->client || !(*i)->user || !(*i)->privilege)
return CYNARA_ADMIN_API_INVALID_PARAM;
switch ((*i)->result) {
case CYNARA_ADMIN_DELETE:
remove[(*i)->bucket].push_back(key(*i));
break;
case CYNARA_ADMIN_DENY:
insertOrUpdate[(*i)->bucket].push_back(Cynara::Policy(key(*i),
Cynara::PredefinedPolicyType::DENY));
break;
case CYNARA_ADMIN_ALLOW:
insertOrUpdate[(*i)->bucket].push_back(Cynara::Policy(key(*i),
Cynara::PredefinedPolicyType::ALLOW));
break;
case CYNARA_ADMIN_BUCKET:
if (!(*i)->result_extra)
return CYNARA_ADMIN_API_INVALID_PARAM;
insertOrUpdate[(*i)->bucket].push_back(Cynara::Policy(key(*i),
Cynara::PolicyResult(
Cynara::PredefinedPolicyType::BUCKET,
(*i)->result_extra)));
break;
default:
return CYNARA_ADMIN_API_INVALID_PARAM;
}
}
} catch (std::bad_alloc ex) {
return CYNARA_ADMIN_API_OUT_OF_MEMORY;
}
return p_cynara_admin->impl->setPolicies(insertOrUpdate, remove);
}
CYNARA_API
int cynara_admin_set_bucket(struct cynara_admin *p_cynara_admin, const char *bucket,
int operation, const char *extra) {
if (!p_cynara_admin || !p_cynara_admin->impl)
return CYNARA_ADMIN_API_INVALID_PARAM;
if (!bucket)
return CYNARA_ADMIN_API_INVALID_PARAM;
std::string extraStr;
try {
extraStr = extra ? extra : "";
} catch (std::bad_alloc ex) {
return CYNARA_ADMIN_API_OUT_OF_MEMORY;
}
switch (operation) {
case CYNARA_ADMIN_DELETE:
return p_cynara_admin->impl->removeBucket(bucket);
case CYNARA_ADMIN_DENY:
return p_cynara_admin->impl->insertOrUpdateBucket(bucket,
Cynara::PolicyResult(Cynara::PredefinedPolicyType::DENY, extraStr));
case CYNARA_ADMIN_ALLOW:
return p_cynara_admin->impl->insertOrUpdateBucket(bucket,
Cynara::PolicyResult(Cynara::PredefinedPolicyType::ALLOW, extraStr));
case CYNARA_ADMIN_BUCKET:
default:
return CYNARA_ADMIN_API_INVALID_PARAM;
}
}
<|endoftext|>
|
<commit_before>/*
* serialport_posix.cpp
* PHD Guiding
*
* Created by Hans Lambermont
* Copyright (c) 2016 Hans Lambermont
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name Craig Stark, Stark Labs nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "phd.h"
#if defined (__linux__) || defined (__APPLE__)
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <errno.h>
wxArrayString SerialPortPosix::GetSerialPortList(void)
{
wxArrayString ret;
// TODO generate this list
ret.Add("/dev/ttyS0");
ret.Add("/dev/ttyS1");
ret.Add("/dev/ttyUSB0");
ret.Add("/dev/ttyUSB1");
ret.Add("/dev/sx-ao-lf");
return ret;
}
SerialPortPosix::SerialPortPosix(void)
{
m_fd = -1;
}
SerialPortPosix::~SerialPortPosix(void)
{
if (m_fd > 0) {
close(m_fd);
m_fd = -1;
}
}
bool SerialPortPosix::Connect(const wxString& portName, int baud, int dataBits, int stopBits, PARITY Parity, bool useRTS, bool useDTR)
{
bool bError = false;
try {
if ((m_fd = open(portName.mb_str(), O_RDWR|O_NOCTTY)) < 0) {
wxString exposeToUser = wxString::Format("open %s failed %s(%d)", portName, strerror((int)errno), (int)errno);
throw ERROR_INFO("SerialPortPosix::Connect " + exposeToUser);
}
struct termios attr;
if (tcgetattr(m_fd, &attr) < 0 ) {
wxString errorWxs = wxString::Format("tcgetattr failed %s(%d)", strerror((int)errno), (int)errno);
throw ERROR_INFO("SerialPortPosix::Connect " + errorWxs);
}
#if defined (__APPLE__)
m_originalAttrs = attr;
cfmakeraw(&attr);
#endif
attr.c_iflag = 0; // input modes
attr.c_oflag = 0; // output modes
attr.c_cflag = CLOCAL; // CLOCAL == Ignore modem control lines.
attr.c_cflag |= CREAD ; // CREAD == Enable receiver.
switch (dataBits) {
case 7:
attr.c_cflag |= CS7; // 7 bit Character size mask.
break;
case 8:
attr.c_cflag |= CS8; // 8 bit Character size mask.
break;
default:
throw ERROR_INFO("SerialPortPosix::Connect unsupported amount of dataBits");
break;
}
switch (stopBits) {
case 1:
break;
case 2:
attr.c_cflag |= CSTOPB; // 2 stop bits
break;
default:
throw ERROR_INFO("SerialPortPosix::Connect invalid amount of stopBits");
break;
}
switch (Parity) {
case ParityNone:
break;
case ParityOdd:
attr.c_cflag |= PARENB | PARODD;
break;
case ParityEven:
attr.c_cflag |= PARENB; // Enable parity generation on output and parity checking for input.
break;
case ParityMark: // TODO, not in POSIX. CMSPAR
case ParitySpace: // TODO, not in POSIX. CMSPAR
default:
throw ERROR_INFO("SerialPortPosix::Connect invalid parity");
break;
}
attr.c_lflag &= ~ICANON; // Do not wait for a line delimiter. Work in noncanonical mode.
attr.c_lflag &= ~( ECHO | ECHOE | ISIG | IEXTEN | NOFLSH | TOSTOP); // local modes
attr.c_lflag |= NOFLSH;
attr.c_cc[VTIME] = (uint8_t)0; // timeout in deciseconds
attr.c_cc[VMIN] = (uint8_t)0; // minimum number of characters for noncanonical read
unsigned int speed = B0;
switch (baud) {
case 9600: speed = B9600; break;
case 19200: speed = B19200; break;
case 38400: speed = B38400; break;
case 57600: speed = B57600; break;
case 115200: speed = B115200; break;
case 230400: speed = B230400; break;
default:
throw ERROR_INFO("SerialPortPosix::Connect unsupported baudrate");
break;
}
if ((cfsetispeed(&attr, speed) < 0) || (cfsetospeed(&attr, speed) <0)) {
throw ERROR_INFO("cfsetispeed failed");
}
if (tcsetattr(m_fd, TCSAFLUSH, &attr) < 0 ) {
wxString errowWxs = wxString::Format("tcsetattr failed %s(%d)", strerror((int)errno), (int)errno);
throw ERROR_INFO("SerialPortPosix::Connect " + errowWxs);
}
int ioctl_ret = 0;
unsigned int argp;
if ((ioctl_ret = ioctl(m_fd, TIOCMGET, &argp) < 0)) {
throw ERROR_INFO("ioctl TIOCMGET");
}
if (useDTR) {
argp |= TIOCM_DTR;
}
if (useRTS) {
argp |= TIOCM_RTS;
}
if ((ioctl_ret = ioctl(m_fd, TIOCMSET, &argp) < 0)) {
throw ERROR_INFO("ioctl TIOCMSET");
}
}
catch (const wxString& Msg)
{
POSSIBLY_UNUSED(Msg);
bError = true;
}
return bError;
}
bool SerialPortPosix::Disconnect(void)
{
bool bError = false;
try {
#if defined (__APPLE__)
if (tcdrain(m_fd) == -1){
fprintf(stderr,"Error waiting for drain - %s(%d).\n",strerror(errno), errno);
}
if (tcsetattr(m_fd, TCSANOW, &m_originalAttrs) == -1){
fprintf(stderr,"Error resetting tty attributes - %s(%d).\n",strerror(errno),errno);
}
#endif
if (close(m_fd) == -1){
throw ERROR_INFO("SerialPortPosix: close failed");
}
} catch (const wxString& Msg) {
POSSIBLY_UNUSED(Msg);
bError = true;
}
m_fd = -1;
return bError;
}
bool SerialPortPosix::SetReceiveTimeout(int timeoutMilliSeconds)
{
bool bError = false;
Debug.AddLine(wxString::Format("SerialPortPosix::SetReceiveTimeout %d ms", timeoutMilliSeconds));
try {
struct termios attr;
if (tcgetattr(m_fd, &attr) < 0 ) {
throw ERROR_INFO("tcgetattr failed");
}
int timeoutDeciSeconds = (timeoutMilliSeconds + 99) / 100;
attr.c_cc[VTIME] = (uint8_t)timeoutDeciSeconds;
if (tcsetattr(m_fd, TCSAFLUSH, &attr) < 0 ) {
throw ERROR_INFO("tcsetattr failed");
}
} catch (const wxString& Msg) {
POSSIBLY_UNUSED(Msg);
bError = true;
}
return bError;
}
bool SerialPortPosix::Send(const unsigned char *pData, unsigned int count)
{
bool bError = false;
try {
int nBytesWritten;
Debug.AddBytes("SerialPortPosix::Send", pData, count);
if ((nBytesWritten = write(m_fd, pData, count)) < 0) {
throw ERROR_INFO("SerialPortPosix: write failed");
}
if (nBytesWritten != count) {
throw ERROR_INFO("SerialPortPosix: nBytesWritten != count");
}
} catch (const wxString& Msg) {
POSSIBLY_UNUSED(Msg);
bError = true;
}
return bError;
}
bool SerialPortPosix::Receive(unsigned char *pData, unsigned count)
{
bool bError = false;
try {
const unsigned int originalCount = count;
do {
const ssize_t receiveCount = read(m_fd, pData, count);
if (receiveCount == -1){
throw ERROR_INFO("SerialPortPosix: read Failed");
}
if (receiveCount == 0){
break; // eof
}
Debug.AddBytes("SerialPortPosix::Receive", pData, receiveCount);
count -= receiveCount;
pData += receiveCount;
} while(count > 0);
if (count > 0){
throw ERROR_INFO("SerialPortPosix: " + wxString::Format(wxT("%i"),count) + " remaining bytes to read at eof " + ", expected total of " + wxString::Format(wxT("%i"),originalCount));
}
} catch (const wxString& Msg) {
POSSIBLY_UNUSED(Msg);
bError = true;
}
return bError;
}
bool SerialPortPosix::SetRTS(bool asserted)
{
return true; // TODO
}
bool SerialPortPosix::SetDTR(bool asserted)
{
return true; // TODO
}
#endif // __linux__
<commit_msg>Linux: fix logic error in serial port utility class used by SX AO. Fixes #735<commit_after>/*
* serialport_posix.cpp
* PHD Guiding
*
* Created by Hans Lambermont
* Copyright (c) 2016 Hans Lambermont
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name Craig Stark, Stark Labs nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "phd.h"
#if defined (__linux__) || defined (__APPLE__)
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <errno.h>
wxArrayString SerialPortPosix::GetSerialPortList(void)
{
wxArrayString ret;
// TODO generate this list
ret.Add("/dev/ttyS0");
ret.Add("/dev/ttyS1");
ret.Add("/dev/ttyUSB0");
ret.Add("/dev/ttyUSB1");
ret.Add("/dev/sx-ao-lf");
return ret;
}
SerialPortPosix::SerialPortPosix(void)
{
m_fd = -1;
}
SerialPortPosix::~SerialPortPosix(void)
{
if (m_fd > 0) {
close(m_fd);
m_fd = -1;
}
}
bool SerialPortPosix::Connect(const wxString& portName, int baud, int dataBits, int stopBits, PARITY Parity, bool useRTS, bool useDTR)
{
bool bError = false;
try
{
if ((m_fd = open(portName.mb_str(), O_RDWR|O_NOCTTY)) < 0) {
wxString exposeToUser = wxString::Format("open %s failed %s(%d)", portName, strerror((int)errno), (int)errno);
throw ERROR_INFO("SerialPortPosix::Connect " + exposeToUser);
}
struct termios attr;
if (tcgetattr(m_fd, &attr) < 0) {
wxString errorWxs = wxString::Format("tcgetattr failed %s(%d)", strerror((int)errno), (int)errno);
throw ERROR_INFO("SerialPortPosix::Connect " + errorWxs);
}
#if defined (__APPLE__)
m_originalAttrs = attr;
cfmakeraw(&attr);
#endif
attr.c_iflag = 0; // input modes
attr.c_oflag = 0; // output modes
attr.c_cflag = CLOCAL; // CLOCAL == Ignore modem control lines.
attr.c_cflag |= CREAD ; // CREAD == Enable receiver.
switch (dataBits) {
case 7:
attr.c_cflag |= CS7; // 7 bit Character size mask.
break;
case 8:
attr.c_cflag |= CS8; // 8 bit Character size mask.
break;
default:
throw ERROR_INFO("SerialPortPosix::Connect unsupported amount of dataBits");
break;
}
switch (stopBits) {
case 1:
break;
case 2:
attr.c_cflag |= CSTOPB; // 2 stop bits
break;
default:
throw ERROR_INFO("SerialPortPosix::Connect invalid amount of stopBits");
break;
}
switch (Parity) {
case ParityNone:
break;
case ParityOdd:
attr.c_cflag |= PARENB | PARODD;
break;
case ParityEven:
attr.c_cflag |= PARENB; // Enable parity generation on output and parity checking for input.
break;
case ParityMark: // TODO, not in POSIX. CMSPAR
case ParitySpace: // TODO, not in POSIX. CMSPAR
default:
throw ERROR_INFO("SerialPortPosix::Connect invalid parity");
break;
}
attr.c_lflag &= ~ICANON; // Do not wait for a line delimiter. Work in noncanonical mode.
attr.c_lflag &= ~( ECHO | ECHOE | ISIG | IEXTEN | NOFLSH | TOSTOP); // local modes
attr.c_lflag |= NOFLSH;
attr.c_cc[VTIME] = (uint8_t)0; // timeout in deciseconds
attr.c_cc[VMIN] = (uint8_t)0; // minimum number of characters for noncanonical read
unsigned int speed = B0;
switch (baud) {
case 9600: speed = B9600; break;
case 19200: speed = B19200; break;
case 38400: speed = B38400; break;
case 57600: speed = B57600; break;
case 115200: speed = B115200; break;
case 230400: speed = B230400; break;
default:
throw ERROR_INFO("SerialPortPosix::Connect unsupported baudrate");
break;
}
if (cfsetispeed(&attr, speed) < 0 || cfsetospeed(&attr, speed) < 0) {
throw ERROR_INFO("cfsetispeed failed");
}
if (tcsetattr(m_fd, TCSAFLUSH, &attr) < 0 ) {
wxString errowWxs = wxString::Format("tcsetattr failed %s(%d)", strerror((int)errno), (int)errno);
throw ERROR_INFO("SerialPortPosix::Connect " + errowWxs);
}
int ioctl_ret = 0;
unsigned int argp;
if ((ioctl_ret = ioctl(m_fd, TIOCMGET, &argp)) < 0) {
throw ERROR_INFO("ioctl TIOCMGET");
}
if (useDTR) {
argp |= TIOCM_DTR;
}
if (useRTS) {
argp |= TIOCM_RTS;
}
if ((ioctl_ret = ioctl(m_fd, TIOCMSET, &argp)) < 0) {
throw ERROR_INFO("ioctl TIOCMSET");
}
}
catch (const wxString& Msg)
{
POSSIBLY_UNUSED(Msg);
bError = true;
}
return bError;
}
bool SerialPortPosix::Disconnect(void)
{
bool bError = false;
try
{
#if defined (__APPLE__)
if (tcdrain(m_fd) == -1) {
fprintf(stderr,"Error waiting for drain - %s(%d).\n",strerror(errno), errno);
}
if (tcsetattr(m_fd, TCSANOW, &m_originalAttrs) == -1) {
fprintf(stderr,"Error resetting tty attributes - %s(%d).\n",strerror(errno),errno);
}
#endif
if (close(m_fd) == -1) {
throw ERROR_INFO("SerialPortPosix: close failed");
}
}
catch (const wxString& Msg)
{
POSSIBLY_UNUSED(Msg);
bError = true;
}
m_fd = -1;
return bError;
}
bool SerialPortPosix::SetReceiveTimeout(int timeoutMilliSeconds)
{
bool bError = false;
Debug.Write(wxString::Format("SerialPortPosix::SetReceiveTimeout %d ms\n", timeoutMilliSeconds));
try
{
struct termios attr;
if (tcgetattr(m_fd, &attr) < 0) {
throw ERROR_INFO("tcgetattr failed");
}
int timeoutDeciSeconds = (timeoutMilliSeconds + 99) / 100;
attr.c_cc[VTIME] = (uint8_t)timeoutDeciSeconds;
if (tcsetattr(m_fd, TCSAFLUSH, &attr) < 0) {
throw ERROR_INFO("tcsetattr failed");
}
}
catch (const wxString& Msg)
{
POSSIBLY_UNUSED(Msg);
bError = true;
}
return bError;
}
bool SerialPortPosix::Send(const unsigned char *pData, unsigned int count)
{
bool bError = false;
try
{
Debug.AddBytes("SerialPortPosix::Send", pData, count);
size_t rem = count;
while (rem > 0)
{
ssize_t const nBytesWritten = write(m_fd, pData, rem);
if (nBytesWritten < 0)
throw ERROR_INFO("SerialPortPosix: write failed");
rem -= nBytesWritten;
pData += nBytesWritten;
}
}
catch (const wxString& Msg)
{
POSSIBLY_UNUSED(Msg);
bError = true;
}
return bError;
}
bool SerialPortPosix::Receive(unsigned char *pData, unsigned int count)
{
bool bError = false;
try
{
size_t rem = count;
while (rem > 0)
{
ssize_t const receiveCount = read(m_fd, pData, rem);
if (receiveCount == -1)
throw ERROR_INFO("SerialPortPosix: read Failed");
if (receiveCount == 0)
break; // eof
Debug.AddBytes("SerialPortPosix::Receive", pData, receiveCount);
rem -= receiveCount;
pData += receiveCount;
}
if (rem > 0) {
throw ERROR_INFO("SerialPortPosix: " + wxString::Format(wxT("%i"), rem) + " remaining bytes to read at eof " + ", expected total of " + wxString::Format(wxT("%i"), count));
}
}
catch (const wxString& Msg)
{
POSSIBLY_UNUSED(Msg);
bError = true;
}
return bError;
}
bool SerialPortPosix::SetRTS(bool asserted)
{
return true; // TODO
}
bool SerialPortPosix::SetDTR(bool asserted)
{
return true; // TODO
}
#endif // __linux__
<|endoftext|>
|
<commit_before>#include "MotorDetailsMessage.h"
#include "MessageDecodingHelpers.h"
#include "MessageDefines.h"
#include <QDebug>
using namespace MessageDecodingHelpers;
namespace
{
const int PHASE_CCURRENT = 1;
const int PHASE_BCURRENT = 5;
const int MOTOR_VOLTAGE_REAL = 9;
const int MOTOR_VOLTAGE_IMAGINARY = 13;
const int MOTOR_CURRENT_REAL = 17;
const int MOTOR_CURRENT_IMAGINARY = 21;
const int BACK_EMF_REAL = 25;
const int BACK_EMF_IMAGINARY = 29;
const int VOLTAGE_RAIL_SUPPPLY_15_V = 33;
const int VOLTAGE_RAIL_SUPPLY_33_V = 37;
const int VOLTAGE_RAIL_SUPPLY_19_V = 41;
const int HEAT_SINK_TEMPERATURE = 45;
const int MOTOR_TEMPTERATURE = 49;
const int DSP_BOARD_TEMPERATURE = 53;
const int DC_BUS_AMP_HOURS = 57;
const int ODOMETER = 61;
const int SLIP_SPEED = 65;
}
MotorDetailsMessage::MotorDetailsMessage(const QByteArray& messageData, unsigned char motorNumber)
: messageData_(messageData)
, motorNumber_(motorNumber)
{
}
float MotorDetailsMessage::phaseCCurrent() const
{
return getFloat(messageData_, PHASE_CCURRENT);
}
float MotorDetailsMessage::phaseBCurrent() const
{
return getFloat(messageData_, PHASE_BCURRENT);
}
float MotorDetailsMessage::motorVoltageReal() const
{
return getFloat(messageData_, MOTOR_VOLTAGE_REAL);
}
float MotorDetailsMessage::motorVoltageImaginary() const
{
return getFloat(messageData_, MOTOR_VOLTAGE_IMAGINARY);
}
float MotorDetailsMessage::motorCurrentReal() const
{
return getFloat(messageData_, MOTOR_CURRENT_REAL);
}
float MotorDetailsMessage::motorCurrentImaginary() const
{
return getFloat(messageData_, MOTOR_CURRENT_IMAGINARY);
}
float MotorDetailsMessage::backEmfReal() const
{
return getFloat(messageData_, BACK_EMF_REAL);
}
float MotorDetailsMessage::backEmfImaginary() const
{
return getFloat(messageData_, BACK_EMF_IMAGINARY);
}
float MotorDetailsMessage::voltageRailSuppply15V() const
{
return getFloat(messageData_, VOLTAGE_RAIL_SUPPPLY_15_V);
}
float MotorDetailsMessage::voltageRailSupply33V() const
{
return getFloat(messageData_, VOLTAGE_RAIL_SUPPLY_33_V);
}
float MotorDetailsMessage::voltageRailSupply19V() const
{
return getFloat(messageData_, VOLTAGE_RAIL_SUPPLY_19_V);
}
float MotorDetailsMessage::heatSinkTemperature() const
{
return getFloat(messageData_, HEAT_SINK_TEMPERATURE);
}
float MotorDetailsMessage::motorTempterature() const
{
return getFloat(messageData_, MOTOR_TEMPTERATURE);
}
float MotorDetailsMessage::dspBoardTemperature() const
{
return getFloat(messageData_, DSP_BOARD_TEMPERATURE);
}
float MotorDetailsMessage::dcBusAmpHours() const
{
return getFloat(messageData_, DC_BUS_AMP_HOURS);
}
float MotorDetailsMessage::odometer() const
{
return getFloat(messageData_, ODOMETER);
}
float MotorDetailsMessage::slipSpeed() const
{
return getFloat(messageData_, SLIP_SPEED);
}
QString MotorDetailsMessage::toString() const
{
QString messageString;
if (motorNumber_ == 0x0) {
messageString += QString::number(MessageDefines::Motor0Details) + ", ";
}
else {
// For the sake of not halting programs execution, treat all other cases as motor one
if (motorNumber != 0x1) {
// Log that this was used incorrectly
qDebug() << "Invalid motor number, defaulting to motor 1";
}
messageString += QString::number(MessageDefines::Motor1Details) + ", ";
}
messageString += QString::number(phaseCCurrent()) + ", ";
messageString += QString::number(phaseBCurrent()) + ", ";
messageString += QString::number(motorVoltageReal()) + ", ";
messageString += QString::number(motorVoltageImaginary()) + ", ";
messageString += QString::number(motorCurrentReal()) + ", ";
messageString += QString::number(motorCurrentImaginary()) + ", ";
messageString += QString::number(backEmfReal()) + ", ";
messageString += QString::number(backEmfImaginary()) + ", ";
messageString += QString::number(voltageRailSuppply15V()) + ", ";
messageString += QString::number(voltageRailSupply33V()) + ", ";
messageString += QString::number(voltageRailSupply19V()) + ", ";
messageString += QString::number(heatSinkTemperature()) + ", ";
messageString += QString::number(motorTempterature()) + ", ";
messageString += QString::number(dspBoardTemperature()) + ", ";
messageString += QString::number(dcBusAmpHours()) + ", ";
messageString += QString::number(odometer()) + ", ";
messageString += QString::number(slipSpeed()) + ", ";
return messageString;
}
<commit_msg>Fixing MotorDetailsMessage packageID<commit_after>#include "MotorDetailsMessage.h"
#include "MessageDecodingHelpers.h"
#include "MessageDefines.h"
#include <QDebug>
using namespace MessageDecodingHelpers;
namespace
{
const int PHASE_CCURRENT = 1;
const int PHASE_BCURRENT = 5;
const int MOTOR_VOLTAGE_REAL = 9;
const int MOTOR_VOLTAGE_IMAGINARY = 13;
const int MOTOR_CURRENT_REAL = 17;
const int MOTOR_CURRENT_IMAGINARY = 21;
const int BACK_EMF_REAL = 25;
const int BACK_EMF_IMAGINARY = 29;
const int VOLTAGE_RAIL_SUPPPLY_15_V = 33;
const int VOLTAGE_RAIL_SUPPLY_33_V = 37;
const int VOLTAGE_RAIL_SUPPLY_19_V = 41;
const int HEAT_SINK_TEMPERATURE = 45;
const int MOTOR_TEMPTERATURE = 49;
const int DSP_BOARD_TEMPERATURE = 53;
const int DC_BUS_AMP_HOURS = 57;
const int ODOMETER = 61;
const int SLIP_SPEED = 65;
}
MotorDetailsMessage::MotorDetailsMessage(const QByteArray& messageData, unsigned char motorNumber)
: messageData_(messageData)
, motorNumber_(motorNumber)
{
}
float MotorDetailsMessage::phaseCCurrent() const
{
return getFloat(messageData_, PHASE_CCURRENT);
}
float MotorDetailsMessage::phaseBCurrent() const
{
return getFloat(messageData_, PHASE_BCURRENT);
}
float MotorDetailsMessage::motorVoltageReal() const
{
return getFloat(messageData_, MOTOR_VOLTAGE_REAL);
}
float MotorDetailsMessage::motorVoltageImaginary() const
{
return getFloat(messageData_, MOTOR_VOLTAGE_IMAGINARY);
}
float MotorDetailsMessage::motorCurrentReal() const
{
return getFloat(messageData_, MOTOR_CURRENT_REAL);
}
float MotorDetailsMessage::motorCurrentImaginary() const
{
return getFloat(messageData_, MOTOR_CURRENT_IMAGINARY);
}
float MotorDetailsMessage::backEmfReal() const
{
return getFloat(messageData_, BACK_EMF_REAL);
}
float MotorDetailsMessage::backEmfImaginary() const
{
return getFloat(messageData_, BACK_EMF_IMAGINARY);
}
float MotorDetailsMessage::voltageRailSuppply15V() const
{
return getFloat(messageData_, VOLTAGE_RAIL_SUPPPLY_15_V);
}
float MotorDetailsMessage::voltageRailSupply33V() const
{
return getFloat(messageData_, VOLTAGE_RAIL_SUPPLY_33_V);
}
float MotorDetailsMessage::voltageRailSupply19V() const
{
return getFloat(messageData_, VOLTAGE_RAIL_SUPPLY_19_V);
}
float MotorDetailsMessage::heatSinkTemperature() const
{
return getFloat(messageData_, HEAT_SINK_TEMPERATURE);
}
float MotorDetailsMessage::motorTempterature() const
{
return getFloat(messageData_, MOTOR_TEMPTERATURE);
}
float MotorDetailsMessage::dspBoardTemperature() const
{
return getFloat(messageData_, DSP_BOARD_TEMPERATURE);
}
float MotorDetailsMessage::dcBusAmpHours() const
{
return getFloat(messageData_, DC_BUS_AMP_HOURS);
}
float MotorDetailsMessage::odometer() const
{
return getFloat(messageData_, ODOMETER);
}
float MotorDetailsMessage::slipSpeed() const
{
return getFloat(messageData_, SLIP_SPEED);
}
QString MotorDetailsMessage::toString() const
{
QString messageString;
if ((motorNumber & 0xe) != 0x0) {
qDebug() << "Invalid motor number, unexpected behaviour likely";
}
messageString += QString::number(MessageDefines::Motor0Details + motorNumber_) + ", ";
messageString += QString::number(phaseCCurrent()) + ", ";
messageString += QString::number(phaseBCurrent()) + ", ";
messageString += QString::number(motorVoltageReal()) + ", ";
messageString += QString::number(motorVoltageImaginary()) + ", ";
messageString += QString::number(motorCurrentReal()) + ", ";
messageString += QString::number(motorCurrentImaginary()) + ", ";
messageString += QString::number(backEmfReal()) + ", ";
messageString += QString::number(backEmfImaginary()) + ", ";
messageString += QString::number(voltageRailSuppply15V()) + ", ";
messageString += QString::number(voltageRailSupply33V()) + ", ";
messageString += QString::number(voltageRailSupply19V()) + ", ";
messageString += QString::number(heatSinkTemperature()) + ", ";
messageString += QString::number(motorTempterature()) + ", ";
messageString += QString::number(dspBoardTemperature()) + ", ";
messageString += QString::number(dcBusAmpHours()) + ", ";
messageString += QString::number(odometer()) + ", ";
messageString += QString::number(slipSpeed()) + ", ";
return messageString;
}
<|endoftext|>
|
<commit_before>// Copyright 2016 AUV-IITK
#include <ros/ros.h>
#include <std_msgs/Float32.h>
#include <std_msgs/Float64.h>
#include <std_msgs/Int32.h>
#include <std_msgs/String.h>
#include <std_msgs/Bool.h>
#include <std_msgs/Float64MultiArray.h>
#include <actionlib/server/simple_action_server.h>
#include <actionlib/client/simple_action_client.h>
#include <task_commons/buoyAction.h>
#include <motion_commons/ForwardAction.h>
#include <motion_commons/TurnAction.h>
#include <motion_commons/SidewardAction.h>
#include <motion_commons/UpwardAction.h>
#include <motion_commons/ForwardActionFeedback.h>
#include <motion_commons/TurnActionFeedback.h>
#include <motion_commons/SidewardActionFeedback.h>
#include <motion_commons/UpwardActionFeedback.h>
#include <motion_commons/UpwardActionResult.h>
#include <motion_commons/SidewardActionResult.h>
#include <string>
typedef actionlib::SimpleActionServer<task_commons::buoyAction> Server;
typedef actionlib::SimpleActionClient<motion_commons::ForwardAction> ClientForward;
typedef actionlib::SimpleActionClient<motion_commons::SidewardAction> ClientSideward;
typedef actionlib::SimpleActionClient<motion_commons::UpwardAction> ClientUpward;
typedef actionlib::SimpleActionClient<motion_commons::TurnAction> ClientTurn;
class TaskBuoyInnerClass
{
private:
ros::NodeHandle nh_;
Server buoy_server_;
std::string action_name_;
std_msgs::Float64 data_X_;
std_msgs::Float64 data_Y_;
std_msgs::Float64 data_distance_;
task_commons::buoyFeedback feedback_;
task_commons::buoyResult result_;
ros::Subscriber sub_ip_;
ros::Subscriber yaw_sub_;
ros::Subscriber pressure_sensor_sub;
ros::Publisher switch_buoy_detection;
ros::Publisher yaw_pub_;
ros::Publisher present_distance_;
ros::Publisher present_X_;
ros::Publisher present_Y_;
ClientForward ForwardClient_;
ClientSideward SidewardClient_;
ClientUpward UpwardClient_;
ClientTurn TurnClient_;
motion_commons::ForwardGoal forwardgoal;
motion_commons::SidewardGoal sidewardgoal;
motion_commons::UpwardGoal upwardgoal;
motion_commons::TurnGoal turngoal;
bool successBuoy, heightCenter, sideCenter, IP_stopped, heightGoal;
float present_depth;
public:
TaskBuoyInnerClass(std::string name, std::string node, std::string node1, std::string node2, std::string node3)
: buoy_server_(nh_, name, boost::bind(&TaskBuoyInnerClass::analysisCB, this, _1), false)
, action_name_(name)
, ForwardClient_(node)
, SidewardClient_(node1)
, UpwardClient_(node2)
, TurnClient_(node3)
{
ROS_INFO("inside constructor");
buoy_server_.registerPreemptCallback(boost::bind(&TaskBuoyInnerClass::preemptCB, this));
switch_buoy_detection = nh_.advertise<std_msgs::Bool>("buoy_detection_switch", 1000);
present_X_ = nh_.advertise<std_msgs::Float64>("/varun/motion/y_distance", 1000);
present_Y_ = nh_.advertise<std_msgs::Float64>("/varun/motion/z_distance", 1000);
present_distance_ = nh_.advertise<std_msgs::Float64>("/varun/motion/x_distance", 1000);
yaw_pub_ = nh_.advertise<std_msgs::Float64>("/varun/motion/yaw", 1000);
sub_ip_ =
nh_.subscribe<std_msgs::Float64MultiArray>("/varun/ip/buoy", 1000, &TaskBuoyInnerClass::buoyNavigation, this);
yaw_sub_ = nh_.subscribe<std_msgs::Float64>("/varun/sensors/imu/yaw", 1000, &TaskBuoyInnerClass::yawCB, this);
pressure_sensor_sub =
nh_.subscribe<std_msgs::Float64>("/varun/sensors/pressure_sensor/depth",
1000, &TaskBuoyInnerClass::pressureCB, this);
buoy_server_.start();
}
~TaskBuoyInnerClass(void)
{
}
void yawCB(std_msgs::Float64 imu_data)
{
yaw_pub_.publish(imu_data);
}
void pressureCB(std_msgs::Float64 pressure_sensor_data)
{
present_depth = pressure_sensor_data.data;
if (successBuoy)
present_Y_.publish(pressure_sensor_data);
}
void buoyNavigation(std_msgs::Float64MultiArray array)
{
data_X_.data = array.data[1];
data_Y_.data = array.data[2];
data_distance_.data = array.data[3];
present_X_.publish(data_X_);
present_Y_.publish(data_Y_);
if (data_distance_.data > 0)
present_distance_.publish(data_distance_);
else if (data_distance_.data < 0)
{
IP_stopped = true;
stopBuoyDetection();
ROS_INFO("Bot is in front of buoy, IP stopped.");
}
}
void preemptCB(void)
{
// Not actually preempting the goal because Prakhar did it in analysisCB
ROS_INFO("Called when preempted from the client");
}
void spinThreadUpwardCamera()
{
ClientUpward &tempUpward = UpwardClient_;
tempUpward.waitForResult();
heightCenter = (*(tempUpward.getResult())).Result;
if (heightCenter)
{
ROS_INFO("Bot is at height center");
}
else
{
ROS_INFO("Bot is not at height center, something went wrong");
}
}
void spinThreadUpwardPressure()
{
ClientUpward &tempUpward = UpwardClient_;
tempUpward.waitForResult();
heightGoal = (*(tempUpward.getResult())).Result;
if (heightGoal)
{
ROS_INFO("Bot is at desired height.");
}
else
{
ROS_INFO("Bot is not at desired height, something went wrong");
}
}
void spinThreadSidewardCamera()
{
ClientSideward &tempSideward = SidewardClient_;
tempSideward.waitForResult();
sideCenter = (*(tempSideward.getResult())).Result;
if (sideCenter)
{
ROS_INFO("Bot is at side center");
}
else
{
ROS_INFO("Bot is not at side center, something went wrong");
}
}
void analysisCB(const task_commons::buoyGoalConstPtr goal)
{
ROS_INFO("Inside analysisCB");
heightCenter = false;
sideCenter = false;
successBuoy = false;
IP_stopped = false;
heightGoal = false;
ros::Rate looprate(12);
if (!buoy_server_.isActive())
return;
ROS_INFO("Waiting for Forward server to start.");
ForwardClient_.waitForServer();
SidewardClient_.waitForServer();
UpwardClient_.waitForServer();
TurnClient_.waitForServer();
TaskBuoyInnerClass::startBuoyDetection();
sidewardgoal.Goal = 0;
sidewardgoal.loop = 10;
SidewardClient_.sendGoal(sidewardgoal);
boost::thread spin_thread_sideward_camera(&TaskBuoyInnerClass::spinThreadSidewardCamera, this);
// Stabilization of yaw
turngoal.AngleToTurn = 0;
turngoal.loop = 100000;
TurnClient_.sendGoal(turngoal);
upwardgoal.Goal = 0;
upwardgoal.loop = 10;
UpwardClient_.sendGoal(upwardgoal);
boost::thread spin_thread_upward_camera(&TaskBuoyInnerClass::spinThreadUpwardCamera, this);
while (goal->order)
{
if (buoy_server_.isPreemptRequested() || !ros::ok())
{
ROS_INFO("%s: Preempted", action_name_.c_str());
// set the action state to preempted
buoy_server_.setPreempted();
successBuoy = false;
break;
}
looprate.sleep();
if (heightCenter && sideCenter)
{
break;
}
// publish the feedback
feedback_.nosignificance = false;
buoy_server_.publishFeedback(feedback_);
ROS_INFO("x = %f, y = %f, front distance = %f", data_X_.data, data_Y_.data, data_distance_.data);
ros::spinOnce();
}
ROS_INFO("Bot is in center of buoy");
forwardgoal.Goal = 0;
forwardgoal.loop = 10;
ForwardClient_.sendGoal(forwardgoal);
while (goal->order)
{
if (buoy_server_.isPreemptRequested() || !ros::ok())
{
ROS_INFO("%s: Preempted", action_name_.c_str());
// set the action state to preempted
buoy_server_.setPreempted();
successBuoy = false;
break;
}
looprate.sleep();
if (IP_stopped)
{
successBuoy = true;
ROS_INFO("Waiting for hitting the buoy...");
sleep(1);
break;
}
feedback_.nosignificance = false;
buoy_server_.publishFeedback(feedback_);
ROS_INFO("x = %f, y = %f, front distance = %f", data_X_.data, data_Y_.data, data_distance_.data);
ros::spinOnce();
}
ForwardClient_.cancelGoal(); // stop motion here
upwardgoal.Goal = present_depth + 5;
upwardgoal.loop = 10;
UpwardClient_.sendGoal(upwardgoal);
ROS_INFO("moving upward");
boost::thread spin_thread_upward_pressure(&TaskBuoyInnerClass::spinThreadUpwardPressure, this);
while (!heightGoal)
{
ROS_INFO("present depth = %f", present_depth);
looprate.sleep();
ros::spinOnce();
}
result_.MotionCompleted = successBuoy && heightGoal;
ROS_INFO("%s: Succeeded", action_name_.c_str());
// set the action state to succeeded
buoy_server_.setSucceeded(result_);
}
void startBuoyDetection()
{
std_msgs::Bool msg;
msg.data = false;
switch_buoy_detection.publish(msg);
}
void stopBuoyDetection()
{
std_msgs::Bool msg;
msg.data = true;
switch_buoy_detection.publish(msg);
}
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "buoy_server");
ROS_INFO("Waiting for Goal");
TaskBuoyInnerClass taskBuoyObject(ros::this_node::getName(), "forward", "sideward", "upward", "turningXY");
ros::spin();
return 0;
}
<commit_msg>fixed the errors for buoy out of screen<commit_after>// Copyright 2016 AUV-IITK
#include <ros/ros.h>
#include <std_msgs/Float32.h>
#include <std_msgs/Float64.h>
#include <std_msgs/Int32.h>
#include <std_msgs/String.h>
#include <std_msgs/Bool.h>
#include <std_msgs/Float64MultiArray.h>
#include <actionlib/server/simple_action_server.h>
#include <actionlib/client/simple_action_client.h>
#include <task_commons/buoyAction.h>
#include <motion_commons/ForwardAction.h>
#include <motion_commons/TurnAction.h>
#include <motion_commons/SidewardAction.h>
#include <motion_commons/UpwardAction.h>
#include <motion_commons/ForwardActionFeedback.h>
#include <motion_commons/TurnActionFeedback.h>
#include <motion_commons/SidewardActionFeedback.h>
#include <motion_commons/UpwardActionFeedback.h>
#include <motion_commons/UpwardActionResult.h>
#include <motion_commons/SidewardActionResult.h>
#include <string>
typedef actionlib::SimpleActionServer<task_commons::buoyAction> Server;
typedef actionlib::SimpleActionClient<motion_commons::ForwardAction> ClientForward;
typedef actionlib::SimpleActionClient<motion_commons::SidewardAction> ClientSideward;
typedef actionlib::SimpleActionClient<motion_commons::UpwardAction> ClientUpward;
typedef actionlib::SimpleActionClient<motion_commons::TurnAction> ClientTurn;
class TaskBuoyInnerClass
{
private:
ros::NodeHandle nh_;
Server buoy_server_;
std::string action_name_;
std_msgs::Float64 data_X_;
std_msgs::Float64 data_Y_;
std_msgs::Float64 data_distance_;
task_commons::buoyFeedback feedback_;
task_commons::buoyResult result_;
ros::Subscriber sub_ip_;
ros::Subscriber yaw_sub_;
ros::Subscriber pressure_sensor_sub;
ros::Publisher switch_buoy_detection;
ros::Publisher yaw_pub_;
ros::Publisher present_distance_;
ros::Publisher present_X_;
ros::Publisher present_Y_;
ClientForward ForwardClient_;
ClientSideward SidewardClient_;
ClientUpward UpwardClient_;
ClientTurn TurnClient_;
motion_commons::ForwardGoal forwardgoal;
motion_commons::SidewardGoal sidewardgoal;
motion_commons::UpwardGoal upwardgoal;
motion_commons::TurnGoal turngoal;
bool successBuoy, heightCenter, sideCenter, IP_stopped, heightGoal;
float present_depth;
public:
TaskBuoyInnerClass(std::string name, std::string node, std::string node1, std::string node2, std::string node3)
: buoy_server_(nh_, name, boost::bind(&TaskBuoyInnerClass::analysisCB, this, _1), false)
, action_name_(name)
, ForwardClient_(node)
, SidewardClient_(node1)
, UpwardClient_(node2)
, TurnClient_(node3)
{
ROS_INFO("inside constructor");
buoy_server_.registerPreemptCallback(boost::bind(&TaskBuoyInnerClass::preemptCB, this));
switch_buoy_detection = nh_.advertise<std_msgs::Bool>("buoy_detection_switch", 1000);
present_X_ = nh_.advertise<std_msgs::Float64>("/varun/motion/y_distance", 1000);
present_Y_ = nh_.advertise<std_msgs::Float64>("/varun/motion/z_distance", 1000);
present_distance_ = nh_.advertise<std_msgs::Float64>("/varun/motion/x_distance", 1000);
yaw_pub_ = nh_.advertise<std_msgs::Float64>("/varun/motion/yaw", 1000);
sub_ip_ =
nh_.subscribe<std_msgs::Float64MultiArray>("/varun/ip/buoy", 1000, &TaskBuoyInnerClass::buoyNavigation, this);
yaw_sub_ = nh_.subscribe<std_msgs::Float64>("/varun/sensors/imu/yaw", 1000, &TaskBuoyInnerClass::yawCB, this);
pressure_sensor_sub =
nh_.subscribe<std_msgs::Float64>("/varun/sensors/pressure_sensor/depth",
1000, &TaskBuoyInnerClass::pressureCB, this);
buoy_server_.start();
}
~TaskBuoyInnerClass(void)
{
}
void yawCB(std_msgs::Float64 imu_data)
{
yaw_pub_.publish(imu_data);
}
void pressureCB(std_msgs::Float64 pressure_sensor_data)
{
present_depth = pressure_sensor_data.data;
if (successBuoy)
present_Y_.publish(pressure_sensor_data);
}
void buoyNavigation(std_msgs::Float64MultiArray array)
{
data_X_.data = array.data[1];
data_Y_.data = array.data[2];
data_distance_.data = array.data[3];
if (data_distance_.data > 0)
{
present_distance_.publish(data_distance_);
present_X_.publish(data_X_);
present_Y_.publish(data_Y_);
}
// if distance is -1 to -4 then buoy is out of frame and the motion library will assume the last data.
else if (data_distance_.data == -5)
{
IP_stopped = true;
stopBuoyDetection();
ROS_INFO("Bot is in front of buoy, IP stopped.");
}
}
void preemptCB(void)
{
// Not actually preempting the goal because Prakhar did it in analysisCB
ROS_INFO("Called when preempted from the client");
}
void spinThreadUpwardCamera()
{
ClientUpward &tempUpward = UpwardClient_;
tempUpward.waitForResult();
heightCenter = (*(tempUpward.getResult())).Result;
if (heightCenter)
{
ROS_INFO("Bot is at height center");
}
else
{
ROS_INFO("Bot is not at height center, something went wrong");
}
}
void spinThreadUpwardPressure()
{
ClientUpward &tempUpward = UpwardClient_;
tempUpward.waitForResult();
heightGoal = (*(tempUpward.getResult())).Result;
if (heightGoal)
{
ROS_INFO("Bot is at desired height.");
}
else
{
ROS_INFO("Bot is not at desired height, something went wrong");
}
}
void spinThreadSidewardCamera()
{
ClientSideward &tempSideward = SidewardClient_;
tempSideward.waitForResult();
sideCenter = (*(tempSideward.getResult())).Result;
if (sideCenter)
{
ROS_INFO("Bot is at side center");
}
else
{
ROS_INFO("Bot is not at side center, something went wrong");
}
}
void analysisCB(const task_commons::buoyGoalConstPtr goal)
{
ROS_INFO("Inside analysisCB");
heightCenter = false;
sideCenter = false;
successBuoy = false;
IP_stopped = false;
heightGoal = false;
ros::Rate looprate(12);
if (!buoy_server_.isActive())
return;
ROS_INFO("Waiting for Forward server to start.");
ForwardClient_.waitForServer();
SidewardClient_.waitForServer();
UpwardClient_.waitForServer();
TurnClient_.waitForServer();
TaskBuoyInnerClass::startBuoyDetection();
sidewardgoal.Goal = 0;
sidewardgoal.loop = 10;
SidewardClient_.sendGoal(sidewardgoal);
boost::thread spin_thread_sideward_camera(&TaskBuoyInnerClass::spinThreadSidewardCamera, this);
// Stabilization of yaw
turngoal.AngleToTurn = 0;
turngoal.loop = 100000;
TurnClient_.sendGoal(turngoal);
upwardgoal.Goal = 0;
upwardgoal.loop = 10;
UpwardClient_.sendGoal(upwardgoal);
boost::thread spin_thread_upward_camera(&TaskBuoyInnerClass::spinThreadUpwardCamera, this);
while (goal->order)
{
if (buoy_server_.isPreemptRequested() || !ros::ok())
{
ROS_INFO("%s: Preempted", action_name_.c_str());
// set the action state to preempted
buoy_server_.setPreempted();
successBuoy = false;
break;
}
looprate.sleep();
if (heightCenter && sideCenter)
{
break;
}
// publish the feedback
feedback_.nosignificance = false;
buoy_server_.publishFeedback(feedback_);
ROS_INFO("x = %f, y = %f, front distance = %f", data_X_.data, data_Y_.data, data_distance_.data);
ros::spinOnce();
}
ROS_INFO("Bot is in center of buoy");
forwardgoal.Goal = 0;
forwardgoal.loop = 10;
ForwardClient_.sendGoal(forwardgoal);
while (goal->order)
{
if (buoy_server_.isPreemptRequested() || !ros::ok())
{
ROS_INFO("%s: Preempted", action_name_.c_str());
// set the action state to preempted
buoy_server_.setPreempted();
successBuoy = false;
break;
}
looprate.sleep();
if (IP_stopped)
{
successBuoy = true;
ROS_INFO("Waiting for hitting the buoy...");
sleep(1);
break;
}
feedback_.nosignificance = false;
buoy_server_.publishFeedback(feedback_);
ROS_INFO("x = %f, y = %f, front distance = %f", data_X_.data, data_Y_.data, data_distance_.data);
ros::spinOnce();
}
ForwardClient_.cancelGoal(); // stop motion here
upwardgoal.Goal = present_depth + 5;
upwardgoal.loop = 10;
UpwardClient_.sendGoal(upwardgoal);
ROS_INFO("moving upward");
boost::thread spin_thread_upward_pressure(&TaskBuoyInnerClass::spinThreadUpwardPressure, this);
while (!heightGoal)
{
ROS_INFO("present depth = %f", present_depth);
looprate.sleep();
ros::spinOnce();
}
result_.MotionCompleted = successBuoy && heightGoal;
ROS_INFO("%s: Succeeded", action_name_.c_str());
// set the action state to succeeded
buoy_server_.setSucceeded(result_);
}
void startBuoyDetection()
{
std_msgs::Bool msg;
msg.data = false;
switch_buoy_detection.publish(msg);
}
void stopBuoyDetection()
{
std_msgs::Bool msg;
msg.data = true;
switch_buoy_detection.publish(msg);
}
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "buoy_server");
ROS_INFO("Waiting for Goal");
TaskBuoyInnerClass taskBuoyObject(ros::this_node::getName(), "forward", "sideward", "upward", "turningXY");
ros::spin();
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2015, Andreas Fett. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
*/
#include <inttypes.h>
#include <stdexcept>
#include <ostream>
#include <cassert>
#include "token-stream.h"
#include "utf8stream.h"
namespace {
bool is_ws(int c)
{
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
}
}
namespace jsonp {
std::ostream & operator<<(std::ostream & os, Token::Type type)
{
#define CASE_TOKEN_TYPE(name) case name: os << # name; break
switch (type) {
CASE_TOKEN_TYPE(Token::INVALID);
CASE_TOKEN_TYPE(Token::BEGIN_ARRAY);
CASE_TOKEN_TYPE(Token::END_ARRAY);
CASE_TOKEN_TYPE(Token::BEGIN_OBJECT);
CASE_TOKEN_TYPE(Token::END_OBJECT);
CASE_TOKEN_TYPE(Token::NAME_SEPARATOR);
CASE_TOKEN_TYPE(Token::VALUE_SEPARATOR);
CASE_TOKEN_TYPE(Token::TRUE_LITERAL);
CASE_TOKEN_TYPE(Token::FALSE_LITERAL);
CASE_TOKEN_TYPE(Token::NULL_LITERAL);
CASE_TOKEN_TYPE(Token::STRING);
CASE_TOKEN_TYPE(Token::NUMBER);
}
#undef CASE_TOKEN_TYPE
return os;
}
TokenStream::TokenStream(Utf8Stream & stream)
:
stream_(stream)
{ }
void TokenStream::scan()
{
int c;
do {
c = stream_.getc();
} while (is_ws(c));
if (stream_.state() != Utf8Stream::SGOOD) {
return;
}
try {
(this->*select_scanner(c))();
} catch (std::runtime_error const& e) {
throw;
}
// error
assert(false && "implement error handling");
}
TokenStream::scanner TokenStream::select_scanner(int c)
{
scanner res(0);
switch (c) {
case '[': case '{': case ']':
case '}': case ':': case ',':
res = &TokenStream::scan_structural;
break;
case 't':
res = &TokenStream::scan_true;
break;
case 'n':
res = &TokenStream::scan_null;
break;
case 'f':
res = &TokenStream::scan_false;
break;
case '"':
res = &TokenStream::scan_string;
break;
case '-':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c = '0';
res = &TokenStream::scan_number;
break;
default:
c = 0;
res = &TokenStream::invalid_token;
break;
}
token.type = Token::Type(c);
return res;
}
void TokenStream::invalid_token() { throw std::runtime_error("invalid token"); }
void TokenStream::scan_structural() { /* NOOP */ }
void TokenStream::scan_true() { scan_literal("true"); }
void TokenStream::scan_false() { scan_literal("false"); }
void TokenStream::scan_null() { scan_literal("null"); }
void TokenStream::scan_literal(const char *literal)
{
for (const char *p(&literal[1]); *p; p++) {
if (stream_.getc() != *p) {
throw std::runtime_error(literal);
}
}
}
void TokenStream::scan_string()
{
// TODO
}
void TokenStream::scan_number()
{
stream_.ungetc();
int c(stream_.getc());
bool minus(c == '-');
if (minus) {
c = stream_.getc();
}
uint64_t mantissa(0);
size_t digits(0);
size_t point(0);
bool done(false);
for (; !done; c = stream_.getc()) {
switch (c) {
case '.':
if (!point) {
point = digits;
} else {
throw std::runtime_error("invalid decimal point");
}
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
mantissa = mantissa * 10 + (c - '0');
if (++digits > 1 && !mantissa) {
throw std::runtime_error("no leading zeros please");
}
break;
default:
done = true;
break;
}
}
bool eminus(false);
uint64_t exponent(0);
if (c == 'e' || c == 'E') {
c = stream_.getc();
if (c == '+' || c == '-') {
eminus = c == '-';
c = stream_.getc();
}
while (c >= '0' && c <= '9') {
exponent = exponent * 10 + (c - '0');
c = stream_.getc();
}
}
if (eminus) {
}
}
}
<commit_msg>TokenStream: fix EOF handling<commit_after>/*
Copyright (c) 2015, Andreas Fett. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
*/
#include <inttypes.h>
#include <stdexcept>
#include <ostream>
#include <cassert>
#include "token-stream.h"
#include "utf8stream.h"
namespace {
bool is_ws(int c)
{
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
}
}
namespace jsonp {
std::ostream & operator<<(std::ostream & os, Token::Type type)
{
#define CASE_TOKEN_TYPE(name) case name: os << # name; break
switch (type) {
CASE_TOKEN_TYPE(Token::INVALID);
CASE_TOKEN_TYPE(Token::BEGIN_ARRAY);
CASE_TOKEN_TYPE(Token::END_ARRAY);
CASE_TOKEN_TYPE(Token::BEGIN_OBJECT);
CASE_TOKEN_TYPE(Token::END_OBJECT);
CASE_TOKEN_TYPE(Token::NAME_SEPARATOR);
CASE_TOKEN_TYPE(Token::VALUE_SEPARATOR);
CASE_TOKEN_TYPE(Token::TRUE_LITERAL);
CASE_TOKEN_TYPE(Token::FALSE_LITERAL);
CASE_TOKEN_TYPE(Token::NULL_LITERAL);
CASE_TOKEN_TYPE(Token::STRING);
CASE_TOKEN_TYPE(Token::NUMBER);
}
#undef CASE_TOKEN_TYPE
return os;
}
TokenStream::TokenStream(Utf8Stream & stream)
:
stream_(stream)
{ }
void TokenStream::scan()
{
int c;
do {
c = stream_.getc();
} while (is_ws(c));
if (c == int(Utf8Stream::SEOF)) {
return;
}
if (stream_.state() == Utf8Stream::SBAD) {
return;
}
try {
(this->*select_scanner(c))();
} catch (std::runtime_error const& e) {
throw;
}
// error
assert(false && "implement error handling");
}
TokenStream::scanner TokenStream::select_scanner(int c)
{
scanner res(0);
switch (c) {
case '[': case '{': case ']':
case '}': case ':': case ',':
res = &TokenStream::scan_structural;
break;
case 't':
res = &TokenStream::scan_true;
break;
case 'n':
res = &TokenStream::scan_null;
break;
case 'f':
res = &TokenStream::scan_false;
break;
case '"':
res = &TokenStream::scan_string;
break;
case '-':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
c = '0';
res = &TokenStream::scan_number;
break;
default:
c = 0;
res = &TokenStream::invalid_token;
break;
}
token.type = Token::Type(c);
return res;
}
void TokenStream::invalid_token() { throw std::runtime_error("invalid token"); }
void TokenStream::scan_structural() { /* NOOP */ }
void TokenStream::scan_true() { scan_literal("true"); }
void TokenStream::scan_false() { scan_literal("false"); }
void TokenStream::scan_null() { scan_literal("null"); }
void TokenStream::scan_literal(const char *literal)
{
for (const char *p(&literal[1]); *p; p++) {
if (stream_.getc() != *p) {
throw std::runtime_error(literal);
}
}
}
void TokenStream::scan_string()
{
// TODO
}
void TokenStream::scan_number()
{
stream_.ungetc();
int c(stream_.getc());
bool minus(c == '-');
if (minus) {
c = stream_.getc();
}
uint64_t mantissa(0);
size_t digits(0);
size_t point(0);
bool done(false);
for (; !done; c = stream_.getc()) {
switch (c) {
case '.':
if (!point) {
point = digits;
} else {
throw std::runtime_error("invalid decimal point");
}
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
mantissa = mantissa * 10 + (c - '0');
if (++digits > 1 && !mantissa) {
throw std::runtime_error("no leading zeros please");
}
break;
default:
done = true;
break;
}
}
bool eminus(false);
uint64_t exponent(0);
if (c == 'e' || c == 'E') {
c = stream_.getc();
if (c == '+' || c == '-') {
eminus = c == '-';
c = stream_.getc();
}
while (c >= '0' && c <= '9') {
exponent = exponent * 10 + (c - '0');
c = stream_.getc();
}
}
if (eminus) {
}
}
}
<|endoftext|>
|
<commit_before>#line 2 "togo/utility/utility.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief Utilities.
@ingroup utility
*/
#pragma once
#include <togo/config.hpp>
#include <togo/types.hpp>
#include <togo/utility/traits.hpp>
#include <togo/utility/constraints.hpp>
#include <type_traits>
namespace togo {
/**
@addtogroup utility
@{
*/
/** @name Type utilities */ /// @{
/// Cast unsigned integral to signed integral.
template<class T>
inline constexpr typename std::make_signed<T>::type
signed_cast(T const value) noexcept {
return static_cast<typename std::make_signed<T>::type>(value);
}
/// Cast signed integral to unsigned integral.
template<class T>
inline constexpr typename std::make_unsigned<T>::type
unsigned_cast(T const value) noexcept {
return static_cast<typename std::make_unsigned<T>::type>(value);
}
/// Get number of elements in bounded array.
template<class T, unsigned N>
inline constexpr unsigned
array_extent(T const (&)[N]) noexcept {
return N;
}
/// Get number of elements in bounded array.
template<class T, class U, unsigned N>
inline constexpr unsigned
array_extent(T const (U::* const)[N]) noexcept {
return N;
}
/// Get sizeof type or 0 if the type is empty.
template<class T>
inline constexpr unsigned
sizeof_empty() noexcept {
return std::is_empty<T>::value ? 0 : sizeof(T);
}
/// @}
/** @name Misc utilities */ /// @{
/// Swap the values of two references.
template<class T>
inline void swap(T& x, T& y) {
T temp = x;
x = y;
y = temp;
}
/// Less-than comparison operator wrapper.
template<class T>
inline bool less(T const& x, T const& y) {
return x < y;
}
/// Greater-than comparison operator wrapper.
template<class T>
inline bool greater(T const& x, T const& y) {
return x > y;
}
/// @}
/** @name Arithmetic utilities */ /// @{
/// Get the smallest of two values.
template<class T>
inline constexpr T min(T const x, T const y) noexcept {
TOGO_CONSTRAIN_INTEGRAL(T);
return x < y ? x : y;
}
/// Get the largest of two values.
template<class T>
inline constexpr T max(T const x, T const y) noexcept {
TOGO_CONSTRAIN_INTEGRAL(T);
return x > y ? x : y;
}
/// Clamp a value between a minimum and maximum.
template<class T>
inline constexpr T clamp(T const x, T const minimum, T const maximum) noexcept {
TOGO_CONSTRAIN_INTEGRAL(T);
return
x < minimum
? minimum
: x > maximum
? maximum
: x
;
}
/// @}
/** @name Memory utilities */ /// @{
/// Advance pointer by bytes.
/// @warning This advances by bytes, not sizeof(T).
template<class T>
inline T* pointer_add(T* p, u32 const bytes) noexcept {
return reinterpret_cast<T*>(reinterpret_cast<char*>(p) + bytes);
}
/// Aligns a pointer by moving it forward.
template<class T>
inline T* pointer_align(T* p, u32 const align) noexcept {
u32 const m = reinterpret_cast<std::uintptr_t>(p) % align;
if (m) {
p = pointer_add(p, align - m);
}
return p;
}
/// @}
/** @name Enum utilities */ /// @{
/// Return true whether an enum value is non-zero.
template<class T>
inline constexpr bool enum_bool(T const value) {
static_assert(
std::is_enum<T>::value,
"T must be an enum"
);
return static_cast<typename std::underlying_type<T>::type>(value);
}
/** @cond INTERNAL */
template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT operator|(FlagT const& x, FlagT const& y) noexcept {
return static_cast<FlagT>(
static_cast<unsigned>(x) | static_cast<unsigned>(y)
);
}
template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT operator&(FlagT const& x, FlagT const& y) noexcept {
return static_cast<FlagT>(
static_cast<unsigned>(x) & static_cast<unsigned>(y)
);
}
template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT operator~(FlagT const& x) noexcept {
return static_cast<FlagT>(
~static_cast<unsigned>(x)
);
}
template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT& operator|=(FlagT& x, FlagT const& y) noexcept {
return x = static_cast<FlagT>(
static_cast<unsigned>(x) | static_cast<unsigned>(y)
);
}
template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT& operator&=(FlagT& x, FlagT const& y) noexcept {
return x = static_cast<FlagT>(
static_cast<unsigned>(x) & static_cast<unsigned>(y)
);
}
/** @endcond */ // INTERNAL
/// @}
/** @name Collection utilities */ /// @{
/// Array reference.
template<class T>
struct ArrayRef {
T* _begin;
T* _end;
};
/// Make reference to array.
template<class T>
inline ArrayRef<T> array_ref(unsigned const size, T* const data) {
return ArrayRef<T>{data, data + size};
}
/** @cond INTERNAL */
template<class T>
inline T* begin(ArrayRef<T> const& ar) { return ar._begin; }
template<class T>
inline T const* cbegin(ArrayRef<T> const& ar) { return ar._begin; }
template<class T>
inline T* end(ArrayRef<T> const& ar) { return ar._end; }
template<class T>
inline T const* cend(ArrayRef<T> const& ar) { return ar._end; }
/** @endcond */ // INTERNAL
/// @}
/** @} */ // end of doc-group utility
} // namespace togo
<commit_msg>utility/utility: added rvalue_ref(), forward(), and type_value().<commit_after>#line 2 "togo/utility/utility.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief Utilities.
@ingroup utility
*/
#pragma once
#include <togo/config.hpp>
#include <togo/types.hpp>
#include <togo/utility/traits.hpp>
#include <togo/utility/constraints.hpp>
#include <type_traits>
namespace togo {
/**
@addtogroup utility
@{
*/
/** @name Type utilities */ /// @{
/// Cast unsigned integral to signed integral.
template<class T>
inline constexpr typename std::make_signed<T>::type
signed_cast(T const value) noexcept {
return static_cast<typename std::make_signed<T>::type>(value);
}
/// Cast signed integral to unsigned integral.
template<class T>
inline constexpr typename std::make_unsigned<T>::type
unsigned_cast(T const value) noexcept {
return static_cast<typename std::make_unsigned<T>::type>(value);
}
/// Get number of elements in bounded array.
template<class T, unsigned N>
inline constexpr unsigned
array_extent(T const (&)[N]) noexcept {
return N;
}
/// Get number of elements in bounded array.
template<class T, class U, unsigned N>
inline constexpr unsigned
array_extent(T const (U::* const)[N]) noexcept {
return N;
}
/// Get sizeof type or 0 if the type is empty.
template<class T>
inline constexpr unsigned
sizeof_empty() noexcept {
return std::is_empty<T>::value ? 0 : sizeof(T);
}
/// @}
/** @name Misc utilities */ /// @{
/// Make an rvalue reference.
///
/// This is equivalent to std::move(), whose name is totally bonkers.
template<class T>
inline constexpr remove_ref<T>&& rvalue_ref(T&& x) noexcept {
return static_cast<remove_ref<T>&&>(x);
}
/// Retain value category when passing to another function.
///
/// This is equivalent to std::forward().
template<class T>
inline constexpr T&& forward(remove_ref<T>& x) noexcept {
return static_cast<T&&>(x);
}
template<class T>
inline constexpr T&& forward(remove_ref<T>&& x) noexcept {
static_assert(
!is_lvalue_reference<T>::value,
"rvalue cannot be forwarded as an lvalue"
);
return static_cast<T&&>(x);
}
/// A type as an unevaluated value.
///
/// This is equivalent to std::declval().
template<class T>
inline add_rvalue_ref<T> type_value() noexcept;
/// Swap the values of two references.
template<class T>
inline void swap(T& x, T& y) {
T temp = x;
x = y;
y = temp;
}
/// Less-than comparison operator wrapper.
template<class T>
inline bool less(T const& x, T const& y) {
return x < y;
}
/// Greater-than comparison operator wrapper.
template<class T>
inline bool greater(T const& x, T const& y) {
return x > y;
}
/// @}
/** @name Arithmetic utilities */ /// @{
/// Get the smallest of two values.
template<class T>
inline constexpr T min(T const x, T const y) noexcept {
TOGO_CONSTRAIN_INTEGRAL(T);
return x < y ? x : y;
}
/// Get the largest of two values.
template<class T>
inline constexpr T max(T const x, T const y) noexcept {
TOGO_CONSTRAIN_INTEGRAL(T);
return x > y ? x : y;
}
/// Clamp a value between a minimum and maximum.
template<class T>
inline constexpr T clamp(T const x, T const minimum, T const maximum) noexcept {
TOGO_CONSTRAIN_INTEGRAL(T);
return
x < minimum
? minimum
: x > maximum
? maximum
: x
;
}
/// @}
/** @name Memory utilities */ /// @{
/// Advance pointer by bytes.
/// @warning This advances by bytes, not sizeof(T).
template<class T>
inline T* pointer_add(T* p, u32 const bytes) noexcept {
return reinterpret_cast<T*>(reinterpret_cast<char*>(p) + bytes);
}
/// Aligns a pointer by moving it forward.
template<class T>
inline T* pointer_align(T* p, u32 const align) noexcept {
u32 const m = reinterpret_cast<std::uintptr_t>(p) % align;
if (m) {
p = pointer_add(p, align - m);
}
return p;
}
/// @}
/** @name Enum utilities */ /// @{
/// Return true whether an enum value is non-zero.
template<class T>
inline constexpr bool enum_bool(T const value) {
static_assert(
std::is_enum<T>::value,
"T must be an enum"
);
return static_cast<typename std::underlying_type<T>::type>(value);
}
/** @cond INTERNAL */
template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT operator|(FlagT const& x, FlagT const& y) noexcept {
return static_cast<FlagT>(
static_cast<unsigned>(x) | static_cast<unsigned>(y)
);
}
template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT operator&(FlagT const& x, FlagT const& y) noexcept {
return static_cast<FlagT>(
static_cast<unsigned>(x) & static_cast<unsigned>(y)
);
}
template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT operator~(FlagT const& x) noexcept {
return static_cast<FlagT>(
~static_cast<unsigned>(x)
);
}
template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT& operator|=(FlagT& x, FlagT const& y) noexcept {
return x = static_cast<FlagT>(
static_cast<unsigned>(x) | static_cast<unsigned>(y)
);
}
template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT& operator&=(FlagT& x, FlagT const& y) noexcept {
return x = static_cast<FlagT>(
static_cast<unsigned>(x) & static_cast<unsigned>(y)
);
}
/** @endcond */ // INTERNAL
/// @}
/** @name Collection utilities */ /// @{
/// Array reference.
template<class T>
struct ArrayRef {
T* _begin;
T* _end;
};
/// Make reference to array.
template<class T>
inline ArrayRef<T> array_ref(unsigned const size, T* const data) {
return ArrayRef<T>{data, data + size};
}
/** @cond INTERNAL */
template<class T>
inline T* begin(ArrayRef<T> const& ar) { return ar._begin; }
template<class T>
inline T const* cbegin(ArrayRef<T> const& ar) { return ar._begin; }
template<class T>
inline T* end(ArrayRef<T> const& ar) { return ar._end; }
template<class T>
inline T const* cend(ArrayRef<T> const& ar) { return ar._end; }
/** @endcond */ // INTERNAL
/// @}
/** @} */ // end of doc-group utility
} // namespace togo
<|endoftext|>
|
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "tool_utils.hh"
#include "../registrardb-internal.hh"
#include "../registrardb.hh"
using namespace std;
struct MyListener : public ContactUpdateListener {
RegistrarDb::BindParameters params;
MyListener(const RegistrarDb::BindParameters ¶ms) : params(params){};
virtual void onRecordFound(Record *r) {
// cout << "record found : ";
// r->print(cout);
// cout << endl;
auto ecc = firstContact(*r);
long rExpire = ecc.mExpireAt - ecc.mUpdatedTime;
check("expire", atol(params.sip.contact->m_expires), rExpire);
}
virtual void onError() {
BAD("RegistrarDbListener:error");
}
virtual void onInvalid() {
BAD("RegistrarDbListener:invalid");
}
virtual void onContactUpdated(const std::shared_ptr<ExtendedContact> &ec) {
}
};
SofiaHome home;
void checkExpireHandling() {
check("resolve expire1", ExtendedContact::resolveExpire(NULL, 5), 5);
check("resolve expire2", ExtendedContact::resolveExpire(NULL, -1), -1);
check("resolve expire3", ExtendedContact::resolveExpire("5", 6), 5);
check("resolve expire4", ExtendedContact::resolveExpire("5", -1), 5);
}
static sip_contact_t *uid_ct(const char *urlparams, const char *ctparams) {
return sip_contact_format(home.h, "<%s%s>%s", "sip:localhost:12345", urlparams, ctparams);
}
void checkUniqueIdExtraction() {
#define UID_PARAM theparam
string theparam = "UID_PARAM";
check("+sip.instance in ct param", Record::extractUniqueId(uid_ct("", ";+sip.instance=UID_PARAM")), theparam);
check("+sip.instance in url param", Record::extractUniqueId(uid_ct(";+sip.instance=UID_PARAM", "")), theparam);
check("line in ct param", Record::extractUniqueId(uid_ct("", ";line=UID_PARAM")), theparam);
check("line url param", Record::extractUniqueId(uid_ct(";line=UID_PARAM", "")), theparam);
}
int main(int argc, char **argv) {
init_tests();
checkExpireHandling();
checkUniqueIdExtraction();
int expire_delta = 1000;
list<string> paths{"path1", "path2", "path3"};
string contactid{"ip:5223"};
string callid{"callid"};
string line{"line"};
string contact = "sip:" + contactid + ";line=" + line;
string contactWithChev = "<" + contact + ">";
uint32_t cseq = 123456;
float quality = 1;
bool alias = false;
const url_t *from = url_make(home.h, "sip:guillaume@bc");
ExtendedContactCommon ecc(contactid.c_str(), paths, callid.c_str(), line.c_str());
sip_contact_t *sip_contact =
sip_contact_format(home.h, "<%s>;q=%f;expires=%d", contact.c_str(), quality, expire_delta);
sip_path_t *sip_path = path_fromstl(home.h, paths);
sip_accept_t *accept = NULL;
RegistrarDbInternal registrar("preferred_ip");
RegistrarDb::BindParameters params(
RegistrarDb::BindParameters::SipParams(from, sip_contact, callid.c_str(), cseq, sip_path, accept), 55555,
alias);
auto listener = make_shared<MyListener>(params);
registrar.bind(params, listener);
registrar.clearAll();
cout << "success" << endl;
return 0;
}
<commit_msg>Fixed binder.cc compil<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "tool_utils.hh"
#include "../registrardb-internal.hh"
#include "../registrardb.hh"
using namespace std;
struct MyListener : public ContactUpdateListener {
virtual void onRecordFound(Record *r) {
// cout << "record found : ";
// r->print(cout);
// cout << endl;
auto ecc = firstContact(*r);
long rExpire = ecc.mExpireAt - ecc.mUpdatedTime;
check("expire", atol(params.sip.contact->m_expires), rExpire);
}
virtual void onError() {
BAD("RegistrarDbListener:error");
}
virtual void onInvalid() {
BAD("RegistrarDbListener:invalid");
}
virtual void onContactUpdated(const std::shared_ptr<ExtendedContact> &ec) {
}
};
SofiaHome home;
void checkExpireHandling() {
check("resolve expire1", ExtendedContact::resolveExpire(NULL, 5), 5);
check("resolve expire2", ExtendedContact::resolveExpire(NULL, -1), -1);
check("resolve expire3", ExtendedContact::resolveExpire("5", 6), 5);
check("resolve expire4", ExtendedContact::resolveExpire("5", -1), 5);
}
static sip_contact_t *uid_ct(const char *urlparams, const char *ctparams) {
return sip_contact_format(home.h, "<%s%s>%s", "sip:localhost:12345", urlparams, ctparams);
}
void checkUniqueIdExtraction() {
#define UID_PARAM theparam
string theparam = "UID_PARAM";
check("+sip.instance in ct param", Record::extractUniqueId(uid_ct("", ";+sip.instance=UID_PARAM")), theparam);
check("+sip.instance in url param", Record::extractUniqueId(uid_ct(";+sip.instance=UID_PARAM", "")), theparam);
check("line in ct param", Record::extractUniqueId(uid_ct("", ";line=UID_PARAM")), theparam);
check("line url param", Record::extractUniqueId(uid_ct(";line=UID_PARAM", "")), theparam);
}
int main(int argc, char **argv) {
init_tests();
checkExpireHandling();
checkUniqueIdExtraction();
int expire_delta = 1000;
list<string> paths{"path1", "path2", "path3"};
string contactid{"ip:5223"};
string callid{"callid"};
string line{"line"};
string contact = "sip:" + contactid + ";line=" + line;
string contactWithChev = "<" + contact + ">";
uint32_t cseq = 123456;
float quality = 1;
bool alias = false;
const url_t *from = url_make(home.h, "sip:guillaume@bc");
ExtendedContactCommon ecc(contactid.c_str(), paths, callid.c_str(), line.c_str());
sip_contact_t *sip_contact =
sip_contact_format(home.h, "<%s>;q=%f;expires=%d", contact.c_str(), quality, expire_delta);
sip_path_t *sip_path = path_fromstl(home.h, paths);
sip_accept_t *accept = NULL;
RegistrarDbInternal registrar("preferred_ip");
RegistrarDb::BindParameters params(
RegistrarDb::BindParameters::SipParams(from, sip_contact, callid.c_str(), cseq, sip_path, accept), 55555,
alias);
auto listener = make_shared<MyListener>(params);
registrar.bind(params, listener);
registrar.clearAll();
cout << "success" << endl;
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2007, 2008, 2009 libmv authors.
//
// 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 <algorithm>
#include <string>
#include "libmv/base/vector.h"
#include "libmv/correspondence/klt.h"
#include "libmv/image/image.h"
#include "libmv/image/image_io.h"
#include "libmv/image/image_drawing.h"
#include "libmv/image/surf.h"
#include "libmv/image/surf_descriptor.h"
#include "libmv/tools/tool.h"
using namespace libmv;
using namespace std;
void DrawSurfFeatures( Array3Df & im, const libmv::vector<libmv::SurfFeature> & feat);
int main(int argc, char **argv) {
libmv::Init("track a sequence", &argc, &argv);
if (argc != 2) {
LOG(ERROR) << "Missing an image.";
return 1;
}
const string filename = argv[1];
Array3Df image;
if (!ReadPnm(filename.c_str(), &image)) {
LOG(FATAL) << "Failed loading image: " << filename;
return 0;
}
// TODO(pmoulon) Assert that the image value is within [0.f;255.f]
//for(int j=0; j < image.Height(); ++j)
//for(int i=0; i < image.Width(); ++i)
// image(j,i) *=255;
libmv::vector<libmv::SurfFeature> features;
libmv::SurfFeatures(image, 4, 4, &features);
DrawSurfFeatures(image, features);
WritePnm(image, "SurfOutput.pnm");
return 0;
}
void DrawSurfFeatures( Array3Df & im, const libmv::vector<libmv::SurfFeature> & feat)
{
std::cout << feat.size() << " Detected points " <<std::endl;
for(int i=0; i<feat.size(); ++i)
{
const libmv::SurfFeature & feature = feat[i];
const int x = feature.x();
const int y = feature.y();
const float scale = 2*feature.scale;
//std::cout << i << " " << x << " " << y << " " << feature.getScale() <<std::endl;
DrawCircle(x, y, scale, (unsigned char)255, &im);
const float angle = feature.orientation;
DrawLine(x, y, x + scale * cos(angle), y + scale*sin(angle),
(unsigned char) 255, &im);
}
}
<commit_msg>- Add usage function and add ability to configure the output image via command line.<commit_after>// Copyright (c) 2007, 2008, 2009 libmv authors.
//
// 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 <algorithm>
#include <string>
#include "libmv/base/vector.h"
#include "libmv/correspondence/klt.h"
#include "libmv/image/image.h"
#include "libmv/image/image_io.h"
#include "libmv/image/image_drawing.h"
#include "libmv/image/surf.h"
#include "libmv/image/surf_descriptor.h"
#include "libmv/tools/tool.h"
using namespace libmv;
using namespace std;
void usage() {
LOG(ERROR) << " interest_points ImageNameIn.pgm ImageNameOut.pgm " <<std::endl
<< " ImageNameIn.pgm : the input image on which surf features will be extrated, " << std::endl
<< " ImageNameOut.pgm : the surf keypoints will be displayed on it. " << std::endl
<< " INFO : work with pgm image only." << std::endl;
}
void DrawSurfFeatures( Array3Df & im, const libmv::vector<libmv::SurfFeature> & feat);
int main(int argc, char **argv) {
libmv::Init("Extract surf feature from an image", &argc, &argv);
if (argc != 3 || !(GetFormat(argv[1])==Pnm && GetFormat(argv[2])==Pnm)) {
usage();
LOG(ERROR) << "Missing parameters or errors in the command line.";
return 1;
}
// Parse input parameter
const string sImageIn = argv[1];
const string sImageOut = argv[2];
Array3Du imageIn;
if (!ReadPnm(sImageIn.c_str(), &imageIn)) {
LOG(FATAL) << "Failed loading image: " << sImageIn;
return 0;
}
Array3Df image;
ByteArrayToScaledFloatArray(imageIn, &image);
// TODO(pmoulon) Assert that the image value is within [0.f;255.f]
for(int j=0; j < image.Height(); ++j)
for(int i=0; i < image.Width(); ++i)
image(j,i) *=255;
libmv::vector<libmv::SurfFeature> features;
libmv::SurfFeatures(image, 4, 4, &features);
DrawSurfFeatures(image, features);
if (!WritePnm(image, sImageOut.c_str())) {
LOG(FATAL) << "Failed saving output image: " << sImageOut;
}
return 0;
}
void DrawSurfFeatures( Array3Df & im, const libmv::vector<libmv::SurfFeature> & feat)
{
std::cout << feat.size() << " Detected points " <<std::endl;
for (int i = 0; i < feat.size(); ++i)
{
const libmv::SurfFeature & feature = feat[i];
const int x = feature.x();
const int y = feature.y();
const float scale = 2*feature.scale;
//std::cout << i << " " << x << " " << y << " " << feature.getScale() <<std::endl;
DrawCircle(x, y, scale, (unsigned char)255, &im);
const float angle = feature.orientation;
DrawLine(x, y, x + scale * cos(angle), y + scale*sin(angle),
(unsigned char) 255, &im);
}
}
<|endoftext|>
|
<commit_before>#include "include/amici_interface_cpp.h"
#include <include/edata_accessors.h>
#include <include/udata_accessors.h>
#include <include/rdata_accessors.h>
#include <include/tdata_accessors.h>
#include <cstring>
/**
* @ brief initialise matrix and attach to the field
* @ param FIELD name of the field to which the matrix will be attached
* @ param D1 number of rows in the matrix
* @ param D2 number of columns in the matrix
*/
#define initField2(FIELD,D1,D2) \
double *mx ## FIELD; \
mx ## FIELD = new double[D1 * D2](); \
FIELD ## data = mx ## FIELD;
/**
* @ brief initialise 3D tensor and attach to the field
* @ param FIELD name of the field to which the tensor will be attached
* @ param D1 number of rows in the tensor
* @ param D2 number of columns in the tensor
* @ param D3 number of elements in the third dimension of the tensor
*/
#define initField3(FIELD,D1,D2,D3) \
double *mx ## FIELD; \
mx ## FIELD = new double[D1 * D2 * D3](); \
FIELD ## data = mx ## FIELD;
/**
* @ brief initialise 4D tensor and attach to the field
* @ param FIELD name of the field to which the tensor will be attached
* @ param D1 number of rows in the tensor
* @ param D2 number of columns in the tensor
* @ param D3 number of elements in the third dimension of the tensor
* @ param D4 number of elements in the fourth dimension of the tensor
*/
#define initField4(FIELD,D1,D2,D3,D4) \
double *mx ## FIELD; \
mx ## FIELD = new double[D1 * D2 * D3 * D4](); \
FIELD ## data = mx ## FIELD;
void initUserDataFields(UserData *udata, ReturnData *rdata) {
initField2(llh,1,1);
initField2(chi2,1,1);
double *mxts = new double[nt]();
tsdata = mxts;
initField2(numsteps,nt,1);
initField2(numrhsevals,nt,1);
initField2(order,nt,1);
if(sensi >= AMI_SENSI_ORDER_FIRST){
initField2(numstepsS,nt,1);
initField2(numrhsevalsS,nt,1);
}
if((nz>0) & (ne>0)){
initField2(z,nmaxevent,nz);
initField2(rz,nmaxevent,nz);
initField2(sigmaz,nmaxevent,nz);
}
if(nx>0) {
initField2(x,nt,nx);
initField2(xdot,1,nx);
initField2(J,nx,nx);
}
if(ny>0) {
initField2(y,nt,ny);
initField2(sigmay,nt,ny);
if (sensi_meth == AMI_SENSI_SS) {
initField2(dydp,ny,nplist);
initField2(dydx,ny,nx);
initField2(dxdotdp,nx,nplist);
}
}
if(sensi >= AMI_SENSI_ORDER_FIRST) {
initField2(sllh,nplist,1);
if (sensi_meth == AMI_SENSI_FSA) {
initField3(sx,nt,nx,nplist);
if(ny>0) {
initField3(sy,nt,ny,nplist);
initField3(ssigmay,nt,ny,nplist);
}
if((nz>0) & (ne>0)){
initField3(srz,nmaxevent,nz,nplist);
if(sensi >= AMI_SENSI_ORDER_SECOND){
initField4(s2rz,nmaxevent,nz,nplist,nplist);
}
initField3(sz,nmaxevent,nz,nplist);
initField3(ssigmaz,nmaxevent,nz,nplist);
}
}
if (sensi_meth == AMI_SENSI_ASA) {
if(ny>0) {
initField3(ssigmay,nt,ny,nplist);
}
if((nz>0) & (ne>0)){
initField3(ssigmaz,nmaxevent,nz,nplist);
}
}
if(sensi >= AMI_SENSI_ORDER_SECOND) {
initField2(s2llh,ng-1,nplist);
}
}
}
ReturnData *initReturnData(UserData *udata, int *pstatus) {
/**
* initReturnData initialises a ReturnData struct
*
* @param[in] udata pointer to the user data struct @type UserData
* @param[out] pstatus flag indicating success of execution @type *int
* @return rdata initialized return data struct @type ReturnData
*/
ReturnData *rdata; /* returned rdata struct */
/* Return rdata structure */
rdata = new ReturnData();
if (rdata == NULL)
return(NULL);
memset(rdata, 0, sizeof(*rdata));
double dblstatus;
initUserDataFields(udata, rdata);
*pstatus = (int) dblstatus;
return(rdata);
}
ReturnData *getSimulationResults(UserData *udata, ExpData *edata, int *pstatus) {
/**
* getSimulationResults runs the forward an backwards simulation and returns results in a ReturnData struct
*
* @param[in] udata pointer to the user data struct @type UserData
* @param[in] edata pointer to the experimental data struct @type ExpData
* @param[out] pstatus flag indicating success of execution @type *int
* @return rdata data struct with simulation results @type ReturnData
*/
double *originalParams = 0;
if(udata->am_pscale != AMI_SCALING_NONE) {
originalParams = (double *) malloc(sizeof(double) * np);
memcpy(originalParams, p, sizeof(double) * np);
unscaleParameters(udata);
}
int iroot = 0;
booleantype setupBdone = false;
*pstatus = 0;
int problem;
ReturnData *rdata;
TempData *tdata = new TempData();
void *ami_mem = 0; /* pointer to cvodes memory block */
if (tdata == NULL) goto freturn;
if (nx>0) {
ami_mem = setupAMI(pstatus, udata, tdata);
if (ami_mem == NULL) goto freturn;
}
rdata = initReturnData(udata, pstatus);
if (rdata == NULL) goto freturn;
*pstatus = 0;
problem = workForwardProblem(udata, tdata, rdata, edata, pstatus, ami_mem, &iroot);
if(problem)
goto freturn;
problem = workBackwardProblem(udata, tdata, rdata, edata, pstatus, ami_mem, &iroot, &setupBdone);
if(problem)
goto freturn;
applyChainRuleFactorToSimulationResults(udata, rdata, edata);
freturn:
freeTempDataAmiMem(udata, tdata, ami_mem, setupBdone, *pstatus);
if(originalParams) {
memcpy(p, originalParams, sizeof(double) * np);
free(originalParams);
}
return rdata;
}
<commit_msg>Cleanup initField code; do not need mx* variables for non-matlab<commit_after>#include "include/amici_interface_cpp.h"
#include <include/edata_accessors.h>
#include <include/udata_accessors.h>
#include <include/rdata_accessors.h>
#include <include/tdata_accessors.h>
#include <cstring>
/**
* @ brief initialise matrix and attach to the field
* @ param FIELD name of the field to which the matrix will be attached
* @ param D1 number of rows in the matrix
* @ param D2 number of columns in the matrix
*/
#define initField2(FIELD,D1,D2) \
FIELD ## data = new double[D1 * D2]();
/**
* @ brief initialise 3D tensor and attach to the field
* @ param FIELD name of the field to which the tensor will be attached
* @ param D1 number of rows in the tensor
* @ param D2 number of columns in the tensor
* @ param D3 number of elements in the third dimension of the tensor
*/
#define initField3(FIELD,D1,D2,D3) \
FIELD ## data = new double[D1 * D2 * D3]();
/**
* @ brief initialise 4D tensor and attach to the field
* @ param FIELD name of the field to which the tensor will be attached
* @ param D1 number of rows in the tensor
* @ param D2 number of columns in the tensor
* @ param D3 number of elements in the third dimension of the tensor
* @ param D4 number of elements in the fourth dimension of the tensor
*/
#define initField4(FIELD,D1,D2,D3,D4) \
FIELD ## data = new double[D1 * D2 * D3 * D4]();
void initUserDataFields(UserData *udata, ReturnData *rdata) {
initField2(llh,1,1);
initField2(chi2,1,1);
tsdata = new double[nt]();
initField2(numsteps,nt,1);
initField2(numrhsevals,nt,1);
initField2(order,nt,1);
if(sensi >= AMI_SENSI_ORDER_FIRST){
initField2(numstepsS,nt,1);
initField2(numrhsevalsS,nt,1);
}
if((nz>0) & (ne>0)){
initField2(z,nmaxevent,nz);
initField2(rz,nmaxevent,nz);
initField2(sigmaz,nmaxevent,nz);
}
if(nx>0) {
initField2(x,nt,nx);
initField2(xdot,1,nx);
initField2(J,nx,nx);
}
if(ny>0) {
initField2(y,nt,ny);
initField2(sigmay,nt,ny);
if (sensi_meth == AMI_SENSI_SS) {
initField2(dydp,ny,nplist);
initField2(dydx,ny,nx);
initField2(dxdotdp,nx,nplist);
}
}
if(sensi >= AMI_SENSI_ORDER_FIRST) {
initField2(sllh,nplist,1);
if (sensi_meth == AMI_SENSI_FSA) {
initField3(sx,nt,nx,nplist);
if(ny>0) {
initField3(sy,nt,ny,nplist);
initField3(ssigmay,nt,ny,nplist);
}
if((nz>0) & (ne>0)){
initField3(srz,nmaxevent,nz,nplist);
if(sensi >= AMI_SENSI_ORDER_SECOND){
initField4(s2rz,nmaxevent,nz,nplist,nplist);
}
initField3(sz,nmaxevent,nz,nplist);
initField3(ssigmaz,nmaxevent,nz,nplist);
}
}
if (sensi_meth == AMI_SENSI_ASA) {
if(ny>0) {
initField3(ssigmay,nt,ny,nplist);
}
if((nz>0) & (ne>0)){
initField3(ssigmaz,nmaxevent,nz,nplist);
}
}
if(sensi >= AMI_SENSI_ORDER_SECOND) {
initField2(s2llh,ng-1,nplist);
}
}
}
ReturnData *initReturnData(UserData *udata, int *pstatus) {
/**
* initReturnData initialises a ReturnData struct
*
* @param[in] udata pointer to the user data struct @type UserData
* @param[out] pstatus flag indicating success of execution @type *int
* @return rdata initialized return data struct @type ReturnData
*/
ReturnData *rdata; /* returned rdata struct */
/* Return rdata structure */
rdata = new ReturnData();
if (rdata == NULL)
return(NULL);
memset(rdata, 0, sizeof(*rdata));
double dblstatus;
initUserDataFields(udata, rdata);
*pstatus = (int) dblstatus;
return(rdata);
}
ReturnData *getSimulationResults(UserData *udata, ExpData *edata, int *pstatus) {
/**
* getSimulationResults runs the forward an backwards simulation and returns results in a ReturnData struct
*
* @param[in] udata pointer to the user data struct @type UserData
* @param[in] edata pointer to the experimental data struct @type ExpData
* @param[out] pstatus flag indicating success of execution @type *int
* @return rdata data struct with simulation results @type ReturnData
*/
double *originalParams = 0;
if(udata->am_pscale != AMI_SCALING_NONE) {
originalParams = (double *) malloc(sizeof(double) * np);
memcpy(originalParams, p, sizeof(double) * np);
unscaleParameters(udata);
}
int iroot = 0;
booleantype setupBdone = false;
*pstatus = 0;
int problem;
ReturnData *rdata;
TempData *tdata = new TempData();
void *ami_mem = 0; /* pointer to cvodes memory block */
if (tdata == NULL) goto freturn;
if (nx>0) {
ami_mem = setupAMI(pstatus, udata, tdata);
if (ami_mem == NULL) goto freturn;
}
rdata = initReturnData(udata, pstatus);
if (rdata == NULL) goto freturn;
*pstatus = 0;
problem = workForwardProblem(udata, tdata, rdata, edata, pstatus, ami_mem, &iroot);
if(problem)
goto freturn;
problem = workBackwardProblem(udata, tdata, rdata, edata, pstatus, ami_mem, &iroot, &setupBdone);
if(problem)
goto freturn;
applyChainRuleFactorToSimulationResults(udata, rdata, edata);
freturn:
freeTempDataAmiMem(udata, tdata, ami_mem, setupBdone, *pstatus);
if(originalParams) {
memcpy(p, originalParams, sizeof(double) * np);
free(originalParams);
}
return rdata;
}
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2007 by carm *
* carm@localhost *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <QtGui>
#include "QProjectM_MainWindow.hpp"
#include "QProjectMFileDialog.hpp"
#include <QTextStream>
#include <QCloseEvent>
#include <QFileDialog>
#include "QPlaylistModel.hpp"
QProjectM_MainWindow::QProjectM_MainWindow(const std::string & config_file)
:m_QProjectMFileDialog(new QProjectMFileDialog(this))
{
ui.setupUi(this);
m_QProjectMWidget = new QProjectMWidget(config_file, this);
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), m_QProjectMWidget, SLOT(updateGL()));
connect(ui.lockPresetCheckBox, SIGNAL(stateChanged(int)),
m_QProjectMWidget, SLOT(setPresetLock(int)));
connect(ui.clearPresetList_PushButton, SIGNAL(pressed()),
this, SLOT(clearPlaylist()));
connect(m_QProjectMWidget, SIGNAL(projectM_Initialized()), this, SLOT(postProjectM_Initialize()));
m_QProjectMWidget->makeCurrent();
m_QProjectMWidget->setFocus();
m_timer->start(0);
setCentralWidget(m_QProjectMWidget);
createActions();
createMenus();
createToolBars();
createStatusBar();
readSettings();
ui.presetPlayListDockWidget->hide();
}
void QProjectM_MainWindow::clearPlaylist() {
playlistModel->clear();
for (QHash<QString, PlaylistItemVector*>::iterator pos = historyHash.begin(); pos != historyHash.end(); ++pos) {
delete(pos.value());
}
historyHash.clear();
previousFilter = QString();
ui.presetSearchBarLineEdit->clear();
}
QProjectM * QProjectM_MainWindow::getQProjectM() {
return m_QProjectMWidget->getQProjectM();
}
void QProjectM_MainWindow::updatePlaylistSelection(bool hardCut, unsigned int index) {
if (hardCut)
statusBar()->showMessage(tr("*** Hard cut ***") , 2000);
else
statusBar()->showMessage(tr("*** Soft cut ***") , 2000);
//ui.tableView->selectRow(index);
}
void QProjectM_MainWindow::selectPlaylistItem(const QModelIndex & index) {
getQProjectM()->selectPreset(index.row());
}
void QProjectM_MainWindow::postProjectM_Initialize() {
playlistModel = new QPlaylistModel(*m_QProjectMWidget->getQProjectM(),this);
refreshPlaylist();
ui.tableView->setModel(playlistModel);
connect(m_QProjectMWidget->getQProjectM(), SIGNAL(presetSwitchedSignal(bool,unsigned int)), this, SLOT(updatePlaylistSelection(bool,unsigned int)));
connect(ui.presetSearchBarLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(updateFilteredPlaylist(const QString&)));
connect(ui.tableView, SIGNAL(activated(const QModelIndex &)),
this, SLOT(selectPlaylistItem(const QModelIndex &)));
connect(ui.tableView, SIGNAL(clicked(const QModelIndex &)),
this, SLOT(changeRating(const QModelIndex &)));
}
void QProjectM_MainWindow::changeRating(const QModelIndex & index) {
if (index.column() == 0)
return;
playlistModel->setData
(index, (playlistModel->data(index, QPlaylistModel::RatingRole).toInt()+1) % 6, QPlaylistModel::RatingRole);
}
void QProjectM_MainWindow::keyReleaseEvent ( QKeyEvent * e ) {
QModelIndex modelIndex;
switch (e->key()) {
case Qt::Key_L:
if (ui.presetSearchBarLineEdit->hasFocus())
return;
if (ui.lockPresetCheckBox->checkState() == Qt::Checked)
ui.lockPresetCheckBox->setCheckState(Qt::Unchecked);
else
ui.lockPresetCheckBox->setCheckState(Qt::Checked);
// the projectM widget handles the actual lock
//e->ignore();
//m_QProjectMWidget->keyReleaseEvent(e);
return;
case Qt::Key_F1:
//emit(keyPressed m_QProjectMWidget,
case Qt::Key_F:
if (ui.presetSearchBarLineEdit->hasFocus())
return;
this->setWindowState(this->windowState() ^ Qt::WindowFullScreen);
return;
case Qt::Key_M:
if (ui.presetSearchBarLineEdit->hasFocus())
return;
if (ui.presetPlayListDockWidget->isVisible()) {
ui.presetPlayListDockWidget->hide();
} else
ui.presetPlayListDockWidget->show();
if (menuBar()->isVisible()) {
menuBar()->hide();
m_QProjectMWidget->setFocus();
}
else {
menuBar()->show();
}
if (statusBar()->isVisible()) {
statusBar()->hide();
}
else {
statusBar()->show();
}
return;
case Qt::Key_R:
if (ui.presetSearchBarLineEdit->hasFocus())
return;
//modelIndex.selectRandom()
//modelIndex = QModelIndex(0,0,0);
//selectPlaylistItem(modelIndex);
//updatePlaylistSelection(true, modelIndex.row());
return;
default:
//m_QProjectMWidget->keyReleaseEvent(e);
break;//e->ignore();
}
}
void QProjectM_MainWindow::closeEvent(QCloseEvent *event)
{
}
void QProjectM_MainWindow::open()
{
if ( m_QProjectMFileDialog->exec()) {
const QStringList & files = m_QProjectMFileDialog->selectedFiles();
for (QStringList::const_iterator pos = files.begin();
pos != files.end(); ++pos) {
if (*pos != "")
loadFile(*pos);
}
PlaylistItemVector * playlistItems = historyHash.value(QString());
for (QHash<QString, PlaylistItemVector*>::iterator pos = historyHash.begin(); pos != historyHash.end(); ++pos) {
if (pos.key() != QString())
delete(pos.value());
}
historyHash.clear();
historyHash.insert(QString(), playlistItems);
updateFilteredPlaylist(previousFilter);
//for (PlaylistItemVector::iterator pos = playlistItems->begin(); pos != playlistItems->end(); ++pos) {
// playlistModel->appendRow(pos->url, pos->name, pos->rating);
//}
}
//playlistModel->setHeaderData(0, Qt::Horizontal, tr("Preset"));//, Qt::DisplayRole);
}
//void QAbstractItemView::clicked ( const QModelIndex & index ) [signal]
void QProjectM_MainWindow::refreshPlaylist() {
PlaylistItemVector * playlistItems = new PlaylistItemVector();
for (int i = 0; i < playlistModel->rowCount();i++) {
QModelIndex index = playlistModel->index(i, 0);
const QString & name = playlistModel->data(index, Qt::DisplayRole).toString();
const QString & url = playlistModel->data(index, QPlaylistModel::URLInfoRole).toString();
playlistItems->push_back(PlaylistItemMetaData(url, name, 3));
}
historyHash.insert(QString(), playlistItems);
QHeaderView * hHeader = new QHeaderView(Qt::Horizontal, this);
QHeaderView * vHeader = new QHeaderView(Qt::Vertical, this);
hHeader->setClickable(false);
hHeader->setSortIndicatorShown(false);
//hHeader->setSortIndicator(1, Qt::AscendingOrder);
hHeader->setStretchLastSection(false);
ui.tableView->setVerticalHeader(vHeader);
ui.tableView->setHorizontalHeader(hHeader);
hHeader->resizeSection(0, 200);
hHeader->setResizeMode(0, QHeaderView::Stretch);
hHeader->setResizeMode(1, QHeaderView::Fixed);
hHeader->resizeSection(1, 25);
// playlistModel->setHeaderData(0, Qt::Horizontal, tr("Preset"));//, Qt::DisplayRole);
vHeader->hide();
// playlistModel->setHeaderData(0, Qt::Horizontal, 200, Qt::SizeHintRole);
//playlistModel->setHeaderData(1, Qt::Horizontal, tr("Rating"));//, Qt::DisplayRole);
//playlistModel->setHeaderData(2, Qt::Horizontal, tr("Preset"));//, Qt::DisplayRole);
}
void QProjectM_MainWindow::about()
{
QMessageBox::about(this, tr("About QProjectM and ProjectM"),
tr("<b>QProjectM</b> provides useful gui extensions to the projectM core library. For problems please email Carmelo Piccione (carmelo.piccione@gmail.com). \n<b>projectM</b> is an advanced music visualizer based on Geiss's Milkdrop. For more info visit us at <a href=\"http://projectm.sf.net\">projectm.sf.net</a>."));
}
void QProjectM_MainWindow::createActions()
{
connect(ui.actionExit, SIGNAL(triggered()), this, SLOT(close()));
connect(ui.actionAddPresets, SIGNAL(triggered()), this, SLOT(open()));
connect(ui.actionAbout_qprojectM, SIGNAL(triggered()), this, SLOT(about()));
//connect(ui.actionAbout_Qt, SIGNAL(triggered()), this, SLOT(aboutQt()));
}
void QProjectM_MainWindow::createMenus()
{
ui.menuBar->hide();
}
void QProjectM_MainWindow::createToolBars()
{
}
void QProjectM_MainWindow::createStatusBar()
{
statusBar()->hide();
statusBar()->showMessage(tr("Welcome to qprojectM!"));
}
void QProjectM_MainWindow::readSettings()
{
QSettings settings("Trolltech", "QProjectM");
QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
QSize size = settings.value("size", QSize(1000, 600)).toSize();
resize(size);
move(pos);
}
void QProjectM_MainWindow::writeSettings()
{
QSettings settings("Trolltech", "QProjectM");
settings.setValue("pos", pos());
settings.setValue("size", size());
}
void QProjectM_MainWindow::loadFile(const QString &fileName, int rating)
{
const QString & name = strippedName(fileName);
PlaylistItemVector * playlistItems = historyHash.value(QString());
playlistItems->push_back(PlaylistItemMetaData(fileName, name, rating));
}
QString QProjectM_MainWindow::strippedName(const QString &fullFileName)
{
return QFileInfo(fullFileName).fileName();
}
void QProjectM_MainWindow::updateFilteredPlaylist(const QString & text) {
const QString filter = text.toLower();
playlistModel->clear();
if (historyHash.contains(filter)) {
const PlaylistItemVector & playlistItems = *historyHash.value(filter);
for (PlaylistItemVector::const_iterator pos = playlistItems.begin(); pos != playlistItems.end();++pos) {
playlistModel->appendRow(pos->url, pos->name, pos->rating);
}
} else {
const PlaylistItemVector & playlistItems = *historyHash.value(QString());
PlaylistItemVector * playlistItems2 = new PlaylistItemVector();
for (PlaylistItemVector::const_iterator pos = playlistItems.begin(); pos != playlistItems.end();++pos) {
if ((pos->name).contains(filter, Qt::CaseInsensitive)) {
playlistModel->appendRow(pos->url, pos->name, pos->rating);
playlistItems2->push_back(*pos);
}
}
historyHash.insert(filter, playlistItems2);
}
previousFilter = filter;
#if 0
if (!(filter.substring(0, filter.length()-1) == previousFilter)) {
PlaylistItemVector & playlistItems = *exclusionHash.value(previousFilter);
while (!playlistItems.empty()) {
const StringPair & pair = playlistItems.last();
/// @bug need to do **ordered** insert, or something faster (index reference book keeping?)
playlistModel->appendRow(pair.first, pair.second);
playlistItems.pop_back();
}
exclusionHash.remove(previousFilter);
delete(&playlistItems);
} else {
assert(filter.length() != previousFilter.length());
PlaylistItemVector * playlistItems = new PlaylistItemVector();
exclusionHash.insert(filter, playlistItems);
for (int i = 0; i < playlistModel->rowCount(); i++) {
QModelIndex index = playlistModel->index(i, 0);
const QString & name = playlistModel->data(index, Qt::DisplayRole).toString();
const QString & url = playlistModel->data(index, QPlaylistModel::URLInfoRole).toString();
if (!name.contains(filter, Qt::CaseInsensitive)) {
playlistItems->push_back(StringPair(url, name));
assert (i < playlistModel->rowCount());
assert (i >= 0);
playlistModel->removeRow(i);
i--;
}
}
}
#endif
}
<commit_msg>serious bug fix when clearing the playlist. search seems pretty solid now<commit_after>/***************************************************************************
* Copyright (C) 2007 by carm *
* carm@localhost *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <QtGui>
#include "QProjectM_MainWindow.hpp"
#include "QProjectMFileDialog.hpp"
#include <QTextStream>
#include <QCloseEvent>
#include <QFileDialog>
#include "QPlaylistModel.hpp"
QProjectM_MainWindow::QProjectM_MainWindow(const std::string & config_file)
:m_QProjectMFileDialog(new QProjectMFileDialog(this))
{
ui.setupUi(this);
m_QProjectMWidget = new QProjectMWidget(config_file, this);
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), m_QProjectMWidget, SLOT(updateGL()));
connect(ui.lockPresetCheckBox, SIGNAL(stateChanged(int)),
m_QProjectMWidget, SLOT(setPresetLock(int)));
connect(ui.clearPresetList_PushButton, SIGNAL(pressed()),
this, SLOT(clearPlaylist()));
connect(m_QProjectMWidget, SIGNAL(projectM_Initialized()), this, SLOT(postProjectM_Initialize()));
m_QProjectMWidget->makeCurrent();
m_QProjectMWidget->setFocus();
m_timer->start(0);
setCentralWidget(m_QProjectMWidget);
createActions();
createMenus();
createToolBars();
createStatusBar();
readSettings();
ui.presetPlayListDockWidget->hide();
}
void QProjectM_MainWindow::clearPlaylist() {
playlistModel->clear();
for (QHash<QString, PlaylistItemVector*>::iterator pos = historyHash.begin(); pos != historyHash.end(); ++pos) {
delete(pos.value());
}
historyHash.clear();
historyHash.insert(QString(), new PlaylistItemVector);
previousFilter = QString();
ui.presetSearchBarLineEdit->clear();
}
QProjectM * QProjectM_MainWindow::getQProjectM() {
return m_QProjectMWidget->getQProjectM();
}
void QProjectM_MainWindow::updatePlaylistSelection(bool hardCut, unsigned int index) {
if (hardCut)
statusBar()->showMessage(tr("*** Hard cut ***") , 2000);
else
statusBar()->showMessage(tr("*** Soft cut ***") , 2000);
//ui.tableView->selectRow(index);
}
void QProjectM_MainWindow::selectPlaylistItem(const QModelIndex & index) {
getQProjectM()->selectPreset(index.row());
}
void QProjectM_MainWindow::postProjectM_Initialize() {
playlistModel = new QPlaylistModel(*m_QProjectMWidget->getQProjectM(),this);
refreshPlaylist();
ui.tableView->setModel(playlistModel);
connect(m_QProjectMWidget->getQProjectM(), SIGNAL(presetSwitchedSignal(bool,unsigned int)), this, SLOT(updatePlaylistSelection(bool,unsigned int)));
connect(ui.presetSearchBarLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(updateFilteredPlaylist(const QString&)));
connect(ui.tableView, SIGNAL(activated(const QModelIndex &)),
this, SLOT(selectPlaylistItem(const QModelIndex &)));
connect(ui.tableView, SIGNAL(clicked(const QModelIndex &)),
this, SLOT(changeRating(const QModelIndex &)));
}
void QProjectM_MainWindow::changeRating(const QModelIndex & index) {
if (index.column() == 0)
return;
playlistModel->setData
(index, (playlistModel->data(index, QPlaylistModel::RatingRole).toInt()+1) % 6, QPlaylistModel::RatingRole);
}
void QProjectM_MainWindow::keyReleaseEvent ( QKeyEvent * e ) {
QModelIndex modelIndex;
switch (e->key()) {
case Qt::Key_L:
if (ui.presetSearchBarLineEdit->hasFocus())
return;
if (ui.lockPresetCheckBox->checkState() == Qt::Checked)
ui.lockPresetCheckBox->setCheckState(Qt::Unchecked);
else
ui.lockPresetCheckBox->setCheckState(Qt::Checked);
// the projectM widget handles the actual lock
//e->ignore();
//m_QProjectMWidget->keyReleaseEvent(e);
return;
case Qt::Key_F1:
//emit(keyPressed m_QProjectMWidget,
case Qt::Key_F:
if (ui.presetSearchBarLineEdit->hasFocus())
return;
this->setWindowState(this->windowState() ^ Qt::WindowFullScreen);
return;
case Qt::Key_M:
if (ui.presetSearchBarLineEdit->hasFocus())
return;
if (ui.presetPlayListDockWidget->isVisible()) {
ui.presetPlayListDockWidget->hide();
} else
ui.presetPlayListDockWidget->show();
if (menuBar()->isVisible()) {
menuBar()->hide();
m_QProjectMWidget->setFocus();
}
else {
menuBar()->show();
}
if (statusBar()->isVisible()) {
statusBar()->hide();
}
else {
statusBar()->show();
}
return;
case Qt::Key_R:
if (ui.presetSearchBarLineEdit->hasFocus())
return;
//modelIndex.selectRandom()
//modelIndex = QModelIndex(0,0,0);
//selectPlaylistItem(modelIndex);
//updatePlaylistSelection(true, modelIndex.row());
return;
default:
//m_QProjectMWidget->keyReleaseEvent(e);
break;//e->ignore();
}
}
void QProjectM_MainWindow::closeEvent(QCloseEvent *event)
{
}
void QProjectM_MainWindow::open()
{
if ( m_QProjectMFileDialog->exec()) {
const QStringList & files = m_QProjectMFileDialog->selectedFiles();
for (QStringList::const_iterator pos = files.begin();
pos != files.end(); ++pos) {
if (*pos != "")
loadFile(*pos);
}
PlaylistItemVector * playlistItems = historyHash.value(QString());
for (QHash<QString, PlaylistItemVector*>::iterator pos = historyHash.begin(); pos != historyHash.end(); ++pos) {
if (pos.key() != QString())
delete(pos.value());
}
historyHash.clear();
historyHash.insert(QString(), playlistItems);
updateFilteredPlaylist(previousFilter);
//for (PlaylistItemVector::iterator pos = playlistItems->begin(); pos != playlistItems->end(); ++pos) {
// playlistModel->appendRow(pos->url, pos->name, pos->rating);
//}
}
//playlistModel->setHeaderData(0, Qt::Horizontal, tr("Preset"));//, Qt::DisplayRole);
}
//void QAbstractItemView::clicked ( const QModelIndex & index ) [signal]
void QProjectM_MainWindow::refreshPlaylist() {
PlaylistItemVector * playlistItems = new PlaylistItemVector();
for (int i = 0; i < playlistModel->rowCount();i++) {
QModelIndex index = playlistModel->index(i, 0);
const QString & name = playlistModel->data(index, Qt::DisplayRole).toString();
const QString & url = playlistModel->data(index, QPlaylistModel::URLInfoRole).toString();
playlistItems->push_back(PlaylistItemMetaData(url, name, 3));
}
historyHash.insert(QString(), playlistItems);
QHeaderView * hHeader = new QHeaderView(Qt::Horizontal, this);
QHeaderView * vHeader = new QHeaderView(Qt::Vertical, this);
hHeader->setClickable(false);
hHeader->setSortIndicatorShown(false);
//hHeader->setSortIndicator(1, Qt::AscendingOrder);
hHeader->setStretchLastSection(false);
ui.tableView->setVerticalHeader(vHeader);
ui.tableView->setHorizontalHeader(hHeader);
hHeader->resizeSection(0, 200);
hHeader->setResizeMode(0, QHeaderView::Stretch);
hHeader->setResizeMode(1, QHeaderView::Fixed);
hHeader->resizeSection(1, 25);
// playlistModel->setHeaderData(0, Qt::Horizontal, tr("Preset"));//, Qt::DisplayRole);
vHeader->hide();
// playlistModel->setHeaderData(0, Qt::Horizontal, 200, Qt::SizeHintRole);
//playlistModel->setHeaderData(1, Qt::Horizontal, tr("Rating"));//, Qt::DisplayRole);
//playlistModel->setHeaderData(2, Qt::Horizontal, tr("Preset"));//, Qt::DisplayRole);
}
void QProjectM_MainWindow::about()
{
QMessageBox::about(this, tr("About QProjectM and ProjectM"),
tr("<b>QProjectM</b> provides useful gui extensions to the projectM core library. For problems please email Carmelo Piccione (carmelo.piccione@gmail.com). \n<b>projectM</b> is an advanced music visualizer based on Geiss's Milkdrop. For more info visit us at <a href=\"http://projectm.sf.net\">projectm.sf.net</a>."));
}
void QProjectM_MainWindow::createActions()
{
connect(ui.actionExit, SIGNAL(triggered()), this, SLOT(close()));
connect(ui.actionAddPresets, SIGNAL(triggered()), this, SLOT(open()));
connect(ui.actionAbout_qprojectM, SIGNAL(triggered()), this, SLOT(about()));
//connect(ui.actionAbout_Qt, SIGNAL(triggered()), this, SLOT(aboutQt()));
}
void QProjectM_MainWindow::createMenus()
{
ui.menuBar->hide();
}
void QProjectM_MainWindow::createToolBars()
{
}
void QProjectM_MainWindow::createStatusBar()
{
statusBar()->hide();
statusBar()->showMessage(tr("Welcome to qprojectM!"));
}
void QProjectM_MainWindow::readSettings()
{
QSettings settings("Trolltech", "QProjectM");
QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
QSize size = settings.value("size", QSize(1000, 600)).toSize();
resize(size);
move(pos);
}
void QProjectM_MainWindow::writeSettings()
{
QSettings settings("Trolltech", "QProjectM");
settings.setValue("pos", pos());
settings.setValue("size", size());
}
void QProjectM_MainWindow::loadFile(const QString &fileName, int rating)
{
const QString & name = strippedName(fileName);
PlaylistItemVector * playlistItems = historyHash.value(QString(), 0);
assert (playlistItems != 0);
playlistItems->push_back(PlaylistItemMetaData(fileName, name, rating));
}
QString QProjectM_MainWindow::strippedName(const QString &fullFileName)
{
return QFileInfo(fullFileName).fileName();
}
void QProjectM_MainWindow::updateFilteredPlaylist(const QString & text) {
const QString filter = text.toLower();
playlistModel->clear();
if (historyHash.contains(filter)) {
const PlaylistItemVector & playlistItems = *historyHash.value(filter);
for (PlaylistItemVector::const_iterator pos = playlistItems.begin(); pos != playlistItems.end();++pos) {
playlistModel->appendRow(pos->url, pos->name, pos->rating);
}
} else {
const PlaylistItemVector & playlistItems = *historyHash.value(QString());
PlaylistItemVector * playlistItems2 = new PlaylistItemVector();
for (PlaylistItemVector::const_iterator pos = playlistItems.begin(); pos != playlistItems.end();++pos) {
if ((pos->name).contains(filter, Qt::CaseInsensitive)) {
playlistModel->appendRow(pos->url, pos->name, pos->rating);
playlistItems2->push_back(*pos);
}
}
historyHash.insert(filter, playlistItems2);
}
previousFilter = filter;
#if 0
if (!(filter.substring(0, filter.length()-1) == previousFilter)) {
PlaylistItemVector & playlistItems = *exclusionHash.value(previousFilter);
while (!playlistItems.empty()) {
const StringPair & pair = playlistItems.last();
/// @bug need to do **ordered** insert, or something faster (index reference book keeping?)
playlistModel->appendRow(pair.first, pair.second);
playlistItems.pop_back();
}
exclusionHash.remove(previousFilter);
delete(&playlistItems);
} else {
assert(filter.length() != previousFilter.length());
PlaylistItemVector * playlistItems = new PlaylistItemVector();
exclusionHash.insert(filter, playlistItems);
for (int i = 0; i < playlistModel->rowCount(); i++) {
QModelIndex index = playlistModel->index(i, 0);
const QString & name = playlistModel->data(index, Qt::DisplayRole).toString();
const QString & url = playlistModel->data(index, QPlaylistModel::URLInfoRole).toString();
if (!name.contains(filter, Qt::CaseInsensitive)) {
playlistItems->push_back(StringPair(url, name));
assert (i < playlistModel->rowCount());
assert (i >= 0);
playlistModel->removeRow(i);
i--;
}
}
}
#endif
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQuick module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <private/qquickshadereffectnode_p.h>
#include "qquickshadereffectmesh_p.h"
#include "qquickshadereffect_p.h"
#include <QtQuick/qsgtextureprovider.h>
#include <QtQuick/private/qsgrenderer_p.h>
QT_BEGIN_NAMESPACE
class QQuickCustomMaterialShader : public QSGMaterialShader
{
public:
QQuickCustomMaterialShader(const QQuickShaderEffectMaterialKey &key, const QVector<QByteArray> &attributes);
virtual void deactivate();
virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
virtual char const *const *attributeNames() const;
protected:
friend class QQuickShaderEffectNode;
virtual void compile();
virtual const char *vertexShader() const;
virtual const char *fragmentShader() const;
const QQuickShaderEffectMaterialKey m_key;
QVector<const char *> m_attributeNames;
const QVector<QByteArray> m_attributes;
QString m_log;
bool m_compiled;
QVector<int> m_uniformLocs[QQuickShaderEffectMaterialKey::ShaderTypeCount];
uint m_initialized : 1;
};
QQuickCustomMaterialShader::QQuickCustomMaterialShader(const QQuickShaderEffectMaterialKey &key, const QVector<QByteArray> &attributes)
: m_key(key)
, m_attributes(attributes)
, m_compiled(false)
, m_initialized(false)
{
for (int i = 0; i < attributes.count(); ++i)
m_attributeNames.append(attributes.at(i).constData());
m_attributeNames.append(0);
}
void QQuickCustomMaterialShader::deactivate()
{
QSGMaterialShader::deactivate();
glDisable(GL_CULL_FACE);
}
void QQuickCustomMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
{
typedef QQuickShaderEffectMaterial::UniformData UniformData;
Q_ASSERT(newEffect != 0);
QQuickShaderEffectMaterial *material = static_cast<QQuickShaderEffectMaterial *>(newEffect);
if (!material->m_emittedLogChanged && material->m_node) {
material->m_emittedLogChanged = true;
emit material->m_node->logAndStatusChanged(m_log, m_compiled ? QQuickShaderEffect::Compiled
: QQuickShaderEffect::Error);
}
int textureProviderIndex = 0;
if (!m_initialized) {
for (int shaderType = 0; shaderType < QQuickShaderEffectMaterialKey::ShaderTypeCount; ++shaderType) {
Q_ASSERT(m_uniformLocs[shaderType].isEmpty());
m_uniformLocs[shaderType].reserve(material->uniforms[shaderType].size());
for (int i = 0; i < material->uniforms[shaderType].size(); ++i) {
const UniformData &d = material->uniforms[shaderType].at(i);
QByteArray name = d.name;
if (d.specialType == UniformData::Sampler) {
program()->setUniformValue(d.name.constData(), textureProviderIndex++);
// We don't need to store the sampler uniform locations, since their values
// only need to be set once. Look for the "qt_SubRect_" uniforms instead.
// These locations are used when binding the textures later.
name = "qt_SubRect_" + name;
}
m_uniformLocs[shaderType].append(program()->uniformLocation(name.constData()));
}
}
m_initialized = true;
textureProviderIndex = 0;
}
QOpenGLFunctions *functions = state.context()->functions();
for (int shaderType = 0; shaderType < QQuickShaderEffectMaterialKey::ShaderTypeCount; ++shaderType) {
for (int i = 0; i < material->uniforms[shaderType].size(); ++i) {
const UniformData &d = material->uniforms[shaderType].at(i);
int loc = m_uniformLocs[shaderType].at(i);
if (d.specialType == UniformData::Sampler) {
int idx = textureProviderIndex++;
functions->glActiveTexture(GL_TEXTURE0 + idx);
if (QSGTextureProvider *provider = material->textureProviders.at(idx)) {
if (QSGTexture *texture = provider->texture()) {
if (loc >= 0) {
QRectF r = texture->normalizedTextureSubRect();
program()->setUniformValue(loc, r.x(), r.y(), r.width(), r.height());
} else if (texture->isAtlasTexture()) {
texture = texture->removedFromAtlas();
}
texture->bind();
continue;
}
}
qWarning("ShaderEffect: source or provider missing when binding textures");
glBindTexture(GL_TEXTURE_2D, 0);
} else if (d.specialType == UniformData::Opacity) {
program()->setUniformValue(loc, state.opacity());
} else if (d.specialType == UniformData::Matrix) {
if (state.isMatrixDirty())
program()->setUniformValue(loc, state.combinedMatrix());
} else if (d.specialType == UniformData::None) {
switch (int(d.value.type())) {
case QMetaType::QColor:
program()->setUniformValue(loc, qt_premultiply_color(qvariant_cast<QColor>(d.value)));
break;
case QMetaType::Float:
program()->setUniformValue(loc, qvariant_cast<float>(d.value));
break;
case QMetaType::Double:
program()->setUniformValue(loc, (float) qvariant_cast<double>(d.value));
break;
case QMetaType::QTransform:
program()->setUniformValue(loc, qvariant_cast<QTransform>(d.value));
break;
case QMetaType::Int:
program()->setUniformValue(loc, d.value.toInt());
break;
case QMetaType::Bool:
program()->setUniformValue(loc, GLint(d.value.toBool()));
break;
case QMetaType::QSize:
case QMetaType::QSizeF:
program()->setUniformValue(loc, d.value.toSizeF());
break;
case QMetaType::QPoint:
case QMetaType::QPointF:
program()->setUniformValue(loc, d.value.toPointF());
break;
case QMetaType::QRect:
case QMetaType::QRectF:
{
QRectF r = d.value.toRectF();
program()->setUniformValue(loc, r.x(), r.y(), r.width(), r.height());
}
break;
case QMetaType::QVector3D:
program()->setUniformValue(loc, qvariant_cast<QVector3D>(d.value));
break;
case QMetaType::QVector4D:
program()->setUniformValue(loc, qvariant_cast<QVector4D>(d.value));
break;
case QMetaType::QMatrix4x4:
program()->setUniformValue(loc, qvariant_cast<QMatrix4x4>(d.value));
break;
default:
break;
}
}
}
}
functions->glActiveTexture(GL_TEXTURE0);
const QQuickShaderEffectMaterial *oldMaterial = static_cast<const QQuickShaderEffectMaterial *>(oldEffect);
if (oldEffect == 0 || material->cullMode != oldMaterial->cullMode) {
switch (material->cullMode) {
case QQuickShaderEffectMaterial::FrontFaceCulling:
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
break;
case QQuickShaderEffectMaterial::BackFaceCulling:
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
break;
default:
glDisable(GL_CULL_FACE);
break;
}
}
}
char const *const *QQuickCustomMaterialShader::attributeNames() const
{
return m_attributeNames.constData();
}
void QQuickCustomMaterialShader::compile()
{
Q_ASSERT_X(!program()->isLinked(), "QQuickCustomMaterialShader::compile()", "Compile called multiple times!");
m_log.clear();
m_compiled = true;
if (!program()->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShader())) {
m_log += QLatin1String("*** Vertex shader ***\n");
m_log += program()->log();
m_compiled = false;
}
if (!program()->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShader())) {
m_log += QLatin1String("*** Fragment shader ***\n");
m_log += program()->log();
m_compiled = false;
}
char const *const *attr = attributeNames();
#ifndef QT_NO_DEBUG
int maxVertexAttribs = 0;
glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &maxVertexAttribs);
int attrCount = 0;
while (attrCount < maxVertexAttribs && attr[attrCount])
++attrCount;
if (attr[attrCount]) {
qWarning("List of attribute names is too long.\n"
"Maximum number of attributes on this hardware is %i.\n"
"Vertex shader:\n%s\n"
"Fragment shader:\n%s\n",
maxVertexAttribs, vertexShader(), fragmentShader());
}
#endif
if (m_compiled) {
#ifndef QT_NO_DEBUG
for (int i = 0; i < attrCount; ++i) {
#else
for (int i = 0; attr[i]; ++i) {
#endif
if (*attr[i])
program()->bindAttributeLocation(attr[i], i);
}
m_compiled = program()->link();
m_log += program()->log();
}
static const char fallbackVertexShader[] =
"uniform highp mat4 qt_Matrix;"
"attribute highp vec4 v;"
"void main() { gl_Position = qt_Matrix * v; }";
static const char fallbackFragmentShader[] =
"void main() { gl_FragColor = vec4(1., 0., 1., 1.); }";
if (!m_compiled) {
qWarning("QQuickCustomMaterialShader: Shader compilation failed:");
qWarning() << program()->log();
program()->removeAllShaders();
program()->addShaderFromSourceCode(QOpenGLShader::Vertex, fallbackVertexShader);
program()->addShaderFromSourceCode(QOpenGLShader::Fragment, fallbackFragmentShader);
#ifndef QT_NO_DEBUG
for (int i = 0; i < attrCount; ++i) {
#else
for (int i = 0; attr[i]; ++i) {
#endif
if (qstrcmp(attr[i], qtPositionAttributeName()) == 0)
program()->bindAttributeLocation("v", i);
}
program()->link();
}
}
const char *QQuickCustomMaterialShader::vertexShader() const
{
return m_key.sourceCode[QQuickShaderEffectMaterialKey::VertexShader].constData();
}
const char *QQuickCustomMaterialShader::fragmentShader() const
{
return m_key.sourceCode[QQuickShaderEffectMaterialKey::FragmentShader].constData();
}
bool QQuickShaderEffectMaterialKey::operator == (const QQuickShaderEffectMaterialKey &other) const
{
if (className != other.className)
return false;
for (int shaderType = 0; shaderType < ShaderTypeCount; ++shaderType) {
if (sourceCode[shaderType] != other.sourceCode[shaderType])
return false;
}
return true;
}
uint qHash(const QQuickShaderEffectMaterialKey &key)
{
uint hash = qHash((void *)key.className);
typedef QQuickShaderEffectMaterialKey Key;
for (int shaderType = 0; shaderType < Key::ShaderTypeCount; ++shaderType)
hash = hash * 31337 + qHash(key.sourceCode[shaderType]);
return hash;
}
QHash<QQuickShaderEffectMaterialKey, QSharedPointer<QSGMaterialType> > QQuickShaderEffectMaterial::materialMap;
QQuickShaderEffectMaterial::QQuickShaderEffectMaterial(QQuickShaderEffectNode *node)
: cullMode(NoCulling)
, m_node(node)
, m_emittedLogChanged(false)
{
setFlag(Blending | RequiresFullMatrix, true);
}
QSGMaterialType *QQuickShaderEffectMaterial::type() const
{
return m_type.data();
}
QSGMaterialShader *QQuickShaderEffectMaterial::createShader() const
{
return new QQuickCustomMaterialShader(m_source, attributes);
}
int QQuickShaderEffectMaterial::compare(const QSGMaterial *other) const
{
return this - static_cast<const QQuickShaderEffectMaterial *>(other);
}
void QQuickShaderEffectMaterial::setProgramSource(const QQuickShaderEffectMaterialKey &source)
{
m_source = source;
m_emittedLogChanged = false;
m_type = materialMap.value(m_source);
if (m_type.isNull()) {
m_type = QSharedPointer<QSGMaterialType>(new QSGMaterialType);
materialMap.insert(m_source, m_type);
}
}
void QQuickShaderEffectMaterial::updateTextures() const
{
for (int i = 0; i < textureProviders.size(); ++i) {
if (QSGTextureProvider *provider = textureProviders.at(i)) {
if (QSGDynamicTexture *texture = qobject_cast<QSGDynamicTexture *>(provider->texture()))
texture->updateTexture();
}
}
}
void QQuickShaderEffectMaterial::invalidateTextureProvider(QSGTextureProvider *provider)
{
for (int i = 0; i < textureProviders.size(); ++i) {
if (provider == textureProviders.at(i))
textureProviders[i] = 0;
}
}
QQuickShaderEffectNode::QQuickShaderEffectNode()
{
QSGNode::setFlag(UsePreprocess, true);
#ifdef QSG_RUNTIME_DESCRIPTION
qsgnode_set_description(this, QLatin1String("shadereffect"));
#endif
}
QQuickShaderEffectNode::~QQuickShaderEffectNode()
{
}
void QQuickShaderEffectNode::markDirtyTexture()
{
markDirty(DirtyMaterial);
}
void QQuickShaderEffectNode::textureProviderDestroyed(QObject *object)
{
Q_ASSERT(material());
static_cast<QQuickShaderEffectMaterial *>(material())->invalidateTextureProvider(static_cast<QSGTextureProvider *>(object));
}
void QQuickShaderEffectNode::preprocess()
{
Q_ASSERT(material());
static_cast<QQuickShaderEffectMaterial *>(material())->updateTextures();
}
QT_END_NAMESPACE
<commit_msg>Respect Qt.vector2d as input to ShaderEffect uniforms.<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQuick module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <private/qquickshadereffectnode_p.h>
#include "qquickshadereffectmesh_p.h"
#include "qquickshadereffect_p.h"
#include <QtQuick/qsgtextureprovider.h>
#include <QtQuick/private/qsgrenderer_p.h>
QT_BEGIN_NAMESPACE
class QQuickCustomMaterialShader : public QSGMaterialShader
{
public:
QQuickCustomMaterialShader(const QQuickShaderEffectMaterialKey &key, const QVector<QByteArray> &attributes);
virtual void deactivate();
virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
virtual char const *const *attributeNames() const;
protected:
friend class QQuickShaderEffectNode;
virtual void compile();
virtual const char *vertexShader() const;
virtual const char *fragmentShader() const;
const QQuickShaderEffectMaterialKey m_key;
QVector<const char *> m_attributeNames;
const QVector<QByteArray> m_attributes;
QString m_log;
bool m_compiled;
QVector<int> m_uniformLocs[QQuickShaderEffectMaterialKey::ShaderTypeCount];
uint m_initialized : 1;
};
QQuickCustomMaterialShader::QQuickCustomMaterialShader(const QQuickShaderEffectMaterialKey &key, const QVector<QByteArray> &attributes)
: m_key(key)
, m_attributes(attributes)
, m_compiled(false)
, m_initialized(false)
{
for (int i = 0; i < attributes.count(); ++i)
m_attributeNames.append(attributes.at(i).constData());
m_attributeNames.append(0);
}
void QQuickCustomMaterialShader::deactivate()
{
QSGMaterialShader::deactivate();
glDisable(GL_CULL_FACE);
}
void QQuickCustomMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
{
typedef QQuickShaderEffectMaterial::UniformData UniformData;
Q_ASSERT(newEffect != 0);
QQuickShaderEffectMaterial *material = static_cast<QQuickShaderEffectMaterial *>(newEffect);
if (!material->m_emittedLogChanged && material->m_node) {
material->m_emittedLogChanged = true;
emit material->m_node->logAndStatusChanged(m_log, m_compiled ? QQuickShaderEffect::Compiled
: QQuickShaderEffect::Error);
}
int textureProviderIndex = 0;
if (!m_initialized) {
for (int shaderType = 0; shaderType < QQuickShaderEffectMaterialKey::ShaderTypeCount; ++shaderType) {
Q_ASSERT(m_uniformLocs[shaderType].isEmpty());
m_uniformLocs[shaderType].reserve(material->uniforms[shaderType].size());
for (int i = 0; i < material->uniforms[shaderType].size(); ++i) {
const UniformData &d = material->uniforms[shaderType].at(i);
QByteArray name = d.name;
if (d.specialType == UniformData::Sampler) {
program()->setUniformValue(d.name.constData(), textureProviderIndex++);
// We don't need to store the sampler uniform locations, since their values
// only need to be set once. Look for the "qt_SubRect_" uniforms instead.
// These locations are used when binding the textures later.
name = "qt_SubRect_" + name;
}
m_uniformLocs[shaderType].append(program()->uniformLocation(name.constData()));
}
}
m_initialized = true;
textureProviderIndex = 0;
}
QOpenGLFunctions *functions = state.context()->functions();
for (int shaderType = 0; shaderType < QQuickShaderEffectMaterialKey::ShaderTypeCount; ++shaderType) {
for (int i = 0; i < material->uniforms[shaderType].size(); ++i) {
const UniformData &d = material->uniforms[shaderType].at(i);
int loc = m_uniformLocs[shaderType].at(i);
if (d.specialType == UniformData::Sampler) {
int idx = textureProviderIndex++;
functions->glActiveTexture(GL_TEXTURE0 + idx);
if (QSGTextureProvider *provider = material->textureProviders.at(idx)) {
if (QSGTexture *texture = provider->texture()) {
if (loc >= 0) {
QRectF r = texture->normalizedTextureSubRect();
program()->setUniformValue(loc, r.x(), r.y(), r.width(), r.height());
} else if (texture->isAtlasTexture()) {
texture = texture->removedFromAtlas();
}
texture->bind();
continue;
}
}
qWarning("ShaderEffect: source or provider missing when binding textures");
glBindTexture(GL_TEXTURE_2D, 0);
} else if (d.specialType == UniformData::Opacity) {
program()->setUniformValue(loc, state.opacity());
} else if (d.specialType == UniformData::Matrix) {
if (state.isMatrixDirty())
program()->setUniformValue(loc, state.combinedMatrix());
} else if (d.specialType == UniformData::None) {
switch (int(d.value.type())) {
case QMetaType::QColor:
program()->setUniformValue(loc, qt_premultiply_color(qvariant_cast<QColor>(d.value)));
break;
case QMetaType::Float:
program()->setUniformValue(loc, qvariant_cast<float>(d.value));
break;
case QMetaType::Double:
program()->setUniformValue(loc, (float) qvariant_cast<double>(d.value));
break;
case QMetaType::QTransform:
program()->setUniformValue(loc, qvariant_cast<QTransform>(d.value));
break;
case QMetaType::Int:
program()->setUniformValue(loc, d.value.toInt());
break;
case QMetaType::Bool:
program()->setUniformValue(loc, GLint(d.value.toBool()));
break;
case QMetaType::QSize:
case QMetaType::QSizeF:
program()->setUniformValue(loc, d.value.toSizeF());
break;
case QMetaType::QPoint:
case QMetaType::QPointF:
program()->setUniformValue(loc, d.value.toPointF());
break;
case QMetaType::QRect:
case QMetaType::QRectF:
{
QRectF r = d.value.toRectF();
program()->setUniformValue(loc, r.x(), r.y(), r.width(), r.height());
}
break;
case QMetaType::QVector2D:
program()->setUniformValue(loc, qvariant_cast<QVector2D>(d.value));
break;
case QMetaType::QVector3D:
program()->setUniformValue(loc, qvariant_cast<QVector3D>(d.value));
break;
case QMetaType::QVector4D:
program()->setUniformValue(loc, qvariant_cast<QVector4D>(d.value));
break;
case QMetaType::QMatrix4x4:
program()->setUniformValue(loc, qvariant_cast<QMatrix4x4>(d.value));
break;
default:
break;
}
}
}
}
functions->glActiveTexture(GL_TEXTURE0);
const QQuickShaderEffectMaterial *oldMaterial = static_cast<const QQuickShaderEffectMaterial *>(oldEffect);
if (oldEffect == 0 || material->cullMode != oldMaterial->cullMode) {
switch (material->cullMode) {
case QQuickShaderEffectMaterial::FrontFaceCulling:
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
break;
case QQuickShaderEffectMaterial::BackFaceCulling:
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
break;
default:
glDisable(GL_CULL_FACE);
break;
}
}
}
char const *const *QQuickCustomMaterialShader::attributeNames() const
{
return m_attributeNames.constData();
}
void QQuickCustomMaterialShader::compile()
{
Q_ASSERT_X(!program()->isLinked(), "QQuickCustomMaterialShader::compile()", "Compile called multiple times!");
m_log.clear();
m_compiled = true;
if (!program()->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShader())) {
m_log += QLatin1String("*** Vertex shader ***\n");
m_log += program()->log();
m_compiled = false;
}
if (!program()->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShader())) {
m_log += QLatin1String("*** Fragment shader ***\n");
m_log += program()->log();
m_compiled = false;
}
char const *const *attr = attributeNames();
#ifndef QT_NO_DEBUG
int maxVertexAttribs = 0;
glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &maxVertexAttribs);
int attrCount = 0;
while (attrCount < maxVertexAttribs && attr[attrCount])
++attrCount;
if (attr[attrCount]) {
qWarning("List of attribute names is too long.\n"
"Maximum number of attributes on this hardware is %i.\n"
"Vertex shader:\n%s\n"
"Fragment shader:\n%s\n",
maxVertexAttribs, vertexShader(), fragmentShader());
}
#endif
if (m_compiled) {
#ifndef QT_NO_DEBUG
for (int i = 0; i < attrCount; ++i) {
#else
for (int i = 0; attr[i]; ++i) {
#endif
if (*attr[i])
program()->bindAttributeLocation(attr[i], i);
}
m_compiled = program()->link();
m_log += program()->log();
}
static const char fallbackVertexShader[] =
"uniform highp mat4 qt_Matrix;"
"attribute highp vec4 v;"
"void main() { gl_Position = qt_Matrix * v; }";
static const char fallbackFragmentShader[] =
"void main() { gl_FragColor = vec4(1., 0., 1., 1.); }";
if (!m_compiled) {
qWarning("QQuickCustomMaterialShader: Shader compilation failed:");
qWarning() << program()->log();
program()->removeAllShaders();
program()->addShaderFromSourceCode(QOpenGLShader::Vertex, fallbackVertexShader);
program()->addShaderFromSourceCode(QOpenGLShader::Fragment, fallbackFragmentShader);
#ifndef QT_NO_DEBUG
for (int i = 0; i < attrCount; ++i) {
#else
for (int i = 0; attr[i]; ++i) {
#endif
if (qstrcmp(attr[i], qtPositionAttributeName()) == 0)
program()->bindAttributeLocation("v", i);
}
program()->link();
}
}
const char *QQuickCustomMaterialShader::vertexShader() const
{
return m_key.sourceCode[QQuickShaderEffectMaterialKey::VertexShader].constData();
}
const char *QQuickCustomMaterialShader::fragmentShader() const
{
return m_key.sourceCode[QQuickShaderEffectMaterialKey::FragmentShader].constData();
}
bool QQuickShaderEffectMaterialKey::operator == (const QQuickShaderEffectMaterialKey &other) const
{
if (className != other.className)
return false;
for (int shaderType = 0; shaderType < ShaderTypeCount; ++shaderType) {
if (sourceCode[shaderType] != other.sourceCode[shaderType])
return false;
}
return true;
}
uint qHash(const QQuickShaderEffectMaterialKey &key)
{
uint hash = qHash((void *)key.className);
typedef QQuickShaderEffectMaterialKey Key;
for (int shaderType = 0; shaderType < Key::ShaderTypeCount; ++shaderType)
hash = hash * 31337 + qHash(key.sourceCode[shaderType]);
return hash;
}
QHash<QQuickShaderEffectMaterialKey, QSharedPointer<QSGMaterialType> > QQuickShaderEffectMaterial::materialMap;
QQuickShaderEffectMaterial::QQuickShaderEffectMaterial(QQuickShaderEffectNode *node)
: cullMode(NoCulling)
, m_node(node)
, m_emittedLogChanged(false)
{
setFlag(Blending | RequiresFullMatrix, true);
}
QSGMaterialType *QQuickShaderEffectMaterial::type() const
{
return m_type.data();
}
QSGMaterialShader *QQuickShaderEffectMaterial::createShader() const
{
return new QQuickCustomMaterialShader(m_source, attributes);
}
int QQuickShaderEffectMaterial::compare(const QSGMaterial *other) const
{
return this - static_cast<const QQuickShaderEffectMaterial *>(other);
}
void QQuickShaderEffectMaterial::setProgramSource(const QQuickShaderEffectMaterialKey &source)
{
m_source = source;
m_emittedLogChanged = false;
m_type = materialMap.value(m_source);
if (m_type.isNull()) {
m_type = QSharedPointer<QSGMaterialType>(new QSGMaterialType);
materialMap.insert(m_source, m_type);
}
}
void QQuickShaderEffectMaterial::updateTextures() const
{
for (int i = 0; i < textureProviders.size(); ++i) {
if (QSGTextureProvider *provider = textureProviders.at(i)) {
if (QSGDynamicTexture *texture = qobject_cast<QSGDynamicTexture *>(provider->texture()))
texture->updateTexture();
}
}
}
void QQuickShaderEffectMaterial::invalidateTextureProvider(QSGTextureProvider *provider)
{
for (int i = 0; i < textureProviders.size(); ++i) {
if (provider == textureProviders.at(i))
textureProviders[i] = 0;
}
}
QQuickShaderEffectNode::QQuickShaderEffectNode()
{
QSGNode::setFlag(UsePreprocess, true);
#ifdef QSG_RUNTIME_DESCRIPTION
qsgnode_set_description(this, QLatin1String("shadereffect"));
#endif
}
QQuickShaderEffectNode::~QQuickShaderEffectNode()
{
}
void QQuickShaderEffectNode::markDirtyTexture()
{
markDirty(DirtyMaterial);
}
void QQuickShaderEffectNode::textureProviderDestroyed(QObject *object)
{
Q_ASSERT(material());
static_cast<QQuickShaderEffectMaterial *>(material())->invalidateTextureProvider(static_cast<QSGTextureProvider *>(object));
}
void QQuickShaderEffectNode::preprocess()
{
Q_ASSERT(material());
static_cast<QQuickShaderEffectMaterial *>(material())->updateTextures();
}
QT_END_NAMESPACE
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.