text
stringlengths 54
60.6k
|
|---|
<commit_before>
#include "antsUtilities.h"
#include <algorithm>
#include "itkSurfaceCurvatureBase.h"
#include "itkSurfaceImageCurvature.h"
#include "ReadWriteImage.h"
namespace ants
{
/*
void test1()
{
typedef itk::SurfaceCurvatureBase<ImageType> ParamType;
ParamType::Pointer Parameterizer=ParamType::New();
// Parameterizer->TestEstimateTangentPlane(p);
Parameterizer->FindNeighborhood();
// Parameterizer->WeightedEstimateTangentPlane( Parameterizer->GetOrigin() );
Parameterizer->EstimateTangentPlane(
Parameterizer->GetAveragePoint());
Parameterizer->PrintFrame();
// Parameterizer->SetOrigin(Parameterizer->GetAveragePoint());
for(int i=0; i<3; i++){
Parameterizer->ComputeWeightsAndDirectionalKappaAndAngles
(Parameterizer->GetOrigin());
Parameterizer->ComputeFrame(Parameterizer->GetOrigin());
Parameterizer->EstimateCurvature();
Parameterizer->PrintFrame();
}
Parameterizer->ComputeJoshiFrame(Parameterizer->GetOrigin()); Parameterizer->PrintFrame();
antscout << " err 1 " << Parameterizer->ErrorEstimate(Parameterizer->GetOrigin()) <<
" err 2 " << Parameterizer->ErrorEstimate(Parameterizer->GetOrigin(),-1) << std::endl;
}
*/
// entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to
// 'main()'
int SurfaceCurvature( std::vector<std::string> args, std::ostream* out_stream = NULL )
{
// put the arguments coming in as 'args' into standard (argc,argv) format;
// 'args' doesn't have the command name as first, argument, so add it manually;
// 'args' may have adjacent arguments concatenated into one argument,
// which the parser should handle
args.insert( args.begin(), "SurfaceCurvature" );
int argc = args.size();
char* * argv = new char *[args.size() + 1];
for( unsigned int i = 0; i < args.size(); ++i )
{
// allocate space for the string plus a null character
argv[i] = new char[args[i].length() + 1];
std::strncpy( argv[i], args[i].c_str(), args[i].length() );
// place the null character in the end
argv[i][args[i].length()] = '\0';
}
argv[argc] = 0;
// class to automatically cleanup argv upon destruction
class Cleanup_argv
{
public:
Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )
{
}
~Cleanup_argv()
{
for( unsigned int i = 0; i < argc_plus_one; ++i )
{
delete[] argv[i];
}
delete[] argv;
}
private:
char* * argv;
unsigned int argc_plus_one;
};
Cleanup_argv cleanup_argv( argv, argc + 1 );
antscout->set_stream( out_stream );
if( argc < 3 )
{
antscout << " usage : SurfaceCurvature FileNameIn FileNameOut sigma option " << std::endl;
antscout << " e.g : SurfaceCurvature BrainIn.nii BrainOut.nii 3 0 " << std::endl;
antscout << " option 0 means just compute mean curvature from intensity " << std::endl;
antscout << " option 5 means characterize surface from intensity " << std::endl;
antscout << " option 6 means compute gaussian curvature " << std::endl;
antscout << " ... " << std::endl;
antscout << " for surface characterization " << std::endl;
antscout << " 1 == (+) bowl " << std::endl;
antscout << " 2 == (-) bowl " << std::endl;
antscout << " 3 == (+) saddle " << std::endl;
antscout << " 4 == (-) saddle " << std::endl;
antscout << " 5 == (+) U " << std::endl;
antscout << " 6 == (-) U " << std::endl;
antscout << " 7 == flat " << std::endl;
antscout << " 8 == a perfectly even saddle (rare) " << std::endl;
antscout << " " << std::endl;
antscout << " we add 128 to mean curvature results s.t. they are differentiated from background (zero) "
<< std::endl;
return 0;
}
typedef itk::Image<float, 3> ImageType;
typedef itk::Image<float, 3> floatImageType;
enum { ImageDimension = ImageType::ImageDimension };
typedef itk::SurfaceImageCurvature<ImageType> ParamType;
ParamType::Pointer Parameterizer = ParamType::New();
typedef ImageType::PixelType PixType;
int opt = 0;
float sig = 1.0;
if( argc > 3 )
{
sig = atof( argv[3]);
}
antscout << " sigma " << sig << std::endl;
if( argc > 4 )
{
opt = (int) atoi(argv[4]);
}
if( opt < 0 )
{
antscout << " error " << std::endl;
return 0;
}
ImageType::Pointer input;
ReadImage<ImageType>(input, argv[1]);
antscout << " done reading " << std::string(argv[1]) << std::endl;
// float ballradius = 2.0;
// if (argc >= 6) ballradius = (float) atof(argv[5]);
// if (ballradius > 0 && thresh > 0) input = SegmentImage<ImageType>(input, thresh, ballradius);
Parameterizer->SetInputImage(input);
// Parameterizer->ProcessLabelImage();
Parameterizer->SetNeighborhoodRadius( 1. );
// antscout << " set sig " ; std::cin >> sig;
if( sig <= 0.5 )
{
sig = 1.66;
}
antscout << " sigma " << sig << " option " << opt << std::endl;
Parameterizer->SetSigma(sig);
if( opt == 1 )
{
Parameterizer->SetUseLabel(true);
Parameterizer->SetUseGeodesicNeighborhood(false);
}
else
{
Parameterizer->SetUseLabel(false);
Parameterizer->SetUseGeodesicNeighborhood(false);
float sign = 1.0;
if( opt == 3 )
{
sign = -1.0;
}
antscout << " setting outward direction as " << sign;
Parameterizer->SetkSign(sign);
Parameterizer->SetThreshold(0);
}
// Parameterizer->ComputeSurfaceArea();
// Parameterizer->IntegrateFunctionOverSurface();
// Parameterizer->IntegrateFunctionOverSurface(true);
antscout << " computing frame " << std::endl;
if( opt != 5 && opt != 6 )
{
Parameterizer->ComputeFrameOverDomain( 3 );
}
else
{
Parameterizer->ComputeFrameOverDomain( opt );
}
// Parameterizer->SetNeighborhoodRadius( 2 );
// Parameterizer->LevelSetMeanCurvature();
// Parameterizer->SetNeighborhoodRadius( 2.9 );
// Parameterizer->IntegrateFunctionOverSurface(false);
// Parameterizer->SetNeighborhoodRadius( 1.5 );
// Parameterizer->IntegrateFunctionOverSurface(true);
// for (int i=0; i<1; i++) Parameterizer->PostProcessGeometry();
ImageType::Pointer output = NULL;
// Parameterizer->GetFunctionImage()->SetSpacing( input->GetSpacing() );
// Parameterizer->GetFunctionImage()->SetDirection( input->GetDirection() );
// Parameterizer->GetFunctionImage()->SetOrigin( input->GetOrigin() );
// smooth->SetSpacing(reader->GetOutput()->GetSpacing());
// SmoothImage(Parameterizer->GetFunctionImage(),smooth,3);
// NormalizeImage(smooth,output,mn);
// NormalizeImage(Parameterizer->GetFunctionImage(),output,mn);
WriteImage<floatImageType>(Parameterizer->GetFunctionImage(), argv[2]);
antscout << " done writing ";
return 1;
}
} // namespace ants
<commit_msg>DOC: add reference and comments on SurfaceCurvature<commit_after>
#include "antsUtilities.h"
#include <algorithm>
#include "itkSurfaceCurvatureBase.h"
#include "itkSurfaceImageCurvature.h"
#include "ReadWriteImage.h"
namespace ants
{
/*
void test1()
{
typedef itk::SurfaceCurvatureBase<ImageType> ParamType;
ParamType::Pointer Parameterizer=ParamType::New();
// Parameterizer->TestEstimateTangentPlane(p);
Parameterizer->FindNeighborhood();
// Parameterizer->WeightedEstimateTangentPlane( Parameterizer->GetOrigin() );
Parameterizer->EstimateTangentPlane(
Parameterizer->GetAveragePoint());
Parameterizer->PrintFrame();
// Parameterizer->SetOrigin(Parameterizer->GetAveragePoint());
for(int i=0; i<3; i++){
Parameterizer->ComputeWeightsAndDirectionalKappaAndAngles
(Parameterizer->GetOrigin());
Parameterizer->ComputeFrame(Parameterizer->GetOrigin());
Parameterizer->EstimateCurvature();
Parameterizer->PrintFrame();
}
Parameterizer->ComputeJoshiFrame(Parameterizer->GetOrigin()); Parameterizer->PrintFrame();
antscout << " err 1 " << Parameterizer->ErrorEstimate(Parameterizer->GetOrigin()) <<
" err 2 " << Parameterizer->ErrorEstimate(Parameterizer->GetOrigin(),-1) << std::endl;
}
*/
// entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to
// 'main()'
int SurfaceCurvature( std::vector<std::string> args, std::ostream* out_stream = NULL )
{
// put the arguments coming in as 'args' into standard (argc,argv) format;
// 'args' doesn't have the command name as first, argument, so add it manually;
// 'args' may have adjacent arguments concatenated into one argument,
// which the parser should handle
args.insert( args.begin(), "SurfaceCurvature" );
int argc = args.size();
char* * argv = new char *[args.size() + 1];
for( unsigned int i = 0; i < args.size(); ++i )
{
// allocate space for the string plus a null character
argv[i] = new char[args[i].length() + 1];
std::strncpy( argv[i], args[i].c_str(), args[i].length() );
// place the null character in the end
argv[i][args[i].length()] = '\0';
}
argv[argc] = 0;
// class to automatically cleanup argv upon destruction
class Cleanup_argv
{
public:
Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )
{
}
~Cleanup_argv()
{
for( unsigned int i = 0; i < argc_plus_one; ++i )
{
delete[] argv[i];
}
delete[] argv;
}
private:
char* * argv;
unsigned int argc_plus_one;
};
Cleanup_argv cleanup_argv( argv, argc + 1 );
antscout->set_stream( out_stream );
if( argc < 3 )
{
antscout << " This implements The Shape Operator for Differential Analysis of Images (google for the pdf)" << std::endl;
antscout << " By B. Avants and J.C. Gee " << std::endl;
antscout << " Documentation is on demand --- if there is enough interest, documentation will improve." << std::endl;
antscout << " There are several modes of operation and you must try parameters and input either binary or gray scale images to see the different effects ---- experimentation or reading the (minimal) documentation / paper / code is needed to understand the program " << std::endl;
antscout << " usage : SurfaceCurvature FileNameIn FileNameOut sigma option " << std::endl;
antscout << " e.g : SurfaceCurvature BrainIn.nii BrainOut.nii 3 0 " << std::endl;
antscout << " option 0 means just compute mean curvature from intensity " << std::endl;
antscout << " option 5 means characterize surface from intensity " << std::endl;
antscout << " option 6 means compute gaussian curvature " << std::endl;
antscout << " ... " << std::endl;
antscout << " for surface characterization " << std::endl;
antscout << " 1 == (+) bowl " << std::endl;
antscout << " 2 == (-) bowl " << std::endl;
antscout << " 3 == (+) saddle " << std::endl;
antscout << " 4 == (-) saddle " << std::endl;
antscout << " 5 == (+) U " << std::endl;
antscout << " 6 == (-) U " << std::endl;
antscout << " 7 == flat " << std::endl;
antscout << " 8 == a perfectly even saddle (rare) " << std::endl;
antscout << " " << std::endl;
antscout << " we add 128 to mean curvature results s.t. they are differentiated from background (zero) "
<< std::endl;
return 0;
}
typedef itk::Image<float, 3> ImageType;
typedef itk::Image<float, 3> floatImageType;
enum { ImageDimension = ImageType::ImageDimension };
typedef itk::SurfaceImageCurvature<ImageType> ParamType;
ParamType::Pointer Parameterizer = ParamType::New();
typedef ImageType::PixelType PixType;
int opt = 0;
float sig = 1.0;
if( argc > 3 )
{
sig = atof( argv[3]);
}
antscout << " sigma " << sig << std::endl;
if( argc > 4 )
{
opt = (int) atoi(argv[4]);
}
if( opt < 0 )
{
antscout << " error " << std::endl;
return 0;
}
ImageType::Pointer input;
ReadImage<ImageType>(input, argv[1]);
antscout << " done reading " << std::string(argv[1]) << std::endl;
// float ballradius = 2.0;
// if (argc >= 6) ballradius = (float) atof(argv[5]);
// if (ballradius > 0 && thresh > 0) input = SegmentImage<ImageType>(input, thresh, ballradius);
Parameterizer->SetInputImage(input);
// Parameterizer->ProcessLabelImage();
Parameterizer->SetNeighborhoodRadius( 1. );
// antscout << " set sig " ; std::cin >> sig;
if( sig <= 0.5 )
{
sig = 1.66;
}
antscout << " sigma " << sig << " option " << opt << std::endl;
Parameterizer->SetSigma(sig);
if( opt == 1 )
{
Parameterizer->SetUseLabel(true);
Parameterizer->SetUseGeodesicNeighborhood(false);
}
else
{
Parameterizer->SetUseLabel(false);
Parameterizer->SetUseGeodesicNeighborhood(false);
float sign = 1.0;
if( opt == 3 )
{
sign = -1.0;
}
antscout << " setting outward direction as " << sign;
Parameterizer->SetkSign(sign);
Parameterizer->SetThreshold(0);
}
// Parameterizer->ComputeSurfaceArea();
// Parameterizer->IntegrateFunctionOverSurface();
// Parameterizer->IntegrateFunctionOverSurface(true);
antscout << " computing frame " << std::endl;
if( opt != 5 && opt != 6 )
{
Parameterizer->ComputeFrameOverDomain( 3 );
}
else
{
Parameterizer->ComputeFrameOverDomain( opt );
}
// Parameterizer->SetNeighborhoodRadius( 2 );
// Parameterizer->LevelSetMeanCurvature();
// Parameterizer->SetNeighborhoodRadius( 2.9 );
// Parameterizer->IntegrateFunctionOverSurface(false);
// Parameterizer->SetNeighborhoodRadius( 1.5 );
// Parameterizer->IntegrateFunctionOverSurface(true);
// for (int i=0; i<1; i++) Parameterizer->PostProcessGeometry();
ImageType::Pointer output = NULL;
// Parameterizer->GetFunctionImage()->SetSpacing( input->GetSpacing() );
// Parameterizer->GetFunctionImage()->SetDirection( input->GetDirection() );
// Parameterizer->GetFunctionImage()->SetOrigin( input->GetOrigin() );
// smooth->SetSpacing(reader->GetOutput()->GetSpacing());
// SmoothImage(Parameterizer->GetFunctionImage(),smooth,3);
// NormalizeImage(smooth,output,mn);
// NormalizeImage(Parameterizer->GetFunctionImage(),output,mn);
WriteImage<floatImageType>(Parameterizer->GetFunctionImage(), argv[2]);
antscout << " done writing ";
return 1;
}
} // namespace ants
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: commandcontainer.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-07-10 15:09:08 $
*
* 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 _DBA_COREDATAACCESS_COMMANDCONTAINER_HXX_
#define _DBA_COREDATAACCESS_COMMANDCONTAINER_HXX_
#ifndef _DBA_CORE_DEFINITIONCONTAINER_HXX_
#include "definitioncontainer.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
//........................................................................
namespace dbaccess
{
//........................................................................
//==========================================================================
//= OCommandContainer
//==========================================================================
typedef ::cppu::ImplHelper1 < ::com::sun::star::lang::XSingleServiceFactory
> OCommandContainer_BASE;
class OCommandContainer : public ODefinitionContainer
,public OCommandContainer_BASE
{
sal_Bool m_bTables;
public:
/** constructs the container.<BR>
*/
OCommandContainer(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB
,const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _xParentContainer
,const TContentPtr& _pImpl
,sal_Bool _bTables
);
DECLARE_XINTERFACE( )
DECLARE_TYPEPROVIDER( );
// XSingleServiceFactory
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstance( ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithArguments( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
protected:
virtual ~OCommandContainer();
// ODefinitionContainer
virtual ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent > createObject(const ::rtl::OUString& _rName);
};
//........................................................................
} // namespace dbaccess
//........................................................................
#endif // _DBA_COREDATAACCESS_COMMANDCONTAINER_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.8.300); FILE MERGED 2008/03/31 13:26:46 rt 1.8.300.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: commandcontainer.hxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _DBA_COREDATAACCESS_COMMANDCONTAINER_HXX_
#define _DBA_COREDATAACCESS_COMMANDCONTAINER_HXX_
#ifndef _DBA_CORE_DEFINITIONCONTAINER_HXX_
#include "definitioncontainer.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
//........................................................................
namespace dbaccess
{
//........................................................................
//==========================================================================
//= OCommandContainer
//==========================================================================
typedef ::cppu::ImplHelper1 < ::com::sun::star::lang::XSingleServiceFactory
> OCommandContainer_BASE;
class OCommandContainer : public ODefinitionContainer
,public OCommandContainer_BASE
{
sal_Bool m_bTables;
public:
/** constructs the container.<BR>
*/
OCommandContainer(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB
,const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _xParentContainer
,const TContentPtr& _pImpl
,sal_Bool _bTables
);
DECLARE_XINTERFACE( )
DECLARE_TYPEPROVIDER( );
// XSingleServiceFactory
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstance( ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithArguments( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
protected:
virtual ~OCommandContainer();
// ODefinitionContainer
virtual ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent > createObject(const ::rtl::OUString& _rName);
};
//........................................................................
} // namespace dbaccess
//........................................................................
#endif // _DBA_COREDATAACCESS_COMMANDCONTAINER_HXX_
<|endoftext|>
|
<commit_before>#include "fake_lem1802.hpp"
#include <algorithm>
#include <cctype>
namespace cpu {
// Consts
const char esc = 27; // ESC character -> ANSI escape codes
/**
* @brief Moves the terminal cursor at row X
*/
inline void row (int x)
{
std::cout << esc << "[0;" << (x) << "H";
}
Fake_Lem1802::Fake_Lem1802() : screen_map (0), font_map (0), palette_map (0),
border_col (0), ticks (0)
{
// Fake default font
def_font_map = new uint16_t[256];
// Load default palette
def_palette_map[ 0] = 0x0000;
def_palette_map[ 1] = 0x000a;
def_palette_map[ 2] = 0x00a0;
def_palette_map[ 3] = 0x00aa;
def_palette_map[ 4] = 0x0a00;
def_palette_map[ 5] = 0x0a0a;
def_palette_map[ 6] = 0x0a50;
def_palette_map[ 7] = 0x0aaa;
def_palette_map[ 8] = 0x0555;
def_palette_map[ 9] = 0x055f;
def_palette_map[10] = 0x05f5;
def_palette_map[11] = 0x05ff;
def_palette_map[12] = 0x0f55;
def_palette_map[13] = 0x0f5f;
def_palette_map[14] = 0x0ff5;
def_palette_map[15] = 0x0fff;
}
Fake_Lem1802::~Fake_Lem1802()
{
delete[] def_font_map;
}
void Fake_Lem1802::attachTo (DCPU* cpu, size_t index) {
this->IHardware::attachTo(cpu, index);
tick_per_refresh = cpu->cpu_clock / 60;
}
void Fake_Lem1802::handleInterrupt()
{
if (this->cpu == NULL)
return;
size_t s;
switch (cpu->GetA() ) {
case MEM_MAP_SCREEN:
screen_map = cpu->GetB();
if (screen_map != 0)
ticks = tick_per_refresh +1; // Force to do initial print
break;
case MEM_MAP_FONT:
font_map = cpu->GetB();
break;
case MEM_MAP_PALETTE:
palette_map = cpu->GetB();
break;
case SET_BORDER_COLOR:
border_col = cpu->GetB() & 0xf;
break;
case MEM_DUMP_FONT:
s = RAM_SIZE - 1 - cpu->GetB() < 256 ? RAM_SIZE - 1 - cpu->GetB() : 256 ;
std::copy_n (def_font_map, s, cpu->getMem() + cpu->GetB() );
break;
case MEM_DUMP_PALETTE:
s = RAM_SIZE - 1 - cpu->GetB() < 16 ? RAM_SIZE - 1 - cpu->GetB() : 16 ;
std::copy_n (def_palette_map, s, cpu->getMem() + cpu->GetB() );
break;
default:
// do nothing
break;
}
}
void Fake_Lem1802::tick()
{
if (++ticks > tick_per_refresh) {
// Update screen at 60Hz aprox
ticks = 0;
this->show();
}
}
void Fake_Lem1802::show()
{
using namespace std;
if (this->cpu == NULL)
return;
if (screen_map != 0) {
row (this->index * 32);
for (int row = 0; row < 12; row++) {
for (int col = 0; col < 32; col++) {
uint16_t pos = screen_map + row * 32 + col;
char tmp = (char) (cpu->getMem() [pos] & 0x00FF);
if (isprint (tmp) )
cout << tmp;
else
cout << ' ';
}
cout << endl;
}
}
}
} // END of NAMESPACE
<commit_msg>Added LEM default font<commit_after>#include "fake_lem1802.hpp"
#include <algorithm>
#include <cctype>
namespace cpu {
// Consts
const char esc = 27; // ESC character -> ANSI escape codes
/**
* @brief Moves the terminal cursor at row X
*/
inline void row (int x)
{
std::cout << esc << "[0;" << (x) << "H";
}
Fake_Lem1802::Fake_Lem1802() : screen_map (0), font_map (0), palette_map (0),
border_col (0), ticks (0)
{
// Default font
def_font_map = new uint16_t[256]{
0xb79e, 0x388e, 0x722c, 0x75f4, 0x19bb, 0x7f8f, 0x85f9, 0xb158,
0x242e, 0x2400, 0x082a, 0x0800, 0x0008, 0x0000, 0x0808, 0x0808,
0x00ff, 0x0000, 0x00f8, 0x0808, 0x08f8, 0x0000, 0x080f, 0x0000,
0x000f, 0x0808, 0x00ff, 0x0808, 0x08f8, 0x0808, 0x08ff, 0x0000,
0x080f, 0x0808, 0x08ff, 0x0808, 0x6633, 0x99cc, 0x9933, 0x66cc,
0xfef8, 0xe080, 0x7f1f, 0x0701, 0x0107, 0x1f7f, 0x80e0, 0xf8fe,
0x5500, 0xaa00, 0x55aa, 0x55aa, 0xffaa, 0xff55, 0x0f0f, 0x0f0f,
0xf0f0, 0xf0f0, 0x0000, 0xffff, 0xffff, 0x0000, 0xffff, 0xffff,
0x0000, 0x0000, 0x005f, 0x0000, 0x0300, 0x0300, 0x3e14, 0x3e00,
0x266b, 0x3200, 0x611c, 0x4300, 0x3629, 0x7650, 0x0002, 0x0100,
0x1c22, 0x4100, 0x4122, 0x1c00, 0x1408, 0x1400, 0x081c, 0x0800,
0x4020, 0x0000, 0x0808, 0x0800, 0x0040, 0x0000, 0x601c, 0x0300,
0x3e49, 0x3e00, 0x427f, 0x4000, 0x6259, 0x4600, 0x2249, 0x3600,
0x0f08, 0x7f00, 0x2745, 0x3900, 0x3e49, 0x3200, 0x6119, 0x0700,
0x3649, 0x3600, 0x2649, 0x3e00, 0x0024, 0x0000, 0x4024, 0x0000,
0x0814, 0x2200, 0x1414, 0x1400, 0x2214, 0x0800, 0x0259, 0x0600,
0x3e59, 0x5e00, 0x7e09, 0x7e00, 0x7f49, 0x3600, 0x3e41, 0x2200,
0x7f41, 0x3e00, 0x7f49, 0x4100, 0x7f09, 0x0100, 0x3e41, 0x7a00,
0x7f08, 0x7f00, 0x417f, 0x4100, 0x2040, 0x3f00, 0x7f08, 0x7700,
0x7f40, 0x4000, 0x7f06, 0x7f00, 0x7f01, 0x7e00, 0x3e41, 0x3e00,
0x7f09, 0x0600, 0x3e61, 0x7e00, 0x7f09, 0x7600, 0x2649, 0x3200,
0x017f, 0x0100, 0x3f40, 0x7f00, 0x1f60, 0x1f00, 0x7f30, 0x7f00,
0x7708, 0x7700, 0x0778, 0x0700, 0x7149, 0x4700, 0x007f, 0x4100,
0x031c, 0x6000, 0x417f, 0x0000, 0x0201, 0x0200, 0x8080, 0x8000,
0x0001, 0x0200, 0x2454, 0x7800, 0x7f44, 0x3800, 0x3844, 0x2800,
0x3844, 0x7f00, 0x3854, 0x5800, 0x087e, 0x0900, 0x4854, 0x3c00,
0x7f04, 0x7800, 0x047d, 0x0000, 0x2040, 0x3d00, 0x7f10, 0x6c00,
0x017f, 0x0000, 0x7c18, 0x7c00, 0x7c04, 0x7800, 0x3844, 0x3800,
0x7c14, 0x0800, 0x0814, 0x7c00, 0x7c04, 0x0800, 0x4854, 0x2400,
0x043e, 0x4400, 0x3c40, 0x7c00, 0x1c60, 0x1c00, 0x7c30, 0x7c00,
0x6c10, 0x6c00, 0x4c50, 0x3c00, 0x6454, 0x4c00, 0x0836, 0x4100,
0x0077, 0x0000, 0x4136, 0x0800, 0x0201, 0x0201, 0x0205, 0x0200
};
// Default palette
def_palette_map[ 0] = 0x0000;
def_palette_map[ 1] = 0x000a;
def_palette_map[ 2] = 0x00a0;
def_palette_map[ 3] = 0x00aa;
def_palette_map[ 4] = 0x0a00;
def_palette_map[ 5] = 0x0a0a;
def_palette_map[ 6] = 0x0a50;
def_palette_map[ 7] = 0x0aaa;
def_palette_map[ 8] = 0x0555;
def_palette_map[ 9] = 0x055f;
def_palette_map[10] = 0x05f5;
def_palette_map[11] = 0x05ff;
def_palette_map[12] = 0x0f55;
def_palette_map[13] = 0x0f5f;
def_palette_map[14] = 0x0ff5;
def_palette_map[15] = 0x0fff;
}
Fake_Lem1802::~Fake_Lem1802()
{
delete[] def_font_map;
}
void Fake_Lem1802::attachTo (DCPU* cpu, size_t index) {
this->IHardware::attachTo(cpu, index);
tick_per_refresh = cpu->cpu_clock / 60;
}
void Fake_Lem1802::handleInterrupt()
{
if (this->cpu == NULL)
return;
size_t s;
switch (cpu->GetA() ) {
case MEM_MAP_SCREEN:
screen_map = cpu->GetB();
if (screen_map != 0)
ticks = tick_per_refresh +1; // Force to do initial print
break;
case MEM_MAP_FONT:
font_map = cpu->GetB();
break;
case MEM_MAP_PALETTE:
palette_map = cpu->GetB();
break;
case SET_BORDER_COLOR:
border_col = cpu->GetB() & 0xf;
break;
case MEM_DUMP_FONT:
s = RAM_SIZE - 1 - cpu->GetB() < 256 ? RAM_SIZE - 1 - cpu->GetB() : 256 ;
std::copy_n (def_font_map, s, cpu->getMem() + cpu->GetB() );
break;
case MEM_DUMP_PALETTE:
s = RAM_SIZE - 1 - cpu->GetB() < 16 ? RAM_SIZE - 1 - cpu->GetB() : 16 ;
std::copy_n (def_palette_map, s, cpu->getMem() + cpu->GetB() );
break;
default:
// do nothing
break;
}
}
void Fake_Lem1802::tick()
{
if (++ticks > tick_per_refresh) {
// Update screen at 60Hz aprox
ticks = 0;
this->show();
}
}
void Fake_Lem1802::show()
{
using namespace std;
if (this->cpu == NULL)
return;
if (screen_map != 0) {
row (this->index * 32);
for (int row = 0; row < 12; row++) {
for (int col = 0; col < 32; col++) {
uint16_t pos = screen_map + row * 32 + col;
char tmp = (char) (cpu->getMem() [pos] & 0x00FF);
if (isprint (tmp) )
cout << tmp;
else
cout << ' ';
}
cout << endl;
}
}
}
} // END of NAMESPACE
<|endoftext|>
|
<commit_before>/**
* Copyright 2008 Matthew Graham
* 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 "connection_acceptor.h"
#include <set>
#include <memory>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <poll.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <iostream>
#include "connected_socket.h"
connection_acceptor_c::connection_acceptor_c()
: m_listener()
, m_open()
, m_ready()
, m_backlog( connection_acceptor_c::DEFAULT_BACKLOG )
{}
connection_acceptor_c::~connection_acceptor_c()
{
close();
}
bool connection_acceptor_c::listen( short port )
{
int listener( create_listener_socket( port, m_backlog ) );
if ( ! listener ) {
return false;
}
m_listener[ listener ] = port;
std::cerr << "m_listener[ " << listener << " ] = " << port << "\n";
return true;
}
int connection_acceptor_c::create_listener_socket( int port, int backlog )
{
int listener( 0 );
// create the socket
listener = socket( PF_INET, SOCK_STREAM, 0 );
if ( listener < 0 ) {
// error. do something.
perror( "Unable to create socket." );
return false;
} else if ( listener == 0 ) {
perror( "wtf happened?" );
return false;
}
// printf( "Socket connected at: %u\n", m_listener );
// bind the socket
struct sockaddr_in addr;
memset( &addr, 0, sizeof(addr) );
addr.sin_family = AF_INET;
addr.sin_port = htons( port );
addr.sin_addr.s_addr = INADDR_ANY;
int bind_error = bind( listener, (struct sockaddr *) &addr
, sizeof(addr) );
if ( bind_error ) {
// error. do something.
perror( "Unable to bind socket." );
return false;
}
// std::cout << "Socket is bound.\n";
// make the socket listen
int listen_error = ::listen( listener, backlog );
if ( listen_error < 0 ) {
// error. do something.
perror( "Socket won't listen." );
return false;
}
// printf( "Listening on port %u...\n", port );
struct sockaddr_in name;
socklen_t name_len = sizeof( name );
int sockname_err = getsockname( listener, (struct sockaddr *) &name
, &name_len );
if ( sockname_err ) {
perror( "getsockname error" );
return false;
}
fcntl( listener, F_SETFL, O_NONBLOCK );
return listener;
}
void connection_acceptor_c::close()
{
// close the listeners first
listener_iterator listener( m_listener.begin() );
for ( ; listener!=m_listener.end(); ++listener ) {
shutdown( listener->first, SHUT_RDWR );
}
m_listener.clear();
// close the open connections
connection_iterator conn( m_open.begin() );
for ( ; conn!=m_open.end(); ++conn ) {
shutdown( conn->first, SHUT_RDWR );
delete conn->second;
}
m_ready.clear();
m_open.clear();
}
connection_i * connection_acceptor_c::connection()
{
// check if there's already a ready connection queued
connection_i *ready_conn = NULL;
if ( ! m_ready.empty() ) {
ready_conn = m_ready.front();
m_ready.pop_front();
return ready_conn;
}
// build the poll set to check for new connections and input
int listener_count( m_listener.size() );
int connection_count( m_open.size() );
int poll_count( listener_count + connection_count );
pollfd *polls = new pollfd[ poll_count ];
int i( 0 );
// build listener poll structures
listener_iterator lit( m_listener.begin() );
for ( ; lit != m_listener.end(); ++lit ) {
polls[i].fd = lit->first;
polls[i].events = POLLIN | POLLRDHUP;
polls[i++].revents = 0;
}
// build polls for open connections
connection_iterator conn( m_open.begin() );
std::set< int > closed_connections;
for ( ; conn!=m_open.end(); ++conn ) {
if ( conn->second->open() ) {
polls[i].fd = conn->first;
polls[i].events = POLLIN;
polls[i++].revents = 0;
} else {
// flag the connection as closed
closed_connections.insert( conn->first );
}
}
// delete any closed connections
std::set< int >::const_iterator closed_it( closed_connections.begin() );
for ( ; closed_it!=closed_connections.end(); ++closed_it ) {
conn = m_open.find( *closed_it );
if ( conn != m_open.end() ) {
std::auto_ptr< connection_i > closed_conn(
m_open[ *closed_it ] );
m_open.erase( *closed_it );
}
}
std::cerr << "poll( " << listener_count << ", " << connection_count
<< " )...\n";
int ready_count( poll( polls, poll_count, 1000 ) );
if ( ready_count == 0 ) {
delete[] polls;
return NULL;
}
std::cerr << "ready_count == " << ready_count << std::endl;
if ( ready_count < 0 ) {
perror( "Poll error" );
}
// accept connections on the listeners
for ( i=0; i<listener_count; ++i ) {
if ( polls[i].revents & POLLIN ) {
int listener( polls[i].fd );
int port( m_listener[ listener ] );
accept( listener, port );
} else if ( polls[i].revents != 0 ) {
std::cerr << "polls[" << i << "].revents = "
<< polls[i].revents << std::endl;
}
}
// check for input on open connections
for ( i=listener_count; i<poll_count; ++i ) {
if ( polls[i].revents & POLLRDHUP ) {
// this connection is closed.
// delete it.
std::cerr << "deleting a closed connection\n";
close_socket( polls[i].fd );
} else if ( polls[i].revents & POLLIN ) {
std::cerr << "i=" << i << "; ";
std::cerr << "m_ready.push_back( m_open["
<< polls[i].fd << "] )\n";
m_ready.push_back( m_open[ polls[i].fd ] );
} else {
std::cerr << "polls[" << i << "].revents = "
<< polls[i].revents << std::endl;
}
}
delete[] polls;
// return the ready connection if there is one
if ( m_ready.empty() ) {
return NULL;
}
ready_conn = m_ready.front();
m_ready.pop_front();
return ready_conn;
}
void connection_acceptor_c::replace( connection_i *conn )
{
// doesn't do anything yet.
}
void connection_acceptor_c::accept( int listener, int port )
{
int sock( ::accept( listener, NULL, 0 ) );
if ( sock < 0 ) {
if ( errno == EWOULDBLOCK ) {
// non-block, when no resource is available
// std::cerr << "EWOULDBLOCK\n";
return;
} else if ( errno == EAGAIN ) {
// non-block, when no resource is available
std::cerr << "EAGAIN\n";
return;
} else if ( errno == EPERM ) {
std::cerr << "EPERM\n";
return;
} else if ( sock < 0 ) {
std::cerr << "sock error = " << sock << std::endl;
perror( "No connection." );
return;
}
std::cerr << "accept() failed\n";
return;
}
std::cerr << "Connected at " << sock << std::endl;
// set the socket as non-blocking before returning it
fcntl( sock, F_SETFL, O_NONBLOCK );
m_open[ sock ] = new connected_socket_c( sock, port );
}
void connection_acceptor_c::close_socket( int socket )
{
connection_iterator it( m_open.find( socket ) );
if ( it == m_open.end() ) {
return;
}
delete it->second;
m_open.erase( it->first );
}
<commit_msg>commented out debug msgs in connection_acceptor<commit_after>/**
* Copyright 2008 Matthew Graham
* 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 "connection_acceptor.h"
#include <set>
#include <memory>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <poll.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <iostream>
#include "connected_socket.h"
connection_acceptor_c::connection_acceptor_c()
: m_listener()
, m_open()
, m_ready()
, m_backlog( connection_acceptor_c::DEFAULT_BACKLOG )
{}
connection_acceptor_c::~connection_acceptor_c()
{
close();
}
bool connection_acceptor_c::listen( short port )
{
int listener( create_listener_socket( port, m_backlog ) );
if ( ! listener ) {
return false;
}
m_listener[ listener ] = port;
std::cerr << "m_listener[ " << listener << " ] = " << port << "\n";
return true;
}
int connection_acceptor_c::create_listener_socket( int port, int backlog )
{
int listener( 0 );
// create the socket
listener = socket( PF_INET, SOCK_STREAM, 0 );
if ( listener < 0 ) {
// error. do something.
perror( "Unable to create socket." );
return false;
} else if ( listener == 0 ) {
perror( "wtf happened?" );
return false;
}
// printf( "Socket connected at: %u\n", m_listener );
// bind the socket
struct sockaddr_in addr;
memset( &addr, 0, sizeof(addr) );
addr.sin_family = AF_INET;
addr.sin_port = htons( port );
addr.sin_addr.s_addr = INADDR_ANY;
int bind_error = bind( listener, (struct sockaddr *) &addr
, sizeof(addr) );
if ( bind_error ) {
// error. do something.
perror( "Unable to bind socket." );
return false;
}
// std::cout << "Socket is bound.\n";
// make the socket listen
int listen_error = ::listen( listener, backlog );
if ( listen_error < 0 ) {
// error. do something.
perror( "Socket won't listen." );
return false;
}
// printf( "Listening on port %u...\n", port );
struct sockaddr_in name;
socklen_t name_len = sizeof( name );
int sockname_err = getsockname( listener, (struct sockaddr *) &name
, &name_len );
if ( sockname_err ) {
perror( "getsockname error" );
return false;
}
fcntl( listener, F_SETFL, O_NONBLOCK );
return listener;
}
void connection_acceptor_c::close()
{
// close the listeners first
listener_iterator listener( m_listener.begin() );
for ( ; listener!=m_listener.end(); ++listener ) {
shutdown( listener->first, SHUT_RDWR );
}
m_listener.clear();
// close the open connections
connection_iterator conn( m_open.begin() );
for ( ; conn!=m_open.end(); ++conn ) {
shutdown( conn->first, SHUT_RDWR );
delete conn->second;
}
m_ready.clear();
m_open.clear();
}
connection_i * connection_acceptor_c::connection()
{
// check if there's already a ready connection queued
connection_i *ready_conn = NULL;
if ( ! m_ready.empty() ) {
ready_conn = m_ready.front();
m_ready.pop_front();
return ready_conn;
}
// build the poll set to check for new connections and input
int listener_count( m_listener.size() );
int connection_count( m_open.size() );
int poll_count( listener_count + connection_count );
pollfd *polls = new pollfd[ poll_count ];
int i( 0 );
// build listener poll structures
listener_iterator lit( m_listener.begin() );
for ( ; lit != m_listener.end(); ++lit ) {
polls[i].fd = lit->first;
polls[i].events = POLLIN | POLLRDHUP;
polls[i++].revents = 0;
}
// build polls for open connections
connection_iterator conn( m_open.begin() );
std::set< int > closed_connections;
for ( ; conn!=m_open.end(); ++conn ) {
if ( conn->second->open() ) {
polls[i].fd = conn->first;
polls[i].events = POLLIN;
polls[i++].revents = 0;
} else {
// flag the connection as closed
closed_connections.insert( conn->first );
}
}
// delete any closed connections
std::set< int >::const_iterator closed_it( closed_connections.begin() );
for ( ; closed_it!=closed_connections.end(); ++closed_it ) {
conn = m_open.find( *closed_it );
if ( conn != m_open.end() ) {
std::auto_ptr< connection_i > closed_conn(
m_open[ *closed_it ] );
m_open.erase( *closed_it );
}
}
// std::cerr << "poll( " << listener_count << ", " << connection_count
// << " )...\n";
int ready_count( poll( polls, poll_count, 1000 ) );
if ( ready_count == 0 ) {
delete[] polls;
return NULL;
}
// std::cerr << "ready_count == " << ready_count << std::endl;
if ( ready_count < 0 ) {
perror( "Poll error" );
}
// accept connections on the listeners
for ( i=0; i<listener_count; ++i ) {
if ( polls[i].revents & POLLIN ) {
int listener( polls[i].fd );
int port( m_listener[ listener ] );
accept( listener, port );
} else if ( polls[i].revents != 0 ) {
std::cerr << "polls[" << i << "].revents = "
<< polls[i].revents << std::endl;
}
}
// check for input on open connections
for ( i=listener_count; i<poll_count; ++i ) {
if ( polls[i].revents & POLLRDHUP ) {
// this connection is closed.
// delete it.
std::cerr << "deleting a closed connection\n";
close_socket( polls[i].fd );
} else if ( polls[i].revents & POLLIN ) {
// std::cerr << "i=" << i << "; ";
// std::cerr << "m_ready.push_back( m_open["
// << polls[i].fd << "] )\n";
m_ready.push_back( m_open[ polls[i].fd ] );
} else {
std::cerr << "polls[" << i << "].revents = "
<< polls[i].revents << std::endl;
}
}
delete[] polls;
// return the ready connection if there is one
if ( m_ready.empty() ) {
return NULL;
}
ready_conn = m_ready.front();
m_ready.pop_front();
return ready_conn;
}
void connection_acceptor_c::replace( connection_i *conn )
{
// doesn't do anything yet.
}
void connection_acceptor_c::accept( int listener, int port )
{
int sock( ::accept( listener, NULL, 0 ) );
if ( sock < 0 ) {
if ( errno == EWOULDBLOCK ) {
// non-block, when no resource is available
// std::cerr << "EWOULDBLOCK\n";
return;
} else if ( errno == EAGAIN ) {
// non-block, when no resource is available
std::cerr << "EAGAIN\n";
return;
} else if ( errno == EPERM ) {
std::cerr << "EPERM\n";
return;
} else if ( sock < 0 ) {
std::cerr << "sock error = " << sock << std::endl;
perror( "No connection." );
return;
}
std::cerr << "accept() failed\n";
return;
}
std::cerr << "Connected at " << sock << std::endl;
// set the socket as non-blocking before returning it
fcntl( sock, F_SETFL, O_NONBLOCK );
m_open[ sock ] = new connected_socket_c( sock, port );
}
void connection_acceptor_c::close_socket( int socket )
{
connection_iterator it( m_open.find( socket ) );
if ( it == m_open.end() ) {
return;
}
delete it->second;
m_open.erase( it->first );
}
<|endoftext|>
|
<commit_before>//
// TextureBuilder.hpp
// Clock Signal
//
// Created by Thomas Harte on 08/03/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#ifndef Outputs_CRT_Internals_TextureBuilder_hpp
#define Outputs_CRT_Internals_TextureBuilder_hpp
#include <cstdint>
#include <memory>
#include <vector>
#include "OpenGL.hpp"
#include "CRTConstants.hpp"
namespace Outputs {
namespace CRT {
/*!
Owns an OpenGL texture resource and provides mechanisms to fill it from bottom left to top right
with runs of data, ensuring each run is neighboured immediately to the left and right by copies of its
first and last pixels.
*/
class TextureBuilder {
public:
/// Constructs an instance of InputTextureBuilder that contains a texture of colour depth @c bytes_per_pixel;
/// this creates a new texture and binds it to the current active texture unit.
TextureBuilder(size_t bytes_per_pixel);
virtual ~TextureBuilder();
/// Finds the first available space of at least @c required_length pixels in size. Calls must be paired off
/// with calls to @c reduce_previous_allocation_to.
/// @returns a pointer to the allocated space if any was available; @c nullptr otherwise.
uint8_t *allocate_write_area(size_t required_length);
/// Announces that the owner is finished with the region created by the most recent @c allocate_write_area
/// and indicates that its actual final size was @c actual_length.
void reduce_previous_allocation_to(size_t actual_length);
/// @returns the start column for the most recent allocated write area.
uint16_t get_last_write_x_position();
/// @returns the row of the most recent allocated write area.
uint16_t get_last_write_y_position();
/// @returns @c true if all future calls to @c allocate_write_area will fail on account of the input texture
/// being full; @c false if calls may succeed.
bool is_full();
/// Updates the currently-bound texture with all new data provided since the last @c submit.
void submit();
private:
// where pixel data will be put to the next time a write is requested
uint16_t next_write_x_position_, next_write_y_position_;
// the most recent position returned for pixel data writing
uint16_t write_x_position_, write_y_position_;
// details of the most recent allocation
size_t write_target_pointer_;
size_t last_allocation_amount_;
// the buffer size
size_t bytes_per_pixel_;
// the buffer
std::vector<uint8_t> image_;
GLuint texture_name_;
};
}
}
#endif /* CRTInputBufferBuilder_hpp */
<commit_msg>Fixed comment.<commit_after>//
// TextureBuilder.hpp
// Clock Signal
//
// Created by Thomas Harte on 08/03/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#ifndef Outputs_CRT_Internals_TextureBuilder_hpp
#define Outputs_CRT_Internals_TextureBuilder_hpp
#include <cstdint>
#include <memory>
#include <vector>
#include "OpenGL.hpp"
#include "CRTConstants.hpp"
namespace Outputs {
namespace CRT {
/*!
Owns an OpenGL texture resource and provides mechanisms to fill it from bottom left to top right
with runs of data, ensuring each run is neighboured immediately to the left and right by copies of its
first and last pixels.
*/
class TextureBuilder {
public:
/// Constructs an instance of InputTextureBuilder that contains a texture of colour depth @c bytes_per_pixel;
/// this creates a new texture and binds it to the current active texture unit.
TextureBuilder(size_t bytes_per_pixel);
virtual ~TextureBuilder();
/// Finds the first available space of at least @c required_length pixels in size. Calls must be paired off
/// with calls to @c reduce_previous_allocation_to.
/// @returns a pointer to the allocated space if any was available; @c nullptr otherwise.
uint8_t *allocate_write_area(size_t required_length);
/// Announces that the owner is finished with the region created by the most recent @c allocate_write_area
/// and indicates that its actual final size was @c actual_length.
void reduce_previous_allocation_to(size_t actual_length);
/// @returns the start column for the most recent allocated write area.
uint16_t get_last_write_x_position();
/// @returns the row of the most recent allocated write area.
uint16_t get_last_write_y_position();
/// @returns @c true if all future calls to @c allocate_write_area will fail on account of the input texture
/// being full; @c false if calls may succeed.
bool is_full();
/// Updates the currently-bound texture with all new data provided since the last @c submit.
void submit();
private:
// where pixel data will be put to the next time a write is requested
uint16_t next_write_x_position_, next_write_y_position_;
// the most recent position returned for pixel data writing
uint16_t write_x_position_, write_y_position_;
// details of the most recent allocation
size_t write_target_pointer_;
size_t last_allocation_amount_;
// the buffer size
size_t bytes_per_pixel_;
// the buffer
std::vector<uint8_t> image_;
GLuint texture_name_;
};
}
}
#endif /* Outputs_CRT_Internals_TextureBuilder_hpp */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: lineinfo.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2004-08-23 08:36:41 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SW_LINEINFO_HXX
#define SW_LINEINFO_HXX
#ifndef _CALBCK_HXX
#include "calbck.hxx"
#endif
#ifndef _NUMRULE_HXX
#include "numrule.hxx"
#endif
#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
class SwCharFmt;
class SwDoc;
enum LineNumberPosition
{
LINENUMBER_POS_LEFT,
LINENUMBER_POS_RIGHT,
LINENUMBER_POS_INSIDE,
LINENUMBER_POS_OUTSIDE
};
class SW_DLLPUBLIC SwLineNumberInfo : public SwClient //purpose of derivation from SwClient:
//character style for displaying the numbers.
{
SvxNumberType aType; //e.g. roman linenumbers
String aDivider; //String for aditional interval (vert. lines user defined)
USHORT nPosFromLeft; //Position for paint
USHORT nCountBy; //Paint only for every n line
USHORT nDividerCountBy; //Interval for display of an user defined
//string every n lines
LineNumberPosition ePos; //Where should the display occur (number and divicer)
BOOL bPaintLineNumbers; //Should anything be displayed?
BOOL bCountBlankLines; //Count empty lines?
BOOL bCountInFlys; //Count also within FlyFrames?
BOOL bRestartEachPage; //Restart counting at the first paragraph of each page
//(even on follows when paragraphs are splitted)
public:
SwLineNumberInfo();
SwLineNumberInfo(const SwLineNumberInfo&);
SwLineNumberInfo& operator=(const SwLineNumberInfo&);
BOOL operator==( const SwLineNumberInfo& rInf ) const;
SwCharFmt *GetCharFmt(SwDoc &rDoc) const;
void SetCharFmt( SwCharFmt* );
const SvxNumberType &GetNumType() const { return aType; }
void SetNumType( SvxNumberType aNew ){ aType = aNew; }
const String &GetDivider() const { return aDivider; }
void SetDivider( const String &r ) { aDivider = r; }
USHORT GetDividerCountBy() const { return nDividerCountBy; }
void SetDividerCountBy( USHORT n ) { nDividerCountBy = n; }
USHORT GetPosFromLeft() const { return nPosFromLeft; }
void SetPosFromLeft( USHORT n) { nPosFromLeft = n; }
USHORT GetCountBy() const { return nCountBy; }
void SetCountBy( USHORT n) { nCountBy = n; }
LineNumberPosition GetPos() const { return ePos; }
void SetPos( LineNumberPosition eP ){ ePos = eP; }
BOOL IsPaintLineNumbers() const { return bPaintLineNumbers; }
void SetPaintLineNumbers( BOOL b ){ bPaintLineNumbers = b; }
BOOL IsCountBlankLines() const { return bCountBlankLines; }
void SetCountBlankLines( BOOL b ) { bCountBlankLines = b; }
BOOL IsCountInFlys() const { return bCountInFlys; }
void SetCountInFlys( BOOL b ) { bCountInFlys = b; }
BOOL IsRestartEachPage() const { return bRestartEachPage; }
void SetRestartEachPage( BOOL b ) { bRestartEachPage = b; }
virtual void Modify( SfxPoolItem*, SfxPoolItem* );
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.596); FILE MERGED 2005/09/05 13:36:16 rt 1.3.596.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: lineinfo.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 01:59:57 $
*
* 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 SW_LINEINFO_HXX
#define SW_LINEINFO_HXX
#ifndef _CALBCK_HXX
#include "calbck.hxx"
#endif
#ifndef _NUMRULE_HXX
#include "numrule.hxx"
#endif
#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
class SwCharFmt;
class SwDoc;
enum LineNumberPosition
{
LINENUMBER_POS_LEFT,
LINENUMBER_POS_RIGHT,
LINENUMBER_POS_INSIDE,
LINENUMBER_POS_OUTSIDE
};
class SW_DLLPUBLIC SwLineNumberInfo : public SwClient //purpose of derivation from SwClient:
//character style for displaying the numbers.
{
SvxNumberType aType; //e.g. roman linenumbers
String aDivider; //String for aditional interval (vert. lines user defined)
USHORT nPosFromLeft; //Position for paint
USHORT nCountBy; //Paint only for every n line
USHORT nDividerCountBy; //Interval for display of an user defined
//string every n lines
LineNumberPosition ePos; //Where should the display occur (number and divicer)
BOOL bPaintLineNumbers; //Should anything be displayed?
BOOL bCountBlankLines; //Count empty lines?
BOOL bCountInFlys; //Count also within FlyFrames?
BOOL bRestartEachPage; //Restart counting at the first paragraph of each page
//(even on follows when paragraphs are splitted)
public:
SwLineNumberInfo();
SwLineNumberInfo(const SwLineNumberInfo&);
SwLineNumberInfo& operator=(const SwLineNumberInfo&);
BOOL operator==( const SwLineNumberInfo& rInf ) const;
SwCharFmt *GetCharFmt(SwDoc &rDoc) const;
void SetCharFmt( SwCharFmt* );
const SvxNumberType &GetNumType() const { return aType; }
void SetNumType( SvxNumberType aNew ){ aType = aNew; }
const String &GetDivider() const { return aDivider; }
void SetDivider( const String &r ) { aDivider = r; }
USHORT GetDividerCountBy() const { return nDividerCountBy; }
void SetDividerCountBy( USHORT n ) { nDividerCountBy = n; }
USHORT GetPosFromLeft() const { return nPosFromLeft; }
void SetPosFromLeft( USHORT n) { nPosFromLeft = n; }
USHORT GetCountBy() const { return nCountBy; }
void SetCountBy( USHORT n) { nCountBy = n; }
LineNumberPosition GetPos() const { return ePos; }
void SetPos( LineNumberPosition eP ){ ePos = eP; }
BOOL IsPaintLineNumbers() const { return bPaintLineNumbers; }
void SetPaintLineNumbers( BOOL b ){ bPaintLineNumbers = b; }
BOOL IsCountBlankLines() const { return bCountBlankLines; }
void SetCountBlankLines( BOOL b ) { bCountBlankLines = b; }
BOOL IsCountInFlys() const { return bCountInFlys; }
void SetCountInFlys( BOOL b ) { bCountInFlys = b; }
BOOL IsRestartEachPage() const { return bRestartEachPage; }
void SetRestartEachPage( BOOL b ) { bRestartEachPage = b; }
virtual void Modify( SfxPoolItem*, SfxPoolItem* );
};
#endif
<|endoftext|>
|
<commit_before>#include "components/camera.hpp"
#include "components/collision.hpp"
#include "components/player.hpp"
#include "components/render.hpp"
#include "components/transform.hpp"
#include "components/velocity.hpp"
#include "data.hpp"
#include "exception.hpp"
#include <fstream>
#include <iostream>
#include <map>
namespace core
{
const std::string component_name_camera{"camera"};
const std::string component_name_collision{"collision"};
const std::string component_name_player{"player"};
const std::string component_name_texture{"texture"};
const std::string component_name_transform{"transform"};
const std::string component_name_velocity{"velocity"};
void DataReader::factory_component_player(
const Json::Value data, anax::Entity entity)
{
const std::string prop_move_accel{"move_accel"};
const std::string prop_top_speed{"top_speed"};
check_required_component_property(
data, component_name_player, prop_move_accel);
float move_accel = data[prop_move_accel].asFloat();
check_required_component_property(
data, component_name_player, prop_top_speed);
float top_speed = data[prop_top_speed].asFloat();
entity.addComponent<components::PlayerComponent>(move_accel, top_speed);
}
void DataReader::factory_component_camera(
const Json::Value data, anax::Entity entity)
{
const std::string prop_zoom{"zoom"};
const std::string prop_target{"target"};
float zoom = data.get(prop_zoom, 1.0f).asFloat();
check_required_component_property(data, component_name_camera, prop_target);
std::string target = data[prop_target].asString();
auto player = m_map_entities[target];
entity.addComponent<components::CameraComponent>(player, zoom);
}
void DataReader::factory_component_collision(
const Json::Value data, anax::Entity entity)
{
const std::string prop_x{"x"};
const std::string prop_y{"y"};
const std::string prop_h{"h"};
const std::string prop_w{"w"};
const std::string prop_causeevents{"cancauseevents"};
int x = data.get(prop_x, 0).asInt();
int y = data.get(prop_y, 0).asInt();
check_required_component_property(data, component_name_collision, prop_w);
check_required_component_property(data, component_name_collision, prop_h);
check_required_component_property(
data, component_name_collision, prop_causeevents);
int h = data[prop_h].asInt();
int w = data[prop_w].asInt();
bool cancauseevents = data[prop_causeevents].asBool();
entity.addComponent<components::Collision>(x, y, h, w, cancauseevents);
}
void DataReader::factory_component_texture(
const Json::Value data, anax::Entity entity)
{
const std::string prop_texture_path{"texture_path"};
check_required_component_property(
data, component_name_texture, prop_texture_path);
std::string texture_path = data[prop_texture_path].asString();
entity.addComponent<components::TextureComponent>(texture_path);
}
void DataReader::factory_component_transform(
const Json::Value data, anax::Entity entity)
{
const std::string prop_pos_x{"pos_x"};
const std::string prop_pos_y{"pos_y"};
const std::string prop_size_x{"size_x"};
const std::string prop_size_y{"size_y"};
const std::string prop_rotation{"rotation"};
const std::string prop_flip_horiz{"flip_horiz"};
const std::string prop_flip_vert{"flip_vert"};
check_required_component_property(
data, component_name_transform, prop_pos_x);
float pos_x = data[prop_pos_x].asFloat();
check_required_component_property(
data, component_name_transform, prop_pos_y);
float pos_y = data[prop_pos_y].asFloat();
check_required_component_property(
data, component_name_transform, prop_size_x);
float size_x = data[prop_size_x].asFloat();
check_required_component_property(
data, component_name_transform, prop_size_y);
float size_y = data[prop_size_y].asFloat();
check_required_component_property(
data, component_name_transform, prop_rotation);
float rotation = data[prop_rotation].asFloat();
check_required_component_property(
data, component_name_transform, prop_flip_vert);
bool flip_vert = data[prop_flip_vert].asBool();
check_required_component_property(
data, component_name_transform, prop_flip_horiz);
bool flip_horiz = data[prop_flip_horiz].asBool();
entity.addComponent<components::TransformComponent>(
pos_x, pos_y, size_x, size_y, rotation, flip_vert, flip_horiz);
}
void DataReader::factory_component_velocity(
const Json::Value data, anax::Entity entity)
{
const std::string prop_mass{"mass"};
const std::string prop_friction{"friction"};
const std::string prop_force_x{"force_x"};
const std::string prop_force_y{"force_y"};
const float prop_force_x_default = 0.0f;
const float prop_force_y_default = 0.0f;
const std::string prop_vel_x{"vel_x"};
const std::string prop_vel_y{"vel_y"};
const float prop_vel_x_default = 0.0f;
const float prop_vel_y_default = 0.0f;
float velocity_x = data.get(prop_vel_x, prop_vel_x_default).asFloat();
float velocity_y = data.get(prop_vel_y, prop_vel_y_default).asFloat();
float force_x = data.get(prop_force_x, prop_force_x_default).asFloat();
float force_y = data.get(prop_force_y, prop_force_y_default).asFloat();
check_required_component_property(data, component_name_velocity, prop_mass);
float mass = data[prop_mass].asFloat();
check_required_component_property(
data, component_name_velocity, prop_friction);
float friction = data[prop_friction].asFloat();
entity.addComponent<components::VelocityComponent>(
mass, friction, velocity_x, velocity_y, force_x, force_y);
}
DataReader::DataReader(std::string filename) : JsonFileReader(filename)
{
m_sp_logger = logging_get_logger("data");
component_factories.insert(std::make_pair(
component_name_camera, &DataReader::factory_component_camera));
component_factories.insert(std::make_pair(
component_name_collision, &DataReader::factory_component_collision));
component_factories.insert(std::make_pair(
component_name_player, &DataReader::factory_component_player));
component_factories.insert(std::make_pair(
component_name_texture, &DataReader::factory_component_texture));
component_factories.insert(std::make_pair(
component_name_transform, &DataReader::factory_component_transform));
component_factories.insert(std::make_pair(
component_name_velocity, &DataReader::factory_component_velocity));
}
anax::Entity DataReader::makeEntity(std::string entityname, anax::World& world)
{
const std::string prop_name_components{"components"};
const std::string prop_name_template{"template"};
if (!m_json_data.isMember(entityname))
{
m_sp_logger->error("JSON data {} missing referenced entity {}",
m_str_description,
entityname);
throw ExceptionParseFailure(
m_str_description, "Missing referenced entity");
}
auto entity = world.createEntity();
Json::Value entity_data;
if (m_json_data[entityname].isMember(prop_name_template))
{
std::string templatename =
m_json_data[entityname][prop_name_template].asString();
m_sp_logger->info(
"Using template {} for entity {}", templatename, entityname);
entity_data = merge_values(
m_map_references[templatename], m_json_data[entityname]);
}
else
{
entity_data = m_json_data[entityname];
}
if (!entity_data.isMember(prop_name_components))
{
m_sp_logger->error("JSON data {} entity {} missing {}",
m_str_description,
entityname,
prop_name_components);
throw ExceptionParseFailure(
m_str_description, "JSON data entity missing components");
}
auto components = entity_data[prop_name_components];
m_sp_logger->info("Components list for entity name {} size {}",
entityname,
components.size());
Json::Value::Members member_names = components.getMemberNames();
for (auto type : member_names)
{
m_sp_logger->info("Creating component {}", type);
factory_method fp = component_factories[type];
(this->*fp)(components[type], entity);
}
entity.activate();
return entity;
}
void DataReader::makeEntities(anax::World& world)
{
const std::string object_name_world{"world"};
const std::string prop_name_entities{"entities"};
scan_references(m_json_data);
if (!m_json_data.isMember(object_name_world))
{
m_sp_logger->error(
"JSON data {} missing {}", m_str_description, object_name_world);
throw ExceptionParseFailure(
m_str_description, "JSON Data missing world");
}
if (!m_json_data[object_name_world].isMember(prop_name_entities))
{
m_sp_logger->error("JSON data {} world missing {}",
m_str_description,
prop_name_entities);
throw ExceptionParseFailure(
m_str_description, "JSON Data world missing entities");
}
auto entities = m_json_data[object_name_world][prop_name_entities];
m_sp_logger->info("Entities list for world size {}", entities.size());
for (auto value : entities)
{
std::string name = value.asString();
auto entity = makeEntity(name, world);
m_map_entities.insert({name, entity});
}
}
LevelReader::LevelReader(std::string filename) : JsonFileReader(filename)
{
m_sp_logger = logging_get_logger("data");
}
void LevelReader::build_level(std::unique_ptr<Level>& up_level)
{
uint16_t size_x = m_json_data["width"].asInt();
uint16_t size_y = m_json_data["height"].asInt();
float tileheight = m_json_data["tileheight"].asFloat();
up_level = std::make_unique<Level>(size_x, size_y, tileheight);
auto p_level = up_level.get();
// TODO(Keegan): Use tilewidth as well
auto tilesets = m_json_data["tilesets"];
std::string tileset_source;
for (auto it = tilesets.begin(); it != tilesets.end(); ++it)
{
int firstgid = (*it)["firstgid"].asInt();
tileset_source = (*it)["source"].asString();
m_sp_logger->info(
"Found a tileset gid {} source {}", firstgid, tileset_source);
}
// Only load last tileset for now
auto p_tileset = load_tileset(tileset_source);
p_level->set_tileset(p_tileset);
auto layers = m_json_data["layers"];
for (auto it = layers.begin(); it != layers.end(); ++it)
{
int height = (*it)["height"].asInt();
int width = (*it)["width"].asInt();
float opacity = (*it)["opacity"].asFloat();
std::string name = (*it)["name"].asString();
m_sp_logger->info(
"found a layer named {} width {} height {} opacity {}",
name,
width,
height,
opacity);
auto data = (*it)["data"];
for (uint16_t index = 0; index < data.size(); ++index)
{
uint16_t tile_x = index % width;
uint16_t tile_y = index / width;
int16_t tilegid = data[index].asInt();
p_level->set(tile_x, tile_y, tilegid);
}
}
return;
}
LevelTileSet* LevelReader::load_tileset(std::string filename)
{
Json::Reader reader_json;
filename.insert(0, "data/");
m_sp_logger->info("Loading data from {}", filename);
std::ifstream config_file(filename, std::ifstream::binary);
if (!reader_json.parse(config_file, m_json_tileset))
{
m_sp_logger->error(
"Failed to parse JSON file {}:", filename, "JSON format error");
m_sp_logger->error(reader_json.getFormattedErrorMessages());
throw ExceptionParseFailure(
m_str_description, std::string("JSON format error"));
}
std::string image_filename = m_json_tileset["image"].asString();
std::string name = m_json_tileset["name"].asString();
uint16_t tilewidth = m_json_tileset["tilewidth"].asInt();
uint16_t tileheight = m_json_tileset["tilewidth"].asInt();
uint16_t tilecount = m_json_tileset["tilecount"].asInt();
uint16_t columns = m_json_tileset["columns"].asInt();
uint16_t margin = m_json_tileset["margin"].asInt();
uint16_t spacing = m_json_tileset["spacing"].asInt();
return new LevelTileSet{name,
image_filename,
columns,
tilecount,
tilewidth,
tileheight,
spacing,
margin};
}
} // namespace core
<commit_msg>Data: Read level scale from json file<commit_after>#include "components/camera.hpp"
#include "components/collision.hpp"
#include "components/player.hpp"
#include "components/render.hpp"
#include "components/transform.hpp"
#include "components/velocity.hpp"
#include "data.hpp"
#include "exception.hpp"
#include <fstream>
#include <iostream>
#include <map>
namespace core
{
const std::string component_name_camera{"camera"};
const std::string component_name_collision{"collision"};
const std::string component_name_player{"player"};
const std::string component_name_texture{"texture"};
const std::string component_name_transform{"transform"};
const std::string component_name_velocity{"velocity"};
void DataReader::factory_component_player(
const Json::Value data, anax::Entity entity)
{
const std::string prop_move_accel{"move_accel"};
const std::string prop_top_speed{"top_speed"};
check_required_component_property(
data, component_name_player, prop_move_accel);
float move_accel = data[prop_move_accel].asFloat();
check_required_component_property(
data, component_name_player, prop_top_speed);
float top_speed = data[prop_top_speed].asFloat();
entity.addComponent<components::PlayerComponent>(move_accel, top_speed);
}
void DataReader::factory_component_camera(
const Json::Value data, anax::Entity entity)
{
const std::string prop_zoom{"zoom"};
const std::string prop_target{"target"};
float zoom = data.get(prop_zoom, 1.0f).asFloat();
check_required_component_property(data, component_name_camera, prop_target);
std::string target = data[prop_target].asString();
auto player = m_map_entities[target];
entity.addComponent<components::CameraComponent>(player, zoom);
}
void DataReader::factory_component_collision(
const Json::Value data, anax::Entity entity)
{
const std::string prop_x{"x"};
const std::string prop_y{"y"};
const std::string prop_h{"h"};
const std::string prop_w{"w"};
const std::string prop_causeevents{"cancauseevents"};
int x = data.get(prop_x, 0).asInt();
int y = data.get(prop_y, 0).asInt();
check_required_component_property(data, component_name_collision, prop_w);
check_required_component_property(data, component_name_collision, prop_h);
check_required_component_property(
data, component_name_collision, prop_causeevents);
int h = data[prop_h].asInt();
int w = data[prop_w].asInt();
bool cancauseevents = data[prop_causeevents].asBool();
entity.addComponent<components::Collision>(x, y, h, w, cancauseevents);
}
void DataReader::factory_component_texture(
const Json::Value data, anax::Entity entity)
{
const std::string prop_texture_path{"texture_path"};
check_required_component_property(
data, component_name_texture, prop_texture_path);
std::string texture_path = data[prop_texture_path].asString();
entity.addComponent<components::TextureComponent>(texture_path);
}
void DataReader::factory_component_transform(
const Json::Value data, anax::Entity entity)
{
const std::string prop_pos_x{"pos_x"};
const std::string prop_pos_y{"pos_y"};
const std::string prop_size_x{"size_x"};
const std::string prop_size_y{"size_y"};
const std::string prop_rotation{"rotation"};
const std::string prop_flip_horiz{"flip_horiz"};
const std::string prop_flip_vert{"flip_vert"};
check_required_component_property(
data, component_name_transform, prop_pos_x);
float pos_x = data[prop_pos_x].asFloat();
check_required_component_property(
data, component_name_transform, prop_pos_y);
float pos_y = data[prop_pos_y].asFloat();
check_required_component_property(
data, component_name_transform, prop_size_x);
float size_x = data[prop_size_x].asFloat();
check_required_component_property(
data, component_name_transform, prop_size_y);
float size_y = data[prop_size_y].asFloat();
check_required_component_property(
data, component_name_transform, prop_rotation);
float rotation = data[prop_rotation].asFloat();
check_required_component_property(
data, component_name_transform, prop_flip_vert);
bool flip_vert = data[prop_flip_vert].asBool();
check_required_component_property(
data, component_name_transform, prop_flip_horiz);
bool flip_horiz = data[prop_flip_horiz].asBool();
entity.addComponent<components::TransformComponent>(
pos_x, pos_y, size_x, size_y, rotation, flip_vert, flip_horiz);
}
void DataReader::factory_component_velocity(
const Json::Value data, anax::Entity entity)
{
const std::string prop_mass{"mass"};
const std::string prop_friction{"friction"};
const std::string prop_force_x{"force_x"};
const std::string prop_force_y{"force_y"};
const float prop_force_x_default = 0.0f;
const float prop_force_y_default = 0.0f;
const std::string prop_vel_x{"vel_x"};
const std::string prop_vel_y{"vel_y"};
const float prop_vel_x_default = 0.0f;
const float prop_vel_y_default = 0.0f;
float velocity_x = data.get(prop_vel_x, prop_vel_x_default).asFloat();
float velocity_y = data.get(prop_vel_y, prop_vel_y_default).asFloat();
float force_x = data.get(prop_force_x, prop_force_x_default).asFloat();
float force_y = data.get(prop_force_y, prop_force_y_default).asFloat();
check_required_component_property(data, component_name_velocity, prop_mass);
float mass = data[prop_mass].asFloat();
check_required_component_property(
data, component_name_velocity, prop_friction);
float friction = data[prop_friction].asFloat();
entity.addComponent<components::VelocityComponent>(
mass, friction, velocity_x, velocity_y, force_x, force_y);
}
DataReader::DataReader(std::string filename) : JsonFileReader(filename)
{
m_sp_logger = logging_get_logger("data");
component_factories.insert(std::make_pair(
component_name_camera, &DataReader::factory_component_camera));
component_factories.insert(std::make_pair(
component_name_collision, &DataReader::factory_component_collision));
component_factories.insert(std::make_pair(
component_name_player, &DataReader::factory_component_player));
component_factories.insert(std::make_pair(
component_name_texture, &DataReader::factory_component_texture));
component_factories.insert(std::make_pair(
component_name_transform, &DataReader::factory_component_transform));
component_factories.insert(std::make_pair(
component_name_velocity, &DataReader::factory_component_velocity));
}
anax::Entity DataReader::makeEntity(std::string entityname, anax::World& world)
{
const std::string prop_name_components{"components"};
const std::string prop_name_template{"template"};
if (!m_json_data.isMember(entityname))
{
m_sp_logger->error("JSON data {} missing referenced entity {}",
m_str_description,
entityname);
throw ExceptionParseFailure(
m_str_description, "Missing referenced entity");
}
auto entity = world.createEntity();
Json::Value entity_data;
if (m_json_data[entityname].isMember(prop_name_template))
{
std::string templatename =
m_json_data[entityname][prop_name_template].asString();
m_sp_logger->info(
"Using template {} for entity {}", templatename, entityname);
entity_data = merge_values(
m_map_references[templatename], m_json_data[entityname]);
}
else
{
entity_data = m_json_data[entityname];
}
if (!entity_data.isMember(prop_name_components))
{
m_sp_logger->error("JSON data {} entity {} missing {}",
m_str_description,
entityname,
prop_name_components);
throw ExceptionParseFailure(
m_str_description, "JSON data entity missing components");
}
auto components = entity_data[prop_name_components];
m_sp_logger->info("Components list for entity name {} size {}",
entityname,
components.size());
Json::Value::Members member_names = components.getMemberNames();
for (auto type : member_names)
{
m_sp_logger->info("Creating component {}", type);
factory_method fp = component_factories[type];
(this->*fp)(components[type], entity);
}
entity.activate();
return entity;
}
void DataReader::makeEntities(anax::World& world)
{
const std::string object_name_world{"world"};
const std::string prop_name_entities{"entities"};
scan_references(m_json_data);
if (!m_json_data.isMember(object_name_world))
{
m_sp_logger->error(
"JSON data {} missing {}", m_str_description, object_name_world);
throw ExceptionParseFailure(
m_str_description, "JSON Data missing world");
}
if (!m_json_data[object_name_world].isMember(prop_name_entities))
{
m_sp_logger->error("JSON data {} world missing {}",
m_str_description,
prop_name_entities);
throw ExceptionParseFailure(
m_str_description, "JSON Data world missing entities");
}
auto entities = m_json_data[object_name_world][prop_name_entities];
m_sp_logger->info("Entities list for world size {}", entities.size());
for (auto value : entities)
{
std::string name = value.asString();
auto entity = makeEntity(name, world);
m_map_entities.insert({name, entity});
}
}
LevelReader::LevelReader(std::string filename) : JsonFileReader(filename)
{
m_sp_logger = logging_get_logger("data");
}
void LevelReader::build_level(std::unique_ptr<Level>& up_level)
{
uint16_t size_x = m_json_data["width"].asInt();
uint16_t size_y = m_json_data["height"].asInt();
float tileheight = m_json_data["tileheight"].asFloat();
float scale = m_json_data["properties"].get("scale", 1.0).asFloat();
up_level = std::make_unique<Level>(size_x, size_y, tileheight * scale);
auto p_level = up_level.get();
// TODO(Keegan): Use tilewidth as well
auto tilesets = m_json_data["tilesets"];
std::string tileset_source;
for (auto it = tilesets.begin(); it != tilesets.end(); ++it)
{
int firstgid = (*it)["firstgid"].asInt();
tileset_source = (*it)["source"].asString();
m_sp_logger->info(
"Found a tileset gid {} source {}", firstgid, tileset_source);
}
// Only load last tileset for now
auto p_tileset = load_tileset(tileset_source);
p_level->set_tileset(p_tileset);
auto layers = m_json_data["layers"];
for (auto it = layers.begin(); it != layers.end(); ++it)
{
int height = (*it)["height"].asInt();
int width = (*it)["width"].asInt();
float opacity = (*it)["opacity"].asFloat();
std::string name = (*it)["name"].asString();
m_sp_logger->info(
"found a layer named {} width {} height {} opacity {}",
name,
width,
height,
opacity);
auto data = (*it)["data"];
for (uint16_t index = 0; index < data.size(); ++index)
{
uint16_t tile_x = index % width;
uint16_t tile_y = index / width;
int16_t tilegid = data[index].asInt();
p_level->set(tile_x, tile_y, tilegid);
}
}
return;
}
LevelTileSet* LevelReader::load_tileset(std::string filename)
{
Json::Reader reader_json;
filename.insert(0, "data/");
m_sp_logger->info("Loading data from {}", filename);
std::ifstream config_file(filename, std::ifstream::binary);
if (!reader_json.parse(config_file, m_json_tileset))
{
m_sp_logger->error(
"Failed to parse JSON file {}:", filename, "JSON format error");
m_sp_logger->error(reader_json.getFormattedErrorMessages());
throw ExceptionParseFailure(
m_str_description, std::string("JSON format error"));
}
std::string image_filename = m_json_tileset["image"].asString();
std::string name = m_json_tileset["name"].asString();
uint16_t tilewidth = m_json_tileset["tilewidth"].asInt();
uint16_t tileheight = m_json_tileset["tilewidth"].asInt();
uint16_t tilecount = m_json_tileset["tilecount"].asInt();
uint16_t columns = m_json_tileset["columns"].asInt();
uint16_t margin = m_json_tileset["margin"].asInt();
uint16_t spacing = m_json_tileset["spacing"].asInt();
return new LevelTileSet{name,
image_filename,
columns,
tilecount,
tilewidth,
tileheight,
spacing,
margin};
}
} // namespace core
<|endoftext|>
|
<commit_before>#include <gdb.hpp>
#include <array>
#include <cassert>
namespace narcissus {
//XXX
namespace h8_3069f {
gdb_server::gdb_server(
std::array<std::uint8_t, (std::uint32_t)h8_3069f::mem_info::rom_size>&& memory,
boost::asio::io_service& io_service,
std::uint16_t port)
: cpu_(std::make_shared<h8_3069f::cpu>(std::move(memory))),
acceptor_(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)),
socket_(io_service)
{}
auto gdb_server::run() -> void
{
cpu_->before_run();
acceptor_.accept(socket_);
try
{
while (true)
{
std::array<char, 1024> data{0};
boost::system::error_code error;
size_t length = socket_.read_some(boost::asio::buffer(data), error);
if(error == boost::asio::error::eof)
{
std::cout << "eof" << std::endl;
break;
}
else if(error)
{
throw boost::system::system_error(error);
}
std::cout << "receive: " << std::string(data.data()) << std::endl;
// auto r = work(data, length);
work(data, length);
// if(!r.empty())
// {
// std::cout << "send: " << r.c_str() << std::endl;
// boost::asio::write(socket_, boost::asio::buffer(r.c_str(), r.length()));
// }
}
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
auto gdb_server::work(std::array<char, 1024>& data, size_t length)
-> void
{
auto i = 0;
for ( i = 0; i < length; i++) {
if(data[i] == '$')
{
break;
}
}
if(i >= length)
{
return;
}
std::stringstream stream;
auto ack = [this]
{
boost::asio::write(socket_, boost::asio::buffer("+", 1));
};
auto reply = [this](std::string s)
{
std::stringstream stream;
stream << "$" << s << "#"
<< std::hex << std::setfill('0') << std::setw(2)
<< (check_sum(s.c_str()) % 0x100);
boost::asio::write(socket_, boost::asio::buffer(stream.str().c_str(), stream.str().length()));
};
switch (data[++i]) {
// read register
case '?':
{
//$?#3f
ack();
reply("T001");
// std::string reply("T001");
// stream << "$" << reply << "#"
// << std::hex << std::setfill('0') << std::setw(2)
// << (check_sum(reply.c_str()) % 0x100);
// return stream.str();
break;
}
// return cpu register
case 'g':
assert(false);
break;
// single step
case 's':
{
auto pc = cpu_->cycle();
assert(false);
}
case 'q':
{
switch (data[++i]) {
case 'a':
{
//$qAttached#8f
ack();
reply("l");
break;
}
case 'S':
{
//$qSupported:multiprocess+;swbreak+;hwbreak+;qRelocInsn+#c9
ack();
reply("multiprocess-");
// std::string stubfeature("multiprocess-");
// stream << "$" << stubfeature << "#"
// << std::hex << std::setfill('0') << std::setw(2)
// << (check_sum(stubfeature.c_str()) % 0x100);
break;
// return stream.str();
}
case 'T':
{
switch (data[++i]) {
case 'S':
{
//$qTStatus#49
ack();
reply("T0;tnotrun:0");
break;
// std::string stubfeature("T0;tnotrun:0");
// stream << "$" << stubfeature << "#"
// << std::hex << std::setfill('0') << std::setw(2)
// << (check_sum(stubfeature.c_str()) % 0x100);
// return stream.str();
}
case 'f':
{
//TODO $qTfV#81
ack();
reply("1:0000000000000000:1:61");
break;
// std::string qtfv("1:0000000000000000:1:61");
// stream << "$" << qtfv << "#"
// << std::hex << std::setfill('0') << std::setw(2)
// << (check_sum(qtfv.c_str()) % 0x100);
// return stream.str();
}
case 's':
{
//$qTsV#8e
ack();
reply("l");
break;
// std::string qtsv("1:0000000000000000:1:61");
// std::string qtsv("l");
// stream << "$" << qtsv << "#"
// << std::hex << std::setfill('0') << std::setw(2)
// << (check_sum(qtsv.c_str()) % 0x100);
// return stream.str();
}
}
}
case 'f':
{
switch(data[++i]){
case 'T':
{
//$qfThreadInfo#bb
ack();
reply("m 0");
break;
// return reply("m 0");
}
}
}
case 's':
{
switch (data[++i]) {
case 'T':
//$qsThreadInfo#c8+
ack();
reply("l");
break;
}
}
}
}
case '+':
{
reply("");
break;
// return "";
}
// case 'H':
// {
// return "OK";
// }
default:
{
//TODO
//$Hg0#df
// assert(false);
ack();
reply("");
break;
// boost::asio::write(socket_, boost::asio::buffer("+", 1));
// boost::asio::write(socket_, boost::asio::buffer("$#00", 4));
// return "$#00";
}
}
}
auto gdb_server::interrupt(::narcissus::h8_3069f::interrupts int_num) -> bool
{
return cpu_->interrupt(int_num);
}
//XXX
} // namespace h8_3069f
} // namespace narcissus
<commit_msg>delete code<commit_after>#include <gdb.hpp>
#include <array>
#include <cassert>
namespace narcissus {
//XXX
namespace h8_3069f {
gdb_server::gdb_server(
std::array<std::uint8_t, (std::uint32_t)h8_3069f::mem_info::rom_size>&& memory,
boost::asio::io_service& io_service,
std::uint16_t port)
: cpu_(std::make_shared<h8_3069f::cpu>(std::move(memory))),
acceptor_(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)),
socket_(io_service)
{}
auto gdb_server::run() -> void
{
cpu_->before_run();
acceptor_.accept(socket_);
try
{
while (true)
{
std::array<char, 1024> data{0};
boost::system::error_code error;
size_t length = socket_.read_some(boost::asio::buffer(data), error);
if(error == boost::asio::error::eof)
{
std::cout << "eof" << std::endl;
break;
}
else if(error)
{
throw boost::system::system_error(error);
}
std::cout << "receive: " << std::string(data.data()) << std::endl;
// auto r = work(data, length);
work(data, length);
// if(!r.empty())
// {
// std::cout << "send: " << r.c_str() << std::endl;
// boost::asio::write(socket_, boost::asio::buffer(r.c_str(), r.length()));
// }
}
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
auto gdb_server::work(std::array<char, 1024>& data, size_t length)
-> void
{
auto i = 0;
for ( i = 0; i < length; i++) {
if(data[i] == '$')
{
break;
}
}
if(i >= length)
{
return;
}
std::stringstream stream;
auto ack = [this]
{
boost::asio::write(socket_, boost::asio::buffer("+", 1));
};
auto reply = [this](std::string s)
{
std::stringstream stream;
stream << "$" << s << "#"
<< std::hex << std::setfill('0') << std::setw(2)
<< (check_sum(s.c_str()) % 0x100);
boost::asio::write(socket_, boost::asio::buffer(stream.str().c_str(), stream.str().length()));
};
switch (data[++i]) {
// read register
case '?':
{
//$?#3f
ack();
reply("T001");
break;
}
// return cpu register
case 'g':
assert(false);
break;
// single step
case 's':
{
auto pc = cpu_->cycle();
assert(false);
}
case 'q':
{
switch (data[++i]) {
case 'A':
{
//$qAttached#8f
ack();
reply("l");
break;
}
case 'C':
{
//$qC#b4
assert(false);
}
case 'S':
{
//$qSupported:multiprocess+;swbreak+;hwbreak+;qRelocInsn+#c9
ack();
reply("multiprocess-");
break;
}
case 'T':
{
switch (data[++i]) {
case 'S':
{
//$qTStatus#49
ack();
reply("T0;tnotrun:0");
break;
}
case 'f':
{
//TODO $qTfV#81
ack();
reply("1:0000000000000000:1:61");
break;
}
case 's':
{
//$qTsV#8e
ack();
reply("l");
break;
}
}
}
case 'f':
{
switch(data[++i]){
case 'T':
{
//$qfThreadInfo#bb
ack();
reply("m 0");
break;
}
}
}
case 's':
{
switch (data[++i]) {
case 'T':
//$qsThreadInfo#c8+
ack();
reply("l");
break;
}
}
}
}
case '+':
{
reply("");
break;
}
default:
{
//TODO
//$Hg0#df
ack();
reply("");
break;
}
}
}
auto gdb_server::interrupt(::narcissus::h8_3069f::interrupts int_num) -> bool
{
return cpu_->interrupt(int_num);
}
//XXX
} // namespace h8_3069f
} // namespace narcissus
<|endoftext|>
|
<commit_before>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <iostream>
// Local includes
#include "libmesh.h"
#include "auto_ptr.h"
#include "getpot.h"
#include "reference_counter.h"
#include "remote_elem.h"
#include "threads.h"
#if defined(HAVE_MPI)
# include <mpi.h>
# include "petsc_macro.h"
# if defined(HAVE_PETSC)
EXTERN_C_FOR_PETSC_BEGIN
# include <petsc.h>
# include <petscerror.h>
EXTERN_C_FOR_PETSC_END
# endif // #if defined(HAVE_PETSC)
# if defined(HAVE_SLEPC)
EXTERN_C_FOR_PETSC_BEGIN
# include <slepc.h>
EXTERN_C_FOR_PETSC_END
# endif // #if defined(HAVE_SLEPC)
#endif // #if defined(HAVE_MPI)
// --------------------------------------------------------
// Local anonymous namespace to hold miscelaneous variables
namespace {
AutoPtr<GetPot> command_line (NULL);
AutoPtr<Threads::task_scheduler_init> task_scheduler (NULL);
#if defined(HAVE_MPI)
bool libmesh_initialized_mpi = false;
#endif
}
// ------------------------------------------------------------
// libMeshdata initialization
#ifdef HAVE_MPI
MPI_Comm libMesh::COMM_WORLD = MPI_COMM_NULL;
#endif
PerfLog libMesh::perflog ("libMesh",
#ifdef ENABLE_PERFORMANCE_LOGGING
true
#else
false
#endif
);
const Real libMesh::pi = 3.1415926535897932384626433832795029L;
#ifdef USE_COMPLEX_NUMBERS
const Number libMesh::imaginary (0., 1.);
const Number libMesh::zero (0., 0.);
#else
const Number libMesh::zero = 0.;
#endif
const unsigned int libMesh::invalid_uint = static_cast<unsigned int>(-1);
// ------------------------------------------------------------
// libMesh::libMeshPrivateData data initialization
int libMesh::libMeshPrivateData::_n_processors = 1;
int libMesh::libMeshPrivateData::_processor_id = 0;
int libMesh::libMeshPrivateData::_n_threads = 1; /* Threads::task_scheduler_init::automatic; */
bool libMesh::libMeshPrivateData::_is_initialized = false;
SolverPackage libMesh::libMeshPrivateData::_solver_package =
#if defined(HAVE_PETSC) // PETSc is the default
PETSC_SOLVERS;
#elif defined(HAVE_TRILINOS) // Use Trilinos if PETSc isn't there
TRILINOS_SOLVERS;
#elif defined(HAVE_LASPACK) // Use LASPACK if neither are there
LASPACK_SOLVERS;
#else // No valid linear solver package at compile time
INVALID_SOLVER_PACKAGE;
#endif
// ------------------------------------------------------------
// libMesh functions
namespace libMesh {
#ifndef HAVE_MPI
void _init (int &argc, char** & argv)
#else
void _init (int &argc, char** & argv,
MPI_Comm COMM_WORLD_IN)
#endif
{
// should _not_ be initialized already.
libmesh_assert (!libMesh::initialized());
// Build a command-line parser.
command_line.reset (new GetPot (argc, argv));
// Build a task scheduler
{
// Get the requested number of threads, defaults to 1 to avoid MPI and
// multithreading competition. If you would like to use MPI and multithreading
// at the same time then (n_mpi_processes_per_node)x(n_threads) should be the
// number of processing cores per node.
libMesh::libMeshPrivateData::_n_threads =
libMesh::command_line_value ("--n_threads", 1);
task_scheduler.reset (new Threads::task_scheduler_init(libMesh::n_threads()));
}
// Construct singletons who may be at risk of the
// "static initialization order fiasco"
//
// RemoteElem depends on static reference counting data
remote_elem = new RemoteElem();
#if defined(HAVE_MPI)
// Allow the user to bypass PETSc initialization
if (!libMesh::on_command_line ("--disable-mpi"))
{
int flag;
MPI_Initialized (&flag);
if (!flag)
{
MPI_Init (&argc, &argv);
libmesh_initialized_mpi = true;
}
// Duplicate the input communicator for internal use
MPI_Comm_dup (COMM_WORLD_IN, &libMesh::COMM_WORLD);
//MPI_Comm_set_name not supported in at least SGI MPT's MPI implementation
//MPI_Comm_set_name (libMesh::COMM_WORLD, "libMesh::COMM_WORLD");
MPI_Comm_rank (libMesh::COMM_WORLD, &libMeshPrivateData::_processor_id);
MPI_Comm_size (libMesh::COMM_WORLD, &libMeshPrivateData::_n_processors);
# if defined(HAVE_PETSC)
if (!libMesh::on_command_line ("--disable-petsc"))
{
int ierr=0;
PETSC_COMM_WORLD = libMesh::COMM_WORLD;
# if defined(HAVE_SLEPC)
ierr = SlepcInitialize (&argc, &argv, NULL, NULL);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
# else
ierr = PetscInitialize (&argc, &argv, NULL, NULL);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
# endif
}
# endif
}
#else
// No MPI, can only be uniprocessor
libmesh_assert (libMeshPrivateData::_n_processors == 1);
libmesh_assert (libMeshPrivateData::_processor_id == 0);
#endif
// Could we have gotten bad values from the above calls?
libmesh_assert (libMeshPrivateData::_n_processors > 0);
libmesh_assert (libMeshPrivateData::_processor_id >= 0);
// Re-parse the command-line arguments. Note that PETSc and MPI
// initialization above may have removed command line arguments
// that are not relevant to this application in the above calls.
// We don't want a false-positive by detecting those arguments.
command_line->parse_command_line (argc, argv);
// The following line is an optimization when simultaneous
// C and C++ style access to output streams is not required.
// The amount of benefit which occurs is probably implementation
// defined, and may be nothing. On the other hand, I have seen
// some IO tests where IO peformance improves by a factor of two.
if (!libMesh::on_command_line ("--sync-with-stdio"))
std::ios::sync_with_stdio(false);
// redirect std::cout to nothing on all
// other processors unless explicitly told
// not to via the --keep-cout command-line argument.
if (libMesh::processor_id() != 0)
if (!libMesh::on_command_line ("--keep-cout"))
std::cout.rdbuf (NULL);
// The library is now ready for use
libMeshPrivateData::_is_initialized = true;
// Make sure these work. Library methods
// depend on these being implemented properly,
// so this is a good time to test them!
libmesh_assert (libMesh::initialized());
libmesh_assert (!libMesh::closed());
}
int _close ()
{
// Delete reference counted singleton(s)
delete remote_elem;
// Clear the thread task manager we started
task_scheduler.reset();
#if defined(HAVE_MPI)
// Allow the user to bypass MPI finalization
if (!libMesh::on_command_line ("--disable-mpi"))
{
// We may be here in only one process,
// because an uncaught libmesh_error() exception
// called the LibMeshInit destructor.
//
// If that's the case, we need to MPI_Abort(),
// not just wait for other processes that
// might never get to MPI_Finalize()
if (libmesh_initialized_mpi &&
std::uncaught_exception())
{
std::cerr << "Uncaught exception - aborting" << std::endl;
MPI_Abort(libMesh::COMM_WORLD,1);
}
# if defined(HAVE_PETSC)
// Allow the user to bypass PETSc finalization
if (!libMesh::on_command_line ("--disable-petsc"))
{
# if defined(HAVE_SLEPC)
SlepcFinalize();
# else
PetscFinalize();
# endif
}
# endif
MPI_Comm_free (&libMesh::COMM_WORLD);
if (libmesh_initialized_mpi)
MPI_Finalize();
}
#endif
// Force the \p ReferenceCounter to print
// its reference count information. This allows
// us to find memory leaks. By default the
// \p ReferenceCounter only prints its information
// when the last created object has been destroyed.
// That does no good if we are leaking memory!
ReferenceCounter::print_info ();
// Print an informative message if we detect a memory leak
if (ReferenceCounter::n_objects() != 0)
{
std::cerr << "Memory leak detected!"
<< std::endl;
#if !defined(ENABLE_REFERENCE_COUNTING) || defined(NDEBUG)
std::cerr << "Compile in DEBUG mode with --enable-reference-counting"
<< std::endl
<< "for more information"
<< std::endl;
#endif
}
// Reconnect the output streams
// (don't do this, or we will get messages from objects
// that go out of scope after the following return)
//std::cout.rdbuf(std::cerr.rdbuf());
// Set the initialized() flag to false
libMeshPrivateData::_is_initialized = false;
// Return the number of outstanding objects.
// This is equivalent to return 0 if all of
// the reference counted objects have been
// deleted.
return static_cast<int>(ReferenceCounter::n_objects());
}
}
#ifndef HAVE_MPI
void libMesh::init (int &argc, char** & argv)
{
deprecated(); // Use LibMeshInit instead
libMesh::_init(argc, argv);
}
#else
void libMesh::init (int &argc, char** & argv,
MPI_Comm COMM_WORLD_IN)
{
deprecated(); // Use LibMeshInit instead
libMesh::_init(argc, argv, COMM_WORLD_IN);
}
#endif
int libMesh::close ()
{
deprecated(); // Use LibMeshInit instead
return libMesh::_close();
}
#ifndef HAVE_MPI
LibMeshInit::LibMeshInit (int &argc, char** & argv)
{
libMesh::_init(argc, argv);
}
#else
LibMeshInit::LibMeshInit (int &argc, char** & argv,
MPI_Comm COMM_WORLD_IN)
{
libMesh::_init(argc, argv, COMM_WORLD_IN);
}
#endif
LibMeshInit::~LibMeshInit()
{
libMesh::_close();
}
bool libMesh::on_command_line (const std::string& arg)
{
// Make sure the command line parser is ready for use
libmesh_assert (command_line.get() != NULL);
return command_line->search (arg);
}
template <typename T>
T libMesh::command_line_value (const std::string &name, T value)
{
// Make sure the command line parser is ready for use
libmesh_assert (command_line.get() != NULL);
// only if the variable exists in the file
if (command_line->have_variable(name.c_str()))
value = (*command_line)(name.c_str(), value);
return value;
}
SolverPackage libMesh::default_solver_package ()
{
libmesh_assert (libMesh::initialized());
static bool called = false;
// Check the command line. Since the command line is
// unchanging it is sufficient to do this only once.
if (!called)
{
called = true;
#ifdef HAVE_PETSC
if (libMesh::on_command_line ("--use-petsc"))
libMeshPrivateData::_solver_package = PETSC_SOLVERS;
#endif
#ifdef HAVE_TRILINOS
if (libMesh::on_command_line ("--use-trilinos") ||
libMesh::on_command_line ("--disable-petsc"))
libMeshPrivateData::_solver_package = TRILINOS_SOLVERS;
#endif
#ifdef HAVE_LASPACK
if (libMesh::on_command_line ("--use-laspack" ) ||
libMesh::on_command_line ("--disable-petsc"))
libMeshPrivateData::_solver_package = LASPACK_SOLVERS;
#endif
if (libMesh::on_command_line ("--disable-laspack") &&
libMesh::on_command_line ("--disable-trilinos") &&
libMesh::on_command_line ("--disable-petsc"))
libMeshPrivateData::_solver_package = INVALID_SOLVER_PACKAGE;
}
return libMeshPrivateData::_solver_package;
}
//-------------------------------------------------------------------------------
template int libMesh::command_line_value<int> (const std::string&, int);
template Real libMesh::command_line_value<Real> (const std::string&, Real);
template std::string libMesh::command_line_value<std::string> (const std::string&, std::string);
<commit_msg>added command-line option --redirect-stdout. When specified each processor sends std::cout and std::cerr to a file named stdout.processor.PID<commit_after>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <iostream>
#include <fstream>
// Local includes
#include "libmesh.h"
#include "auto_ptr.h"
#include "getpot.h"
#include "reference_counter.h"
#include "remote_elem.h"
#include "threads.h"
#if defined(HAVE_MPI)
# include <mpi.h>
# include "petsc_macro.h"
# if defined(HAVE_PETSC)
EXTERN_C_FOR_PETSC_BEGIN
# include <petsc.h>
# include <petscerror.h>
EXTERN_C_FOR_PETSC_END
# endif // #if defined(HAVE_PETSC)
# if defined(HAVE_SLEPC)
EXTERN_C_FOR_PETSC_BEGIN
# include <slepc.h>
EXTERN_C_FOR_PETSC_END
# endif // #if defined(HAVE_SLEPC)
#endif // #if defined(HAVE_MPI)
// --------------------------------------------------------
// Local anonymous namespace to hold miscelaneous variables
namespace {
AutoPtr<GetPot> command_line (NULL);
AutoPtr<std::ofstream> _ofstream (NULL);
AutoPtr<Threads::task_scheduler_init> task_scheduler (NULL);
#if defined(HAVE_MPI)
bool libmesh_initialized_mpi = false;
#endif
}
// ------------------------------------------------------------
// libMeshdata initialization
#ifdef HAVE_MPI
MPI_Comm libMesh::COMM_WORLD = MPI_COMM_NULL;
#endif
PerfLog libMesh::perflog ("libMesh",
#ifdef ENABLE_PERFORMANCE_LOGGING
true
#else
false
#endif
);
const Real libMesh::pi = 3.1415926535897932384626433832795029L;
#ifdef USE_COMPLEX_NUMBERS
const Number libMesh::imaginary (0., 1.);
const Number libMesh::zero (0., 0.);
#else
const Number libMesh::zero = 0.;
#endif
const unsigned int libMesh::invalid_uint = static_cast<unsigned int>(-1);
// ------------------------------------------------------------
// libMesh::libMeshPrivateData data initialization
int libMesh::libMeshPrivateData::_n_processors = 1;
int libMesh::libMeshPrivateData::_processor_id = 0;
int libMesh::libMeshPrivateData::_n_threads = 1; /* Threads::task_scheduler_init::automatic; */
bool libMesh::libMeshPrivateData::_is_initialized = false;
SolverPackage libMesh::libMeshPrivateData::_solver_package =
#if defined(HAVE_PETSC) // PETSc is the default
PETSC_SOLVERS;
#elif defined(HAVE_TRILINOS) // Use Trilinos if PETSc isn't there
TRILINOS_SOLVERS;
#elif defined(HAVE_LASPACK) // Use LASPACK if neither are there
LASPACK_SOLVERS;
#else // No valid linear solver package at compile time
INVALID_SOLVER_PACKAGE;
#endif
// ------------------------------------------------------------
// libMesh functions
namespace libMesh {
#ifndef HAVE_MPI
void _init (int &argc, char** & argv)
#else
void _init (int &argc, char** & argv,
MPI_Comm COMM_WORLD_IN)
#endif
{
// should _not_ be initialized already.
libmesh_assert (!libMesh::initialized());
// Build a command-line parser.
command_line.reset (new GetPot (argc, argv));
// Build a task scheduler
{
// Get the requested number of threads, defaults to 1 to avoid MPI and
// multithreading competition. If you would like to use MPI and multithreading
// at the same time then (n_mpi_processes_per_node)x(n_threads) should be the
// number of processing cores per node.
libMesh::libMeshPrivateData::_n_threads =
libMesh::command_line_value ("--n_threads", 1);
task_scheduler.reset (new Threads::task_scheduler_init(libMesh::n_threads()));
}
// Construct singletons who may be at risk of the
// "static initialization order fiasco"
//
// RemoteElem depends on static reference counting data
remote_elem = new RemoteElem();
#if defined(HAVE_MPI)
// Allow the user to bypass PETSc initialization
if (!libMesh::on_command_line ("--disable-mpi"))
{
int flag;
MPI_Initialized (&flag);
if (!flag)
{
MPI_Init (&argc, &argv);
libmesh_initialized_mpi = true;
}
// Duplicate the input communicator for internal use
MPI_Comm_dup (COMM_WORLD_IN, &libMesh::COMM_WORLD);
//MPI_Comm_set_name not supported in at least SGI MPT's MPI implementation
//MPI_Comm_set_name (libMesh::COMM_WORLD, "libMesh::COMM_WORLD");
MPI_Comm_rank (libMesh::COMM_WORLD, &libMeshPrivateData::_processor_id);
MPI_Comm_size (libMesh::COMM_WORLD, &libMeshPrivateData::_n_processors);
# if defined(HAVE_PETSC)
if (!libMesh::on_command_line ("--disable-petsc"))
{
int ierr=0;
PETSC_COMM_WORLD = libMesh::COMM_WORLD;
# if defined(HAVE_SLEPC)
ierr = SlepcInitialize (&argc, &argv, NULL, NULL);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
# else
ierr = PetscInitialize (&argc, &argv, NULL, NULL);
CHKERRABORT(libMesh::COMM_WORLD,ierr);
# endif
}
# endif
}
#else
// No MPI, can only be uniprocessor
libmesh_assert (libMeshPrivateData::_n_processors == 1);
libmesh_assert (libMeshPrivateData::_processor_id == 0);
#endif
// Could we have gotten bad values from the above calls?
libmesh_assert (libMeshPrivateData::_n_processors > 0);
libmesh_assert (libMeshPrivateData::_processor_id >= 0);
// Re-parse the command-line arguments. Note that PETSc and MPI
// initialization above may have removed command line arguments
// that are not relevant to this application in the above calls.
// We don't want a false-positive by detecting those arguments.
command_line->parse_command_line (argc, argv);
// The following line is an optimization when simultaneous
// C and C++ style access to output streams is not required.
// The amount of benefit which occurs is probably implementation
// defined, and may be nothing. On the other hand, I have seen
// some IO tests where IO peformance improves by a factor of two.
if (!libMesh::on_command_line ("--sync-with-stdio"))
std::ios::sync_with_stdio(false);
// redirect std::cout to nothing on all
// other processors unless explicitly told
// not to via the --keep-cout command-line argument.
if (libMesh::processor_id() != 0)
if (!libMesh::on_command_line ("--keep-cout"))
std::cout.rdbuf (NULL);
// The library is now ready for use
libMeshPrivateData::_is_initialized = true;
// Make sure these work. Library methods
// depend on these being implemented properly,
// so this is a good time to test them!
libmesh_assert (libMesh::initialized());
libmesh_assert (!libMesh::closed());
}
int _close ()
{
// Delete reference counted singleton(s)
delete remote_elem;
// Clear the thread task manager we started
task_scheduler.reset();
#if defined(HAVE_MPI)
// Allow the user to bypass MPI finalization
if (!libMesh::on_command_line ("--disable-mpi"))
{
// We may be here in only one process,
// because an uncaught libmesh_error() exception
// called the LibMeshInit destructor.
//
// If that's the case, we need to MPI_Abort(),
// not just wait for other processes that
// might never get to MPI_Finalize()
if (libmesh_initialized_mpi &&
std::uncaught_exception())
{
std::cerr << "Uncaught exception - aborting" << std::endl;
MPI_Abort(libMesh::COMM_WORLD,1);
}
# if defined(HAVE_PETSC)
// Allow the user to bypass PETSc finalization
if (!libMesh::on_command_line ("--disable-petsc"))
{
# if defined(HAVE_SLEPC)
SlepcFinalize();
# else
PetscFinalize();
# endif
}
# endif
MPI_Comm_free (&libMesh::COMM_WORLD);
if (libmesh_initialized_mpi)
MPI_Finalize();
}
#endif
// Force the \p ReferenceCounter to print
// its reference count information. This allows
// us to find memory leaks. By default the
// \p ReferenceCounter only prints its information
// when the last created object has been destroyed.
// That does no good if we are leaking memory!
ReferenceCounter::print_info ();
// Print an informative message if we detect a memory leak
if (ReferenceCounter::n_objects() != 0)
{
std::cerr << "Memory leak detected!"
<< std::endl;
#if !defined(ENABLE_REFERENCE_COUNTING) || defined(NDEBUG)
std::cerr << "Compile in DEBUG mode with --enable-reference-counting"
<< std::endl
<< "for more information"
<< std::endl;
#endif
}
// Reconnect the output streams
// (don't do this, or we will get messages from objects
// that go out of scope after the following return)
//std::cout.rdbuf(std::cerr.rdbuf());
// Set the initialized() flag to false
libMeshPrivateData::_is_initialized = false;
// Return the number of outstanding objects.
// This is equivalent to return 0 if all of
// the reference counted objects have been
// deleted.
return static_cast<int>(ReferenceCounter::n_objects());
}
}
#ifndef HAVE_MPI
void libMesh::init (int &argc, char** & argv)
{
deprecated(); // Use LibMeshInit instead
libMesh::_init(argc, argv);
}
#else
void libMesh::init (int &argc, char** & argv,
MPI_Comm COMM_WORLD_IN)
{
deprecated(); // Use LibMeshInit instead
libMesh::_init(argc, argv, COMM_WORLD_IN);
}
#endif
int libMesh::close ()
{
deprecated(); // Use LibMeshInit instead
return libMesh::_close();
}
#ifndef HAVE_MPI
LibMeshInit::LibMeshInit (int &argc, char** & argv)
{
libMesh::_init(argc, argv);
}
#else
LibMeshInit::LibMeshInit (int &argc, char** & argv,
MPI_Comm COMM_WORLD_IN)
{
libMesh::_init(argc, argv, COMM_WORLD_IN);
// Honor the --redirect-stdout command-line option.
// When this is specified each processor sends
// std::cout/std::cerr messages to
// stdout.processor.####
if (libMesh::on_command_line ("--redirect-stdout"))
{
char filechar[80];
sprintf (filechar, "stdout.processor.%04d",
libMesh::processor_id());
_ofstream.reset (new std::ofstream (filechar));
std::cout.rdbuf (_ofstream->rdbuf());
std::cerr.rdbuf (_ofstream->rdbuf());
}
}
#endif
LibMeshInit::~LibMeshInit()
{
libMesh::_close();
}
bool libMesh::on_command_line (const std::string& arg)
{
// Make sure the command line parser is ready for use
libmesh_assert (command_line.get() != NULL);
return command_line->search (arg);
}
template <typename T>
T libMesh::command_line_value (const std::string &name, T value)
{
// Make sure the command line parser is ready for use
libmesh_assert (command_line.get() != NULL);
// only if the variable exists in the file
if (command_line->have_variable(name.c_str()))
value = (*command_line)(name.c_str(), value);
return value;
}
SolverPackage libMesh::default_solver_package ()
{
libmesh_assert (libMesh::initialized());
static bool called = false;
// Check the command line. Since the command line is
// unchanging it is sufficient to do this only once.
if (!called)
{
called = true;
#ifdef HAVE_PETSC
if (libMesh::on_command_line ("--use-petsc"))
libMeshPrivateData::_solver_package = PETSC_SOLVERS;
#endif
#ifdef HAVE_TRILINOS
if (libMesh::on_command_line ("--use-trilinos") ||
libMesh::on_command_line ("--disable-petsc"))
libMeshPrivateData::_solver_package = TRILINOS_SOLVERS;
#endif
#ifdef HAVE_LASPACK
if (libMesh::on_command_line ("--use-laspack" ) ||
libMesh::on_command_line ("--disable-petsc"))
libMeshPrivateData::_solver_package = LASPACK_SOLVERS;
#endif
if (libMesh::on_command_line ("--disable-laspack") &&
libMesh::on_command_line ("--disable-trilinos") &&
libMesh::on_command_line ("--disable-petsc"))
libMeshPrivateData::_solver_package = INVALID_SOLVER_PACKAGE;
}
return libMeshPrivateData::_solver_package;
}
//-------------------------------------------------------------------------------
template int libMesh::command_line_value<int> (const std::string&, int);
template Real libMesh::command_line_value<Real> (const std::string&, Real);
template std::string libMesh::command_line_value<std::string> (const std::string&, std::string);
<|endoftext|>
|
<commit_before>// $Id: fe_clough.C,v 1.3 2005-02-23 03:42:16 roystgnr Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson,
// Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Local includes
#include "dense_matrix.h"
#include "dense_vector.h"
#include "dof_map.h"
#include "elem.h"
#include "fe.h"
#include "fe_interface.h"
#include "quadrature_clough.h"
// ------------------------------------------------------------
// Hierarchic-specific implementations
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::nodal_soln(const Elem* elem,
const Order order,
const std::vector<Number>& elem_soln,
std::vector<Number>& nodal_soln)
{
const unsigned int n_nodes = elem->n_nodes();
const ElemType type = elem->type();
nodal_soln.resize(n_nodes);
switch (order)
{
// Piecewise cubic shape functions only
case THIRD:
{
const unsigned int n_sf =
FE<Dim,T>::n_shape_functions(type, order);
for (unsigned int n=0; n<n_nodes; n++)
{
const Point mapped_point = FE<Dim,T>::inverse_map(elem,
elem->point(n));
assert (elem_soln.size() == n_sf);
// Zero before summation
nodal_soln[n] = 0;
// u_i = Sum (alpha_i phi_i)
for (unsigned int i=0; i<n_sf; i++)
nodal_soln[n] += elem_soln[i]*FE<Dim,T>::shape(elem,
order,
i,
mapped_point);
}
return;
}
default:
{
error();
}
}
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs(const ElemType t, const Order o)
{
switch (o)
{
// Piecewise cubic Clough-Tocher element
case THIRD:
{
switch (t)
{
case TRI6:
return 12;
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
default:
{
error();
}
}
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs_at_node(const ElemType t,
const Order o,
const unsigned int n)
{
switch (o)
{
// The third-order hierarchic shape functions
case THIRD:
{
switch (t)
{
// The 2D Clough-Tocher defined on a 6-noded triangle
case TRI6:
{
switch (n)
{
case 0:
case 1:
case 2:
return 3;
case 3:
case 4:
case 5:
return 1;
default:
error();
}
}
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
default:
{
error();
}
}
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs_per_elem(const ElemType t,
const Order o)
{
switch (o)
{
// The third-order Clough-Tocher shape functions
case THIRD:
{
switch (t)
{
// The 2D hierarchic defined on a 6-noded triangle
case TRI6:
return 0;
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
// Otherwise no DOFS per element
default:
error();
return 0;
}
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::compute_constraints (std::map<unsigned int,
std::map<unsigned int, float> > &
constraints,
DofMap &dof_map,
const unsigned int variable_number,
const Elem* elem)
{
// Only constrain elements in 2,3D.
if (Dim == 1)
return;
assert (elem != NULL);
const FEType& fe_type = dof_map.variable_type(variable_number);
AutoPtr<FEBase> my_fe (FEBase::build(Dim, fe_type));
AutoPtr<FEBase> parent_fe (FEBase::build(Dim, fe_type));
QClough my_qface(Dim-1, fe_type.default_quadrature_order());
my_fe->attach_quadrature_rule (&my_qface);
std::vector<Point> parent_qface;
const std::vector<Real>& JxW = my_fe->get_JxW();
const std::vector<Point>& q_point = my_fe->get_xyz();
const std::vector<std::vector<Real> >& phi = my_fe->get_phi();
const std::vector<std::vector<Real> >& parent_phi =
parent_fe->get_phi();
const std::vector<Point>& face_normals = my_fe->get_normals();
const std::vector<std::vector<RealGradient> >& dphi =
my_fe->get_dphi();
const std::vector<std::vector<RealGradient> >& parent_dphi =
parent_fe->get_dphi();
const std::vector<unsigned int> child_dof_indices;
const std::vector<unsigned int> parent_dof_indices;
DenseMatrix<Number> Ke;
DenseVector<Number> Fe;
std::vector<DenseVector<Number> > Ue;
// Look at the element faces. Check to see if we need to
// build constraints.
for (unsigned int s=0; s<elem->n_sides(); s++)
if (elem->neighbor(s) != NULL)
// constrain dofs shared between
// this element and ones coarser
// than this element.
if (elem->neighbor(s)->level() < elem->level())
{
// FIXME: hanging nodes aren't working yet!
std::cerr << "Error: hanging nodes not yet implemented for "
<< "Clough-Tocher elements!" << std::endl;
error();
// Get pointers to the elements of interest and its parent.
const Elem* parent = elem->parent();
// This can't happen... Only level-0 elements have NULL
// parents, and no level-0 elements can be at a higher
// level than their neighbors!
assert (parent != NULL);
my_fe->reinit(elem, s);
const AutoPtr<Elem> my_side (elem->build_side(s));
const AutoPtr<Elem> parent_side (parent->build_side(s));
const unsigned int n_dofs = FEInterface::n_dofs(Dim-1,
fe_type,
my_side->type());
assert(n_dofs == FEInterface::n_dofs(Dim-1, fe_type,
parent_side->type()));
const unsigned int n_qp = my_qface.n_points();
FEInterface::inverse_map (Dim, fe_type, parent, q_point,
parent_qface);
parent_fe->reinit(parent, &parent_qface);
Ke.resize (n_dofs, n_dofs);
Ue.resize(n_dofs);
for (unsigned int i = 0; i != n_dofs; ++i)
for (unsigned int j = 0; j != n_dofs; ++j)
for (unsigned int qp = 0; qp != n_qp; ++qp)
Ke(i,j) += JxW[qp] * (phi[i][qp] * phi[j][qp] +
(dphi[i][qp] *
face_normals[qp]) *
(dphi[j][qp] *
face_normals[qp]));
for (unsigned int i = 0; i != n_dofs; ++i)
{
Fe.resize (n_dofs);
for (unsigned int j = 0; j != n_dofs; ++j)
for (unsigned int qp = 0; qp != n_qp; ++qp)
Fe(j) += JxW[qp] * (parent_phi[i][qp] * phi[j][qp] +
(parent_dphi[i][qp] *
face_normals[qp]) *
(dphi[j][qp] *
face_normals[qp]));
Ke.cholesky_solve(Fe, Ue[i]);
}
}
}
template <unsigned int Dim, FEFamily T>
bool FE<Dim,T>::shapes_need_reinit() const
{
return true;
}
//--------------------------------------------------------------
// Explicit instantiations
template class FE<1,CLOUGH>; // FIXME: 1D Not yet functional!
template class FE<2,CLOUGH>;
template class FE<3,CLOUGH>; // FIXME: 2D Not yet functional!
<commit_msg><commit_after>// $Id: fe_clough.C,v 1.4 2005-02-23 03:53:17 roystgnr Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson,
// Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Local includes
#include "dense_matrix.h"
#include "dense_vector.h"
#include "dof_map.h"
#include "elem.h"
#include "fe.h"
#include "fe_interface.h"
#include "quadrature_clough.h"
// ------------------------------------------------------------
// Hierarchic-specific implementations
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::nodal_soln(const Elem* elem,
const Order order,
const std::vector<Number>& elem_soln,
std::vector<Number>& nodal_soln)
{
const unsigned int n_nodes = elem->n_nodes();
const ElemType type = elem->type();
nodal_soln.resize(n_nodes);
switch (order)
{
// Piecewise cubic shape functions only
case THIRD:
{
const unsigned int n_sf =
FE<Dim,T>::n_shape_functions(type, order);
for (unsigned int n=0; n<n_nodes; n++)
{
const Point mapped_point = FE<Dim,T>::inverse_map(elem,
elem->point(n));
assert (elem_soln.size() == n_sf);
// Zero before summation
nodal_soln[n] = 0;
// u_i = Sum (alpha_i phi_i)
for (unsigned int i=0; i<n_sf; i++)
nodal_soln[n] += elem_soln[i]*FE<Dim,T>::shape(elem,
order,
i,
mapped_point);
}
return;
}
default:
{
error();
}
}
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs(const ElemType t, const Order o)
{
switch (o)
{
// Piecewise cubic Clough-Tocher element
case THIRD:
{
switch (t)
{
case TRI6:
return 12;
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
default:
{
error();
}
}
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs_at_node(const ElemType t,
const Order o,
const unsigned int n)
{
switch (o)
{
// The third-order hierarchic shape functions
case THIRD:
{
switch (t)
{
// The 2D Clough-Tocher defined on a 6-noded triangle
case TRI6:
{
switch (n)
{
case 0:
case 1:
case 2:
return 3;
case 3:
case 4:
case 5:
return 1;
default:
error();
}
}
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
default:
{
error();
}
}
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs_per_elem(const ElemType t,
const Order o)
{
switch (o)
{
// The third-order Clough-Tocher shape functions
case THIRD:
{
switch (t)
{
// The 2D hierarchic defined on a 6-noded triangle
case TRI6:
return 0;
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
// Otherwise no DOFS per element
default:
error();
return 0;
}
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::compute_constraints (std::map<unsigned int,
std::map<unsigned int, float> > &,
const unsigned int,
const unsigned int,
const FEType& fe_type,
const Elem* elem)
{
// Only constrain elements in 2,3D.
if (Dim == 1)
return;
assert (elem != NULL);
// const FEType& fe_type = dof_map.variable_type(variable_number);
AutoPtr<FEBase> my_fe (FEBase::build(Dim, fe_type));
AutoPtr<FEBase> parent_fe (FEBase::build(Dim, fe_type));
QClough my_qface(Dim-1, fe_type.default_quadrature_order());
my_fe->attach_quadrature_rule (&my_qface);
std::vector<Point> parent_qface;
const std::vector<Real>& JxW = my_fe->get_JxW();
const std::vector<Point>& q_point = my_fe->get_xyz();
const std::vector<std::vector<Real> >& phi = my_fe->get_phi();
const std::vector<std::vector<Real> >& parent_phi =
parent_fe->get_phi();
const std::vector<Point>& face_normals = my_fe->get_normals();
const std::vector<std::vector<RealGradient> >& dphi =
my_fe->get_dphi();
const std::vector<std::vector<RealGradient> >& parent_dphi =
parent_fe->get_dphi();
const std::vector<unsigned int> child_dof_indices;
const std::vector<unsigned int> parent_dof_indices;
DenseMatrix<Number> Ke;
DenseVector<Number> Fe;
std::vector<DenseVector<Number> > Ue;
// Look at the element faces. Check to see if we need to
// build constraints.
for (unsigned int s=0; s<elem->n_sides(); s++)
if (elem->neighbor(s) != NULL)
// constrain dofs shared between
// this element and ones coarser
// than this element.
if (elem->neighbor(s)->level() < elem->level())
{
// FIXME: hanging nodes aren't working yet!
std::cerr << "Error: hanging nodes not yet implemented for "
<< "Clough-Tocher elements!" << std::endl;
error();
// Get pointers to the elements of interest and its parent.
const Elem* parent = elem->parent();
// This can't happen... Only level-0 elements have NULL
// parents, and no level-0 elements can be at a higher
// level than their neighbors!
assert (parent != NULL);
my_fe->reinit(elem, s);
const AutoPtr<Elem> my_side (elem->build_side(s));
const AutoPtr<Elem> parent_side (parent->build_side(s));
const unsigned int n_dofs = FEInterface::n_dofs(Dim-1,
fe_type,
my_side->type());
assert(n_dofs == FEInterface::n_dofs(Dim-1, fe_type,
parent_side->type()));
const unsigned int n_qp = my_qface.n_points();
FEInterface::inverse_map (Dim, fe_type, parent, q_point,
parent_qface);
parent_fe->reinit(parent, &parent_qface);
Ke.resize (n_dofs, n_dofs);
Ue.resize(n_dofs);
for (unsigned int i = 0; i != n_dofs; ++i)
for (unsigned int j = 0; j != n_dofs; ++j)
for (unsigned int qp = 0; qp != n_qp; ++qp)
Ke(i,j) += JxW[qp] * (phi[i][qp] * phi[j][qp] +
(dphi[i][qp] *
face_normals[qp]) *
(dphi[j][qp] *
face_normals[qp]));
for (unsigned int i = 0; i != n_dofs; ++i)
{
Fe.resize (n_dofs);
for (unsigned int j = 0; j != n_dofs; ++j)
for (unsigned int qp = 0; qp != n_qp; ++qp)
Fe(j) += JxW[qp] * (parent_phi[i][qp] * phi[j][qp] +
(parent_dphi[i][qp] *
face_normals[qp]) *
(dphi[j][qp] *
face_normals[qp]));
Ke.cholesky_solve(Fe, Ue[i]);
}
}
}
template <unsigned int Dim, FEFamily T>
bool FE<Dim,T>::shapes_need_reinit() const
{
return true;
}
//--------------------------------------------------------------
// Explicit instantiations
template class FE<1,CLOUGH>; // FIXME: 1D Not yet functional!
template class FE<2,CLOUGH>;
template class FE<3,CLOUGH>; // FIXME: 2D Not yet functional!
<|endoftext|>
|
<commit_before>//===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the "backend" phase of LTO, i.e. it performs
// optimization and code generation on a loaded module. It is generally used
// internally by the LTO class but can also be used independently, for example
// to implement a standalone ThinLTO backend.
//
//===----------------------------------------------------------------------===//
#include "llvm/LTO/LTOBackend.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/CGSCCPassManager.h"
#include "llvm/Analysis/LoopPassManager.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Verifier.h"
#include "llvm/LTO/LTO.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/Passes/PassBuilder.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/ThreadPool.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Transforms/Utils/FunctionImportUtils.h"
#include "llvm/Transforms/Utils/SplitModule.h"
using namespace llvm;
using namespace lto;
Error Config::addSaveTemps(std::string OutputFileName,
bool UseInputModulePath) {
ShouldDiscardValueNames = false;
std::error_code EC;
ResolutionFile = llvm::make_unique<raw_fd_ostream>(
OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
if (EC)
return errorCodeToError(EC);
auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
// Keep track of the hook provided by the linker, which also needs to run.
ModuleHookFn LinkerHook = Hook;
Hook = [=](unsigned Task, const Module &M) {
// If the linker's hook returned false, we need to pass that result
// through.
if (LinkerHook && !LinkerHook(Task, M))
return false;
std::string PathPrefix;
// If this is the combined module (not a ThinLTO backend compile) or the
// user hasn't requested using the input module's path, emit to a file
// named from the provided OutputFileName with the Task ID appended.
if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
PathPrefix = OutputFileName + utostr(Task);
} else
PathPrefix = M.getModuleIdentifier();
std::string Path = PathPrefix + "." + PathSuffix + ".bc";
std::error_code EC;
raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
if (EC) {
// Because -save-temps is a debugging feature, we report the error
// directly and exit.
llvm::errs() << "failed to open " << Path << ": " << EC.message()
<< '\n';
exit(1);
}
WriteBitcodeToFile(&M, OS, /*ShouldPreserveUseListOrder=*/false);
return true;
};
};
setHook("0.preopt", PreOptModuleHook);
setHook("1.promote", PostPromoteModuleHook);
setHook("2.internalize", PostInternalizeModuleHook);
setHook("3.import", PostImportModuleHook);
setHook("4.opt", PostOptModuleHook);
setHook("5.precodegen", PreCodeGenModuleHook);
CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
std::string Path = OutputFileName + "index.bc";
std::error_code EC;
raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
if (EC) {
// Because -save-temps is a debugging feature, we report the error
// directly and exit.
llvm::errs() << "failed to open " << Path << ": " << EC.message() << '\n';
exit(1);
}
WriteIndexToFile(Index, OS);
return true;
};
return Error();
}
namespace {
std::unique_ptr<TargetMachine>
createTargetMachine(Config &Conf, StringRef TheTriple,
const Target *TheTarget) {
SubtargetFeatures Features;
Features.getDefaultSubtargetFeatures(Triple(TheTriple));
for (const std::string &A : Conf.MAttrs)
Features.AddFeature(A);
return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
TheTriple, Conf.CPU, Features.getString(), Conf.Options, Conf.RelocModel,
Conf.CodeModel, Conf.CGOptLevel));
}
static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
std::string PipelineDesc,
bool DisableVerify) {
PassBuilder PB(TM);
AAManager AA;
LoopAnalysisManager LAM;
FunctionAnalysisManager FAM;
CGSCCAnalysisManager CGAM;
ModuleAnalysisManager MAM;
// Register the AA manager first so that our version is the one used.
FAM.registerPass([&] { return std::move(AA); });
// Register all the basic analyses with the managers.
PB.registerModuleAnalyses(MAM);
PB.registerCGSCCAnalyses(CGAM);
PB.registerFunctionAnalyses(FAM);
PB.registerLoopAnalyses(LAM);
PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
ModulePassManager MPM;
// Always verify the input.
MPM.addPass(VerifierPass());
// Now, add all the passes we've been requested to.
if (!PB.parsePassPipeline(MPM, PipelineDesc))
report_fatal_error("unable to parse pass pipeline description: " +
PipelineDesc);
if (!DisableVerify)
MPM.addPass(VerifierPass());
MPM.run(Mod, MAM);
}
static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
bool IsThinLto) {
legacy::PassManager passes;
passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
PassManagerBuilder PMB;
PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
PMB.Inliner = createFunctionInliningPass();
// Unconditionally verify input since it is not verified before this
// point and has unknown origin.
PMB.VerifyInput = true;
PMB.VerifyOutput = !Conf.DisableVerify;
PMB.LoopVectorize = true;
PMB.SLPVectorize = true;
PMB.OptLevel = Conf.OptLevel;
if (IsThinLto)
PMB.populateThinLTOPassManager(passes);
else
PMB.populateLTOPassManager(passes);
passes.run(Mod);
}
bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
bool IsThinLto) {
Mod.setDataLayout(TM->createDataLayout());
if (Conf.OptPipeline.empty())
runOldPMPasses(Conf, Mod, TM, IsThinLto);
else
runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.DisableVerify);
return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
}
/// Monolithic LTO does not support caching (yet), this is a convenient wrapper
/// around AddOutput to workaround this.
static AddOutputFn getUncachedOutputWrapper(AddOutputFn &AddOutput,
unsigned Task) {
return [Task, &AddOutput](unsigned TaskId) {
auto Output = AddOutput(Task);
if (Output->isCachingEnabled() && Output->tryLoadFromCache(""))
report_fatal_error("Cache hit without a valid key?");
assert(Task == TaskId && "Unexpexted TaskId mismatch");
return Output;
};
}
void codegen(Config &Conf, TargetMachine *TM, AddOutputFn AddOutput,
unsigned Task, Module &Mod) {
if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
return;
auto Output = AddOutput(Task);
std::unique_ptr<raw_pwrite_stream> OS = Output->getStream();
legacy::PassManager CodeGenPasses;
if (TM->addPassesToEmitFile(CodeGenPasses, *OS,
TargetMachine::CGFT_ObjectFile))
report_fatal_error("Failed to setup codegen");
CodeGenPasses.run(Mod);
}
void splitCodeGen(Config &C, TargetMachine *TM, AddOutputFn AddOutput,
unsigned ParallelCodeGenParallelismLevel,
std::unique_ptr<Module> Mod) {
ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
unsigned ThreadCount = 0;
const Target *T = &TM->getTarget();
SplitModule(
std::move(Mod), ParallelCodeGenParallelismLevel,
[&](std::unique_ptr<Module> MPart) {
// We want to clone the module in a new context to multi-thread the
// codegen. We do it by serializing partition modules to bitcode
// (while still on the main thread, in order to avoid data races) and
// spinning up new threads which deserialize the partitions into
// separate contexts.
// FIXME: Provide a more direct way to do this in LLVM.
SmallString<0> BC;
raw_svector_ostream BCOS(BC);
WriteBitcodeToFile(MPart.get(), BCOS);
// Enqueue the task
CodegenThreadPool.async(
[&](const SmallString<0> &BC, unsigned ThreadId) {
LTOLLVMContext Ctx(C);
ErrorOr<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
Ctx);
if (!MOrErr)
report_fatal_error("Failed to read bitcode");
std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
std::unique_ptr<TargetMachine> TM =
createTargetMachine(C, MPartInCtx->getTargetTriple(), T);
codegen(C, TM.get(),
getUncachedOutputWrapper(AddOutput, ThreadId), ThreadId,
*MPartInCtx);
},
// Pass BC using std::move to ensure that it get moved rather than
// copied into the thread's context.
std::move(BC), ThreadCount++);
},
false);
}
Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
if (!C.OverrideTriple.empty())
Mod.setTargetTriple(C.OverrideTriple);
else if (Mod.getTargetTriple().empty())
Mod.setTargetTriple(C.DefaultTriple);
std::string Msg;
const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
if (!T)
return make_error<StringError>(Msg, inconvertibleErrorCode());
return T;
}
}
Error lto::backend(Config &C, AddOutputFn AddOutput,
unsigned ParallelCodeGenParallelismLevel,
std::unique_ptr<Module> Mod) {
Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
if (!TOrErr)
return TOrErr.takeError();
std::unique_ptr<TargetMachine> TM =
createTargetMachine(C, Mod->getTargetTriple(), *TOrErr);
if (!C.CodeGenOnly)
if (!opt(C, TM.get(), 0, *Mod, /*IsThinLto=*/false))
return Error();
if (ParallelCodeGenParallelismLevel == 1) {
codegen(C, TM.get(), getUncachedOutputWrapper(AddOutput, 0), 0, *Mod);
} else {
splitCodeGen(C, TM.get(), AddOutput, ParallelCodeGenParallelismLevel,
std::move(Mod));
}
return Error();
}
Error lto::thinBackend(Config &Conf, unsigned Task, AddOutputFn AddOutput,
Module &Mod, ModuleSummaryIndex &CombinedIndex,
const FunctionImporter::ImportMapTy &ImportList,
const GVSummaryMapTy &DefinedGlobals,
MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
if (!TOrErr)
return TOrErr.takeError();
std::unique_ptr<TargetMachine> TM =
createTargetMachine(Conf, Mod.getTargetTriple(), *TOrErr);
if (Conf.CodeGenOnly) {
codegen(Conf, TM.get(), AddOutput, Task, Mod);
return Error();
}
if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
return Error();
renameModuleForThinLTO(Mod, CombinedIndex);
thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
return Error();
if (!DefinedGlobals.empty())
thinLTOInternalizeModule(Mod, DefinedGlobals);
if (Conf.PostInternalizeModuleHook &&
!Conf.PostInternalizeModuleHook(Task, Mod))
return Error();
auto ModuleLoader = [&](StringRef Identifier) {
assert(Mod.getContext().isODRUniquingDebugTypes() &&
"ODR Type uniquing shoudl be enabled on the context");
return std::move(getLazyBitcodeModule(MemoryBuffer::getMemBuffer(
ModuleMap[Identifier], false),
Mod.getContext(),
/*ShouldLazyLoadMetadata=*/true)
.get());
};
FunctionImporter Importer(CombinedIndex, ModuleLoader);
Importer.importFunctions(Mod, ImportList);
if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
return Error();
if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLto=*/true))
return Error();
codegen(Conf, TM.get(), AddOutput, Task, Mod);
return Error();
}
<commit_msg>[lib/LTO] Fix a typo. NFC.<commit_after>//===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the "backend" phase of LTO, i.e. it performs
// optimization and code generation on a loaded module. It is generally used
// internally by the LTO class but can also be used independently, for example
// to implement a standalone ThinLTO backend.
//
//===----------------------------------------------------------------------===//
#include "llvm/LTO/LTOBackend.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/CGSCCPassManager.h"
#include "llvm/Analysis/LoopPassManager.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Verifier.h"
#include "llvm/LTO/LTO.h"
#include "llvm/MC/SubtargetFeature.h"
#include "llvm/Passes/PassBuilder.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/ThreadPool.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Transforms/Utils/FunctionImportUtils.h"
#include "llvm/Transforms/Utils/SplitModule.h"
using namespace llvm;
using namespace lto;
Error Config::addSaveTemps(std::string OutputFileName,
bool UseInputModulePath) {
ShouldDiscardValueNames = false;
std::error_code EC;
ResolutionFile = llvm::make_unique<raw_fd_ostream>(
OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
if (EC)
return errorCodeToError(EC);
auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
// Keep track of the hook provided by the linker, which also needs to run.
ModuleHookFn LinkerHook = Hook;
Hook = [=](unsigned Task, const Module &M) {
// If the linker's hook returned false, we need to pass that result
// through.
if (LinkerHook && !LinkerHook(Task, M))
return false;
std::string PathPrefix;
// If this is the combined module (not a ThinLTO backend compile) or the
// user hasn't requested using the input module's path, emit to a file
// named from the provided OutputFileName with the Task ID appended.
if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
PathPrefix = OutputFileName + utostr(Task);
} else
PathPrefix = M.getModuleIdentifier();
std::string Path = PathPrefix + "." + PathSuffix + ".bc";
std::error_code EC;
raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
if (EC) {
// Because -save-temps is a debugging feature, we report the error
// directly and exit.
llvm::errs() << "failed to open " << Path << ": " << EC.message()
<< '\n';
exit(1);
}
WriteBitcodeToFile(&M, OS, /*ShouldPreserveUseListOrder=*/false);
return true;
};
};
setHook("0.preopt", PreOptModuleHook);
setHook("1.promote", PostPromoteModuleHook);
setHook("2.internalize", PostInternalizeModuleHook);
setHook("3.import", PostImportModuleHook);
setHook("4.opt", PostOptModuleHook);
setHook("5.precodegen", PreCodeGenModuleHook);
CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
std::string Path = OutputFileName + "index.bc";
std::error_code EC;
raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
if (EC) {
// Because -save-temps is a debugging feature, we report the error
// directly and exit.
llvm::errs() << "failed to open " << Path << ": " << EC.message() << '\n';
exit(1);
}
WriteIndexToFile(Index, OS);
return true;
};
return Error();
}
namespace {
std::unique_ptr<TargetMachine>
createTargetMachine(Config &Conf, StringRef TheTriple,
const Target *TheTarget) {
SubtargetFeatures Features;
Features.getDefaultSubtargetFeatures(Triple(TheTriple));
for (const std::string &A : Conf.MAttrs)
Features.AddFeature(A);
return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
TheTriple, Conf.CPU, Features.getString(), Conf.Options, Conf.RelocModel,
Conf.CodeModel, Conf.CGOptLevel));
}
static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
std::string PipelineDesc,
bool DisableVerify) {
PassBuilder PB(TM);
AAManager AA;
LoopAnalysisManager LAM;
FunctionAnalysisManager FAM;
CGSCCAnalysisManager CGAM;
ModuleAnalysisManager MAM;
// Register the AA manager first so that our version is the one used.
FAM.registerPass([&] { return std::move(AA); });
// Register all the basic analyses with the managers.
PB.registerModuleAnalyses(MAM);
PB.registerCGSCCAnalyses(CGAM);
PB.registerFunctionAnalyses(FAM);
PB.registerLoopAnalyses(LAM);
PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
ModulePassManager MPM;
// Always verify the input.
MPM.addPass(VerifierPass());
// Now, add all the passes we've been requested to.
if (!PB.parsePassPipeline(MPM, PipelineDesc))
report_fatal_error("unable to parse pass pipeline description: " +
PipelineDesc);
if (!DisableVerify)
MPM.addPass(VerifierPass());
MPM.run(Mod, MAM);
}
static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
bool IsThinLto) {
legacy::PassManager passes;
passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
PassManagerBuilder PMB;
PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
PMB.Inliner = createFunctionInliningPass();
// Unconditionally verify input since it is not verified before this
// point and has unknown origin.
PMB.VerifyInput = true;
PMB.VerifyOutput = !Conf.DisableVerify;
PMB.LoopVectorize = true;
PMB.SLPVectorize = true;
PMB.OptLevel = Conf.OptLevel;
if (IsThinLto)
PMB.populateThinLTOPassManager(passes);
else
PMB.populateLTOPassManager(passes);
passes.run(Mod);
}
bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
bool IsThinLto) {
Mod.setDataLayout(TM->createDataLayout());
if (Conf.OptPipeline.empty())
runOldPMPasses(Conf, Mod, TM, IsThinLto);
else
runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.DisableVerify);
return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
}
/// Monolithic LTO does not support caching (yet), this is a convenient wrapper
/// around AddOutput to workaround this.
static AddOutputFn getUncachedOutputWrapper(AddOutputFn &AddOutput,
unsigned Task) {
return [Task, &AddOutput](unsigned TaskId) {
auto Output = AddOutput(Task);
if (Output->isCachingEnabled() && Output->tryLoadFromCache(""))
report_fatal_error("Cache hit without a valid key?");
assert(Task == TaskId && "Unexpexted TaskId mismatch");
return Output;
};
}
void codegen(Config &Conf, TargetMachine *TM, AddOutputFn AddOutput,
unsigned Task, Module &Mod) {
if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
return;
auto Output = AddOutput(Task);
std::unique_ptr<raw_pwrite_stream> OS = Output->getStream();
legacy::PassManager CodeGenPasses;
if (TM->addPassesToEmitFile(CodeGenPasses, *OS,
TargetMachine::CGFT_ObjectFile))
report_fatal_error("Failed to setup codegen");
CodeGenPasses.run(Mod);
}
void splitCodeGen(Config &C, TargetMachine *TM, AddOutputFn AddOutput,
unsigned ParallelCodeGenParallelismLevel,
std::unique_ptr<Module> Mod) {
ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
unsigned ThreadCount = 0;
const Target *T = &TM->getTarget();
SplitModule(
std::move(Mod), ParallelCodeGenParallelismLevel,
[&](std::unique_ptr<Module> MPart) {
// We want to clone the module in a new context to multi-thread the
// codegen. We do it by serializing partition modules to bitcode
// (while still on the main thread, in order to avoid data races) and
// spinning up new threads which deserialize the partitions into
// separate contexts.
// FIXME: Provide a more direct way to do this in LLVM.
SmallString<0> BC;
raw_svector_ostream BCOS(BC);
WriteBitcodeToFile(MPart.get(), BCOS);
// Enqueue the task
CodegenThreadPool.async(
[&](const SmallString<0> &BC, unsigned ThreadId) {
LTOLLVMContext Ctx(C);
ErrorOr<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
Ctx);
if (!MOrErr)
report_fatal_error("Failed to read bitcode");
std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
std::unique_ptr<TargetMachine> TM =
createTargetMachine(C, MPartInCtx->getTargetTriple(), T);
codegen(C, TM.get(),
getUncachedOutputWrapper(AddOutput, ThreadId), ThreadId,
*MPartInCtx);
},
// Pass BC using std::move to ensure that it get moved rather than
// copied into the thread's context.
std::move(BC), ThreadCount++);
},
false);
}
Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
if (!C.OverrideTriple.empty())
Mod.setTargetTriple(C.OverrideTriple);
else if (Mod.getTargetTriple().empty())
Mod.setTargetTriple(C.DefaultTriple);
std::string Msg;
const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
if (!T)
return make_error<StringError>(Msg, inconvertibleErrorCode());
return T;
}
}
Error lto::backend(Config &C, AddOutputFn AddOutput,
unsigned ParallelCodeGenParallelismLevel,
std::unique_ptr<Module> Mod) {
Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
if (!TOrErr)
return TOrErr.takeError();
std::unique_ptr<TargetMachine> TM =
createTargetMachine(C, Mod->getTargetTriple(), *TOrErr);
if (!C.CodeGenOnly)
if (!opt(C, TM.get(), 0, *Mod, /*IsThinLto=*/false))
return Error();
if (ParallelCodeGenParallelismLevel == 1) {
codegen(C, TM.get(), getUncachedOutputWrapper(AddOutput, 0), 0, *Mod);
} else {
splitCodeGen(C, TM.get(), AddOutput, ParallelCodeGenParallelismLevel,
std::move(Mod));
}
return Error();
}
Error lto::thinBackend(Config &Conf, unsigned Task, AddOutputFn AddOutput,
Module &Mod, ModuleSummaryIndex &CombinedIndex,
const FunctionImporter::ImportMapTy &ImportList,
const GVSummaryMapTy &DefinedGlobals,
MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
if (!TOrErr)
return TOrErr.takeError();
std::unique_ptr<TargetMachine> TM =
createTargetMachine(Conf, Mod.getTargetTriple(), *TOrErr);
if (Conf.CodeGenOnly) {
codegen(Conf, TM.get(), AddOutput, Task, Mod);
return Error();
}
if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
return Error();
renameModuleForThinLTO(Mod, CombinedIndex);
thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
return Error();
if (!DefinedGlobals.empty())
thinLTOInternalizeModule(Mod, DefinedGlobals);
if (Conf.PostInternalizeModuleHook &&
!Conf.PostInternalizeModuleHook(Task, Mod))
return Error();
auto ModuleLoader = [&](StringRef Identifier) {
assert(Mod.getContext().isODRUniquingDebugTypes() &&
"ODR Type uniquing should be enabled on the context");
return std::move(getLazyBitcodeModule(MemoryBuffer::getMemBuffer(
ModuleMap[Identifier], false),
Mod.getContext(),
/*ShouldLazyLoadMetadata=*/true)
.get());
};
FunctionImporter Importer(CombinedIndex, ModuleLoader);
Importer.importFunctions(Mod, ImportList);
if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
return Error();
if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLto=*/true))
return Error();
codegen(Conf, TM.get(), AddOutput, Task, Mod);
return Error();
}
<|endoftext|>
|
<commit_before>#pragma once
#include <vector>
#include <opencv2/opencv.hpp>
#include "window.hh"
struct mblbp_feature
{
// self-explanatory constructor
mblbp_feature(int x, int y, int block_width, int block_height);
// horizontal (x, y) offset relative to the origin of the window
int x, y;
int block_w; // block width, must be a multiple of 3
int block_h; // block height, must be a multiple of 3
};
using mblbp_features = std::vector<mblbp_feature>;
int mblbp_calculate_feature(const cv::Mat &integral,
const window &potential_window,
const mblbp_feature &feature);
std::vector<mblbp_feature> mblbp_all_features();
<commit_msg>mblbp documentation<commit_after>#pragma once
#include <vector>
#include <opencv2/opencv.hpp>
#include "window.hh"
struct mblbp_feature
{
mblbp_feature(int x, int y, int block_width, int block_height); // constructor
int x, y; // horizontal (x, y) offset relative to the origin of the window
int block_w; // block width, must be a multiple of 3
int block_h; // block height, must be a multiple of 3
};
using mblbp_features = std::vector<mblbp_feature>;
/* Calculate a MB-LBP feature at a specific window
** The feature will be scaled accordingly with window.scale
**
** Parameters
** ----------
** integral : cv::Mat
** Integral representation of the image
**
** potential_window : window
** Window that needs to be tested for a face
**
** feature : mblbp_feature
** Feature to calculate
**
** Return
** ------
** feature_value : int
** The calculated value of the feature
*/
int mblbp_calculate_feature(const cv::Mat &integral,
const window &potential_window,
const mblbp_feature &feature);
/* Generate all MB-LBP features inside a window
** The size of the window is defined in "parameters.hh"
**
** This function is mainly used for calculating all the MB-LBP features when
** training the classifier. The classifier is the result of a selection of the
** best MB-LBP features. To select the best MB-LBP features, they need to all be
** calculated, and that is the purpose of this function.
**
** Return
** ------
** features : std::vector<mblbp_feature>
** All features contained in the window
*/
std::vector<mblbp_feature> mblbp_all_features();
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xpathapi.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _XPATHAPI_HXX
#define _XPATHAPI_HXX
#include <map>
#include <vector>
#include <sal/types.h>
#include <cppuhelper/implbase2.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Sequence.h>
#include <com/sun/star/uno/XInterface.hpp>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/xml/xpath/XXPathAPI.hpp>
#include <com/sun/star/xml/dom/XNode.hpp>
#include <com/sun/star/xml/dom/XNodeList.hpp>
#include <com/sun/star/xml/xpath/XXPathAPI.hpp>
#include <com/sun/star/xml/xpath/XXPathObject.hpp>
#include <com/sun/star/xml/xpath/XXPathExtension.hpp>
#include <com/sun/star/xml/xpath/Libxml2ExtensionHandle.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XUnoTunnel.hpp>
#include "libxml/tree.h"
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::xml::dom;
using namespace com::sun::star::xml::xpath;
namespace XPath
{
typedef std::map<OUString, OUString> nsmap_t;
typedef std::vector< Reference<XXPathExtension> > extensions_t;
class CXPathAPI
: public ::cppu::WeakImplHelper2< XXPathAPI, XServiceInfo >
{
private:
nsmap_t m_nsmap;
const Reference < XMultiServiceFactory >& m_aFactory;
extensions_t m_extensions;
public:
// ctor
CXPathAPI(const Reference< XMultiServiceFactory >& rSMgr);
// call for factory
static Reference< XInterface > getInstance(const Reference < XMultiServiceFactory >& xFactory);
// static helpers for service info and component management
static const char* aImplementationName;
static const char* aSupportedServiceNames[];
static OUString _getImplementationName();
static Sequence< OUString > _getSupportedServiceNames();
static Reference< XInterface > _getInstance(const Reference< XMultiServiceFactory >& rSMgr);
// XServiceInfo
virtual OUString SAL_CALL getImplementationName()
throw (RuntimeException);
virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName)
throw (RuntimeException);
virtual Sequence< OUString > SAL_CALL getSupportedServiceNames ()
throw (RuntimeException);
// --- XXPathAPI ---
virtual void SAL_CALL registerNS(const OUString& aPrefix, const OUString& aURI)
throw (RuntimeException);
virtual void SAL_CALL unregisterNS(const OUString& aPrefix, const OUString& aURI)
throw (RuntimeException);
/**
Use an XPath string to select a nodelist.
*/
virtual Reference< XNodeList > SAL_CALL selectNodeList(const Reference< XNode >& contextNode, const OUString& str)
throw (RuntimeException);
/**
Use an XPath string to select a nodelist.
*/
virtual Reference< XNodeList > SAL_CALL selectNodeListNS(const Reference< XNode >& contextNode, const OUString& str, const Reference< XNode >& namespaceNode)
throw (RuntimeException);
/**
Use an XPath string to select a single node.
*/
virtual Reference< XNode > SAL_CALL selectSingleNode(const Reference< XNode >& contextNode, const OUString& str)
throw (RuntimeException);
/**
Use an XPath string to select a single node.
*/
virtual Reference< XNode > SAL_CALL selectSingleNodeNS(const Reference< XNode >& contextNode, const OUString& str, const Reference< XNode >& namespaceNode)
throw (RuntimeException);
virtual Reference< XXPathObject > SAL_CALL eval(const Reference< XNode >& contextNode, const OUString& str)
throw (RuntimeException);
virtual Reference< XXPathObject > SAL_CALL evalNS(const Reference< XNode >& contextNode, const OUString& str, const Reference< XNode >& namespaceNode)
throw (RuntimeException);
virtual void SAL_CALL registerExtension(const OUString& aName) throw (RuntimeException);
virtual void SAL_CALL registerExtensionInstance(const Reference< XXPathExtension>& aExtension) throw (RuntimeException);
};
}
#endif
<commit_msg>INTEGRATION: CWS xmlfix2 (1.4.38); FILE MERGED 2008/05/15 17:26:55 mst 1.4.38.2: RESYNC: (1.4-1.5); FILE MERGED 2008/03/31 14:20:36 mst 1.4.38.1: #i81678#: interface change: XXPathAPI - unoxml/source/xpath/xpathapi{.hxx,.cxx}: + adapt to changes in css.xml.xpath.XXPathAPI<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xpathapi.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _XPATHAPI_HXX
#define _XPATHAPI_HXX
#include <map>
#include <vector>
#include <sal/types.h>
#include <cppuhelper/implbase2.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Sequence.h>
#include <com/sun/star/uno/XInterface.hpp>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/xml/xpath/XXPathAPI.hpp>
#include <com/sun/star/xml/dom/XNode.hpp>
#include <com/sun/star/xml/dom/XNodeList.hpp>
#include <com/sun/star/xml/xpath/XXPathAPI.hpp>
#include <com/sun/star/xml/xpath/XXPathObject.hpp>
#include <com/sun/star/xml/xpath/XXPathExtension.hpp>
#include <com/sun/star/xml/xpath/Libxml2ExtensionHandle.hpp>
#include <com/sun/star/xml/xpath/XPathException.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XUnoTunnel.hpp>
#include "libxml/tree.h"
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::xml::dom;
using namespace com::sun::star::xml::xpath;
namespace XPath
{
typedef std::map<OUString, OUString> nsmap_t;
typedef std::vector< Reference<XXPathExtension> > extensions_t;
class CXPathAPI
: public ::cppu::WeakImplHelper2< XXPathAPI, XServiceInfo >
{
private:
nsmap_t m_nsmap;
const Reference < XMultiServiceFactory >& m_aFactory;
extensions_t m_extensions;
public:
// ctor
CXPathAPI(const Reference< XMultiServiceFactory >& rSMgr);
// call for factory
static Reference< XInterface > getInstance(const Reference < XMultiServiceFactory >& xFactory);
// static helpers for service info and component management
static const char* aImplementationName;
static const char* aSupportedServiceNames[];
static OUString _getImplementationName();
static Sequence< OUString > _getSupportedServiceNames();
static Reference< XInterface > _getInstance(const Reference< XMultiServiceFactory >& rSMgr);
// XServiceInfo
virtual OUString SAL_CALL getImplementationName()
throw (RuntimeException);
virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName)
throw (RuntimeException);
virtual Sequence< OUString > SAL_CALL getSupportedServiceNames ()
throw (RuntimeException);
// --- XXPathAPI ---
virtual void SAL_CALL registerNS(const OUString& aPrefix, const OUString& aURI)
throw (RuntimeException);
virtual void SAL_CALL unregisterNS(const OUString& aPrefix, const OUString& aURI)
throw (RuntimeException);
/**
Use an XPath string to select a nodelist.
*/
virtual Reference< XNodeList > SAL_CALL selectNodeList(const Reference< XNode >& contextNode, const OUString& str)
throw (RuntimeException, XPathException);
/**
Use an XPath string to select a nodelist.
*/
virtual Reference< XNodeList > SAL_CALL selectNodeListNS(const Reference< XNode >& contextNode, const OUString& str, const Reference< XNode >& namespaceNode)
throw (RuntimeException, XPathException);
/**
Use an XPath string to select a single node.
*/
virtual Reference< XNode > SAL_CALL selectSingleNode(const Reference< XNode >& contextNode, const OUString& str)
throw (RuntimeException, XPathException);
/**
Use an XPath string to select a single node.
*/
virtual Reference< XNode > SAL_CALL selectSingleNodeNS(const Reference< XNode >& contextNode, const OUString& str, const Reference< XNode >& namespaceNode)
throw (RuntimeException, XPathException);
virtual Reference< XXPathObject > SAL_CALL eval(const Reference< XNode >& contextNode, const OUString& str)
throw (RuntimeException, XPathException);
virtual Reference< XXPathObject > SAL_CALL evalNS(const Reference< XNode >& contextNode, const OUString& str, const Reference< XNode >& namespaceNode)
throw (RuntimeException, XPathException);
virtual void SAL_CALL registerExtension(const OUString& aName) throw (RuntimeException);
virtual void SAL_CALL registerExtensionInstance(const Reference< XXPathExtension>& aExtension) throw (RuntimeException);
};
}
#endif
<|endoftext|>
|
<commit_before>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.
#pragma once
#include "Grappa.hpp"
#include "Message.hpp"
#include "FullEmptyLocal.hpp"
#include "Message.hpp"
#include "ConditionVariable.hpp"
#include "MessagePool.hpp"
#include <type_traits>
GRAPPA_DECLARE_STAT(SummarizingStatistic<uint64_t>, flat_combiner_fetch_and_add_amount);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_short_circuits);
GRAPPA_DECLARE_STAT(SummarizingStatistic<double>, delegate_roundtrip_latency);
GRAPPA_DECLARE_STAT(SummarizingStatistic<double>, delegate_network_latency);
GRAPPA_DECLARE_STAT(SummarizingStatistic<double>, delegate_wakeup_latency);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_ops);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_targets);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_reads);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_read_targets);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_writes);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_write_targets);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_cmpswaps);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_cmpswap_targets);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_fetchadds);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_fetchadd_targets);
namespace Grappa {
/// @addtogroup Delegates
/// @{
namespace impl {
inline void record_network_latency(int64_t start_time) {
auto latency = Grappa::timestamp() - start_time;
delegate_network_latency += latency;
}
inline void record_wakeup_latency(int64_t start_time, int64_t network_time) {
auto current_time = Grappa::timestamp();
auto blocked_time = current_time - start_time;
auto wakeup_latency = current_time - network_time;
delegate_roundtrip_latency += blocked_time;
delegate_wakeup_latency += wakeup_latency;
}
/// Overloaded version for func with void return type.
template <typename F>
inline void call(Core dest, F func, void (F::*mf)() const) {
delegate_ops++;
Core origin = Grappa::mycore();
if (dest == origin) {
// short-circuit if local
delegate_short_circuits++;
return func();
} else {
int64_t network_time = 0;
int64_t start_time = Grappa::timestamp();
FullEmpty<bool> result;
send_message(dest, [&result, origin, func, &network_time, start_time] {
delegate_targets++;
func();
// TODO: replace with handler-safe send_message
send_heap_message(origin, [&result, &network_time, start_time] {
network_time = Grappa::timestamp();
record_network_latency(start_time);
result.writeXF(true);
});
}); // send message
// ... and wait for the call to complete
result.readFF();
record_wakeup_latency(start_time, network_time);
return;
}
}
template <typename F>
inline auto call(Core dest, F func, decltype(func()) (F::*mf)() const) -> decltype(func()) {
// Note: code below (calling call_async) could be used to avoid duplication of code,
// but call_async adds some overhead (object creation overhead, especially for short
// -circuit case and extra work in MessagePool)
// AsyncHandle<decltype(func())> a;
// MessagePool<sizeof(Message<F>)> pool;
// a.call_async(pool, dest, func);
// return a.get_result();
// TODO: find a way to implement using async version that doesn't introduce overhead
delegate_ops++;
using R = decltype(func());
Core origin = Grappa::mycore();
if (dest == origin) {
// short-circuit if local
delegate_targets++;
delegate_short_circuits++;
return func();
} else {
FullEmpty<R> result;
int64_t network_time = 0;
int64_t start_time = Grappa::timestamp();
send_message(dest, [&result, origin, func, &network_time, start_time] {
delegate_targets++;
R val = func();
// TODO: replace with handler-safe send_message
send_heap_message(origin, [&result, val, &network_time, start_time] {
network_time = Grappa::timestamp();
record_network_latency(start_time);
result.writeXF(val); // can't block in message, assumption is that result is already empty
});
}); // send message
// ... and wait for the result
R r = result.readFE();
record_wakeup_latency(start_time, network_time);
return r;
}
}
} // namespace impl
namespace delegate {
/// Implements essentially a blocking remote procedure call. Callable object (lambda,
/// function pointer, or functor object) is called from the `dest` core and the return
/// value is sent back to the calling task.
template <typename F>
inline auto call(Core dest, F func) -> decltype(func()) {
return impl::call(dest, func, &F::operator());
}
/// Helper that makes it easier to implement custom delegate operations on global
/// addresses specifically.
///
/// Example:
/// @code
/// GlobalAddress<int> xa;
/// bool is_zero = delegate::call(xa, [](int* x){ return *x == 0; });
/// @endcode
template< typename T, typename F >
inline auto call(GlobalAddress<T> target, F func) -> decltype(func(target.pointer())) {
return call(target.core(), [target,func]{ return func(target.pointer()); });
}
/// Try lock on remote mutex. Does \b not lock or unlock, creates a SuspendedDelegate if lock has already
/// been taken, which is triggered on unlocking of the Mutex.
template< typename M, typename F >
inline auto call(Core dest, M mutex, F func) -> decltype(func(mutex())) {
using R = decltype(func(mutex()));
delegate_ops++;
if (dest == mycore()) {
delegate_targets++;
delegate_short_circuits++;
// auto l = mutex();
// lock(l);
auto r = func(mutex());
// unlock(l);
return r;
} else {
FullEmpty<R> result;
auto result_addr = make_global(&result);
auto set_result = [result_addr](const R& val){
send_heap_message(result_addr.core(), [result_addr,val]{
result_addr->writeXF(val);
});
};
send_message(dest, [set_result,mutex,func] {
delegate_targets++;
auto l = mutex();
if (is_unlocked(l)) { // if lock is not held
// lock(l);
set_result(func(l));
} else {
add_waiter(l, new_suspended_delegate([set_result,func,l]{
// lock(l);
CHECK(is_unlocked(l));
set_result(func(l));
}));
}
});
auto r = result.readFE();
return r;
}
}
/// Alternative version of delegate::call that spawns a privateTask to allow the delegate
/// to perform suspending actions.
///
/// @note Use of this is not advised: suspending violates much of the assumptions about
/// delegates we usually make, and can easily cause deadlock if no workers are available
/// to execute the spawned privateTask. A better option for possibly-blocking delegates
/// is to use the Mutex version of delegate::call(Core,M,F).
template <typename F>
inline auto call_suspendable(Core dest, F func) -> decltype(func()) {
delegate_ops++;
using R = decltype(func());
Core origin = Grappa::mycore();
if (dest == origin) {
delegate_targets++;
delegate_short_circuits++;
return func();
} else {
FullEmpty<R> result;
int64_t network_time = 0;
int64_t start_time = Grappa::timestamp();
send_message(dest, [&result, origin, func, &network_time, start_time] {
delegate_targets++;
privateTask([&result, origin, func, &network_time, start_time] {
R val = func();
// TODO: replace with handler-safe send_message
send_heap_message(origin, [&result, val, &network_time, start_time] {
network_time = Grappa::timestamp();
record_network_latency(start_time);
result.writeXF(val); // can't block in message, assumption is that result is already empty
});
});
}); // send message
// ... and wait for the result
R r = result.readFE();
record_wakeup_latency(start_time, network_time);
return r;
}
}
/// Read the value (potentially remote) at the given GlobalAddress, blocks the calling task until
/// round-trip communication is complete.
/// @warning Target object must lie on a single node (not span blocks in global address space).
template< typename T >
T read(GlobalAddress<T> target) {
delegate_reads++;
return call(target.node(), [target]() -> T {
delegate_read_targets++;
return *target.pointer();
});
}
/// Blocking remote write.
/// @warning Target object must lie on a single node (not span blocks in global address space).
template< typename T, typename U >
void write(GlobalAddress<T> target, U value) {
delegate_writes++;
// TODO: don't return any val, requires changes to `delegate::call()`.
return call(target.node(), [target, value] {
delegate_write_targets++;
*target.pointer() = value;
});
}
/// Fetch the value at `target`, increment the value stored there with `inc` and return the
/// original value to blocking thread.
/// @warning Target object must lie on a single node (not span blocks in global address space).
template< typename T, typename U >
T fetch_and_add(GlobalAddress<T> target, U inc) {
delegate_fetchadds++;
return call(target.node(), [target, inc]() -> T {
delegate_fetchadd_targets++;
T* p = target.pointer();
T r = *p;
*p += inc;
return r;
});
}
/// Flat combines fetch_and_add to a single global address
/// @warning Target object must lie on a single node (not span blocks in global address space).
template < typename T, typename U >
class FetchAddCombiner {
// TODO: generalize to define other types of combiners
private:
// configuration
const GlobalAddress<T> target;
const U initVal;
const uint64_t flush_threshold;
// state
T result;
U increment;
uint64_t committed;
uint64_t participant_count;
uint64_t ready_waiters;
bool outstanding;
ConditionVariable untilNotOutstanding;
ConditionVariable untilReceived;
// wait until fetch add unit is in aggregate mode
// TODO: add concurrency (multiple fetch add units)
void block_until_ready() {
while ( outstanding ) {
ready_waiters++;
Grappa::wait(&untilNotOutstanding);
ready_waiters--;
}
}
void set_ready() {
outstanding = false;
Grappa::broadcast(&untilNotOutstanding);
}
void set_not_ready() {
outstanding = true;
}
public:
FetchAddCombiner( GlobalAddress<T> target, uint64_t flush_threshold, U initVal )
: target( target )
, initVal( initVal )
, flush_threshold( flush_threshold )
, result()
, increment( initVal )
, committed( 0 )
, participant_count( 0 )
, ready_waiters( 0 )
, outstanding( false )
, untilNotOutstanding()
, untilReceived()
{}
/// Promise that in the future
/// you will call `fetch_and_add`.
///
/// Must be called before a call to `fetch_and_add`
///
/// After calling promise, this task must NOT have a dependence on any
/// `fetch_and_add` occurring before it calls `fetch_and_add` itself
/// or deadlock may occur.
///
/// For good performance, should allow other
/// tasks to run before calling `fetch_and_add`
void promise() {
committed += 1;
}
// because tasks run serially, promise() replaces the flat combining tree
T fetch_and_add( U inc ) {
block_until_ready();
// fetch add unit is now aggregating so add my inc
participant_count++;
committed--;
increment += inc;
// if I'm the last entered client and either the flush threshold
// is reached or there are no more committed participants then start the flush
if ( ready_waiters == 0 && (participant_count >= flush_threshold || committed == 0 )) {
set_not_ready();
uint64_t increment_total = increment;
flat_combiner_fetch_and_add_amount += increment_total;
auto t = target;
result = call(target.node(), [t, increment_total]() -> U {
T * p = t.pointer();
uint64_t r = *p;
*p += increment_total;
return r;
});
// tell the others that the result has arrived
Grappa::broadcast(&untilReceived);
} else {
// someone else will start the flush
Grappa::wait(&untilReceived);
}
uint64_t my_start = result;
result += inc;
participant_count--;
increment -= inc; // for validation purposes (could just set to 0)
if ( participant_count == 0 ) {
CHECK( increment == 0 ) << "increment = " << increment << " even though all participants are done";
set_ready();
}
return my_start;
}
};
/// If value at `target` equals `cmp_val`, set the value to `new_val` and return `true`,
/// otherwise do nothing and return `false`.
/// @warning Target object must lie on a single node (not span blocks in global address space).
template< typename T, typename U, typename V >
bool compare_and_swap(GlobalAddress<T> target, U cmp_val, V new_val) {
delegate_cmpswaps++;
return call(target.node(), [target, cmp_val, new_val]() -> bool {
T * p = target.pointer();
delegate_cmpswap_targets++;
if (cmp_val == *p) {
*p = new_val;
return true;
} else {
return false;
}
});
}
/// @}
} // namespace delegate
} // namespace Grappa
<commit_msg>allow const types with call() (need to be convertible, not same)<commit_after>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.
#pragma once
#include "Grappa.hpp"
#include "Message.hpp"
#include "FullEmptyLocal.hpp"
#include "Message.hpp"
#include "ConditionVariable.hpp"
#include "MessagePool.hpp"
#include <type_traits>
GRAPPA_DECLARE_STAT(SummarizingStatistic<uint64_t>, flat_combiner_fetch_and_add_amount);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_short_circuits);
GRAPPA_DECLARE_STAT(SummarizingStatistic<double>, delegate_roundtrip_latency);
GRAPPA_DECLARE_STAT(SummarizingStatistic<double>, delegate_network_latency);
GRAPPA_DECLARE_STAT(SummarizingStatistic<double>, delegate_wakeup_latency);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_ops);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_targets);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_reads);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_read_targets);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_writes);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_write_targets);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_cmpswaps);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_cmpswap_targets);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_fetchadds);
GRAPPA_DECLARE_STAT(SimpleStatistic<uint64_t>, delegate_fetchadd_targets);
namespace Grappa {
/// @addtogroup Delegates
/// @{
namespace impl {
inline void record_network_latency(int64_t start_time) {
auto latency = Grappa::timestamp() - start_time;
delegate_network_latency += latency;
}
inline void record_wakeup_latency(int64_t start_time, int64_t network_time) {
auto current_time = Grappa::timestamp();
auto blocked_time = current_time - start_time;
auto wakeup_latency = current_time - network_time;
delegate_roundtrip_latency += blocked_time;
delegate_wakeup_latency += wakeup_latency;
}
/// Overloaded version for func with void return type.
template <typename F>
inline void call(Core dest, F func, void (F::*mf)() const) {
delegate_ops++;
Core origin = Grappa::mycore();
if (dest == origin) {
// short-circuit if local
delegate_short_circuits++;
return func();
} else {
int64_t network_time = 0;
int64_t start_time = Grappa::timestamp();
FullEmpty<bool> result;
send_message(dest, [&result, origin, func, &network_time, start_time] {
delegate_targets++;
func();
// TODO: replace with handler-safe send_message
send_heap_message(origin, [&result, &network_time, start_time] {
network_time = Grappa::timestamp();
record_network_latency(start_time);
result.writeXF(true);
});
}); // send message
// ... and wait for the call to complete
result.readFF();
record_wakeup_latency(start_time, network_time);
return;
}
}
template <typename F, typename TT >
inline auto call(Core dest, F func, TT (F::*mf)() const) -> TT {
static_assert(std::is_convertible< decltype(func()), TT >(),
"lambda doesn't return the expected type");
// Note: code below (calling call_async) could be used to avoid duplication of code,
// but call_async adds some overhead (object creation overhead, especially for short
// -circuit case and extra work in MessagePool)
// AsyncHandle<decltype(func())> a;
// MessagePool<sizeof(Message<F>)> pool;
// a.call_async(pool, dest, func);
// return a.get_result();
// TODO: find a way to implement using async version that doesn't introduce overhead
delegate_ops++;
using R = decltype(func());
Core origin = Grappa::mycore();
if (dest == origin) {
// short-circuit if local
delegate_targets++;
delegate_short_circuits++;
return func();
} else {
FullEmpty<R> result;
int64_t network_time = 0;
int64_t start_time = Grappa::timestamp();
send_message(dest, [&result, origin, func, &network_time, start_time] {
delegate_targets++;
R val = func();
// TODO: replace with handler-safe send_message
send_heap_message(origin, [&result, val, &network_time, start_time] {
network_time = Grappa::timestamp();
record_network_latency(start_time);
result.writeXF(val); // can't block in message, assumption is that result is already empty
});
}); // send message
// ... and wait for the result
R r = result.readFE();
record_wakeup_latency(start_time, network_time);
return r;
}
}
} // namespace impl
namespace delegate {
/// Implements essentially a blocking remote procedure call. Callable object (lambda,
/// function pointer, or functor object) is called from the `dest` core and the return
/// value is sent back to the calling task.
template <typename F>
inline auto call(Core dest, F func) -> decltype(func()) {
return impl::call(dest, func, &F::operator());
}
/// Helper that makes it easier to implement custom delegate operations on global
/// addresses specifically.
///
/// Example:
/// @code
/// GlobalAddress<int> xa;
/// bool is_zero = delegate::call(xa, [](int* x){ return *x == 0; });
/// @endcode
template< typename T, typename F >
inline auto call(GlobalAddress<T> target, F func) -> decltype(func(target.pointer())) {
return call(target.core(), [target,func]{ return func(target.pointer()); });
}
/// Try lock on remote mutex. Does \b not lock or unlock, creates a SuspendedDelegate if lock has already
/// been taken, which is triggered on unlocking of the Mutex.
template< typename M, typename F >
inline auto call(Core dest, M mutex, F func) -> decltype(func(mutex())) {
using R = decltype(func(mutex()));
delegate_ops++;
if (dest == mycore()) {
delegate_targets++;
delegate_short_circuits++;
// auto l = mutex();
// lock(l);
auto r = func(mutex());
// unlock(l);
return r;
} else {
FullEmpty<R> result;
auto result_addr = make_global(&result);
auto set_result = [result_addr](const R& val){
send_heap_message(result_addr.core(), [result_addr,val]{
result_addr->writeXF(val);
});
};
send_message(dest, [set_result,mutex,func] {
delegate_targets++;
auto l = mutex();
if (is_unlocked(l)) { // if lock is not held
// lock(l);
set_result(func(l));
} else {
add_waiter(l, new_suspended_delegate([set_result,func,l]{
// lock(l);
CHECK(is_unlocked(l));
set_result(func(l));
}));
}
});
auto r = result.readFE();
return r;
}
}
/// Alternative version of delegate::call that spawns a privateTask to allow the delegate
/// to perform suspending actions.
///
/// @note Use of this is not advised: suspending violates much of the assumptions about
/// delegates we usually make, and can easily cause deadlock if no workers are available
/// to execute the spawned privateTask. A better option for possibly-blocking delegates
/// is to use the Mutex version of delegate::call(Core,M,F).
template <typename F>
inline auto call_suspendable(Core dest, F func) -> decltype(func()) {
delegate_ops++;
using R = decltype(func());
Core origin = Grappa::mycore();
if (dest == origin) {
delegate_targets++;
delegate_short_circuits++;
return func();
} else {
FullEmpty<R> result;
int64_t network_time = 0;
int64_t start_time = Grappa::timestamp();
send_message(dest, [&result, origin, func, &network_time, start_time] {
delegate_targets++;
privateTask([&result, origin, func, &network_time, start_time] {
R val = func();
// TODO: replace with handler-safe send_message
send_heap_message(origin, [&result, val, &network_time, start_time] {
network_time = Grappa::timestamp();
record_network_latency(start_time);
result.writeXF(val); // can't block in message, assumption is that result is already empty
});
});
}); // send message
// ... and wait for the result
R r = result.readFE();
record_wakeup_latency(start_time, network_time);
return r;
}
}
/// Read the value (potentially remote) at the given GlobalAddress, blocks the calling task until
/// round-trip communication is complete.
/// @warning Target object must lie on a single node (not span blocks in global address space).
template< typename T >
T read(GlobalAddress<T> target) {
delegate_reads++;
return call(target.node(), [target]() -> T {
delegate_read_targets++;
return *target.pointer();
});
}
template< typename T >
const T read_const(GlobalAddress<const T> target) {
delegate_reads++;
return call(target.node(), [target]() -> const T {
delegate_read_targets++;
return *target.pointer();
});
}
/// Blocking remote write.
/// @warning Target object must lie on a single node (not span blocks in global address space).
template< typename T, typename U >
void write(GlobalAddress<T> target, U value) {
delegate_writes++;
// TODO: don't return any val, requires changes to `delegate::call()`.
return call(target.node(), [target, value] {
delegate_write_targets++;
*target.pointer() = value;
});
}
/// Fetch the value at `target`, increment the value stored there with `inc` and return the
/// original value to blocking thread.
/// @warning Target object must lie on a single node (not span blocks in global address space).
template< typename T, typename U >
T fetch_and_add(GlobalAddress<T> target, U inc) {
delegate_fetchadds++;
return call(target.node(), [target, inc]() -> T {
delegate_fetchadd_targets++;
T* p = target.pointer();
T r = *p;
*p += inc;
return r;
});
}
/// Flat combines fetch_and_add to a single global address
/// @warning Target object must lie on a single node (not span blocks in global address space).
template < typename T, typename U >
class FetchAddCombiner {
// TODO: generalize to define other types of combiners
private:
// configuration
const GlobalAddress<T> target;
const U initVal;
const uint64_t flush_threshold;
// state
T result;
U increment;
uint64_t committed;
uint64_t participant_count;
uint64_t ready_waiters;
bool outstanding;
ConditionVariable untilNotOutstanding;
ConditionVariable untilReceived;
// wait until fetch add unit is in aggregate mode
// TODO: add concurrency (multiple fetch add units)
void block_until_ready() {
while ( outstanding ) {
ready_waiters++;
Grappa::wait(&untilNotOutstanding);
ready_waiters--;
}
}
void set_ready() {
outstanding = false;
Grappa::broadcast(&untilNotOutstanding);
}
void set_not_ready() {
outstanding = true;
}
public:
FetchAddCombiner( GlobalAddress<T> target, uint64_t flush_threshold, U initVal )
: target( target )
, initVal( initVal )
, flush_threshold( flush_threshold )
, result()
, increment( initVal )
, committed( 0 )
, participant_count( 0 )
, ready_waiters( 0 )
, outstanding( false )
, untilNotOutstanding()
, untilReceived()
{}
/// Promise that in the future
/// you will call `fetch_and_add`.
///
/// Must be called before a call to `fetch_and_add`
///
/// After calling promise, this task must NOT have a dependence on any
/// `fetch_and_add` occurring before it calls `fetch_and_add` itself
/// or deadlock may occur.
///
/// For good performance, should allow other
/// tasks to run before calling `fetch_and_add`
void promise() {
committed += 1;
}
// because tasks run serially, promise() replaces the flat combining tree
T fetch_and_add( U inc ) {
block_until_ready();
// fetch add unit is now aggregating so add my inc
participant_count++;
committed--;
increment += inc;
// if I'm the last entered client and either the flush threshold
// is reached or there are no more committed participants then start the flush
if ( ready_waiters == 0 && (participant_count >= flush_threshold || committed == 0 )) {
set_not_ready();
uint64_t increment_total = increment;
flat_combiner_fetch_and_add_amount += increment_total;
auto t = target;
result = call(target.node(), [t, increment_total]() -> U {
T * p = t.pointer();
uint64_t r = *p;
*p += increment_total;
return r;
});
// tell the others that the result has arrived
Grappa::broadcast(&untilReceived);
} else {
// someone else will start the flush
Grappa::wait(&untilReceived);
}
uint64_t my_start = result;
result += inc;
participant_count--;
increment -= inc; // for validation purposes (could just set to 0)
if ( participant_count == 0 ) {
CHECK( increment == 0 ) << "increment = " << increment << " even though all participants are done";
set_ready();
}
return my_start;
}
};
/// If value at `target` equals `cmp_val`, set the value to `new_val` and return `true`,
/// otherwise do nothing and return `false`.
/// @warning Target object must lie on a single node (not span blocks in global address space).
template< typename T, typename U, typename V >
bool compare_and_swap(GlobalAddress<T> target, U cmp_val, V new_val) {
delegate_cmpswaps++;
return call(target.node(), [target, cmp_val, new_val]() -> bool {
T * p = target.pointer();
delegate_cmpswap_targets++;
if (cmp_val == *p) {
*p = new_val;
return true;
} else {
return false;
}
});
}
/// @}
} // namespace delegate
} // namespace Grappa
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2018 gRPC 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 "src/core/lib/iomgr/port.h"
// This test won't work except with posix sockets enabled
#ifdef GRPC_POSIX_SOCKET_TCP
#include <arpa/inet.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string>
#include "absl/strings/str_cat.h"
#include <grpc/grpc.h>
#include <grpc/grpc_security.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/load_file.h"
#include "test/core/util/port.h"
#include "test/core/util/test_config.h"
#define SSL_CERT_PATH "src/core/tsi/test_creds/server1.pem"
#define SSL_KEY_PATH "src/core/tsi/test_creds/server1.key"
#define SSL_CA_PATH "src/core/tsi/test_creds/ca.pem"
// Simple gRPC server. This listens until client_handshake_complete occurs.
static gpr_event client_handshake_complete;
static void server_thread(void* arg) {
const int port = *static_cast<int*>(arg);
// Load key pair and establish server SSL credentials.
grpc_ssl_pem_key_cert_pair pem_key_cert_pair;
grpc_slice ca_slice, cert_slice, key_slice;
GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
grpc_load_file(SSL_CA_PATH, 1, &ca_slice)));
GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
grpc_load_file(SSL_CERT_PATH, 1, &cert_slice)));
GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
grpc_load_file(SSL_KEY_PATH, 1, &key_slice)));
const char* ca_cert =
reinterpret_cast<const char*> GRPC_SLICE_START_PTR(ca_slice);
pem_key_cert_pair.private_key =
reinterpret_cast<const char*> GRPC_SLICE_START_PTR(key_slice);
pem_key_cert_pair.cert_chain =
reinterpret_cast<const char*> GRPC_SLICE_START_PTR(cert_slice);
grpc_server_credentials* ssl_creds = grpc_ssl_server_credentials_create(
ca_cert, &pem_key_cert_pair, 1, 0, nullptr);
// Start server listening on local port.
std::string addr = absl::StrCat("127.0.0.1:", port);
grpc_server* server = grpc_server_create(nullptr, nullptr);
GPR_ASSERT(
grpc_server_add_secure_http2_port(server, addr.c_str(), ssl_creds));
grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
grpc_server_register_completion_queue(server, cq, nullptr);
grpc_server_start(server);
// Wait a bounded number of time until client_handshake_complete is set,
// sleeping between polls. The total time spent (deadline * retries)
// should be strictly greater than the client retry limit so that the
// client will always timeout first.
int retries = 60;
while (!gpr_event_get(&client_handshake_complete) && retries-- > 0) {
const gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(1);
grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr);
GPR_ASSERT(ev.type == GRPC_QUEUE_TIMEOUT);
}
gpr_log(GPR_INFO, "Shutting down server");
grpc_server_shutdown_and_notify(server, cq, nullptr);
grpc_server_cancel_all_calls(server);
grpc_completion_queue_shutdown(cq);
const gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(60);
grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr);
GPR_ASSERT(ev.type == GRPC_OP_COMPLETE);
grpc_server_destroy(server);
grpc_completion_queue_destroy(cq);
grpc_server_credentials_release(ssl_creds);
grpc_slice_unref(cert_slice);
grpc_slice_unref(key_slice);
grpc_slice_unref(ca_slice);
}
// This test launches a minimal TLS grpc server on a separate thread and then
// establishes a TLS handshake via the core library to the server. The client
// uses the supplied verify options.
static bool verify_peer_options_test(verify_peer_options* verify_options) {
bool success = true;
grpc_init();
int port = grpc_pick_unused_port_or_die();
gpr_event_init(&client_handshake_complete);
// Launch the gRPC server thread.
bool ok;
grpc_core::Thread thd("grpc_client_ssl_test", server_thread, &port, &ok);
GPR_ASSERT(ok);
thd.Start();
// Load key pair and establish client SSL credentials.
grpc_ssl_pem_key_cert_pair pem_key_cert_pair;
grpc_slice ca_slice, cert_slice, key_slice;
GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
grpc_load_file(SSL_CA_PATH, 1, &ca_slice)));
GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
grpc_load_file(SSL_CERT_PATH, 1, &cert_slice)));
GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
grpc_load_file(SSL_KEY_PATH, 1, &key_slice)));
const char* ca_cert =
reinterpret_cast<const char*> GRPC_SLICE_START_PTR(ca_slice);
pem_key_cert_pair.private_key =
reinterpret_cast<const char*> GRPC_SLICE_START_PTR(key_slice);
pem_key_cert_pair.cert_chain =
reinterpret_cast<const char*> GRPC_SLICE_START_PTR(cert_slice);
grpc_channel_credentials* ssl_creds = grpc_ssl_credentials_create(
ca_cert, &pem_key_cert_pair, verify_options, nullptr);
// Establish a channel pointing at the TLS server. Since the gRPC runtime is
// lazy, this won't necessarily establish a connection yet.
std::string target = absl::StrCat("127.0.0.1:", port);
grpc_arg ssl_name_override = {
GRPC_ARG_STRING,
const_cast<char*>(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG),
{const_cast<char*>("foo.test.google.fr")}};
grpc_channel_args grpc_args;
grpc_args.num_args = 1;
grpc_args.args = &ssl_name_override;
grpc_channel* channel = grpc_secure_channel_create(ssl_creds, target.c_str(),
&grpc_args, nullptr);
GPR_ASSERT(channel);
// Initially the channel will be idle, the
// grpc_channel_check_connectivity_state triggers an attempt to connect.
GPR_ASSERT(grpc_channel_check_connectivity_state(
channel, 1 /* try_to_connect */) == GRPC_CHANNEL_IDLE);
// Wait a bounded number of times for the channel to be ready. When the
// channel is ready, the initial TLS handshake will have successfully
// completed. The total time spent on the client side (retries * deadline)
// should be greater than the server side time limit.
int retries = 10;
grpc_connectivity_state state = GRPC_CHANNEL_IDLE;
grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
while (state != GRPC_CHANNEL_READY && retries-- > 0) {
grpc_channel_watch_connectivity_state(
channel, state, grpc_timeout_seconds_to_deadline(3), cq, nullptr);
gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(5);
grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr);
GPR_ASSERT(ev.type == GRPC_OP_COMPLETE);
state =
grpc_channel_check_connectivity_state(channel, 0 /* try_to_connect */);
}
grpc_completion_queue_destroy(cq);
if (retries < 0) {
success = false;
}
grpc_channel_destroy(channel);
grpc_channel_credentials_release(ssl_creds);
grpc_slice_unref(cert_slice);
grpc_slice_unref(key_slice);
grpc_slice_unref(ca_slice);
// Now that the client is completely cleaned up, trigger the server to
// shutdown
gpr_event_set(&client_handshake_complete, &client_handshake_complete);
// Wait for the server to completely shutdown
thd.Join();
grpc_shutdown();
return success;
}
static int callback_return_value = 0;
static char callback_target_host[4096];
static char callback_target_pem[4096];
static void* callback_userdata = nullptr;
static void* destruct_userdata = nullptr;
static int verify_callback(const char* target_host, const char* target_pem,
void* userdata) {
if (target_host != nullptr) {
snprintf(callback_target_host, sizeof(callback_target_host), "%s",
target_host);
} else {
callback_target_host[0] = '\0';
}
if (target_pem != nullptr) {
snprintf(callback_target_pem, sizeof(callback_target_pem), "%s",
target_pem);
} else {
callback_target_pem[0] = '\0';
}
callback_userdata = userdata;
return callback_return_value;
}
static void verify_destruct(void* userdata) { destruct_userdata = userdata; }
int main(int argc, char* argv[]) {
grpc::testing::TestEnvironment env(argc, argv);
int userdata = 42;
verify_peer_options verify_options;
// Load the server's cert so that we can assert it gets passed to the callback
grpc_slice cert_slice;
GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
grpc_load_file(SSL_CERT_PATH, 1, &cert_slice)));
const char* server_cert =
reinterpret_cast<const char*> GRPC_SLICE_START_PTR(cert_slice);
// Running with all-null values should have no effect
verify_options.verify_peer_callback = nullptr;
verify_options.verify_peer_callback_userdata = nullptr;
verify_options.verify_peer_destruct = nullptr;
GPR_ASSERT(verify_peer_options_test(&verify_options));
GPR_ASSERT(strlen(callback_target_host) == 0);
GPR_ASSERT(strlen(callback_target_pem) == 0);
GPR_ASSERT(callback_userdata == nullptr);
GPR_ASSERT(destruct_userdata == nullptr);
// Running with the callbacks and verify we get the expected values
verify_options.verify_peer_callback = verify_callback;
verify_options.verify_peer_callback_userdata = static_cast<void*>(&userdata);
verify_options.verify_peer_destruct = verify_destruct;
GPR_ASSERT(verify_peer_options_test(&verify_options));
GPR_ASSERT(strcmp(callback_target_host, "foo.test.google.fr") == 0);
GPR_ASSERT(strcmp(callback_target_pem, server_cert) == 0);
GPR_ASSERT(callback_userdata == static_cast<void*>(&userdata));
GPR_ASSERT(destruct_userdata == static_cast<void*>(&userdata));
// If the callback returns non-zero, initializing the channel should fail.
callback_return_value = 1;
GPR_ASSERT(!verify_peer_options_test(&verify_options));
grpc_slice_unref(cert_slice);
return 0;
}
#else /* GRPC_POSIX_SOCKET_TCP */
int main(int argc, char** argv) { return 1; }
#endif /* GRPC_POSIX_SOCKET_TCP */
<commit_msg>fix concurrent file read flake<commit_after>/*
*
* Copyright 2018 gRPC 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 "src/core/lib/iomgr/port.h"
// This test won't work except with posix sockets enabled
#ifdef GRPC_POSIX_SOCKET_TCP
#include <arpa/inet.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string>
#include "absl/strings/str_cat.h"
#include <grpc/grpc.h>
#include <grpc/grpc_security.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/load_file.h"
#include "test/core/util/port.h"
#include "test/core/util/test_config.h"
#define SSL_CERT_PATH "src/core/tsi/test_creds/server1.pem"
#define SSL_KEY_PATH "src/core/tsi/test_creds/server1.key"
#define SSL_CA_PATH "src/core/tsi/test_creds/ca.pem"
// Simple gRPC server. This listens until client_handshake_complete occurs.
static gpr_event client_handshake_complete;
static void server_thread(void* arg) {
const int port = *static_cast<int*>(arg);
// Load key pair and establish server SSL credentials.
grpc_ssl_pem_key_cert_pair pem_key_cert_pair;
grpc_slice ca_slice, cert_slice, key_slice;
GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
grpc_load_file(SSL_CA_PATH, 1, &ca_slice)));
GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
grpc_load_file(SSL_CERT_PATH, 1, &cert_slice)));
GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
grpc_load_file(SSL_KEY_PATH, 1, &key_slice)));
const char* ca_cert =
reinterpret_cast<const char*> GRPC_SLICE_START_PTR(ca_slice);
pem_key_cert_pair.private_key =
reinterpret_cast<const char*> GRPC_SLICE_START_PTR(key_slice);
pem_key_cert_pair.cert_chain =
reinterpret_cast<const char*> GRPC_SLICE_START_PTR(cert_slice);
grpc_server_credentials* ssl_creds = grpc_ssl_server_credentials_create(
ca_cert, &pem_key_cert_pair, 1, 0, nullptr);
// Start server listening on local port.
std::string addr = absl::StrCat("127.0.0.1:", port);
grpc_server* server = grpc_server_create(nullptr, nullptr);
GPR_ASSERT(
grpc_server_add_secure_http2_port(server, addr.c_str(), ssl_creds));
grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
grpc_server_register_completion_queue(server, cq, nullptr);
grpc_server_start(server);
// Wait a bounded number of time until client_handshake_complete is set,
// sleeping between polls. The total time spent (deadline * retries)
// should be strictly greater than the client retry limit so that the
// client will always timeout first.
int retries = 60;
while (!gpr_event_get(&client_handshake_complete) && retries-- > 0) {
const gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(1);
grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr);
GPR_ASSERT(ev.type == GRPC_QUEUE_TIMEOUT);
}
gpr_log(GPR_INFO, "Shutting down server");
grpc_server_shutdown_and_notify(server, cq, nullptr);
grpc_server_cancel_all_calls(server);
grpc_completion_queue_shutdown(cq);
const gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(60);
grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr);
GPR_ASSERT(ev.type == GRPC_OP_COMPLETE);
grpc_server_destroy(server);
grpc_completion_queue_destroy(cq);
grpc_server_credentials_release(ssl_creds);
grpc_slice_unref(cert_slice);
grpc_slice_unref(key_slice);
grpc_slice_unref(ca_slice);
}
// This test launches a minimal TLS grpc server on a separate thread and then
// establishes a TLS handshake via the core library to the server. The client
// uses the supplied verify options.
static bool verify_peer_options_test(verify_peer_options* verify_options) {
bool success = true;
grpc_init();
int port = grpc_pick_unused_port_or_die();
gpr_event_init(&client_handshake_complete);
// Load key pair and establish client SSL credentials.
// NOTE: we intentionally load the credential files before starting
// the server thread because grpc_load_file can experience trouble
// when two threads attempt to load the same file concurrently
// and server thread also reads the same files as soon as it starts.
// See https://github.com/grpc/grpc/issues/23503 for details.
grpc_ssl_pem_key_cert_pair pem_key_cert_pair;
grpc_slice ca_slice, cert_slice, key_slice;
GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
grpc_load_file(SSL_CA_PATH, 1, &ca_slice)));
GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
grpc_load_file(SSL_CERT_PATH, 1, &cert_slice)));
GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
grpc_load_file(SSL_KEY_PATH, 1, &key_slice)));
const char* ca_cert =
reinterpret_cast<const char*> GRPC_SLICE_START_PTR(ca_slice);
pem_key_cert_pair.private_key =
reinterpret_cast<const char*> GRPC_SLICE_START_PTR(key_slice);
pem_key_cert_pair.cert_chain =
reinterpret_cast<const char*> GRPC_SLICE_START_PTR(cert_slice);
grpc_channel_credentials* ssl_creds = grpc_ssl_credentials_create(
ca_cert, &pem_key_cert_pair, verify_options, nullptr);
// Launch the gRPC server thread.
bool ok;
grpc_core::Thread thd("grpc_client_ssl_test", server_thread, &port, &ok);
GPR_ASSERT(ok);
thd.Start();
// Establish a channel pointing at the TLS server. Since the gRPC runtime is
// lazy, this won't necessarily establish a connection yet.
std::string target = absl::StrCat("127.0.0.1:", port);
grpc_arg ssl_name_override = {
GRPC_ARG_STRING,
const_cast<char*>(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG),
{const_cast<char*>("foo.test.google.fr")}};
grpc_channel_args grpc_args;
grpc_args.num_args = 1;
grpc_args.args = &ssl_name_override;
grpc_channel* channel = grpc_secure_channel_create(ssl_creds, target.c_str(),
&grpc_args, nullptr);
GPR_ASSERT(channel);
// Initially the channel will be idle, the
// grpc_channel_check_connectivity_state triggers an attempt to connect.
GPR_ASSERT(grpc_channel_check_connectivity_state(
channel, 1 /* try_to_connect */) == GRPC_CHANNEL_IDLE);
// Wait a bounded number of times for the channel to be ready. When the
// channel is ready, the initial TLS handshake will have successfully
// completed. The total time spent on the client side (retries * deadline)
// should be greater than the server side time limit.
int retries = 10;
grpc_connectivity_state state = GRPC_CHANNEL_IDLE;
grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
while (state != GRPC_CHANNEL_READY && retries-- > 0) {
grpc_channel_watch_connectivity_state(
channel, state, grpc_timeout_seconds_to_deadline(3), cq, nullptr);
gpr_timespec cq_deadline = grpc_timeout_seconds_to_deadline(5);
grpc_event ev = grpc_completion_queue_next(cq, cq_deadline, nullptr);
GPR_ASSERT(ev.type == GRPC_OP_COMPLETE);
state =
grpc_channel_check_connectivity_state(channel, 0 /* try_to_connect */);
}
grpc_completion_queue_destroy(cq);
if (retries < 0) {
success = false;
}
grpc_channel_destroy(channel);
grpc_channel_credentials_release(ssl_creds);
grpc_slice_unref(cert_slice);
grpc_slice_unref(key_slice);
grpc_slice_unref(ca_slice);
// Now that the client is completely cleaned up, trigger the server to
// shutdown
gpr_event_set(&client_handshake_complete, &client_handshake_complete);
// Wait for the server to completely shutdown
thd.Join();
grpc_shutdown();
return success;
}
static int callback_return_value = 0;
static char callback_target_host[4096];
static char callback_target_pem[4096];
static void* callback_userdata = nullptr;
static void* destruct_userdata = nullptr;
static int verify_callback(const char* target_host, const char* target_pem,
void* userdata) {
if (target_host != nullptr) {
snprintf(callback_target_host, sizeof(callback_target_host), "%s",
target_host);
} else {
callback_target_host[0] = '\0';
}
if (target_pem != nullptr) {
snprintf(callback_target_pem, sizeof(callback_target_pem), "%s",
target_pem);
} else {
callback_target_pem[0] = '\0';
}
callback_userdata = userdata;
return callback_return_value;
}
static void verify_destruct(void* userdata) { destruct_userdata = userdata; }
int main(int argc, char* argv[]) {
grpc::testing::TestEnvironment env(argc, argv);
int userdata = 42;
verify_peer_options verify_options;
// Load the server's cert so that we can assert it gets passed to the callback
grpc_slice cert_slice;
GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
grpc_load_file(SSL_CERT_PATH, 1, &cert_slice)));
const char* server_cert =
reinterpret_cast<const char*> GRPC_SLICE_START_PTR(cert_slice);
// Running with all-null values should have no effect
verify_options.verify_peer_callback = nullptr;
verify_options.verify_peer_callback_userdata = nullptr;
verify_options.verify_peer_destruct = nullptr;
GPR_ASSERT(verify_peer_options_test(&verify_options));
GPR_ASSERT(strlen(callback_target_host) == 0);
GPR_ASSERT(strlen(callback_target_pem) == 0);
GPR_ASSERT(callback_userdata == nullptr);
GPR_ASSERT(destruct_userdata == nullptr);
// Running with the callbacks and verify we get the expected values
verify_options.verify_peer_callback = verify_callback;
verify_options.verify_peer_callback_userdata = static_cast<void*>(&userdata);
verify_options.verify_peer_destruct = verify_destruct;
GPR_ASSERT(verify_peer_options_test(&verify_options));
GPR_ASSERT(strcmp(callback_target_host, "foo.test.google.fr") == 0);
GPR_ASSERT(strcmp(callback_target_pem, server_cert) == 0);
GPR_ASSERT(callback_userdata == static_cast<void*>(&userdata));
GPR_ASSERT(destruct_userdata == static_cast<void*>(&userdata));
// If the callback returns non-zero, initializing the channel should fail.
callback_return_value = 1;
GPR_ASSERT(!verify_peer_options_test(&verify_options));
grpc_slice_unref(cert_slice);
return 0;
}
#else /* GRPC_POSIX_SOCKET_TCP */
int main(int argc, char** argv) { return 1; }
#endif /* GRPC_POSIX_SOCKET_TCP */
<|endoftext|>
|
<commit_before>//----------------------------------*-C++-*----------------------------------//
/*!
* \file core/Transfer_Data_Field.hh
* \author Stuart Slattery
* \date Fri Nov 18 11:57:58 2011
* \brief Transfer_Data_Field class definition.
* \note Copyright (C) 2011 Oak Ridge National Laboratory, UT-Battelle, LLC.
*/
//---------------------------------------------------------------------------//
// $Id: template.hh,v 1.4 2008/01/02 17:18:47 9te Exp $
//---------------------------------------------------------------------------//
#ifndef core_Transfer_Data_Field_hh
#define core_Transfer_Data_Field_hh
#include <string>
#include "Transfer_Data_Source.hh"
#include "Transfer_Data_Target.hh"
#include "Transfer_Map.hh"
#include "Teuchos_RCP.hpp"
namespace coupler
{
//===========================================================================//
/*!
* \class Transfer_Data_Field
* \brief Field type for data transfers. This exists for more a explicit
* defintion of fields in the coupler user interface.
*/
/*!
* \example core/test/tstTransfer_Data_Field.cc
*
* Test of Transfer_Data_Field.
*/
//===========================================================================//
template<class DataType_T>
class Transfer_Data_Field
{
public:
//@{
//! Useful typedefs.
typedef DataType_T DataType;
typedef Transfer_Data_Source<DataType> Transfer_Data_Source_t;
typedef Teuchos::RCP<Transfer_Data_Source_t> RCP_Transfer_Data_Source;
typedef Transfer_Data_Target<DataType> Transfer_Data_Target_t;
typedef Teuchos::RCP<Transfer_Data_Target_t> RCP_Transfer_Data_Target;
typedef Teuchos::RCP<Transfer_Map> RCP_Transfer_Map;
//@}
private:
// Field name.
std::string d_field_name;
// Data transfer source implemenation.
RCP_Transfer_Data_Source d_source;
// Data transfer target implemenation.
RCP_Transfer_Data_Target d_target;
// Topology map for transfer from the source to the target.
RCP_Transfer_Map d_map;
// Boolean for scalar field.
bool d_scalar;
// Boolean for field mapping. True if mapping complete.
bool d_mapped;
public:
// Constructor.
Transfer_Data_Field(const std::string &field_name,
RCP_Transfer_Data_Source source,
RCP_Transfer_Data_Target target,
bool scalar);
// Destructor.
~Transfer_Data_Field();
//! Get the field name.
const std::string& name()
{ return d_field_name; }
//! Get the transfer data source.
RCP_Transfer_Data_Source source()
{ return d_source; }
//! Get the transfer data target.
RCP_Transfer_Data_Target target()
{ return d_target; }
//! Set the topology map.
void set_map(RCP_Transfer_Map transfer_map);
//! Get the topology map.
RCP_Transfer_Map get_map()
{ return d_map; }
//! Return the scalar boolean.
bool is_scalar()
{ return d_scalar; }
//! Return the mapped boolean.
bool is_mapped()
{ return d_mapped; }
};
} // end namespace coupler
#endif // core_Transfer_Data_Field_hh
//---------------------------------------------------------------------------//
// end of core/Transfer_Data_Field.hh
//---------------------------------------------------------------------------//
<commit_msg>Fixed a comment typo in the Transfer_Data_Field and set the scalar boolean in the constructor to default to false. This means that default fields are distributed.<commit_after>//----------------------------------*-C++-*----------------------------------//
/*!
* \file core/Transfer_Data_Field.hh
* \author Stuart Slattery
* \date Fri Nov 18 11:57:58 2011
* \brief Transfer_Data_Field class definition.
* \note Copyright (C) 2011 Oak Ridge National Laboratory, UT-Battelle, LLC.
*/
//---------------------------------------------------------------------------//
// $Id: template.hh,v 1.4 2008/01/02 17:18:47 9te Exp $
//---------------------------------------------------------------------------//
#ifndef core_Transfer_Data_Field_hh
#define core_Transfer_Data_Field_hh
#include <string>
#include "Transfer_Data_Source.hh"
#include "Transfer_Data_Target.hh"
#include "Transfer_Map.hh"
#include "Teuchos_RCP.hpp"
namespace coupler
{
//===========================================================================//
/*!
* \class Transfer_Data_Field
* \brief Field type for data transfers. This exists for more a explicit
* definition of fields in the coupler user interface.
*/
/*!
* \example core/test/tstTransfer_Data_Field.cc
*
* Test of Transfer_Data_Field.
*/
//===========================================================================//
template<class DataType_T>
class Transfer_Data_Field
{
public:
//@{
//! Useful typedefs.
typedef DataType_T DataType;
typedef Transfer_Data_Source<DataType> Transfer_Data_Source_t;
typedef Teuchos::RCP<Transfer_Data_Source_t> RCP_Transfer_Data_Source;
typedef Transfer_Data_Target<DataType> Transfer_Data_Target_t;
typedef Teuchos::RCP<Transfer_Data_Target_t> RCP_Transfer_Data_Target;
typedef Teuchos::RCP<Transfer_Map> RCP_Transfer_Map;
//@}
private:
// Field name.
std::string d_field_name;
// Data transfer source implemenation.
RCP_Transfer_Data_Source d_source;
// Data transfer target implemenation.
RCP_Transfer_Data_Target d_target;
// Topology map for transfer from the source to the target.
RCP_Transfer_Map d_map;
// Boolean for scalar field.
bool d_scalar;
// Boolean for field mapping. True if mapping complete.
bool d_mapped;
public:
// Constructor.
Transfer_Data_Field(const std::string &field_name,
RCP_Transfer_Data_Source source,
RCP_Transfer_Data_Target target,
bool scalar = false);
// Destructor.
~Transfer_Data_Field();
//! Get the field name.
const std::string& name()
{ return d_field_name; }
//! Get the transfer data source.
RCP_Transfer_Data_Source source()
{ return d_source; }
//! Get the transfer data target.
RCP_Transfer_Data_Target target()
{ return d_target; }
//! Set the topology map.
void set_map(RCP_Transfer_Map transfer_map);
//! Get the topology map.
RCP_Transfer_Map get_map()
{ return d_map; }
//! Return the scalar boolean.
bool is_scalar()
{ return d_scalar; }
//! Return the mapped boolean.
bool is_mapped()
{ return d_mapped; }
};
} // end namespace coupler
#endif // core_Transfer_Data_Field_hh
//---------------------------------------------------------------------------//
// end of core/Transfer_Data_Field.hh
//---------------------------------------------------------------------------//
<|endoftext|>
|
<commit_before>// Copyright 2010 Google Inc. All Rights Reserved.
// Author: jacobsa@google.com (Aaron Jacobs)
//
// 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 "gjstest/internal/cpp/v8_utils.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/stringprintf.h"
using v8::Array;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Handle;
using v8::Isolate;
using v8::Local;
using v8::Message;
using v8::ObjectTemplate;
using v8::Persistent;
using v8::ScriptCompiler;
using v8::ScriptOrigin;
using v8::StackFrame;
using v8::StackTrace;
using v8::String;
using v8::TryCatch;
using v8::UnboundScript;
using v8::Value;
namespace gjstest {
static Local<String> ConvertString(const std::string& s) {
return String::NewFromUtf8(
Isolate::GetCurrent(),
s.data(),
String::kNormalString,
s.size());
}
std::string ConvertToString(const Handle<Value>& value) {
const String::Utf8Value utf8_value(value);
return std::string(*utf8_value, utf8_value.length());
}
void ConvertToStringVector(
const v8::Handle<v8::Value>& value,
std::vector<std::string>* result) {
CHECK(!value.IsEmpty()) << "value must be non-empty";
CHECK(value->IsArray()) << "value must be an array";
Array* array = Array::Cast(*value);
const uint32 length = array->Length();
for (uint32 i = 0; i < length; ++i) {
result->push_back(ConvertToString(array->Get(i)));
}
}
static Local<UnboundScript> Compile(
const std::string& js,
const std::string& filename) {
if (filename.empty()) {
ScriptCompiler::Source source(ConvertString(js));
return ScriptCompiler::CompileUnbound(
Isolate::GetCurrent(),
&source);
}
ScriptCompiler::Source source(
ConvertString(js),
ScriptOrigin(ConvertString(filename)));
return ScriptCompiler::CompileUnbound(
Isolate::GetCurrent(),
&source);
}
Local<Value> ExecuteJs(
const std::string& js,
const std::string& filename) {
// Attempt to compile the script.
const Local<UnboundScript> script = Compile(js, filename);
if (script.IsEmpty()) {
return Local<Value>();
}
// Run the script.
return script->BindToCurrentContext()->Run();
}
std::string DescribeError(const TryCatch& try_catch) {
const std::string exception = ConvertToString(try_catch.Exception());
const Local<Message> message = try_catch.Message();
// If there's no message, just return the exception.
if (message.IsEmpty()) return exception;
// We want to return a message of the form:
//
// foo.js:7: ReferenceError: blah is not defined.
//
const std::string filename =
ConvertToString(message->GetScriptResourceName());
const int line = message->GetLineNumber();
// Sometimes for multi-line errors there is no line number.
if (!line) {
return StringPrintf("%s: %s", filename.c_str(), exception.c_str());
}
return StringPrintf("%s:%i: %s", filename.c_str(), line, exception.c_str());
}
static void RunAssociatedCallback(
const v8::FunctionCallbackInfo<Value>& cb_info) {
// Unwrap the callback that was associated with this function.
const Local<Value> data = cb_info.Data();
CHECK(data->IsExternal());
const External* external = External::Cast(*data);
V8FunctionCallback* callback =
static_cast<V8FunctionCallback*>(external->Value());
cb_info.GetReturnValue().Set(callback->Run(cb_info));
}
template <typename T, typename C>
static void DeleteCallback(
Isolate* isolate,
Persistent<T>* ref,
C* callback) {
ref->Dispose();
delete callback;
}
void RegisterFunction(
const std::string& name,
V8FunctionCallback* callback,
Handle<ObjectTemplate>* tmpl) {
CHECK(callback->IsRepeatable());
// Wrap up the callback in an External that can be decoded later.
const Local<Value> data = External::New(callback);
// Create a function template with the wrapped callback as associated data,
// and export it.
(*tmpl)->Set(
ConvertString(name),
FunctionTemplate::New(RunAssociatedCallback, data));
// Dispose of the callback when the object template goes away.
Persistent<ObjectTemplate> weak_ref(
CHECK_NOTNULL(Isolate::GetCurrent()),
*tmpl);
weak_ref.MakeWeak(
callback,
&DeleteCallback);
}
Local<Function> MakeFunction(
const std::string& name,
V8FunctionCallback* callback) {
CHECK(callback->IsRepeatable());
// Wrap up the callback in an External that can be decoded later.
const Local<Value> data = External::New(callback);
// Create a function template with the wrapped callback as associated data,
// and instantiate it.
const Local<Function> result =
FunctionTemplate::New(RunAssociatedCallback, data)->GetFunction();
result->SetName(ConvertString(name));
// Dispose of the callback when the function is garbage collected.
Persistent<Function> weak_ref(
CHECK_NOTNULL(Isolate::GetCurrent()),
result);
weak_ref.MakeWeak(
callback,
&DeleteCallback);
return result;
}
} // namespace gjstest
<commit_msg>Fixed missing Isolate parameters, due to yet another v8 change:<commit_after>// Copyright 2010 Google Inc. All Rights Reserved.
// Author: jacobsa@google.com (Aaron Jacobs)
//
// 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 "gjstest/internal/cpp/v8_utils.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/stringprintf.h"
using v8::Array;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Handle;
using v8::Isolate;
using v8::Local;
using v8::Message;
using v8::ObjectTemplate;
using v8::Persistent;
using v8::ScriptCompiler;
using v8::ScriptOrigin;
using v8::StackFrame;
using v8::StackTrace;
using v8::String;
using v8::TryCatch;
using v8::UnboundScript;
using v8::Value;
namespace gjstest {
static Local<String> ConvertString(const std::string& s) {
return String::NewFromUtf8(
Isolate::GetCurrent(),
s.data(),
String::kNormalString,
s.size());
}
std::string ConvertToString(const Handle<Value>& value) {
const String::Utf8Value utf8_value(value);
return std::string(*utf8_value, utf8_value.length());
}
void ConvertToStringVector(
const v8::Handle<v8::Value>& value,
std::vector<std::string>* result) {
CHECK(!value.IsEmpty()) << "value must be non-empty";
CHECK(value->IsArray()) << "value must be an array";
Array* array = Array::Cast(*value);
const uint32 length = array->Length();
for (uint32 i = 0; i < length; ++i) {
result->push_back(ConvertToString(array->Get(i)));
}
}
static Local<UnboundScript> Compile(
const std::string& js,
const std::string& filename) {
if (filename.empty()) {
ScriptCompiler::Source source(ConvertString(js));
return ScriptCompiler::CompileUnbound(
Isolate::GetCurrent(),
&source);
}
ScriptCompiler::Source source(
ConvertString(js),
ScriptOrigin(ConvertString(filename)));
return ScriptCompiler::CompileUnbound(
Isolate::GetCurrent(),
&source);
}
Local<Value> ExecuteJs(
const std::string& js,
const std::string& filename) {
// Attempt to compile the script.
const Local<UnboundScript> script = Compile(js, filename);
if (script.IsEmpty()) {
return Local<Value>();
}
// Run the script.
return script->BindToCurrentContext()->Run();
}
std::string DescribeError(const TryCatch& try_catch) {
const std::string exception = ConvertToString(try_catch.Exception());
const Local<Message> message = try_catch.Message();
// If there's no message, just return the exception.
if (message.IsEmpty()) return exception;
// We want to return a message of the form:
//
// foo.js:7: ReferenceError: blah is not defined.
//
const std::string filename =
ConvertToString(message->GetScriptResourceName());
const int line = message->GetLineNumber();
// Sometimes for multi-line errors there is no line number.
if (!line) {
return StringPrintf("%s: %s", filename.c_str(), exception.c_str());
}
return StringPrintf("%s:%i: %s", filename.c_str(), line, exception.c_str());
}
static void RunAssociatedCallback(
const v8::FunctionCallbackInfo<Value>& cb_info) {
// Unwrap the callback that was associated with this function.
const Local<Value> data = cb_info.Data();
CHECK(data->IsExternal());
const External* external = External::Cast(*data);
V8FunctionCallback* callback =
static_cast<V8FunctionCallback*>(external->Value());
cb_info.GetReturnValue().Set(callback->Run(cb_info));
}
template <typename T, typename C>
static void DeleteCallback(
Isolate* isolate,
Persistent<T>* ref,
C* callback) {
ref->Dispose();
delete callback;
}
void RegisterFunction(
const std::string& name,
V8FunctionCallback* callback,
Handle<ObjectTemplate>* tmpl) {
CHECK(callback->IsRepeatable());
// Wrap up the callback in an External that can be decoded later.
const Local<Value> data = External::New(Isolate::GetCurrent(), callback);
// Create a function template with the wrapped callback as associated data,
// and export it.
(*tmpl)->Set(
ConvertString(name),
FunctionTemplate::New(
Isolate::GetCurrent(),
RunAssociatedCallback,
data));
// Dispose of the callback when the object template goes away.
Persistent<ObjectTemplate> weak_ref(
CHECK_NOTNULL(Isolate::GetCurrent()),
*tmpl);
weak_ref.MakeWeak(
callback,
&DeleteCallback);
}
Local<Function> MakeFunction(
const std::string& name,
V8FunctionCallback* callback) {
CHECK(callback->IsRepeatable());
// Wrap up the callback in an External that can be decoded later.
const Local<Value> data =
External::New(
Isolate::GetCurrent(),
callback);
// Create a function template with the wrapped callback as associated data,
// and instantiate it.
const Local<Function> result =
FunctionTemplate::New(
Isolate::GetCurrent(),
RunAssociatedCallback,
data)
->GetFunction();
result->SetName(ConvertString(name));
// Dispose of the callback when the function is garbage collected.
Persistent<Function> weak_ref(
CHECK_NOTNULL(Isolate::GetCurrent()),
result);
weak_ref.MakeWeak(
callback,
&DeleteCallback);
return result;
}
} // namespace gjstest
<|endoftext|>
|
<commit_before>#include "ff.h"
#include "utils/string_utils.hpp"
extern "C" {
WCHAR ff_uni2oem (DWORD uni, WORD cp)
{
}
};
<commit_msg>Remove: cleanup<commit_after><|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
#include <test/models/utility.hpp>
#include <fstream>
#include <stan/io/dump.hpp>
#include <stan/mcmc/chains.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
class LogisticSpeedTest :
public testing::Test {
public:
static const size_t num_chains;
static bool has_R;
static bool has_jags;
static std::string path;
std::string Rscript;
std::vector<std::string> data_files;
static void SetUpTestCase() {
std::cout << "-----\n\n";
std::vector<std::string> model_path;
model_path.push_back("models");
model_path.push_back("speed");
model_path.push_back("logistic");
path = convert_model_path(model_path);
}
// returns number of milliseconds to execute commands;
/**
* Executes the Stan model and returns elapsed time.
*
* The Stan model is executed <code>num_chains</code> times.
* The <code>command</code> argument has the basic Stan command
* to run. The <code>filename</code> argument has the basename
* for the output samples. This is append with the chain id and
* the suffix '.csv'.
*
* The standard output stream and error output stream for each
* chain is recorded and output in command_outputs.
*
*
* @param[in] command The command to run.
* @param[in] filename The output filename without a suffix.
* @param[out] command_outputs The captured output per chain.
*
* @return Elapsed time running the commands in milliseconds.
*/
long run_stan(const std::string& command, const std::string& filename, std::vector<std::string> command_outputs) {
using boost::posix_time::ptime;
long time = 0;
for (size_t chain = 0; chain < num_chains; chain++) {
std::stringstream command_chain;
command_chain << command;
command_chain << " --chain_id=" << chain
<< " --samples=" << path << get_path_separator()
<< filename << ".chain_" << chain << ".csv";
std::string command_output;
try {
ptime time_start(boost::posix_time::microsec_clock::universal_time()); // start timer
command_output = run_command(command_chain.str());
ptime time_end(boost::posix_time::microsec_clock::universal_time()); // end timer
time += (time_end - time_start).total_milliseconds();
} catch(...) {
ADD_FAILURE() << "Failed running command: " << command_chain.str();
}
command_outputs.push_back(command_output);
}
return time;
}
stan::mcmc::chains<> create_chains(const std::string& filename) {
std::stringstream samples;
samples << path << get_path_separator()
<< filename << ".chain_0.csv";
std::vector<std::string> names;
std::vector<std::vector<size_t> > dimss;
stan::mcmc::read_variables(samples.str(), 2U,
names, dimss);
stan::mcmc::chains<> chains(num_chains, names, dimss);
for (size_t chain = 0; chain < num_chains; chain++) {
samples.str("");
samples << path << get_path_separator()
<< filename << ".chain_" << chain << ".csv";
stan::mcmc::add_chain(chains, chain, samples.str(), 2U);
}
return chains;
}
void get_beta(const std::string& filename, std::vector<double>& beta) {
std::stringstream param_filename;
param_filename << path << get_path_separator() << filename
<< "_param.Rdata";
std::ifstream param_ifstream(param_filename.str().c_str());
stan::io::dump param_values(param_ifstream);
beta = param_values.vals_r("beta");
for (size_t i = 0; i < beta.size(); i++) {
std::cout << "beta[" << i << "]: " << beta[i] << std::endl;
}
}
void test_logistic_speed_stan(const std::string& filename, size_t iterations) {
if (!has_R)
return;
std::stringstream command;
command << path << get_path_separator() << "logistic"
<< " --data=" << path << get_path_separator() << filename << ".Rdata"
<< " --iter=" << iterations
<< " --refresh=" << iterations;
std::vector<std::string> command_outputs;
long time = run_stan(command.str(), filename, command_outputs);
stan::mcmc::chains<> chains = create_chains(filename);
std::vector<double> beta;
get_beta(filename, beta);
std::cout << "************************************************************\n"
<< "milliseconds: " << time << std::endl
<< "************************************************************\n";
size_t num_params = chains.num_params();
for (size_t i = 0; i < num_params; i++) {
std::cout << "------------------------------------------------------------\n";
std::cout << "beta[" << i << "]" << std::endl;
std::cout << "\tmean: " << chains.mean(i) << std::endl;
std::cout << "\tsd: " << chains.sd(i) << std::endl;
std::cout << "\tneff: " << chains.effective_sample_size(i) << std::endl;
std::cout << "\tsplit R hat: " << chains.split_potential_scale_reduction(i) << std::endl;
}
SUCCEED();
}
};
const size_t LogisticSpeedTest::num_chains = 4;
bool LogisticSpeedTest::has_R;
bool LogisticSpeedTest::has_jags;
std::string LogisticSpeedTest::path;
TEST_F(LogisticSpeedTest,Prerequisites) {
std::string command;
command = "Rscript --version";
try {
run_command(command);
has_R = true;
} catch (...) {
std::cout << "System does not have Rscript available" << std::endl
<< "Failed to run: " << command << std::endl;
}
std::vector<std::string> test_file;
test_file.push_back("src");
test_file.push_back("models");
test_file.push_back("speed");
test_file.push_back("empty.jags");
command = "jags ";
command += path;
try {
run_command(command);
has_jags = true;
} catch (...) {
std::cout << "System does not have jags available" << std::endl
<< "Failed to run: " << command << std::endl;
}
Rscript = "logistic_generate_data.R";
data_files.push_back("logistic_128_2");
data_files.push_back("logistic_1024_2");
data_files.push_back("logistic_4096_2");
}
TEST_F(LogisticSpeedTest,GenerateData) {
if (!has_R) {
std::cout << "No R available" << std::endl;
return; // should this fail? probably
}
bool has_data = true;
for (size_t i = 0; i < data_files.size() && has_data; i++) {
std::string data_file = path;
data_file += get_path_separator();
data_file += data_files[i];
data_file += ".Rdata";
std::ifstream file(data_file.c_str());
if (!file)
has_data = false;
}
if (has_data)
return;
// generate data using R script
std::string command;
command = "cd ";
command += path;
command += " && ";
command += "Rscript ";
command += Rscript;
// no guarantee here that we have the right files
ASSERT_NO_THROW(run_command(command))
<< command;
SUCCEED();
}
TEST_F(LogisticSpeedTest,Stan_128_2) {
test_logistic_speed_stan("logistic_128_2", 250U);
}
TEST_F(LogisticSpeedTest,Stan_1024_2) {
test_logistic_speed_stan("logistic_1024_2", 250U);
}
TEST_F(LogisticSpeedTest,Stan_4096_2) {
test_logistic_speed_stan("logistic_4096_2", 250U);
}
<commit_msg>speed-comparisons: refactoring test<commit_after>#include <gtest/gtest.h>
#include <test/models/utility.hpp>
#include <fstream>
#include <stan/io/dump.hpp>
#include <stan/mcmc/chains.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
class LogisticSpeedTest :
public testing::Test {
public:
static const size_t num_chains;
static bool has_R;
static bool has_jags;
static std::string path;
std::string Rscript;
std::vector<std::string> data_files;
static void SetUpTestCase() {
std::cout << "-----\n\n";
std::vector<std::string> model_path;
model_path.push_back("models");
model_path.push_back("speed");
model_path.push_back("logistic");
path = convert_model_path(model_path);
}
// returns number of milliseconds to execute commands;
/**
* Executes the Stan model and returns elapsed time.
*
* The Stan model is executed <code>num_chains</code> times.
* The <code>command</code> argument has the basic Stan command
* to run. The <code>filename</code> argument has the basename
* for the output samples. This is append with the chain id and
* the suffix '.csv'.
*
* The standard output stream and error output stream for each
* chain is recorded and output in command_outputs.
*
*
* @param[in] command The command to run.
* @param[in] filename The output filename without a suffix.
* @param[out] command_outputs The captured output per chain.
*
* @return Elapsed time running the commands in milliseconds.
*/
long run_stan(const std::string& command, const std::string& filename, std::vector<std::string> command_outputs) {
using boost::posix_time::ptime;
long time = 0;
for (size_t chain = 0; chain < num_chains; chain++) {
std::stringstream command_chain;
command_chain << command;
command_chain << " --chain_id=" << chain
<< " --samples=" << path << get_path_separator()
<< filename << ".chain_" << chain << ".csv";
std::string command_output;
try {
ptime time_start(boost::posix_time::microsec_clock::universal_time()); // start timer
command_output = run_command(command_chain.str());
ptime time_end(boost::posix_time::microsec_clock::universal_time()); // end timer
time += (time_end - time_start).total_milliseconds();
} catch(...) {
ADD_FAILURE() << "Failed running command: " << command_chain.str();
}
command_outputs.push_back(command_output);
}
return time;
}
stan::mcmc::chains<> create_chains(const std::string& filename) {
std::stringstream samples;
samples << path << get_path_separator()
<< filename << ".chain_0.csv";
std::vector<std::string> names;
std::vector<std::vector<size_t> > dimss;
stan::mcmc::read_variables(samples.str(), 2U,
names, dimss);
stan::mcmc::chains<> chains(num_chains, names, dimss);
for (size_t chain = 0; chain < num_chains; chain++) {
samples.str("");
samples << path << get_path_separator()
<< filename << ".chain_" << chain << ".csv";
stan::mcmc::add_chain(chains, chain, samples.str(), 2U);
}
return chains;
}
void get_beta(const std::string& filename, std::vector<double>& beta) {
std::stringstream param_filename;
param_filename << path << get_path_separator() << filename
<< "_param.Rdata";
std::ifstream param_ifstream(param_filename.str().c_str());
stan::io::dump param_values(param_ifstream);
beta = param_values.vals_r("beta");
for (size_t i = 0; i < beta.size(); i++) {
std::cout << "beta[" << i << "]: " << beta[i] << std::endl;
}
}
void test_logistic_speed_stan(const std::string& filename, size_t iterations) {
if (!has_R)
return;
std::stringstream command;
command << path << get_path_separator() << "logistic"
<< " --data=" << path << get_path_separator() << filename << ".Rdata"
<< " --iter=" << iterations
<< " --refresh=" << iterations;
std::vector<std::string> command_outputs;
long time = run_stan(command.str(), filename, command_outputs);
stan::mcmc::chains<> chains = create_chains(filename);
std::vector<double> beta;
get_beta(filename, beta);
std::cout << "************************************************************\n"
<< "milliseconds: " << time << std::endl
<< "************************************************************\n";
size_t num_params = chains.num_params();
for (size_t i = 0; i < num_params; i++) {
std::cout << "------------------------------------------------------------\n";
std::cout << "beta[" << i << "]" << std::endl;
std::cout << "\tmean: " << chains.mean(i) << std::endl;
std::cout << "\tsd: " << chains.sd(i) << std::endl;
std::cout << "\tneff: " << chains.effective_sample_size(i) << std::endl;
std::cout << "\tsplit R hat: " << chains.split_potential_scale_reduction(i) << std::endl;
}
SUCCEED();
}
};
const size_t LogisticSpeedTest::num_chains = 4;
bool LogisticSpeedTest::has_R;
bool LogisticSpeedTest::has_jags;
std::string LogisticSpeedTest::path;
TEST_F(LogisticSpeedTest,Prerequisites) {
std::string command;
command = "Rscript --version";
try {
run_command(command);
has_R = true;
} catch (...) {
std::cout << "System does not have Rscript available" << std::endl
<< "Failed to run: " << command << std::endl;
}
std::vector<std::string> test_file;
test_file.push_back("src");
test_file.push_back("models");
test_file.push_back("speed");
test_file.push_back("empty.jags");
command = "jags ";
command += path;
try {
run_command(command);
has_jags = true;
} catch (...) {
std::cout << "System does not have jags available" << std::endl
<< "Failed to run: " << command << std::endl;
}
Rscript = "logistic_generate_data.R";
data_files.push_back("logistic_128_2");
data_files.push_back("logistic_1024_2");
data_files.push_back("logistic_4096_2");
}
TEST_F(LogisticSpeedTest,GenerateData) {
if (!has_R) {
std::cout << "No R available" << std::endl;
return; // should this fail? probably
}
bool has_data = true;
for (size_t i = 0; i < data_files.size() && has_data; i++) {
std::string data_file = path;
data_file += get_path_separator();
data_file += data_files[i];
data_file += ".Rdata";
std::ifstream file(data_file.c_str());
if (!file)
has_data = false;
}
if (has_data)
return;
// generate data using R script
std::string command;
command = "cd ";
command += path;
command += " && ";
command += "Rscript ";
command += Rscript;
// no guarantee here that we have the right files
ASSERT_NO_THROW(run_command(command))
<< command;
SUCCEED();
}
TEST_F(LogisticSpeedTest,Stan_128_2) {
test_logistic_speed_stan("logistic_128_2", 250U);
}
TEST_F(LogisticSpeedTest,Stan_1024_2) {
test_logistic_speed_stan("logistic_1024_2", 250U);
}
TEST_F(LogisticSpeedTest,Stan_4096_2) {
test_logistic_speed_stan("logistic_4096_2", 250U);
}
<|endoftext|>
|
<commit_before>// Copyright 2019 Google LLC
//
// 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
//
// https://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 "google/cloud/storage/client.h"
#include "google/cloud/storage/testing/storage_integration_test.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/testing_util/status_matchers.h"
#include <gmock/gmock.h>
#include <algorithm>
#include <cstdio>
#include <fstream>
#include <future>
#include <regex>
#include <thread>
namespace google {
namespace cloud {
namespace storage {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace {
auto const kObjectSize = 16 * 1024;
class ObjectFileMultiThreadedTest
: public google::cloud::storage::testing::StorageIntegrationTest {
protected:
void SetUp() override {
bucket_name_ = google::cloud::internal::GetEnv(
"GOOGLE_CLOUD_CPP_STORAGE_TEST_BUCKET_NAME")
.value_or("");
ASSERT_FALSE(bucket_name_.empty());
auto object_count = google::cloud::internal::GetEnv(
"GOOGLE_CLOUD_CPP_STORAGE_TEST_OBJECT_COUNT");
if (object_count) object_count_ = std::stoi(*object_count);
}
static int ThreadCount() {
static int const kCount = [] {
auto c = static_cast<int>(std::thread::hardware_concurrency());
return (std::max)(c / 2, 8);
}();
return kCount;
}
std::vector<std::string> CreateObjectNames() {
std::vector<std::string> object_names(object_count_);
// Use MakeRandomFilename() because the same name is used for
// the destination file.
std::generate_n(object_names.begin(), object_names.size(),
[this] { return MakeRandomFilename(); });
return object_names;
}
Status CreateSomeObjects(Client client,
std::vector<std::string> const& object_names,
int thread_count, int modulo) {
auto contents = [this] {
std::unique_lock<std::mutex> lk(mu_);
return MakeRandomData(kObjectSize);
}();
int index = 0;
for (auto const& n : object_names) {
if (index++ % thread_count != modulo) continue;
if (modulo == 0) {
std::unique_lock<std::mutex> lk(mu_);
std::cout << '.' << std::flush;
}
auto metadata =
client.InsertObject(bucket_name_, n, contents, IfGenerationMatch(0));
if (!metadata) return metadata.status();
}
return Status();
}
void CreateObjects(Client const& client,
std::vector<std::string> const& object_names) {
// Parallelize the object creation too because it can be slow.
int const thread_count = ThreadCount();
auto create_some_objects = [this, &client, &object_names,
thread_count](int modulo) {
return CreateSomeObjects(client, object_names, thread_count, modulo);
};
std::vector<std::future<Status>> tasks(thread_count);
int modulo = 0;
for (auto& t : tasks) {
t = std::async(std::launch::async, create_some_objects, modulo++);
}
for (auto& t : tasks) {
auto const status = t.get();
EXPECT_STATUS_OK(status);
}
}
Status DeleteSomeObjects(Client client,
std::vector<std::string> const& object_names,
int thread_count, int modulo) {
int index = 0;
Status status;
for (auto const& name : object_names) {
if (index++ % thread_count != modulo) continue;
if (modulo == 0) {
std::unique_lock<std::mutex> lk(mu_);
std::cout << '.' << std::flush;
}
auto result = client.DeleteObject(bucket_name_, name);
if (!result.ok()) status = result;
}
return status;
}
void DeleteObjects(Client const& client,
std::vector<std::string> const& object_names) {
// Parallelize the object deletion too because it can be slow.
int const thread_count = ThreadCount();
auto delete_some_objects = [this, &client, &object_names,
thread_count](int modulo) {
return DeleteSomeObjects(client, object_names, thread_count, modulo);
};
std::vector<std::future<Status>> tasks(thread_count);
int modulo = 0;
for (auto& t : tasks) {
t = std::async(std::launch::async, delete_some_objects, modulo++);
}
for (auto& t : tasks) {
auto const status = t.get();
EXPECT_STATUS_OK(status);
}
}
std::mutex mu_;
std::string bucket_name_;
int object_count_ = 128;
};
TEST_F(ObjectFileMultiThreadedTest, Download) {
StatusOr<Client> client = MakeIntegrationTestClient();
ASSERT_STATUS_OK(client);
auto const object_names = CreateObjectNames();
std::cout << "Create test objects " << std::flush;
ASSERT_NO_FATAL_FAILURE(CreateObjects(*client, object_names));
std::cout << " DONE\n";
// Create multiple threads, each downloading a portion of the objects.
auto const thread_count = ThreadCount();
auto download_some_objects = [this, thread_count, &client,
&object_names](int modulo) {
std::cout << '+' << std::flush;
int index = 0;
for (auto const& name : object_names) {
if (index++ % thread_count != modulo) continue;
if (modulo == 0) {
std::unique_lock<std::mutex> lk(mu_);
std::cout << '.' << std::flush;
}
auto status = client->DownloadToFile(bucket_name_, name, name);
if (!status.ok()) return status; // stop on the first error
}
return Status();
};
std::cout << "Performing downloads " << std::flush;
std::vector<std::future<Status>> tasks(thread_count);
int modulo = 0;
for (auto& t : tasks) {
t = std::async(std::launch::async, download_some_objects, modulo++);
}
for (auto& t : tasks) {
auto const status = t.get();
EXPECT_STATUS_OK(status);
}
std::cout << " DONE\n";
for (auto const& name : object_names) {
EXPECT_EQ(0, std::remove(name.c_str()));
}
std::cout << "Delete test objects " << std::flush;
ASSERT_NO_FATAL_FAILURE(DeleteObjects(*client, object_names));
std::cout << " DONE\n";
}
} // anonymous namespace
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace storage
} // namespace cloud
} // namespace google
<commit_msg>cleanup(storage): deflake integration test (#9764)<commit_after>// Copyright 2019 Google LLC
//
// 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
//
// https://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 "google/cloud/storage/client.h"
#include "google/cloud/storage/testing/storage_integration_test.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/testing_util/status_matchers.h"
#include <gmock/gmock.h>
#include <algorithm>
#include <cstdio>
#include <fstream>
#include <future>
#include <regex>
#include <thread>
namespace google {
namespace cloud {
namespace storage {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace {
auto const kObjectSize = 16 * 1024;
class ObjectFileMultiThreadedTest
: public google::cloud::storage::testing::StorageIntegrationTest {
protected:
void SetUp() override {
bucket_name_ = google::cloud::internal::GetEnv(
"GOOGLE_CLOUD_CPP_STORAGE_TEST_BUCKET_NAME")
.value_or("");
ASSERT_FALSE(bucket_name_.empty());
auto object_count = google::cloud::internal::GetEnv(
"GOOGLE_CLOUD_CPP_STORAGE_TEST_OBJECT_COUNT");
if (object_count) object_count_ = std::stoi(*object_count);
}
static int ThreadCount() {
static int const kCount = [] {
auto c = static_cast<int>(std::thread::hardware_concurrency());
return (std::max)(c / 2, 8);
}();
return kCount;
}
std::vector<std::string> CreateObjectNames() {
std::vector<std::string> object_names(object_count_);
// Use MakeRandomFilename() because the same name is used for
// the destination file.
std::generate_n(object_names.begin(), object_names.size(),
[this] { return MakeRandomFilename(); });
return object_names;
}
Status CreateSomeObjects(Client client,
std::vector<std::string> const& object_names,
int thread_count, int modulo) {
auto contents = [this] {
std::unique_lock<std::mutex> lk(mu_);
return MakeRandomData(kObjectSize);
}();
int index = 0;
for (auto const& n : object_names) {
if (index++ % thread_count != modulo) continue;
if (modulo == 0) {
std::unique_lock<std::mutex> lk(mu_);
std::cout << '.' << std::flush;
}
auto metadata =
client.InsertObject(bucket_name_, n, contents, IfGenerationMatch(0));
if (metadata) continue;
// kAlreadyExists is acceptable, it happens if (1) a retry attempt
// succeeds, but returns kUnavailable or a similar error (these can be
// network / overload issues), (2) the next retry attempt finds the object
// was already created.
if (metadata.status().code() == StatusCode::kAlreadyExists) continue;
return metadata.status();
}
return Status();
}
void CreateObjects(Client const& client,
std::vector<std::string> const& object_names) {
// Parallelize the object creation too because it can be slow.
int const thread_count = ThreadCount();
auto create_some_objects = [this, &client, &object_names,
thread_count](int modulo) {
return CreateSomeObjects(client, object_names, thread_count, modulo);
};
std::vector<std::future<Status>> tasks(thread_count);
int modulo = 0;
for (auto& t : tasks) {
t = std::async(std::launch::async, create_some_objects, modulo++);
}
for (auto& t : tasks) {
auto const status = t.get();
EXPECT_STATUS_OK(status);
}
}
Status DeleteSomeObjects(Client client,
std::vector<std::string> const& object_names,
int thread_count, int modulo) {
int index = 0;
Status status;
for (auto const& name : object_names) {
if (index++ % thread_count != modulo) continue;
if (modulo == 0) {
std::unique_lock<std::mutex> lk(mu_);
std::cout << '.' << std::flush;
}
auto result = client.DeleteObject(bucket_name_, name);
if (result.ok()) continue;
// kNotFound is acceptable, it happens if (1) a retry attempt succeeds,
// but returns kUnavailable or a similar error, (2) the next retry attempt
// cannot find the object.
if (result.code() == StatusCode::kNotFound) continue;
status = result;
}
return status;
}
void DeleteObjects(Client const& client,
std::vector<std::string> const& object_names) {
// Parallelize the object deletion too because it can be slow.
int const thread_count = ThreadCount();
auto delete_some_objects = [this, &client, &object_names,
thread_count](int modulo) {
return DeleteSomeObjects(client, object_names, thread_count, modulo);
};
std::vector<std::future<Status>> tasks(thread_count);
int modulo = 0;
for (auto& t : tasks) {
t = std::async(std::launch::async, delete_some_objects, modulo++);
}
for (auto& t : tasks) {
auto const status = t.get();
EXPECT_STATUS_OK(status);
}
}
std::mutex mu_;
std::string bucket_name_;
int object_count_ = 128;
};
TEST_F(ObjectFileMultiThreadedTest, Download) {
StatusOr<Client> client = MakeIntegrationTestClient();
ASSERT_STATUS_OK(client);
auto const object_names = CreateObjectNames();
std::cout << "Create test objects " << std::flush;
ASSERT_NO_FATAL_FAILURE(CreateObjects(*client, object_names));
std::cout << " DONE\n";
// Create multiple threads, each downloading a portion of the objects.
auto const thread_count = ThreadCount();
auto download_some_objects = [this, thread_count, &client,
&object_names](int modulo) {
std::cout << '+' << std::flush;
int index = 0;
for (auto const& name : object_names) {
if (index++ % thread_count != modulo) continue;
if (modulo == 0) {
std::unique_lock<std::mutex> lk(mu_);
std::cout << '.' << std::flush;
}
auto status = client->DownloadToFile(bucket_name_, name, name);
if (!status.ok()) return status; // stop on the first error
}
return Status();
};
std::cout << "Performing downloads " << std::flush;
std::vector<std::future<Status>> tasks(thread_count);
int modulo = 0;
for (auto& t : tasks) {
t = std::async(std::launch::async, download_some_objects, modulo++);
}
for (auto& t : tasks) {
auto const status = t.get();
EXPECT_STATUS_OK(status);
}
std::cout << " DONE\n";
for (auto const& name : object_names) {
EXPECT_EQ(0, std::remove(name.c_str()));
}
std::cout << "Delete test objects " << std::flush;
ASSERT_NO_FATAL_FAILURE(DeleteObjects(*client, object_names));
std::cout << " DONE\n";
}
} // anonymous namespace
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace storage
} // namespace cloud
} // namespace google
<|endoftext|>
|
<commit_before>#include "stan/math/functions/logical_eq.hpp"
#include <gtest/gtest.h>
TEST(MathFunctions,logical_eq) {
using stan::math::logical_eq;
EXPECT_TRUE(logical_eq(1,1));
EXPECT_TRUE(logical_eq(5.7,5.7));
EXPECT_TRUE(logical_eq(0,0.0));
EXPECT_FALSE(logical_eq(0,1));
EXPECT_FALSE(logical_eq(1.0,0));
EXPECT_FALSE(logical_eq(1, 2));
EXPECT_FALSE(logical_eq(2.0, -1.0));
}
<commit_msg>added NaN test for logical_eq<commit_after>#include <stan/math/functions/logical_eq.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <gtest/gtest.h>
TEST(MathFunctions,logical_eq) {
using stan::math::logical_eq;
EXPECT_TRUE(logical_eq(1,1));
EXPECT_TRUE(logical_eq(5.7,5.7));
EXPECT_TRUE(logical_eq(0,0.0));
EXPECT_FALSE(logical_eq(0,1));
EXPECT_FALSE(logical_eq(1.0,0));
EXPECT_FALSE(logical_eq(1, 2));
EXPECT_FALSE(logical_eq(2.0, -1.0));
}
TEST(MathFunctions, logical_eq_nan) {
double nan = std::numeric_limits<double>::quiet_NaN();
EXPECT_FALSE(stan::math::logical_eq(1.0, nan));
EXPECT_FALSE(stan::math::logical_eq(nan, 2.0));
EXPECT_FALSE(stan::math::logical_eq(nan, nan));
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: Bservices.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 05:25:24 $
*
* 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 _CONNECTIVITY_ADABAS_BDRIVER_HXX_
#include "adabas/BDriver.hxx"
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
using namespace connectivity::adabas;
using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::registry::XRegistryKey;
using ::com::sun::star::lang::XSingleServiceFactory;
using ::com::sun::star::lang::XMultiServiceFactory;
typedef Reference< XSingleServiceFactory > (SAL_CALL *createFactoryFunc)
(
const Reference< XMultiServiceFactory > & rServiceManager,
const OUString & rComponentName,
::cppu::ComponentInstantiation pCreateFunction,
const Sequence< OUString > & rServiceNames,
rtl_ModuleCount* _pT
);
//***************************************************************************************
//
// Die vorgeschriebene C-Api muss erfuellt werden!
// Sie besteht aus drei Funktionen, die von dem Modul exportiert werden muessen.
//
//---------------------------------------------------------------------------------------
void REGISTER_PROVIDER(
const OUString& aServiceImplName,
const Sequence< OUString>& Services,
const Reference< ::com::sun::star::registry::XRegistryKey > & xKey)
{
OUString aMainKeyName;
aMainKeyName = OUString::createFromAscii("/");
aMainKeyName += aServiceImplName;
aMainKeyName += OUString::createFromAscii("/UNO/SERVICES");
Reference< ::com::sun::star::registry::XRegistryKey > xNewKey( xKey->createKey(aMainKeyName) );
OSL_ENSURE(xNewKey.is(), "ADABAS::component_writeInfo : could not create a registry key !");
for (sal_uInt32 i=0; i<Services.getLength(); ++i)
xNewKey->createKey(Services[i]);
}
//---------------------------------------------------------------------------------------
struct ProviderRequest
{
Reference< XSingleServiceFactory > xRet;
Reference< XMultiServiceFactory > const xServiceManager;
OUString const sImplementationName;
ProviderRequest(
void* pServiceManager,
sal_Char const* pImplementationName
)
: xServiceManager(reinterpret_cast<XMultiServiceFactory*>(pServiceManager))
, sImplementationName(OUString::createFromAscii(pImplementationName))
{
}
inline
sal_Bool CREATE_PROVIDER(
const OUString& Implname,
const Sequence< OUString > & Services,
::cppu::ComponentInstantiation Factory,
createFactoryFunc creator
)
{
if (!xRet.is() && (Implname == sImplementationName))
try
{
xRet = creator( xServiceManager, sImplementationName,Factory, Services,0);
}
catch(...)
{
}
return xRet.is();
}
void* getProvider() const { return xRet.get(); }
};
//---------------------------------------------------------------------------------------
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char **ppEnvTypeName,
uno_Environment **ppEnv
)
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//---------------------------------------------------------------------------------------
extern "C" sal_Bool SAL_CALL component_writeInfo(
void* pServiceManager,
void* pRegistryKey
)
{
if (pRegistryKey)
try
{
Reference< ::com::sun::star::registry::XRegistryKey > xKey(reinterpret_cast< ::com::sun::star::registry::XRegistryKey*>(pRegistryKey));
REGISTER_PROVIDER(
ODriver::getImplementationName_Static(),
ODriver::getSupportedServiceNames_Static(), xKey);
return sal_True;
}
catch (::com::sun::star::registry::InvalidRegistryException& )
{
OSL_ENSURE(sal_False, "ODBC::component_writeInfo : could not create a registry key ! ## InvalidRegistryException !");
}
return sal_False;
}
//---------------------------------------------------------------------------------------
extern "C" void* SAL_CALL component_getFactory(
const sal_Char* pImplementationName,
void* pServiceManager,
void* pRegistryKey)
{
void* pRet = 0;
if (pServiceManager)
{
ProviderRequest aReq(pServiceManager,pImplementationName);
aReq.CREATE_PROVIDER(
ODriver::getImplementationName_Static(),
ODriver::getSupportedServiceNames_Static(),
ODriver_CreateInstance, ::cppu::createSingleFactory)
;
if(aReq.xRet.is())
aReq.xRet->acquire();
pRet = aReq.getProvider();
}
return pRet;
};
<commit_msg>INTEGRATION: CWS warnings01 (1.4.30); FILE MERGED 2005/12/22 11:44:31 fs 1.4.30.3: #i57457# warning-free code 2005/11/16 12:58:51 fs 1.4.30.2: #i57457# warning free code 2005/11/07 14:43:04 fs 1.4.30.1: #i57457# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: Bservices.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-20 01:11:49 $
*
* 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 _CONNECTIVITY_ADABAS_BDRIVER_HXX_
#include "adabas/BDriver.hxx"
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
using namespace connectivity::adabas;
using ::rtl::OUString;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::registry::XRegistryKey;
using ::com::sun::star::lang::XSingleServiceFactory;
using ::com::sun::star::lang::XMultiServiceFactory;
typedef Reference< XSingleServiceFactory > (SAL_CALL *createFactoryFunc)
(
const Reference< XMultiServiceFactory > & rServiceManager,
const OUString & rComponentName,
::cppu::ComponentInstantiation pCreateFunction,
const Sequence< OUString > & rServiceNames,
rtl_ModuleCount* _pT
);
//***************************************************************************************
//
// Die vorgeschriebene C-Api muss erfuellt werden!
// Sie besteht aus drei Funktionen, die von dem Modul exportiert werden muessen.
//
//---------------------------------------------------------------------------------------
void REGISTER_PROVIDER(
const OUString& aServiceImplName,
const Sequence< OUString>& Services,
const Reference< ::com::sun::star::registry::XRegistryKey > & xKey)
{
OUString aMainKeyName;
aMainKeyName = OUString::createFromAscii("/");
aMainKeyName += aServiceImplName;
aMainKeyName += OUString::createFromAscii("/UNO/SERVICES");
Reference< ::com::sun::star::registry::XRegistryKey > xNewKey( xKey->createKey(aMainKeyName) );
OSL_ENSURE(xNewKey.is(), "ADABAS::component_writeInfo : could not create a registry key !");
for (sal_Int32 i=0; i<Services.getLength(); ++i)
xNewKey->createKey(Services[i]);
}
//---------------------------------------------------------------------------------------
struct ProviderRequest
{
Reference< XSingleServiceFactory > xRet;
Reference< XMultiServiceFactory > const xServiceManager;
OUString const sImplementationName;
ProviderRequest(
void* pServiceManager,
sal_Char const* pImplementationName
)
: xServiceManager(reinterpret_cast<XMultiServiceFactory*>(pServiceManager))
, sImplementationName(OUString::createFromAscii(pImplementationName))
{
}
inline
sal_Bool CREATE_PROVIDER(
const OUString& Implname,
const Sequence< OUString > & Services,
::cppu::ComponentInstantiation Factory,
createFactoryFunc creator
)
{
if (!xRet.is() && (Implname == sImplementationName))
try
{
xRet = creator( xServiceManager, sImplementationName,Factory, Services,0);
}
catch(...)
{
}
return xRet.is();
}
void* getProvider() const { return xRet.get(); }
};
//---------------------------------------------------------------------------------------
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char **ppEnvTypeName,
uno_Environment ** /*ppEnv*/
)
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//---------------------------------------------------------------------------------------
extern "C" sal_Bool SAL_CALL component_writeInfo(
void* /*pServiceManager*/,
void* pRegistryKey
)
{
if (pRegistryKey)
try
{
Reference< ::com::sun::star::registry::XRegistryKey > xKey(reinterpret_cast< ::com::sun::star::registry::XRegistryKey*>(pRegistryKey));
REGISTER_PROVIDER(
ODriver::getImplementationName_Static(),
ODriver::getSupportedServiceNames_Static(), xKey);
return sal_True;
}
catch (::com::sun::star::registry::InvalidRegistryException& )
{
OSL_ENSURE(sal_False, "ODBC::component_writeInfo : could not create a registry key ! ## InvalidRegistryException !");
}
return sal_False;
}
//---------------------------------------------------------------------------------------
extern "C" void* SAL_CALL component_getFactory(
const sal_Char* pImplementationName,
void* pServiceManager,
void* /*pRegistryKey*/)
{
void* pRet = 0;
if (pServiceManager)
{
ProviderRequest aReq(pServiceManager,pImplementationName);
aReq.CREATE_PROVIDER(
ODriver::getImplementationName_Static(),
ODriver::getSupportedServiceNames_Static(),
ODriver_CreateInstance, ::cppu::createSingleFactory)
;
if(aReq.xRet.is())
aReq.xRet->acquire();
pRet = aReq.getProvider();
}
return pRet;
};
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: CConnection.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: oj $ $Date: 2001-10-05 06:15:36 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_CALC_CONNECTION_HXX_
#include "calc/CConnection.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_DATABASEMETADATA_HXX_
#include "calc/CDatabaseMetaData.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_CATALOG_HXX_
#include "calc/CCatalog.hxx"
#endif
#ifndef _CONNECTIVITY_RESOURCE_HRC_
#include "Resource.hrc"
#endif
#ifndef _CONNECTIVITY_MODULECONTEXT_HXX_
#include "ModuleContext.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_ODRIVER_HXX_
#include "calc/CDriver.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCOMPONENTLOADER_HPP_
#include <com/sun/star/frame/XComponentLoader.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_XSPREADSHEETDOCUMENT_HPP_
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#endif
#ifndef _URLOBJ_HXX //autogen wg. INetURLObject
#include <tools/urlobj.hxx>
#endif
#ifndef _CONNECTIVITY_CALC_PREPAREDSTATEMENT_HXX_
#include "calc/CPreparedStatement.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_STATEMENT_HXX_
#include "calc/CStatement.hxx"
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
using namespace connectivity::calc;
using namespace connectivity::file;
typedef connectivity::file::OConnection OConnection_BASE;
//------------------------------------------------------------------------------
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::sheet;
// --------------------------------------------------------------------------------
OCalcConnection::OCalcConnection(ODriver* _pDriver) : OConnection(_pDriver)
{
// m_aFilenameExtension is not used
}
OCalcConnection::~OCalcConnection()
{
}
void OCalcConnection::construct(const ::rtl::OUString& url,const Sequence< PropertyValue >& info)
throw(SQLException)
{
// open file
sal_Int32 nLen = url.indexOf(':');
nLen = url.indexOf(':',nLen+1);
::rtl::OUString aDSN(url.copy(nLen+1));
String aFileName = aDSN;
INetURLObject aURL;
aURL.SetSmartProtocol(INET_PROT_FILE);
{
SvtPathOptions aPathOptions;
aFileName = aPathOptions.SubstituteVariable(aFileName);
}
aURL.SetSmartURL(aFileName);
if ( aURL.GetProtocol() == INET_PROT_NOT_VALID )
{
// don't pass invalid URL to loadComponentFromURL
throw SQLException();
}
aFileName = aURL.GetMainURL(INetURLObject::NO_DECODE);
Reference< XComponentLoader > xDesktop( getDriver()->getFactory()->createInstance(
::rtl::OUString::createFromAscii("com.sun.star.frame.Desktop")), UNO_QUERY );
if (!xDesktop.is())
{
OSL_ASSERT("no desktop");
throw SQLException();
}
// open read-only as long as updating isn't implemented
Sequence<PropertyValue> aArgs(2);
aArgs[0].Name = ::rtl::OUString::createFromAscii("Hidden");
aArgs[0].Value <<= (sal_Bool) sal_True;
aArgs[1].Name = ::rtl::OUString::createFromAscii("ReadOnly");
aArgs[1].Value <<= (sal_Bool) sal_True;
Reference<XComponent> xComponent = xDesktop->loadComponentFromURL(
aFileName, ::rtl::OUString::createFromAscii("_blank"), 0, aArgs );
m_xDoc = Reference<XSpreadsheetDocument>( xComponent, UNO_QUERY );
// if the URL is not a spreadsheet document, throw the exception here
// instead of at the first access to it
if ( !m_xDoc.is() )
throw SQLException();
// file::OConnection::construct (reads the directory) is not called
}
void OCalcConnection::disposing()
{
::osl::MutexGuard aGuard(m_aMutex);
::comphelper::disposeComponent( m_xDoc );
OConnection::disposing();
}
// XServiceInfo
// --------------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO(OCalcConnection, "com.sun.star.sdbc.drivers.calc.Connection", "com.sun.star.sdbc.Connection")
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL OCalcConnection::getMetaData( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
Reference< XDatabaseMetaData > xMetaData = m_xMetaData;
if(!xMetaData.is())
{
xMetaData = new OCalcDatabaseMetaData(this);
m_xMetaData = xMetaData;
}
return xMetaData;
}
//------------------------------------------------------------------------------
::com::sun::star::uno::Reference< XTablesSupplier > OCalcConnection::createCatalog()
{
::osl::MutexGuard aGuard( m_aMutex );
Reference< XTablesSupplier > xTab = m_xCatalog;
if(!xTab.is())
{
OCalcCatalog *pCat = new OCalcCatalog(this);
xTab = pCat;
m_xCatalog = xTab;
}
return xTab;
}
// --------------------------------------------------------------------------------
Reference< XStatement > SAL_CALL OCalcConnection::createStatement( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
Reference< XStatement > xReturn = new OCalcStatement(this);
m_aStatements.push_back(WeakReferenceHelper(xReturn));
return xReturn;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OCalcConnection::prepareStatement( const ::rtl::OUString& sql )
throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
OCalcPreparedStatement* pStmt = new OCalcPreparedStatement(this);
Reference< XPreparedStatement > xHoldAlive = pStmt;
pStmt->construct(sql);
m_aStatements.push_back(WeakReferenceHelper(*pStmt));
return pStmt;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OCalcConnection::prepareCall( const ::rtl::OUString& sql )
throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
return NULL;
}
<commit_msg>INTEGRATION: CWS insight01 (1.8.114); FILE MERGED 2004/05/11 12:04:37 oj 1.8.114.2: #i21957# make use of a password when set 2003/08/04 06:11:36 oj 1.8.114.1: #111075# ongoing work<commit_after>/*************************************************************************
*
* $RCSfile: CConnection.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2004-08-02 16:58:49 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_CALC_CONNECTION_HXX_
#include "calc/CConnection.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_DATABASEMETADATA_HXX_
#include "calc/CDatabaseMetaData.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_CATALOG_HXX_
#include "calc/CCatalog.hxx"
#endif
#ifndef _CONNECTIVITY_RESOURCE_HRC_
#include "Resource.hrc"
#endif
#ifndef _CONNECTIVITY_MODULECONTEXT_HXX_
#include "ModuleContext.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_ODRIVER_HXX_
#include "calc/CDriver.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCOMPONENTLOADER_HPP_
#include <com/sun/star/frame/XComponentLoader.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_XSPREADSHEETDOCUMENT_HPP_
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#endif
#ifndef _URLOBJ_HXX //autogen wg. INetURLObject
#include <tools/urlobj.hxx>
#endif
#ifndef _CONNECTIVITY_CALC_PREPAREDSTATEMENT_HXX_
#include "calc/CPreparedStatement.hxx"
#endif
#ifndef _CONNECTIVITY_CALC_STATEMENT_HXX_
#include "calc/CStatement.hxx"
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
using namespace connectivity::calc;
using namespace connectivity::file;
typedef connectivity::file::OConnection OConnection_BASE;
//------------------------------------------------------------------------------
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::sheet;
// --------------------------------------------------------------------------------
OCalcConnection::OCalcConnection(ODriver* _pDriver) : OConnection(_pDriver)
{
// m_aFilenameExtension is not used
}
OCalcConnection::~OCalcConnection()
{
}
void OCalcConnection::construct(const ::rtl::OUString& url,const Sequence< PropertyValue >& info)
throw(SQLException)
{
// open file
sal_Int32 nLen = url.indexOf(':');
nLen = url.indexOf(':',nLen+1);
::rtl::OUString aDSN(url.copy(nLen+1));
String aFileName = aDSN;
INetURLObject aURL;
aURL.SetSmartProtocol(INET_PROT_FILE);
{
SvtPathOptions aPathOptions;
aFileName = aPathOptions.SubstituteVariable(aFileName);
}
aURL.SetSmartURL(aFileName);
if ( aURL.GetProtocol() == INET_PROT_NOT_VALID )
{
// don't pass invalid URL to loadComponentFromURL
throw SQLException();
}
aFileName = aURL.GetMainURL(INetURLObject::NO_DECODE);
Reference< XComponentLoader > xDesktop( getDriver()->getFactory()->createInstance(
::rtl::OUString::createFromAscii("com.sun.star.frame.Desktop")), UNO_QUERY );
if (!xDesktop.is())
{
OSL_ASSERT("no desktop");
throw SQLException();
}
::rtl::OUString sPassword;
const char* pPwd = "password";
const PropertyValue *pIter = info.getConstArray();
const PropertyValue *pEnd = pIter + info.getLength();
for(;pIter != pEnd;++pIter)
{
if(!pIter->Name.compareToAscii(pPwd))
{
pIter->Value >>= sPassword;
break;
}
}
// open read-only as long as updating isn't implemented
Sequence<PropertyValue> aArgs(2);
aArgs[0].Name = ::rtl::OUString::createFromAscii("Hidden");
aArgs[0].Value <<= (sal_Bool) sal_True;
aArgs[1].Name = ::rtl::OUString::createFromAscii("ReadOnly");
aArgs[1].Value <<= (sal_Bool) sal_True;
if ( sPassword.getLength() )
{
sal_Int32 nPos = aArgs.getLength();
aArgs.realloc(nPos+1);
aArgs[nPos].Name = ::rtl::OUString::createFromAscii("Password");
aArgs[nPos].Value <<= sPassword;
}
Reference<XComponent> xComponent = xDesktop->loadComponentFromURL(
aFileName, ::rtl::OUString::createFromAscii("_blank"), 0, aArgs );
m_xDoc = Reference<XSpreadsheetDocument>( xComponent, UNO_QUERY );
// if the URL is not a spreadsheet document, throw the exception here
// instead of at the first access to it
if ( !m_xDoc.is() )
throw SQLException();
// file::OConnection::construct (reads the directory) is not called
}
void OCalcConnection::disposing()
{
::osl::MutexGuard aGuard(m_aMutex);
::comphelper::disposeComponent( m_xDoc );
OConnection::disposing();
}
// XServiceInfo
// --------------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO(OCalcConnection, "com.sun.star.sdbc.drivers.calc.Connection", "com.sun.star.sdbc.Connection")
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL OCalcConnection::getMetaData( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
Reference< XDatabaseMetaData > xMetaData = m_xMetaData;
if(!xMetaData.is())
{
xMetaData = new OCalcDatabaseMetaData(this);
m_xMetaData = xMetaData;
}
return xMetaData;
}
//------------------------------------------------------------------------------
::com::sun::star::uno::Reference< XTablesSupplier > OCalcConnection::createCatalog()
{
::osl::MutexGuard aGuard( m_aMutex );
Reference< XTablesSupplier > xTab = m_xCatalog;
if(!xTab.is())
{
OCalcCatalog *pCat = new OCalcCatalog(this);
xTab = pCat;
m_xCatalog = xTab;
}
return xTab;
}
// --------------------------------------------------------------------------------
Reference< XStatement > SAL_CALL OCalcConnection::createStatement( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
Reference< XStatement > xReturn = new OCalcStatement(this);
m_aStatements.push_back(WeakReferenceHelper(xReturn));
return xReturn;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OCalcConnection::prepareStatement( const ::rtl::OUString& sql )
throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
OCalcPreparedStatement* pStmt = new OCalcPreparedStatement(this);
Reference< XPreparedStatement > xHoldAlive = pStmt;
pStmt->construct(sql);
m_aStatements.push_back(WeakReferenceHelper(*pStmt));
return pStmt;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OCalcConnection::prepareCall( const ::rtl::OUString& sql )
throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE::rBHelper.bDisposed);
return NULL;
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>#include <fstream>
#include <iostream>
using namespace std;
template <class T>
class Tree
{
private:
struct Node
{
T value_;
Node *left;
Node *right;
Node() {};
Node(const T value) : value_(value) { };
~Node() {};
void show(ostream &out, int level) const;
};
Node *root;
void null_tree(Node *tr_)
{
if (!tr_) return;
if (tr_->left)
{
null_tree(tr_->left);
tr_->left = nullptr;
}
if (tr_->right)
{
null_tree(tr_->right);
tr_->right = nullptr;
}
delete tr_;
}
Node * find_(const T &value) const
{
Node *tr = root;
while (tr)
{
if (tr->value_ != value)
{
if (value < tr->value_)
tr = tr->left;
else tr = tr->right;
}
else break;
}
if (!tr) return nullptr;
else return tr;
}
void add_node(Node *&add_n, T value)
{
add_n = new Node(value);
add_n->left = nullptr;
add_n->right = nullptr;
}
Node* add_(const T &value, Node * tr = 0)
{
if (!root)
{
root = new Node(value);
root->left = nullptr;
root->right = nullptr;
return root;
}
if (!tr) tr = root;
if ((tr) && (tr->value_ != value))
{
if (value < tr->value_)
{
if (tr->left)
add_(value, tr->left);
else
{
add_node(tr->left, value);
return tr->left;
}
}
else
{
if (tr->right)
add_(value, tr->right);
else
{
add_node(tr->right, value);
return tr->right;
}
}
}
return 0;
}
int count(Node* tr) const
{
if (!tr) return 0;
int l = 0, r = 0;
if (tr->left) l = count(tr->left);
if (tr->right) r = count(tr->right);
return l + r + 1;
}
void print_pre(const Node * tr, std::ofstream &file) const
{
try
{
if (!tr) throw 1;
}
catch (int)
{
return;
}
file << tr->value_ << " ";
if (tr->left)
print_pre(tr->left, file);
if (tr->right)
print_pre(tr->right, file);
}
bool Delete(Node **Tree, T &value)
{
Node *tr;
if (*Tree == nullptr) return false;
if (find(value)==0) return false;
else
if (value<(**Tree).value_) Delete(&((**Tree).left), value);
else
if (value>(**Tree).value_) Delete(&((**Tree).right), value);
else {
tr = *Tree;
if ((*tr).right ==nullptr) { *Tree = (*tr).left; delete tr; }
else
if ((*tr).left == nullptr) { *Tree = (*tr).right; delete tr; }
else Delete_(&((*tr).left), &tr);
}
return true;
}
void Delete_(Node **r, Node **tr)
{
if ((**r).right != nullptr)
{
Node* min = (*r)->right;
while (min->left)
min = min->left;
T val_ = min->value_;
delete min;
(**r).value_ = val_;
}
}
bool isEqual(Node* root2, const Node* root1)
{
return (root2&&root1 ? root2->value_ == root1->value_&&isEqual(root2->left, root1->left) && isEqual(root2->right, root1->right) : !root2 && !root1);
};
public:
Tree()
{
root = nullptr;
};
Tree(std::initializer_list<T> list)
{
root = nullptr;
for (auto& item : list)
{
add(item);
}
}
~Tree()
{
null_tree(root);
};
Node* tree_one()
{
return root;
};
void file_tree(char* name);
bool add(const T &value);
bool find(const T &value);
void print(ostream &out) const;
int count_() const;
bool isEmpty()
{
Node* root1 = nullptr;
return isEqual(root, root1);
}
bool operator ==(const Tree<T> &a)
{
return isEqual(root, a.root);
}
bool del(T value)
{
return Delete(&root, value);
}
void pr(char* name) const;
};
template <class T>
void Tree<T>::pr(char* name) const
{
ofstream file(name);
if (file.is_open())
{
file << count_() << " ";
print_pre(root, file);
file.close();
}
}
template <class T>
int Tree<T>::count_() const
{
return count(root);
}
template <class T>
void Tree<T>::print(ostream &out) const
{
root->show(out, 0);
}
template <class T>
void Tree<T>::Node::show(ostream &out, int level) const
{
const Node *tr = this;
if (tr) tr->right->show(out, level + 1);
for (int i = 0; i<level; i++)
out << " ";
if (tr) out << tr->value_ << endl;
else out << "End" << endl;
if (tr) tr->left->show(out, level + 1);
}
template <class T>
bool Tree<T>::add(const T &value)
{
Node *tr = add_(value);
if (tr) return true;
else return false;
}
template <class T>
void Tree<T>::file_tree(char* name)
{
ifstream file(name);
if (file.is_open())
{
int i_max;
file >> i_max;
for (int i = 0; i < i_max; ++i)
{
T node;
file >> node;
add(node);
}
file.close();
}
else {
throw "";
}
}
template <class T>
bool Tree<T>::find(const T &value)
{
Node *tr = find_(value);
if (tr) return true;
else return false;
}
<commit_msg>Update tree.hpp<commit_after>#include <fstream>
#include <iostream>
using namespace std;
template <class T>
class Tree
{
private:
struct Node
{
T value_;
Node *left;
Node *right;
Node() {};
Node(const T value) : value_(value) { };
~Node() {};
void show(ostream &out, int level) const;
};
Node *root;
void null_tree(Node *tr_)
{
if (!tr_) return;
if (tr_->left)
{
null_tree(tr_->left);
tr_->left = nullptr;
}
if (tr_->right)
{
null_tree(tr_->right);
tr_->right = nullptr;
}
delete tr_;
}
Node * find_(const T &value) const
{
Node *tr = root;
while (tr)
{
if (tr->value_ != value)
{
if (value < tr->value_)
tr = tr->left;
else tr = tr->right;
}
else break;
}
if (!tr) return nullptr;
else return tr;
}
void add_node(Node *&add_n, T value)
{
add_n = new Node(value);
add_n->left = nullptr;
add_n->right = nullptr;
}
Node* add_(const T &value, Node * tr = 0)
{
if (!root)
{
root = new Node(value);
root->left = nullptr;
root->right = nullptr;
return root;
}
if (!tr) tr = root;
if ((tr) && (tr->value_ != value))
{
if (value < tr->value_)
{
if (tr->left)
add_(value, tr->left);
else
{
add_node(tr->left, value);
return tr->left;
}
}
else
{
if (tr->right)
add_(value, tr->right);
else
{
add_node(tr->right, value);
return tr->right;
}
}
}
return 0;
}
int count(Node* tr) const
{
if (!tr) return 0;
int l = 0, r = 0;
if (tr->left) l = count(tr->left);
if (tr->right) r = count(tr->right);
return l + r + 1;
}
void print_pre(const Node * tr, std::ofstream &file) const
{
try
{
if (!tr) throw 1;
}
catch (int)
{
return;
}
file << tr->value_ << " ";
if (tr->left)
print_pre(tr->left, file);
if (tr->right)
print_pre(tr->right, file);
}
bool Delete(Node **Tree, T &value)
{
Node *tr;
if (*Tree == nullptr) return false;
if (find(value)==0) return false;
else
if (value<(**Tree).value_) Delete(&((**Tree).left), value);
else
if (value>(**Tree).value_) Delete(&((**Tree).right), value);
else {
tr = *Tree;
if ((*tr).right ==nullptr) { *Tree = (*tr).left; delete tr; }
else
if ((*tr).left == nullptr) { *Tree = (*tr).right; delete tr; }
else Delete_(&((*tr).left), &tr);
}
return true;
}
void Delete_(Node **r, Node **tr)
{
if ((**q).right != nullptr)
{
Node* min; T val_;
min = (*q)->right;
while (min->left)
min = min->left;
val_ = min->value_;
del( min->value_);
(**q).value_ = val_;
}
}
bool isEqual(Node* root2, const Node* root1)
{
return (root2&&root1 ? root2->value_ == root1->value_&&isEqual(root2->left, root1->left) && isEqual(root2->right, root1->right) : !root2 && !root1);
};
public:
Tree()
{
root = nullptr;
};
Tree(std::initializer_list<T> list)
{
root = nullptr;
for (auto& item : list)
{
add(item);
}
}
~Tree()
{
null_tree(root);
};
Node* tree_one()
{
return root;
};
void file_tree(char* name);
bool add(const T &value);
bool find(const T &value);
void print(ostream &out) const;
int count_() const;
bool isEmpty()
{
Node* root1 = nullptr;
return isEqual(root, root1);
}
bool operator ==(const Tree<T> &a)
{
return isEqual(root, a.root);
}
bool del(T value)
{
return Delete(&root, value);
}
void pr(char* name) const;
};
template <class T>
void Tree<T>::pr(char* name) const
{
ofstream file(name);
if (file.is_open())
{
file << count_() << " ";
print_pre(root, file);
file.close();
}
}
template <class T>
int Tree<T>::count_() const
{
return count(root);
}
template <class T>
void Tree<T>::print(ostream &out) const
{
root->show(out, 0);
}
template <class T>
void Tree<T>::Node::show(ostream &out, int level) const
{
const Node *tr = this;
if (tr) tr->right->show(out, level + 1);
for (int i = 0; i<level; i++)
out << " ";
if (tr) out << tr->value_ << endl;
else out << "End" << endl;
if (tr) tr->left->show(out, level + 1);
}
template <class T>
bool Tree<T>::add(const T &value)
{
Node *tr = add_(value);
if (tr) return true;
else return false;
}
template <class T>
void Tree<T>::file_tree(char* name)
{
ifstream file(name);
if (file.is_open())
{
int i_max;
file >> i_max;
for (int i = 0; i < i_max; ++i)
{
T node;
file >> node;
add(node);
}
file.close();
}
else {
throw "";
}
}
template <class T>
bool Tree<T>::find(const T &value)
{
Node *tr = find_(value);
if (tr) return true;
else return false;
}
<|endoftext|>
|
<commit_before>#include "physics/checkpointer.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace principia {
namespace physics {
using base::not_null;
using base::Status;
using geometry::Instant;
using quantities::si::Second;
using ::testing::MockFunction;
using ::testing::Ref;
using ::testing::Return;
using ::testing::_;
struct Message {
class Checkpoint {
public:
serialization::Point* mutable_time() {
return &time_;
}
const serialization::Point& time() const {
return time_;
}
private:
serialization::Point time_;
};
google::protobuf::RepeatedPtrField<Checkpoint> checkpoint;
};
class CheckpointerTest : public ::testing::Test {
protected:
CheckpointerTest()
: checkpointer_(writer_.AsStdFunction(),
reader_.AsStdFunction()) {}
MockFunction<Status(Message::Checkpoint const&)> reader_;
MockFunction<void(not_null<Message::Checkpoint*>)> writer_;
Checkpointer<Message> checkpointer_;
};
TEST_F(CheckpointerTest, WriteToCheckpoint) {
Instant const t = Instant() + 10 * Second;
EXPECT_CALL(writer_, Call(_));
checkpointer_.WriteToCheckpoint(t);
}
TEST_F(CheckpointerTest, WriteToCheckpointIfNeeded) {
Instant const t1 = Instant() + 10 * Second;
EXPECT_CALL(writer_, Call(_));
checkpointer_.WriteToCheckpoint(t1);
Instant const t2 = t1 + 8 * Second;
EXPECT_CALL(writer_, Call(_)).Times(0);
checkpointer_.WriteToCheckpointIfNeeded(
t2,
/*max_time_between_checkpoints=*/10 * Second);
EXPECT_CALL(writer_, Call(_));
Instant const t3 = t2 + 3 * Second;
checkpointer_.WriteToCheckpointIfNeeded(
t3,
/*max_time_between_checkpoints=*/10 * Second);
}
TEST_F(CheckpointerTest, Serialization) {
Instant t = Instant() + 10 * Second;
EXPECT_CALL(writer_, Call(_)).Times(2);
checkpointer_.WriteToCheckpoint(t);
t += 13 * Second;
checkpointer_.WriteToCheckpoint(t);
Message m;
checkpointer_.WriteToMessage(&m.checkpoint);
EXPECT_EQ(2, m.checkpoint.size());
EXPECT_EQ(10, m.checkpoint[0].time().scalar().magnitude());
EXPECT_EQ(23, m.checkpoint[1].time().scalar().magnitude());
auto const checkpointer =
Checkpointer<Message>::ReadFromMessage(writer_.AsStdFunction(),
reader_.AsStdFunction(),
m.checkpoint);
EXPECT_EQ(Instant() + 10 * Second, checkpointer->oldest_checkpoint());
}
} // namespace physics
} // namespace principia
<commit_msg>More test for the Checkpointer.<commit_after>#include "physics/checkpointer.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "testing_utilities/matchers.hpp"
namespace principia {
namespace physics {
using base::Error;
using base::not_null;
using base::Status;
using geometry::Instant;
using quantities::si::Second;
using testing_utilities::StatusIs;
using ::testing::Field;
using ::testing::InSequence;
using ::testing::MockFunction;
using ::testing::Ref;
using ::testing::Return;
using ::testing::_;
ACTION_P(SetPayload, payload) {
arg0->payload = payload;
}
struct Message {
class Checkpoint {
public:
serialization::Point* mutable_time() {
return &time_;
}
const serialization::Point& time() const {
return time_;
}
int payload = 0;
private:
serialization::Point time_;
};
google::protobuf::RepeatedPtrField<Checkpoint> checkpoint;
};
class CheckpointerTest : public ::testing::Test {
protected:
CheckpointerTest()
: checkpointer_(writer_.AsStdFunction(),
reader_.AsStdFunction()) {}
MockFunction<Status(Message::Checkpoint const&)> reader_;
MockFunction<void(not_null<Message::Checkpoint*>)> writer_;
Checkpointer<Message> checkpointer_;
};
TEST_F(CheckpointerTest, WriteToCheckpoint) {
Instant const t = Instant() + 10 * Second;
EXPECT_CALL(writer_, Call(_));
checkpointer_.WriteToCheckpoint(t);
}
TEST_F(CheckpointerTest, WriteToCheckpointIfNeeded) {
Instant const t1 = Instant() + 10 * Second;
EXPECT_CALL(writer_, Call(_));
checkpointer_.WriteToCheckpoint(t1);
EXPECT_EQ(t1, checkpointer_.oldest_checkpoint());
Instant const t2 = t1 + 8 * Second;
EXPECT_CALL(writer_, Call(_)).Times(0);
EXPECT_FALSE(checkpointer_.WriteToCheckpointIfNeeded(
t2,
/*max_time_between_checkpoints=*/10 * Second));
EXPECT_EQ(t1, checkpointer_.oldest_checkpoint());
EXPECT_CALL(writer_, Call(_));
Instant const t3 = t2 + 3 * Second;
EXPECT_TRUE(checkpointer_.WriteToCheckpointIfNeeded(
t3,
/*max_time_between_checkpoints=*/10 * Second));
EXPECT_EQ(t1, checkpointer_.oldest_checkpoint());
}
TEST_F(CheckpointerTest, ReadFromOldestCheckpoint) {
EXPECT_THAT(checkpointer_.ReadFromOldestCheckpoint(),
StatusIs(Error::NOT_FOUND));
Instant const t1 = Instant() + 10 * Second;
EXPECT_CALL(writer_, Call(_));
checkpointer_.WriteToCheckpoint(t1);
EXPECT_CALL(reader_, Call(_))
.WillOnce(Return(Status::CANCELLED))
.WillOnce(Return(Status::OK));
EXPECT_THAT(checkpointer_.ReadFromOldestCheckpoint(),
StatusIs(Error::CANCELLED));
EXPECT_OK(checkpointer_.ReadFromOldestCheckpoint());
}
TEST_F(CheckpointerTest, ReadFromAllCheckpointsBackwards) {
Instant const t1 = Instant() + 10 * Second;
EXPECT_CALL(writer_, Call(_)).WillOnce(SetPayload(1));
checkpointer_.WriteToCheckpoint(t1);
Instant const t2 = t1 + 11 * Second;
EXPECT_CALL(writer_, Call(_)).WillOnce(SetPayload(2));
checkpointer_.WriteToCheckpoint(t2);
Instant const t3 = t2 + 11 * Second;
EXPECT_CALL(writer_, Call(_)).WillOnce(SetPayload(3));
checkpointer_.WriteToCheckpoint(t3);
{
InSequence s;
EXPECT_CALL(reader_, Call(Field(&Message::Checkpoint::payload, 3)));
EXPECT_CALL(reader_, Call(Field(&Message::Checkpoint::payload, 2)));
EXPECT_CALL(reader_, Call(Field(&Message::Checkpoint::payload, 1)));
}
EXPECT_OK(
checkpointer_.ReadFromAllCheckpointsBackwards(reader_.AsStdFunction()));
{
InSequence s;
EXPECT_CALL(reader_, Call(Field(&Message::Checkpoint::payload, 3)));
EXPECT_CALL(reader_, Call(Field(&Message::Checkpoint::payload, 2)))
.WillOnce(Return(Status::CANCELLED));
}
EXPECT_THAT(
checkpointer_.ReadFromAllCheckpointsBackwards(reader_.AsStdFunction()),
StatusIs(Error::CANCELLED));
}
TEST_F(CheckpointerTest, Serialization) {
Instant t = Instant() + 10 * Second;
EXPECT_CALL(writer_, Call(_)).Times(2);
checkpointer_.WriteToCheckpoint(t);
t += 13 * Second;
checkpointer_.WriteToCheckpoint(t);
Message m;
checkpointer_.WriteToMessage(&m.checkpoint);
EXPECT_EQ(2, m.checkpoint.size());
EXPECT_EQ(10, m.checkpoint[0].time().scalar().magnitude());
EXPECT_EQ(23, m.checkpoint[1].time().scalar().magnitude());
auto const checkpointer =
Checkpointer<Message>::ReadFromMessage(writer_.AsStdFunction(),
reader_.AsStdFunction(),
m.checkpoint);
EXPECT_EQ(Instant() + 10 * Second, checkpointer->oldest_checkpoint());
}
} // namespace physics
} // namespace principia
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003-2011 Rony Shapiro <ronys@users.sourceforge.net>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/** \file pwsgridtable.cpp
*
*/
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
////@end includes
#include <utility> // for make_pair
#include <limits> //for MAX_INT
#include "PWSgridtable.h"
#include "passwordsafeframe.h"
#include "PWSgrid.h"
#include "../../core/ItemData.h"
#include "../../core/PWScore.h"
#include <wx/tokenzr.h>
////@begin XPM images
////@end XPM images
/*!
* PWSGridTable type definition
*/
IMPLEMENT_CLASS(PWSGridTable, wxGridTableBase)
typedef StringX (CItemData::*ItemDataFuncT)() const;
struct PWSGridCellDataType {
CItemData::FieldType ft;
ItemDataFuncT func;
bool visible;
int width;
int position;
} PWSGridCellData[] = {
{ CItemData::GROUP, &CItemData::GetGroup, true, wxDefaultCoord, 0},
{ CItemData::TITLE, &CItemData::GetTitle, true, wxDefaultCoord, 1},
{ CItemData::USER, &CItemData::GetUser, true, wxDefaultCoord, 2},
{ CItemData::URL, &CItemData::GetURL, true, wxDefaultCoord, 3},
{ CItemData::EMAIL, &CItemData::GetEmail, true, wxDefaultCoord, 4},
{ CItemData::AUTOTYPE, &CItemData::GetAutoType, true, wxDefaultCoord, 5},
{ CItemData::RUNCMD, &CItemData::GetRunCommand, true, wxDefaultCoord, 6},
{ CItemData::PROTECTED, &CItemData::GetProtected, true, wxDefaultCoord, 7},
{ CItemData::CTIME, &CItemData::GetCTimeL, true, wxDefaultCoord, 8},
{ CItemData::PMTIME, &CItemData::GetPMTimeL, true, wxDefaultCoord, 9},
{ CItemData::ATIME, &CItemData::GetATimeL, true, wxDefaultCoord, 10},
{ CItemData::XTIME, &CItemData::GetXTimeL, true, wxDefaultCoord, 11},
{ CItemData::XTIME_INT, &CItemData::GetXTimeInt, true, wxDefaultCoord, 12},
{ CItemData::RMTIME, &CItemData::GetRMTimeL, true, wxDefaultCoord, 13},
{ CItemData::PASSWORD, &CItemData::GetPassword, false, wxDefaultCoord, 14},
{ CItemData::PWHIST, &CItemData::GetPWHistory, true, wxDefaultCoord, 15},
{ CItemData::POLICY, &CItemData::GetPWPolicy, true, wxDefaultCoord, 16},
{ CItemData::DCA, &CItemData::GetDCA, true, wxDefaultCoord, 17},
};
/*!
* PWSGridTable constructor
*/
PWSGridTable::PWSGridTable(PWSGrid* pwsgrid) : m_pwsgrid(pwsgrid)
{
//PWSGridTable could be created many times, but the above table should be initialized
//only once to avoid losing the changes made during a session
static bool initialized = false;
if (!initialized) {
RestoreSettings();
initialized = true;
}
}
/*!
* PWSGridTable destructor
*/
PWSGridTable::~PWSGridTable()
{
}
/*!
* wxGridTableBase override implementations
*/
int PWSGridTable::GetNumberRows()
{
const size_t N = m_pwsgrid->GetNumItems();
assert(N <= size_t(std::numeric_limits<int>::max()));
return int(N);
}
int PWSGridTable::GetNumberCols()
{
return NumberOf(PWSGridCellData);
}
bool PWSGridTable::IsEmptyCell(int row, int col)
{
const wxString val = GetValue(row, col);
return val == wxEmptyString || val.empty() || val.IsSameAs(wxT("Unknown"));
}
wxString PWSGridTable::GetColLabelValue(int col)
{
return (size_t(col) < NumberOf(PWSGridCellData)) ?
towxstring(CItemData::FieldName(PWSGridCellData[col].ft)) : wxString();
}
wxString PWSGridTable::GetValue(int row, int col)
{
if (size_t(row) < m_pwsgrid->GetNumItems() &&
size_t(col) < NumberOf(PWSGridCellData)) {
const CItemData* item = m_pwsgrid->GetItem(row);
if (item != NULL) {
return towxstring((item->*PWSGridCellData[col].func)());
}
}
return wxEmptyString;
}
void PWSGridTable::SetValue(int /*row*/, int /*col*/, const wxString& /*value*/)
{
//I think it comes here only if the grid is editable
}
void PWSGridTable::Clear()
{
m_pwsgrid->DeleteAllItems();
}
//overriden
void PWSGridTable::SetView(wxGrid* newGrid)
{
wxGrid* oldGrid = GetView();
wxGridTableBase::SetView(newGrid);
if (newGrid) {
//A new gridtable is being installed. Update the grid with our settings
for (size_t idx = 0; idx < WXSIZEOF(PWSGridCellData); ++idx) {
#if wxCHECK_VERSION(2, 9, 1)
if (PWSGridCellData[idx].visible)
newGrid->ShowCol(idx);
else
newGrid->HideCol(idx);
#endif
//calling SetColSize, SetColPos would make them visible, so don't call them
//unless they are really visible
if (PWSGridCellData[idx].visible) {
if (PWSGridCellData[idx].width != wxDefaultCoord)
newGrid->SetColSize(idx, PWSGridCellData[idx].width);
newGrid->SetColPos(idx, PWSGridCellData[idx].position);
}
}
}
else {
wxCHECK_RET(oldGrid, wxT("Both old and new grid views are NULL"));
//This gridtable is about to be deleted. Save current settings
for (size_t idx = 0; idx < WXSIZEOF(PWSGridCellData); ++idx) {
bool visible = true;
#if wxCHECK_VERSION(2, 9, 1)
visible = PWSGridCellData[idx].visible = oldGrid->IsColShown(idx);
#endif
if (visible) {
PWSGridCellData[idx].width = oldGrid->GetColSize(idx);
PWSGridCellData[idx].position = oldGrid->GetColPos(idx);
}
}
}
}
bool PWSGridTable::DeleteRows(size_t pos, size_t numRows)
{
size_t curNumRows = m_pwsgrid->GetNumItems();
if (pos >= curNumRows) {
wxFAIL_MSG( wxString::Format
(
wxT("Called PWSGridTable::DeleteRows(pos=%lu, N=%lu)\nPos value is invalid for present table with %lu rows"),
static_cast<unsigned int>(pos),
static_cast<unsigned int>(numRows),
static_cast<unsigned int>(curNumRows)
) );
return false;
}
if (numRows > curNumRows - pos)
numRows = curNumRows - pos;
if (GetView()) {
//This will actually remove the item from grid display
wxGridTableMessage msg(this,
wxGRIDTABLE_NOTIFY_ROWS_DELETED,
reinterpret_cast<int &>(pos),
reinterpret_cast<int &>(numRows));
GetView()->ProcessTableMessage(msg);
}
return true;
}
bool PWSGridTable::AppendRows(size_t numRows/*=1*/)
{
if (GetView()) {
wxGridTableMessage msg(this,
wxGRIDTABLE_NOTIFY_ROWS_APPENDED,
reinterpret_cast<int &>(numRows));
GetView()->ProcessTableMessage(msg);
}
return true;
}
bool PWSGridTable::InsertRows(size_t pos/*=0*/, size_t numRows/*=1*/)
{
if (GetView()) {
wxGridTableMessage msg(this,
wxGRIDTABLE_NOTIFY_ROWS_INSERTED,
reinterpret_cast<int &>(pos),
reinterpret_cast<int &>(numRows));
GetView()->ProcessTableMessage(msg);
}
return true;
}
//static
int PWSGridTable::GetColumnFieldType(int colID)
{
wxCHECK_MSG(colID >= 0 && size_t(colID) < WXSIZEOF(PWSGridCellData), CItemData::END,
wxT("column ID is greater than the number of columns in PWSGrid"));
return PWSGridCellData[colID].ft;
}
void PWSGridTable::SaveSettings(void) const
{
wxString colWidths, colShown;
wxGrid* grid = GetView();
const int nCols = grid->GetNumberCols();
for(int idx = 0; idx < nCols; ++idx) {
const int colID = grid->GetColAt(idx);
#if wxCHECK_VERSION(2, 9, 1)
if (!grid->IsColShown(colID))
continue;
#endif
colShown << GetColumnFieldType(colID) << wxT(',');
colWidths << grid->GetColSize(colID) << wxT(',');
}
if (!colShown.IsEmpty())
colShown.RemoveLast();
if (!colWidths.IsEmpty())
colWidths.RemoveLast();
//write these, even if colWidth and colShown are empty
PWSprefs::GetInstance()->SetPref(PWSprefs::ListColumns, tostringx(colShown));
PWSprefs::GetInstance()->SetPref(PWSprefs::ColumnWidths, tostringx(colWidths));
}
void PWSGridTable::RestoreSettings(void) const
{
wxString colShown = towxstring(PWSprefs::GetInstance()->GetPref(PWSprefs::ListColumns));
wxString colWidths = towxstring(PWSprefs::GetInstance()->GetPref(PWSprefs::ColumnWidths));
wxArrayString colShownArray = wxStringTokenize(colShown, wxT(" \r\n\t,"), wxTOKEN_STRTOK);
wxArrayString colWidthArray = wxStringTokenize(colWidths, wxT(" \r\n\t,"), wxTOKEN_STRTOK);
if (colShownArray.Count() != colWidthArray.Count() || colShownArray.Count() == 0)
return;
//turn off all the columns first
for(size_t n = 0; n < WXSIZEOF(PWSGridCellData); ++n) {
PWSGridCellData[n].visible = false;
}
//now turn on the selected columns
for( size_t idx = 0; idx < colShownArray.Count(); ++idx) {
const int fieldType = wxAtoi(colShownArray[idx]);
const int fieldWidth = wxAtoi(colWidthArray[idx]);
for(size_t n = 0; n < WXSIZEOF(PWSGridCellData); ++n) {
if (PWSGridCellData[n].ft == fieldType) {
PWSGridCellData[n].visible = true;
PWSGridCellData[n].width = fieldWidth;
PWSGridCellData[n].position = idx;
break;
}
}
}
}
<commit_msg>Fixed WX build by removing dependency on "StringX Get<FieldName>()" functions of CItemData<commit_after>/*
* Copyright (c) 2003-2011 Rony Shapiro <ronys@users.sourceforge.net>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/** \file pwsgridtable.cpp
*
*/
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
////@end includes
#include <utility> // for make_pair
#include <limits> //for MAX_INT
#include "PWSgridtable.h"
#include "passwordsafeframe.h"
#include "PWSgrid.h"
#include "../../core/ItemData.h"
#include "../../core/PWScore.h"
#include <wx/tokenzr.h>
////@begin XPM images
////@end XPM images
/*!
* PWSGridTable type definition
*/
IMPLEMENT_CLASS(PWSGridTable, wxGridTableBase)
typedef StringX (CItemData::*ItemDataFuncT)() const;
struct PWSGridCellDataType {
CItemData::FieldType ft;
bool visible;
int width;
int position;
} PWSGridCellData[] = {
{ CItemData::GROUP, true, wxDefaultCoord, 0},
{ CItemData::TITLE, true, wxDefaultCoord, 1},
{ CItemData::USER, true, wxDefaultCoord, 2},
{ CItemData::URL, true, wxDefaultCoord, 3},
{ CItemData::EMAIL, true, wxDefaultCoord, 4},
{ CItemData::AUTOTYPE, true, wxDefaultCoord, 5},
{ CItemData::RUNCMD, true, wxDefaultCoord, 6},
{ CItemData::PROTECTED, true, wxDefaultCoord, 7},
{ CItemData::CTIME, true, wxDefaultCoord, 8},
{ CItemData::PMTIME, true, wxDefaultCoord, 9},
{ CItemData::ATIME, true, wxDefaultCoord, 10},
{ CItemData::XTIME, true, wxDefaultCoord, 11},
{ CItemData::XTIME_INT, true, wxDefaultCoord, 12},
{ CItemData::RMTIME, true, wxDefaultCoord, 13},
{ CItemData::PASSWORD, false, wxDefaultCoord, 14},
{ CItemData::PWHIST, true, wxDefaultCoord, 15},
{ CItemData::POLICY, true, wxDefaultCoord, 16},
{ CItemData::DCA, true, wxDefaultCoord, 17},
};
/*!
* PWSGridTable constructor
*/
PWSGridTable::PWSGridTable(PWSGrid* pwsgrid) : m_pwsgrid(pwsgrid)
{
//PWSGridTable could be created many times, but the above table should be initialized
//only once to avoid losing the changes made during a session
static bool initialized = false;
if (!initialized) {
RestoreSettings();
initialized = true;
}
}
/*!
* PWSGridTable destructor
*/
PWSGridTable::~PWSGridTable()
{
}
/*!
* wxGridTableBase override implementations
*/
int PWSGridTable::GetNumberRows()
{
const size_t N = m_pwsgrid->GetNumItems();
assert(N <= size_t(std::numeric_limits<int>::max()));
return int(N);
}
int PWSGridTable::GetNumberCols()
{
return NumberOf(PWSGridCellData);
}
bool PWSGridTable::IsEmptyCell(int row, int col)
{
const wxString val = GetValue(row, col);
return val == wxEmptyString || val.empty() || val.IsSameAs(wxT("Unknown"));
}
wxString PWSGridTable::GetColLabelValue(int col)
{
return (size_t(col) < NumberOf(PWSGridCellData)) ?
towxstring(CItemData::FieldName(PWSGridCellData[col].ft)) : wxString();
}
wxString PWSGridTable::GetValue(int row, int col)
{
if (size_t(row) < m_pwsgrid->GetNumItems() &&
size_t(col) < NumberOf(PWSGridCellData)) {
const CItemData* item = m_pwsgrid->GetItem(row);
if (item != NULL) {
return towxstring(item->GetFieldValue(PWSGridCellData[col].ft));
}
}
return wxEmptyString;
}
void PWSGridTable::SetValue(int /*row*/, int /*col*/, const wxString& /*value*/)
{
//I think it comes here only if the grid is editable
}
void PWSGridTable::Clear()
{
m_pwsgrid->DeleteAllItems();
}
//overriden
void PWSGridTable::SetView(wxGrid* newGrid)
{
wxGrid* oldGrid = GetView();
wxGridTableBase::SetView(newGrid);
if (newGrid) {
//A new gridtable is being installed. Update the grid with our settings
for (size_t idx = 0; idx < WXSIZEOF(PWSGridCellData); ++idx) {
#if wxCHECK_VERSION(2, 9, 1)
if (PWSGridCellData[idx].visible)
newGrid->ShowCol(idx);
else
newGrid->HideCol(idx);
#endif
//calling SetColSize, SetColPos would make them visible, so don't call them
//unless they are really visible
if (PWSGridCellData[idx].visible) {
if (PWSGridCellData[idx].width != wxDefaultCoord)
newGrid->SetColSize(idx, PWSGridCellData[idx].width);
newGrid->SetColPos(idx, PWSGridCellData[idx].position);
}
}
}
else {
wxCHECK_RET(oldGrid, wxT("Both old and new grid views are NULL"));
//This gridtable is about to be deleted. Save current settings
for (size_t idx = 0; idx < WXSIZEOF(PWSGridCellData); ++idx) {
bool visible = true;
#if wxCHECK_VERSION(2, 9, 1)
visible = PWSGridCellData[idx].visible = oldGrid->IsColShown(idx);
#endif
if (visible) {
PWSGridCellData[idx].width = oldGrid->GetColSize(idx);
PWSGridCellData[idx].position = oldGrid->GetColPos(idx);
}
}
}
}
bool PWSGridTable::DeleteRows(size_t pos, size_t numRows)
{
size_t curNumRows = m_pwsgrid->GetNumItems();
if (pos >= curNumRows) {
wxFAIL_MSG( wxString::Format
(
wxT("Called PWSGridTable::DeleteRows(pos=%lu, N=%lu)\nPos value is invalid for present table with %lu rows"),
static_cast<unsigned int>(pos),
static_cast<unsigned int>(numRows),
static_cast<unsigned int>(curNumRows)
) );
return false;
}
if (numRows > curNumRows - pos)
numRows = curNumRows - pos;
if (GetView()) {
//This will actually remove the item from grid display
wxGridTableMessage msg(this,
wxGRIDTABLE_NOTIFY_ROWS_DELETED,
reinterpret_cast<int &>(pos),
reinterpret_cast<int &>(numRows));
GetView()->ProcessTableMessage(msg);
}
return true;
}
bool PWSGridTable::AppendRows(size_t numRows/*=1*/)
{
if (GetView()) {
wxGridTableMessage msg(this,
wxGRIDTABLE_NOTIFY_ROWS_APPENDED,
reinterpret_cast<int &>(numRows));
GetView()->ProcessTableMessage(msg);
}
return true;
}
bool PWSGridTable::InsertRows(size_t pos/*=0*/, size_t numRows/*=1*/)
{
if (GetView()) {
wxGridTableMessage msg(this,
wxGRIDTABLE_NOTIFY_ROWS_INSERTED,
reinterpret_cast<int &>(pos),
reinterpret_cast<int &>(numRows));
GetView()->ProcessTableMessage(msg);
}
return true;
}
//static
int PWSGridTable::GetColumnFieldType(int colID)
{
wxCHECK_MSG(colID >= 0 && size_t(colID) < WXSIZEOF(PWSGridCellData), CItemData::END,
wxT("column ID is greater than the number of columns in PWSGrid"));
return PWSGridCellData[colID].ft;
}
void PWSGridTable::SaveSettings(void) const
{
wxString colWidths, colShown;
wxGrid* grid = GetView();
const int nCols = grid->GetNumberCols();
for(int idx = 0; idx < nCols; ++idx) {
const int colID = grid->GetColAt(idx);
#if wxCHECK_VERSION(2, 9, 1)
if (!grid->IsColShown(colID))
continue;
#endif
colShown << GetColumnFieldType(colID) << wxT(',');
colWidths << grid->GetColSize(colID) << wxT(',');
}
if (!colShown.IsEmpty())
colShown.RemoveLast();
if (!colWidths.IsEmpty())
colWidths.RemoveLast();
//write these, even if colWidth and colShown are empty
PWSprefs::GetInstance()->SetPref(PWSprefs::ListColumns, tostringx(colShown));
PWSprefs::GetInstance()->SetPref(PWSprefs::ColumnWidths, tostringx(colWidths));
}
void PWSGridTable::RestoreSettings(void) const
{
wxString colShown = towxstring(PWSprefs::GetInstance()->GetPref(PWSprefs::ListColumns));
wxString colWidths = towxstring(PWSprefs::GetInstance()->GetPref(PWSprefs::ColumnWidths));
wxArrayString colShownArray = wxStringTokenize(colShown, wxT(" \r\n\t,"), wxTOKEN_STRTOK);
wxArrayString colWidthArray = wxStringTokenize(colWidths, wxT(" \r\n\t,"), wxTOKEN_STRTOK);
if (colShownArray.Count() != colWidthArray.Count() || colShownArray.Count() == 0)
return;
//turn off all the columns first
for(size_t n = 0; n < WXSIZEOF(PWSGridCellData); ++n) {
PWSGridCellData[n].visible = false;
}
//now turn on the selected columns
for( size_t idx = 0; idx < colShownArray.Count(); ++idx) {
const int fieldType = wxAtoi(colShownArray[idx]);
const int fieldWidth = wxAtoi(colWidthArray[idx]);
for(size_t n = 0; n < WXSIZEOF(PWSGridCellData); ++n) {
if (PWSGridCellData[n].ft == fieldType) {
PWSGridCellData[n].visible = true;
PWSGridCellData[n].width = fieldWidth;
PWSGridCellData[n].position = idx;
break;
}
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>Prediction: fix angle diff typo<commit_after><|endoftext|>
|
<commit_before>/// \file ROOT/TPad.hxx
/// \ingroup Gpad ROOT7
/// \author Axel Naumann <axel@cern.ch>
/// \date 2017-07-06
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT7_TPad
#define ROOT7_TPad
#include <memory>
#include <vector>
#include "ROOT/TDrawable.hxx"
#include "ROOT/TFrame.hxx"
#include "ROOT/TPadExtent.hxx"
#include "ROOT/TPadPos.hxx"
#include "ROOT/TypeTraits.hxx"
namespace ROOT {
namespace Experimental {
class TPad;
namespace Internal {
class TVirtualCanvasPainter;
}
/** \class ROOT::Experimental::TPadBase
Base class for graphic containers for `TDrawable`-s.
*/
class TPadBase {
public:
using Primitives_t = std::vector<std::unique_ptr<TDrawable>>;
private:
/// Content of the pad.
Primitives_t fPrimitives;
/// TFrame with user coordinate system, if used by this pad.
std::unique_ptr<TFrame> fFrame;
/// Disable copy construction.
TPadBase(const TPadBase &) = delete;
/// Disable assignment.
TPadBase &operator=(const TPadBase &) = delete;
/// Adds a `DRAWABLE` to `fPrimitives`, returning the drawing options as given by `DRAWABLE::Options()`.
template <class DRAWABLE>
auto &AddDrawable(std::unique_ptr<DRAWABLE> &&uPtr)
{
DRAWABLE &drw = *uPtr;
fPrimitives.emplace_back(std::move(uPtr));
return drw.GetOptions();
}
protected:
/// Allow derived classes to default construct a TPadBase.
TPadBase() = default;
public:
virtual ~TPadBase();
/// Divide this pad into a grid of subpad with padding in between.
/// \param nHoriz Number of horizontal pads.
/// \param nVert Number of vertical pads.
/// \param padding Padding between pads.
/// \returns vector of vector (ret[x][y]) of created pads.
std::vector<std::vector<TPad *>> Divide(int nHoriz, int nVert, const TPadExtent &padding = {});
/// Add something to be painted.
/// The pad observes what's lifetime through a weak pointer.
template <class T>
auto &Draw(const std::shared_ptr<T> &what)
{
// Requires GetDrawable(what) to be known!
return AddDrawable(GetDrawable(what, *this));
}
/// Add something to be painted. The pad claims ownership.
template <class T>
auto &Draw(std::unique_ptr<T> &&what)
{
// Requires GetDrawable(what) to be known!
return AddDrawable(GetDrawable(std::move(what), *this));
}
/// Add a copy of something to be painted.
template <class T, class = typename std::enable_if<!ROOT::TypeTraits::IsSmartOrDumbPtr<T>::value>::type>
auto &Draw(const T &what)
{
// Requires GetDrawable(what) to be known!
return Draw(std::make_unique<T>(what));
}
/// Remove an object from the list of primitives.
// TODO: void Wipe();
/// Get the elements contained in the canvas.
const Primitives_t &GetPrimitives() const { return fPrimitives; }
/// Convert a `Pixel` position to Canvas-normalized positions.
virtual std::array<TPadCoord::Normal, 2> PixelsToNormal(const std::array<TPadCoord::Pixel, 2> &pos) const = 0;
/// Access to the top-most canvas, if any (const version).
virtual const TCanvas &GetCanvas() const = 0;
/// Access to the top-most canvas, if any (non-const version).
virtual TCanvas &GetCanvas() = 0;
/// Convert user coordinates to normal coordinates.
std::array<TPadCoord::Normal, 2> UserToNormal(const std::array<TPadCoord::User, 2> &pos) const
{
return fFrame->UserToNormal(pos);
}
};
} // namespace Internal
/** \class TPadDrawable
Draw a TPad, by drawing its contained graphical elements at the pad offset in the parent pad.'
*/
class TPadDrawable: public TDrawable {
private:
const std::unique_ptr<TPad> fPad; ///< The pad to be painted
TPadPos fPos; ///< Offset with respect to parent TPad.
public:
TPadDrawable() = default;
TPadDrawable(std::unique_ptr<TPad> &&pPad, const TPadPos &pos): fPad(std::move(pPad)), fPos(pos) {}
/// Paint the pad.
void Paint(Internal::TVirtualCanvasPainter & /*canv*/) final
{
// FIXME: and then what? Something with fPad.GetListOfPrimitives()?
}
TPad *Get() const { return fPad.get(); }
/// No options here.
void GetOptions() const {}
};
/** \class ROOT::Experimental::TPad
Graphic container for `TDrawable`-s.
*/
class TPad: public Internal::TPadBase {
private:
/// Pad containing this pad as a sub-pad.
const TPadBase *fParent = nullptr;
/// Size of the pad in the parent's (!) coordinate system.
TPadExtent fSize;
public:
friend std::unique_ptr<TPadDrawable> GetDrawable(std::unique_ptr<TPad> &&pad, const TPadPos &pos)
{
return std::make_unique<TPadDrawable>(std::move(pad), pos);
}
/// Create a child pad.
TPad(const TPadBase &parent, const TPadExtent &size): fParent(&parent), fSize(size) {}
/// Destructor to have a vtable.
virtual ~TPad();
/// Access to the parent pad (const version).
const TPadBase &GetParent() const { return *fParent; }
/// Access to the parent pad (non-const version).
TPadBase &GetParent() { return *fParent; }
/// Access to the top-most canvas (const version).
const TCanvas &GetCanvas() const override { return fParent->GetCanvas(); }
/// Access to the top-most canvas (non-const version).
TCanvas &GetCanvas() override { return fParent->GetCanvas(); }
/// Get the size of the pad in parent (!) coordinates.
const TPadExtent &GetSize() const { return fSize; }
/// Convert a `Pixel` position to Canvas-normalized positions.
std::array<TPadCoord::Normal, 2> PixelsToNormal(const std::array<TPadCoord::Pixel, 2> &pos) const override
{
std::array<TPadCoord::Normal, 2> posInParentNormal = fParent->PixelsToNormal(pos);
std::array<TPadCoord::Normal, 2> myPixelInNormal =
fParent->PixelsToNormal({{fSize.fHoriz.fPixel, fSize.fVert.fPixel}});
std::array<TPadCoord::Normal, 2> myUserInNormal =
fParent->UserToNormal({{fSize.fHoriz.fUser, fSize.fVert.fUser}});
// If the parent says pos is at 0.6 in normal coords, and our size converted to normal is 0.2, then pos in our
// coord system is 3.0!
return {{posInParentNormal[0] / (fSize.fHoriz.fNormal + myPixelInNormal[0] + myUserInNormal[0]),
posInParentNormal[1] / (fSize.fVert.fNormal + myPixelInNormal[1] + myUserInNormal[1])}};
}
/// Convert a TPadPos to [x, y] of normalized coordinates.
std::array<TPadCoord::Normal, 2> ToNormal(const Internal::TPadHorizVert &pos) const
{
std::array<TPadCoord::Normal, 2> pixelsInNormal = PixelsToNormal({{pos.fHoriz.fPixel, pos.fVert.fPixel}});
std::array<TPadCoord::Normal, 2> userInNormal = UserToNormal({{pos.fHoriz.fUser, pos.fVert.fUser}});
return {{pos.fHoriz.fNormal + pixelsInNormal[0] + userInNormal[0],
pos.fVert.fNormal + pixelsInNormal[1] + userInNormal[1]}};
}
};
} // namespace Experimental
} // namespace ROOT
#endif
<commit_msg>TPadBase is not Internal::.<commit_after>/// \file ROOT/TPad.hxx
/// \ingroup Gpad ROOT7
/// \author Axel Naumann <axel@cern.ch>
/// \date 2017-07-06
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT7_TPad
#define ROOT7_TPad
#include <memory>
#include <vector>
#include "ROOT/TDrawable.hxx"
#include "ROOT/TFrame.hxx"
#include "ROOT/TPadExtent.hxx"
#include "ROOT/TPadPos.hxx"
#include "ROOT/TypeTraits.hxx"
namespace ROOT {
namespace Experimental {
class TPad;
namespace Internal {
class TVirtualCanvasPainter;
}
/** \class ROOT::Experimental::TPadBase
Base class for graphic containers for `TDrawable`-s.
*/
class TPadBase {
public:
using Primitives_t = std::vector<std::unique_ptr<TDrawable>>;
private:
/// Content of the pad.
Primitives_t fPrimitives;
/// TFrame with user coordinate system, if used by this pad.
std::unique_ptr<TFrame> fFrame;
/// Disable copy construction.
TPadBase(const TPadBase &) = delete;
/// Disable assignment.
TPadBase &operator=(const TPadBase &) = delete;
/// Adds a `DRAWABLE` to `fPrimitives`, returning the drawing options as given by `DRAWABLE::Options()`.
template <class DRAWABLE>
auto &AddDrawable(std::unique_ptr<DRAWABLE> &&uPtr)
{
DRAWABLE &drw = *uPtr;
fPrimitives.emplace_back(std::move(uPtr));
return drw.GetOptions();
}
protected:
/// Allow derived classes to default construct a TPadBase.
TPadBase() = default;
public:
virtual ~TPadBase();
/// Divide this pad into a grid of subpad with padding in between.
/// \param nHoriz Number of horizontal pads.
/// \param nVert Number of vertical pads.
/// \param padding Padding between pads.
/// \returns vector of vector (ret[x][y]) of created pads.
std::vector<std::vector<TPad *>> Divide(int nHoriz, int nVert, const TPadExtent &padding = {});
/// Add something to be painted.
/// The pad observes what's lifetime through a weak pointer.
template <class T>
auto &Draw(const std::shared_ptr<T> &what)
{
// Requires GetDrawable(what) to be known!
return AddDrawable(GetDrawable(what, *this));
}
/// Add something to be painted. The pad claims ownership.
template <class T>
auto &Draw(std::unique_ptr<T> &&what)
{
// Requires GetDrawable(what) to be known!
return AddDrawable(GetDrawable(std::move(what), *this));
}
/// Add a copy of something to be painted.
template <class T, class = typename std::enable_if<!ROOT::TypeTraits::IsSmartOrDumbPtr<T>::value>::type>
auto &Draw(const T &what)
{
// Requires GetDrawable(what) to be known!
return Draw(std::make_unique<T>(what));
}
/// Remove an object from the list of primitives.
// TODO: void Wipe();
/// Get the elements contained in the canvas.
const Primitives_t &GetPrimitives() const { return fPrimitives; }
/// Convert a `Pixel` position to Canvas-normalized positions.
virtual std::array<TPadCoord::Normal, 2> PixelsToNormal(const std::array<TPadCoord::Pixel, 2> &pos) const = 0;
/// Access to the top-most canvas, if any (const version).
virtual const TCanvas &GetCanvas() const = 0;
/// Access to the top-most canvas, if any (non-const version).
virtual TCanvas &GetCanvas() = 0;
/// Convert user coordinates to normal coordinates.
std::array<TPadCoord::Normal, 2> UserToNormal(const std::array<TPadCoord::User, 2> &pos) const
{
return fFrame->UserToNormal(pos);
}
};
/** \class TPadDrawable
Draw a TPad, by drawing its contained graphical elements at the pad offset in the parent pad.'
*/
class TPadDrawable: public TDrawable {
private:
const std::unique_ptr<TPad> fPad; ///< The pad to be painted
TPadPos fPos; ///< Offset with respect to parent TPad.
public:
TPadDrawable() = default;
TPadDrawable(std::unique_ptr<TPad> &&pPad, const TPadPos &pos): fPad(std::move(pPad)), fPos(pos) {}
/// Paint the pad.
void Paint(Internal::TVirtualCanvasPainter & /*canv*/) final
{
// FIXME: and then what? Something with fPad.GetListOfPrimitives()?
}
TPad *Get() const { return fPad.get(); }
/// No options here.
void GetOptions() const {}
};
/** \class ROOT::Experimental::TPad
Graphic container for `TDrawable`-s.
*/
class TPad: public TPadBase {
private:
/// Pad containing this pad as a sub-pad.
const TPadBase *fParent = nullptr;
/// Size of the pad in the parent's (!) coordinate system.
TPadExtent fSize;
public:
friend std::unique_ptr<TPadDrawable> GetDrawable(std::unique_ptr<TPad> &&pad, const TPadPos &pos)
{
return std::make_unique<TPadDrawable>(std::move(pad), pos);
}
/// Create a child pad.
TPad(const TPadBase &parent, const TPadExtent &size): fParent(&parent), fSize(size) {}
/// Destructor to have a vtable.
virtual ~TPad();
/// Access to the parent pad (const version).
const TPadBase &GetParent() const { return *fParent; }
/// Access to the parent pad (non-const version).
TPadBase &GetParent() { return *fParent; }
/// Access to the top-most canvas (const version).
const TCanvas &GetCanvas() const override { return fParent->GetCanvas(); }
/// Access to the top-most canvas (non-const version).
TCanvas &GetCanvas() override { return fParent->GetCanvas(); }
/// Get the size of the pad in parent (!) coordinates.
const TPadExtent &GetSize() const { return fSize; }
/// Convert a `Pixel` position to Canvas-normalized positions.
std::array<TPadCoord::Normal, 2> PixelsToNormal(const std::array<TPadCoord::Pixel, 2> &pos) const override
{
std::array<TPadCoord::Normal, 2> posInParentNormal = fParent->PixelsToNormal(pos);
std::array<TPadCoord::Normal, 2> myPixelInNormal =
fParent->PixelsToNormal({{fSize.fHoriz.fPixel, fSize.fVert.fPixel}});
std::array<TPadCoord::Normal, 2> myUserInNormal =
fParent->UserToNormal({{fSize.fHoriz.fUser, fSize.fVert.fUser}});
// If the parent says pos is at 0.6 in normal coords, and our size converted to normal is 0.2, then pos in our
// coord system is 3.0!
return {{posInParentNormal[0] / (fSize.fHoriz.fNormal + myPixelInNormal[0] + myUserInNormal[0]),
posInParentNormal[1] / (fSize.fVert.fNormal + myPixelInNormal[1] + myUserInNormal[1])}};
}
/// Convert a TPadPos to [x, y] of normalized coordinates.
std::array<TPadCoord::Normal, 2> ToNormal(const Internal::TPadHorizVert &pos) const
{
std::array<TPadCoord::Normal, 2> pixelsInNormal = PixelsToNormal({{pos.fHoriz.fPixel, pos.fVert.fPixel}});
std::array<TPadCoord::Normal, 2> userInNormal = UserToNormal({{pos.fHoriz.fUser, pos.fVert.fUser}});
return {{pos.fHoriz.fNormal + pixelsInNormal[0] + userInNormal[0],
pos.fVert.fNormal + pixelsInNormal[1] + userInNormal[1]}};
}
};
} // namespace Experimental
} // namespace ROOT
#endif
<|endoftext|>
|
<commit_before>// @(#)root/hist:$Id$
// Author: Olivier Couet 13/07/09
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Riostream.h"
#include "TPad.h"
#include "TGraphStruct.h"
#include <stdio.h>
#include <gvc.h>
#include <gvplugin.h>
#ifdef GVIZ_STATIC
extern gvplugin_library_t gvplugin_dot_layout_LTX_library;
///extern gvplugin_library_t gvplugin_neato_layout_LTX_library;
///extern gvplugin_library_t gvplugin_core_LTX_library;
lt_symlist_t lt_preloaded_symbols[] = {
{ "gvplugin_dot_layout_LTX_library", (void*)(&gvplugin_dot_layout_LTX_library) },
/// { "gvplugin_neato_layout_LTX_library", (void*)(&gvplugin_neato_layout_LTX_library) },
/// { "gvplugin_core_LTX_library", (void*)(&gvplugin_core_LTX_library) },
{ 0, 0 }
};
#endif
ClassImp(TGraphStruct)
//______________________________________________________________________________
/* Begin_Html
<center><h2>Graph Structure class</h2></center>
The Graph Structure is an interface to the graphviz package.
<p>
The graphviz package is a graph visualization system. This interface consists in
three classes:
<ol>
<li> TGraphStruct: holds the graph structure. It uses the graphiz library to
layout the graphs and the ROOT graphics to paint them.
<li> TGraphNode: Is a graph node object which can be added in a TGraphStruct.
<li> TGraphEdge: Is an edge object connecting two nodes which can be added in
a TGraphStruct.
</ol>
End_Html
Begin_Macro(source)
../../../tutorials/graphs/graphstruct.C
End_Macro
Begin_Html
A graph structure can be dumped into a "dot" file using DumpAsDotFile.
End_Html */
//______________________________________________________________________________
TGraphStruct::TGraphStruct()
{
// Graph Structure default constructor.
fNodes = 0;
fEdges = 0;
fGVGraph = 0;
fGVC = 0;
SetMargin();
}
//______________________________________________________________________________
TGraphStruct::~TGraphStruct()
{
// Graph Structure default destructor.
gvFreeLayout(fGVC,fGVGraph);
agclose(fGVGraph);
gvFreeContext(fGVC);
if (fNodes) delete fNodes;
if (fEdges) delete fEdges;
}
//______________________________________________________________________________
void TGraphStruct::AddEdge(TGraphEdge *edge)
{
// Add the edge "edge" in this TGraphStruct.
if (!fEdges) fEdges = new TList;
fEdges->Add(edge);
}
//______________________________________________________________________________
TGraphEdge *TGraphStruct::AddEdge(TGraphNode *n1, TGraphNode *n2)
{
// Create an edge between n1 and n2 and put it in this graph.
//
// Two edges can connect the same nodes the same way, so there
// is no need to check if an edge already exists.
if (!fEdges) fEdges = new TList;
TGraphEdge *edge = new TGraphEdge(n1, n2);
fEdges->Add(edge);
return edge;
}
//______________________________________________________________________________
void TGraphStruct::AddNode(TGraphNode *node)
{
// Add the node "node" in this TGraphStruct.
if (!fNodes) fNodes = new TList;
fNodes->Add(node);
}
//______________________________________________________________________________
TGraphNode *TGraphStruct::AddNode(const char *name, const char *title)
{
// Create the node "name" if it does not exist and add it to this TGraphStruct.
if (!fNodes) fNodes = new TList;
TGraphNode *node = (TGraphNode*)fNodes->FindObject(name);
if (!node) {
node = new TGraphNode(name, title);
fNodes->Add(node);
}
return node;
}
//______________________________________________________________________________
void TGraphStruct::DumpAsDotFile(const char *filename)
{
// Dump this graph structure as a "dot" file.
if (!fGVGraph) {
Int_t ierr = Layout();
if (ierr) return;
}
FILE *file;
file=fopen(filename,"wt");
agwrite(fGVGraph, file);
fclose(file);
}
//______________________________________________________________________________
void TGraphStruct::Draw(Option_t *option)
{
// Draw the graph
if (!fGVGraph) {
Int_t ierr = Layout();
if (ierr) return;
}
// Get the bounding box
if (gPad) {
gPad->Range(GD_bb(fGVGraph).LL.x-fMargin, GD_bb(fGVGraph).LL.y-fMargin,
GD_bb(fGVGraph).UR.x+fMargin, GD_bb(fGVGraph).UR.y+fMargin);
}
AppendPad(option);
// Draw the nodes
if (fNodes) {
TGraphNode *node;
node = (TGraphNode*) fNodes->First();
node->Draw();
for(Int_t i = 1; i < fNodes->GetSize(); i++){
node = (TGraphNode*)fNodes->After(node);
node->Draw();
}
}
// Draw the edges
if (fEdges) {
TGraphEdge *edge;
edge = (TGraphEdge*) fEdges->First();
edge->Draw();
for(Int_t i = 1; i < fEdges->GetSize(); i++){
edge = (TGraphEdge*)fEdges->After(edge);
edge->Draw();
}
}
}
//______________________________________________________________________________
Int_t TGraphStruct::Layout()
{
// Layout the graph into a GraphViz data structure
TGraphNode *node;
TGraphEdge *edge;
// Create the graph context.
if (fGVC) gvFreeContext(fGVC);
#ifdef GVIZ_STATIC
fGVC = gvContextPlugins(lt_preloaded_symbols, 0);
#else
fGVC = gvContext();
#endif
// Create the graph.
if (fGVGraph) {
gvFreeLayout(fGVC,fGVGraph);
agclose(fGVGraph);
}
fGVGraph = agopen((char*)"GVGraph", AGDIGRAPH);
// Put the GV nodes into the GV graph
if (fNodes) {
node = (TGraphNode*) fNodes->First();
node->CreateGVNode(fGVGraph);
for(Int_t i = 1; i < fNodes->GetSize(); i++){
node = (TGraphNode*)fNodes->After(node);
node->CreateGVNode(fGVGraph);
}
}
// Put the edges into the graph
if (fEdges) {
edge = (TGraphEdge*) fEdges->First();
edge->CreateGVEdge(fGVGraph);
for(Int_t i = 1; i < fEdges->GetSize(); i++){
edge = (TGraphEdge*)fEdges->After(edge);
edge->CreateGVEdge(fGVGraph);
}
}
// Layout the graph
int ierr = gvLayout(fGVC, fGVGraph, (char*)"dot");
if (ierr) return ierr;
// Layout the nodes
if (fNodes) {
node = (TGraphNode*) fNodes->First();
node->Layout();
for(Int_t i = 1; i < fNodes->GetSize(); i++){
node = (TGraphNode*)fNodes->After(node);
node->Layout();
}
}
// Layout the edges
if (fEdges) {
edge = (TGraphEdge*) fEdges->First();
edge->Layout();
for(Int_t i = 1; i < fEdges->GetSize(); i++){
edge = (TGraphEdge*)fEdges->After(edge);
edge->Layout();
}
}
return 0;
}
//______________________________________________________________________________
void TGraphStruct::SavePrimitive(ostream &out, Option_t * /*= ""*/)
{
// Save primitive as a C++ statement(s) on output stream out
out<<" TGraphStruct *graphstruct = new TGraphStruct();"<<endl;
// Save the nodes
if (fNodes) {
TGraphNode *node;
node = (TGraphNode*) fNodes->First();
out<<" TGraphNode *"<<node->GetName()<<" = graphstruct->AddNode(\""<<
node->GetName()<<"\",\""<<
node->GetTitle()<<"\");"<<endl;
node->SaveAttributes(out);
for(Int_t i = 1; i < fNodes->GetSize(); i++){
node = (TGraphNode*)fNodes->After(node);
out<<" TGraphNode *"<<node->GetName()<<" = graphstruct->AddNode(\""<<
node->GetName()<<"\",\""<<
node->GetTitle()<<"\");"<<endl;
node->SaveAttributes(out);
}
}
// Save the edges
if (fEdges) {
TGraphEdge *edge;
Int_t en = 1;
edge = (TGraphEdge*) fEdges->First();
out<<" TGraphEdge *"<<"e"<<en<<
" = new TGraphEdge("<<
edge->GetNode1()->GetName()<<","<<
edge->GetNode2()->GetName()<<");"<<endl;
out<<" graphstruct->AddEdge("<<"e"<<en<<");"<<endl;
edge->SaveAttributes(out,Form("e%d",en));
for(Int_t i = 1; i < fEdges->GetSize(); i++){
en++;
edge = (TGraphEdge*)fEdges->After(edge);
out<<" TGraphEdge *"<<"e"<<en<<
" = new TGraphEdge("<<
edge->GetNode1()->GetName()<<","<<
edge->GetNode2()->GetName()<<");"<<endl;
out<<" graphstruct->AddEdge("<<"e"<<en<<");"<<endl;
edge->SaveAttributes(out,Form("e%d",en));
}
}
out<<" graphstruct->Draw();"<<endl;
}
//______________________________________________________________________________
void TGraphStruct::Streamer(TBuffer &/*b*/)
{
}
<commit_msg>Fix coverity report #33137<commit_after>// @(#)root/hist:$Id$
// Author: Olivier Couet 13/07/09
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Riostream.h"
#include "TPad.h"
#include "TGraphStruct.h"
#include <stdio.h>
#include <gvc.h>
#include <gvplugin.h>
#ifdef GVIZ_STATIC
extern gvplugin_library_t gvplugin_dot_layout_LTX_library;
///extern gvplugin_library_t gvplugin_neato_layout_LTX_library;
///extern gvplugin_library_t gvplugin_core_LTX_library;
lt_symlist_t lt_preloaded_symbols[] = {
{ "gvplugin_dot_layout_LTX_library", (void*)(&gvplugin_dot_layout_LTX_library) },
/// { "gvplugin_neato_layout_LTX_library", (void*)(&gvplugin_neato_layout_LTX_library) },
/// { "gvplugin_core_LTX_library", (void*)(&gvplugin_core_LTX_library) },
{ 0, 0 }
};
#endif
ClassImp(TGraphStruct)
//______________________________________________________________________________
/* Begin_Html
<center><h2>Graph Structure class</h2></center>
The Graph Structure is an interface to the graphviz package.
<p>
The graphviz package is a graph visualization system. This interface consists in
three classes:
<ol>
<li> TGraphStruct: holds the graph structure. It uses the graphiz library to
layout the graphs and the ROOT graphics to paint them.
<li> TGraphNode: Is a graph node object which can be added in a TGraphStruct.
<li> TGraphEdge: Is an edge object connecting two nodes which can be added in
a TGraphStruct.
</ol>
End_Html
Begin_Macro(source)
../../../tutorials/graphs/graphstruct.C
End_Macro
Begin_Html
A graph structure can be dumped into a "dot" file using DumpAsDotFile.
End_Html */
//______________________________________________________________________________
TGraphStruct::TGraphStruct()
{
// Graph Structure default constructor.
fNodes = 0;
fEdges = 0;
fGVGraph = 0;
fGVC = 0;
SetMargin();
}
//______________________________________________________________________________
TGraphStruct::~TGraphStruct()
{
// Graph Structure default destructor.
gvFreeLayout(fGVC,fGVGraph);
agclose(fGVGraph);
gvFreeContext(fGVC);
if (fNodes) delete fNodes;
if (fEdges) delete fEdges;
}
//______________________________________________________________________________
void TGraphStruct::AddEdge(TGraphEdge *edge)
{
// Add the edge "edge" in this TGraphStruct.
if (!fEdges) fEdges = new TList;
fEdges->Add(edge);
}
//______________________________________________________________________________
TGraphEdge *TGraphStruct::AddEdge(TGraphNode *n1, TGraphNode *n2)
{
// Create an edge between n1 and n2 and put it in this graph.
//
// Two edges can connect the same nodes the same way, so there
// is no need to check if an edge already exists.
if (!fEdges) fEdges = new TList;
TGraphEdge *edge = new TGraphEdge(n1, n2);
fEdges->Add(edge);
return edge;
}
//______________________________________________________________________________
void TGraphStruct::AddNode(TGraphNode *node)
{
// Add the node "node" in this TGraphStruct.
if (!fNodes) fNodes = new TList;
fNodes->Add(node);
}
//______________________________________________________________________________
TGraphNode *TGraphStruct::AddNode(const char *name, const char *title)
{
// Create the node "name" if it does not exist and add it to this TGraphStruct.
if (!fNodes) fNodes = new TList;
TGraphNode *node = (TGraphNode*)fNodes->FindObject(name);
if (!node) {
node = new TGraphNode(name, title);
fNodes->Add(node);
}
return node;
}
//______________________________________________________________________________
void TGraphStruct::DumpAsDotFile(const char *filename)
{
// Dump this graph structure as a "dot" file.
if (!fGVGraph) {
Int_t ierr = Layout();
if (ierr) return;
}
FILE *file;
file=fopen(filename,"wt");
agwrite(fGVGraph, file);
fclose(file);
}
//______________________________________________________________________________
void TGraphStruct::Draw(Option_t *option)
{
// Draw the graph
if (!fGVGraph) {
Int_t ierr = Layout();
if (ierr) return;
}
// Get the bounding box
if (gPad) {
gPad->Range(GD_bb(fGVGraph).LL.x-fMargin, GD_bb(fGVGraph).LL.y-fMargin,
GD_bb(fGVGraph).UR.x+fMargin, GD_bb(fGVGraph).UR.y+fMargin);
}
AppendPad(option);
// Draw the nodes
if (fNodes) {
TGraphNode *node;
node = (TGraphNode*) fNodes->First();
node->Draw();
for(Int_t i = 1; i < fNodes->GetSize(); i++){
node = (TGraphNode*)fNodes->After(node);
if (node) node->Draw();
}
}
// Draw the edges
if (fEdges) {
TGraphEdge *edge;
edge = (TGraphEdge*) fEdges->First();
edge->Draw();
for(Int_t i = 1; i < fEdges->GetSize(); i++){
edge = (TGraphEdge*)fEdges->After(edge);
edge->Draw();
}
}
}
//______________________________________________________________________________
Int_t TGraphStruct::Layout()
{
// Layout the graph into a GraphViz data structure
TGraphNode *node;
TGraphEdge *edge;
// Create the graph context.
if (fGVC) gvFreeContext(fGVC);
#ifdef GVIZ_STATIC
fGVC = gvContextPlugins(lt_preloaded_symbols, 0);
#else
fGVC = gvContext();
#endif
// Create the graph.
if (fGVGraph) {
gvFreeLayout(fGVC,fGVGraph);
agclose(fGVGraph);
}
fGVGraph = agopen((char*)"GVGraph", AGDIGRAPH);
// Put the GV nodes into the GV graph
if (fNodes) {
node = (TGraphNode*) fNodes->First();
node->CreateGVNode(fGVGraph);
for(Int_t i = 1; i < fNodes->GetSize(); i++){
node = (TGraphNode*)fNodes->After(node);
node->CreateGVNode(fGVGraph);
}
}
// Put the edges into the graph
if (fEdges) {
edge = (TGraphEdge*) fEdges->First();
edge->CreateGVEdge(fGVGraph);
for(Int_t i = 1; i < fEdges->GetSize(); i++){
edge = (TGraphEdge*)fEdges->After(edge);
edge->CreateGVEdge(fGVGraph);
}
}
// Layout the graph
int ierr = gvLayout(fGVC, fGVGraph, (char*)"dot");
if (ierr) return ierr;
// Layout the nodes
if (fNodes) {
node = (TGraphNode*) fNodes->First();
node->Layout();
for(Int_t i = 1; i < fNodes->GetSize(); i++){
node = (TGraphNode*)fNodes->After(node);
node->Layout();
}
}
// Layout the edges
if (fEdges) {
edge = (TGraphEdge*) fEdges->First();
edge->Layout();
for(Int_t i = 1; i < fEdges->GetSize(); i++){
edge = (TGraphEdge*)fEdges->After(edge);
edge->Layout();
}
}
return 0;
}
//______________________________________________________________________________
void TGraphStruct::SavePrimitive(ostream &out, Option_t * /*= ""*/)
{
// Save primitive as a C++ statement(s) on output stream out
out<<" TGraphStruct *graphstruct = new TGraphStruct();"<<endl;
// Save the nodes
if (fNodes) {
TGraphNode *node;
node = (TGraphNode*) fNodes->First();
out<<" TGraphNode *"<<node->GetName()<<" = graphstruct->AddNode(\""<<
node->GetName()<<"\",\""<<
node->GetTitle()<<"\");"<<endl;
node->SaveAttributes(out);
for(Int_t i = 1; i < fNodes->GetSize(); i++){
node = (TGraphNode*)fNodes->After(node);
out<<" TGraphNode *"<<node->GetName()<<" = graphstruct->AddNode(\""<<
node->GetName()<<"\",\""<<
node->GetTitle()<<"\");"<<endl;
node->SaveAttributes(out);
}
}
// Save the edges
if (fEdges) {
TGraphEdge *edge;
Int_t en = 1;
edge = (TGraphEdge*) fEdges->First();
out<<" TGraphEdge *"<<"e"<<en<<
" = new TGraphEdge("<<
edge->GetNode1()->GetName()<<","<<
edge->GetNode2()->GetName()<<");"<<endl;
out<<" graphstruct->AddEdge("<<"e"<<en<<");"<<endl;
edge->SaveAttributes(out,Form("e%d",en));
for(Int_t i = 1; i < fEdges->GetSize(); i++){
en++;
edge = (TGraphEdge*)fEdges->After(edge);
out<<" TGraphEdge *"<<"e"<<en<<
" = new TGraphEdge("<<
edge->GetNode1()->GetName()<<","<<
edge->GetNode2()->GetName()<<");"<<endl;
out<<" graphstruct->AddEdge("<<"e"<<en<<");"<<endl;
edge->SaveAttributes(out,Form("e%d",en));
}
}
out<<" graphstruct->Draw();"<<endl;
}
//______________________________________________________________________________
void TGraphStruct::Streamer(TBuffer &/*b*/)
{
}
<|endoftext|>
|
<commit_before>#include <string.h>
#include "merlin_image.h":
namespace merlin {
Persistent<FunctionTemplate> MerlinImage::constructor_template;
Handle<Value>
MerlinImage::New(const Arguments& args) {
HandleScope scope;
node::Buffer *buf = ObjectWrap::Unwrap<node::Buffer>(args[0]->ToObject());
MerlinImage* img = new MerlinImage(buf);
img->Wrap(args.This());
return scope.Close(args.This());
}
Handle<Value>
MerlinImage::GetBuffer(const Arguments& args) {
HandleScope scope;
MerlinImage *img = ObjectWrap::Unwrap<MerlinImage>(args.This());
Handle<Value> buf = img->buffer->handle_;
return scope.Close(buf);
}
Handle<Value>
MerlinImage::CropImage(const Arguments& args) {
HandleScope scope;
MerlinImage *img = ObjectWrap::Unwrap<MerlinImage>(args.This());
MagickReadImageBlob(img->wand, img->buffer->data(), img->buffer->length());
MagickCropImage(img->wand, 10, 10, 10, 10);
size_t length;
unsigned char* data = MagickGetImageBlob(img->wand, &length);
MagickSetFormat(img->wand, "JPEG");
node::Buffer *buf = node::Buffer::New(length);
char *buff_data = buf->data();
strcpy(buff_data, (char *)data);
return scope.Close(buf->handle_);
}
void
MerlinImage::Initialize(Handle<Object> target) {
HandleScope scope;
Handle<FunctionTemplate> f = FunctionTemplate::New(MerlinImage::New);
constructor_template = Persistent<FunctionTemplate>::New(f);
constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
constructor_template->SetClassName(String::NewSymbol("MerlinImage"));
NODE_SET_PROTOTYPE_METHOD(constructor_template, "cropImage", MerlinImage::CropImage);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "getBuffer", MerlinImage::GetBuffer);
target->Set(String::NewSymbol("MerlinImage"), constructor_template->GetFunction());
}
MerlinImage::MerlinImage(node::Buffer *buffer) :
buffer(buffer)
{
wand = NewMagickWand();
}
MerlinImage::~MerlinImage() {
delete buffer;
wand = DestroyMagickWand(wand);
}
}
<commit_msg>memcpy!<commit_after>#include <string.h>
#include "merlin_image.h":
namespace merlin {
Persistent<FunctionTemplate> MerlinImage::constructor_template;
Handle<Value>
MerlinImage::New(const Arguments& args) {
HandleScope scope;
node::Buffer *buf = ObjectWrap::Unwrap<node::Buffer>(args[0]->ToObject());
MerlinImage* img = new MerlinImage(buf);
img->Wrap(args.This());
return scope.Close(args.This());
}
Handle<Value>
MerlinImage::GetBuffer(const Arguments& args) {
HandleScope scope;
MerlinImage *img = ObjectWrap::Unwrap<MerlinImage>(args.This());
Handle<Value> buf = img->buffer->handle_;
return scope.Close(buf);
}
Handle<Value>
MerlinImage::CropImage(const Arguments& args) {
HandleScope scope;
MerlinImage *img = ObjectWrap::Unwrap<MerlinImage>(args.This());
MagickReadImageBlob(img->wand, img->buffer->data(), img->buffer->length());
MagickCropImage(img->wand, 100, 100, 100, 100);
size_t length;
unsigned char* data = MagickGetImageBlob(img->wand, &length);
node::Buffer *buf = node::Buffer::New(length);
char *buff_data = buf->data();
memcpy(buff_data, data, length);
return scope.Close(buf->handle_);
}
void
MerlinImage::Initialize(Handle<Object> target) {
HandleScope scope;
Handle<FunctionTemplate> f = FunctionTemplate::New(MerlinImage::New);
constructor_template = Persistent<FunctionTemplate>::New(f);
constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
constructor_template->SetClassName(String::NewSymbol("MerlinImage"));
NODE_SET_PROTOTYPE_METHOD(constructor_template, "cropImage", MerlinImage::CropImage);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "getBuffer", MerlinImage::GetBuffer);
target->Set(String::NewSymbol("MerlinImage"), constructor_template->GetFunction());
}
MerlinImage::MerlinImage(node::Buffer *buffer) :
buffer(buffer)
{
wand = NewMagickWand();
}
MerlinImage::~MerlinImage() {
delete buffer;
wand = DestroyMagickWand(wand);
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#ifndef MFEM_PYRAMID
#define MFEM_PYRAMID
#include "../config/config.hpp"
#include "element.hpp"
namespace mfem
{
/// Data type Pyramid element
class Pyramid : public Element
{
protected:
int indices[5];
public:
typedef Geometry::Constants<Geometry::PYRAMID> geom_t;
Pyramid() : Element(Geometry::PYRAMID) { }
/// Constructs wedge by specifying the indices and the attribute.
Pyramid(const int *ind, int attr = 1);
/// Constructs wedge by specifying the indices and the attribute.
Pyramid(int ind1, int ind2, int ind3, int ind4, int ind5,
int attr = 1);
/// Return element's type.
virtual Type GetType() const { return Element::PYRAMID; }
/// Set the vertices according to the given input.
virtual void SetVertices(const int *ind);
/// Returns the indices of the element's vertices.
virtual void GetVertices(Array<int> &v) const;
virtual int *GetVertices() { return indices; }
virtual int GetNVertices() const { return 5; }
virtual int GetNEdges() const { return 8; }
virtual const int *GetEdgeVertices(int ei) const
{ return geom_t::Edges[ei]; }
/// @deprecated Use GetNFaces(void) and GetNFaceVertices(int) instead.
MFEM_DEPRECATED virtual int GetNFaces(int &nFaceVertices) const;
virtual int GetNFaces() const { return 5; }
virtual int GetNFaceVertices(int fi) const
{ return ( ( fi < 1 ) ? 4 : 3); }
virtual const int *GetFaceVertices(int fi) const
{ return geom_t::FaceVert[fi]; }
virtual Element *Duplicate(Mesh *m) const
{ return new Pyramid(indices, attribute); }
virtual ~Pyramid() { }
};
extern class LinearPyramidFiniteElement PyramidFE;
}
#endif
<commit_msg>Fixing comments<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#ifndef MFEM_PYRAMID
#define MFEM_PYRAMID
#include "../config/config.hpp"
#include "element.hpp"
namespace mfem
{
/// Data type Pyramid element
class Pyramid : public Element
{
protected:
int indices[5];
public:
typedef Geometry::Constants<Geometry::PYRAMID> geom_t;
Pyramid() : Element(Geometry::PYRAMID) { }
/// Constructs pyramid by specifying the indices and the attribute.
Pyramid(const int *ind, int attr = 1);
/// Constructs pyramid by specifying the indices and the attribute.
Pyramid(int ind1, int ind2, int ind3, int ind4, int ind5,
int attr = 1);
/// Return element's type.
virtual Type GetType() const { return Element::PYRAMID; }
/// Set the vertices according to the given input.
virtual void SetVertices(const int *ind);
/// Returns the indices of the element's vertices.
virtual void GetVertices(Array<int> &v) const;
virtual int *GetVertices() { return indices; }
virtual int GetNVertices() const { return 5; }
virtual int GetNEdges() const { return 8; }
virtual const int *GetEdgeVertices(int ei) const
{ return geom_t::Edges[ei]; }
/// @deprecated Use GetNFaces(void) and GetNFaceVertices(int) instead.
MFEM_DEPRECATED virtual int GetNFaces(int &nFaceVertices) const;
virtual int GetNFaces() const { return 5; }
virtual int GetNFaceVertices(int fi) const
{ return ( ( fi < 1 ) ? 4 : 3); }
virtual const int *GetFaceVertices(int fi) const
{ return geom_t::FaceVert[fi]; }
virtual Element *Duplicate(Mesh *m) const
{ return new Pyramid(indices, attribute); }
virtual ~Pyramid() { }
};
extern class LinearPyramidFiniteElement PyramidFE;
}
#endif
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////////
// Copyright � 2007, Daniel �nnerby
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#include "pch.hpp"
#include <core/debug.h>
#include <core/playback/Transport.h>
#include <core/plugin/PluginFactory.h>
#include <algorithm>
#include <boost/thread.hpp>
using namespace musik::core::audio;
static std::string TAG = "Transport";
#define RESET_NEXT_PLAYER() \
delete this->nextPlayer; \
this->nextPlayer = NULL;
#define DEFER(x, y) \
{ \
boost::thread thread(boost::bind(x, this, y)); \
thread.detach(); \
}
static void pausePlayer(Player* p) {
p->Pause();
}
static void resumePlayer(Player* p) {
p->Resume();
}
static void deletePlayer(Player* p) {
delete p;
}
Transport::Transport()
: volume(1.0)
, state(PlaybackStopped)
, nextPlayer(NULL) {
this->output = Player::CreateDefaultOutput();
}
Transport::~Transport() {
}
Transport::PlaybackState Transport::GetPlaybackState() {
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
return this->state;
}
void Transport::PrepareNextTrack(const std::string& trackUrl) {
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
this->nextPlayer = new Player(trackUrl, this->volume, this->output);
}
void Transport::Start(const std::string& url) {
musik::debug::info(TAG, "we were asked to start the track at " + url);
Player* newPlayer = new Player(url, this->volume, this->output);
musik::debug::info(TAG, "Player created successfully");
this->StartWithPlayer(newPlayer);
}
void Transport::StartWithPlayer(Player* newPlayer) {
if (newPlayer) {
{
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
if (newPlayer != nextPlayer) {
delete nextPlayer;
}
this->nextPlayer = NULL;
newPlayer->PlaybackStarted.connect(this, &Transport::OnPlaybackStarted);
newPlayer->PlaybackAlmostEnded.connect(this, &Transport::OnPlaybackAlmostEnded);
newPlayer->PlaybackFinished.connect(this, &Transport::OnPlaybackFinished);
newPlayer->PlaybackStopped.connect(this, &Transport::OnPlaybackStopped);
newPlayer->PlaybackError.connect(this, &Transport::OnPlaybackError);
musik::debug::info(TAG, "play()");
this->active.push_front(newPlayer);
newPlayer->SetVolume(this->volume);
newPlayer->Play();
}
this->RaiseStreamEvent(Transport::StreamScheduled, newPlayer);
}
}
void Transport::Stop() {
musik::debug::info(TAG, "stop");
std::list<Player*> toDelete;
{
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
RESET_NEXT_PLAYER();
std::swap(toDelete, this->active);
}
/* do the actual delete outside of the critical section! the players run
in a background thread that will emit a signal on completion, but the
destructor joins(). */
std::for_each(toDelete.begin(), toDelete.end(), deletePlayer);
this->active.clear();
this->SetPlaybackState(PlaybackStopped);
}
bool Transport::Pause() {
musik::debug::info(TAG, "pause");
size_t count = 0;
{
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
std::for_each(this->active.begin(), this->active.end(), pausePlayer);
count = this->active.size();
}
if (count) {
this->SetPlaybackState(PlaybackPaused);
return true;
}
return false;
}
bool Transport::Resume() {
musik::debug::info(TAG, "resume");
size_t count = 0;
{
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
std::for_each(this->active.begin(), this->active.end(), resumePlayer);
count = this->active.size();
}
if (count) {
this->SetPlaybackState(Transport::PlaybackPlaying);
return true;
}
return false;
}
double Transport::Position() {
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
if (!this->active.empty()) {
return this->active.front()->Position();
}
return 0;
}
void Transport::SetPosition(double seconds) {
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
if (!this->active.empty()) {
this->active.front()->SetPosition(seconds);
this->TimeChanged(seconds);
}
}
double Transport::Volume() {
return this->volume;
}
void Transport::SetVolume(double volume) {
double oldVolume = this->volume;
volume = std::max(0.0, std::min(1.0, volume));
this->volume = volume;
if (oldVolume != this->volume) {
this->VolumeChanged();
}
musik::debug::info(TAG, boost::str(
boost::format("set volume %d%%") % round(volume * 100)));
{
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
if (!this->active.empty()) {
this->active.front()->SetVolume(volume);
}
}
}
void Transport::OnPlaybackStarted(Player* player) {
this->RaiseStreamEvent(Transport::StreamPlaying, player);
this->SetPlaybackState(Transport::PlaybackPlaying);
}
void Transport::OnPlaybackAlmostEnded(Player* player) {
this->RaiseStreamEvent(Transport::StreamAlmostDone, player);
}
void Transport::RemoveActive(Player* player) {
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
std::list<Player*>::iterator it =
std::find(this->active.begin(), this->active.end(), player);
if (it != this->active.end()) {
delete (*it);
this->active.erase(it);
}
}
void Transport::OnPlaybackFinished(Player* player) {
this->RaiseStreamEvent(Transport::StreamFinished, player);
bool startedNext = false;
{
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
if (this->nextPlayer) {
this->StartWithPlayer(this->nextPlayer);
startedNext = true;
}
}
if (!startedNext) {
this->SetPlaybackState(Transport::PlaybackStopped);
}
DEFER(&Transport::RemoveActive, player);
}
void Transport::OnPlaybackStopped (Player* player) {
this->RaiseStreamEvent(Transport::StreamStopped, player);
this->SetPlaybackState(Transport::PlaybackStopped);
DEFER(&Transport::RemoveActive, player);
}
void Transport::OnPlaybackError(Player* player) {
this->RaiseStreamEvent(Transport::StreamError, player);
this->SetPlaybackState(Transport::PlaybackStopped);
DEFER(&Transport::RemoveActive, player);
}
void Transport::SetPlaybackState(int state) {
bool changed = false;
{
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
this->state = (PlaybackState) state;
}
if (changed) {
this->PlaybackEvent(state);
}
}
void Transport::RaiseStreamEvent(int type, Player* player) {
this->StreamEvent(type, player->GetUrl());
}
<commit_msg>Fixed a deadlock in Transport.<commit_after>//////////////////////////////////////////////////////////////////////////////
// Copyright � 2007, Daniel �nnerby
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#include "pch.hpp"
#include <core/debug.h>
#include <core/playback/Transport.h>
#include <core/plugin/PluginFactory.h>
#include <algorithm>
#include <boost/thread.hpp>
using namespace musik::core::audio;
static std::string TAG = "Transport";
#define RESET_NEXT_PLAYER() \
delete this->nextPlayer; \
this->nextPlayer = NULL;
#define DEFER(x, y) \
{ \
boost::thread thread(boost::bind(x, this, y)); \
thread.detach(); \
}
static void pausePlayer(Player* p) {
p->Pause();
}
static void resumePlayer(Player* p) {
p->Resume();
}
static void deletePlayer(Player* p) {
delete p;
}
Transport::Transport()
: volume(1.0)
, state(PlaybackStopped)
, nextPlayer(NULL) {
this->output = Player::CreateDefaultOutput();
}
Transport::~Transport() {
}
Transport::PlaybackState Transport::GetPlaybackState() {
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
return this->state;
}
void Transport::PrepareNextTrack(const std::string& trackUrl) {
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
this->nextPlayer = new Player(trackUrl, this->volume, this->output);
}
void Transport::Start(const std::string& url) {
musik::debug::info(TAG, "we were asked to start the track at " + url);
Player* newPlayer = new Player(url, this->volume, this->output);
musik::debug::info(TAG, "Player created successfully");
this->StartWithPlayer(newPlayer);
}
void Transport::StartWithPlayer(Player* newPlayer) {
if (newPlayer) {
{
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
if (newPlayer != nextPlayer) {
delete nextPlayer;
}
this->nextPlayer = NULL;
newPlayer->PlaybackStarted.connect(this, &Transport::OnPlaybackStarted);
newPlayer->PlaybackAlmostEnded.connect(this, &Transport::OnPlaybackAlmostEnded);
newPlayer->PlaybackFinished.connect(this, &Transport::OnPlaybackFinished);
newPlayer->PlaybackStopped.connect(this, &Transport::OnPlaybackStopped);
newPlayer->PlaybackError.connect(this, &Transport::OnPlaybackError);
musik::debug::info(TAG, "play()");
this->active.push_front(newPlayer);
newPlayer->SetVolume(this->volume);
newPlayer->Play();
}
this->RaiseStreamEvent(Transport::StreamScheduled, newPlayer);
}
}
void Transport::Stop() {
musik::debug::info(TAG, "stop");
std::list<Player*> toDelete;
{
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
RESET_NEXT_PLAYER();
std::swap(toDelete, this->active);
}
/* do the actual delete outside of the critical section! the players run
in a background thread that will emit a signal on completion, but the
destructor joins(). */
std::for_each(toDelete.begin(), toDelete.end(), deletePlayer);
this->active.clear();
this->SetPlaybackState(PlaybackStopped);
}
bool Transport::Pause() {
musik::debug::info(TAG, "pause");
size_t count = 0;
{
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
std::for_each(this->active.begin(), this->active.end(), pausePlayer);
count = this->active.size();
}
if (count) {
this->SetPlaybackState(PlaybackPaused);
return true;
}
return false;
}
bool Transport::Resume() {
musik::debug::info(TAG, "resume");
size_t count = 0;
{
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
std::for_each(this->active.begin(), this->active.end(), resumePlayer);
count = this->active.size();
}
if (count) {
this->SetPlaybackState(Transport::PlaybackPlaying);
return true;
}
return false;
}
double Transport::Position() {
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
if (!this->active.empty()) {
return this->active.front()->Position();
}
return 0;
}
void Transport::SetPosition(double seconds) {
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
if (!this->active.empty()) {
this->active.front()->SetPosition(seconds);
this->TimeChanged(seconds);
}
}
double Transport::Volume() {
return this->volume;
}
void Transport::SetVolume(double volume) {
double oldVolume = this->volume;
volume = std::max(0.0, std::min(1.0, volume));
this->volume = volume;
if (oldVolume != this->volume) {
this->VolumeChanged();
}
musik::debug::info(TAG, boost::str(
boost::format("set volume %d%%") % round(volume * 100)));
{
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
if (!this->active.empty()) {
this->active.front()->SetVolume(volume);
}
}
}
void Transport::OnPlaybackStarted(Player* player) {
this->RaiseStreamEvent(Transport::StreamPlaying, player);
this->SetPlaybackState(Transport::PlaybackPlaying);
}
void Transport::OnPlaybackAlmostEnded(Player* player) {
this->RaiseStreamEvent(Transport::StreamAlmostDone, player);
}
void Transport::RemoveActive(Player* player) {
bool found = false;
{
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
std::list<Player*>::iterator it =
std::find(this->active.begin(), this->active.end(), player);
if (it != this->active.end()) {
this->active.erase(it);
found = true;
}
}
/* outside of the critical section, otherwise potential deadlock */
if (found) {
delete player;
}
}
void Transport::OnPlaybackFinished(Player* player) {
this->RaiseStreamEvent(Transport::StreamFinished, player);
bool startedNext = false;
{
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
if (this->nextPlayer) {
this->StartWithPlayer(this->nextPlayer);
startedNext = true;
}
}
if (!startedNext) {
this->SetPlaybackState(Transport::PlaybackStopped);
}
DEFER(&Transport::RemoveActive, player);
}
void Transport::OnPlaybackStopped (Player* player) {
this->RaiseStreamEvent(Transport::StreamStopped, player);
this->SetPlaybackState(Transport::PlaybackStopped);
DEFER(&Transport::RemoveActive, player);
}
void Transport::OnPlaybackError(Player* player) {
this->RaiseStreamEvent(Transport::StreamError, player);
this->SetPlaybackState(Transport::PlaybackStopped);
DEFER(&Transport::RemoveActive, player);
}
void Transport::SetPlaybackState(int state) {
bool changed = false;
{
boost::recursive_mutex::scoped_lock lock(this->stateMutex);
this->state = (PlaybackState) state;
}
if (changed) {
this->PlaybackEvent(state);
}
}
void Transport::RaiseStreamEvent(int type, Player* player) {
this->StreamEvent(type, player->GetUrl());
}
<|endoftext|>
|
<commit_before>#include <cassert>
#include <algorithm>
#include <libinput.h>
#include <iostream>
extern "C"
{
#include <wlr/types/wlr_seat.h>
}
#include "input-inhibit.hpp"
#include "signal-definitions.hpp"
#include "core.hpp"
#include "touch.hpp"
#include "keyboard.hpp"
#include "cursor.hpp"
#include "input-manager.hpp"
#include "workspace-manager.hpp"
#include "debug.hpp"
bool input_manager::is_touch_enabled()
{
return touch_count > 0;
}
void input_manager::update_capabilities()
{
uint32_t cap = 0;
if (pointer_count)
cap |= WL_SEAT_CAPABILITY_POINTER;
if (keyboards.size())
cap |= WL_SEAT_CAPABILITY_KEYBOARD;
if (touch_count)
cap |= WL_SEAT_CAPABILITY_TOUCH;
wlr_seat_set_capabilities(seat, cap);
}
void handle_new_input_cb(wl_listener*, void *data)
{
auto dev = static_cast<wlr_input_device*> (data);
assert(dev);
core->input->handle_new_input(dev);
}
void input_manager::handle_new_input(wlr_input_device *dev)
{
if (!cursor)
create_seat();
log_info("handle new input: %s, default mapping: %s", dev->name, dev->output_name);
input_devices.push_back(std::make_unique<wf_input_device> (dev));
if (dev->type == WLR_INPUT_DEVICE_KEYBOARD)
keyboards.push_back(std::make_unique<wf_keyboard> (dev, core->config));
if (dev->type == WLR_INPUT_DEVICE_POINTER)
{
cursor->attach_device(dev);
pointer_count++;
}
if (dev->type == WLR_INPUT_DEVICE_TOUCH)
{
touch_count++;
if (!our_touch)
our_touch = std::unique_ptr<wf_touch> (new wf_touch(cursor->cursor));
our_touch->add_device(dev);
}
auto section = core->config->get_section(nonull(dev->name));
auto mapped_output = section->get_option("output",
nonull(dev->output_name))->as_string();
auto wo = core->get_output(mapped_output);
if (wo)
wlr_cursor_map_input_to_output(cursor->cursor, dev, wo->handle);
update_capabilities();
}
void input_manager::handle_input_destroyed(wlr_input_device *dev)
{
log_info("remove input: %s", dev->name);
auto it = std::remove_if(input_devices.begin(), input_devices.end(),
[=] (const std::unique_ptr<wf_input_device>& idev) { return idev->device == dev; });
input_devices.erase(it, input_devices.end());
if (dev->type == WLR_INPUT_DEVICE_KEYBOARD)
{
auto it = std::remove_if(keyboards.begin(), keyboards.end(),
[=] (const std::unique_ptr<wf_keyboard>& kbd) { return kbd->device == dev; });
keyboards.erase(it, keyboards.end());
}
if (dev->type == WLR_INPUT_DEVICE_POINTER)
{
cursor->detach_device(dev);
pointer_count--;
}
if (dev->type == WLR_INPUT_DEVICE_TOUCH)
touch_count--;
update_capabilities();
}
input_manager::input_manager()
{
input_device_created.notify = handle_new_input_cb;
seat = wlr_seat_create(core->display, "default");
wl_signal_add(&core->backend->events.new_input,
&input_device_created);
surface_map_state_changed = [=] (signal_data *data)
{
auto ev = static_cast<_surface_map_state_changed_signal*> (data);
if (cursor->grabbed_surface == ev->surface && !ev->surface->is_mapped())
{
cursor->end_held_grab();
} else
{
update_cursor_position(get_current_time(), false);
}
if (our_touch)
{
if (our_touch->grabbed_surface == ev->surface && !ev->surface->is_mapped())
our_touch->end_touch_down_grab();
for (auto f : our_touch->gesture_recognizer.current)
handle_touch_motion(get_current_time(), f.first, f.second.sx, f.second.sy);
}
};
config_updated = [=] (signal_data *)
{
for (auto& dev : input_devices)
dev->update_options();
for (auto& kbd : keyboards)
kbd->reload_input_options();
};
core->connect_signal("reload-config", &config_updated);
/*
session_listener.notify = session_signal_handler;
wl_signal_add(&core->ec->session_signal, &session_listener);
*/
}
input_manager::~input_manager()
{
core->disconnect_signal("reload-config", &config_updated);
}
uint32_t input_manager::get_modifiers()
{
uint32_t mods = 0;
auto keyboard = wlr_seat_get_keyboard(seat);
if (keyboard)
mods = wlr_keyboard_get_modifiers(keyboard);
return mods;
}
bool input_manager::grab_input(wayfire_grab_interface iface)
{
if (!iface || !iface->grabbed || !session_active)
return false;
assert(!active_grab); // cannot have two active input grabs!
if (our_touch)
our_touch->input_grabbed();
active_grab = iface;
auto kbd = wlr_seat_get_keyboard(seat);
auto mods = kbd->modifiers;
mods.depressed = 0;
wlr_seat_keyboard_send_modifiers(seat, &mods);
set_keyboard_focus(NULL, seat);
update_cursor_focus(nullptr, 0, 0);
core->set_cursor("default");
return true;
}
static void idle_update_cursor(void *data)
{
auto input = (input_manager*) data;
input->update_cursor_position(get_current_time(), false);
}
void input_manager::ungrab_input()
{
if (active_grab)
active_grab->output->set_active_view(active_grab->output->get_active_view());
active_grab = nullptr;
/* We must update cursor focus, however, if we update "too soon", the current
* pointer event (button press/release, maybe something else) will be sent to
* the client, which shouldn't happen (at the time of the event, there was
* still an active input grab) */
wl_event_loop_add_idle(core->ev_loop, idle_update_cursor, this);
}
bool input_manager::input_grabbed()
{
return active_grab || !session_active;
}
void input_manager::toggle_session()
{
session_active ^= 1;
if (!session_active)
{
if (active_grab)
{
auto grab = active_grab;
ungrab_input();
active_grab = grab;
}
} else
{
if (active_grab)
{
auto grab = active_grab;
active_grab = nullptr;
grab_input(grab);
}
}
}
bool input_manager::can_focus_surface(wayfire_surface_t *surface)
{
if (exclusive_client && surface->get_client() != exclusive_client)
return false;
return true;
}
wayfire_surface_t* input_manager::input_surface_at(int x, int y,
int& lx, int& ly)
{
auto output = core->get_output_at(x, y);
/* If the output at these coordinates was just destroyed or some other edge case */
if (!output)
return nullptr;
auto og = output->get_layout_geometry();
x -= og.x;
y -= og.y;
wayfire_surface_t *new_focus = nullptr;
output->workspace->for_each_view(
[&] (wayfire_view view)
{
if (new_focus) return; // we already found a focus surface
if (can_focus_surface(view.get())) // make sure focusing this surface isn't disabled
new_focus = view->map_input_coordinates(x, y, lx, ly);
},
WF_VISIBLE_LAYERS);
return new_focus;
}
void input_manager::set_exclusive_focus(wl_client *client)
{
exclusive_client = client;
core->for_each_output([&client] (wayfire_output *output)
{
if (client)
inhibit_output(output);
else
uninhibit_output(output);
});
/* We no longer have an exclusively focused client, so we should restore
* focus to the topmost view */
if (!client)
core->get_active_output()->refocus(nullptr);
}
/* add/remove bindings */
wf_binding* input_manager::new_binding(wf_binding_type type, wf_option value,
wayfire_output *output, void *callback)
{
auto binding = std::make_unique<wf_binding>();
assert(value && output && callback);
binding->type = type;
binding->value = value;
binding->output = output;
binding->call.raw = callback;
auto raw = binding.get();
bindings[type].push_back(std::move(binding));
return raw;
}
void input_manager::rem_binding(binding_criteria criteria)
{
for(auto& category : bindings)
{
auto& container = category.second;
auto it = container.begin();
while (it != container.end())
{
if (criteria((*it).get())) {
it = container.erase(it);
} else {
++it;
}
}
}
}
void input_manager::rem_binding(wf_binding *binding)
{
rem_binding([=] (wf_binding *ptr) { return binding == ptr; });
}
void input_manager::rem_binding(void *callback)
{
rem_binding([=] (wf_binding* ptr) {return ptr->call.raw == callback; });
}
void input_manager::free_output_bindings(wayfire_output *output)
{
rem_binding([=] (wf_binding* binding) {
return binding->output == output;
});
}
<commit_msg>input-manager: handle null parameter in surface_map_state_changed<commit_after>#include <cassert>
#include <algorithm>
#include <libinput.h>
#include <iostream>
extern "C"
{
#include <wlr/types/wlr_seat.h>
}
#include "input-inhibit.hpp"
#include "signal-definitions.hpp"
#include "core.hpp"
#include "touch.hpp"
#include "keyboard.hpp"
#include "cursor.hpp"
#include "input-manager.hpp"
#include "workspace-manager.hpp"
#include "debug.hpp"
bool input_manager::is_touch_enabled()
{
return touch_count > 0;
}
void input_manager::update_capabilities()
{
uint32_t cap = 0;
if (pointer_count)
cap |= WL_SEAT_CAPABILITY_POINTER;
if (keyboards.size())
cap |= WL_SEAT_CAPABILITY_KEYBOARD;
if (touch_count)
cap |= WL_SEAT_CAPABILITY_TOUCH;
wlr_seat_set_capabilities(seat, cap);
}
void handle_new_input_cb(wl_listener*, void *data)
{
auto dev = static_cast<wlr_input_device*> (data);
assert(dev);
core->input->handle_new_input(dev);
}
void input_manager::handle_new_input(wlr_input_device *dev)
{
if (!cursor)
create_seat();
log_info("handle new input: %s, default mapping: %s", dev->name, dev->output_name);
input_devices.push_back(std::make_unique<wf_input_device> (dev));
if (dev->type == WLR_INPUT_DEVICE_KEYBOARD)
keyboards.push_back(std::make_unique<wf_keyboard> (dev, core->config));
if (dev->type == WLR_INPUT_DEVICE_POINTER)
{
cursor->attach_device(dev);
pointer_count++;
}
if (dev->type == WLR_INPUT_DEVICE_TOUCH)
{
touch_count++;
if (!our_touch)
our_touch = std::unique_ptr<wf_touch> (new wf_touch(cursor->cursor));
our_touch->add_device(dev);
}
auto section = core->config->get_section(nonull(dev->name));
auto mapped_output = section->get_option("output",
nonull(dev->output_name))->as_string();
auto wo = core->get_output(mapped_output);
if (wo)
wlr_cursor_map_input_to_output(cursor->cursor, dev, wo->handle);
update_capabilities();
}
void input_manager::handle_input_destroyed(wlr_input_device *dev)
{
log_info("remove input: %s", dev->name);
auto it = std::remove_if(input_devices.begin(), input_devices.end(),
[=] (const std::unique_ptr<wf_input_device>& idev) { return idev->device == dev; });
input_devices.erase(it, input_devices.end());
if (dev->type == WLR_INPUT_DEVICE_KEYBOARD)
{
auto it = std::remove_if(keyboards.begin(), keyboards.end(),
[=] (const std::unique_ptr<wf_keyboard>& kbd) { return kbd->device == dev; });
keyboards.erase(it, keyboards.end());
}
if (dev->type == WLR_INPUT_DEVICE_POINTER)
{
cursor->detach_device(dev);
pointer_count--;
}
if (dev->type == WLR_INPUT_DEVICE_TOUCH)
touch_count--;
update_capabilities();
}
input_manager::input_manager()
{
input_device_created.notify = handle_new_input_cb;
seat = wlr_seat_create(core->display, "default");
wl_signal_add(&core->backend->events.new_input,
&input_device_created);
surface_map_state_changed = [=] (signal_data *data)
{
auto ev = static_cast<_surface_map_state_changed_signal*> (data);
if (ev && cursor->grabbed_surface == ev->surface && !ev->surface->is_mapped())
{
cursor->end_held_grab();
} else
{
update_cursor_position(get_current_time(), false);
}
if (our_touch)
{
if (ev && our_touch->grabbed_surface == ev->surface && !ev->surface->is_mapped())
our_touch->end_touch_down_grab();
for (auto f : our_touch->gesture_recognizer.current)
handle_touch_motion(get_current_time(), f.first, f.second.sx, f.second.sy);
}
};
config_updated = [=] (signal_data *)
{
for (auto& dev : input_devices)
dev->update_options();
for (auto& kbd : keyboards)
kbd->reload_input_options();
};
core->connect_signal("reload-config", &config_updated);
/*
session_listener.notify = session_signal_handler;
wl_signal_add(&core->ec->session_signal, &session_listener);
*/
}
input_manager::~input_manager()
{
core->disconnect_signal("reload-config", &config_updated);
}
uint32_t input_manager::get_modifiers()
{
uint32_t mods = 0;
auto keyboard = wlr_seat_get_keyboard(seat);
if (keyboard)
mods = wlr_keyboard_get_modifiers(keyboard);
return mods;
}
bool input_manager::grab_input(wayfire_grab_interface iface)
{
if (!iface || !iface->grabbed || !session_active)
return false;
assert(!active_grab); // cannot have two active input grabs!
if (our_touch)
our_touch->input_grabbed();
active_grab = iface;
auto kbd = wlr_seat_get_keyboard(seat);
auto mods = kbd->modifiers;
mods.depressed = 0;
wlr_seat_keyboard_send_modifiers(seat, &mods);
set_keyboard_focus(NULL, seat);
update_cursor_focus(nullptr, 0, 0);
core->set_cursor("default");
return true;
}
static void idle_update_cursor(void *data)
{
auto input = (input_manager*) data;
input->update_cursor_position(get_current_time(), false);
}
void input_manager::ungrab_input()
{
if (active_grab)
active_grab->output->set_active_view(active_grab->output->get_active_view());
active_grab = nullptr;
/* We must update cursor focus, however, if we update "too soon", the current
* pointer event (button press/release, maybe something else) will be sent to
* the client, which shouldn't happen (at the time of the event, there was
* still an active input grab) */
wl_event_loop_add_idle(core->ev_loop, idle_update_cursor, this);
}
bool input_manager::input_grabbed()
{
return active_grab || !session_active;
}
void input_manager::toggle_session()
{
session_active ^= 1;
if (!session_active)
{
if (active_grab)
{
auto grab = active_grab;
ungrab_input();
active_grab = grab;
}
} else
{
if (active_grab)
{
auto grab = active_grab;
active_grab = nullptr;
grab_input(grab);
}
}
}
bool input_manager::can_focus_surface(wayfire_surface_t *surface)
{
if (exclusive_client && surface->get_client() != exclusive_client)
return false;
return true;
}
wayfire_surface_t* input_manager::input_surface_at(int x, int y,
int& lx, int& ly)
{
auto output = core->get_output_at(x, y);
/* If the output at these coordinates was just destroyed or some other edge case */
if (!output)
return nullptr;
auto og = output->get_layout_geometry();
x -= og.x;
y -= og.y;
wayfire_surface_t *new_focus = nullptr;
output->workspace->for_each_view(
[&] (wayfire_view view)
{
if (new_focus) return; // we already found a focus surface
if (can_focus_surface(view.get())) // make sure focusing this surface isn't disabled
new_focus = view->map_input_coordinates(x, y, lx, ly);
},
WF_VISIBLE_LAYERS);
return new_focus;
}
void input_manager::set_exclusive_focus(wl_client *client)
{
exclusive_client = client;
core->for_each_output([&client] (wayfire_output *output)
{
if (client)
inhibit_output(output);
else
uninhibit_output(output);
});
/* We no longer have an exclusively focused client, so we should restore
* focus to the topmost view */
if (!client)
core->get_active_output()->refocus(nullptr);
}
/* add/remove bindings */
wf_binding* input_manager::new_binding(wf_binding_type type, wf_option value,
wayfire_output *output, void *callback)
{
auto binding = std::make_unique<wf_binding>();
assert(value && output && callback);
binding->type = type;
binding->value = value;
binding->output = output;
binding->call.raw = callback;
auto raw = binding.get();
bindings[type].push_back(std::move(binding));
return raw;
}
void input_manager::rem_binding(binding_criteria criteria)
{
for(auto& category : bindings)
{
auto& container = category.second;
auto it = container.begin();
while (it != container.end())
{
if (criteria((*it).get())) {
it = container.erase(it);
} else {
++it;
}
}
}
}
void input_manager::rem_binding(wf_binding *binding)
{
rem_binding([=] (wf_binding *ptr) { return binding == ptr; });
}
void input_manager::rem_binding(void *callback)
{
rem_binding([=] (wf_binding* ptr) {return ptr->call.raw == callback; });
}
void input_manager::free_output_bindings(wayfire_output *output)
{
rem_binding([=] (wf_binding* binding) {
return binding->output == output;
});
}
<|endoftext|>
|
<commit_before>#include<bits/stdc++.h>
using namespace std;
const int much = 1000000;
bool is_prime[much];
void sieve(){
memset (is_prime, true, sizeof(is_prime));
is_prime[0] = is_prime [1] = false;
for (int i = 2; i < much; ++i) {
for (int j = (i << 1); j < much; j += i) {
is_prime[j] = false;
}
}
}
bool test(int t)
{
int orig = t, cnt = 0, tmp10 = 1;
while (t > 0) {
if (!is_prime [t]) {
return false;
}
t /= 10;
++cnt;
tmp10 *= 10;
}
while(orig > 0)
{
if (!is_prime[orig]) {
return false;
}
orig = (orig % (tmp10 /= 10));
}
return true;
}
int main()
{
long long sum = 0;
sieve ();
for (int i = 10; i < much; ++i) {
if (test(i)) {
sum += i;
}
}
cout << sum << '\n';
return 0;
}
<commit_msg>Make small changes<commit_after>#include<bits/stdc++.h>
using namespace std;
const int much = 1000000;
bool is_prime[much];
void sieve(){
memset (is_prime, true, sizeof(is_prime));
is_prime[0] = is_prime[1] = false;
for (int i = 2; i < much; ++i) {
for (int j = (i << 1); j < much; j += i) {
is_prime[j] = false;
}
}
}
bool test(int t)
{
int orig = t, cnt = 0, tmp10 = 1;
while (t > 0) {
if (!is_prime[t]) {
return false;
}
t /= 10;
++cnt;
tmp10 *= 10;
}
while(orig > 0)
{
if (!is_prime[orig]) {
return false;
}
orig = (orig % (tmp10 /= 10));
}
return true;
}
int main()
{
long long sum = 0;
sieve ();
for (int i = 10; i < much; ++i) {
if (test(i)) {
sum += i;
}
}
cout << sum << '\n';
return 0;
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
#include "atn/LL1Analyzer.h"
#include "Token.h"
#include "atn/RuleTransition.h"
#include "misc/IntervalSet.h"
#include "RuleContext.h"
#include "atn/DecisionState.h"
#include "Recognizer.h"
#include "atn/ATNType.h"
#include "Exceptions.h"
#include "support/CPPUtils.h"
#include "atn/ATN.h"
using namespace antlr4;
using namespace antlr4::atn;
using namespace antlrcpp;
ATN::ATN() : ATN(ATNType::LEXER, 0) {
}
ATN::ATN(ATN &&other) {
// All source vectors are implicitly cleared by the moves.
states = std::move(other.states);
decisionToState = std::move(other.decisionToState);
ruleToStartState = std::move(other.ruleToStartState);
ruleToStopState = std::move(other.ruleToStopState);
grammarType = std::move(other.grammarType);
maxTokenType = std::move(other.maxTokenType);
ruleToTokenType = std::move(other.ruleToTokenType);
lexerActions = std::move(other.lexerActions);
modeToStartState = std::move(other.modeToStartState);
}
ATN::ATN(ATNType grammarType_in, size_t maxTokenType_in) : grammarType(grammarType_in), maxTokenType(maxTokenType_in) {
}
ATN::~ATN() {
for (ATNState *state : states) {
delete state;
}
}
/**
* Required to be defined (even though not used) as we have an explicit move assignment operator.
*/
ATN& ATN::operator = (ATN &other) NOEXCEPT {
states = other.states;
decisionToState = other.decisionToState;
ruleToStartState = other.ruleToStartState;
ruleToStopState = other.ruleToStopState;
grammarType = other.grammarType;
maxTokenType = other.maxTokenType;
ruleToTokenType = other.ruleToTokenType;
lexerActions = other.lexerActions;
modeToStartState = other.modeToStartState;
return *this;
}
/**
* Explicit move assignment operator to make this the preferred assignment. With implicit copy/move assignment
* operators it seems the copy operator is preferred causing trouble when releasing the allocated ATNState instances.
*/
ATN& ATN::operator = (ATN &&other) NOEXCEPT {
// All source vectors are implicitly cleared by the moves.
states = std::move(other.states);
decisionToState = std::move(other.decisionToState);
ruleToStartState = std::move(other.ruleToStartState);
ruleToStopState = std::move(other.ruleToStopState);
grammarType = std::move(other.grammarType);
maxTokenType = std::move(other.maxTokenType);
ruleToTokenType = std::move(other.ruleToTokenType);
lexerActions = std::move(other.lexerActions);
modeToStartState = std::move(other.modeToStartState);
return *this;
}
misc::IntervalSet ATN::nextTokens(ATNState *s, RuleContext *ctx) const {
LL1Analyzer analyzer(*this);
return analyzer.LOOK(s, ctx);
}
misc::IntervalSet& ATN::nextTokens(ATNState *s) const {
if (s->nextTokenWithinRule.isEmpty()) {
s->nextTokenWithinRule = nextTokens(s, nullptr);
s->nextTokenWithinRule.setReadOnly(true);
}
return s->nextTokenWithinRule;
}
void ATN::addState(ATNState *state) {
if (state != nullptr) {
//state->atn = this;
state->stateNumber = (int)states.size();
}
states.push_back(state);
}
void ATN::removeState(ATNState *state) {
delete states.at(state->stateNumber);// just free mem, don't shift states in list
states.at(state->stateNumber) = nullptr;
}
int ATN::defineDecisionState(DecisionState *s) {
decisionToState.push_back(s);
s->decision = (int)decisionToState.size() - 1;
return s->decision;
}
DecisionState *ATN::getDecisionState(size_t decision) const {
if (!decisionToState.empty()) {
return decisionToState[decision];
}
return nullptr;
}
size_t ATN::getNumberOfDecisions() const {
return decisionToState.size();
}
misc::IntervalSet ATN::getExpectedTokens(size_t stateNumber, RuleContext *context) const {
if (stateNumber == ATNState::INVALID_STATE_NUMBER || stateNumber >= states.size()) {
throw IllegalArgumentException("Invalid state number.");
}
RuleContext *ctx = context;
ATNState *s = states.at(stateNumber);
misc::IntervalSet following = nextTokens(s);
if (!following.contains(Token::EPSILON)) {
return following;
}
misc::IntervalSet expected;
expected.addAll(following);
expected.remove(Token::EPSILON);
while (ctx && ctx->invokingState != ATNState::INVALID_STATE_NUMBER && following.contains(Token::EPSILON)) {
ATNState *invokingState = states.at(ctx->invokingState);
RuleTransition *rt = static_cast<RuleTransition*>(invokingState->transitions[0]);
following = nextTokens(rt->followState);
expected.addAll(following);
expected.remove(Token::EPSILON);
if (ctx->parent == nullptr) {
break;
}
ctx = (RuleContext *)ctx->parent;
}
if (following.contains(Token::EPSILON)) {
expected.add(Token::EOF);
}
return expected;
}
std::string ATN::toString() const {
std::stringstream ss;
std::string type;
switch (grammarType) {
case ATNType::LEXER:
type = "LEXER ";
break;
case ATNType::PARSER:
type = "PARSER ";
break;
default:
break;
}
ss << "(" << type << "ATN " << std::hex << this << std::dec << ") maxTokenType: " << maxTokenType << std::endl;
ss << "states (" << states.size() << ") {" << std::endl;
size_t index = 0;
for (auto state : states) {
if (state == nullptr) {
ss << " " << index++ << ": nul" << std::endl;
} else {
std::string text = state->toString();
ss << " " << index++ << ": " << indent(text, " ", false) << std::endl;
}
}
index = 0;
for (auto state : decisionToState) {
if (state == nullptr) {
ss << " " << index++ << ": nul" << std::endl;
} else {
std::string text = state->toString();
ss << " " << index++ << ": " << indent(text, " ", false) << std::endl;
}
}
ss << "}";
return ss.str();
}
<commit_msg>ATN: Handle empty, read-only, nextTokenWithinRule<commit_after>/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
#include "atn/LL1Analyzer.h"
#include "Token.h"
#include "atn/RuleTransition.h"
#include "misc/IntervalSet.h"
#include "RuleContext.h"
#include "atn/DecisionState.h"
#include "Recognizer.h"
#include "atn/ATNType.h"
#include "Exceptions.h"
#include "support/CPPUtils.h"
#include "atn/ATN.h"
using namespace antlr4;
using namespace antlr4::atn;
using namespace antlrcpp;
ATN::ATN() : ATN(ATNType::LEXER, 0) {
}
ATN::ATN(ATN &&other) {
// All source vectors are implicitly cleared by the moves.
states = std::move(other.states);
decisionToState = std::move(other.decisionToState);
ruleToStartState = std::move(other.ruleToStartState);
ruleToStopState = std::move(other.ruleToStopState);
grammarType = std::move(other.grammarType);
maxTokenType = std::move(other.maxTokenType);
ruleToTokenType = std::move(other.ruleToTokenType);
lexerActions = std::move(other.lexerActions);
modeToStartState = std::move(other.modeToStartState);
}
ATN::ATN(ATNType grammarType_in, size_t maxTokenType_in) : grammarType(grammarType_in), maxTokenType(maxTokenType_in) {
}
ATN::~ATN() {
for (ATNState *state : states) {
delete state;
}
}
/**
* Required to be defined (even though not used) as we have an explicit move assignment operator.
*/
ATN& ATN::operator = (ATN &other) NOEXCEPT {
states = other.states;
decisionToState = other.decisionToState;
ruleToStartState = other.ruleToStartState;
ruleToStopState = other.ruleToStopState;
grammarType = other.grammarType;
maxTokenType = other.maxTokenType;
ruleToTokenType = other.ruleToTokenType;
lexerActions = other.lexerActions;
modeToStartState = other.modeToStartState;
return *this;
}
/**
* Explicit move assignment operator to make this the preferred assignment. With implicit copy/move assignment
* operators it seems the copy operator is preferred causing trouble when releasing the allocated ATNState instances.
*/
ATN& ATN::operator = (ATN &&other) NOEXCEPT {
// All source vectors are implicitly cleared by the moves.
states = std::move(other.states);
decisionToState = std::move(other.decisionToState);
ruleToStartState = std::move(other.ruleToStartState);
ruleToStopState = std::move(other.ruleToStopState);
grammarType = std::move(other.grammarType);
maxTokenType = std::move(other.maxTokenType);
ruleToTokenType = std::move(other.ruleToTokenType);
lexerActions = std::move(other.lexerActions);
modeToStartState = std::move(other.modeToStartState);
return *this;
}
misc::IntervalSet ATN::nextTokens(ATNState *s, RuleContext *ctx) const {
LL1Analyzer analyzer(*this);
return analyzer.LOOK(s, ctx);
}
misc::IntervalSet& ATN::nextTokens(ATNState *s) const {
if (s->nextTokenWithinRule.isEmpty()) {
auto candidate = nextTokens(s, nullptr);
if (!candidate.isEmpty() || !s->nextTokenWithinRule.isReadOnly()) {
s->nextTokenWithinRule = candidate;
s->nextTokenWithinRule.setReadOnly(true);
}
}
return s->nextTokenWithinRule;
}
void ATN::addState(ATNState *state) {
if (state != nullptr) {
//state->atn = this;
state->stateNumber = (int)states.size();
}
states.push_back(state);
}
void ATN::removeState(ATNState *state) {
delete states.at(state->stateNumber);// just free mem, don't shift states in list
states.at(state->stateNumber) = nullptr;
}
int ATN::defineDecisionState(DecisionState *s) {
decisionToState.push_back(s);
s->decision = (int)decisionToState.size() - 1;
return s->decision;
}
DecisionState *ATN::getDecisionState(size_t decision) const {
if (!decisionToState.empty()) {
return decisionToState[decision];
}
return nullptr;
}
size_t ATN::getNumberOfDecisions() const {
return decisionToState.size();
}
misc::IntervalSet ATN::getExpectedTokens(size_t stateNumber, RuleContext *context) const {
if (stateNumber == ATNState::INVALID_STATE_NUMBER || stateNumber >= states.size()) {
throw IllegalArgumentException("Invalid state number.");
}
RuleContext *ctx = context;
ATNState *s = states.at(stateNumber);
misc::IntervalSet following = nextTokens(s);
if (!following.contains(Token::EPSILON)) {
return following;
}
misc::IntervalSet expected;
expected.addAll(following);
expected.remove(Token::EPSILON);
while (ctx && ctx->invokingState != ATNState::INVALID_STATE_NUMBER && following.contains(Token::EPSILON)) {
ATNState *invokingState = states.at(ctx->invokingState);
RuleTransition *rt = static_cast<RuleTransition*>(invokingState->transitions[0]);
following = nextTokens(rt->followState);
expected.addAll(following);
expected.remove(Token::EPSILON);
if (ctx->parent == nullptr) {
break;
}
ctx = (RuleContext *)ctx->parent;
}
if (following.contains(Token::EPSILON)) {
expected.add(Token::EOF);
}
return expected;
}
std::string ATN::toString() const {
std::stringstream ss;
std::string type;
switch (grammarType) {
case ATNType::LEXER:
type = "LEXER ";
break;
case ATNType::PARSER:
type = "PARSER ";
break;
default:
break;
}
ss << "(" << type << "ATN " << std::hex << this << std::dec << ") maxTokenType: " << maxTokenType << std::endl;
ss << "states (" << states.size() << ") {" << std::endl;
size_t index = 0;
for (auto state : states) {
if (state == nullptr) {
ss << " " << index++ << ": nul" << std::endl;
} else {
std::string text = state->toString();
ss << " " << index++ << ": " << indent(text, " ", false) << std::endl;
}
}
index = 0;
for (auto state : decisionToState) {
if (state == nullptr) {
ss << " " << index++ << ": nul" << std::endl;
} else {
std::string text = state->toString();
ss << " " << index++ << ": " << indent(text, " ", false) << std::endl;
}
}
ss << "}";
return ss.str();
}
<|endoftext|>
|
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2018 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"
#include "mbed_trace.h"
#include <stdlib.h>
using namespace utest::v1;
#define TEST_BLOCK_COUNT 10
#define TEST_ERROR_MASK 16
#define TEST_NUM_OF_THREADS 5
const struct {
const char *name;
bd_size_t (BlockDevice::*method)() const;
} ATTRS[] = {
{"read size", &BlockDevice::get_read_size},
{"program size", &BlockDevice::get_program_size},
{"erase size", &BlockDevice::get_erase_size},
{"total size", &BlockDevice::size},
};
static SingletonPtr<PlatformMutex> _mutex;
// Mutex is protecting rand() per srand for buffer writing and verification.
// Mutex is also protecting printouts for clear logs.
// Mutex is NOT protecting Block Device actions: erase/program/read - which is the purpose of the multithreaded test!
void basic_erase_program_read_test(BlockDevice *block_device, bd_size_t block_size, uint8_t *write_block,
uint8_t *read_block, unsigned addrwidth)
{
int err = 0;
_mutex->lock();
// Find a random block
bd_addr_t block = (rand() * block_size) % (block_device->size());
// Use next random number as temporary seed to keep
// the address progressing in the pseudorandom sequence
unsigned seed = rand();
// Fill with random sequence
srand(seed);
for (bd_size_t i_ind = 0; i_ind < block_size; i_ind++) {
write_block[i_ind] = 0xff & rand();
}
// Write, sync, and read the block
utest_printf("\ntest %0*llx:%llu...", addrwidth, block, block_size);
_mutex->unlock();
err = block_device->erase(block, block_size);
TEST_ASSERT_EQUAL(0, err);
err = block_device->program(write_block, block, block_size);
TEST_ASSERT_EQUAL(0, err);
err = block_device->read(read_block, block, block_size);
TEST_ASSERT_EQUAL(0, err);
_mutex->lock();
// Check that the data was unmodified
srand(seed);
int val_rand;
for (bd_size_t i_ind = 0; i_ind < block_size; i_ind++) {
val_rand = rand();
if ( (0xff & val_rand) != read_block[i_ind] ) {
utest_printf("\n Assert Failed Buf Read - block:size: %llx:%llu \n", block, block_size);
utest_printf("\n pos: %llu, exp: %02x, act: %02x, wrt: %02x \n", i_ind, (0xff & val_rand),
read_block[i_ind],
write_block[i_ind] );
}
TEST_ASSERT_EQUAL(0xff & val_rand, read_block[i_ind]);
}
_mutex->unlock();
}
void test_random_program_read_erase()
{
utest_printf("\nTest Random Program Read Erase Starts..\n");
BlockDevice *block_device = BlockDevice::get_default_instance();
int err = block_device->init();
TEST_ASSERT_EQUAL(0, err);
for (unsigned atr = 0; atr < sizeof(ATTRS) / sizeof(ATTRS[0]); atr++) {
static const char *prefixes[] = {"", "k", "M", "G"};
for (int i_ind = 3; i_ind >= 0; i_ind--) {
bd_size_t size = (block_device->*ATTRS[atr].method)();
if (size >= (1ULL << 10 * i_ind)) {
utest_printf("%s: %llu%sbytes (%llubytes)\n",
ATTRS[atr].name, size >> 10 * i_ind, prefixes[i_ind], size);
break;
}
}
}
bd_size_t block_size = block_device->get_erase_size();
unsigned addrwidth = ceil(log(float(block_device->size() - 1)) / log(float(16))) + 1;
uint8_t *write_block = new (std::nothrow) uint8_t[block_size];
uint8_t *read_block = new (std::nothrow) uint8_t[block_size];
if (!write_block || !read_block) {
utest_printf("\n Not enough memory for test");
goto end;
}
for (int b = 0; b < TEST_BLOCK_COUNT; b++) {
basic_erase_program_read_test(block_device, block_size, write_block, read_block, addrwidth);
}
err = block_device->deinit();
TEST_ASSERT_EQUAL(0, err);
end:
delete[] write_block;
delete[] read_block;
}
static void test_thread_job(void *block_device_ptr)
{
static int thread_num = 0;
thread_num++;
BlockDevice *block_device = (BlockDevice *)block_device_ptr;
bd_size_t block_size = block_device->get_erase_size();
unsigned addrwidth = ceil(log(float(block_device->size() - 1)) / log(float(16))) + 1;
uint8_t *write_block = new (std::nothrow) uint8_t[block_size];
uint8_t *read_block = new (std::nothrow) uint8_t[block_size];
if (!write_block || !read_block ) {
utest_printf("\n Not enough memory for test");
goto end;
}
for (int b = 0; b < TEST_BLOCK_COUNT; b++) {
basic_erase_program_read_test(block_device, block_size, write_block, read_block, addrwidth);
}
end:
delete[] write_block;
delete[] read_block;
}
void test_multi_threads()
{
utest_printf("\nTest Multi Threaded Erase/Program/Read Starts..\n");
BlockDevice *block_device = BlockDevice::get_default_instance();
int err = block_device->init();
TEST_ASSERT_EQUAL(0, err);
for (unsigned atr = 0; atr < sizeof(ATTRS) / sizeof(ATTRS[0]); atr++) {
static const char *prefixes[] = {"", "k", "M", "G"};
for (int i_ind = 3; i_ind >= 0; i_ind--) {
bd_size_t size = (block_device->*ATTRS[atr].method)();
if (size >= (1ULL << 10 * i_ind)) {
utest_printf("%s: %llu%sbytes (%llubytes)\n",
ATTRS[atr].name, size >> 10 * i_ind, prefixes[i_ind], size);
break;
}
}
}
rtos::Thread bd_thread[TEST_NUM_OF_THREADS];
osStatus threadStatus;
int i_ind;
for (i_ind = 0; i_ind < TEST_NUM_OF_THREADS; i_ind++) {
threadStatus = bd_thread[i_ind].start(callback(test_thread_job, (void *)block_device));
if (threadStatus != 0) {
utest_printf("\n Thread %d Start Failed!", i_ind + 1);
}
}
for (i_ind = 0; i_ind < TEST_NUM_OF_THREADS; i_ind++) {
bd_thread[i_ind].join();
}
err = block_device->deinit();
TEST_ASSERT_EQUAL(0, err);
}
// Test setup
utest::v1::status_t test_setup(const size_t number_of_cases)
{
GREENTEA_SETUP(60, "default_auto");
return verbose_test_setup_handler(number_of_cases);
}
Case cases[] = {
Case("Testing read write random blocks", test_random_program_read_erase),
Case("Testing Multi Threads Erase Program Read", test_multi_threads)
};
Specification specification(test_setup, cases);
int main()
{
return !Harness::run(specification);
}
<commit_msg>Fix build issues<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2018 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mbed.h"
#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"
#include "mbed_trace.h"
#include <stdlib.h>
using namespace utest::v1;
#define TEST_BLOCK_COUNT 10
#define TEST_ERROR_MASK 16
#define TEST_NUM_OF_THREADS 5
const struct {
const char *name;
bd_size_t (BlockDevice::*method)() const;
} ATTRS[] = {
{"read size", &BlockDevice::get_read_size},
{"program size", &BlockDevice::get_program_size},
{"erase size", &BlockDevice::get_erase_size},
{"total size", &BlockDevice::size},
};
static SingletonPtr<PlatformMutex> _mutex;
// Mutex is protecting rand() per srand for buffer writing and verification.
// Mutex is also protecting printouts for clear logs.
// Mutex is NOT protecting Block Device actions: erase/program/read - which is the purpose of the multithreaded test!
void basic_erase_program_read_test(BlockDevice *block_device, bd_size_t block_size, uint8_t *write_block,
uint8_t *read_block, unsigned addrwidth)
{
int err = 0;
_mutex->lock();
// Find a random block
bd_addr_t block = (rand() * block_size) % (block_device->size());
// Use next random number as temporary seed to keep
// the address progressing in the pseudorandom sequence
unsigned seed = rand();
// Fill with random sequence
srand(seed);
for (bd_size_t i_ind = 0; i_ind < block_size; i_ind++) {
write_block[i_ind] = 0xff & rand();
}
// Write, sync, and read the block
utest_printf("\ntest %0*llx:%llu...", addrwidth, block, block_size);
_mutex->unlock();
err = block_device->erase(block, block_size);
TEST_ASSERT_EQUAL(0, err);
err = block_device->program(write_block, block, block_size);
TEST_ASSERT_EQUAL(0, err);
err = block_device->read(read_block, block, block_size);
TEST_ASSERT_EQUAL(0, err);
_mutex->lock();
// Check that the data was unmodified
srand(seed);
int val_rand;
for (bd_size_t i_ind = 0; i_ind < block_size; i_ind++) {
val_rand = rand();
if ( (0xff & val_rand) != read_block[i_ind] ) {
utest_printf("\n Assert Failed Buf Read - block:size: %llx:%llu \n", block, block_size);
utest_printf("\n pos: %llu, exp: %02x, act: %02x, wrt: %02x \n", i_ind, (0xff & val_rand),
read_block[i_ind],
write_block[i_ind] );
}
TEST_ASSERT_EQUAL(0xff & val_rand, read_block[i_ind]);
}
_mutex->unlock();
}
void test_random_program_read_erase()
{
utest_printf("\nTest Random Program Read Erase Starts..\n");
BlockDevice *block_device = BlockDevice::get_default_instance();
int err = block_device->init();
TEST_ASSERT_EQUAL(0, err);
for (unsigned atr = 0; atr < sizeof(ATTRS) / sizeof(ATTRS[0]); atr++) {
static const char *prefixes[] = {"", "k", "M", "G"};
for (int i_ind = 3; i_ind >= 0; i_ind--) {
bd_size_t size = (block_device->*ATTRS[atr].method)();
if (size >= (1ULL << 10 * i_ind)) {
utest_printf("%s: %llu%sbytes (%llubytes)\n",
ATTRS[atr].name, size >> 10 * i_ind, prefixes[i_ind], size);
break;
}
}
}
bd_size_t block_size = block_device->get_erase_size();
unsigned addrwidth = ceil(log(float(block_device->size() - 1)) / log(float(16))) + 1;
uint8_t *write_block = new (std::nothrow) uint8_t[block_size];
uint8_t *read_block = new (std::nothrow) uint8_t[block_size];
if (!write_block || !read_block) {
utest_printf("\n Not enough memory for test");
goto end;
}
for (int b = 0; b < TEST_BLOCK_COUNT; b++) {
basic_erase_program_read_test(block_device, block_size, write_block, read_block, addrwidth);
}
err = block_device->deinit();
TEST_ASSERT_EQUAL(0, err);
end:
delete[] write_block;
delete[] read_block;
}
static void test_thread_job(void *block_device_ptr)
{
static int thread_num = 0;
thread_num++;
BlockDevice *block_device = (BlockDevice *)block_device_ptr;
bd_size_t block_size = block_device->get_erase_size();
unsigned addrwidth = ceil(log(float(block_device->size() - 1)) / log(float(16))) + 1;
uint8_t *write_block = new (std::nothrow) uint8_t[block_size];
uint8_t *read_block = new (std::nothrow) uint8_t[block_size];
if (!write_block || !read_block ) {
utest_printf("\n Not enough memory for test");
goto end;
}
for (int b = 0; b < TEST_BLOCK_COUNT; b++) {
basic_erase_program_read_test(block_device, block_size, write_block, read_block, addrwidth);
}
end:
delete[] write_block;
delete[] read_block;
}
void test_multi_threads()
{
utest_printf("\nTest Multi Threaded Erase/Program/Read Starts..\n");
BlockDevice *block_device = BlockDevice::get_default_instance();
int err = block_device->init();
TEST_ASSERT_EQUAL(0, err);
for (unsigned atr = 0; atr < sizeof(ATTRS) / sizeof(ATTRS[0]); atr++) {
static const char *prefixes[] = {"", "k", "M", "G"};
for (int i_ind = 3; i_ind >= 0; i_ind--) {
bd_size_t size = (block_device->*ATTRS[atr].method)();
if (size >= (1ULL << 10 * i_ind)) {
utest_printf("%s: %llu%sbytes (%llubytes)\n",
ATTRS[atr].name, size >> 10 * i_ind, prefixes[i_ind], size);
break;
}
}
}
rtos::Thread bd_thread[TEST_NUM_OF_THREADS];
osStatus threadStatus;
int i_ind;
for (i_ind = 0; i_ind < TEST_NUM_OF_THREADS; i_ind++) {
threadStatus = bd_thread[i_ind].start(callback(test_thread_job, (void *)block_device));
if (threadStatus != 0) {
utest_printf("\n Thread %d Start Failed!", i_ind + 1);
}
}
for (i_ind = 0; i_ind < TEST_NUM_OF_THREADS; i_ind++) {
bd_thread[i_ind].join();
}
err = block_device->deinit();
TEST_ASSERT_EQUAL(0, err);
}
// Test setup
utest::v1::status_t test_setup(const size_t number_of_cases)
{
GREENTEA_SETUP(60, "default_auto");
return verbose_test_setup_handler(number_of_cases);
}
Case cases[] = {
Case("Testing read write random blocks", test_random_program_read_erase),
Case("Testing Multi Threads Erase Program Read", test_multi_threads)
};
Specification specification(test_setup, cases);
int main()
{
return !Harness::run(specification);
}
<|endoftext|>
|
<commit_before>// copyright
#include "cif++/Config.h"
#include "cif++/Cif++.h"
#include "cif++/BondMap.h"
#include "cif++/Compound.h"
#include "cif++/CifUtils.h"
using namespace std;
namespace mmcif
{
// --------------------------------------------------------------------
BondMap::BondMap(const Structure& p)
: dim(0)
{
auto atoms = p.atoms();
dim = atoms.size();
bond = vector<bool>(dim * (dim - 1), false);
for (auto& atom: atoms)
{
size_t ix = index.size();
index[atom.id()] = ix;
};
auto bindAtoms = [this](const string& a, const string& b)
{
size_t ixa = index[a];
size_t ixb = index[b];
if (ixb < ixa)
swap(ixa, ixb);
uint32 ix = ixb + ixa * dim - ixa * (ixa + 1) / 2;
assert(ix < bond.size());
bond[ix] = true;
};
cif::Datablock& db = p.getFile().data();
// collect all compounds first
set<string> compounds;
for (auto c: db["chem_comp"])
compounds.insert(c["id"].as<string>());
// make sure we also have all residues in the polyseq
for (auto m: db["entity_poly_seq"])
{
string c = m["mon_id"].as<string>();
if (compounds.count(c))
continue;
cerr << "Warning: mon_id " << c << " is missing in the chem_comp category" << endl;
compounds.insert(c);
}
// first link all residues in a polyseq
string lastAsymID;
int lastSeqID = 0;
for (auto r: db["pdbx_poly_seq_scheme"])
{
string asymId;
int seqId;
cif::tie(asymId, seqId) = r.get("asym_id", "seq_id");
if (asymId != lastAsymID) // first in a new sequece
{
lastAsymID = asymId;
lastSeqID = seqId;
continue;
}
auto c = db["atom_site"].find(cif::Key("label_asym_id") == asymId and cif::Key("label_seq_id") == lastSeqID and cif::Key("label_atom_id") == "C");
if (c.size() != 1)
cerr << "Unexpected number (" << c.size() << ") of atoms with atom ID C in asym_id " << asymId << " with seq id " << lastSeqID << endl;
auto n = db["atom_site"].find(cif::Key("label_asym_id") == asymId and cif::Key("label_seq_id") == seqId and cif::Key("label_atom_id") == "N");
if (n.size() != 1)
cerr << "Unexpected number (" << n.size() << ") of atoms with atom ID N in asym_id " << asymId << " with seq id " << seqId << endl;
if (not (c.empty() or n.empty()))
bindAtoms(c.front()["id"].as<string>(), n.front()["id"].as<string>());
lastSeqID = seqId;
}
for (auto l: db["struct_conn"])
{
string asym1, asym2, atomId1, atomId2;
int seqId1, seqId2;
cif::tie(asym1, asym2, atomId1, atomId2, seqId1, seqId2) =
l.get("ptnr1_label_asym_id", "ptnr2_label_asym_id",
"ptnr1_label_atom_id", "ptnr2_label_atom_id",
"ptnr1_label_seq_id", "ptnr2_label_seq_id");
auto a =
l["ptnr1_label_seq_id"].empty() ?
db["atom_site"].find(cif::Key("label_asym_id") == asym1 and cif::Key("label_atom_id") == atomId1) :
db["atom_site"].find(cif::Key("label_asym_id") == asym1 and cif::Key("label_seq_id") == seqId1 and cif::Key("label_atom_id") == atomId1);
if (a.size() != 1)
cerr << "Unexpected number (" << a.size() << ") of atoms for link with asym_id " << asym1 << " seq_id " << seqId1 << " atom_id " << atomId1 << endl;
auto b =
l["ptnr2_label_seq_id"].empty() ?
db["atom_site"].find(cif::Key("label_asym_id") == asym2 and cif::Key("label_atom_id") == atomId2) :
db["atom_site"].find(cif::Key("label_asym_id") == asym2 and cif::Key("label_seq_id") == seqId2 and cif::Key("label_atom_id") == atomId2);
if (b.size() != 1)
cerr << "Unexpected number (" << b.size() << ") of atoms for link with asym_id " << asym2 << " seq_id " << seqId2 << " atom_id " << atomId2 << endl;
if (not (a.empty() or b.empty()))
bindAtoms(a.front()["id"].as<string>(), b.front()["id"].as<string>());
}
// then link all atoms in the compounds
cif::Progress progress(compounds.size(), "Creating bond map");
for (auto c: compounds)
{
auto* compound = mmcif::Compound::create(c);
if (not compound)
{
cerr << "Missing compound information for " << c << endl;
continue;
}
if (compound->isWater())
{
if (VERBOSE)
cerr << "skipping water in bond map calculation" << endl;
continue;
}
// loop over poly_seq_scheme
for (auto r: db["pdbx_poly_seq_scheme"].find(cif::Key("mon_id") == c))
{
string asymId;
int seqId;
cif::tie(asymId, seqId) = r.get("asym_id", "seq_id");
vector<Atom> rAtoms;
for (auto a: db["atom_site"].find(cif::Key("label_asym_id") == asymId and cif::Key("label_seq_id") == seqId))
rAtoms.push_back(p.getAtomById(a["id"].as<string>()));
for (size_t i = 0; i + 1 < rAtoms.size(); ++i)
{
for (size_t j = i + 1; j < rAtoms.size(); ++j)
{
if (compound->atomsBonded(rAtoms[i].labelAtomId(), rAtoms[j].labelAtomId()))
bindAtoms(rAtoms[i].id(), rAtoms[j].id());
}
}
}
// loop over pdbx_nonpoly_scheme
for (auto r: db["pdbx_nonpoly_scheme"].find(cif::Key("mon_id") == c))
{
string asymId;
cif::tie(asymId) = r.get("asym_id");
vector<Atom> rAtoms;
for (auto a: db["atom_site"].find(cif::Key("label_asym_id") == asymId))
rAtoms.push_back(p.getAtomById(a["id"].as<string>()));
for (size_t i = 0; i + 1 < rAtoms.size(); ++i)
{
for (size_t j = i + 1; j < rAtoms.size(); ++j)
{
if (compound->atomsBonded(rAtoms[i].labelAtomId(), rAtoms[j].labelAtomId()))
{
size_t ixa = index[rAtoms[i].id()];
size_t ixb = index[rAtoms[j].id()];
if (ixb < ixa)
swap(ixa, ixb);
uint32 ix = ixb + ixa * dim - ixa * (ixa + 1) / 2;
assert(ix < bond.size());
bond[ix] = true;
}
}
}
}
progress.consumed(1);
}
}
bool BondMap::operator()(const Atom& a, const Atom& b) const
{
uint32 ixa = index.at(a.id());
uint32 ixb = index.at(b.id());
if (ixb < ixa)
swap(ixa, ixb);
uint32 ix = ixb + ixa * dim - ixa * (ixa + 1) / 2;
assert(ix < bond.size());
return bond[ix];
}
}
<commit_msg>refactored<commit_after>// copyright
#include "cif++/Config.h"
#include "cif++/Cif++.h"
#include "cif++/BondMap.h"
#include "cif++/Compound.h"
#include "cif++/CifUtils.h"
using namespace std;
namespace mmcif
{
// --------------------------------------------------------------------
BondMap::BondMap(const Structure& p)
: dim(0)
{
auto atoms = p.atoms();
dim = atoms.size();
bond = vector<bool>(dim * (dim - 1), false);
for (auto& atom: atoms)
{
size_t ix = index.size();
index[atom.id()] = ix;
};
auto bindAtoms = [this](const string& a, const string& b)
{
size_t ixa = index[a];
size_t ixb = index[b];
if (ixb < ixa)
swap(ixa, ixb);
uint32 ix = ixb + ixa * dim - ixa * (ixa + 1) / 2;
assert(ix < bond.size());
bond[ix] = true;
};
cif::Datablock& db = p.getFile().data();
// collect all compounds first
set<string> compounds;
for (auto c: db["chem_comp"])
compounds.insert(c["id"].as<string>());
// make sure we also have all residues in the polyseq
for (auto m: db["entity_poly_seq"])
{
string c = m["mon_id"].as<string>();
if (compounds.count(c))
continue;
cerr << "Warning: mon_id " << c << " is missing in the chem_comp category" << endl;
compounds.insert(c);
}
// first link all residues in a polyseq
string lastAsymID;
int lastSeqID = 0;
for (auto r: db["pdbx_poly_seq_scheme"])
{
string asymId;
int seqId;
cif::tie(asymId, seqId) = r.get("asym_id", "seq_id");
if (asymId != lastAsymID) // first in a new sequece
{
lastAsymID = asymId;
lastSeqID = seqId;
continue;
}
auto c = db["atom_site"].find(cif::Key("label_asym_id") == asymId and cif::Key("label_seq_id") == lastSeqID and cif::Key("label_atom_id") == "C");
if (c.size() != 1)
cerr << "Unexpected number (" << c.size() << ") of atoms with atom ID C in asym_id " << asymId << " with seq id " << lastSeqID << endl;
auto n = db["atom_site"].find(cif::Key("label_asym_id") == asymId and cif::Key("label_seq_id") == seqId and cif::Key("label_atom_id") == "N");
if (n.size() != 1)
cerr << "Unexpected number (" << n.size() << ") of atoms with atom ID N in asym_id " << asymId << " with seq id " << seqId << endl;
if (not (c.empty() or n.empty()))
bindAtoms(c.front()["id"].as<string>(), n.front()["id"].as<string>());
lastSeqID = seqId;
}
for (auto l: db["struct_conn"])
{
string asym1, asym2, atomId1, atomId2;
int seqId1, seqId2;
cif::tie(asym1, asym2, atomId1, atomId2, seqId1, seqId2) =
l.get("ptnr1_label_asym_id", "ptnr2_label_asym_id",
"ptnr1_label_atom_id", "ptnr2_label_atom_id",
"ptnr1_label_seq_id", "ptnr2_label_seq_id");
auto a =
l["ptnr1_label_seq_id"].empty() ?
db["atom_site"].find(cif::Key("label_asym_id") == asym1 and cif::Key("label_atom_id") == atomId1) :
db["atom_site"].find(cif::Key("label_asym_id") == asym1 and cif::Key("label_seq_id") == seqId1 and cif::Key("label_atom_id") == atomId1);
if (a.size() != 1)
cerr << "Unexpected number (" << a.size() << ") of atoms for link with asym_id " << asym1 << " seq_id " << seqId1 << " atom_id " << atomId1 << endl;
auto b =
l["ptnr2_label_seq_id"].empty() ?
db["atom_site"].find(cif::Key("label_asym_id") == asym2 and cif::Key("label_atom_id") == atomId2) :
db["atom_site"].find(cif::Key("label_asym_id") == asym2 and cif::Key("label_seq_id") == seqId2 and cif::Key("label_atom_id") == atomId2);
if (b.size() != 1)
cerr << "Unexpected number (" << b.size() << ") of atoms for link with asym_id " << asym2 << " seq_id " << seqId2 << " atom_id " << atomId2 << endl;
if (not (a.empty() or b.empty()))
bindAtoms(a.front()["id"].as<string>(), b.front()["id"].as<string>());
}
// then link all atoms in the compounds
cif::Progress progress(compounds.size(), "Creating bond map");
for (auto c: compounds)
{
auto* compound = mmcif::Compound::create(c);
if (not compound)
{
if (VERBOSE)
cerr << "Missing compound information for " << c << endl;
continue;
}
if (compound->isWater())
{
if (VERBOSE)
cerr << "skipping water in bond map calculation" << endl;
continue;
}
// loop over poly_seq_scheme
for (auto r: db["pdbx_poly_seq_scheme"].find(cif::Key("mon_id") == c))
{
string asymId;
int seqId;
cif::tie(asymId, seqId) = r.get("asym_id", "seq_id");
vector<Atom> rAtoms;
for (auto a: db["atom_site"].find(cif::Key("label_asym_id") == asymId and cif::Key("label_seq_id") == seqId))
rAtoms.push_back(p.getAtomById(a["id"].as<string>()));
for (size_t i = 0; i + 1 < rAtoms.size(); ++i)
{
for (size_t j = i + 1; j < rAtoms.size(); ++j)
{
if (compound->atomsBonded(rAtoms[i].labelAtomId(), rAtoms[j].labelAtomId()))
bindAtoms(rAtoms[i].id(), rAtoms[j].id());
}
}
}
// loop over pdbx_nonpoly_scheme
for (auto r: db["pdbx_nonpoly_scheme"].find(cif::Key("mon_id") == c))
{
string asymId;
cif::tie(asymId) = r.get("asym_id");
vector<Atom> rAtoms;
for (auto a: db["atom_site"].find(cif::Key("label_asym_id") == asymId))
rAtoms.push_back(p.getAtomById(a["id"].as<string>()));
for (size_t i = 0; i + 1 < rAtoms.size(); ++i)
{
for (size_t j = i + 1; j < rAtoms.size(); ++j)
{
if (compound->atomsBonded(rAtoms[i].labelAtomId(), rAtoms[j].labelAtomId()))
{
size_t ixa = index[rAtoms[i].id()];
size_t ixb = index[rAtoms[j].id()];
if (ixb < ixa)
swap(ixa, ixb);
uint32 ix = ixb + ixa * dim - ixa * (ixa + 1) / 2;
assert(ix < bond.size());
bond[ix] = true;
}
}
}
}
progress.consumed(1);
}
}
bool BondMap::operator()(const Atom& a, const Atom& b) const
{
uint32 ixa = index.at(a.id());
uint32 ixb = index.at(b.id());
if (ixb < ixa)
swap(ixa, ixb);
uint32 ix = ixb + ixa * dim - ixa * (ixa + 1) / 2;
assert(ix < bond.size());
return bond[ix];
}
}
<|endoftext|>
|
<commit_before>#pragma once
#include "CSingleton.hpp"
#include <vector>
#include <string>
#include <unordered_map>
#include <tuple>
#include <boost/chrono.hpp>
using std::vector;
using std::string;
using std::unordered_map;
using default_clock = boost::chrono::steady_clock;
#include "types.hpp"
#include "mysql.hpp"
class CResult
{
friend class CResultSet;
public:
struct FieldInfo
{
string Name;
enum_field_types Type;
};
private: //constructor / destructor
CResult() = default;
~CResult();
private: //variables
unsigned int m_NumFields = 0;
my_ulonglong m_NumRows = 0;
char ***m_Data = nullptr;
vector<FieldInfo> m_Fields;
public: //functions
inline my_ulonglong GetRowCount() const
{
return m_NumRows;
}
inline unsigned int GetFieldCount() const
{
return m_NumFields;
}
bool GetFieldName(unsigned int idx, string &dest) const;
bool GetFieldType(unsigned int idx, enum_field_types &dest) const;
bool GetRowData(unsigned int row, unsigned int fieldidx, const char **dest) const;
inline bool GetRowData(unsigned int row, unsigned int fieldidx, string &dest) const
{
const char *cdest = nullptr;
bool result = GetRowData(row, fieldidx, &cdest);
if(result && cdest != nullptr)
dest = cdest;
return result;
}
bool GetRowDataByName(unsigned int row, const string &field, const char **dest) const;
bool GetRowDataByName(unsigned int row, const string &field, string &dest) const
{
const char *cdest = nullptr;
bool result = GetRowDataByName(row, field, &cdest);
if (result && cdest != nullptr)
dest = cdest;
return result;
}
};
class CResultSet
{
public:
enum class TimeType
{
MILLISECONDS,
MICROSECONDS,
};
private:
CResultSet() = default;
public:
~CResultSet();
private:
vector<Result_t> m_Results;
Result_t m_ActiveResult = nullptr;
my_ulonglong
m_InsertId = 0,
m_AffectedRows = 0;
unsigned int m_WarningCount = 0;
unsigned int
m_ExecTimeMilli = 0,
m_ExecTimeMicro = 0;
string m_ExecQuery;
public:
inline const Result_t GetActiveResult()
{
if (m_ActiveResult == nullptr)
m_ActiveResult = m_Results.front();
return m_ActiveResult;
}
bool SetActiveResult(size_t result_idx)
{
if (result_idx < GetResultCount())
{
m_ActiveResult = m_Results.at(result_idx);
return true;
}
return false;
}
inline size_t GetResultCount()
{
return m_Results.size();
}
inline const Result_t GetResultByIndex(size_t idx)
{
return idx < GetResultCount() ? m_Results.at(idx) : nullptr;
}
inline my_ulonglong InsertId() const
{
return m_InsertId;
}
inline my_ulonglong AffectedRows() const
{
return m_AffectedRows;
}
inline unsigned int WarningCount() const
{
return m_WarningCount;
}
inline auto GetExecutionTime(TimeType type) const
{
if (type == TimeType::MILLISECONDS)
return m_ExecTimeMilli;
return m_ExecTimeMicro;
}
inline const string &GetExecutedQuery() const
{
return m_ExecQuery;
}
public: //factory function
static ResultSet_t Create(MYSQL *connection,
default_clock::duration &exec_time, string query_str);
};
class CResultSetManager : public CSingleton< CResultSetManager >
{
friend class CSingleton< CResultSetManager >;
private:
CResultSetManager() = default;
~CResultSetManager() = default;
private:
ResultSet_t m_ActiveResultSet;
unordered_map<ResultSetId_t, ResultSet_t> m_StoredResults;
public:
inline void SetActiveResultSet(ResultSet_t resultset)
{
m_ActiveResultSet = resultset;
}
inline ResultSet_t GetActiveResultSet()
{
return m_ActiveResultSet;
}
inline bool IsValidResultSet(ResultSetId_t id)
{
return m_StoredResults.find(id) != m_StoredResults.end();
}
ResultSetId_t StoreActiveResultSet();
bool DeleteResultSet(ResultSetId_t id);
inline ResultSet_t GetResultSet(ResultSetId_t id)
{
return IsValidResultSet(id) ? m_StoredResults.at(id) : nullptr;
}
};
<commit_msg>fix execution time compile warnings on Linux (2)<commit_after>#pragma once
#include "CSingleton.hpp"
#include <vector>
#include <string>
#include <unordered_map>
#include <tuple>
#include <boost/chrono.hpp>
using std::vector;
using std::string;
using std::unordered_map;
using default_clock = boost::chrono::steady_clock;
#include "types.hpp"
#include "mysql.hpp"
class CResult
{
friend class CResultSet;
public:
struct FieldInfo
{
string Name;
enum_field_types Type;
};
private: //constructor / destructor
CResult() = default;
~CResult();
private: //variables
unsigned int m_NumFields = 0;
my_ulonglong m_NumRows = 0;
char ***m_Data = nullptr;
vector<FieldInfo> m_Fields;
public: //functions
inline my_ulonglong GetRowCount() const
{
return m_NumRows;
}
inline unsigned int GetFieldCount() const
{
return m_NumFields;
}
bool GetFieldName(unsigned int idx, string &dest) const;
bool GetFieldType(unsigned int idx, enum_field_types &dest) const;
bool GetRowData(unsigned int row, unsigned int fieldidx, const char **dest) const;
inline bool GetRowData(unsigned int row, unsigned int fieldidx, string &dest) const
{
const char *cdest = nullptr;
bool result = GetRowData(row, fieldidx, &cdest);
if(result && cdest != nullptr)
dest = cdest;
return result;
}
bool GetRowDataByName(unsigned int row, const string &field, const char **dest) const;
bool GetRowDataByName(unsigned int row, const string &field, string &dest) const
{
const char *cdest = nullptr;
bool result = GetRowDataByName(row, field, &cdest);
if (result && cdest != nullptr)
dest = cdest;
return result;
}
};
class CResultSet
{
public:
enum class TimeType
{
MILLISECONDS,
MICROSECONDS,
};
private:
CResultSet() = default;
public:
~CResultSet();
private:
vector<Result_t> m_Results;
Result_t m_ActiveResult = nullptr;
my_ulonglong
m_InsertId = 0,
m_AffectedRows = 0;
unsigned int m_WarningCount = 0;
unsigned int
m_ExecTimeMilli = 0,
m_ExecTimeMicro = 0;
string m_ExecQuery;
public:
inline const Result_t GetActiveResult()
{
if (m_ActiveResult == nullptr)
m_ActiveResult = m_Results.front();
return m_ActiveResult;
}
bool SetActiveResult(size_t result_idx)
{
if (result_idx < GetResultCount())
{
m_ActiveResult = m_Results.at(result_idx);
return true;
}
return false;
}
inline size_t GetResultCount()
{
return m_Results.size();
}
inline const Result_t GetResultByIndex(size_t idx)
{
return idx < GetResultCount() ? m_Results.at(idx) : nullptr;
}
inline my_ulonglong InsertId() const
{
return m_InsertId;
}
inline my_ulonglong AffectedRows() const
{
return m_AffectedRows;
}
inline unsigned int WarningCount() const
{
return m_WarningCount;
}
inline unsigned int GetExecutionTime(TimeType type) const
{
if (type == TimeType::MILLISECONDS)
return m_ExecTimeMilli;
return m_ExecTimeMicro;
}
inline const string &GetExecutedQuery() const
{
return m_ExecQuery;
}
public: //factory function
static ResultSet_t Create(MYSQL *connection,
default_clock::duration &exec_time, string query_str);
};
class CResultSetManager : public CSingleton< CResultSetManager >
{
friend class CSingleton< CResultSetManager >;
private:
CResultSetManager() = default;
~CResultSetManager() = default;
private:
ResultSet_t m_ActiveResultSet;
unordered_map<ResultSetId_t, ResultSet_t> m_StoredResults;
public:
inline void SetActiveResultSet(ResultSet_t resultset)
{
m_ActiveResultSet = resultset;
}
inline ResultSet_t GetActiveResultSet()
{
return m_ActiveResultSet;
}
inline bool IsValidResultSet(ResultSetId_t id)
{
return m_StoredResults.find(id) != m_StoredResults.end();
}
ResultSetId_t StoreActiveResultSet();
bool DeleteResultSet(ResultSetId_t id);
inline ResultSet_t GetResultSet(ResultSetId_t id)
{
return IsValidResultSet(id) ? m_StoredResults.at(id) : nullptr;
}
};
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2019, Open Source Robotics Foundation, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, 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 <gmock/gmock.h>
#include <realtime_tools/realtime_server_goal_handle.h>
#include <actionlib/client/simple_action_client.h>
#include <actionlib/TwoIntsAction.h>
#include <chrono>
#include <functional>
#include <memory>
#include <mutex>
#include <thread>
using realtime_tools::RealtimeServerGoalHandle;
using TwoIntsActionClient = actionlib::SimpleActionClient<actionlib::TwoIntsAction>;
using TwoIntsActionServer = actionlib::ActionServer<actionlib::TwoIntsAction>;
const size_t ATTEMPTS = 10;
const std::chrono::milliseconds DELAY(250);
struct ActionCallback
{
using GoalHandle = TwoIntsActionServer::GoalHandle;
bool have_handle_ = false;
GoalHandle handle_;
std::mutex mtx_;
void goal_callback(GoalHandle handle)
{
std::unique_lock<std::mutex> lock(mtx_);
handle_ = handle;
handle_.setAccepted();
have_handle_ = true;
}
void cancel_callback(GoalHandle handle)
{
}
bool wait_for_handle()
{
for (size_t i = 0; i < ATTEMPTS; ++i)
{
ros::spinOnce();
std::this_thread::sleep_for(DELAY);
std::unique_lock<std::mutex> lock(mtx_);
if (have_handle_)
{
break;
}
}
std::unique_lock<std::mutex> lock(mtx_);
return have_handle_;
}
};
struct FeedbackCallback
{
bool have_feedback_ = false;
std::mutex mtx_;
using FeedbackConstPtr = TwoIntsActionServer::FeedbackConstPtr;
void feedback_callback(const FeedbackConstPtr &)
{
std::unique_lock<std::mutex> lock(mtx_);
have_feedback_ = true;
}
bool wait_for_feedback()
{
for (size_t i = 0; i < ATTEMPTS; ++i)
{
ros::spinOnce();
std::this_thread::sleep_for(DELAY);
std::unique_lock<std::mutex> lock(mtx_);
if (have_feedback_)
{
break;
}
}
std::unique_lock<std::mutex> lock(mtx_);
return have_feedback_;
}
};
std::shared_ptr<TwoIntsActionClient>
send_goal(
const std::string & server_name,
FeedbackCallback * cb = nullptr)
{
auto ac = std::make_shared<TwoIntsActionClient>(server_name, true);
for (size_t i = 0; i < ATTEMPTS && !ac->isServerConnected(); ++i)
{
ros::spinOnce();
std::this_thread::sleep_for(DELAY);
}
if (!ac->isServerConnected())
{
ac.reset();
} else {
actionlib::TwoIntsGoal goal;
goal.a = 2;
goal.b = 3;
ac->sendGoal(
goal,
TwoIntsActionClient::SimpleDoneCallback(),
TwoIntsActionClient::SimpleActiveCallback(),
std::bind(&FeedbackCallback::feedback_callback, cb, std::placeholders::_1));
}
return ac;
}
bool wait_for_result(std::shared_ptr<TwoIntsActionClient> ac)
{
for (int i = 0; i < ATTEMPTS; ++i)
{
ros::spinOnce();
if (ac->getState().isDone())
{
return true;
}
std::this_thread::sleep_for(DELAY);
}
return false;
}
std::shared_ptr<TwoIntsActionServer>
make_server(const std::string & server_name, ActionCallback & callbacks)
{
ros::NodeHandle nh;
auto as = std::make_shared<TwoIntsActionServer>(
nh, server_name,
std::bind(&ActionCallback::goal_callback, &callbacks, std::placeholders::_1),
std::bind(&ActionCallback::cancel_callback, &callbacks, std::placeholders::_1), false));
as->start();
return as;
}
TEST(RealtimeServerGoalHandle, set_aborted)
{
ActionCallback callbacks;
const std::string server_name("set_aborted");
auto as = make_server(server_name, callbacks);
auto client = send_goal(server_name);
ASSERT_NE(nullptr, client.get());
ASSERT_TRUE(callbacks.wait_for_handle());
RealtimeServerGoalHandle<actionlib::TwoIntsAction> rt_handle(callbacks.handle_);
ASSERT_TRUE(rt_handle.valid());
{
actionlib::TwoIntsResult::Ptr result(new actionlib::TwoIntsResult);
result->sum = 42;
rt_handle.setAborted(result);
rt_handle.runNonRealtime(ros::TimerEvent());
}
ASSERT_TRUE(wait_for_result(client));
auto state = client->getState();
EXPECT_EQ(state, actionlib::SimpleClientGoalState::ABORTED) << state.toString();
auto result = client->getResult();
ASSERT_NE(nullptr, result.get());
EXPECT_EQ(42, result->sum);
}
TEST(RealtimeServerGoalHandle, set_canceled)
{
ActionCallback callbacks;
const std::string server_name("set_canceled");
auto as = make_server(server_name, callbacks);
auto client = send_goal(server_name);
ASSERT_NE(nullptr, client.get());
ASSERT_TRUE(callbacks.wait_for_handle());
RealtimeServerGoalHandle<actionlib::TwoIntsAction> rt_handle(callbacks.handle_);
ASSERT_TRUE(rt_handle.valid());
// Cancel and wait for server to learn about that
client->cancelGoal();
for (size_t i = 0; i < ATTEMPTS; ++i)
{
actionlib_msgs::GoalStatus gs = callbacks.handle_.getGoalStatus();
if (gs.status == actionlib_msgs::GoalStatus::PREEMPTING) {
break;
}
ros::spinOnce();
std::this_thread::sleep_for(DELAY);
}
ASSERT_EQ(callbacks.handle_.getGoalStatus().status, actionlib_msgs::GoalStatus::PREEMPTING);
{
actionlib::TwoIntsResult::Ptr result(new actionlib::TwoIntsResult);
result->sum = 1234;
rt_handle.setCanceled(result);
rt_handle.runNonRealtime(ros::TimerEvent());
}
ASSERT_TRUE(wait_for_result(client));
auto state = client->getState();
EXPECT_EQ(state, actionlib::SimpleClientGoalState::PREEMPTED) << state.toString();
auto result = client->getResult();
ASSERT_NE(nullptr, result.get());
EXPECT_EQ(1234, result->sum);
}
TEST(RealtimeServerGoalHandle, set_succeeded)
{
ActionCallback callbacks;
const std::string server_name("set_succeeded");
auto as = make_server(server_name, callbacks);
auto client = send_goal(server_name);
ASSERT_NE(nullptr, client.get());
ASSERT_TRUE(callbacks.wait_for_handle());
RealtimeServerGoalHandle<actionlib::TwoIntsAction> rt_handle(callbacks.handle_);
ASSERT_TRUE(rt_handle.valid());
{
actionlib::TwoIntsResult::Ptr result(new actionlib::TwoIntsResult);
result->sum = 321;
rt_handle.setSucceeded(result);
rt_handle.runNonRealtime(ros::TimerEvent());
}
ASSERT_TRUE(wait_for_result(client));
auto state = client->getState();
EXPECT_EQ(state, actionlib::SimpleClientGoalState::SUCCEEDED) << state.toString();
auto result = client->getResult();
ASSERT_NE(nullptr, result.get());
EXPECT_EQ(321, result->sum);
}
TEST(RealtimeServerGoalHandle, send_feedback)
{
ActionCallback callbacks;
FeedbackCallback client_callbacks;
const std::string server_name("send_feedback");
auto as = make_server(server_name, callbacks);
auto client = send_goal(server_name, &client_callbacks);
ASSERT_NE(nullptr, client.get());
ASSERT_TRUE(callbacks.wait_for_handle());
RealtimeServerGoalHandle<actionlib::TwoIntsAction> rt_handle(callbacks.handle_);
ASSERT_TRUE(rt_handle.valid());
{
actionlib::TwoIntsFeedback::Ptr fb(new actionlib::TwoIntsFeedback());
rt_handle.setFeedback(fb);
rt_handle.runNonRealtime(ros::TimerEvent());
}
EXPECT_TRUE(client_callbacks.wait_for_feedback());
}
int main(int argc, char ** argv) {
::testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "realtime_server_goal_handle_tests");
return RUN_ALL_TESTS();
}
<commit_msg>Remove extra )<commit_after>/*
* Copyright (c) 2019, Open Source Robotics Foundation, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, 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 <gmock/gmock.h>
#include <realtime_tools/realtime_server_goal_handle.h>
#include <actionlib/client/simple_action_client.h>
#include <actionlib/TwoIntsAction.h>
#include <chrono>
#include <functional>
#include <memory>
#include <mutex>
#include <thread>
using realtime_tools::RealtimeServerGoalHandle;
using TwoIntsActionClient = actionlib::SimpleActionClient<actionlib::TwoIntsAction>;
using TwoIntsActionServer = actionlib::ActionServer<actionlib::TwoIntsAction>;
const size_t ATTEMPTS = 10;
const std::chrono::milliseconds DELAY(250);
struct ActionCallback
{
using GoalHandle = TwoIntsActionServer::GoalHandle;
bool have_handle_ = false;
GoalHandle handle_;
std::mutex mtx_;
void goal_callback(GoalHandle handle)
{
std::unique_lock<std::mutex> lock(mtx_);
handle_ = handle;
handle_.setAccepted();
have_handle_ = true;
}
void cancel_callback(GoalHandle handle)
{
}
bool wait_for_handle()
{
for (size_t i = 0; i < ATTEMPTS; ++i)
{
ros::spinOnce();
std::this_thread::sleep_for(DELAY);
std::unique_lock<std::mutex> lock(mtx_);
if (have_handle_)
{
break;
}
}
std::unique_lock<std::mutex> lock(mtx_);
return have_handle_;
}
};
struct FeedbackCallback
{
bool have_feedback_ = false;
std::mutex mtx_;
using FeedbackConstPtr = TwoIntsActionServer::FeedbackConstPtr;
void feedback_callback(const FeedbackConstPtr &)
{
std::unique_lock<std::mutex> lock(mtx_);
have_feedback_ = true;
}
bool wait_for_feedback()
{
for (size_t i = 0; i < ATTEMPTS; ++i)
{
ros::spinOnce();
std::this_thread::sleep_for(DELAY);
std::unique_lock<std::mutex> lock(mtx_);
if (have_feedback_)
{
break;
}
}
std::unique_lock<std::mutex> lock(mtx_);
return have_feedback_;
}
};
std::shared_ptr<TwoIntsActionClient>
send_goal(
const std::string & server_name,
FeedbackCallback * cb = nullptr)
{
auto ac = std::make_shared<TwoIntsActionClient>(server_name, true);
for (size_t i = 0; i < ATTEMPTS && !ac->isServerConnected(); ++i)
{
ros::spinOnce();
std::this_thread::sleep_for(DELAY);
}
if (!ac->isServerConnected())
{
ac.reset();
} else {
actionlib::TwoIntsGoal goal;
goal.a = 2;
goal.b = 3;
ac->sendGoal(
goal,
TwoIntsActionClient::SimpleDoneCallback(),
TwoIntsActionClient::SimpleActiveCallback(),
std::bind(&FeedbackCallback::feedback_callback, cb, std::placeholders::_1));
}
return ac;
}
bool wait_for_result(std::shared_ptr<TwoIntsActionClient> ac)
{
for (int i = 0; i < ATTEMPTS; ++i)
{
ros::spinOnce();
if (ac->getState().isDone())
{
return true;
}
std::this_thread::sleep_for(DELAY);
}
return false;
}
std::shared_ptr<TwoIntsActionServer>
make_server(const std::string & server_name, ActionCallback & callbacks)
{
ros::NodeHandle nh;
auto as = std::make_shared<TwoIntsActionServer>(
nh, server_name,
std::bind(&ActionCallback::goal_callback, &callbacks, std::placeholders::_1),
std::bind(&ActionCallback::cancel_callback, &callbacks, std::placeholders::_1), false);
as->start();
return as;
}
TEST(RealtimeServerGoalHandle, set_aborted)
{
ActionCallback callbacks;
const std::string server_name("set_aborted");
auto as = make_server(server_name, callbacks);
auto client = send_goal(server_name);
ASSERT_NE(nullptr, client.get());
ASSERT_TRUE(callbacks.wait_for_handle());
RealtimeServerGoalHandle<actionlib::TwoIntsAction> rt_handle(callbacks.handle_);
ASSERT_TRUE(rt_handle.valid());
{
actionlib::TwoIntsResult::Ptr result(new actionlib::TwoIntsResult);
result->sum = 42;
rt_handle.setAborted(result);
rt_handle.runNonRealtime(ros::TimerEvent());
}
ASSERT_TRUE(wait_for_result(client));
auto state = client->getState();
EXPECT_EQ(state, actionlib::SimpleClientGoalState::ABORTED) << state.toString();
auto result = client->getResult();
ASSERT_NE(nullptr, result.get());
EXPECT_EQ(42, result->sum);
}
TEST(RealtimeServerGoalHandle, set_canceled)
{
ActionCallback callbacks;
const std::string server_name("set_canceled");
auto as = make_server(server_name, callbacks);
auto client = send_goal(server_name);
ASSERT_NE(nullptr, client.get());
ASSERT_TRUE(callbacks.wait_for_handle());
RealtimeServerGoalHandle<actionlib::TwoIntsAction> rt_handle(callbacks.handle_);
ASSERT_TRUE(rt_handle.valid());
// Cancel and wait for server to learn about that
client->cancelGoal();
for (size_t i = 0; i < ATTEMPTS; ++i)
{
actionlib_msgs::GoalStatus gs = callbacks.handle_.getGoalStatus();
if (gs.status == actionlib_msgs::GoalStatus::PREEMPTING) {
break;
}
ros::spinOnce();
std::this_thread::sleep_for(DELAY);
}
ASSERT_EQ(callbacks.handle_.getGoalStatus().status, actionlib_msgs::GoalStatus::PREEMPTING);
{
actionlib::TwoIntsResult::Ptr result(new actionlib::TwoIntsResult);
result->sum = 1234;
rt_handle.setCanceled(result);
rt_handle.runNonRealtime(ros::TimerEvent());
}
ASSERT_TRUE(wait_for_result(client));
auto state = client->getState();
EXPECT_EQ(state, actionlib::SimpleClientGoalState::PREEMPTED) << state.toString();
auto result = client->getResult();
ASSERT_NE(nullptr, result.get());
EXPECT_EQ(1234, result->sum);
}
TEST(RealtimeServerGoalHandle, set_succeeded)
{
ActionCallback callbacks;
const std::string server_name("set_succeeded");
auto as = make_server(server_name, callbacks);
auto client = send_goal(server_name);
ASSERT_NE(nullptr, client.get());
ASSERT_TRUE(callbacks.wait_for_handle());
RealtimeServerGoalHandle<actionlib::TwoIntsAction> rt_handle(callbacks.handle_);
ASSERT_TRUE(rt_handle.valid());
{
actionlib::TwoIntsResult::Ptr result(new actionlib::TwoIntsResult);
result->sum = 321;
rt_handle.setSucceeded(result);
rt_handle.runNonRealtime(ros::TimerEvent());
}
ASSERT_TRUE(wait_for_result(client));
auto state = client->getState();
EXPECT_EQ(state, actionlib::SimpleClientGoalState::SUCCEEDED) << state.toString();
auto result = client->getResult();
ASSERT_NE(nullptr, result.get());
EXPECT_EQ(321, result->sum);
}
TEST(RealtimeServerGoalHandle, send_feedback)
{
ActionCallback callbacks;
FeedbackCallback client_callbacks;
const std::string server_name("send_feedback");
auto as = make_server(server_name, callbacks);
auto client = send_goal(server_name, &client_callbacks);
ASSERT_NE(nullptr, client.get());
ASSERT_TRUE(callbacks.wait_for_handle());
RealtimeServerGoalHandle<actionlib::TwoIntsAction> rt_handle(callbacks.handle_);
ASSERT_TRUE(rt_handle.valid());
{
actionlib::TwoIntsFeedback::Ptr fb(new actionlib::TwoIntsFeedback());
rt_handle.setFeedback(fb);
rt_handle.runNonRealtime(ros::TimerEvent());
}
EXPECT_TRUE(client_callbacks.wait_for_feedback());
}
int main(int argc, char ** argv) {
::testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "realtime_server_goal_handle_tests");
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>#include <tiramisu/tiramisu.h>
#include "benchmarks.h"
#include "math.h"
using namespace tiramisu;
/***
Benchmark for the BLAS NRM2
out = sqrt(x*'x)
where :
x : is a size N vector
x': is the transpose of x
out : is a scalar
***/
int main(int argc, char **argv)
{
tiramisu::init("nrm2");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
constant NN("N", expr(N));
//Iteration variable
var i("i", 0, NN);
//Input
input x("x", {"i"}, {NN}, p_float64);
//Computations
computation S_init("S_init", {}, expr(cast(p_float64, 0)));
computation S("S", {i}, p_float64);
computation result("result", {}, p_float64);
S.set_expression(S(i-1) + x(i ) * x(i));
result.set_expression(cast(p_float64, expr(o_sqrt, S(NN), p_float64)));
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
S.after(S_init, {});
result.after(S, computation::root);
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
//Input Buffer
buffer b_x("b_x", {expr(NN)}, p_float64, a_input);
//Output Buffer
buffer b_result("b_result", {expr(1)}, p_float64, a_output);
//Store input
x.store_in(&b_x);
//Store computations
S_init.store_in(&b_result, {});
S.store_in(&b_result, {});
result.store_in(&b_result, {});
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
tiramisu::codegen({&b_x, &b_result}, "generated_nrm2.o");
return 0;
}
<commit_msg>Fix code style<commit_after>#include <tiramisu/tiramisu.h>
#include "benchmarks.h"
#include "math.h"
using namespace tiramisu;
/***
Benchmark for BLAS NRM2 :
out = sqrt(x*'x)
where :
x : is a size N vector
'x : is the transpose of x
***/
int main(int argc, char **argv)
{
tiramisu::init("nrm2");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
constant NN("N", expr(N));
//Iteration variable
var i("i", 0, NN);
//Input
input x("x", {"i"}, {NN}, p_float64);
//Computations
computation S_init("S_init", {}, expr(cast(p_float64, 0)));
computation S("S", {i}, p_float64);
computation result("result", {}, p_float64);
S.set_expression(S(i-1) + x(i) * x(i));
result.set_expression(cast(p_float64, expr(o_sqrt, S(NN), p_float64)));
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
S.after(S_init, {});
result.after(S, computation::root);
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
//Input Buffer
buffer b_x("b_x", {expr(NN)}, p_float64, a_input);
//Output Buffer
buffer b_result("b_result", {expr(1)}, p_float64, a_output);
//Store input
x.store_in(&b_x);
//Store computations
S_init.store_in(&b_result, {});
S.store_in(&b_result, {});
result.store_in(&b_result, {});
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
tiramisu::codegen({&b_x, &b_result}, "generated_nrm2.o");
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: moduleacceleratorconfiguration.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2004-11-17 14:58:05 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef __FRAMEWORK_ACCELERATORS_MODULEACCELERATORCONFIGURATION_HXX_
#include <accelerators/moduleacceleratorconfiguration.hxx>
#endif
//_______________________________________________
// own includes
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
#ifndef __FRAMEWORK_ACCELERATORCONST_H_
#include <acceleratorconst.h>
#endif
#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif
//_______________________________________________
// interface includes
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif
//_______________________________________________
// other includes
#ifndef _COMPHELPER_SEQUENCEASHASHMAP_HXX
#include <comphelper/sequenceashashmap.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
//_______________________________________________
// const
namespace framework
{
//-----------------------------------------------
// XInterface, XTypeProvider, XServiceInfo
DEFINE_XINTERFACE_2(ModuleAcceleratorConfiguration ,
AcceleratorConfiguration ,
DIRECT_INTERFACE(css::lang::XServiceInfo) ,
DIRECT_INTERFACE(css::lang::XInitialization))
DEFINE_XTYPEPROVIDER_2_WITH_BASECLASS(ModuleAcceleratorConfiguration,
AcceleratorConfiguration ,
css::lang::XServiceInfo ,
css::lang::XInitialization )
DEFINE_XSERVICEINFO_MULTISERVICE(ModuleAcceleratorConfiguration ,
::cppu::OWeakObject ,
SERVICENAME_MODULEACCELERATORCONFIGURATION ,
IMPLEMENTATIONNAME_MODULEACCELERATORCONFIGURATION)
DEFINE_INIT_SERVICE(ModuleAcceleratorConfiguration,
{
/*Attention
I think we don't need any mutex or lock here ... because we are called by our own static method impl_createInstance()
to create a new instance of this class by our own supported service factory.
see macro DEFINE_XSERVICEINFO_MULTISERVICE and "impl_initService()" for further informations!
*/
}
)
//-----------------------------------------------
ModuleAcceleratorConfiguration::ModuleAcceleratorConfiguration(const css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR)
: AcceleratorConfiguration(xSMGR)
{
}
//-----------------------------------------------
ModuleAcceleratorConfiguration::~ModuleAcceleratorConfiguration()
{
m_aPresetHandler.removeStorageListener(this);
}
//-----------------------------------------------
void SAL_CALL ModuleAcceleratorConfiguration::initialize(const css::uno::Sequence< css::uno::Any >& lArguments)
throw(css::uno::Exception ,
css::uno::RuntimeException)
{
// SAFE -> ----------------------------------
WriteGuard aWriteLock(m_aLock);
::comphelper::SequenceAsHashMap lArgs(lArguments);
m_sModule = lArgs.getUnpackedValueOrDefault(::rtl::OUString::createFromAscii("ModuleIdentifier"), ::rtl::OUString());
if (!m_sModule.getLength())
throw css::uno::RuntimeException(
::rtl::OUString::createFromAscii("The module dependend accelerator configuration service was initialized with an empty module identifier!"),
static_cast< ::cppu::OWeakObject* >(this));
aWriteLock.unlock();
// <- SAFE ----------------------------------
impl_ts_fillCache();
}
//-----------------------------------------------
void ModuleAcceleratorConfiguration::impl_ts_fillCache()
{
// SAFE -> ----------------------------------
ReadGuard aReadLock(m_aLock);
::rtl::OUString sModule = m_sModule;
aReadLock.unlock();
// <- SAFE ----------------------------------
// get current office locale ... but dont cache it.
// Otherwise we must be listener on the configuration layer
// which seems to superflous for this small implementation .-)
::comphelper::Locale aLocale = impl_ts_getLocale();
// May be the current app module does not have any
// accelerator config? Handle it gracefully :-)
try
{
// Note: The used preset class is threadsafe by itself ... and live if we live!
// We do not need any mutex here.
// open the folder, where the configuration exists
m_aPresetHandler.connectToResource(
PresetHandler::E_MODULES,
PresetHandler::RESOURCETYPE_ACCELERATOR(),
sModule,
css::uno::Reference< css::embed::XStorage >(),
aLocale);
// check if the user already has a current configuration
// if not - se the default preset as new current one.
// means: copy "share/default.xml" => "user/current.xml"
if (!m_aPresetHandler.existsTarget(PresetHandler::TARGET_CURRENT()))
m_aPresetHandler.copyPresetToTarget(PresetHandler::PRESET_DEFAULT(), PresetHandler::TARGET_CURRENT());
AcceleratorConfiguration::reload();
m_aPresetHandler.addStorageListener(this);
}
catch(const css::uno::RuntimeException& exRun)
{ throw exRun; }
catch(const css::uno::Exception&)
{}
}
} // namespace framework
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.190); FILE MERGED 2005/09/05 13:05:57 rt 1.4.190.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: moduleacceleratorconfiguration.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 01:04:48 $
*
* 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 __FRAMEWORK_ACCELERATORS_MODULEACCELERATORCONFIGURATION_HXX_
#include <accelerators/moduleacceleratorconfiguration.hxx>
#endif
//_______________________________________________
// own includes
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
#ifndef __FRAMEWORK_ACCELERATORCONST_H_
#include <acceleratorconst.h>
#endif
#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif
//_______________________________________________
// interface includes
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif
//_______________________________________________
// other includes
#ifndef _COMPHELPER_SEQUENCEASHASHMAP_HXX
#include <comphelper/sequenceashashmap.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
//_______________________________________________
// const
namespace framework
{
//-----------------------------------------------
// XInterface, XTypeProvider, XServiceInfo
DEFINE_XINTERFACE_2(ModuleAcceleratorConfiguration ,
AcceleratorConfiguration ,
DIRECT_INTERFACE(css::lang::XServiceInfo) ,
DIRECT_INTERFACE(css::lang::XInitialization))
DEFINE_XTYPEPROVIDER_2_WITH_BASECLASS(ModuleAcceleratorConfiguration,
AcceleratorConfiguration ,
css::lang::XServiceInfo ,
css::lang::XInitialization )
DEFINE_XSERVICEINFO_MULTISERVICE(ModuleAcceleratorConfiguration ,
::cppu::OWeakObject ,
SERVICENAME_MODULEACCELERATORCONFIGURATION ,
IMPLEMENTATIONNAME_MODULEACCELERATORCONFIGURATION)
DEFINE_INIT_SERVICE(ModuleAcceleratorConfiguration,
{
/*Attention
I think we don't need any mutex or lock here ... because we are called by our own static method impl_createInstance()
to create a new instance of this class by our own supported service factory.
see macro DEFINE_XSERVICEINFO_MULTISERVICE and "impl_initService()" for further informations!
*/
}
)
//-----------------------------------------------
ModuleAcceleratorConfiguration::ModuleAcceleratorConfiguration(const css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR)
: AcceleratorConfiguration(xSMGR)
{
}
//-----------------------------------------------
ModuleAcceleratorConfiguration::~ModuleAcceleratorConfiguration()
{
m_aPresetHandler.removeStorageListener(this);
}
//-----------------------------------------------
void SAL_CALL ModuleAcceleratorConfiguration::initialize(const css::uno::Sequence< css::uno::Any >& lArguments)
throw(css::uno::Exception ,
css::uno::RuntimeException)
{
// SAFE -> ----------------------------------
WriteGuard aWriteLock(m_aLock);
::comphelper::SequenceAsHashMap lArgs(lArguments);
m_sModule = lArgs.getUnpackedValueOrDefault(::rtl::OUString::createFromAscii("ModuleIdentifier"), ::rtl::OUString());
if (!m_sModule.getLength())
throw css::uno::RuntimeException(
::rtl::OUString::createFromAscii("The module dependend accelerator configuration service was initialized with an empty module identifier!"),
static_cast< ::cppu::OWeakObject* >(this));
aWriteLock.unlock();
// <- SAFE ----------------------------------
impl_ts_fillCache();
}
//-----------------------------------------------
void ModuleAcceleratorConfiguration::impl_ts_fillCache()
{
// SAFE -> ----------------------------------
ReadGuard aReadLock(m_aLock);
::rtl::OUString sModule = m_sModule;
aReadLock.unlock();
// <- SAFE ----------------------------------
// get current office locale ... but dont cache it.
// Otherwise we must be listener on the configuration layer
// which seems to superflous for this small implementation .-)
::comphelper::Locale aLocale = impl_ts_getLocale();
// May be the current app module does not have any
// accelerator config? Handle it gracefully :-)
try
{
// Note: The used preset class is threadsafe by itself ... and live if we live!
// We do not need any mutex here.
// open the folder, where the configuration exists
m_aPresetHandler.connectToResource(
PresetHandler::E_MODULES,
PresetHandler::RESOURCETYPE_ACCELERATOR(),
sModule,
css::uno::Reference< css::embed::XStorage >(),
aLocale);
// check if the user already has a current configuration
// if not - se the default preset as new current one.
// means: copy "share/default.xml" => "user/current.xml"
if (!m_aPresetHandler.existsTarget(PresetHandler::TARGET_CURRENT()))
m_aPresetHandler.copyPresetToTarget(PresetHandler::PRESET_DEFAULT(), PresetHandler::TARGET_CURRENT());
AcceleratorConfiguration::reload();
m_aPresetHandler.addStorageListener(this);
}
catch(const css::uno::RuntimeException& exRun)
{ throw exRun; }
catch(const css::uno::Exception&)
{}
}
} // namespace framework
<|endoftext|>
|
<commit_before>#include "pch.h"
#include "ChakraHost.h"
#include "JsStringify.h"
#include "SerializedSourceContext.h"
void ThrowException(const wchar_t* szException)
{
// We ignore error since we're already in an error state.
JsValueRef errorValue;
JsValueRef errorObject;
JsPointerToString(szException, wcslen(szException), &errorValue);
JsCreateError(errorValue, &errorObject);
JsSetException(errorObject);
}
JsErrorCode DefineHostCallback(JsValueRef globalObject, const wchar_t *callbackName, JsNativeFunction callback, void *callbackState)
{
JsPropertyIdRef propertyId;
IfFailRet(JsGetPropertyIdFromName(callbackName, &propertyId));
JsValueRef function;
IfFailRet(JsCreateFunction(callback, callbackState, &function));
IfFailRet(JsSetProperty(globalObject, propertyId, function, true));
return JsNoError;
}
JsValueRef InvokeConsole(const wchar_t* kind, JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
{
#ifdef _DEBUG
wchar_t buff[56];
swprintf(buff, 56, L"[JS {%s}] ", kind);
OutputDebugStringW(buff);
// First argument is this-context, ignore...
for (USHORT i = 1; i < argumentCount; i++)
{
std::set<JsValueRef> values;
IfFailThrow(StringifyJsValue(arguments[i], 0, values), L"Failed to convert object to string");
OutputDebugStringW(L" ");
}
OutputDebugStringW(L"\n");
#endif
return JS_INVALID_REFERENCE;
};
JsValueRef CALLBACK ConsoleLog(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
{
return InvokeConsole(L"log", callee, isConstructCall, arguments, argumentCount, callbackState);
}
JsValueRef CALLBACK ConsoleWarn(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
{
return InvokeConsole(L"warn", callee, isConstructCall, arguments, argumentCount, callbackState);
}
JsValueRef CALLBACK ConsoleInfo(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
{
return InvokeConsole(L"info", callee, isConstructCall, arguments, argumentCount, callbackState);
}
JsValueRef CALLBACK ConsoleError(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
{
return InvokeConsole(L"error", callee, isConstructCall, arguments, argumentCount, callbackState);
}
JsErrorCode LoadByteCode(const wchar_t* szPath, BYTE** pData, HANDLE* hFile, HANDLE* hMap)
{
*pData = nullptr;
*hFile = CreateFile2(szPath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, OPEN_EXISTING, nullptr);
if (*hFile == INVALID_HANDLE_VALUE)
{
return JsErrorFatal;
}
*hMap = CreateFileMapping(*hFile, nullptr, PAGE_READWRITE | SEC_RESERVE, 0, 0, L"ReactNativeMapping");
if (*hMap == NULL)
{
CloseHandle(*hFile);
return JsErrorFatal;
}
*pData = (BYTE*)MapViewOfFile(*hMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
if (*pData == NULL)
{
CloseHandle(*hMap);
CloseHandle(*hFile);
return JsErrorFatal;
}
return JsNoError;
}
JsErrorCode LoadFileContents(const wchar_t* szPath, wchar_t** pszData)
{
FILE *file;
*pszData = nullptr;
if (_wfopen_s(&file, szPath, L"rb"))
{
return JsErrorInvalidArgument;
}
unsigned int current = ftell(file);
fseek(file, 0, SEEK_END);
unsigned int end = ftell(file);
fseek(file, current, SEEK_SET);
unsigned int lengthBytes = end - current;
char *rawBytes = (char *)calloc(lengthBytes + 1, sizeof(char));
if (rawBytes == nullptr)
{
return JsErrorFatal;
}
fread(rawBytes, sizeof(char), lengthBytes, file);
if (fclose(file))
{
return JsErrorFatal;
}
*pszData = (wchar_t *)calloc(lengthBytes + 1, sizeof(wchar_t));
if (*pszData == nullptr)
{
free(rawBytes);
return JsErrorFatal;
}
if (MultiByteToWideChar(CP_UTF8, 0, rawBytes, lengthBytes + 1, *pszData, lengthBytes + 1) == 0)
{
free(*pszData);
free(rawBytes);
return JsErrorFatal;
}
return JsNoError;
}
bool CompareLastWrite(const wchar_t* szPath1, const wchar_t* szPath2)
{
HANDLE hPath1, hPath2;
FILETIME ftPath1Create, ftPath1Access, ftPath1Write;
FILETIME ftPath2Create, ftPath2Access, ftPath2Write;
hPath1 = CreateFile2(szPath1, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr);
if (hPath1 == INVALID_HANDLE_VALUE && GetLastError() == ERROR_FILE_NOT_FOUND) {
return false;
}
hPath2 = CreateFile2(szPath2, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr);
GetFileTime(hPath1, &ftPath1Create, &ftPath1Access, &ftPath1Write);
GetFileTime(hPath2, &ftPath2Create, &ftPath2Access, &ftPath2Write);
CloseHandle(hPath1);
CloseHandle(hPath2);
return CompareFileTime(&ftPath1Write, &ftPath2Write) == 1;
}
bool CALLBACK LoadSourceCallback(JsSourceContext sourceContext, const wchar_t** scriptBuffer)
{
SerializedSourceContext* context = (SerializedSourceContext*)sourceContext;
*scriptBuffer = context->scriptBuffer;
return true;
}
void CALLBACK UnloadSourceCallback(JsSourceContext sourceContext)
{
SerializedSourceContext* context = (SerializedSourceContext*)sourceContext;
delete context;
}
JsErrorCode ChakraHost::RunSerializedScript(const wchar_t* szPath, const wchar_t* szSerializedPath, const wchar_t* szSourceUri, JsValueRef* result)
{
HANDLE hFile = NULL;
HANDLE hMap = NULL;
JsErrorCode status = JsNoError;
ULONG bufferSize = 0L;
BYTE* buffer = nullptr;
wchar_t* szScriptBuffer = nullptr;
IfFailRet(LoadFileContents(szPath, &szScriptBuffer));
if (!CompareLastWrite(szSerializedPath, szPath))
{
IfFailRet(JsSerializeScript(szScriptBuffer, buffer, &bufferSize));
buffer = new BYTE[bufferSize];
IfFailRet(JsSerializeScript(szScriptBuffer, buffer, &bufferSize));
FILE* file;
_wfopen_s(&file, szSerializedPath, L"wb");
fwrite(buffer, sizeof(BYTE), bufferSize, file);
fclose(file);
}
else
{
IfFailRet(LoadByteCode(szSerializedPath, &buffer, &hFile, &hMap));
}
SerializedSourceContext* context = new SerializedSourceContext();
context->byteBuffer = buffer;
context->scriptBuffer = szScriptBuffer;
context->fileHandle = hFile;
context->mapHandle = hMap;
IfFailRet(JsRunSerializedScriptWithCallback(&LoadSourceCallback, &UnloadSourceCallback, buffer, (JsSourceContext)context, szSourceUri, result));
return status;
}
JsErrorCode ChakraHost::RunScript(const wchar_t* szFileName, const wchar_t* szSourceUri, JsValueRef* result)
{
wchar_t* contents = nullptr;
IfFailRet(LoadFileContents(szFileName, &contents));
JsErrorCode status = JsRunScript(contents, currentSourceContext++, szSourceUri, result);
free(contents);
return status;
}
JsErrorCode ChakraHost::JsonStringify(JsValueRef argument, JsValueRef* result)
{
JsValueRef args[2] = { globalObject, argument };
IfFailRet(JsCallFunction(jsonStringifyObject, args, 2, result));
return JsNoError;
}
JsErrorCode ChakraHost::JsonParse(JsValueRef argument, JsValueRef* result)
{
JsValueRef args[2] = { globalObject, argument };
IfFailRet(JsCallFunction(jsonParseObject, args, 2, result));
return JsNoError;
}
JsErrorCode ChakraHost::GetGlobalVariable(const wchar_t* szPropertyName, JsValueRef* result)
{
JsPropertyIdRef globalVarId;
IfFailRet(JsGetPropertyIdFromName(szPropertyName, &globalVarId));
IfFailRet(JsGetProperty(globalObject, globalVarId, result));
return JsNoError;
}
JsErrorCode ChakraHost::SetGlobalVariable(const wchar_t* szPropertyName, JsValueRef value)
{
JsPropertyIdRef globalVarId;
IfFailRet(JsGetPropertyIdFromName(szPropertyName, &globalVarId));
IfFailRet(JsSetProperty(globalObject, globalVarId, value, true));
return JsNoError;
}
JsErrorCode ChakraHost::InitJson()
{
JsPropertyIdRef jsonPropertyId;
IfFailRet(JsGetPropertyIdFromName(L"JSON", &jsonPropertyId));
JsValueRef jsonObject;
IfFailRet(JsGetProperty(globalObject, jsonPropertyId, &jsonObject));
JsPropertyIdRef jsonParseId;
IfFailRet(JsGetPropertyIdFromName(L"parse", &jsonParseId));
IfFailRet(JsGetProperty(jsonObject, jsonParseId, &jsonParseObject));
JsPropertyIdRef jsonStringifyId;
IfFailRet(JsGetPropertyIdFromName(L"stringify", &jsonStringifyId));
IfFailRet(JsGetProperty(jsonObject, jsonStringifyId, &jsonStringifyObject));
return JsNoError;
}
JsErrorCode ChakraHost::InitConsole()
{
JsPropertyIdRef consolePropertyId;
IfFailRet(JsGetPropertyIdFromName(L"console", &consolePropertyId));
JsValueRef consoleObject;
IfFailRet(JsCreateObject(&consoleObject));
IfFailRet(JsSetProperty(globalObject, consolePropertyId, consoleObject, true));
IfFailRet(DefineHostCallback(consoleObject, L"info", ConsoleInfo, nullptr));
IfFailRet(DefineHostCallback(consoleObject, L"log", ConsoleLog, nullptr));
IfFailRet(DefineHostCallback(consoleObject, L"warn", ConsoleWarn, nullptr));
IfFailRet(DefineHostCallback(consoleObject, L"error", ConsoleError, nullptr));
return JsNoError;
}
JsErrorCode ChakraHost::Init()
{
currentSourceContext = 0;
IfFailRet(JsCreateRuntime(JsRuntimeAttributeNone, nullptr, &runtime));
IfFailRet(JsCreateContext(runtime, &context));
IfFailRet(JsSetCurrentContext(context));
IfFailRet(JsGetGlobalObject(&globalObject));
IfFailRet(InitJson());
IfFailRet(InitConsole());
return JsNoError;
}
JsErrorCode ChakraHost::Destroy()
{
IfFailRet(JsSetCurrentContext(JS_INVALID_REFERENCE));
IfFailRet(JsDisposeRuntime(runtime));
return JsNoError;
}
<commit_msg>fix(ChakraBridge): fixing NativeJavaScriptExecutor to use nativeLoggingCallback (#1015)<commit_after>#include "pch.h"
#include "ChakraHost.h"
#include "JsStringify.h"
#include "SerializedSourceContext.h"
void ThrowException(const wchar_t* szException)
{
// We ignore error since we're already in an error state.
JsValueRef errorValue;
JsValueRef errorObject;
JsPointerToString(szException, wcslen(szException), &errorValue);
JsCreateError(errorValue, &errorObject);
JsSetException(errorObject);
}
JsErrorCode DefineHostCallback(JsValueRef globalObject, const wchar_t *callbackName, JsNativeFunction callback, void *callbackState)
{
JsPropertyIdRef propertyId;
IfFailRet(JsGetPropertyIdFromName(callbackName, &propertyId));
JsValueRef function;
IfFailRet(JsCreateFunction(callback, callbackState, &function));
IfFailRet(JsSetProperty(globalObject, propertyId, function, true));
return JsNoError;
}
wchar_t* LogLevel(int logLevel)
{
switch (logLevel)
{
case 0:
return L"Trace";
case 1:
return L"Info";
case 2:
return L"Warn";
case 3:
return L"Error";
default:
return L"Log";
}
}
JsValueRef CALLBACK NativeLoggingCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
{
#ifdef _DEBUG
wchar_t buff[56];
double logLevelIndex;
JsNumberToDouble(arguments[2], &logLevelIndex);
swprintf(buff, 56, L"[JS %s] ", LogLevel((int)logLevelIndex));
OutputDebugStringW(buff);
StringifyJsString(arguments[1]);
OutputDebugStringW(L"\n");
#endif
return JS_INVALID_REFERENCE;
}
JsErrorCode LoadByteCode(const wchar_t* szPath, BYTE** pData, HANDLE* hFile, HANDLE* hMap)
{
*pData = nullptr;
*hFile = CreateFile2(szPath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, OPEN_EXISTING, nullptr);
if (*hFile == INVALID_HANDLE_VALUE)
{
return JsErrorFatal;
}
*hMap = CreateFileMapping(*hFile, nullptr, PAGE_READWRITE | SEC_RESERVE, 0, 0, L"ReactNativeMapping");
if (*hMap == NULL)
{
CloseHandle(*hFile);
return JsErrorFatal;
}
*pData = (BYTE*)MapViewOfFile(*hMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
if (*pData == NULL)
{
CloseHandle(*hMap);
CloseHandle(*hFile);
return JsErrorFatal;
}
return JsNoError;
}
JsErrorCode LoadFileContents(const wchar_t* szPath, wchar_t** pszData)
{
FILE *file;
*pszData = nullptr;
if (_wfopen_s(&file, szPath, L"rb"))
{
return JsErrorInvalidArgument;
}
unsigned int current = ftell(file);
fseek(file, 0, SEEK_END);
unsigned int end = ftell(file);
fseek(file, current, SEEK_SET);
unsigned int lengthBytes = end - current;
char *rawBytes = (char *)calloc(lengthBytes + 1, sizeof(char));
if (rawBytes == nullptr)
{
return JsErrorFatal;
}
fread(rawBytes, sizeof(char), lengthBytes, file);
if (fclose(file))
{
return JsErrorFatal;
}
*pszData = (wchar_t *)calloc(lengthBytes + 1, sizeof(wchar_t));
if (*pszData == nullptr)
{
free(rawBytes);
return JsErrorFatal;
}
if (MultiByteToWideChar(CP_UTF8, 0, rawBytes, lengthBytes + 1, *pszData, lengthBytes + 1) == 0)
{
free(*pszData);
free(rawBytes);
return JsErrorFatal;
}
return JsNoError;
}
bool CompareLastWrite(const wchar_t* szPath1, const wchar_t* szPath2)
{
HANDLE hPath1, hPath2;
FILETIME ftPath1Create, ftPath1Access, ftPath1Write;
FILETIME ftPath2Create, ftPath2Access, ftPath2Write;
hPath1 = CreateFile2(szPath1, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr);
if (hPath1 == INVALID_HANDLE_VALUE && GetLastError() == ERROR_FILE_NOT_FOUND) {
return false;
}
hPath2 = CreateFile2(szPath2, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr);
GetFileTime(hPath1, &ftPath1Create, &ftPath1Access, &ftPath1Write);
GetFileTime(hPath2, &ftPath2Create, &ftPath2Access, &ftPath2Write);
CloseHandle(hPath1);
CloseHandle(hPath2);
return CompareFileTime(&ftPath1Write, &ftPath2Write) == 1;
}
bool CALLBACK LoadSourceCallback(JsSourceContext sourceContext, const wchar_t** scriptBuffer)
{
SerializedSourceContext* context = (SerializedSourceContext*)sourceContext;
*scriptBuffer = context->scriptBuffer;
return true;
}
void CALLBACK UnloadSourceCallback(JsSourceContext sourceContext)
{
SerializedSourceContext* context = (SerializedSourceContext*)sourceContext;
delete context;
}
JsErrorCode ChakraHost::RunSerializedScript(const wchar_t* szPath, const wchar_t* szSerializedPath, const wchar_t* szSourceUri, JsValueRef* result)
{
HANDLE hFile = NULL;
HANDLE hMap = NULL;
JsErrorCode status = JsNoError;
ULONG bufferSize = 0L;
BYTE* buffer = nullptr;
wchar_t* szScriptBuffer = nullptr;
IfFailRet(LoadFileContents(szPath, &szScriptBuffer));
if (!CompareLastWrite(szSerializedPath, szPath))
{
IfFailRet(JsSerializeScript(szScriptBuffer, buffer, &bufferSize));
buffer = new BYTE[bufferSize];
IfFailRet(JsSerializeScript(szScriptBuffer, buffer, &bufferSize));
FILE* file;
_wfopen_s(&file, szSerializedPath, L"wb");
fwrite(buffer, sizeof(BYTE), bufferSize, file);
fclose(file);
}
else
{
IfFailRet(LoadByteCode(szSerializedPath, &buffer, &hFile, &hMap));
}
SerializedSourceContext* context = new SerializedSourceContext();
context->byteBuffer = buffer;
context->scriptBuffer = szScriptBuffer;
context->fileHandle = hFile;
context->mapHandle = hMap;
IfFailRet(JsRunSerializedScriptWithCallback(&LoadSourceCallback, &UnloadSourceCallback, buffer, (JsSourceContext)context, szSourceUri, result));
return status;
}
JsErrorCode ChakraHost::RunScript(const wchar_t* szFileName, const wchar_t* szSourceUri, JsValueRef* result)
{
wchar_t* contents = nullptr;
IfFailRet(LoadFileContents(szFileName, &contents));
JsErrorCode status = JsRunScript(contents, currentSourceContext++, szSourceUri, result);
free(contents);
return status;
}
JsErrorCode ChakraHost::JsonStringify(JsValueRef argument, JsValueRef* result)
{
JsValueRef args[2] = { globalObject, argument };
IfFailRet(JsCallFunction(jsonStringifyObject, args, 2, result));
return JsNoError;
}
JsErrorCode ChakraHost::JsonParse(JsValueRef argument, JsValueRef* result)
{
JsValueRef args[2] = { globalObject, argument };
IfFailRet(JsCallFunction(jsonParseObject, args, 2, result));
return JsNoError;
}
JsErrorCode ChakraHost::GetGlobalVariable(const wchar_t* szPropertyName, JsValueRef* result)
{
JsPropertyIdRef globalVarId;
IfFailRet(JsGetPropertyIdFromName(szPropertyName, &globalVarId));
IfFailRet(JsGetProperty(globalObject, globalVarId, result));
return JsNoError;
}
JsErrorCode ChakraHost::SetGlobalVariable(const wchar_t* szPropertyName, JsValueRef value)
{
JsPropertyIdRef globalVarId;
IfFailRet(JsGetPropertyIdFromName(szPropertyName, &globalVarId));
IfFailRet(JsSetProperty(globalObject, globalVarId, value, true));
return JsNoError;
}
JsErrorCode ChakraHost::InitJson()
{
JsPropertyIdRef jsonPropertyId;
IfFailRet(JsGetPropertyIdFromName(L"JSON", &jsonPropertyId));
JsValueRef jsonObject;
IfFailRet(JsGetProperty(globalObject, jsonPropertyId, &jsonObject));
JsPropertyIdRef jsonParseId;
IfFailRet(JsGetPropertyIdFromName(L"parse", &jsonParseId));
IfFailRet(JsGetProperty(jsonObject, jsonParseId, &jsonParseObject));
JsPropertyIdRef jsonStringifyId;
IfFailRet(JsGetPropertyIdFromName(L"stringify", &jsonStringifyId));
IfFailRet(JsGetProperty(jsonObject, jsonStringifyId, &jsonStringifyObject));
return JsNoError;
}
JsErrorCode ChakraHost::InitConsole()
{
IfFailRet(DefineHostCallback(globalObject, L"nativeLoggingHook", NativeLoggingCallback, nullptr));
return JsNoError;
}
JsErrorCode ChakraHost::Init()
{
currentSourceContext = 0;
IfFailRet(JsCreateRuntime(JsRuntimeAttributeNone, nullptr, &runtime));
IfFailRet(JsCreateContext(runtime, &context));
IfFailRet(JsSetCurrentContext(context));
IfFailRet(JsGetGlobalObject(&globalObject));
IfFailRet(InitJson());
IfFailRet(InitConsole());
return JsNoError;
}
JsErrorCode ChakraHost::Destroy()
{
IfFailRet(JsSetCurrentContext(JS_INVALID_REFERENCE));
IfFailRet(JsDisposeRuntime(runtime));
return JsNoError;
}
<|endoftext|>
|
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2015 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include "TestHarness.h"
#include "mbed.h"
#if !DEVICE_SPI || !DEVICE_SPI_ASYNCH
#error spi_master_asynch requires asynch SPI
#endif
#define SHORT_XFR 3
#define LONG_XFR 16
#define TEST_BYTE0 0x00
#define TEST_BYTE1 0x11
#define TEST_BYTE2 0xFF
#define TEST_BYTE3 0xAA
#define TEST_BYTE4 0x55
#define TEST_BYTE5 0x50
#define TEST_BYTE_RX TEST_BYTE3
#define TEST_BYTE_TX_BASE TEST_BYTE5
#if defined(TARGET_K64F) || defined(TARGET_K66F)
#define TEST_MOSI_PIN PTD2
#define TEST_MISO_PIN PTD3
#define TEST_SCLK_PIN PTD1
#define TEST_CS_PIN PTD0
#elif defined(TARGET_EFM32LG_STK3600) || defined(TARGET_EFM32GG_STK3700) || defined(TARGET_EFM32WG_STK3800)
#define TEST_MOSI_PIN PD0
#define TEST_MISO_PIN PD1
#define TEST_SCLK_PIN PD2
#define TEST_CS_PIN PD3
#elif defined(TARGET_EFM32ZG_STK3200)
#define TEST_MOSI_PIN PD7
#define TEST_MISO_PIN PD6
#define TEST_SCLK_PIN PC15
#define TEST_CS_PIN PC14
#elif defined(TARGET_EFM32HG_STK3400)
#define TEST_MOSI_PIN PE10
#define TEST_MISO_PIN PE11
#define TEST_SCLK_PIN PE12
#define TEST_CS_PIN PE13
#elif defined(TARGET_RZ_A1H)
#define TEST_MOSI_PIN P10_14
#define TEST_MISO_PIN P10_15
#define TEST_SCLK_PIN P10_12
#define TEST_CS_PIN P10_13
#else
#error Target not supported
#endif
volatile int why;
volatile bool complete;
void cbdone(int event) {
complete = true;
why = event;
}
TEST_GROUP(SPI_Master_Asynchronous)
{
uint8_t tx_buf[LONG_XFR];
uint8_t rx_buf[LONG_XFR];
SPI *obj;
DigitalOut *cs;
event_callback_t callback;
void setup() {
obj = new SPI(TEST_MOSI_PIN, TEST_MISO_PIN, TEST_SCLK_PIN);
cs = new DigitalOut(TEST_CS_PIN);
complete = false;
why = 0;
callback.attach(cbdone);
// Set the default value of tx_buf
for (uint32_t i = 0; i < sizeof(tx_buf); i++) {
tx_buf[i] = i + TEST_BYTE_TX_BASE;
}
memset(rx_buf,TEST_BYTE_RX,sizeof(rx_buf));
}
void teardown() {
delete obj;
obj = NULL;
delete cs;
cs = NULL;
}
uint32_t cmpnbuf(uint8_t *expect, uint8_t *actual, uint32_t offset, uint32_t end, const char *file, uint32_t line)
{
uint32_t i;
for (i = offset; i < end; i++){
if (expect[i] != actual[i]) {
break;
}
}
if (i < end) {
CHECK_EQUAL_LOCATION((int)expect[i], (int)actual[i], file, line);
}
CHECK_EQUAL_LOCATION(end, i, file, line);
return i;
}
uint32_t cmpnbufc(uint8_t expect, uint8_t *actual, uint32_t offset, uint32_t end, const char *file, uint32_t line)
{
uint32_t i;
for (i = offset; i < end; i++){
if (expect != actual[i]) {
break;
}
}
if (i < end) {
CHECK_EQUAL_LOCATION((int)expect, (int)actual[i], file, line);
}
CHECK_EQUAL_LOCATION(end, i, file, line);
return i;
}
void dumpRXbuf() {
uint32_t i;
printf("\r\n");
printf("RX Buffer Contents: [");
//flushf(stdout);
for (i = 0; i < sizeof(rx_buf); i++){
printf("%02x",rx_buf[i]);
if (i+1 < sizeof(rx_buf)){
printf(",");
}
}
printf("]\r\n");
}
};
// SPI write tx length: FIFO-1, read length: 0
// Checks: Null pointer exceptions, completion event
TEST(SPI_Master_Asynchronous, short_tx_0_rx)
{
int rc;
// Write a buffer of Short Transfer length.
rc = obj->transfer( tx_buf,SHORT_XFR,NULL,0, callback, -1);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(why, SPI_EVENT_COMPLETE);
// TODO: Check for a null pointer exception
}
//
// SPI write tx length: FIFO-1, read length: 0, non-null read pointer
// Checks: Null pointer exceptions, completion event, canary values in read buffer
TEST(SPI_Master_Asynchronous, short_tx_0_rx_nn)
{
int rc;
// Write a buffer of Short Transfer length.
rc = obj->transfer( tx_buf,SHORT_XFR,rx_buf,0,callback, -1);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(SPI_EVENT_COMPLETE, why);
// Check that the rx buffer is untouched
cmpnbufc(TEST_BYTE_RX,rx_buf,0,sizeof(rx_buf),__FILE__,__LINE__);
}
// SPI write tx length: 0, read length: FIFO-1
// Checks: Receive value==fill character, completion event
TEST(SPI_Master_Asynchronous, 0_tx_short_rx)
{
int rc;
// Read a buffer of Short Transfer length.
rc = obj->transfer( NULL,0,rx_buf,SHORT_XFR,callback, -1);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(SPI_EVENT_COMPLETE, why);
// TODO: Check for null pointer exception
// Check that the receive buffer contains the fill byte.
cmpnbufc(SPI_FILL_WORD,rx_buf,0,SHORT_XFR,__FILE__,__LINE__);
// Check that remaining portion of the receive buffer contains the rx test byte
cmpnbufc(TEST_BYTE_RX,rx_buf,SHORT_XFR,sizeof(rx_buf),__FILE__,__LINE__);
}
// SPI write tx length: 0, read length: FIFO-1
// Checks: Receive value==fill character, completion event
TEST(SPI_Master_Asynchronous, 0_tx_nn_short_rx)
{
int rc;
// Read a buffer of Short Transfer length.
rc = obj->transfer(tx_buf,0,rx_buf,SHORT_XFR,callback, -1);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(SPI_EVENT_COMPLETE, why);
// Check that the receive buffer contains the fill byte.
cmpnbufc(SPI_FILL_WORD,rx_buf,0,SHORT_XFR,__FILE__,__LINE__);
// Check that remaining portion of the receive buffer contains the rx test byte
cmpnbufc(TEST_BYTE_RX,rx_buf,SHORT_XFR,sizeof(rx_buf),__FILE__,__LINE__);
}
// SPI write tx length: FIFO-1 ascending values, read length: FIFO-1
// Checks: Receive buffer == tx buffer, completion event
TEST(SPI_Master_Asynchronous, short_tx_short_rx)
{
int rc;
// Write/Read a buffer of Long Transfer length.
rc = obj->transfer( tx_buf,SHORT_XFR,rx_buf,SHORT_XFR,callback, -1);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(SPI_EVENT_COMPLETE, why);
// Check that the rx buffer contains the tx bytes
cmpnbuf(tx_buf,rx_buf,0,SHORT_XFR,__FILE__,__LINE__);
// Check that remaining portion of the receive buffer contains the rx test byte
cmpnbufc(TEST_BYTE_RX,rx_buf,SHORT_XFR,sizeof(rx_buf),__FILE__,__LINE__);
}
// SPI write tx length: 2xFIFO ascending values, read length: 2xFIFO
// Checks: Receive buffer == tx buffer, completion event
TEST(SPI_Master_Asynchronous, long_tx_long_rx)
{
int rc;
// Write/Read a buffer of Long Transfer length.
rc = obj->transfer(tx_buf,LONG_XFR,rx_buf,LONG_XFR,callback, -1);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(SPI_EVENT_COMPLETE, why);
//dumpRXbuf();
// Check that the rx buffer contains the tx bytes
cmpnbuf(tx_buf,rx_buf,0,LONG_XFR,__FILE__,__LINE__);
// Check that remaining portion of the receive buffer contains the rx test byte
cmpnbufc(TEST_BYTE_RX,rx_buf,LONG_XFR,sizeof(rx_buf),__FILE__,__LINE__);
}
// SPI write tx length: 2xFIFO, ascending, read length: FIFO-1
// Checks: Receive buffer == tx buffer, completion event, read buffer overflow
TEST(SPI_Master_Asynchronous, long_tx_short_rx)
{
int rc;
// Write a buffer of Short Transfer length.
rc = obj->transfer(tx_buf,LONG_XFR,rx_buf,SHORT_XFR,callback, -1);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(SPI_EVENT_COMPLETE, why);
// Check that the rx buffer contains the tx bytes
cmpnbuf(tx_buf,rx_buf,0,SHORT_XFR,__FILE__,__LINE__);
// Check that remaining portion of the receive buffer contains the rx test byte
cmpnbufc(TEST_BYTE_RX,rx_buf,SHORT_XFR,sizeof(rx_buf),__FILE__,__LINE__);
}
// SPI write tx length: FIFO-1, ascending, read length: 2xFIFO
// Checks: Receive buffer == tx buffer, then fill, completion event
TEST(SPI_Master_Asynchronous, short_tx_long_rx)
{
int rc;
// Write a buffer of Short Transfer length.
rc = obj->transfer(tx_buf,SHORT_XFR,rx_buf,LONG_XFR,callback, -1);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(SPI_EVENT_COMPLETE, why);
//dumpRXbuf();
// Check that the rx buffer contains the tx bytes
cmpnbuf(tx_buf,rx_buf,0,SHORT_XFR,__FILE__,__LINE__);
// Check that the rx buffer contains the tx fill bytes
cmpnbufc(SPI_FILL_WORD,rx_buf,SHORT_XFR,LONG_XFR,__FILE__,__LINE__);
// Check that remaining portion of the receive buffer contains the rx test byte
cmpnbufc(TEST_BYTE_RX,rx_buf,LONG_XFR,sizeof(rx_buf),__FILE__,__LINE__);
}
TEST(SPI_Master_Asynchronous, queue_test)
{
int rc;
// Write/Read a buffer of Long Transfer length.
rc = obj->transfer( tx_buf,4,rx_buf,4,callback, 0);
CHECK_EQUAL(0, rc);
rc = obj->transfer( &tx_buf[4],4, &rx_buf[4],4,callback, 0);
CHECK_EQUAL(0, rc);
rc = obj->transfer( &tx_buf[8],4, &rx_buf[8],4,callback, -1);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(SPI_EVENT_COMPLETE, why);
// Check that the rx buffer contains the tx bytes
cmpnbuf(tx_buf,rx_buf,0,12,__FILE__,__LINE__);
// Check that remaining portion of the receive buffer contains the rx test byte
cmpnbufc(TEST_BYTE_RX,rx_buf,12,sizeof(rx_buf),__FILE__,__LINE__);
}
<commit_msg>UTEST Spi Asynch<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2015 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include "TestHarness.h"
#include "mbed.h"
#if !DEVICE_SPI || !DEVICE_SPI_ASYNCH
#error spi_master_asynch requires asynch SPI
#endif
#define SHORT_XFR 3
#define LONG_XFR 16
#define TEST_BYTE0 0x00
#define TEST_BYTE1 0x11
#define TEST_BYTE2 0xFF
#define TEST_BYTE3 0xAA
#define TEST_BYTE4 0x55
#define TEST_BYTE5 0x50
#define TEST_BYTE_RX TEST_BYTE3
#define TEST_BYTE_TX_BASE TEST_BYTE5
#if defined(TARGET_K64F) || defined(TARGET_K66F)
#define TEST_MOSI_PIN PTD2
#define TEST_MISO_PIN PTD3
#define TEST_SCLK_PIN PTD1
#define TEST_CS_PIN PTD0
#elif defined(TARGET_EFM32LG_STK3600) || defined(TARGET_EFM32GG_STK3700) || defined(TARGET_EFM32WG_STK3800)
#define TEST_MOSI_PIN PD0
#define TEST_MISO_PIN PD1
#define TEST_SCLK_PIN PD2
#define TEST_CS_PIN PD3
#elif defined(TARGET_EFM32ZG_STK3200)
#define TEST_MOSI_PIN PD7
#define TEST_MISO_PIN PD6
#define TEST_SCLK_PIN PC15
#define TEST_CS_PIN PC14
#elif defined(TARGET_EFM32HG_STK3400)
#define TEST_MOSI_PIN PE10
#define TEST_MISO_PIN PE11
#define TEST_SCLK_PIN PE12
#define TEST_CS_PIN PE13
#elif defined(TARGET_RZ_A1H)
#define TEST_MOSI_PIN P10_14
#define TEST_MISO_PIN P10_15
#define TEST_SCLK_PIN P10_12
#define TEST_CS_PIN P10_13
#elif defined(TARGET_FF_ARDUINO)
#define TEST_MOSI_PIN D11
#define TEST_MISO_PIN D12
#define TEST_SCLK_PIN D13
#define TEST_CS_PIN D10
#elif defined(TARGET_DISCO_F429ZI)
#define TEST_MOSI_PIN PC_12
#define TEST_MISO_PIN PC_11
#define TEST_SCLK_PIN PC_10
#define TEST_CS_PIN PA_15
#else
#error Target not supported
#endif
volatile int why;
volatile bool complete;
void cbdone(int event) {
complete = true;
why = event;
}
TEST_GROUP(SPI_Master_Asynchronous)
{
uint8_t tx_buf[LONG_XFR];
uint8_t rx_buf[LONG_XFR];
SPI *obj;
DigitalOut *cs;
event_callback_t callback;
void setup() {
obj = new SPI(TEST_MOSI_PIN, TEST_MISO_PIN, TEST_SCLK_PIN);
cs = new DigitalOut(TEST_CS_PIN);
complete = false;
why = 0;
callback.attach(cbdone);
// Set the default value of tx_buf
for (uint32_t i = 0; i < sizeof(tx_buf); i++) {
tx_buf[i] = i + TEST_BYTE_TX_BASE;
}
memset(rx_buf,TEST_BYTE_RX,sizeof(rx_buf));
}
void teardown() {
delete obj;
obj = NULL;
delete cs;
cs = NULL;
}
uint32_t cmpnbuf(uint8_t *expect, uint8_t *actual, uint32_t offset, uint32_t end, const char *file, uint32_t line)
{
uint32_t i;
for (i = offset; i < end; i++){
if (expect[i] != actual[i]) {
break;
}
}
if (i < end) {
CHECK_EQUAL_LOCATION((int)expect[i], (int)actual[i], file, line);
}
CHECK_EQUAL_LOCATION(end, i, file, line);
return i;
}
uint32_t cmpnbufc(uint8_t expect, uint8_t *actual, uint32_t offset, uint32_t end, const char *file, uint32_t line)
{
uint32_t i;
for (i = offset; i < end; i++){
if (expect != actual[i]) {
break;
}
}
if (i < end) {
CHECK_EQUAL_LOCATION((int)expect, (int)actual[i], file, line);
}
CHECK_EQUAL_LOCATION(end, i, file, line);
return i;
}
void dumpRXbuf() {
uint32_t i;
printf("\r\n");
printf("RX Buffer Contents: [");
//flushf(stdout);
for (i = 0; i < sizeof(rx_buf); i++){
printf("%02x",rx_buf[i]);
if (i+1 < sizeof(rx_buf)){
printf(",");
}
}
printf("]\r\n");
}
};
// SPI write tx length: FIFO-1, read length: 0
// Checks: Null pointer exceptions, completion event
TEST(SPI_Master_Asynchronous, short_tx_0_rx)
{
int rc;
// Write a buffer of Short Transfer length.
rc = obj->transfer( (const uint8_t *) tx_buf, SHORT_XFR, (uint8_t *) NULL, 0, callback, 255);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(why, SPI_EVENT_COMPLETE);
// TODO: Check for a null pointer exception
}
//
// SPI write tx length: FIFO-1, read length: 0, non-null read pointer
// Checks: Null pointer exceptions, completion event, canary values in read buffer
TEST(SPI_Master_Asynchronous, short_tx_0_rx_nn)
{
int rc;
// Write a buffer of Short Transfer length.
rc = obj->transfer( (const uint8_t *)tx_buf,SHORT_XFR,(uint8_t *) rx_buf, 0,callback, -1);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(SPI_EVENT_COMPLETE, why);
// Check that the rx buffer is untouched
cmpnbufc(TEST_BYTE_RX,rx_buf,0,sizeof(rx_buf),__FILE__,__LINE__);
}
// SPI write tx length: 0, read length: FIFO-1
// Checks: Receive value==fill character, completion event
TEST(SPI_Master_Asynchronous, 0_tx_short_rx)
{
int rc;
// Read a buffer of Short Transfer length.
rc = obj->transfer( (const uint8_t *)NULL,0,(uint8_t *) rx_buf,SHORT_XFR,callback, -1);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(SPI_EVENT_COMPLETE, why);
// TODO: Check for null pointer exception
// Check that the receive buffer contains the fill byte.
cmpnbufc(SPI_FILL_WORD,rx_buf,0,SHORT_XFR,__FILE__,__LINE__);
// Check that remaining portion of the receive buffer contains the rx test byte
cmpnbufc(TEST_BYTE_RX,rx_buf,SHORT_XFR,sizeof(rx_buf),__FILE__,__LINE__);
}
// SPI write tx length: 0, read length: FIFO-1
// Checks: Receive value==fill character, completion event
TEST(SPI_Master_Asynchronous, 0_tx_nn_short_rx)
{
int rc;
// Read a buffer of Short Transfer length.
rc = obj->transfer(tx_buf,0,rx_buf,SHORT_XFR,callback, -1);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(SPI_EVENT_COMPLETE, why);
// Check that the receive buffer contains the fill byte.
cmpnbufc(SPI_FILL_WORD,rx_buf,0,SHORT_XFR,__FILE__,__LINE__);
// Check that remaining portion of the receive buffer contains the rx test byte
cmpnbufc(TEST_BYTE_RX,rx_buf,SHORT_XFR,sizeof(rx_buf),__FILE__,__LINE__);
}
// SPI write tx length: FIFO-1 ascending values, read length: FIFO-1
// Checks: Receive buffer == tx buffer, completion event
TEST(SPI_Master_Asynchronous, short_tx_short_rx)
{
int rc;
// Write/Read a buffer of Long Transfer length.
rc = obj->transfer( tx_buf,SHORT_XFR,rx_buf,SHORT_XFR,callback, -1);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(SPI_EVENT_COMPLETE, why);
// Check that the rx buffer contains the tx bytes
cmpnbuf(tx_buf,rx_buf,0,SHORT_XFR,__FILE__,__LINE__);
// Check that remaining portion of the receive buffer contains the rx test byte
cmpnbufc(TEST_BYTE_RX,rx_buf,SHORT_XFR,sizeof(rx_buf),__FILE__,__LINE__);
}
// SPI write tx length: 2xFIFO ascending values, read length: 2xFIFO
// Checks: Receive buffer == tx buffer, completion event
TEST(SPI_Master_Asynchronous, long_tx_long_rx)
{
int rc;
// Write/Read a buffer of Long Transfer length.
rc = obj->transfer(tx_buf,LONG_XFR,rx_buf,LONG_XFR,callback, -1);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(SPI_EVENT_COMPLETE, why);
//dumpRXbuf();
// Check that the rx buffer contains the tx bytes
cmpnbuf(tx_buf,rx_buf,0,LONG_XFR,__FILE__,__LINE__);
// Check that remaining portion of the receive buffer contains the rx test byte
cmpnbufc(TEST_BYTE_RX,rx_buf,LONG_XFR,sizeof(rx_buf),__FILE__,__LINE__);
}
// SPI write tx length: 2xFIFO, ascending, read length: FIFO-1
// Checks: Receive buffer == tx buffer, completion event, read buffer overflow
TEST(SPI_Master_Asynchronous, long_tx_short_rx)
{
int rc;
// Write a buffer of Short Transfer length.
rc = obj->transfer(tx_buf,LONG_XFR,rx_buf,SHORT_XFR,callback, -1);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(SPI_EVENT_COMPLETE, why);
// Check that the rx buffer contains the tx bytes
cmpnbuf(tx_buf,rx_buf,0,SHORT_XFR,__FILE__,__LINE__);
// Check that remaining portion of the receive buffer contains the rx test byte
cmpnbufc(TEST_BYTE_RX,rx_buf,SHORT_XFR,sizeof(rx_buf),__FILE__,__LINE__);
}
// SPI write tx length: FIFO-1, ascending, read length: 2xFIFO
// Checks: Receive buffer == tx buffer, then fill, completion event
TEST(SPI_Master_Asynchronous, short_tx_long_rx)
{
int rc;
// Write a buffer of Short Transfer length.
rc = obj->transfer(tx_buf,SHORT_XFR,rx_buf,LONG_XFR,callback, -1);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(SPI_EVENT_COMPLETE, why);
//dumpRXbuf();
// Check that the rx buffer contains the tx bytes
cmpnbuf(tx_buf,rx_buf,0,SHORT_XFR,__FILE__,__LINE__);
// Check that the rx buffer contains the tx fill bytes
cmpnbufc(SPI_FILL_WORD,rx_buf,SHORT_XFR,LONG_XFR,__FILE__,__LINE__);
// Check that remaining portion of the receive buffer contains the rx test byte
cmpnbufc(TEST_BYTE_RX,rx_buf,LONG_XFR,sizeof(rx_buf),__FILE__,__LINE__);
}
TEST(SPI_Master_Asynchronous, queue_test)
{
int rc;
// Write/Read a buffer of Long Transfer length.
rc = obj->transfer( tx_buf,4,rx_buf,4,callback, 0);
CHECK_EQUAL(0, rc);
rc = obj->transfer( &tx_buf[4],4, &rx_buf[4],4,callback, 0);
CHECK_EQUAL(0, rc);
rc = obj->transfer( &tx_buf[8],4, &rx_buf[8],4,callback, -1);
CHECK_EQUAL(0, rc);
while (!complete);
// Make sure that the callback fires.
CHECK_EQUAL(SPI_EVENT_COMPLETE, why);
// Check that the rx buffer contains the tx bytes
cmpnbuf(tx_buf,rx_buf,0,12,__FILE__,__LINE__);
// Check that remaining portion of the receive buffer contains the rx test byte
cmpnbufc(TEST_BYTE_RX,rx_buf,12,sizeof(rx_buf),__FILE__,__LINE__);
}
<|endoftext|>
|
<commit_before>/* The MIT License
Copyright (c) 2014 Adrian Tan <atks@umich.edu>
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 "profile_afs.h"
namespace
{
KHASH_MAP_INIT_INT(32, int32_t)
class Igor : Program
{
public:
std::string version;
///////////
//options//
///////////
std::string input_vcf_file;
std::string output_dir;
std::string output_pdf_file;
const char* AC;
const char* AN;
std::vector<GenomeInterval> intervals;
std::string interval_list;
///////
//i/o//
///////
BCFOrderedReader *odr;
///////////////
//general use//
///////////////
int ret, is_missing;
khiter_t k;
khash_t(32) *afs;
khash_t(32) *pass_afs;
//////////
//filter//
//////////
std::string fexp;
Filter filter;
bool filter_exists;
/////////
//stats//
/////////
uint32_t no_variants;
/////////
//tools//
/////////
Pedigree *pedigree;
VariantManip *vm;
Igor(int argc, char ** argv)
{
//////////////////////////
//options initialization//
//////////////////////////
try
{
std::string desc = "Plot Allele Frequency Spectrum.";
version = "0.5";
TCLAP::CmdLine cmd(desc, ' ', version);
VTOutput my; cmd.setOutput(&my);
TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals", false, "", "str", cmd);
TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "str", cmd);
TCLAP::ValueArg<std::string> arg_fexp("f", "f", "filter expression []", false, "", "str", cmd);
TCLAP::ValueArg<std::string> arg_output_dir("x", "x", "output directory []", false, "plot_afs", "str", cmd);
TCLAP::ValueArg<std::string> arg_output_pdf_file("y", "y", "output PDF file []", false, "afs.pdf", "str", cmd);
TCLAP::ValueArg<std::string> arg_AC("c", "ac", "AC tag [AC]", false, "AC", "str", cmd);
TCLAP::ValueArg<std::string> arg_AN("n", "an", "AN tag [AN]", false, "AN", "str", cmd);
TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file("<in.vcf>", "input VCF file", true, "","file", cmd);
cmd.parse(argc, argv);
input_vcf_file = arg_input_vcf_file.getValue();
fexp = arg_fexp.getValue();
output_dir = arg_output_dir.getValue();
output_pdf_file = arg_output_pdf_file.getValue();
AC = strdup(arg_AC.getValue().c_str());
AN = strdup(arg_AN.getValue().c_str());
parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue());
}
catch (TCLAP::ArgException &e)
{
std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n";
abort();
}
};
void initialize()
{
//////////////////////
//i/o initialization//
//////////////////////
odr = new BCFOrderedReader(input_vcf_file, intervals);
/////////////////////////
//filter initialization//
/////////////////////////
filter.parse(fexp.c_str());
filter_exists = fexp=="" ? false : true;
afs = kh_init(32);
pass_afs = kh_init(32);
////////////////////////
//stats initialization//
////////////////////////
no_variants = 0;
/////////
//tools//
/////////
vm = new VariantManip();
}
void profile_afs()
{
bcf1_t *v = bcf_init1();
Variant variant;
int32_t *ac=NULL, *an=NULL, n_ac=0, n_an=0;
while(odr->read(v))
{
bcf_unpack(v, BCF_UN_ALL);
if (bcf_get_n_allele(v)!=2)
{
continue;
}
if (filter_exists)
{
int32_t vtype = vm->classify_variant(odr->hdr, v, variant);
if (!filter.apply(odr->hdr, v, &variant))
{
continue;
}
}
bool pass = (bcf_has_filter(odr->hdr, v, const_cast<char*>("PASS"))==1);
bcf_get_info_int32(odr->hdr, v, AC, &ac, &n_ac);
bcf_get_info_int32(odr->hdr, v, AN, &an, &n_an);
if (ac[0]>(an[0]>>1)) {ac[0] = an[0]-ac[0];}
if (ac[0]==0) continue;
k = kh_get(32, afs, ac[0]);
if (k==kh_end(afs))
{
k = kh_put(32, afs, ac[0], &ret);
kh_value(afs, k) = 1;
}
else
{
kh_value(afs, k) = kh_value(afs, k) + 1;
}
if (pass)
{
k = kh_get(32, pass_afs, ac[0]);
if (k==kh_end(pass_afs))
{
k = kh_put(32, pass_afs, ac[0], &ret);
kh_value(pass_afs, k) = 1;
}
else
{
kh_value(pass_afs, k) = kh_value(pass_afs, k) + 1;
}
}
++no_variants;
}
if (n_ac) free(ac);
if (n_an) free(an);
};
void print_options()
{
std::clog << "plot_afs v" << version << "\n\n";
std::clog << "options: input VCF file " << input_vcf_file << "\n";
std::clog << " [c] AC tag " << AC << "\n";
std::clog << " [n] AN tag " << AN << "\n";
print_str_op(" [x] output directory ", output_dir);
print_str_op(" [y] output pdf file ", output_pdf_file);
print_int_op(" [i] intervals ", intervals);
std::clog << "\n";
}
void print_pdf()
{
append_cwd(output_dir);
//create directory
mkdir(output_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
//create data file
std::string file_path = output_dir + "/data.txt";
FILE *out = fopen(file_path.c_str(), "w");
fprintf(out, "mac\tf\tpass\n");
for (k=kh_begin(afs); k!=kh_end(afs); ++k)
{
if (kh_exist(afs, k))
{
fprintf(out, "%d\t%d\t0\n", k , kh_value(afs, k));
}
}
for (k=kh_begin(pass_afs); k!=kh_end(pass_afs); ++k)
{
if (kh_exist(pass_afs, k))
{
fprintf(out, "%d\t%d\t1\n", k , kh_value(pass_afs, k));
}
}
fclose(out);
//create r script
file_path = output_dir + "/plot.r";
out = fopen(file_path.c_str(), "w");
fprintf(out, "setwd(\"%s\")\n", output_dir.c_str());
fprintf(out, "\n");
fprintf(out, "data = read.table(\"data.txt\", header=T)\n");
fprintf(out, "data.all=subset(data, pass==0)\n");
fprintf(out, "pdf(\"%s\",7,5)\n", output_pdf_file.c_str());
fprintf(out, "plot(data.all$mac, data.all$f, log=\"xy\", pch=20, cex=0.5, col=rgb(1,0,0,0.5), main=\"Folded Allele Frequency Spectrum\", xlab=\"Minor allele counts\", ylab=\"Frequency\", panel.last=grid(equilogs=FALSE, col=\"grey\"))\n");
fprintf(out, "data.pass=subset(data, pass==1)\n");
fprintf(out, "points(data.pass$mac, data.pass$f, pch=20, cex=0.5, col=rgb(0,0,1,0.5))\n");
fprintf(out, "legend(\"topright\", c(\"pass\", \"all\"), col = c(rgb(0,0,1,0.5), rgb(1,0,0,0.5)), pch = 20)\n");
fprintf(out, "dev.off()\n");
fclose(out);
//run script
std::string cmd = "cd " + output_dir + "; cat plot.r | R --vanilla > run.log";
system(cmd.c_str());
};
void print_stats()
{
fprintf(stderr, "Stats \n");
fprintf(stderr, " no. of variants : %d\n", no_variants);
fprintf(stderr, "\n");
//do a textual histogram print out of afs
};
~Igor()
{
odr->close();
kh_destroy(32, afs);
kh_destroy(32, pass_afs);
};
private:
};
}
void profile_afs(int argc, char ** argv)
{
Igor igor(argc, argv);
igor.print_options();
igor.initialize();
igor.profile_afs();
igor.print_stats();
igor.print_pdf();
}
<commit_msg>minor changes<commit_after>/* The MIT License
Copyright (c) 2014 Adrian Tan <atks@umich.edu>
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 "profile_afs.h"
namespace
{
KHASH_MAP_INIT_INT(32, int32_t)
class Igor : Program
{
public:
std::string version;
///////////
//options//
///////////
std::string input_vcf_file;
std::string output_dir;
std::string output_pdf_file;
const char* AC;
const char* AN;
std::vector<GenomeInterval> intervals;
std::string interval_list;
///////
//i/o//
///////
BCFOrderedReader *odr;
///////////////
//general use//
///////////////
int ret, is_missing;
khiter_t k;
khash_t(32) *afs;
khash_t(32) *pass_afs;
//////////
//filter//
//////////
std::string fexp;
Filter filter;
bool filter_exists;
/////////
//stats//
/////////
uint32_t no_variants;
/////////
//tools//
/////////
Pedigree *pedigree;
VariantManip *vm;
Igor(int argc, char ** argv)
{
//////////////////////////
//options initialization//
//////////////////////////
try
{
std::string desc = "Plot Allele Frequency Spectrum.";
version = "0.5";
TCLAP::CmdLine cmd(desc, ' ', version);
VTOutput my; cmd.setOutput(&my);
TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals", false, "", "str", cmd);
TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "str", cmd);
TCLAP::ValueArg<std::string> arg_fexp("f", "f", "filter expression []", false, "", "str", cmd);
TCLAP::ValueArg<std::string> arg_output_dir("x", "x", "output directory []", false, "plot_afs", "str", cmd);
TCLAP::ValueArg<std::string> arg_output_pdf_file("y", "y", "output PDF file []", false, "afs.pdf", "str", cmd);
TCLAP::ValueArg<std::string> arg_AC("c", "ac", "AC tag [AC]", false, "AC", "str", cmd);
TCLAP::ValueArg<std::string> arg_AN("n", "an", "AN tag [AN]", false, "AN", "str", cmd);
TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file("<in.vcf>", "input VCF file", true, "","file", cmd);
cmd.parse(argc, argv);
input_vcf_file = arg_input_vcf_file.getValue();
fexp = arg_fexp.getValue();
output_dir = arg_output_dir.getValue();
output_pdf_file = arg_output_pdf_file.getValue();
AC = strdup(arg_AC.getValue().c_str());
AN = strdup(arg_AN.getValue().c_str());
parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue());
}
catch (TCLAP::ArgException &e)
{
std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n";
abort();
}
};
void initialize()
{
//////////////////////
//i/o initialization//
//////////////////////
odr = new BCFOrderedReader(input_vcf_file, intervals);
/////////////////////////
//filter initialization//
/////////////////////////
filter.parse(fexp.c_str());
filter_exists = fexp=="" ? false : true;
afs = kh_init(32);
pass_afs = kh_init(32);
////////////////////////
//stats initialization//
////////////////////////
no_variants = 0;
/////////
//tools//
/////////
vm = new VariantManip();
}
void profile_afs()
{
bcf1_t *v = bcf_init1();
Variant variant;
int32_t *ac=NULL, *an=NULL, n_ac=0, n_an=0;
while(odr->read(v))
{
bcf_unpack(v, BCF_UN_ALL);
bcf_print(odr->hdr, v);
if (bcf_get_n_allele(v)!=2)
{
continue;
}
if (filter_exists)
{
int32_t vtype = vm->classify_variant(odr->hdr, v, variant);
if (!filter.apply(odr->hdr, v, &variant))
{
continue;
}
}
bool pass = (bcf_has_filter(odr->hdr, v, const_cast<char*>("PASS"))==1);
bcf_get_info_int32(odr->hdr, v, AC, &ac, &n_ac);
bcf_get_info_int32(odr->hdr, v, AN, &an, &n_an);
if (ac[0]>(an[0]>>1)) {ac[0] = an[0]-ac[0];}
if (ac[0]==0) continue;
k = kh_get(32, afs, ac[0]);
if (k==kh_end(afs))
{
k = kh_put(32, afs, ac[0], &ret);
kh_value(afs, k) = 1;
}
else
{
kh_value(afs, k) = kh_value(afs, k) + 1;
}
if (pass)
{
k = kh_get(32, pass_afs, ac[0]);
if (k==kh_end(pass_afs))
{
k = kh_put(32, pass_afs, ac[0], &ret);
kh_value(pass_afs, k) = 1;
}
else
{
kh_value(pass_afs, k) = kh_value(pass_afs, k) + 1;
}
}
++no_variants;
}
if (n_ac) free(ac);
if (n_an) free(an);
};
void print_options()
{
std::clog << "plot_afs v" << version << "\n\n";
std::clog << "options: input VCF file " << input_vcf_file << "\n";
std::clog << " [c] AC tag " << AC << "\n";
std::clog << " [n] AN tag " << AN << "\n";
print_str_op(" [x] output directory ", output_dir);
print_str_op(" [y] output pdf file ", output_pdf_file);
print_int_op(" [i] intervals ", intervals);
std::clog << "\n";
}
void print_pdf()
{
append_cwd(output_dir);
//create directory
mkdir(output_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
//create data file
std::string file_path = output_dir + "/data.txt";
FILE *out = fopen(file_path.c_str(), "w");
fprintf(out, "mac\tf\tpass\n");
for (k=kh_begin(afs); k!=kh_end(afs); ++k)
{
if (kh_exist(afs, k))
{
fprintf(out, "%d\t%d\t0\n", k , kh_value(afs, k));
}
}
for (k=kh_begin(pass_afs); k!=kh_end(pass_afs); ++k)
{
if (kh_exist(pass_afs, k))
{
fprintf(out, "%d\t%d\t1\n", k , kh_value(pass_afs, k));
}
}
fclose(out);
//create r script
file_path = output_dir + "/plot.r";
out = fopen(file_path.c_str(), "w");
fprintf(out, "setwd(\"%s\")\n", output_dir.c_str());
fprintf(out, "\n");
fprintf(out, "data = read.table(\"data.txt\", header=T)\n");
fprintf(out, "data.all=subset(data, pass==0)\n");
fprintf(out, "pdf(\"%s\",7,5)\n", output_pdf_file.c_str());
fprintf(out, "plot(data.all$mac, data.all$f, log=\"xy\", pch=20, cex=0.5, col=rgb(1,0,0,0.5), main=\"Folded Allele Frequency Spectrum\", xlab=\"Minor allele counts\", ylab=\"Frequency\", panel.last=grid(equilogs=FALSE, col=\"grey\"))\n");
fprintf(out, "data.pass=subset(data, pass==1)\n");
fprintf(out, "points(data.pass$mac, data.pass$f, pch=20, cex=0.5, col=rgb(0,0,1,0.5))\n");
fprintf(out, "legend(\"topright\", c(\"pass\", \"all\"), col = c(rgb(0,0,1,0.5), rgb(1,0,0,0.5)), pch = 20)\n");
fprintf(out, "dev.off()\n");
fclose(out);
//run script
std::string cmd = "cd " + output_dir + "; cat plot.r | R --vanilla > run.log";
system(cmd.c_str());
};
void print_stats()
{
fprintf(stderr, "Stats \n");
fprintf(stderr, " no. of variants : %d\n", no_variants);
fprintf(stderr, "\n");
//do a textual histogram print out of afs
};
~Igor()
{
odr->close();
kh_destroy(32, afs);
kh_destroy(32, pass_afs);
};
private:
};
}
void profile_afs(int argc, char ** argv)
{
Igor igor(argc, argv);
igor.print_options();
igor.initialize();
igor.profile_afs();
igor.print_stats();
igor.print_pdf();
}
<|endoftext|>
|
<commit_before>// Copyright 2020 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include <utility>
#include "iree/compiler/Dialect/HAL/IR/HALOps.h"
#include "iree/compiler/Dialect/HAL/Transforms/Passes.h"
#include "iree/compiler/Dialect/IREE/IR/IREEDialect.h"
#include "iree/compiler/Dialect/IREE/IR/IREEOps.h"
#include "llvm/ADT/StringSet.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/BlockAndValueMapping.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/Pass/Pass.h"
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace HAL {
// Inlines a condition region from a switch op into the function at the given
// point. This assumes that the insertion point will only be reached if the
// condition the region is predicated on is true.
static void inlineConditionRegion(Region &conditionRegion, Block *exitBlock,
OpBuilder funcBuilder) {
assert(!conditionRegion.empty() && "source regions must not be empty");
assert(conditionRegion.front().getNumArguments() == 0 && "switch does not capture");
// Splice in the region blocks.
auto *insertBlock = funcBuilder.getBlock();
auto postInsertBlockIt = std::next(insertBlock->getIterator())->getIterator();
auto *insertRegion = insertBlock->getParent();
insertRegion->getBlocks().splice(postInsertBlockIt,
conditionRegion.getBlocks());
auto newBlocks = llvm::make_range(std::next(insertBlock->getIterator()),
postInsertBlockIt);
auto *firstNewBlock = &*newBlocks.begin();
// Handle the hal.return ops which will transfer control to the exitBlock.
for (auto &newBlock : newBlocks) {
if (auto returnOp =
dyn_cast<IREE::HAL::ReturnOp>(newBlock.getTerminator())) {
OpBuilder branchBuilder(returnOp);
branchBuilder.create<BranchOp>(returnOp.getLoc(), exitBlock,
returnOp.getOperands());
returnOp.erase();
}
}
// Splice the instructions of the inlined entry block into the insert block.
insertBlock->getOperations().splice(insertBlock->end(),
firstNewBlock->getOperations());
firstNewBlock->erase();
}
// Inlines each switch condition region into the parent function predicated on
// the switch condition expression.
//
// Since switch conditions are evaluated in the order they are defined we can
// trivially turn the switch into a chain of if-else blocks.
// if condition_0_match:
// <inlined condition_0>
// else
// if condition_1_match:
// <inlined condition_1>
// else ...
static void buildConditionDispatchTable(IREE::HAL::DeviceSwitchOp switchOp,
OpBuilder funcBuilder) {
// Split the block containing the switch op such that all ops before the
// switch are before and the switch and the following ops are after.
// We'll have all of our inlined regions bounce over to the afterBlock with
// the results of the call and use that to replace the switch op.
auto *beforeBlock = funcBuilder.getBlock();
auto *afterBlock = beforeBlock->splitBlock(switchOp);
auto finalValues =
llvm::to_vector<4>(afterBlock->addArguments(switchOp.getResultTypes()));
// Create the blocks we'll use for all our conditions so that we can
// reference them when inserting the branch ops.
SmallVector<Block *, 4> conditionMatchBlocks(
switchOp.condition_regions().size());
SmallVector<Block *, 4> conditionFallthroughBlocks(
switchOp.condition_regions().size());
for (int i = 0; i < conditionMatchBlocks.size(); ++i) {
conditionMatchBlocks[i] = funcBuilder.createBlock(afterBlock);
conditionFallthroughBlocks[i] = funcBuilder.createBlock(afterBlock);
}
funcBuilder.setInsertionPoint(beforeBlock, beforeBlock->end());
for (auto condition : llvm::enumerate(llvm::zip(
switchOp.conditions().getValue(), switchOp.condition_regions()))) {
auto conditionAttr =
std::get<0>(condition.value()).cast<IREE::HAL::MatchAttrInterface>();
auto &conditionRegion = std::get<1>(condition.value());
// Insert the branch based on the match. We either match and jump to a
// block that will contain the inlined region or don't match and need to
// fall through.
auto isMatch = conditionAttr.buildConditionExpression(
switchOp.getLoc(), switchOp.device(), funcBuilder);
auto *matchBlock = conditionMatchBlocks[condition.index()];
auto *fallthroughBlock = conditionFallthroughBlocks[condition.index()];
funcBuilder.create<CondBranchOp>(switchOp.getLoc(), isMatch, matchBlock,
fallthroughBlock);
// Block that contains the inlined region and then jumps out of the chain.
funcBuilder.setInsertionPointToStart(matchBlock);
inlineConditionRegion(conditionRegion, afterBlock, funcBuilder);
// Block that we enter to check the next condition.
funcBuilder.setInsertionPointToStart(fallthroughBlock);
if (condition.index() + 1 < conditionFallthroughBlocks.size()) {
// Just continue on - the next loop iteration for the following
// condition will add its IR to the block.
} else {
// Fallthrough of all expressions; die if we expected return values.
funcBuilder.create<IREE::UnreachableOp>(
switchOp.getLoc(),
"device not supported in the compiled configuration");
}
}
// Remove the switch op and replace its results with the final joined
// results.
switchOp.replaceAllUsesWith(finalValues);
}
class InlineDeviceSwitchesPass
: public PassWrapper<InlineDeviceSwitchesPass, OperationPass<FuncOp>> {
public:
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<IREEDialect>();
}
StringRef getArgument() const override {
return "iree-hal-inline-device-switches";
}
StringRef getDescription() const override {
return "Inlines hal.device.switch condition regions";
}
void runOnOperation() override {
auto funcOp = getOperation();
SmallVector<IREE::HAL::DeviceSwitchOp, 4> switchOps;
funcOp.walk([&](IREE::HAL::DeviceSwitchOp switchOp) {
switchOps.push_back(switchOp);
});
for (auto switchOp : switchOps) {
OpBuilder funcBuilder(switchOp);
buildConditionDispatchTable(switchOp, funcBuilder);
switchOp.erase();
}
}
};
std::unique_ptr<OperationPass<FuncOp>> createInlineDeviceSwitchesPass() {
return std::make_unique<InlineDeviceSwitchesPass>();
}
static PassRegistration<InlineDeviceSwitchesPass> pass;
} // namespace HAL
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
<commit_msg>Run clang-format.<commit_after>// Copyright 2020 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include <utility>
#include "iree/compiler/Dialect/HAL/IR/HALOps.h"
#include "iree/compiler/Dialect/HAL/Transforms/Passes.h"
#include "iree/compiler/Dialect/IREE/IR/IREEDialect.h"
#include "iree/compiler/Dialect/IREE/IR/IREEOps.h"
#include "llvm/ADT/StringSet.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/BlockAndValueMapping.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/Pass/Pass.h"
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace HAL {
// Inlines a condition region from a switch op into the function at the given
// point. This assumes that the insertion point will only be reached if the
// condition the region is predicated on is true.
static void inlineConditionRegion(Region &conditionRegion, Block *exitBlock,
OpBuilder funcBuilder) {
assert(!conditionRegion.empty() && "source regions must not be empty");
assert(conditionRegion.front().getNumArguments() == 0 &&
"switch does not capture");
// Splice in the region blocks.
auto *insertBlock = funcBuilder.getBlock();
auto postInsertBlockIt = std::next(insertBlock->getIterator())->getIterator();
auto *insertRegion = insertBlock->getParent();
insertRegion->getBlocks().splice(postInsertBlockIt,
conditionRegion.getBlocks());
auto newBlocks = llvm::make_range(std::next(insertBlock->getIterator()),
postInsertBlockIt);
auto *firstNewBlock = &*newBlocks.begin();
// Handle the hal.return ops which will transfer control to the exitBlock.
for (auto &newBlock : newBlocks) {
if (auto returnOp =
dyn_cast<IREE::HAL::ReturnOp>(newBlock.getTerminator())) {
OpBuilder branchBuilder(returnOp);
branchBuilder.create<BranchOp>(returnOp.getLoc(), exitBlock,
returnOp.getOperands());
returnOp.erase();
}
}
// Splice the instructions of the inlined entry block into the insert block.
insertBlock->getOperations().splice(insertBlock->end(),
firstNewBlock->getOperations());
firstNewBlock->erase();
}
// Inlines each switch condition region into the parent function predicated on
// the switch condition expression.
//
// Since switch conditions are evaluated in the order they are defined we can
// trivially turn the switch into a chain of if-else blocks.
// if condition_0_match:
// <inlined condition_0>
// else
// if condition_1_match:
// <inlined condition_1>
// else ...
static void buildConditionDispatchTable(IREE::HAL::DeviceSwitchOp switchOp,
OpBuilder funcBuilder) {
// Split the block containing the switch op such that all ops before the
// switch are before and the switch and the following ops are after.
// We'll have all of our inlined regions bounce over to the afterBlock with
// the results of the call and use that to replace the switch op.
auto *beforeBlock = funcBuilder.getBlock();
auto *afterBlock = beforeBlock->splitBlock(switchOp);
auto finalValues =
llvm::to_vector<4>(afterBlock->addArguments(switchOp.getResultTypes()));
// Create the blocks we'll use for all our conditions so that we can
// reference them when inserting the branch ops.
SmallVector<Block *, 4> conditionMatchBlocks(
switchOp.condition_regions().size());
SmallVector<Block *, 4> conditionFallthroughBlocks(
switchOp.condition_regions().size());
for (int i = 0; i < conditionMatchBlocks.size(); ++i) {
conditionMatchBlocks[i] = funcBuilder.createBlock(afterBlock);
conditionFallthroughBlocks[i] = funcBuilder.createBlock(afterBlock);
}
funcBuilder.setInsertionPoint(beforeBlock, beforeBlock->end());
for (auto condition : llvm::enumerate(llvm::zip(
switchOp.conditions().getValue(), switchOp.condition_regions()))) {
auto conditionAttr =
std::get<0>(condition.value()).cast<IREE::HAL::MatchAttrInterface>();
auto &conditionRegion = std::get<1>(condition.value());
// Insert the branch based on the match. We either match and jump to a
// block that will contain the inlined region or don't match and need to
// fall through.
auto isMatch = conditionAttr.buildConditionExpression(
switchOp.getLoc(), switchOp.device(), funcBuilder);
auto *matchBlock = conditionMatchBlocks[condition.index()];
auto *fallthroughBlock = conditionFallthroughBlocks[condition.index()];
funcBuilder.create<CondBranchOp>(switchOp.getLoc(), isMatch, matchBlock,
fallthroughBlock);
// Block that contains the inlined region and then jumps out of the chain.
funcBuilder.setInsertionPointToStart(matchBlock);
inlineConditionRegion(conditionRegion, afterBlock, funcBuilder);
// Block that we enter to check the next condition.
funcBuilder.setInsertionPointToStart(fallthroughBlock);
if (condition.index() + 1 < conditionFallthroughBlocks.size()) {
// Just continue on - the next loop iteration for the following
// condition will add its IR to the block.
} else {
// Fallthrough of all expressions; die if we expected return values.
funcBuilder.create<IREE::UnreachableOp>(
switchOp.getLoc(),
"device not supported in the compiled configuration");
}
}
// Remove the switch op and replace its results with the final joined
// results.
switchOp.replaceAllUsesWith(finalValues);
}
class InlineDeviceSwitchesPass
: public PassWrapper<InlineDeviceSwitchesPass, OperationPass<FuncOp>> {
public:
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<IREEDialect>();
}
StringRef getArgument() const override {
return "iree-hal-inline-device-switches";
}
StringRef getDescription() const override {
return "Inlines hal.device.switch condition regions";
}
void runOnOperation() override {
auto funcOp = getOperation();
SmallVector<IREE::HAL::DeviceSwitchOp, 4> switchOps;
funcOp.walk([&](IREE::HAL::DeviceSwitchOp switchOp) {
switchOps.push_back(switchOp);
});
for (auto switchOp : switchOps) {
OpBuilder funcBuilder(switchOp);
buildConditionDispatchTable(switchOp, funcBuilder);
switchOp.erase();
}
}
};
std::unique_ptr<OperationPass<FuncOp>> createInlineDeviceSwitchesPass() {
return std::make_unique<InlineDeviceSwitchesPass>();
}
static PassRegistration<InlineDeviceSwitchesPass> pass;
} // namespace HAL
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
<|endoftext|>
|
<commit_before>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.
#ifndef POSEIDON_CORE_ABSTRACT_TIMER_
#define POSEIDON_CORE_ABSTRACT_TIMER_
#include "../fwd.hpp"
namespace poseidon {
class Abstract_Timer
{
friend class Timer_Driver;
private:
atomic_relaxed<Async_State> m_async_state = { async_state_null };
atomic_relaxed<uint64_t> m_count = { 0 };
// These fields are used internally by the timer driver.
uint64_t m_serial;
public:
// Constructs a timer whose count is zero.
Abstract_Timer() noexcept;
protected:
// This callback is invoked by the timer thread and is intended to be
// overriden by derived classes. `now` is the number of milliseconds
// since system startup.
virtual
void
do_abstract_timer_on_tick(int64_t now)
= 0;
public:
ASTERIA_NONCOPYABLE_VIRTUAL_DESTRUCTOR(Abstract_Timer);
// Gets the schedule state.
Async_State
async_state() const noexcept
{ return this->m_async_state.load(); }
// Gets the number of times that this timer has been triggered.
uint64_t
count() const noexcept
{ return this->m_count.load(); }
};
} // namespace
#endif
<commit_msg>abstract_timer: Reorder a declaration<commit_after>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.
#ifndef POSEIDON_CORE_ABSTRACT_TIMER_
#define POSEIDON_CORE_ABSTRACT_TIMER_
#include "../fwd.hpp"
namespace poseidon {
class Abstract_Timer
{
private:
friend class Timer_Driver;
atomic_relaxed<Async_State> m_async_state = { async_state_null };
atomic_relaxed<uint64_t> m_count = { 0 };
// These fields are used internally by the timer driver.
uint64_t m_serial;
public:
// Constructs a timer whose count is zero.
Abstract_Timer() noexcept;
protected:
// This callback is invoked by the timer thread and is intended to be
// overriden by derived classes. `now` is the number of milliseconds
// since system startup.
virtual
void
do_abstract_timer_on_tick(int64_t now)
= 0;
public:
ASTERIA_NONCOPYABLE_VIRTUAL_DESTRUCTOR(Abstract_Timer);
// Gets the schedule state.
Async_State
async_state() const noexcept
{ return this->m_async_state.load(); }
// Gets the number of times that this timer has been triggered.
uint64_t
count() const noexcept
{ return this->m_count.load(); }
};
} // namespace
#endif
<|endoftext|>
|
<commit_before>#include <string>
#include <functional>
#include <Console.h>
#include <CPU.h>
#include <APU.h>
#include <PPU.h>
#include <Cart.h>
#include <Controller.h>
#include <Divider.h>
void Console::boot() {
ReadBus cpuReadCallback = [this] (uint16_t addr) {
return cpuRead(addr);
};
WriteBus cpuWriteCallback = [this] (uint16_t addr, uint8_t data) {
cpuWrite(addr,data);
};
cpu.boot(cpuReadCallback, cpuWriteCallback);
NMI nmiCallback = [this] () {cpu.signalNMI();};
ppu.boot(&cart, nmiCallback);
}
bool Console::loadINesFile(std::string fileName) {
return cart.loadFile(fileName);
}
uint32_t *Console::getFrameBuffer() {
return ppu.getFrameBuffer();
}
void Console::runForOneFrame() {
do {
tick();
} while (!ppu.endOfFrame());
apu.endFrame();
}
void Console::tick() {
cpuDivider.tick();
if (cpuDivider.hasClocked()) {
cpu.tick();
}
ppu.tick();
}
uint8_t Console::cpuRead(uint16_t addr) {
if (addr < 0x2000) {
return cpuRam[addr % 0x800];
}
else if (addr < 0x4000) {
int port = addr % 8;
switch (port) {
case 0: // 0x2000
return cpuBusMDR;
case 1: // 0x2001
return cpuBusMDR;
case 2: // 0x2002
return ppu.getSTATUS();
case 3: // 0x2003
return cpuBusMDR;
case 4: // 0x2004
return ppu.getOAMDATA();
case 5: // 0x2005
return cpuBusMDR;
case 6: // 0x2006
return cpuBusMDR;
case 7: // 0x2007
return ppu.getDATA();
}
}
else if (addr < 0x4020) {
switch (addr) {
case 0x4015:
return apu.getStatus();
case 0x4016:
return controller1.poll();
case 0x4017: // TODO: controller 2
return 0;
default: // disabled/unused APU test registers
return cpuBusMDR;
}
}
else {
return cart.readPrg(addr);
}
}
void Console::cpuWrite(uint16_t addr, uint8_t value) {
cpuBusMDR = value;
if (addr < 0x2000) {
cpuRam[addr % 0x800] = value;
}
else if (addr < 0x4000) {
int port = addr % 8;
switch (port) {
case 0: // 0x2000
ppu.setCTRL(value);
break;
case 1: // 0x2001
ppu.setMASK(value);
break;
case 2: // 0x2002
break;
case 3: // 0x2003
ppu.setOAMADDR(value);
break;
case 4: // 0x2004
ppu.setOAMDATA(value);
break;
case 5: // 0x2005
ppu.setSCROLL(value);
break;
case 6: // 0x2006
ppu.setADDR(value);
break;
case 7: // 0x2007
ppu.setDATA(value);
break;
}
}
else if (addr < 0x4020) {
if (addr == 0x4014) {
uint16_t startAddr = ((uint16_t)value) << 8;
for (int i = 0; i < 256; ++i) {
ppu.setOAMDATA(cpuRead(startAddr + i));
}
cpu.suspend(514);
}
else if (addr == 0x4016) {
controller1.setStrobe(!!(value & 0x1));
}
else if (addr < 0x4018) {
apu.writeRegister(addr, value);
}
}
else {
cart.writePrg(addr, value);
}
}
<commit_msg>Rewrite cpu read and write methods for readability<commit_after>#include <string>
#include <functional>
#include <Console.h>
#include <CPU.h>
#include <APU.h>
#include <PPU.h>
#include <Cart.h>
#include <Controller.h>
#include <Divider.h>
void Console::boot() {
ReadBus cpuReadCallback = [this] (uint16_t addr) {
return cpuRead(addr);
};
WriteBus cpuWriteCallback = [this] (uint16_t addr, uint8_t data) {
cpuWrite(addr,data);
};
cpu.boot(cpuReadCallback, cpuWriteCallback);
NMI nmiCallback = [this] () {cpu.signalNMI();};
ppu.boot(&cart, nmiCallback);
}
bool Console::loadINesFile(std::string fileName) {
return cart.loadFile(fileName);
}
uint32_t *Console::getFrameBuffer() {
return ppu.getFrameBuffer();
}
void Console::runForOneFrame() {
do {
tick();
} while (!ppu.endOfFrame());
apu.endFrame();
}
void Console::tick() {
cpuDivider.tick();
if (cpuDivider.hasClocked()) {
cpu.tick();
}
ppu.tick();
}
uint8_t Console::cpuRead(uint16_t addr) {
if (addr < 0x2000) {
return cpuRam[addr % 0x800];
}
else if (addr < 0x4000) {
int registerAddr = addr & 0x2007;
switch (registerAddr) {
case 0x2000: return cpuBusMDR;
case 0x2001: return cpuBusMDR;
case 0x2002: return ppu.getSTATUS();
case 0x2003: return cpuBusMDR;
case 0x2004: return ppu.getOAMDATA();
case 0x2005: return cpuBusMDR;
case 0x2006: return cpuBusMDR;
case 0x2007: return ppu.getDATA();
}
}
else if (addr < 0x4018) {
switch (addr) {
case 0x4015: return apu.getStatus();
case 0x4016: return controller1.poll();
case 0x4017: return 0; // TODO: controller 2
}
}
else if (addr < 0x4020) {
return cpuBusMDR; // disabled/unused APU test registers
}
else {
return cart.readPrg(addr);
}
}
void Console::cpuWrite(uint16_t addr, uint8_t value) {
cpuBusMDR = value;
if (addr < 0x2000) {
cpuRam[addr % 0x800] = value;
}
else if (addr < 0x4000) {
int registerAddr = addr & 0x2007;
switch (registerAddr) {
case 0x2000: ppu.setCTRL(value); break;
case 0x2001: ppu.setMASK(value); break;
case 0x2002: break; // ppu status, read-only
case 0x2003: ppu.setOAMADDR(value); break;
case 0x2004: ppu.setOAMDATA(value); break;
case 0x2005: ppu.setSCROLL(value); break;
case 0x2006: ppu.setADDR(value); break;
case 0x2007: ppu.setDATA(value); break;
}
}
else if (addr < 0x4018) {
switch (addr) {
case 0x4014: {
uint16_t startAddr = ((uint16_t)value) << 8;
for (int i = 0; i < 256; ++i) {
ppu.setOAMDATA(cpuRead(startAddr + i));
}
cpu.suspend(514);
} break;
case 0x4016: controller1.setStrobe(!!(value & 0x1)); break;
default: apu.writeRegister(addr, value); break;
}
}
else if (addr < 0x4020) {
return; // disabled/unused APU test registers
}
else {
cart.writePrg(addr, value);
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iceoryx_dds/gateway/toml_gateway_config_parser.hpp"
#include "stubs/stubbed_toml_gateway_config_parser.hpp"
#include "test.hpp"
using namespace ::testing;
using ::testing::_;
// ======================================== Helpers ======================================== //
// ======================================== Fixture ======================================== //
class TomlGatewayConfigParserTest : public Test
{
public:
void SetUp(){};
void TearDown(){};
};
// ======================================== Tests ======================================== //
TEST_F(TomlGatewayConfigParserTest, PassesValidationIfValidCharactersUsedInServiceDescription)
{
// ===== Setup
// Prepare configuration to test with
auto toml = cpptoml::make_table();
auto serviceArray = cpptoml::make_table_array();
auto serviceEntry = cpptoml::make_table();
serviceEntry->insert("service", "service");
serviceEntry->insert("instance", "instance");
serviceEntry->insert("event", "event");
serviceEntry->insert("size", 0);
serviceArray->push_back(serviceEntry);
auto serviceEntryUppercase = cpptoml::make_table();
serviceEntryUppercase->insert("service", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
serviceEntryUppercase->insert("instance", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
serviceEntryUppercase->insert("event", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
serviceEntryUppercase->insert("size", 0);
serviceArray->push_back(serviceEntryUppercase);
auto serviceEntryLowercase = cpptoml::make_table();
serviceEntryLowercase->insert("service", "abcdefghijklmnopqrstuvwxyz");
serviceEntryLowercase->insert("instance", "abcdefghijklmnopqrstuvwxyz");
serviceEntryLowercase->insert("event", "abcdefghijklmnopqrstuvwxyz");
serviceEntryLowercase->insert("size", 0);
serviceArray->push_back(serviceEntryLowercase);
auto serviceEntryNumbers = cpptoml::make_table();
serviceEntryNumbers->insert("service", "Number1234567890");
serviceEntryNumbers->insert("instance", "Number1234567890");
serviceEntryNumbers->insert("event", "Number1234567890");
serviceEntryNumbers->insert("size", 0);
serviceArray->push_back(serviceEntryNumbers);
auto serviceEntryUnderscore = cpptoml::make_table();
serviceEntryUnderscore->insert("service", "service_name");
serviceEntryUnderscore->insert("instance", "instance_name");
serviceEntryUnderscore->insert("event", "event_name");
serviceEntryUnderscore->insert("size", 0);
serviceArray->push_back(serviceEntryUnderscore);
auto serviceEntryBeginsWithUnderscore = cpptoml::make_table();
serviceEntryBeginsWithUnderscore->insert("service", "_service_name");
serviceEntryBeginsWithUnderscore->insert("instance", "_instance_name");
serviceEntryBeginsWithUnderscore->insert("event", "_event_name");
serviceEntryBeginsWithUnderscore->insert("size", 0);
serviceArray->push_back(serviceEntryBeginsWithUnderscore);
toml->insert("services", serviceArray);
// ===== Test
auto result = iox::dds::StubbedTomlGatewayConfigParser::validate(*toml);
EXPECT_EQ(false, result.has_error());
}
TEST_F(TomlGatewayConfigParserTest, FailsValidationIfNoServiceNameInServiceDescription)
{
// ===== Setup
// Prepare configuration to test with
auto toml = cpptoml::make_table();
auto serviceArray = cpptoml::make_table_array();
auto serviceEntryNoServiceName = cpptoml::make_table();
serviceEntryNoServiceName->insert("instance", "instance");
serviceEntryNoServiceName->insert("event", "event");
serviceEntryNoServiceName->insert("size", 0);
serviceArray->push_back(serviceEntryNoServiceName);
toml->insert("services", serviceArray);
// ===== Test
auto result = iox::dds::StubbedTomlGatewayConfigParser::validate(*toml);
EXPECT_EQ(true, result.has_error());
if (result.has_error())
{
EXPECT_EQ(iox::dds::TomlGatewayConfigParseError::INCOMPLETE_SERVICE_DESCRIPTION, result.get_error());
}
}
TEST_F(TomlGatewayConfigParserTest, FailsValidationIfNoInstanceNameInServiceDescription)
{
// ===== Setup
// Prepare configuration to test with
auto toml = cpptoml::make_table();
auto serviceArray = cpptoml::make_table_array();
auto serviceEntryNoInstanceName = cpptoml::make_table();
serviceEntryNoInstanceName->insert("service", "service");
serviceEntryNoInstanceName->insert("event", "event");
serviceEntryNoInstanceName->insert("size", 0);
serviceArray->push_back(serviceEntryNoInstanceName);
toml->insert("services", serviceArray);
// ===== Test
auto result = iox::dds::StubbedTomlGatewayConfigParser::validate(*toml);
EXPECT_EQ(true, result.has_error());
if (result.has_error())
{
EXPECT_EQ(iox::dds::TomlGatewayConfigParseError::INCOMPLETE_SERVICE_DESCRIPTION, result.get_error());
}
}
TEST_F(TomlGatewayConfigParserTest, FailsValidationIfNoEventNameInServiceDescription)
{
// ===== Setup
// Prepare configuration to test with
auto toml = cpptoml::make_table();
auto serviceArray = cpptoml::make_table_array();
auto serviceEntryNoEventName = cpptoml::make_table();
serviceEntryNoEventName->insert("service", "service");
serviceEntryNoEventName->insert("instance", "instance");
serviceEntryNoEventName->insert("size", 0);
serviceArray->push_back(serviceEntryNoEventName);
toml->insert("services", serviceArray);
// ===== Test
auto result = iox::dds::StubbedTomlGatewayConfigParser::validate(*toml);
EXPECT_EQ(true, result.has_error());
if (result.has_error())
{
EXPECT_EQ(iox::dds::TomlGatewayConfigParseError::INCOMPLETE_SERVICE_DESCRIPTION, result.get_error());
}
}
TEST_F(TomlGatewayConfigParserTest, FailsValidationIfNoDataSize)
{
// ===== Setup
// Prepare configuration to test with
auto toml = cpptoml::make_table();
auto serviceArray = cpptoml::make_table_array();
auto serviceEntryNoSize = cpptoml::make_table();
serviceEntryNoSize->insert("service", "service");
serviceEntryNoSize->insert("instance", "instance");
serviceEntryNoSize->insert("event", "event");
serviceArray->push_back(serviceEntryNoSize);
toml->insert("services", serviceArray);
// ===== Test
auto result = iox::dds::StubbedTomlGatewayConfigParser::validate(*toml);
EXPECT_EQ(true, result.has_error());
if (result.has_error())
{
EXPECT_EQ(iox::dds::TomlGatewayConfigParseError::INCOMPLETE_SERVICE_DESCRIPTION, result.get_error());
}
}
TEST_F(TomlGatewayConfigParserTest, FailsValidationIfServiceDescriptionBeginsWithNumber)
{
// ===== Setup
// Prepare configuration to test with
auto toml = cpptoml::make_table();
auto serviceArray = cpptoml::make_table_array();
auto serviceBeginsWithNumber = cpptoml::make_table();
serviceBeginsWithNumber->insert("service", "0000");
serviceBeginsWithNumber->insert("instance", "0000");
serviceBeginsWithNumber->insert("event", "0000");
serviceBeginsWithNumber->insert("size", 0);
serviceArray->push_back(serviceBeginsWithNumber);
toml->insert("services", serviceArray);
// ===== Test
auto result = iox::dds::StubbedTomlGatewayConfigParser::validate(*toml);
EXPECT_EQ(true, result.has_error());
if (result.has_error())
{
EXPECT_EQ(iox::dds::TomlGatewayConfigParseError::INVALID_SERVICE_DESCRIPTION, result.get_error());
}
}
// This is a common error due to a typo in the DDS spec, therefore tested for explicitly.
TEST_F(TomlGatewayConfigParserTest, FailsValidationIfHyphenInServiceDescription)
{
// ===== Setup
// Prepare configuration to test with
auto toml = cpptoml::make_table();
auto serviceArray = cpptoml::make_table_array();
auto serviceEntry = cpptoml::make_table();
serviceEntry->insert("service", "service-name");
serviceEntry->insert("instance", "instance-name");
serviceEntry->insert("event", "event-name");
serviceEntry->insert("size", 0);
serviceArray->push_back(serviceEntry);
toml->insert("services", serviceArray);
// ===== Test
auto result = iox::dds::StubbedTomlGatewayConfigParser::validate(*toml);
EXPECT_EQ(true, result.has_error());
if (result.has_error())
{
EXPECT_EQ(iox::dds::TomlGatewayConfigParseError::INVALID_SERVICE_DESCRIPTION, result.get_error());
}
}
TEST_F(TomlGatewayConfigParserTest, FailsValidationIfNoServicesInConfig)
{
// ===== Setup
// Prepare configuration to test with
auto toml = cpptoml::make_table();
// ===== Test
auto result = iox::dds::StubbedTomlGatewayConfigParser::validate(*toml);
EXPECT_EQ(true, result.has_error());
if (result.has_error())
{
EXPECT_EQ(iox::dds::TomlGatewayConfigParseError::INCOMPLETE_CONFIGURATION, result.get_error());
}
}
<commit_msg>iox-#109 Remove outdated test.<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iceoryx_dds/gateway/toml_gateway_config_parser.hpp"
#include "stubs/stubbed_toml_gateway_config_parser.hpp"
#include "test.hpp"
using namespace ::testing;
using ::testing::_;
// ======================================== Helpers ======================================== //
// ======================================== Fixture ======================================== //
class TomlGatewayConfigParserTest : public Test
{
public:
void SetUp(){};
void TearDown(){};
};
// ======================================== Tests ======================================== //
TEST_F(TomlGatewayConfigParserTest, PassesValidationIfValidCharactersUsedInServiceDescription)
{
// ===== Setup
// Prepare configuration to test with
auto toml = cpptoml::make_table();
auto serviceArray = cpptoml::make_table_array();
auto serviceEntry = cpptoml::make_table();
serviceEntry->insert("service", "service");
serviceEntry->insert("instance", "instance");
serviceEntry->insert("event", "event");
serviceEntry->insert("size", 0);
serviceArray->push_back(serviceEntry);
auto serviceEntryUppercase = cpptoml::make_table();
serviceEntryUppercase->insert("service", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
serviceEntryUppercase->insert("instance", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
serviceEntryUppercase->insert("event", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
serviceEntryUppercase->insert("size", 0);
serviceArray->push_back(serviceEntryUppercase);
auto serviceEntryLowercase = cpptoml::make_table();
serviceEntryLowercase->insert("service", "abcdefghijklmnopqrstuvwxyz");
serviceEntryLowercase->insert("instance", "abcdefghijklmnopqrstuvwxyz");
serviceEntryLowercase->insert("event", "abcdefghijklmnopqrstuvwxyz");
serviceEntryLowercase->insert("size", 0);
serviceArray->push_back(serviceEntryLowercase);
auto serviceEntryNumbers = cpptoml::make_table();
serviceEntryNumbers->insert("service", "Number1234567890");
serviceEntryNumbers->insert("instance", "Number1234567890");
serviceEntryNumbers->insert("event", "Number1234567890");
serviceEntryNumbers->insert("size", 0);
serviceArray->push_back(serviceEntryNumbers);
auto serviceEntryUnderscore = cpptoml::make_table();
serviceEntryUnderscore->insert("service", "service_name");
serviceEntryUnderscore->insert("instance", "instance_name");
serviceEntryUnderscore->insert("event", "event_name");
serviceEntryUnderscore->insert("size", 0);
serviceArray->push_back(serviceEntryUnderscore);
auto serviceEntryBeginsWithUnderscore = cpptoml::make_table();
serviceEntryBeginsWithUnderscore->insert("service", "_service_name");
serviceEntryBeginsWithUnderscore->insert("instance", "_instance_name");
serviceEntryBeginsWithUnderscore->insert("event", "_event_name");
serviceEntryBeginsWithUnderscore->insert("size", 0);
serviceArray->push_back(serviceEntryBeginsWithUnderscore);
toml->insert("services", serviceArray);
// ===== Test
auto result = iox::dds::StubbedTomlGatewayConfigParser::validate(*toml);
EXPECT_EQ(false, result.has_error());
}
TEST_F(TomlGatewayConfigParserTest, FailsValidationIfNoServiceNameInServiceDescription)
{
// ===== Setup
// Prepare configuration to test with
auto toml = cpptoml::make_table();
auto serviceArray = cpptoml::make_table_array();
auto serviceEntryNoServiceName = cpptoml::make_table();
serviceEntryNoServiceName->insert("instance", "instance");
serviceEntryNoServiceName->insert("event", "event");
serviceEntryNoServiceName->insert("size", 0);
serviceArray->push_back(serviceEntryNoServiceName);
toml->insert("services", serviceArray);
// ===== Test
auto result = iox::dds::StubbedTomlGatewayConfigParser::validate(*toml);
EXPECT_EQ(true, result.has_error());
if (result.has_error())
{
EXPECT_EQ(iox::dds::TomlGatewayConfigParseError::INCOMPLETE_SERVICE_DESCRIPTION, result.get_error());
}
}
TEST_F(TomlGatewayConfigParserTest, FailsValidationIfNoInstanceNameInServiceDescription)
{
// ===== Setup
// Prepare configuration to test with
auto toml = cpptoml::make_table();
auto serviceArray = cpptoml::make_table_array();
auto serviceEntryNoInstanceName = cpptoml::make_table();
serviceEntryNoInstanceName->insert("service", "service");
serviceEntryNoInstanceName->insert("event", "event");
serviceEntryNoInstanceName->insert("size", 0);
serviceArray->push_back(serviceEntryNoInstanceName);
toml->insert("services", serviceArray);
// ===== Test
auto result = iox::dds::StubbedTomlGatewayConfigParser::validate(*toml);
EXPECT_EQ(true, result.has_error());
if (result.has_error())
{
EXPECT_EQ(iox::dds::TomlGatewayConfigParseError::INCOMPLETE_SERVICE_DESCRIPTION, result.get_error());
}
}
TEST_F(TomlGatewayConfigParserTest, FailsValidationIfNoEventNameInServiceDescription)
{
// ===== Setup
// Prepare configuration to test with
auto toml = cpptoml::make_table();
auto serviceArray = cpptoml::make_table_array();
auto serviceEntryNoEventName = cpptoml::make_table();
serviceEntryNoEventName->insert("service", "service");
serviceEntryNoEventName->insert("instance", "instance");
serviceEntryNoEventName->insert("size", 0);
serviceArray->push_back(serviceEntryNoEventName);
toml->insert("services", serviceArray);
// ===== Test
auto result = iox::dds::StubbedTomlGatewayConfigParser::validate(*toml);
EXPECT_EQ(true, result.has_error());
if (result.has_error())
{
EXPECT_EQ(iox::dds::TomlGatewayConfigParseError::INCOMPLETE_SERVICE_DESCRIPTION, result.get_error());
}
}
TEST_F(TomlGatewayConfigParserTest, FailsValidationIfServiceDescriptionBeginsWithNumber)
{
// ===== Setup
// Prepare configuration to test with
auto toml = cpptoml::make_table();
auto serviceArray = cpptoml::make_table_array();
auto serviceBeginsWithNumber = cpptoml::make_table();
serviceBeginsWithNumber->insert("service", "0000");
serviceBeginsWithNumber->insert("instance", "0000");
serviceBeginsWithNumber->insert("event", "0000");
serviceBeginsWithNumber->insert("size", 0);
serviceArray->push_back(serviceBeginsWithNumber);
toml->insert("services", serviceArray);
// ===== Test
auto result = iox::dds::StubbedTomlGatewayConfigParser::validate(*toml);
EXPECT_EQ(true, result.has_error());
if (result.has_error())
{
EXPECT_EQ(iox::dds::TomlGatewayConfigParseError::INVALID_SERVICE_DESCRIPTION, result.get_error());
}
}
// This is a common error due to a typo in the DDS spec, therefore tested for explicitly.
TEST_F(TomlGatewayConfigParserTest, FailsValidationIfHyphenInServiceDescription)
{
// ===== Setup
// Prepare configuration to test with
auto toml = cpptoml::make_table();
auto serviceArray = cpptoml::make_table_array();
auto serviceEntry = cpptoml::make_table();
serviceEntry->insert("service", "service-name");
serviceEntry->insert("instance", "instance-name");
serviceEntry->insert("event", "event-name");
serviceEntry->insert("size", 0);
serviceArray->push_back(serviceEntry);
toml->insert("services", serviceArray);
// ===== Test
auto result = iox::dds::StubbedTomlGatewayConfigParser::validate(*toml);
EXPECT_EQ(true, result.has_error());
if (result.has_error())
{
EXPECT_EQ(iox::dds::TomlGatewayConfigParseError::INVALID_SERVICE_DESCRIPTION, result.get_error());
}
}
TEST_F(TomlGatewayConfigParserTest, FailsValidationIfNoServicesInConfig)
{
// ===== Setup
// Prepare configuration to test with
auto toml = cpptoml::make_table();
// ===== Test
auto result = iox::dds::StubbedTomlGatewayConfigParser::validate(*toml);
EXPECT_EQ(true, result.has_error());
if (result.has_error())
{
EXPECT_EQ(iox::dds::TomlGatewayConfigParseError::INCOMPLETE_CONFIGURATION, result.get_error());
}
}
<|endoftext|>
|
<commit_before>/* The MIT License
Copyright (c) 2014 Adrian Tan <atks@umich.edu>
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 "profile_len.h"
namespace
{
struct len_t
{
int32_t dlen;
float maf;
int32_t no_alleles;
int32_t pass;
float ab;
int32_t coding;
};
class Igor : Program
{
public:
std::string version;
///////////
//options//
///////////
std::string input_vcf_file;
std::string output_dir;
std::string output_pdf_file;
const char* AF;
const char* AB;
const char* GENCODE_NFS;
const char* GENCODE_FS;
std::vector<GenomeInterval> intervals;
std::string interval_list;
///////
//i/o//
///////
BCFOrderedReader *odr;
///////////////
//general use//
///////////////
std::vector<len_t> len_pts;
//////////
//filter//
//////////
std::string fexp;
Filter filter;
bool filter_exists;
/////////
//stats//
/////////
uint32_t no_variants;
/////////
//tools//
/////////
Pedigree *pedigree;
VariantManip *vm;
Igor(int argc, char ** argv)
{
//////////////////////////
//options initialization//
//////////////////////////
try
{
std::string desc = "Profile length distribution";
version = "0.5";
TCLAP::CmdLine cmd(desc, ' ', version);
VTOutput my; cmd.setOutput(&my);
TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals", false, "", "str", cmd);
TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "str", cmd);
TCLAP::ValueArg<std::string> arg_fexp("f", "f", "filter expression []", false, "", "str", cmd);
TCLAP::ValueArg<std::string> arg_output_dir("x", "x", "output directory []", false, "plot_len", "str", cmd);
TCLAP::ValueArg<std::string> arg_output_pdf_file("y", "y", "output PDF file []", false, "len.pdf", "str", cmd);
TCLAP::ValueArg<std::string> arg_AF("a", "af", "AF tag [AF]", false, "AF", "str", cmd);
TCLAP::ValueArg<std::string> arg_AB("b", "ab", "AB tag [AB]", false, "AB", "str", cmd);
TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file("<in.vcf>", "input VCF file", true, "","file", cmd);
cmd.parse(argc, argv);
input_vcf_file = arg_input_vcf_file.getValue();
fexp = arg_fexp.getValue();
output_dir = arg_output_dir.getValue();
output_pdf_file = arg_output_pdf_file.getValue();
AF = strdup(arg_AF.getValue().c_str());
AB = strdup(arg_AB.getValue().c_str());
parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue());
}
catch (TCLAP::ArgException &e)
{
std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n";
abort();
}
};
void initialize()
{
//////////////////////
//i/o initialization//
//////////////////////
odr = new BCFOrderedReader(input_vcf_file, intervals);
/////////////////////////
//filter initialization//
/////////////////////////
filter.parse(fexp.c_str());
filter_exists = fexp=="" ? false : true;
////////////////////////
//stats initialization//
////////////////////////
no_variants = 0;
/////////
//tools//
/////////
vm = new VariantManip();
}
void profile_len()
{
bcf1_t *v = bcf_init1();
Variant variant;
float *af=NULL, *ab=NULL;
int32_t n_af=0, n_ab=0;
while(odr->read(v))
{
bcf_unpack(v, BCF_UN_ALL);
if (bcf_get_n_allele(v)!=2)
{
continue;
}
vm->classify_variant(odr->hdr, v, variant);
if (filter_exists)
{
if (!filter.apply(odr->hdr, v, &variant))
{
continue;
}
}
int32_t dlen = variant.alleles[0].dlen;
bcf_get_info_float(odr->hdr, v, AF, &af, &n_af);
int32_t no_alleles = bcf_get_n_allele(v);
int32_t pass = bcf_has_filter(odr->hdr, v, const_cast<char*>("PASS"));
bcf_get_info_float(odr->hdr, v, AB, &ab, &n_ab);
int32_t fs = bcf_get_info_flag(odr->hdr,v, const_cast<char*>("GENCODE_FS"), 0, 0);
int32_t nfs = bcf_get_info_flag(odr->hdr,v, const_cast<char*>("GENCODE_NFS"), 0, 0);
int32_t coding = fs==1 ? 1 : (nfs==1 ? 2 : -1);
float maf = 0;
if (no_alleles==2)
{
maf = af[0]>0.5? 1-af[0]: af[0];
}
else
{
for (size_t i=0; i<n_af; ++i)
{
maf += af[i];
}
maf = maf>0.5? 1-maf: maf;
}
len_t h = {dlen, maf, no_alleles, pass, ab[0], coding};
len_pts.push_back(h);
++no_variants;
}
if (n_af) free(af);
if (n_ab) free(ab);
odr->close();
};
void print_options()
{
std::clog << "plot_len v" << version << "\n\n";
std::clog << "options: input VCF file " << input_vcf_file << "\n";
std::clog << " [a] AF tag " << AF << "\n";
std::clog << " [b] AB tag " << AB << "\n";
print_str_op(" [x] output directory ", output_dir);
print_str_op(" [y] output pdf file ", output_pdf_file);
print_int_op(" [i] intervals ", intervals);
std::clog << "\n";
}
void print_pdf()
{
append_cwd(output_dir);
//create directory
mkdir(output_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
//create data file
std::string file_path = output_dir + "/data.txt";
FILE *out = fopen(file_path.c_str(), "w");
fprintf(out, "dlen\tmaf\tno_alleles\tpass\tab\tcoding\n");
for (size_t i=0; i<len_pts.size(); ++i)
{
fprintf(out, "%d\t%f\t%d\t%d\t%f\t%d\n", len_pts[i].dlen, len_pts[i].maf, len_pts[i].no_alleles,
len_pts[i].pass, len_pts[i].ab, len_pts[i].coding);
}
fclose(out);
//create r script
file_path = output_dir + "/plot.r";
out = fopen(file_path.c_str(), "w");
fprintf(out, "setwd(\"%s\")\n", output_dir.c_str());
fprintf(out, "\n");
fprintf(out, "data = read.table(\"data.txt\", header=T)\n");
fprintf(out, "\n");
fprintf(out, "pdf(\"%s\",7,5)\n", output_pdf_file.c_str());
fprintf(out, "\n");
fprintf(out, "layout(matrix(c(1,2), 2, 1, byrow = TRUE))\n");
fprintf(out, "data.subset = subset(data, abs(dlen)<=10 & pass==1 & no_alleles==2)\n");
fprintf(out, "hist(data.subset$dlen, breaks=seq(-10,10,1),col=rgb(0,0,1,0.5), xlab=\"length\", main=\"Passed Indel Length Distribution\")\n");
fprintf(out, "\n");
fprintf(out, "data.subset = subset(data, abs(dlen)<=10 & pass!=1 & no_alleles==2)\n");
fprintf(out, "hist(data.subset$dlen, breaks=seq(-10,10,1),col=rgb(1,0,0,0.5), xlab=\"length\", main=\"Failed Indel Length Distribution\")\n");
fprintf(out, "\n");
fprintf(out, "layout(matrix(c(1,2), 2, 1, byrow = TRUE))\n");
fprintf(out, "\n");
fprintf(out, "data.subset = subset(data, abs(dlen)<=10 & pass==1 & no_alleles==2 & coding>0)\n");
fprintf(out, "hist(data.subset$dlen, breaks=seq(-10,10,1),col=rgb(0,0,1,0.5), xlab=\"length\", main=\"Passed Coding Indel Length Distribution\")\n");
fprintf(out, "\n");
fprintf(out, "data.subset = subset(data, abs(dlen)<=10 & pass!=1 & no_alleles==2 & coding>0)\n");
fprintf(out, "hist(data.subset$dlen, breaks=seq(-10,10,1),col=rgb(1,0,0,0.5), xlab=\"length\", main=\"Failed Coding Indel Length Distribution\")\n");
fprintf(out, "\n");
fprintf(out, "layout(matrix(c(1,2), 1, 2, byrow = TRUE))\n");
fprintf(out, "data.subset = subset(data, dlen>0 & pass!=1 & no_alleles==2)\n");
fprintf(out, "x = table(abs(data.subset$dlen))/nrow(data.subset)\n");
fprintf(out, "pie(x, main=\"Passed Indel Length Proportion\")\n");
fprintf(out, "\n");
fprintf(out, "data.subset = subset(data, dlen<0 & pass!=1 & no_alleles==2)\n");
fprintf(out, "x = table(abs(data.subset$dlen))/nrow(data.subset)\n");
fprintf(out, "pie(x, main=\"Failed Indel Length Proportion\")\n");
fprintf(out, "\n");
fprintf(out, "layout(matrix(c(1,1), 2, 1, byrow = TRUE))\n");
fprintf(out, "\n");
fprintf(out, "data.subset = subset(data, abs(dlen)<=30 & pass==1 & no_alleles==2)\n");
fprintf(out, "boxplot(data.subset$ab~data.subset$dlen, col=rgb(0,0,1,0.5), pch=\".\", main=\"Passed Indel Allele Balance Profile\")\n");
fprintf(out, "abline(h=0.5, col=\"grey\")\n");
fprintf(out, "\n");
fprintf(out, "layout(matrix(c(1,1), 2, 1, byrow = TRUE))\n");
fprintf(out, "\n");
fprintf(out, "data.subset = subset(data, abs(dlen)<=30 & pass!=1 & no_alleles==2)\n");
fprintf(out, "boxplot(data.subset$ab~data.subset$dlen, col=rgb(1,0,0,0.5), pch=\".\", main=\"Failed Indel Allele Balance Profile\")\n");
fprintf(out, "abline(h=0.5, col=\"grey\")\n");
fprintf(out, "\n");
fprintf(out, "dev.off()\n");
fclose(out);
//run script
std::string cmd = "cd " + output_dir + "; cat plot.r | R --vanilla > run.log";
system(cmd.c_str());
};
void print_stats()
{
fprintf(stderr, "Stats \n");
fprintf(stderr, " no. of variants : %d\n", no_variants);
fprintf(stderr, "\n");
//do a textual histogram print out of afs
};
~Igor()
{
};
private:
};
}
void profile_len(int argc, char ** argv)
{
Igor igor(argc, argv);
igor.print_options();
igor.initialize();
igor.profile_len();
igor.print_stats();
igor.print_pdf();
}
<commit_msg>tweaked profile_len AB plot<commit_after>/* The MIT License
Copyright (c) 2014 Adrian Tan <atks@umich.edu>
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 "profile_len.h"
namespace
{
struct len_t
{
int32_t dlen;
float maf;
int32_t no_alleles;
int32_t pass;
float ab;
int32_t coding;
};
class Igor : Program
{
public:
std::string version;
///////////
//options//
///////////
std::string input_vcf_file;
std::string output_dir;
std::string output_pdf_file;
const char* AF;
const char* AB;
const char* GENCODE_NFS;
const char* GENCODE_FS;
std::vector<GenomeInterval> intervals;
std::string interval_list;
///////
//i/o//
///////
BCFOrderedReader *odr;
///////////////
//general use//
///////////////
std::vector<len_t> len_pts;
//////////
//filter//
//////////
std::string fexp;
Filter filter;
bool filter_exists;
/////////
//stats//
/////////
uint32_t no_variants;
/////////
//tools//
/////////
Pedigree *pedigree;
VariantManip *vm;
Igor(int argc, char ** argv)
{
//////////////////////////
//options initialization//
//////////////////////////
try
{
std::string desc = "Profile length distribution";
version = "0.5";
TCLAP::CmdLine cmd(desc, ' ', version);
VTOutput my; cmd.setOutput(&my);
TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals", false, "", "str", cmd);
TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "str", cmd);
TCLAP::ValueArg<std::string> arg_fexp("f", "f", "filter expression []", false, "", "str", cmd);
TCLAP::ValueArg<std::string> arg_output_dir("x", "x", "output directory []", false, "plot_len", "str", cmd);
TCLAP::ValueArg<std::string> arg_output_pdf_file("y", "y", "output PDF file []", false, "len.pdf", "str", cmd);
TCLAP::ValueArg<std::string> arg_AF("a", "af", "AF tag [AF]", false, "AF", "str", cmd);
TCLAP::ValueArg<std::string> arg_AB("b", "ab", "AB tag [AB]", false, "AB", "str", cmd);
TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file("<in.vcf>", "input VCF file", true, "","file", cmd);
cmd.parse(argc, argv);
input_vcf_file = arg_input_vcf_file.getValue();
fexp = arg_fexp.getValue();
output_dir = arg_output_dir.getValue();
output_pdf_file = arg_output_pdf_file.getValue();
AF = strdup(arg_AF.getValue().c_str());
AB = strdup(arg_AB.getValue().c_str());
parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue());
}
catch (TCLAP::ArgException &e)
{
std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n";
abort();
}
};
void initialize()
{
//////////////////////
//i/o initialization//
//////////////////////
odr = new BCFOrderedReader(input_vcf_file, intervals);
/////////////////////////
//filter initialization//
/////////////////////////
filter.parse(fexp.c_str());
filter_exists = fexp=="" ? false : true;
////////////////////////
//stats initialization//
////////////////////////
no_variants = 0;
/////////
//tools//
/////////
vm = new VariantManip();
}
void profile_len()
{
bcf1_t *v = bcf_init1();
Variant variant;
float *af=NULL, *ab=NULL;
int32_t n_af=0, n_ab=0;
while(odr->read(v))
{
bcf_unpack(v, BCF_UN_ALL);
if (bcf_get_n_allele(v)!=2)
{
continue;
}
vm->classify_variant(odr->hdr, v, variant);
if (filter_exists)
{
if (!filter.apply(odr->hdr, v, &variant))
{
continue;
}
}
int32_t dlen = variant.alleles[0].dlen;
bcf_get_info_float(odr->hdr, v, AF, &af, &n_af);
int32_t no_alleles = bcf_get_n_allele(v);
int32_t pass = bcf_has_filter(odr->hdr, v, const_cast<char*>("PASS"));
bcf_get_info_float(odr->hdr, v, AB, &ab, &n_ab);
int32_t fs = bcf_get_info_flag(odr->hdr,v, const_cast<char*>("GENCODE_FS"), 0, 0);
int32_t nfs = bcf_get_info_flag(odr->hdr,v, const_cast<char*>("GENCODE_NFS"), 0, 0);
int32_t coding = fs==1 ? 1 : (nfs==1 ? 2 : -1);
float maf = 0;
if (no_alleles==2)
{
maf = af[0]>0.5? 1-af[0]: af[0];
}
else
{
for (size_t i=0; i<n_af; ++i)
{
maf += af[i];
}
maf = maf>0.5? 1-maf: maf;
}
len_t h = {dlen, maf, no_alleles, pass, ab[0], coding};
len_pts.push_back(h);
++no_variants;
}
if (n_af) free(af);
if (n_ab) free(ab);
odr->close();
};
void print_options()
{
std::clog << "plot_len v" << version << "\n\n";
std::clog << "options: input VCF file " << input_vcf_file << "\n";
std::clog << " [a] AF tag " << AF << "\n";
std::clog << " [b] AB tag " << AB << "\n";
print_str_op(" [x] output directory ", output_dir);
print_str_op(" [y] output pdf file ", output_pdf_file);
print_int_op(" [i] intervals ", intervals);
std::clog << "\n";
}
void print_pdf()
{
append_cwd(output_dir);
//create directory
mkdir(output_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
//create data file
std::string file_path = output_dir + "/data.txt";
FILE *out = fopen(file_path.c_str(), "w");
fprintf(out, "dlen\tmaf\tno_alleles\tpass\tab\tcoding\n");
for (size_t i=0; i<len_pts.size(); ++i)
{
fprintf(out, "%d\t%f\t%d\t%d\t%f\t%d\n", len_pts[i].dlen, len_pts[i].maf, len_pts[i].no_alleles,
len_pts[i].pass, len_pts[i].ab, len_pts[i].coding);
}
fclose(out);
//create r script
file_path = output_dir + "/plot.r";
out = fopen(file_path.c_str(), "w");
fprintf(out, "setwd(\"%s\")\n", output_dir.c_str());
fprintf(out, "\n");
fprintf(out, "data = read.table(\"data.txt\", header=T)\n");
fprintf(out, "\n");
fprintf(out, "pdf(\"%s\",7,5)\n", output_pdf_file.c_str());
fprintf(out, "\n");
fprintf(out, "layout(matrix(c(1,2), 2, 1, byrow = TRUE))\n");
fprintf(out, "data.subset = subset(data, abs(dlen)<=10 & pass==1 & no_alleles==2)\n");
fprintf(out, "hist(data.subset$dlen, breaks=seq(-10,10,1),col=rgb(0,0,1,0.5), xlab=\"length\", main=\"Passed Indel Length Distribution\")\n");
fprintf(out, "\n");
fprintf(out, "data.subset = subset(data, abs(dlen)<=10 & pass!=1 & no_alleles==2)\n");
fprintf(out, "hist(data.subset$dlen, breaks=seq(-10,10,1),col=rgb(1,0,0,0.5), xlab=\"length\", main=\"Failed Indel Length Distribution\")\n");
fprintf(out, "\n");
fprintf(out, "layout(matrix(c(1,2), 2, 1, byrow = TRUE))\n");
fprintf(out, "\n");
fprintf(out, "data.subset = subset(data, abs(dlen)<=10 & pass==1 & no_alleles==2 & coding>0)\n");
fprintf(out, "hist(data.subset$dlen, breaks=seq(-10,10,1),col=rgb(0,0,1,0.5), xlab=\"length\", main=\"Passed Coding Indel Length Distribution\")\n");
fprintf(out, "\n");
fprintf(out, "data.subset = subset(data, abs(dlen)<=10 & pass!=1 & no_alleles==2 & coding>0)\n");
fprintf(out, "hist(data.subset$dlen, breaks=seq(-10,10,1),col=rgb(1,0,0,0.5), xlab=\"length\", main=\"Failed Coding Indel Length Distribution\")\n");
fprintf(out, "\n");
fprintf(out, "layout(matrix(c(1,2), 1, 2, byrow = TRUE))\n");
fprintf(out, "data.subset = subset(data, dlen>0 & pass!=1 & no_alleles==2)\n");
fprintf(out, "x = table(abs(data.subset$dlen))/nrow(data.subset)\n");
fprintf(out, "pie(x, main=\"Passed Indel Length Proportion\")\n");
fprintf(out, "\n");
fprintf(out, "data.subset = subset(data, dlen<0 & pass!=1 & no_alleles==2)\n");
fprintf(out, "x = table(abs(data.subset$dlen))/nrow(data.subset)\n");
fprintf(out, "pie(x, main=\"Failed Indel Length Proportion\")\n");
fprintf(out, "\n");
fprintf(out, "layout(matrix(c(1,1), 2, 1, byrow = TRUE))\n");
fprintf(out, "\n");
fprintf(out, "data.subset = subset(data, abs(dlen)<=30 & pass==1 & no_alleles==2 & ab<1 & ab>0)\n");
fprintf(out, "boxplot(data.subset$ab~data.subset$dlen, col=rgb(0,0,1,0.5), pch=\".\", main=\"Passed Indel Allele Balance Profile\")\n");
fprintf(out, "abline(h=0.5, col=\"grey\")\n");
fprintf(out, "\n");
fprintf(out, "layout(matrix(c(1,1), 2, 1, byrow = TRUE))\n");
fprintf(out, "\n");
fprintf(out, "data.subset = subset(data, abs(dlen)<=30 & pass!=1 & no_alleles==2 & ab<1 & ab>0)\n");
fprintf(out, "boxplot(data.subset$ab~data.subset$dlen, col=rgb(1,0,0,0.5), pch=\".\", main=\"Failed Indel Allele Balance Profile\")\n");
fprintf(out, "abline(h=0.5, col=\"grey\")\n");
fprintf(out, "\n");
fprintf(out, "dev.off()\n");
fclose(out);
//run script
std::string cmd = "cd " + output_dir + "; cat plot.r | R --vanilla > run.log";
system(cmd.c_str());
};
void print_stats()
{
fprintf(stderr, "Stats \n");
fprintf(stderr, " no. of variants : %d\n", no_variants);
fprintf(stderr, "\n");
//do a textual histogram print out of afs
};
~Igor()
{
};
private:
};
}
void profile_len(int argc, char ** argv)
{
Igor igor(argc, argv);
igor.print_options();
igor.initialize();
igor.profile_len();
igor.print_stats();
igor.print_pdf();
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (c) 2015 Estimation and Control Library (ECL). 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 ECL 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 terrain_estimator.cpp
* Function for fusing rangefinder measurements to estimate terrain vertical position/
*
* @author Paul Riseborough <p_riseborough@live.com.au>
*
*/
#include "ekf.h"
#include "mathlib.h"
bool Ekf::initHagl()
{
// get most recent range measurement from buffer
rangeSample latest_measurement = _range_buffer.get_newest();
if ((_time_last_imu - latest_measurement.time_us) < 2e5 && _R_rng_to_earth_2_2 > 0.7071f) {
// if we have a fresh measurement, use it to initialise the terrain estimator
_terrain_vpos = _state.pos(2) + latest_measurement.rng * _R_rng_to_earth_2_2;
// initialise state variance to variance of measurement
_terrain_var = sq(_params.range_noise);
// success
return true;
} else if (!_control_status.flags.in_air) {
// if on ground we assume a ground clearance
_terrain_vpos = _state.pos(2) + _params.rng_gnd_clearance;
// Use the ground clearance value as our uncertainty
_terrain_var = sq(_params.rng_gnd_clearance);
// ths is a guess
return false;
} else {
// no information - cannot initialise
return false;
}
}
void Ekf::runTerrainEstimator()
{
// Perform a continuity check on range finder data
checkRangeDataContinuity();
// Perform initialisation check
if (!_terrain_initialised) {
_terrain_initialised = initHagl();
} else {
// predict the state variance growth where the state is the vertical position of the terrain underneath the vehicle
// process noise due to errors in vehicle height estimate
_terrain_var += sq(_imu_sample_delayed.delta_vel_dt * _params.terrain_p_noise);
// process noise due to terrain gradient
_terrain_var += sq(_imu_sample_delayed.delta_vel_dt * _params.terrain_gradient) * (sq(_state.vel(0)) + sq(_state.vel(
1)));
// limit the variance to prevent it becoming badly conditioned
_terrain_var = math::constrain(_terrain_var, 0.0f, 1e4f);
// Fuse range finder data if available
if (_range_data_ready) {
fuseHagl();
// update range sensor angle parameters in case they have changed
// we do this here to avoid doing those calculations at a high rate
_sin_tilt_rng = sinf(_params.rng_sens_pitch);
_cos_tilt_rng = cosf(_params.rng_sens_pitch);
}
}
}
void Ekf::fuseHagl()
{
// If the vehicle is excessively tilted, do not try to fuse range finder observations
if (_R_rng_to_earth_2_2 > 0.7071f) {
// get a height above ground measurement from the range finder assuming a flat earth
float meas_hagl = _range_sample_delayed.rng * _R_rng_to_earth_2_2;
// predict the hagl from the vehicle position and terrain height
float pred_hagl = _terrain_vpos - _state.pos(2);
// calculate the innovation
_hagl_innov = pred_hagl - meas_hagl;
// calculate the observation variance adding the variance of the vehicles own height uncertainty
float obs_variance = fmaxf(P[9][9], 0.0f) + sq(_params.range_noise) + sq(_params.range_noise_scaler * _range_sample_delayed.rng);
// calculate the innovation variance - limiting it to prevent a badly conditioned fusion
_hagl_innov_var = fmaxf(_terrain_var + obs_variance, obs_variance);
// perform an innovation consistency check and only fuse data if it passes
float gate_size = fmaxf(_params.range_innov_gate, 1.0f);
_terr_test_ratio = sq(_hagl_innov) / (sq(gate_size) * _hagl_innov_var);
if (_terr_test_ratio <= 1.0f) {
// calculate the Kalman gain
float gain = _terrain_var / _hagl_innov_var;
// correct the state
_terrain_vpos -= gain * _hagl_innov;
// correct the variance
_terrain_var = fmaxf(_terrain_var * (1.0f - gain), 0.0f);
// record last successful fusion event
_time_last_hagl_fuse = _time_last_imu;
_innov_check_fail_status.flags.reject_hagl = false;
} else {
_innov_check_fail_status.flags.reject_hagl = true;
}
} else {
_innov_check_fail_status.flags.reject_hagl = true;
return;
}
}
// return true if the terrain estimate is valid
bool Ekf::get_terrain_valid()
{
if (_terrain_initialised && _range_data_continuous && !_innov_check_fail_status.flags.reject_hagl) {
return true;
} else {
return false;
}
}
// get the estimated vertical position of the terrain relative to the NED origin
void Ekf::get_terrain_vert_pos(float *ret)
{
memcpy(ret, &_terrain_vpos, sizeof(float));
}
void Ekf::get_hagl_innov(float *hagl_innov)
{
memcpy(hagl_innov, &_hagl_innov, sizeof(_hagl_innov));
}
void Ekf::get_hagl_innov_var(float *hagl_innov_var)
{
memcpy(hagl_innov_var, &_hagl_innov_var, sizeof(_hagl_innov_var));
}
// check that the range finder data is continuous
void Ekf::checkRangeDataContinuity()
{
// update range data continuous flag (2Hz ie 500 ms)
/* Timing in micro seconds */
/* Apply a 1.0 sec low pass filter to the time delta from the last range finder updates */
_dt_last_range_update_filt_us = _dt_last_range_update_filt_us * (1.0f - _dt_update) + _dt_update *
(_time_last_imu - _time_last_range);
_dt_last_range_update_filt_us = fminf(_dt_last_range_update_filt_us, 1e6f);
if (_dt_last_range_update_filt_us < 5e5f) {
_range_data_continuous = true;
} else {
_range_data_continuous = false;
}
}
<commit_msg>constrain _terrain_vpos to be a minimum of _params.rng_gnd_clearance larger than _state.pos(2)<commit_after>/****************************************************************************
*
* Copyright (c) 2015 Estimation and Control Library (ECL). 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 ECL 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 terrain_estimator.cpp
* Function for fusing rangefinder measurements to estimate terrain vertical position/
*
* @author Paul Riseborough <p_riseborough@live.com.au>
*
*/
#include "ekf.h"
#include "mathlib.h"
bool Ekf::initHagl()
{
// get most recent range measurement from buffer
rangeSample latest_measurement = _range_buffer.get_newest();
if ((_time_last_imu - latest_measurement.time_us) < 2e5 && _R_rng_to_earth_2_2 > 0.7071f) {
// if we have a fresh measurement, use it to initialise the terrain estimator
_terrain_vpos = _state.pos(2) + latest_measurement.rng * _R_rng_to_earth_2_2;
// initialise state variance to variance of measurement
_terrain_var = sq(_params.range_noise);
// success
return true;
} else if (!_control_status.flags.in_air) {
// if on ground we assume a ground clearance
_terrain_vpos = _state.pos(2) + _params.rng_gnd_clearance;
// Use the ground clearance value as our uncertainty
_terrain_var = sq(_params.rng_gnd_clearance);
// ths is a guess
return false;
} else {
// no information - cannot initialise
return false;
}
}
void Ekf::runTerrainEstimator()
{
// Perform a continuity check on range finder data
checkRangeDataContinuity();
// Perform initialisation check
if (!_terrain_initialised) {
_terrain_initialised = initHagl();
} else {
// predict the state variance growth where the state is the vertical position of the terrain underneath the vehicle
// process noise due to errors in vehicle height estimate
_terrain_var += sq(_imu_sample_delayed.delta_vel_dt * _params.terrain_p_noise);
// process noise due to terrain gradient
_terrain_var += sq(_imu_sample_delayed.delta_vel_dt * _params.terrain_gradient) * (sq(_state.vel(0)) + sq(_state.vel(
1)));
// limit the variance to prevent it becoming badly conditioned
_terrain_var = math::constrain(_terrain_var, 0.0f, 1e4f);
// Fuse range finder data if available
if (_range_data_ready) {
fuseHagl();
// update range sensor angle parameters in case they have changed
// we do this here to avoid doing those calculations at a high rate
_sin_tilt_rng = sinf(_params.rng_sens_pitch);
_cos_tilt_rng = cosf(_params.rng_sens_pitch);
}
//constrain _terrain_vpos to be a minimum of _params.rng_gnd_clearance larger than _state.pos(2)
if (_terrain_vpos - _state.pos(2) < _params.rng_gnd_clearance) {
_terrain_vpos = _params.rng_gnd_clearance + _state.pos(2);
}
}
}
void Ekf::fuseHagl()
{
// If the vehicle is excessively tilted, do not try to fuse range finder observations
if (_R_rng_to_earth_2_2 > 0.7071f) {
// get a height above ground measurement from the range finder assuming a flat earth
float meas_hagl = _range_sample_delayed.rng * _R_rng_to_earth_2_2;
// predict the hagl from the vehicle position and terrain height
float pred_hagl = _terrain_vpos - _state.pos(2);
// calculate the innovation
_hagl_innov = pred_hagl - meas_hagl;
// calculate the observation variance adding the variance of the vehicles own height uncertainty
float obs_variance = fmaxf(P[9][9], 0.0f) + sq(_params.range_noise) + sq(_params.range_noise_scaler * _range_sample_delayed.rng);
// calculate the innovation variance - limiting it to prevent a badly conditioned fusion
_hagl_innov_var = fmaxf(_terrain_var + obs_variance, obs_variance);
// perform an innovation consistency check and only fuse data if it passes
float gate_size = fmaxf(_params.range_innov_gate, 1.0f);
_terr_test_ratio = sq(_hagl_innov) / (sq(gate_size) * _hagl_innov_var);
if (_terr_test_ratio <= 1.0f) {
// calculate the Kalman gain
float gain = _terrain_var / _hagl_innov_var;
// correct the state
_terrain_vpos -= gain * _hagl_innov;
// correct the variance
_terrain_var = fmaxf(_terrain_var * (1.0f - gain), 0.0f);
// record last successful fusion event
_time_last_hagl_fuse = _time_last_imu;
_innov_check_fail_status.flags.reject_hagl = false;
} else {
_innov_check_fail_status.flags.reject_hagl = true;
}
} else {
_innov_check_fail_status.flags.reject_hagl = true;
return;
}
}
// return true if the terrain estimate is valid
bool Ekf::get_terrain_valid()
{
if (_terrain_initialised && _range_data_continuous && !_innov_check_fail_status.flags.reject_hagl) {
return true;
} else {
return false;
}
}
// get the estimated vertical position of the terrain relative to the NED origin
void Ekf::get_terrain_vert_pos(float *ret)
{
memcpy(ret, &_terrain_vpos, sizeof(float));
}
void Ekf::get_hagl_innov(float *hagl_innov)
{
memcpy(hagl_innov, &_hagl_innov, sizeof(_hagl_innov));
}
void Ekf::get_hagl_innov_var(float *hagl_innov_var)
{
memcpy(hagl_innov_var, &_hagl_innov_var, sizeof(_hagl_innov_var));
}
// check that the range finder data is continuous
void Ekf::checkRangeDataContinuity()
{
// update range data continuous flag (2Hz ie 500 ms)
/* Timing in micro seconds */
/* Apply a 1.0 sec low pass filter to the time delta from the last range finder updates */
_dt_last_range_update_filt_us = _dt_last_range_update_filt_us * (1.0f - _dt_update) + _dt_update *
(_time_last_imu - _time_last_range);
_dt_last_range_update_filt_us = fminf(_dt_last_range_update_filt_us, 1e6f);
if (_dt_last_range_update_filt_us < 5e5f) {
_range_data_continuous = true;
} else {
_range_data_continuous = false;
}
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#ifndef SQLITE_STRATEGIES_H
#define SQLITE_STRATEGIES_H 1
#include <cstdlib>
#include <vector>
#include <algorithm>
#include "common.hh"
#include "queueditem.hh"
#include "sqlite-pst.hh"
class EventuallyPersistentEngine;
typedef enum {
select_all,
delete_vbucket
} vb_statement_type;
/**
* Base class for all Sqlite strategies.
*/
class SqliteStrategy {
public:
SqliteStrategy(const char * const fn,
const char * const finit,
const char * const pfinit,
size_t shards);
virtual ~SqliteStrategy();
sqlite3 *open();
void close();
size_t getNumOfDbShards() {
return shardCount;
}
virtual uint16_t getDbShardId(const QueuedItem &qi) {
return getDbShardIdForKey(qi.getKey());
}
virtual const std::vector<Statements *> &allStatements() = 0;
virtual Statements *getStatements(uint16_t vbid, uint16_t vbver,
const std::string &key) = 0;
PreparedStatement *getInsVBucketStateST() {
return ins_vb_stmt;
}
PreparedStatement *getClearVBucketStateST() {
return clear_vb_stmt;
}
PreparedStatement *getGetVBucketStateST() {
return sel_vb_stmt;
}
PreparedStatement *getClearStatsST() {
return clear_stats_stmt;
}
PreparedStatement *getInsStatST() {
return ins_stat_stmt;
}
virtual bool hasEfficientVBLoad() { return false; }
virtual std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst) {
(void)vb;
(void)vbst;
std::vector<PreparedStatement*> rv;
return rv;
}
virtual void closeVBStatements(std::vector<PreparedStatement*> &psts) {
(void)psts;
}
virtual void destroyTables() = 0;
virtual void optimizeWrites(std::vector<QueuedItem> &items) {
(void)items;
}
void execute(const char * const query);
static void disableSchemaCheck() {
shouldCheckSchemaVersion = false;
}
protected:
void doFile(const char * const filename);
uint16_t getDbShardIdForKey(const std::string &key) {
assert(shardCount > 0);
int h=5381;
int i=0;
const char *str = key.c_str();
for(i=0; str[i] != 0x00; i++) {
h = ((h << 5) + h) ^ str[i];
}
return std::abs(h) % (int)shardCount;
}
virtual void initDB() {
doFile(initFile);
}
void checkSchemaVersion();
void initMetaTables();
virtual void initTables() = 0;
virtual void initStatements() = 0;
virtual void initMetaStatements();
virtual void destroyStatements() {};
void destroyMetaStatements();
static bool shouldCheckSchemaVersion;
sqlite3 *db;
const char * const filename;
const char * const initFile;
const char * const postInitFile;
size_t shardCount;
PreparedStatement *ins_vb_stmt;
PreparedStatement *clear_vb_stmt;
PreparedStatement *sel_vb_stmt;
PreparedStatement *clear_stats_stmt;
PreparedStatement *ins_stat_stmt;
uint16_t schema_version;
private:
DISALLOW_COPY_AND_ASSIGN(SqliteStrategy);
};
//
// ----------------------------------------------------------------------
// Concrete Strategies
// ----------------------------------------------------------------------
//
/**
* Strategy for a single table kv store in a single DB.
*/
class SingleTableSqliteStrategy : public SqliteStrategy {
public:
/**
* Constructor.
*
* @param fn the filename of the DB
* @param finit an init script to run as soon as the DB opens
* @param pfinit an init script to run after initializing all schema
* @param shards the number of shards
*/
SingleTableSqliteStrategy(const char * const fn,
const char * const finit,
const char * const pfinit,
size_t shards = 1) :
SqliteStrategy(fn, finit, pfinit, shards), statements() {
assert(filename);
}
virtual ~SingleTableSqliteStrategy() { }
const std::vector<Statements *> &allStatements() {
return statements;
}
Statements *getStatements(uint16_t vbid, uint16_t vbver,
const std::string &key) {
(void)vbid;
(void)vbver;
return statements.at(getDbShardIdForKey(key));
}
void destroyStatements();
virtual void destroyTables();
void optimizeWrites(std::vector<QueuedItem> &items) {
// Sort all the queued items for each db shard by their row ids
CompareQueuedItemsByRowId cq;
std::sort(items.begin(), items.end(), cq);
}
protected:
std::vector<Statements *> statements;
virtual void initTables();
virtual void initStatements();
private:
DISALLOW_COPY_AND_ASSIGN(SingleTableSqliteStrategy);
};
//
// ----------------------------------------------------------------------
// Multi DB strategy
// ----------------------------------------------------------------------
//
/**
* A specialization of SqliteStrategy that allows multiple data
* shards with a single kv table each.
*/
class MultiDBSingleTableSqliteStrategy : public SingleTableSqliteStrategy {
public:
/**
* Constructor.
*
* @param fn same as SqliteStrategy
* @param sp the shard pattern
* @param finit same as SqliteStrategy
* @param pfinit same as SqliteStrategy
* @param n number of DB shards to create
*/
MultiDBSingleTableSqliteStrategy(const char * const fn,
const char * const sp,
const char * const finit,
const char * const pfinit,
int n):
SingleTableSqliteStrategy(fn, finit, pfinit, n),
shardpattern(sp), numTables(n) {
assert(shardpattern);
}
void initDB(void);
void initTables(void);
void initStatements(void);
void destroyTables(void);
private:
const char * const shardpattern;
int numTables;
};
//
// ----------------------------------------------------------------------
// Table Per Vbucket
// ----------------------------------------------------------------------
//
/**
* Strategy for a table per vbucket store in a single DB.
*/
class MultiTableSqliteStrategy : public SqliteStrategy {
public:
/**
* Constructor.
*
* @param fn the filename of the DB
* @param finit an init script to run as soon as the DB opens
* @param pfinit an init script to run after initializing all schema
* @param nv the maxinum number of vbuckets
* @param shards the number of data shards
*/
MultiTableSqliteStrategy(const char * const fn,
const char * const finit,
const char * const pfinit,
int nv,
int shards=1)
: SqliteStrategy(fn, finit, pfinit, shards),
nvbuckets(nv), statements() {
assert(filename);
}
virtual ~MultiTableSqliteStrategy() { }
const std::vector<Statements *> &allStatements() {
return statements;
}
virtual Statements *getStatements(uint16_t vbid, uint16_t vbver,
const std::string &key) {
(void)vbver;
(void)key;
assert(static_cast<size_t>(vbid) < statements.size());
return statements.at(vbid);
}
virtual void destroyStatements();
virtual void destroyTables();
bool hasEfficientVBLoad() { return true; }
virtual std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst) {
std::vector<PreparedStatement*> rv;
assert(static_cast<size_t>(vb) < statements.size());
switch (vbst) {
case select_all:
rv.push_back(statements.at(vb)->all());
break;
case delete_vbucket:
rv.push_back(statements.at(vb)->del_vb());
break;
default:
break;
}
return rv;
}
void closeVBStatements(std::vector<PreparedStatement*> &psts) {
std::for_each(psts.begin(), psts.end(),
std::mem_fun(&PreparedStatement::reset));
}
void optimizeWrites(std::vector<QueuedItem> &items) {
// Sort all the queued items for each db shard by its vbucket
// ID and then its row ids
CompareQueuedItemsByVBAndRowId cq;
std::sort(items.begin(), items.end(), cq);
}
protected:
size_t nvbuckets;
std::vector<Statements *> statements;
virtual void initTables();
virtual void initStatements();
private:
DISALLOW_COPY_AND_ASSIGN(MultiTableSqliteStrategy);
};
//
// ----------------------------------------------------------------------
// Multiple Shards, Table Per Vbucket
// ----------------------------------------------------------------------
//
/**
* Strategy for a table per vbucket store in multiple shards.
*/
class ShardedMultiTableSqliteStrategy : public MultiTableSqliteStrategy {
public:
/**
* Constructor.
*
* @param fn the filename of the DB
* @param sp the shard pattern
* @param finit an init script to run as soon as the DB opens
* @param pfinit an init script to run after initializing all schema
* @param nv the maxinum number of vbuckets
* @param n the number of data shards
*/
ShardedMultiTableSqliteStrategy(const char * const fn,
const char * const sp,
const char * const finit,
const char * const pfinit,
int nv,
int n)
: MultiTableSqliteStrategy(fn, finit, pfinit, nv, n),
shardpattern(sp),
statementsPerShard() {
assert(filename);
}
virtual ~ShardedMultiTableSqliteStrategy() { }
Statements *getStatements(uint16_t vbid, uint16_t vbver,
const std::string &key);
void destroyStatements();
void destroyTables();
std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst);
protected:
const char * const shardpattern;
// statementsPerShard[vbucket][shard]
std::vector<std::vector<Statements*> > statementsPerShard;
void initDB();
void initTables();
void initStatements();
private:
DISALLOW_COPY_AND_ASSIGN(ShardedMultiTableSqliteStrategy);
};
//
// ----------------------------------------------------------------------
// Sharded by VBucket
// ----------------------------------------------------------------------
//
/**
* Strategy for a table per vbucket where each vbucket exists in only
* one shard.
*/
class ShardedByVBucketSqliteStrategy : public MultiTableSqliteStrategy {
public:
/**
* Constructor.
*
* @param fn the filename of the DB
* @param sp the shard pattern for generating shard files
* @param finit an init script to run as soon as the DB opens
* @param pfinit an init script to run after initializing all schema
* @param nv the maxinum number of vbuckets
* @param n the number of data shards
*/
ShardedByVBucketSqliteStrategy(const char * const fn,
const char * const sp,
const char * const finit,
const char * const pfinit,
int nv,
int n)
: MultiTableSqliteStrategy(fn, finit, pfinit, nv, n),
shardpattern(sp) {
assert(filename);
}
uint16_t getDbShardId(const QueuedItem &qi) {
return getShardForVBucket(qi.getVBucketId());
}
virtual ~ShardedByVBucketSqliteStrategy() { }
void destroyTables();
protected:
const char * const shardpattern;
size_t getShardForVBucket(uint16_t vb) {
size_t rv = (static_cast<size_t>(vb) % shardCount);
assert(rv < shardCount);
return rv;
}
void initDB();
void initTables();
void initStatements();
private:
DISALLOW_COPY_AND_ASSIGN(ShardedByVBucketSqliteStrategy);
};
#endif /* SQLITE_STRATEGIES_H */
<commit_msg>MB-3465 Provide specific SQL stmts even for single table strategy<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#ifndef SQLITE_STRATEGIES_H
#define SQLITE_STRATEGIES_H 1
#include <cstdlib>
#include <vector>
#include <algorithm>
#include "common.hh"
#include "queueditem.hh"
#include "sqlite-pst.hh"
class EventuallyPersistentEngine;
typedef enum {
select_all,
delete_vbucket
} vb_statement_type;
/**
* Base class for all Sqlite strategies.
*/
class SqliteStrategy {
public:
SqliteStrategy(const char * const fn,
const char * const finit,
const char * const pfinit,
size_t shards);
virtual ~SqliteStrategy();
sqlite3 *open();
void close();
size_t getNumOfDbShards() {
return shardCount;
}
virtual uint16_t getDbShardId(const QueuedItem &qi) {
return getDbShardIdForKey(qi.getKey());
}
virtual const std::vector<Statements *> &allStatements() = 0;
virtual Statements *getStatements(uint16_t vbid, uint16_t vbver,
const std::string &key) = 0;
PreparedStatement *getInsVBucketStateST() {
return ins_vb_stmt;
}
PreparedStatement *getClearVBucketStateST() {
return clear_vb_stmt;
}
PreparedStatement *getGetVBucketStateST() {
return sel_vb_stmt;
}
PreparedStatement *getClearStatsST() {
return clear_stats_stmt;
}
PreparedStatement *getInsStatST() {
return ins_stat_stmt;
}
virtual bool hasEfficientVBLoad() { return false; }
virtual std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst) {
(void)vb;
(void)vbst;
std::vector<PreparedStatement*> rv;
return rv;
}
virtual void closeVBStatements(std::vector<PreparedStatement*> &psts) {
(void)psts;
}
virtual void destroyTables() = 0;
virtual void optimizeWrites(std::vector<QueuedItem> &items) {
(void)items;
}
void execute(const char * const query);
static void disableSchemaCheck() {
shouldCheckSchemaVersion = false;
}
protected:
void doFile(const char * const filename);
uint16_t getDbShardIdForKey(const std::string &key) {
assert(shardCount > 0);
int h=5381;
int i=0;
const char *str = key.c_str();
for(i=0; str[i] != 0x00; i++) {
h = ((h << 5) + h) ^ str[i];
}
return std::abs(h) % (int)shardCount;
}
virtual void initDB() {
doFile(initFile);
}
void checkSchemaVersion();
void initMetaTables();
virtual void initTables() = 0;
virtual void initStatements() = 0;
virtual void initMetaStatements();
virtual void destroyStatements() {};
void destroyMetaStatements();
static bool shouldCheckSchemaVersion;
sqlite3 *db;
const char * const filename;
const char * const initFile;
const char * const postInitFile;
size_t shardCount;
PreparedStatement *ins_vb_stmt;
PreparedStatement *clear_vb_stmt;
PreparedStatement *sel_vb_stmt;
PreparedStatement *clear_stats_stmt;
PreparedStatement *ins_stat_stmt;
uint16_t schema_version;
private:
DISALLOW_COPY_AND_ASSIGN(SqliteStrategy);
};
//
// ----------------------------------------------------------------------
// Concrete Strategies
// ----------------------------------------------------------------------
//
/**
* Strategy for a single table kv store in a single DB.
*/
class SingleTableSqliteStrategy : public SqliteStrategy {
public:
/**
* Constructor.
*
* @param fn the filename of the DB
* @param finit an init script to run as soon as the DB opens
* @param pfinit an init script to run after initializing all schema
* @param shards the number of shards
*/
SingleTableSqliteStrategy(const char * const fn,
const char * const finit,
const char * const pfinit,
size_t shards = 1) :
SqliteStrategy(fn, finit, pfinit, shards), statements() {
assert(filename);
}
virtual ~SingleTableSqliteStrategy() { }
const std::vector<Statements *> &allStatements() {
return statements;
}
Statements *getStatements(uint16_t vbid, uint16_t vbver,
const std::string &key) {
(void)vbid;
(void)vbver;
return statements.at(getDbShardIdForKey(key));
}
void destroyStatements();
virtual void destroyTables();
void optimizeWrites(std::vector<QueuedItem> &items) {
// Sort all the queued items for each db shard by their row ids
CompareQueuedItemsByRowId cq;
std::sort(items.begin(), items.end(), cq);
}
virtual std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst) {
(void)vb;
std::vector<PreparedStatement*> rv;
std::vector<Statements*>::iterator it;
for (it = statements.begin(); it != statements.end(); ++it) {
switch (vbst) {
case select_all:
rv.push_back((*it)->all());
break;
case delete_vbucket:
rv.push_back((*it)->del_vb());
break;
default:
break;
}
}
return rv;
}
virtual void closeVBStatements(std::vector<PreparedStatement*> &psts) {
std::for_each(psts.begin(), psts.end(),
std::mem_fun(&PreparedStatement::reset));
}
protected:
std::vector<Statements *> statements;
virtual void initTables();
virtual void initStatements();
private:
DISALLOW_COPY_AND_ASSIGN(SingleTableSqliteStrategy);
};
//
// ----------------------------------------------------------------------
// Multi DB strategy
// ----------------------------------------------------------------------
//
/**
* A specialization of SqliteStrategy that allows multiple data
* shards with a single kv table each.
*/
class MultiDBSingleTableSqliteStrategy : public SingleTableSqliteStrategy {
public:
/**
* Constructor.
*
* @param fn same as SqliteStrategy
* @param sp the shard pattern
* @param finit same as SqliteStrategy
* @param pfinit same as SqliteStrategy
* @param n number of DB shards to create
*/
MultiDBSingleTableSqliteStrategy(const char * const fn,
const char * const sp,
const char * const finit,
const char * const pfinit,
int n):
SingleTableSqliteStrategy(fn, finit, pfinit, n),
shardpattern(sp), numTables(n) {
assert(shardpattern);
}
void initDB(void);
void initTables(void);
void initStatements(void);
void destroyTables(void);
private:
const char * const shardpattern;
int numTables;
};
//
// ----------------------------------------------------------------------
// Table Per Vbucket
// ----------------------------------------------------------------------
//
/**
* Strategy for a table per vbucket store in a single DB.
*/
class MultiTableSqliteStrategy : public SqliteStrategy {
public:
/**
* Constructor.
*
* @param fn the filename of the DB
* @param finit an init script to run as soon as the DB opens
* @param pfinit an init script to run after initializing all schema
* @param nv the maxinum number of vbuckets
* @param shards the number of data shards
*/
MultiTableSqliteStrategy(const char * const fn,
const char * const finit,
const char * const pfinit,
int nv,
int shards=1)
: SqliteStrategy(fn, finit, pfinit, shards),
nvbuckets(nv), statements() {
assert(filename);
}
virtual ~MultiTableSqliteStrategy() { }
const std::vector<Statements *> &allStatements() {
return statements;
}
virtual Statements *getStatements(uint16_t vbid, uint16_t vbver,
const std::string &key) {
(void)vbver;
(void)key;
assert(static_cast<size_t>(vbid) < statements.size());
return statements.at(vbid);
}
virtual void destroyStatements();
virtual void destroyTables();
bool hasEfficientVBLoad() { return true; }
virtual std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst) {
std::vector<PreparedStatement*> rv;
assert(static_cast<size_t>(vb) < statements.size());
switch (vbst) {
case select_all:
rv.push_back(statements.at(vb)->all());
break;
case delete_vbucket:
rv.push_back(statements.at(vb)->del_vb());
break;
default:
break;
}
return rv;
}
void closeVBStatements(std::vector<PreparedStatement*> &psts) {
std::for_each(psts.begin(), psts.end(),
std::mem_fun(&PreparedStatement::reset));
}
void optimizeWrites(std::vector<QueuedItem> &items) {
// Sort all the queued items for each db shard by its vbucket
// ID and then its row ids
CompareQueuedItemsByVBAndRowId cq;
std::sort(items.begin(), items.end(), cq);
}
protected:
size_t nvbuckets;
std::vector<Statements *> statements;
virtual void initTables();
virtual void initStatements();
private:
DISALLOW_COPY_AND_ASSIGN(MultiTableSqliteStrategy);
};
//
// ----------------------------------------------------------------------
// Multiple Shards, Table Per Vbucket
// ----------------------------------------------------------------------
//
/**
* Strategy for a table per vbucket store in multiple shards.
*/
class ShardedMultiTableSqliteStrategy : public MultiTableSqliteStrategy {
public:
/**
* Constructor.
*
* @param fn the filename of the DB
* @param sp the shard pattern
* @param finit an init script to run as soon as the DB opens
* @param pfinit an init script to run after initializing all schema
* @param nv the maxinum number of vbuckets
* @param n the number of data shards
*/
ShardedMultiTableSqliteStrategy(const char * const fn,
const char * const sp,
const char * const finit,
const char * const pfinit,
int nv,
int n)
: MultiTableSqliteStrategy(fn, finit, pfinit, nv, n),
shardpattern(sp),
statementsPerShard() {
assert(filename);
}
virtual ~ShardedMultiTableSqliteStrategy() { }
Statements *getStatements(uint16_t vbid, uint16_t vbver,
const std::string &key);
void destroyStatements();
void destroyTables();
std::vector<PreparedStatement*> getVBStatements(uint16_t vb, vb_statement_type vbst);
protected:
const char * const shardpattern;
// statementsPerShard[vbucket][shard]
std::vector<std::vector<Statements*> > statementsPerShard;
void initDB();
void initTables();
void initStatements();
private:
DISALLOW_COPY_AND_ASSIGN(ShardedMultiTableSqliteStrategy);
};
//
// ----------------------------------------------------------------------
// Sharded by VBucket
// ----------------------------------------------------------------------
//
/**
* Strategy for a table per vbucket where each vbucket exists in only
* one shard.
*/
class ShardedByVBucketSqliteStrategy : public MultiTableSqliteStrategy {
public:
/**
* Constructor.
*
* @param fn the filename of the DB
* @param sp the shard pattern for generating shard files
* @param finit an init script to run as soon as the DB opens
* @param pfinit an init script to run after initializing all schema
* @param nv the maxinum number of vbuckets
* @param n the number of data shards
*/
ShardedByVBucketSqliteStrategy(const char * const fn,
const char * const sp,
const char * const finit,
const char * const pfinit,
int nv,
int n)
: MultiTableSqliteStrategy(fn, finit, pfinit, nv, n),
shardpattern(sp) {
assert(filename);
}
uint16_t getDbShardId(const QueuedItem &qi) {
return getShardForVBucket(qi.getVBucketId());
}
virtual ~ShardedByVBucketSqliteStrategy() { }
void destroyTables();
protected:
const char * const shardpattern;
size_t getShardForVBucket(uint16_t vb) {
size_t rv = (static_cast<size_t>(vb) % shardCount);
assert(rv < shardCount);
return rv;
}
void initDB();
void initTables();
void initStatements();
private:
DISALLOW_COPY_AND_ASSIGN(ShardedByVBucketSqliteStrategy);
};
#endif /* SQLITE_STRATEGIES_H */
<|endoftext|>
|
<commit_before>/**
* @file log.cpp
*
* @date 2014-7-29 AM8:43:27
* @author salmon
*/
#include "Log.h"
#include <chrono>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include "design_pattern/SingletonHolder.h"
#include "parse_command_line.h"
namespace simpla { namespace logger
{
/**
* @ingroup Logging
* \brief Logging stream, should be used as a singleton
*/
struct LoggerStreams //: public SingletonHolder<LoggerStreams>
{
static constexpr unsigned int DEFAULT_LINE_WIDTH = 120;
bool is_opened_ = false;
int line_width_ = DEFAULT_LINE_WIDTH;
int mpi_rank_ = 0, mpi_size_ = 1;
LoggerStreams(int level = LOG_INFORM)
: m_std_out_level_(level), line_width_(DEFAULT_LINE_WIDTH) { }
~LoggerStreams() { close(); }
void init();
void close();
inline void open_file(std::string const &name)
{
if (fs.is_open()) fs.close();
fs.open(name.c_str(), std::ios_base::trunc);
}
void push(int level, std::string const &msg);
inline void set_stdout_level(int l)
{
m_std_out_level_ = l;
}
int get_line_width() const
{
return line_width_;
}
void set_line_width(int lineWidth)
{
line_width_ = lineWidth;
}
static std::string time_stamp()
{
auto now = std::chrono::system_clock::to_time_t(
std::chrono::system_clock::now());
char mtstr[100];
std::strftime(mtstr, 100, "%F %T", std::localtime(&now));
return std::string(mtstr);
}
private:
int m_std_out_level_;
std::ofstream fs;
};
void LoggerStreams::init() { is_opened_ = true; }
void LoggerStreams::close()
{
if (is_opened_)
{
VERBOSE << "LoggerStream is closed!" << std::endl;
if (m_std_out_level_ >= LOG_INFORM && mpi_rank_ == 0) { std::cout << std::endl; }
if (fs.is_open()) { fs.close(); }
is_opened_ = false;
}
}
void LoggerStreams::push(int level, std::string const &msg)
{
if (msg == "" || ((level == LOG_INFORM || level == LOG_MESSAGE) && mpi_rank_ > 0)) return;
std::ostringstream prefix;
std::string surfix("");
switch (level)
{
case LOG_FORCE_OUTPUT:
case LOG_OUT_RANGE_ERROR:
case LOG_LOGIC_ERROR:
case LOG_ERROR:
prefix << "[E]";
break;
case LOG_WARNING:
prefix << "[W]"; //red
break;
case LOG_LOG:
prefix << "[L]";
break;
case LOG_VERBOSE:
prefix << "[V]";
break;
case LOG_INFORM:
prefix << "[I]";
break;
case LOG_DEBUG:
prefix << "[D]";
break;
default:
break;
}
if (mpi_size_ > 1)
{
prefix << "[" << mpi_rank_ << "/" << mpi_size_ << "]";
}
prefix << "[" << time_stamp() << "] ";
if (level <= m_std_out_level_)
{
switch (level)
{
case LOG_FORCE_OUTPUT:
case LOG_OUT_RANGE_ERROR:
case LOG_LOGIC_ERROR:
case LOG_ERROR:
std::cerr << "\e[1;31m" << prefix.str() << "\e[1;37m" << msg << "\e[0m" << surfix;
break;
case LOG_WARNING:
std::cerr << "\e[1;32m" << prefix.str() << "\e[1;37m" << msg << "\e[0m" << surfix;
break;
case LOG_MESSAGE:
std::cout << msg;
break;
default:
std::cout << prefix.str() << msg << surfix;
}
}
if (!fs.good())
open_file("simpla.log");
fs << std::endl << prefix.str() << msg << surfix;
}
void open_file(std::string const &file_name)
{
return SingletonHolder<LoggerStreams>::instance().open_file(file_name);
}
void close()
{
SingletonHolder<LoggerStreams>::instance().close();
}
void set_stdout_level(int l)
{
return SingletonHolder<LoggerStreams>::instance().set_stdout_level(l);
}
void set_mpi_comm(int r, int s)
{
SingletonHolder<LoggerStreams>::instance().mpi_rank_ = r;
SingletonHolder<LoggerStreams>::instance().mpi_size_ = s;
}
void set_line_width(int lw)
{
return SingletonHolder<LoggerStreams>::instance().set_line_width(lw);
}
int get_line_width()
{
return SingletonHolder<LoggerStreams>::instance().get_line_width();
}
Logger::Logger()
: base_type(), m_level_(0), current_line_char_count_(0), endl_(true) { }
Logger::Logger(int lv)
: m_level_(lv), current_line_char_count_(0), endl_(true)
{
base_type::operator<<(std::boolalpha);
current_line_char_count_ = get_buffer_length();
}
Logger::~Logger()
{
switch (m_level_)
{
case LOG_ERROR_RUNTIME:
throw (std::runtime_error(this->str()));
break;
case LOG_ERROR_BAD_CAST :
throw (std::bad_cast());
break;
case LOG_ERROR_OUT_OF_RANGE :
throw (std::out_of_range(this->str()));
break;
case LOG_ERROR_LOGICAL :
throw (std::logic_error(this->str()));
break;
default:
flush();
}
}
int Logger::get_buffer_length() const
{
return static_cast<int>(this->str().size());
}
void Logger::flush()
{
SingletonHolder<LoggerStreams>::instance().push(m_level_, this->str());
this->str("");
}
void Logger::surffix(std::string const &s)
{
(*this) << std::setfill('.')
<< std::setw(SingletonHolder<LoggerStreams>::instance().get_line_width()
- current_line_char_count_)
<< std::right << s << std::left << std::endl;
flush();
}
void Logger::endl()
{
(*this) << std::endl;
current_line_char_count_ = 0;
endl_ = true;
}
void Logger::not_endl() { endl_ = false; }
} // namespace logger
}
// namespace simpla
<commit_msg>Success: demo_em (cold fluid + PML+ multi-block)<commit_after>/**
* @file log.cpp
*
* @date 2014-7-29 AM8:43:27
* @author salmon
*/
#include "Log.h"
#include <chrono>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "design_pattern/SingletonHolder.h"
namespace simpla { namespace logger
{
/**
* @ingroup Logging
* \brief Logging stream, should be used as a singleton
*/
struct LoggerStreams
{
static constexpr unsigned int DEFAULT_LINE_WIDTH = 120;
bool is_opened_ = false;
int line_width_ = DEFAULT_LINE_WIDTH;
int mpi_rank_ = 0, mpi_size_ = 1;
LoggerStreams(int level = LOG_INFORM)
: m_std_out_level_(level), line_width_(DEFAULT_LINE_WIDTH) { }
~LoggerStreams() { close(); }
void init();
void close();
inline void open_file(std::string const &name)
{
if (fs.is_open()) fs.close();
fs.open(name.c_str(), std::ios_base::trunc);
}
void push(int level, std::string const &msg);
inline void set_stdout_level(int l)
{
m_std_out_level_ = l;
}
int get_line_width() const
{
return line_width_;
}
void set_line_width(int lineWidth)
{
line_width_ = lineWidth;
}
static std::string time_stamp()
{
auto now = std::chrono::system_clock::to_time_t(
std::chrono::system_clock::now());
char mtstr[100];
std::strftime(mtstr, 100, "%F %T", std::localtime(&now));
return std::string(mtstr);
}
private:
int m_std_out_level_;
std::ofstream fs;
};
void LoggerStreams::init() { is_opened_ = true; }
void LoggerStreams::close()
{
if (is_opened_)
{
VERBOSE << "LoggerStream is closed!" << std::endl;
if (m_std_out_level_ >= LOG_INFORM && mpi_rank_ == 0) { std::cout << std::endl; }
if (fs.is_open()) { fs.close(); }
is_opened_ = false;
}
}
void LoggerStreams::push(int level, std::string const &msg)
{
if (msg == "" || ((level == LOG_INFORM || level == LOG_MESSAGE) && mpi_rank_ > 0)) return;
std::ostringstream prefix;
std::string surfix("");
switch (level)
{
case LOG_FORCE_OUTPUT:
case LOG_OUT_RANGE_ERROR:
case LOG_LOGIC_ERROR:
case LOG_ERROR:
prefix << "[E]";
break;
case LOG_WARNING:
prefix << "[W]"; //red
break;
case LOG_LOG:
prefix << "[L]";
break;
case LOG_VERBOSE:
prefix << "[V]";
break;
case LOG_INFORM:
prefix << "[I]";
break;
case LOG_DEBUG:
prefix << "[D]";
break;
default:
break;
}
if (mpi_size_ > 1)
{
prefix << "[" << mpi_rank_ << "/" << mpi_size_ << "]";
}
prefix << "[" << time_stamp() << "] ";
if (level <= m_std_out_level_)
{
switch (level)
{
case LOG_FORCE_OUTPUT:
case LOG_OUT_RANGE_ERROR:
case LOG_LOGIC_ERROR:
case LOG_ERROR:
std::cerr << "\e[1;31m" << prefix.str() << "\e[1;37m" << msg << "\e[0m" << surfix;
break;
case LOG_WARNING:
std::cerr << "\e[1;32m" << prefix.str() << "\e[1;37m" << msg << "\e[0m" << surfix;
break;
case LOG_MESSAGE:
std::cout << msg;
break;
default:
std::cout << prefix.str() << msg << surfix;
}
}
if (!fs.good())
open_file("simpla.log");
fs << std::endl << prefix.str() << msg << surfix;
}
void open_file(std::string const &file_name)
{
return SingletonHolder<LoggerStreams>::instance().open_file(file_name);
}
void close()
{
SingletonHolder<LoggerStreams>::instance().close();
}
void set_stdout_level(int l)
{
return SingletonHolder<LoggerStreams>::instance().set_stdout_level(l);
}
void set_mpi_comm(int r, int s)
{
SingletonHolder<LoggerStreams>::instance().mpi_rank_ = r;
SingletonHolder<LoggerStreams>::instance().mpi_size_ = s;
}
void set_line_width(int lw)
{
return SingletonHolder<LoggerStreams>::instance().set_line_width(lw);
}
int get_line_width()
{
return SingletonHolder<LoggerStreams>::instance().get_line_width();
}
Logger::Logger()
: base_type(), m_level_(0), current_line_char_count_(0), endl_(true) { }
Logger::Logger(int lv)
: m_level_(lv), current_line_char_count_(0), endl_(true)
{
base_type::operator<<(std::boolalpha);
current_line_char_count_ = get_buffer_length();
}
Logger::~Logger()
{
switch (m_level_)
{
case LOG_ERROR_RUNTIME:
throw (std::runtime_error(this->str()));
break;
case LOG_ERROR_BAD_CAST :
throw (std::bad_cast());
break;
case LOG_ERROR_OUT_OF_RANGE :
throw (std::out_of_range(this->str()));
break;
case LOG_ERROR_LOGICAL :
throw (std::logic_error(this->str()));
break;
default:
flush();
}
}
int Logger::get_buffer_length() const
{
return static_cast<int>(this->str().size());
}
void Logger::flush()
{
SingletonHolder<LoggerStreams>::instance().push(m_level_, this->str());
this->str("");
}
void Logger::surffix(std::string const &s)
{
(*this) << std::setfill('.')
<< std::setw(SingletonHolder<LoggerStreams>::instance().get_line_width()
- current_line_char_count_)
<< std::right << s << std::left << std::endl;
flush();
}
void Logger::endl()
{
(*this) << std::endl;
current_line_char_count_ = 0;
endl_ = true;
}
void Logger::not_endl() { endl_ = false; }
} // namespace logger
}
// namespace simpla
<|endoftext|>
|
<commit_before>#include "ProjectManager.hpp"
#include "ViewManager.hpp"
#include "DataSpecRegistry.hpp"
#include "hecl/Blender/Connection.hpp"
namespace urde {
static logvisor::Module Log("URDE::ProjectManager");
ProjectManager* ProjectManager::g_SharedManager = nullptr;
CToken ProjectResourcePool::GetObj(std::string_view name) {
CToken ret = CSimplePool::GetObj(name);
if (ret)
return ret;
hecl::ProjectPath path(*m_parent.project(), name);
SObjectTag tag =
static_cast<ProjectResourceFactoryBase&>(x18_factory).TagFromPath(path);
if (tag)
return CSimplePool::GetObj(tag);
return {};
}
CToken ProjectResourcePool::GetObj(std::string_view name, const CVParamTransfer& pvxfer) {
CToken ret = CSimplePool::GetObj(name, pvxfer);
if (ret)
return ret;
hecl::ProjectPath path(*m_parent.project(), name);
SObjectTag tag =
static_cast<ProjectResourceFactoryBase&>(x18_factory).TagFromPath(path);
if (tag)
return CSimplePool::GetObj(tag, pvxfer);
return {};
}
bool ProjectManager::m_registeredSpecs = false;
ProjectManager::ProjectManager(ViewManager& vm)
: m_vm(vm), m_clientProc(nullptr), m_factoryMP1(m_clientProc), m_objStore(m_factoryMP1, *this) {
if (!m_registeredSpecs) {
HECLRegisterDataSpecs();
m_registeredSpecs = true;
}
g_SharedManager = this;
}
bool ProjectManager::newProject(hecl::SystemStringView path) {
hecl::ProjectRootPath projPath = hecl::SearchForProject(path);
if (projPath) {
Log.report(logvisor::Warning, fmt(_SYS_STR("project already exists at '{}'")), path);
return false;
}
hecl::MakeDir(path.data());
m_proj = std::make_unique<hecl::Database::Project>(path);
if (!*m_proj) {
m_proj.reset();
return false;
}
m_vm.ProjectChanged(*m_proj);
m_vm.SetupEditorView();
saveProject();
m_vm.m_mainWindow->setTitle(fmt::format(fmt(_SYS_STR("{} - URDE [{}]")),
m_proj->getProjectRootPath().getLastComponent(), m_vm.platformName()));
m_vm.DismissSplash();
m_vm.FadeInEditors();
return true;
}
bool ProjectManager::openProject(hecl::SystemStringView path) {
hecl::SystemString subPath;
hecl::ProjectRootPath projPath = hecl::SearchForProject(path, subPath);
if (!projPath) {
Log.report(logvisor::Warning, fmt(_SYS_STR("project doesn't exist at '{}'")), path);
return false;
}
m_proj = std::make_unique<hecl::Database::Project>(projPath);
if (!*m_proj) {
m_proj.reset();
return false;
}
athena::io::YAMLDocReader r;
const auto makeProj = [this, &r, &subPath](bool needsSave) {
m_vm.ProjectChanged(*m_proj);
if (needsSave)
m_vm.SetupEditorView();
else
m_vm.SetupEditorView(r);
const bool doRun = hecl::StringUtils::BeginsWith(subPath, _SYS_STR("out"));
if (doRun) {
m_mainMP1.emplace(nullptr, nullptr, m_vm.m_mainBooFactory, m_vm.m_mainCommandQueue, m_vm.m_renderTex);
m_vm.InitMP1(*m_mainMP1);
}
if (needsSave)
saveProject();
m_vm.m_mainWindow->setTitle(fmt::format(fmt(_SYS_STR("{} - URDE [{}]")),
m_proj->getProjectRootPath().getLastComponent(), m_vm.platformName()));
m_vm.DismissSplash();
m_vm.FadeInEditors();
m_vm.pushRecentProject(m_proj->getProjectRootPath().getAbsolutePath());
return true;
};
const hecl::ProjectPath urdeSpacesPath(*m_proj, _SYS_STR(".hecl/urde_spaces.yaml"));
athena::io::FileReader reader(urdeSpacesPath.getAbsolutePath());
if (!reader.isOpen()) {
return makeProj(true);
}
const auto readHandler = [](void* data, unsigned char* buffer, size_t size, size_t* size_read) {
auto* const reader = static_cast<athena::io::IStreamReader*>(data);
return athena::io::YAMLAthenaReader(reader, buffer, size, size_read);
};
yaml_parser_set_input(r.getParser(), readHandler, &reader);
if (!r.ValidateClassType("UrdeSpacesState")) {
return makeProj(true);
}
r.reset();
reader.seek(0, athena::Begin);
if (!r.parse(&reader)) {
return makeProj(true);
}
return makeProj(false);
}
bool ProjectManager::extractGame(hecl::SystemStringView path) { return false; }
bool ProjectManager::saveProject() {
if (!m_proj)
return false;
hecl::ProjectPath oldSpacesPath(*m_proj, _SYS_STR(".hecl/~urde_spaces.yaml"));
athena::io::FileWriter writer(oldSpacesPath.getAbsolutePath());
if (!writer.isOpen())
return false;
athena::io::YAMLDocWriter w("UrdeSpacesState");
m_vm.SaveEditorView(w);
if (!w.finish(&writer))
return false;
hecl::ProjectPath newSpacesPath(*m_proj, _SYS_STR(".hecl/urde_spaces.yaml"));
hecl::Unlink(newSpacesPath.getAbsolutePath().data());
hecl::Rename(oldSpacesPath.getAbsolutePath().data(), newSpacesPath.getAbsolutePath().data());
m_vm.pushRecentProject(m_proj->getProjectRootPath().getAbsolutePath());
return true;
}
void ProjectManager::mainUpdate() {
if (m_precooking) {
if (!m_factoryMP1.IsBusy())
m_precooking = false;
else
return;
}
if (m_mainMP1) {
if (m_mainMP1->Proc()) {
m_mainMP1->Shutdown();
m_mainMP1 = std::nullopt;
}
}
}
void ProjectManager::mainDraw() {
if (m_precooking)
return;
if (m_mainMP1)
m_mainMP1->Draw();
}
void ProjectManager::shutdown() {
if (m_mainMP1)
m_mainMP1->Shutdown();
m_clientProc.shutdown();
m_factoryMP1.Shutdown();
hecl::blender::Connection::Shutdown();
}
} // namespace urde
<commit_msg>Editor/ProjectManager: Be explicit about athena's SeekOrigin type<commit_after>#include "ProjectManager.hpp"
#include "ViewManager.hpp"
#include "DataSpecRegistry.hpp"
#include "hecl/Blender/Connection.hpp"
namespace urde {
static logvisor::Module Log("URDE::ProjectManager");
ProjectManager* ProjectManager::g_SharedManager = nullptr;
CToken ProjectResourcePool::GetObj(std::string_view name) {
CToken ret = CSimplePool::GetObj(name);
if (ret)
return ret;
hecl::ProjectPath path(*m_parent.project(), name);
SObjectTag tag =
static_cast<ProjectResourceFactoryBase&>(x18_factory).TagFromPath(path);
if (tag)
return CSimplePool::GetObj(tag);
return {};
}
CToken ProjectResourcePool::GetObj(std::string_view name, const CVParamTransfer& pvxfer) {
CToken ret = CSimplePool::GetObj(name, pvxfer);
if (ret)
return ret;
hecl::ProjectPath path(*m_parent.project(), name);
SObjectTag tag =
static_cast<ProjectResourceFactoryBase&>(x18_factory).TagFromPath(path);
if (tag)
return CSimplePool::GetObj(tag, pvxfer);
return {};
}
bool ProjectManager::m_registeredSpecs = false;
ProjectManager::ProjectManager(ViewManager& vm)
: m_vm(vm), m_clientProc(nullptr), m_factoryMP1(m_clientProc), m_objStore(m_factoryMP1, *this) {
if (!m_registeredSpecs) {
HECLRegisterDataSpecs();
m_registeredSpecs = true;
}
g_SharedManager = this;
}
bool ProjectManager::newProject(hecl::SystemStringView path) {
hecl::ProjectRootPath projPath = hecl::SearchForProject(path);
if (projPath) {
Log.report(logvisor::Warning, fmt(_SYS_STR("project already exists at '{}'")), path);
return false;
}
hecl::MakeDir(path.data());
m_proj = std::make_unique<hecl::Database::Project>(path);
if (!*m_proj) {
m_proj.reset();
return false;
}
m_vm.ProjectChanged(*m_proj);
m_vm.SetupEditorView();
saveProject();
m_vm.m_mainWindow->setTitle(fmt::format(fmt(_SYS_STR("{} - URDE [{}]")),
m_proj->getProjectRootPath().getLastComponent(), m_vm.platformName()));
m_vm.DismissSplash();
m_vm.FadeInEditors();
return true;
}
bool ProjectManager::openProject(hecl::SystemStringView path) {
hecl::SystemString subPath;
hecl::ProjectRootPath projPath = hecl::SearchForProject(path, subPath);
if (!projPath) {
Log.report(logvisor::Warning, fmt(_SYS_STR("project doesn't exist at '{}'")), path);
return false;
}
m_proj = std::make_unique<hecl::Database::Project>(projPath);
if (!*m_proj) {
m_proj.reset();
return false;
}
athena::io::YAMLDocReader r;
const auto makeProj = [this, &r, &subPath](bool needsSave) {
m_vm.ProjectChanged(*m_proj);
if (needsSave)
m_vm.SetupEditorView();
else
m_vm.SetupEditorView(r);
const bool doRun = hecl::StringUtils::BeginsWith(subPath, _SYS_STR("out"));
if (doRun) {
m_mainMP1.emplace(nullptr, nullptr, m_vm.m_mainBooFactory, m_vm.m_mainCommandQueue, m_vm.m_renderTex);
m_vm.InitMP1(*m_mainMP1);
}
if (needsSave)
saveProject();
m_vm.m_mainWindow->setTitle(fmt::format(fmt(_SYS_STR("{} - URDE [{}]")),
m_proj->getProjectRootPath().getLastComponent(), m_vm.platformName()));
m_vm.DismissSplash();
m_vm.FadeInEditors();
m_vm.pushRecentProject(m_proj->getProjectRootPath().getAbsolutePath());
return true;
};
const hecl::ProjectPath urdeSpacesPath(*m_proj, _SYS_STR(".hecl/urde_spaces.yaml"));
athena::io::FileReader reader(urdeSpacesPath.getAbsolutePath());
if (!reader.isOpen()) {
return makeProj(true);
}
const auto readHandler = [](void* data, unsigned char* buffer, size_t size, size_t* size_read) {
auto* const reader = static_cast<athena::io::IStreamReader*>(data);
return athena::io::YAMLAthenaReader(reader, buffer, size, size_read);
};
yaml_parser_set_input(r.getParser(), readHandler, &reader);
if (!r.ValidateClassType("UrdeSpacesState")) {
return makeProj(true);
}
r.reset();
reader.seek(0, athena::SeekOrigin::Begin);
if (!r.parse(&reader)) {
return makeProj(true);
}
return makeProj(false);
}
bool ProjectManager::extractGame(hecl::SystemStringView path) { return false; }
bool ProjectManager::saveProject() {
if (!m_proj)
return false;
hecl::ProjectPath oldSpacesPath(*m_proj, _SYS_STR(".hecl/~urde_spaces.yaml"));
athena::io::FileWriter writer(oldSpacesPath.getAbsolutePath());
if (!writer.isOpen())
return false;
athena::io::YAMLDocWriter w("UrdeSpacesState");
m_vm.SaveEditorView(w);
if (!w.finish(&writer))
return false;
hecl::ProjectPath newSpacesPath(*m_proj, _SYS_STR(".hecl/urde_spaces.yaml"));
hecl::Unlink(newSpacesPath.getAbsolutePath().data());
hecl::Rename(oldSpacesPath.getAbsolutePath().data(), newSpacesPath.getAbsolutePath().data());
m_vm.pushRecentProject(m_proj->getProjectRootPath().getAbsolutePath());
return true;
}
void ProjectManager::mainUpdate() {
if (m_precooking) {
if (!m_factoryMP1.IsBusy())
m_precooking = false;
else
return;
}
if (m_mainMP1) {
if (m_mainMP1->Proc()) {
m_mainMP1->Shutdown();
m_mainMP1 = std::nullopt;
}
}
}
void ProjectManager::mainDraw() {
if (m_precooking)
return;
if (m_mainMP1)
m_mainMP1->Draw();
}
void ProjectManager::shutdown() {
if (m_mainMP1)
m_mainMP1->Shutdown();
m_clientProc.shutdown();
m_factoryMP1.Shutdown();
hecl::blender::Connection::Shutdown();
}
} // namespace urde
<|endoftext|>
|
<commit_before>#pragma once
#include "connected_devices.hpp"
#include "constants.hpp"
#include "filesystem.hpp"
#include "logger.hpp"
#include "session.hpp"
#include "types.hpp"
#include <fstream>
#include <json/json.hpp>
#include <natural_sort/natural_sort.hpp>
#include <string>
#include <unordered_map>
// Example: tests/src/core_configuration/json/example.json
namespace krbn {
class core_configuration final {
public:
#include "core_configuration/global_configuration.hpp"
class profile final {
public:
#include "core_configuration/profile/complex_modifications.hpp"
#include "core_configuration/profile/simple_modifications.hpp"
#include "core_configuration/profile/virtual_hid_keyboard.hpp"
#include "core_configuration/profile/device.hpp"
profile(const nlohmann::json& json) : json_(json),
selected_(false),
simple_modifications_(json.find("simple_modifications") != json.end() ? json["simple_modifications"] : nlohmann::json()),
fn_function_keys_(nlohmann::json({
{"f1", "display_brightness_decrement"},
{"f2", "display_brightness_increment"},
{"f3", "mission_control"},
{"f4", "launchpad"},
{"f5", "illumination_decrement"},
{"f6", "illumination_increment"},
{"f7", "rewind"},
{"f8", "play_or_pause"},
{"f9", "fastforward"},
{"f10", "mute"},
{"f11", "volume_decrement"},
{"f12", "volume_increment"},
})),
complex_modifications_(json.find("complex_modifications") != json.end() ? json["complex_modifications"] : nlohmann::json()),
virtual_hid_keyboard_(json.find("virtual_hid_keyboard") != json.end() ? json["virtual_hid_keyboard"] : nlohmann::json()) {
{
const std::string key = "name";
if (json.find(key) != json.end() && json[key].is_string()) {
name_ = json[key];
}
}
{
const std::string key = "selected";
if (json.find(key) != json.end() && json[key].is_boolean()) {
selected_ = json[key];
}
}
{
const std::string key = "fn_function_keys";
if (json.find(key) != json.end() && json[key].is_object()) {
for (auto it = json[key].begin(); it != json[key].end(); ++it) {
// it.key() is always std::string.
if (it.value().is_string()) {
fn_function_keys_.replace_second(it.key(), it.value());
}
}
}
}
{
const std::string key = "devices";
if (json.find(key) != json.end() && json[key].is_array()) {
for (const auto& device_json : json[key]) {
devices_.emplace_back(device_json);
}
}
}
}
nlohmann::json to_json(void) const {
auto j = json_;
j["name"] = name_;
j["selected"] = selected_;
j["simple_modifications"] = simple_modifications_;
j["fn_function_keys"] = fn_function_keys_;
j["complex_modifications"] = complex_modifications_;
j["virtual_hid_keyboard"] = virtual_hid_keyboard_;
j["devices"] = devices_;
return j;
}
const std::string& get_name(void) const {
return name_;
}
void set_name(const std::string& value) {
name_ = value;
}
bool get_selected(void) const {
return selected_;
}
void set_selected(bool value) {
selected_ = value;
}
const simple_modifications& get_simple_modifications(void) const {
return simple_modifications_;
}
simple_modifications& get_simple_modifications(void) {
return const_cast<simple_modifications&>(static_cast<const profile&>(*this).get_simple_modifications());
}
const simple_modifications* find_simple_modifications(const device_identifiers& identifiers) const {
for (const auto& d : devices_) {
if (d.get_identifiers() == identifiers) {
return &(d.get_simple_modifications());
}
}
return nullptr;
}
simple_modifications* find_simple_modifications(const device_identifiers& identifiers) {
return const_cast<simple_modifications*>(static_cast<const profile&>(*this).find_simple_modifications(identifiers));
}
const simple_modifications& get_fn_function_keys(void) const {
return fn_function_keys_;
}
simple_modifications& get_fn_function_keys(void) {
return const_cast<simple_modifications&>(static_cast<const profile&>(*this).get_fn_function_keys());
}
const simple_modifications* find_fn_function_keys(const device_identifiers& identifiers) const {
for (const auto& d : devices_) {
if (d.get_identifiers() == identifiers) {
return &(d.get_fn_function_keys());
}
}
return nullptr;
}
simple_modifications* find_fn_function_keys(const device_identifiers& identifiers) {
return const_cast<simple_modifications*>(static_cast<const profile&>(*this).find_fn_function_keys(identifiers));
}
const complex_modifications& get_complex_modifications(void) const {
return complex_modifications_;
}
void push_back_complex_modifications_rule(const profile::complex_modifications::rule& rule) {
complex_modifications_.push_back_rule(rule);
}
void erase_complex_modifications_rule(size_t index) {
complex_modifications_.erase_rule(index);
}
void swap_complex_modifications_rules(size_t index1, size_t index2) {
complex_modifications_.swap_rules(index1, index2);
}
void set_complex_modifications_parameter(const std::string& name, int value) {
complex_modifications_.set_parameter_value(name, value);
}
const virtual_hid_keyboard& get_virtual_hid_keyboard(void) const {
return virtual_hid_keyboard_;
}
virtual_hid_keyboard& get_virtual_hid_keyboard(void) {
return virtual_hid_keyboard_;
}
const std::vector<device>& get_devices(void) const {
return devices_;
}
bool get_device_ignore(const device_identifiers& identifiers) {
for (const auto& d : devices_) {
if (d.get_identifiers() == identifiers) {
return d.get_ignore();
}
}
return false;
}
void set_device_ignore(const device_identifiers& identifiers,
bool ignore) {
for (auto&& device : devices_) {
if (device.get_identifiers() == identifiers) {
device.set_ignore(ignore);
return;
}
}
auto json = nlohmann::json({
{"identifiers", identifiers.to_json()},
{"ignore", ignore},
});
devices_.emplace_back(json);
}
bool get_device_disable_built_in_keyboard_if_exists(const device_identifiers& identifiers) {
for (const auto& d : devices_) {
if (d.get_identifiers() == identifiers) {
return d.get_disable_built_in_keyboard_if_exists();
}
}
return false;
}
void set_device_disable_built_in_keyboard_if_exists(const device_identifiers& identifiers,
bool disable_built_in_keyboard_if_exists) {
for (auto&& device : devices_) {
if (device.get_identifiers() == identifiers) {
device.set_disable_built_in_keyboard_if_exists(disable_built_in_keyboard_if_exists);
return;
}
}
auto json = nlohmann::json({
{"identifiers", identifiers.to_json()},
{"disable_built_in_keyboard_if_exists", disable_built_in_keyboard_if_exists},
});
devices_.emplace_back(json);
}
private:
nlohmann::json json_;
std::string name_;
bool selected_;
simple_modifications simple_modifications_;
simple_modifications fn_function_keys_;
complex_modifications complex_modifications_;
virtual_hid_keyboard virtual_hid_keyboard_;
std::vector<device> devices_;
};
core_configuration(const core_configuration&) = delete;
core_configuration(const std::string& file_path) : loaded_(true),
global_configuration_(nlohmann::json()) {
bool valid_file_owner = false;
// Load karabiner.json only when the owner is root or current session user.
if (filesystem::exists(file_path)) {
if (filesystem::is_owned(file_path, 0)) {
valid_file_owner = true;
} else {
if (auto console_user_id = session::get_current_console_user_id()) {
if (filesystem::is_owned(file_path, *console_user_id)) {
valid_file_owner = true;
}
}
}
if (!valid_file_owner) {
logger::get_logger().warn("{0} is not owned by a valid user.", file_path);
loaded_ = false;
} else {
std::ifstream input(file_path);
if (input) {
try {
json_ = nlohmann::json::parse(input);
{
const std::string key = "global";
if (json_.find(key) != json_.end()) {
global_configuration_ = global_configuration(json_[key]);
}
}
{
const std::string key = "profiles";
if (json_.find(key) != json_.end() && json_[key].is_array()) {
for (const auto& profile_json : json_[key]) {
profiles_.emplace_back(profile_json);
}
}
}
} catch (std::exception& e) {
logger::get_logger().error("parse error in {0}: {1}", file_path, e.what());
json_ = nlohmann::json();
loaded_ = false;
}
}
}
}
// Fallbacks
if (profiles_.empty()) {
profiles_.emplace_back(nlohmann::json({
{"name", "Default profile"},
{"selected", true},
}));
}
}
nlohmann::json to_json(void) const {
auto j = json_;
j["global"] = global_configuration_;
j["profiles"] = profiles_;
return j;
}
bool is_loaded(void) const { return loaded_; }
const global_configuration& get_global_configuration(void) const {
return global_configuration_;
}
global_configuration& get_global_configuration(void) {
return global_configuration_;
}
const std::vector<profile>& get_profiles(void) const {
return profiles_;
}
void set_profile_name(size_t index, const std::string name) {
if (index < profiles_.size()) {
profiles_[index].set_name(name);
}
}
void select_profile(size_t index) {
if (index < profiles_.size()) {
for (size_t i = 0; i < profiles_.size(); ++i) {
if (i == index) {
profiles_[i].set_selected(true);
} else {
profiles_[i].set_selected(false);
}
}
}
}
void push_back_profile(void) {
profiles_.emplace_back(nlohmann::json({
{"name", "New profile"},
}));
}
void erase_profile(size_t index) {
if (index < profiles_.size()) {
if (profiles_.size() > 1) {
profiles_.erase(profiles_.begin() + index);
}
}
}
profile& get_selected_profile(void) {
for (auto&& profile : profiles_) {
if (profile.get_selected()) {
return profile;
}
}
return profiles_[0];
}
// Note:
// Be careful calling `save` method.
// If the configuration file is corrupted temporarily (user editing the configuration file in editor),
// the user data will be lost by the `save` method.
// Thus, we should call the `save` method only when it is neccessary.
bool save_to_file(const std::string& file_path) {
filesystem::create_directory_with_intermediate_directories(filesystem::dirname(file_path), 0700);
std::ofstream output(file_path);
if (!output) {
return false;
}
output << std::setw(4) << to_json() << std::endl;
return true;
}
private:
nlohmann::json json_;
bool loaded_;
global_configuration global_configuration_;
std::vector<profile> profiles_;
};
inline void to_json(nlohmann::json& json, const core_configuration::global_configuration& global_configuration) {
json = global_configuration.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile& profile) {
json = profile.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::simple_modifications& simple_modifications) {
json = simple_modifications.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::complex_modifications& complex_modifications) {
json = complex_modifications.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::complex_modifications::rule& rule) {
json = rule.get_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::complex_modifications::parameters& parameters) {
json = parameters.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::virtual_hid_keyboard& virtual_hid_keyboard) {
json = virtual_hid_keyboard.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::device& device) {
json = device.to_json();
}
} // namespace krbn
<commit_msg>add add_device<commit_after>#pragma once
#include "connected_devices.hpp"
#include "constants.hpp"
#include "filesystem.hpp"
#include "logger.hpp"
#include "session.hpp"
#include "types.hpp"
#include <fstream>
#include <json/json.hpp>
#include <natural_sort/natural_sort.hpp>
#include <string>
#include <unordered_map>
// Example: tests/src/core_configuration/json/example.json
namespace krbn {
class core_configuration final {
public:
#include "core_configuration/global_configuration.hpp"
class profile final {
public:
#include "core_configuration/profile/complex_modifications.hpp"
#include "core_configuration/profile/simple_modifications.hpp"
#include "core_configuration/profile/virtual_hid_keyboard.hpp"
#include "core_configuration/profile/device.hpp"
profile(const nlohmann::json& json) : json_(json),
selected_(false),
simple_modifications_(json.find("simple_modifications") != json.end() ? json["simple_modifications"] : nlohmann::json()),
fn_function_keys_(nlohmann::json({
{"f1", "display_brightness_decrement"},
{"f2", "display_brightness_increment"},
{"f3", "mission_control"},
{"f4", "launchpad"},
{"f5", "illumination_decrement"},
{"f6", "illumination_increment"},
{"f7", "rewind"},
{"f8", "play_or_pause"},
{"f9", "fastforward"},
{"f10", "mute"},
{"f11", "volume_decrement"},
{"f12", "volume_increment"},
})),
complex_modifications_(json.find("complex_modifications") != json.end() ? json["complex_modifications"] : nlohmann::json()),
virtual_hid_keyboard_(json.find("virtual_hid_keyboard") != json.end() ? json["virtual_hid_keyboard"] : nlohmann::json()) {
{
const std::string key = "name";
if (json.find(key) != json.end() && json[key].is_string()) {
name_ = json[key];
}
}
{
const std::string key = "selected";
if (json.find(key) != json.end() && json[key].is_boolean()) {
selected_ = json[key];
}
}
{
const std::string key = "fn_function_keys";
if (json.find(key) != json.end() && json[key].is_object()) {
for (auto it = json[key].begin(); it != json[key].end(); ++it) {
// it.key() is always std::string.
if (it.value().is_string()) {
fn_function_keys_.replace_second(it.key(), it.value());
}
}
}
}
{
const std::string key = "devices";
if (json.find(key) != json.end() && json[key].is_array()) {
for (const auto& device_json : json[key]) {
devices_.emplace_back(device_json);
}
}
}
}
nlohmann::json to_json(void) const {
auto j = json_;
j["name"] = name_;
j["selected"] = selected_;
j["simple_modifications"] = simple_modifications_;
j["fn_function_keys"] = fn_function_keys_;
j["complex_modifications"] = complex_modifications_;
j["virtual_hid_keyboard"] = virtual_hid_keyboard_;
j["devices"] = devices_;
return j;
}
const std::string& get_name(void) const {
return name_;
}
void set_name(const std::string& value) {
name_ = value;
}
bool get_selected(void) const {
return selected_;
}
void set_selected(bool value) {
selected_ = value;
}
const simple_modifications& get_simple_modifications(void) const {
return simple_modifications_;
}
simple_modifications& get_simple_modifications(void) {
return const_cast<simple_modifications&>(static_cast<const profile&>(*this).get_simple_modifications());
}
const simple_modifications* find_simple_modifications(const device_identifiers& identifiers) const {
for (const auto& d : devices_) {
if (d.get_identifiers() == identifiers) {
return &(d.get_simple_modifications());
}
}
return nullptr;
}
simple_modifications* find_simple_modifications(const device_identifiers& identifiers) {
add_device(identifiers);
return const_cast<simple_modifications*>(static_cast<const profile&>(*this).find_simple_modifications(identifiers));
}
const simple_modifications& get_fn_function_keys(void) const {
return fn_function_keys_;
}
simple_modifications& get_fn_function_keys(void) {
return const_cast<simple_modifications&>(static_cast<const profile&>(*this).get_fn_function_keys());
}
const simple_modifications* find_fn_function_keys(const device_identifiers& identifiers) const {
for (const auto& d : devices_) {
if (d.get_identifiers() == identifiers) {
return &(d.get_fn_function_keys());
}
}
return nullptr;
}
simple_modifications* find_fn_function_keys(const device_identifiers& identifiers) {
add_device(identifiers);
return const_cast<simple_modifications*>(static_cast<const profile&>(*this).find_fn_function_keys(identifiers));
}
const complex_modifications& get_complex_modifications(void) const {
return complex_modifications_;
}
void push_back_complex_modifications_rule(const profile::complex_modifications::rule& rule) {
complex_modifications_.push_back_rule(rule);
}
void erase_complex_modifications_rule(size_t index) {
complex_modifications_.erase_rule(index);
}
void swap_complex_modifications_rules(size_t index1, size_t index2) {
complex_modifications_.swap_rules(index1, index2);
}
void set_complex_modifications_parameter(const std::string& name, int value) {
complex_modifications_.set_parameter_value(name, value);
}
const virtual_hid_keyboard& get_virtual_hid_keyboard(void) const {
return virtual_hid_keyboard_;
}
virtual_hid_keyboard& get_virtual_hid_keyboard(void) {
return virtual_hid_keyboard_;
}
const std::vector<device>& get_devices(void) const {
return devices_;
}
bool get_device_ignore(const device_identifiers& identifiers) const {
for (const auto& d : devices_) {
if (d.get_identifiers() == identifiers) {
return d.get_ignore();
}
}
return false;
}
void set_device_ignore(const device_identifiers& identifiers,
bool ignore) {
add_device(identifiers);
for (auto&& device : devices_) {
if (device.get_identifiers() == identifiers) {
device.set_ignore(ignore);
return;
}
}
}
bool get_device_disable_built_in_keyboard_if_exists(const device_identifiers& identifiers) const {
for (const auto& d : devices_) {
if (d.get_identifiers() == identifiers) {
return d.get_disable_built_in_keyboard_if_exists();
}
}
return false;
}
void set_device_disable_built_in_keyboard_if_exists(const device_identifiers& identifiers,
bool disable_built_in_keyboard_if_exists) {
add_device(identifiers);
for (auto&& device : devices_) {
if (device.get_identifiers() == identifiers) {
device.set_disable_built_in_keyboard_if_exists(disable_built_in_keyboard_if_exists);
return;
}
}
}
private:
void add_device(const device_identifiers& identifiers) {
for (auto&& device : devices_) {
if (device.get_identifiers() == identifiers) {
return;
}
}
auto json = nlohmann::json({
{"identifiers", identifiers.to_json()},
});
devices_.emplace_back(json);
}
nlohmann::json json_;
std::string name_;
bool selected_;
simple_modifications simple_modifications_;
simple_modifications fn_function_keys_;
complex_modifications complex_modifications_;
virtual_hid_keyboard virtual_hid_keyboard_;
std::vector<device> devices_;
};
core_configuration(const core_configuration&) = delete;
core_configuration(const std::string& file_path) : loaded_(true),
global_configuration_(nlohmann::json()) {
bool valid_file_owner = false;
// Load karabiner.json only when the owner is root or current session user.
if (filesystem::exists(file_path)) {
if (filesystem::is_owned(file_path, 0)) {
valid_file_owner = true;
} else {
if (auto console_user_id = session::get_current_console_user_id()) {
if (filesystem::is_owned(file_path, *console_user_id)) {
valid_file_owner = true;
}
}
}
if (!valid_file_owner) {
logger::get_logger().warn("{0} is not owned by a valid user.", file_path);
loaded_ = false;
} else {
std::ifstream input(file_path);
if (input) {
try {
json_ = nlohmann::json::parse(input);
{
const std::string key = "global";
if (json_.find(key) != json_.end()) {
global_configuration_ = global_configuration(json_[key]);
}
}
{
const std::string key = "profiles";
if (json_.find(key) != json_.end() && json_[key].is_array()) {
for (const auto& profile_json : json_[key]) {
profiles_.emplace_back(profile_json);
}
}
}
} catch (std::exception& e) {
logger::get_logger().error("parse error in {0}: {1}", file_path, e.what());
json_ = nlohmann::json();
loaded_ = false;
}
}
}
}
// Fallbacks
if (profiles_.empty()) {
profiles_.emplace_back(nlohmann::json({
{"name", "Default profile"},
{"selected", true},
}));
}
}
nlohmann::json to_json(void) const {
auto j = json_;
j["global"] = global_configuration_;
j["profiles"] = profiles_;
return j;
}
bool is_loaded(void) const { return loaded_; }
const global_configuration& get_global_configuration(void) const {
return global_configuration_;
}
global_configuration& get_global_configuration(void) {
return global_configuration_;
}
const std::vector<profile>& get_profiles(void) const {
return profiles_;
}
void set_profile_name(size_t index, const std::string name) {
if (index < profiles_.size()) {
profiles_[index].set_name(name);
}
}
void select_profile(size_t index) {
if (index < profiles_.size()) {
for (size_t i = 0; i < profiles_.size(); ++i) {
if (i == index) {
profiles_[i].set_selected(true);
} else {
profiles_[i].set_selected(false);
}
}
}
}
void push_back_profile(void) {
profiles_.emplace_back(nlohmann::json({
{"name", "New profile"},
}));
}
void erase_profile(size_t index) {
if (index < profiles_.size()) {
if (profiles_.size() > 1) {
profiles_.erase(profiles_.begin() + index);
}
}
}
profile& get_selected_profile(void) {
for (auto&& profile : profiles_) {
if (profile.get_selected()) {
return profile;
}
}
return profiles_[0];
}
// Note:
// Be careful calling `save` method.
// If the configuration file is corrupted temporarily (user editing the configuration file in editor),
// the user data will be lost by the `save` method.
// Thus, we should call the `save` method only when it is neccessary.
bool save_to_file(const std::string& file_path) {
filesystem::create_directory_with_intermediate_directories(filesystem::dirname(file_path), 0700);
std::ofstream output(file_path);
if (!output) {
return false;
}
output << std::setw(4) << to_json() << std::endl;
return true;
}
private:
nlohmann::json json_;
bool loaded_;
global_configuration global_configuration_;
std::vector<profile> profiles_;
};
inline void to_json(nlohmann::json& json, const core_configuration::global_configuration& global_configuration) {
json = global_configuration.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile& profile) {
json = profile.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::simple_modifications& simple_modifications) {
json = simple_modifications.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::complex_modifications& complex_modifications) {
json = complex_modifications.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::complex_modifications::rule& rule) {
json = rule.get_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::complex_modifications::parameters& parameters) {
json = parameters.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::virtual_hid_keyboard& virtual_hid_keyboard) {
json = virtual_hid_keyboard.to_json();
}
inline void to_json(nlohmann::json& json, const core_configuration::profile::device& device) {
json = device.to_json();
}
} // namespace krbn
<|endoftext|>
|
<commit_before>#include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
#include "cinder/Rand.h"
#include "sansumbrella/Box2D.h"
#include "cinder/Triangulate.h"
using namespace ci;
using namespace ci::app;
using namespace std;
using namespace su;
class SandboxApp : public AppNative {
public:
void prepareSettings( Settings *settings );
void setup();
void mouseDown( MouseEvent event );
void mouseDrag( MouseEvent event );
void keyDown( KeyEvent event );
void update();
void draw();
private:
void addBox( const ci::Vec2f &loc );
void createCrazyShape();
void applyForceToShape( const ci::Vec2f &force );
Sandbox mSandbox;
Font mFont;
b2Body* mCrazyBody = nullptr;
};
void SandboxApp::prepareSettings(Settings *settings)
{
settings->setWindowSize( 1024, 768 );
settings->enableHighDensityDisplay();
}
void SandboxApp::setup()
{
mSandbox.init();
mSandbox.connectUserSignals( getWindow() );
try
{
mFont = Font( "Futura Medium", 18.0f );
}
catch( exception &exc )
{
cout << "Failed to load: " << exc.what() << endl;
mFont = Font( "Helvetica", 18.0f );
}
createCrazyShape();
}
void SandboxApp::keyDown(KeyEvent event)
{
#define CINDER_IOS true
#ifdef CINDER_IOS
#else
switch ( event.getCode() )
{
case KeyEvent::KEY_c:
createCrazyShape();
break;
case KeyEvent::KEY_UP:
applyForceToShape( Vec2f{ 0, -1000.0f } );
break;
case KeyEvent::KEY_DOWN:
applyForceToShape( Vec2f{ 0, 1000.0f } );
break;
case KeyEvent::KEY_RIGHT:
applyForceToShape( Vec2f{ 1000.0f, 0.0f } );
break;
case KeyEvent::KEY_LEFT:
applyForceToShape( Vec2f{ -1000.0f, 0.0f } );
break;
default:
break;
}
#endif
}
void SandboxApp::applyForceToShape(const ci::Vec2f &force)
{
mCrazyBody->ApplyForceToCenter( b2Vec2{ force.x, force.y } );
// mCrazyBody->ApplyForce( b2Vec2{ force.x, force.y}, b2Vec2{ mSandbox.toPhysics(getWindowWidth()/2), mSandbox.toPhysics(getWindowHeight()) } );
}
void SandboxApp::mouseDown( MouseEvent event )
{
if( !event.isAltDown() )
{
addBox( event.getPos() );
}
}
void SandboxApp::mouseDrag(MouseEvent event)
{
if( !event.isAltDown() )
{
addBox( event.getPos() );
}
}
void SandboxApp::addBox( const ci::Vec2f &loc )
{
mSandbox.createCircle( loc, Rand::randFloat( 5.0f, 20.0f ) );
// mSandbox.createBox( loc, Vec2f( Rand::randFloat(10.0f,40.0f), Rand::randFloat(10.0f,40.0f) ) );
}
void SandboxApp::createCrazyShape()
{
double d1 = getElapsedSeconds();
float d = Rand::randFloat( 0.5, 2.0f );
Path2d outline;
outline.moveTo( cos( 0 ) * d, sin( 0 ) * d );
const int points = 12;
for( int i = 1; i < points; ++i )
{
float t = lmap<float>( i, 0, points, 0, M_PI * 2 );
d = Rand::randFloat( 0.5, 2.0f );
outline.lineTo( cos( t ) * d, sin( t ) * d );
}
vector<b2Vec2> hull_vertices( outline.getNumPoints() );
for( int i = 0; i < hull_vertices.size(); ++i )
{
hull_vertices[i] = b2Vec2{ outline.getPoint(i).x, outline.getPoint(i).y };
}
if( mCrazyBody ){ mSandbox.destroyBody( mCrazyBody ); }
mCrazyBody = mSandbox.createFanShape( mSandbox.toPhysics( getWindowSize() / 2 ), hull_vertices );
// mCrazyBody = mSandbox.createShape( mSandbox.toPhysics( getWindowSize() / 2 ), Triangulator( outline, 1.0 ).calcMesh( Triangulator::WINDING_ODD ) );
double d2 = getElapsedSeconds();
cout << "Creating shape required: " << (d2 - d1) * 1000 << "ms" << endl;
}
void SandboxApp::update()
{
mSandbox.step();
}
void SandboxApp::draw()
{
gl::clear( Color::black() );
mSandbox.debugDraw();
gl::enableAlphaBlending();
gl::drawString( "Framerate: " + to_string(getAverageFps()), Vec2f( 10.0f, 10.0f ), Color::white(), mFont );
gl::drawString( "Num bodies: " + to_string(mSandbox.getBodyCount() ), Vec2f( 10.0f, 30.0f ), Color::white(), mFont );
gl::drawString( "Num contacts: " + to_string(mSandbox.getContactCount() ), Vec2f( 10.0f, 50.0f ), Color::white(), mFont );
}
CINDER_APP_NATIVE( SandboxApp, RendererGl( RendererGl::AA_NONE ) )
<commit_msg>Added license to file and random balls at start.<commit_after>/*
* Copyright (c) 2013 David Wicks
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
#include "cinder/Rand.h"
#include "sansumbrella/Box2D.h"
#include "cinder/Triangulate.h"
using namespace ci;
using namespace ci::app;
using namespace std;
using namespace su;
class SandboxApp : public AppNative {
public:
void prepareSettings( Settings *settings );
void setup();
void mouseDown( MouseEvent event );
void mouseDrag( MouseEvent event );
void keyDown( KeyEvent event );
void update();
void draw();
private:
void addBox( const ci::Vec2f &loc );
void createCrazyShape();
void applyForceToShape( const ci::Vec2f &force );
Sandbox mSandbox;
Font mFont;
b2Body* mCrazyBody = nullptr;
};
void SandboxApp::prepareSettings(Settings *settings)
{
settings->setWindowSize( 1024, 768 );
settings->enableHighDensityDisplay();
}
void SandboxApp::setup()
{
mSandbox.init();
mSandbox.connectUserSignals( getWindow() );
try
{
mFont = Font( "Futura Medium", 18.0f );
}
catch( exception &exc )
{
cout << "Failed to load: " << exc.what() << endl;
mFont = Font( "Helvetica", 18.0f );
}
createCrazyShape();
for( int i = 0; i < 100; ++i )
{
addBox( Vec2f{Rand::randFloat(getWindowWidth()), Rand::randFloat(getWindowHeight())} );
}
}
void SandboxApp::keyDown(KeyEvent event)
{
#ifdef CINDER_GLES
#else
switch ( event.getCode() )
{
case KeyEvent::KEY_c:
createCrazyShape();
break;
case KeyEvent::KEY_UP:
applyForceToShape( Vec2f{ 0, -1000.0f } );
break;
case KeyEvent::KEY_DOWN:
applyForceToShape( Vec2f{ 0, 1000.0f } );
break;
case KeyEvent::KEY_RIGHT:
applyForceToShape( Vec2f{ 1000.0f, 0.0f } );
break;
case KeyEvent::KEY_LEFT:
applyForceToShape( Vec2f{ -1000.0f, 0.0f } );
break;
default:
break;
}
#endif
}
void SandboxApp::applyForceToShape(const ci::Vec2f &force)
{
mCrazyBody->ApplyForceToCenter( b2Vec2{ force.x, force.y } );
// mCrazyBody->ApplyForce( b2Vec2{ force.x, force.y}, b2Vec2{ mSandbox.toPhysics(getWindowWidth()/2), mSandbox.toPhysics(getWindowHeight()) } );
}
void SandboxApp::mouseDown( MouseEvent event )
{
if( !event.isAltDown() )
{
addBox( event.getPos() );
}
}
void SandboxApp::mouseDrag(MouseEvent event)
{
if( !event.isAltDown() )
{
addBox( event.getPos() );
}
}
void SandboxApp::addBox( const ci::Vec2f &loc )
{
mSandbox.createCircle( loc, Rand::randFloat( 5.0f, 20.0f ) );
// mSandbox.createBox( loc, Vec2f( Rand::randFloat(10.0f,40.0f), Rand::randFloat(10.0f,40.0f) ) );
}
void SandboxApp::createCrazyShape()
{
double d1 = getElapsedSeconds();
float d = Rand::randFloat( 0.5, 2.0f );
Path2d outline;
outline.moveTo( cos( 0 ) * d, sin( 0 ) * d );
const int points = 12;
for( int i = 1; i < points; ++i )
{
float t = lmap<float>( i, 0, points, 0, M_PI * 2 );
d = Rand::randFloat( 0.5, 2.0f );
outline.lineTo( cos( t ) * d, sin( t ) * d );
}
vector<b2Vec2> hull_vertices( outline.getNumPoints() );
for( int i = 0; i < hull_vertices.size(); ++i )
{
hull_vertices[i] = b2Vec2{ outline.getPoint(i).x, outline.getPoint(i).y };
}
if( mCrazyBody ){ mSandbox.destroyBody( mCrazyBody ); }
mCrazyBody = mSandbox.createFanShape( mSandbox.toPhysics( getWindowSize() / 2 ), hull_vertices );
// mCrazyBody = mSandbox.createShape( mSandbox.toPhysics( getWindowSize() / 2 ), Triangulator( outline, 1.0 ).calcMesh( Triangulator::WINDING_ODD ) );
double d2 = getElapsedSeconds();
cout << "Creating shape required: " << (d2 - d1) * 1000 << "ms" << endl;
}
void SandboxApp::update()
{
mSandbox.step();
}
void SandboxApp::draw()
{
gl::clear( Color::black() );
mSandbox.debugDraw();
}
CINDER_APP_NATIVE( SandboxApp, RendererGl( RendererGl::AA_NONE ) )
<|endoftext|>
|
<commit_before>#include "app.h"
#include <QFileOpenEvent>
#include <QTextStream>
#include <QFileInfo>
#include <QDir>
#include "mainwindow.h"
namespace NeovimQt {
/// A log handler for Qt messages, all messages are dumped into the file
/// passed via the NVIM_QT_LOG variable. Some information is only available
/// in debug builds (e.g. qDebug is only called in debug builds).
///
/// In UNIX Qt prints messages to the console output, but in Windows this is
/// the only way to get Qt's debug/warning messages.
void logger(QtMsgType type, const QMessageLogContext& ctx, const QString& msg)
{
QFile logFile(qgetenv("NVIM_QT_LOG"));
if (logFile.open(QIODevice::Append | QIODevice::Text)) {
QTextStream stream(&logFile);
stream << msg << "\n";
}
}
#ifdef Q_OS_MAC
bool getLoginEnvironment(const QString& path)
{
QProcess proc;
proc.start(path, {"-l", "-c", "env", "-i"});
if (!proc.waitForFinished()) {
qDebug() << "Failed to execute shell to get environemnt" << path;
return false;
}
QByteArray out = proc.readAllStandardOutput();
foreach(const QByteArray& item, out.split('\n')) {
int index = item.indexOf('=');
if (index > 0) {
qputenv(item.mid(0, index), item.mid(index+1));
qDebug() << item.mid(0, index) << item.mid(index+1);
}
}
return true;
}
#endif
App::App(int &argc, char ** argv)
:QApplication(argc, argv)
{
setWindowIcon(QIcon(":/neovim.png"));
setApplicationDisplayName("Neovim");
#ifdef Q_OS_MAC
QByteArray shellPath = qgetenv("SHELL");
if (!getLoginEnvironment(shellPath)) {
getLoginEnvironment("/bin/bash");
}
#endif
if (!qgetenv("NVIM_QT_LOG").isEmpty()) {
qInstallMessageHandler(logger);
}
}
bool App::event(QEvent *event)
{
if( event->type() == QEvent::FileOpen) {
QFileOpenEvent * fileOpenEvent = static_cast<QFileOpenEvent *>(event);
if(fileOpenEvent) {
emit openFilesTriggered({fileOpenEvent->url()});
}
}
return QApplication::event(event);
}
void App::showUi(NeovimConnector *c, const QCommandLineParser& parser)
{
#ifdef NEOVIMQT_GUI_WIDGET
NeovimQt::Shell *win = new NeovimQt::Shell(c);
win->show();
if (parser.isSet("fullscreen")) {
win->showFullScreen();
} else if (parser.isSet("maximized")) {
win->showMaximized();
} else {
win->show();
}
#else
NeovimQt::MainWindow *win = new NeovimQt::MainWindow(c);
QObject::connect(instance(), SIGNAL(openFilesTriggered(const QList<QUrl>)),
win->shell(), SLOT(openFiles(const QList<QUrl>)));
if (parser.isSet("fullscreen")) {
win->delayedShow(NeovimQt::MainWindow::DelayedShow::FullScreen);
} else if (parser.isSet("maximized")) {
win->delayedShow(NeovimQt::MainWindow::DelayedShow::Maximized);
} else {
win->delayedShow();
}
#endif
}
/// Initialize CLI parser with all the nvim-qt options, process the
/// provided arguments and check for errors.
///
/// When appropriate this function will call QCommandLineParser::showHelp()
/// terminating the program.
void App::processCliOptions(QCommandLineParser &parser, const QStringList& arguments)
{
parser.addOption(QCommandLineOption("nvim",
QCoreApplication::translate("main", "nvim executable path"),
QCoreApplication::translate("main", "nvim_path"),
"nvim"));
parser.addOption(QCommandLineOption("timeout",
QCoreApplication::translate("main", "Error if nvim does not responde after count milliseconds"),
QCoreApplication::translate("main", "ms"),
"10000"));
parser.addOption(QCommandLineOption("geometry",
QCoreApplication::translate("main", "Initial window geometry"),
QCoreApplication::translate("main", "geometry")));
parser.addOption(QCommandLineOption("stylesheet",
QCoreApplication::translate("main", "Apply qss stylesheet from file"),
QCoreApplication::translate("main", "stylesheet")));
parser.addOption(QCommandLineOption("maximized",
QCoreApplication::translate("main", "Maximize the window on startup")));
parser.addOption(QCommandLineOption("fullscreen",
QCoreApplication::translate("main", "Open the window in fullscreen on startup")));
parser.addOption(QCommandLineOption("embed",
QCoreApplication::translate("main", "Communicate with Neovim over stdin/out")));
parser.addOption(QCommandLineOption("server",
QCoreApplication::translate("main", "Connect to existing Neovim instance"),
QCoreApplication::translate("main", "addr")));
parser.addOption(QCommandLineOption("spawn",
QCoreApplication::translate("main", "Treat positional arguments as the nvim argv")));
parser.addHelpOption();
#ifdef Q_OS_UNIX
parser.addOption(QCommandLineOption("nofork",
QCoreApplication::translate("main", "Run in foreground")));
#endif
parser.addPositionalArgument("file",
QCoreApplication::translate("main", "Edit specified file(s)"), "[file...]");
parser.addPositionalArgument("...", "Additional arguments are fowarded to Neovim", "[-- ...]");
parser.process(arguments);
if (parser.isSet("help")) {
parser.showHelp();
}
int exclusive = parser.isSet("server") + parser.isSet("embed") + parser.isSet("spawn");
if (exclusive > 1) {
qWarning() << "Options --server, --spawn and --embed are mutually exclusive\n";
::exit(-1);
}
if (!parser.positionalArguments().isEmpty() &&
(parser.isSet("embed") || parser.isSet("server"))) {
qWarning() << "--embed and --server do not accept positional arguments\n";
::exit(-1);
}
if (parser.positionalArguments().isEmpty() && parser.isSet("spawn")) {
qWarning() << "--spawn requires at least one positional argument\n";
::exit(-1);
}
bool valid_timeout;
int timeout_opt = parser.value("timeout").toInt(&valid_timeout);
if (!valid_timeout || timeout_opt <= 0) {
qWarning() << "Invalid argument for --timeout" << parser.value("timeout");
::exit(-1);
}
}
NeovimConnector* App::createConnector(const QCommandLineParser& parser)
{
if (parser.isSet("embed")) {
return NeovimQt::NeovimConnector::fromStdinOut();
} else if (parser.isSet("server")) {
QString server = parser.value("server");
return NeovimQt::NeovimConnector::connectToNeovim(server);
} else if (parser.isSet("spawn") && !parser.positionalArguments().isEmpty()) {
const QStringList& args = parser.positionalArguments();
return NeovimQt::NeovimConnector::spawn(args.mid(1), args.at(0));
} else {
QStringList neovimArgs;
neovimArgs << "--cmd";
neovimArgs << "set termguicolors";
auto path = qgetenv("NVIM_QT_RUNTIME_PATH");
if (QFileInfo(path).isDir()) {
neovimArgs.insert(0, "--cmd");
neovimArgs.insert(1, QString("let &rtp.=',%1'")
.arg(QString::fromLocal8Bit(path)));
}
#ifdef NVIM_QT_RUNTIME_PATH
else if (QFileInfo(NVIM_QT_RUNTIME_PATH).isDir()) {
neovimArgs.insert(0, "--cmd");
neovimArgs.insert(1, QString("let &rtp.=',%1'")
.arg(NVIM_QT_RUNTIME_PATH));
} else
#endif
{
// Look for the runtime relative to the nvim-qt binary
QDir d = QFileInfo(QCoreApplication::applicationDirPath()).dir();
#ifdef Q_OS_MAC
// within the bundle at ../Resources/runtime
d.cd("Resources");
d.cd("runtime");
#else
// ../share/nvim-qt/runtime
d.cd("share");
d.cd("nvim-qt");
d.cd("runtime");
#endif
if (d.exists()) {
neovimArgs.insert(0, "--cmd");
neovimArgs.insert(1, QString("let &rtp.=',%1'")
.arg(d.path()));
}
}
// Pass positional file arguments to Neovim
neovimArgs.append(parser.positionalArguments());
return NeovimQt::NeovimConnector::spawn(neovimArgs, parser.value("nvim"));
}
}
} // Namespace
<commit_msg>GUI: Load Qt stylesheet from NVIM_QT_STYLESHEET<commit_after>#include "app.h"
#include <QFileOpenEvent>
#include <QTextStream>
#include <QFileInfo>
#include <QDir>
#include "mainwindow.h"
namespace NeovimQt {
/// A log handler for Qt messages, all messages are dumped into the file
/// passed via the NVIM_QT_LOG variable. Some information is only available
/// in debug builds (e.g. qDebug is only called in debug builds).
///
/// In UNIX Qt prints messages to the console output, but in Windows this is
/// the only way to get Qt's debug/warning messages.
void logger(QtMsgType type, const QMessageLogContext& ctx, const QString& msg)
{
QFile logFile(qgetenv("NVIM_QT_LOG"));
if (logFile.open(QIODevice::Append | QIODevice::Text)) {
QTextStream stream(&logFile);
stream << msg << "\n";
}
}
#ifdef Q_OS_MAC
bool getLoginEnvironment(const QString& path)
{
QProcess proc;
proc.start(path, {"-l", "-c", "env", "-i"});
if (!proc.waitForFinished()) {
qDebug() << "Failed to execute shell to get environemnt" << path;
return false;
}
QByteArray out = proc.readAllStandardOutput();
foreach(const QByteArray& item, out.split('\n')) {
int index = item.indexOf('=');
if (index > 0) {
qputenv(item.mid(0, index), item.mid(index+1));
qDebug() << item.mid(0, index) << item.mid(index+1);
}
}
return true;
}
#endif
App::App(int &argc, char ** argv)
:QApplication(argc, argv)
{
setWindowIcon(QIcon(":/neovim.png"));
setApplicationDisplayName("Neovim");
#ifdef Q_OS_MAC
QByteArray shellPath = qgetenv("SHELL");
if (!getLoginEnvironment(shellPath)) {
getLoginEnvironment("/bin/bash");
}
#endif
if (!qgetenv("NVIM_QT_LOG").isEmpty()) {
qInstallMessageHandler(logger);
}
QByteArray stylesheet_path = qgetenv("NVIM_QT_STYLESHEET");
if (!stylesheet_path.isEmpty()) {
QFile qssfile(stylesheet_path);
if (qssfile.open(QIODevice::ReadOnly)) {
setStyleSheet(qssfile.readAll());
} else {
qWarning("Unable to open stylesheet from $NVIM_QT_STYLESHEET");
}
}
}
bool App::event(QEvent *event)
{
if( event->type() == QEvent::FileOpen) {
QFileOpenEvent * fileOpenEvent = static_cast<QFileOpenEvent *>(event);
if(fileOpenEvent) {
emit openFilesTriggered({fileOpenEvent->url()});
}
}
return QApplication::event(event);
}
void App::showUi(NeovimConnector *c, const QCommandLineParser& parser)
{
#ifdef NEOVIMQT_GUI_WIDGET
NeovimQt::Shell *win = new NeovimQt::Shell(c);
win->show();
if (parser.isSet("fullscreen")) {
win->showFullScreen();
} else if (parser.isSet("maximized")) {
win->showMaximized();
} else {
win->show();
}
#else
NeovimQt::MainWindow *win = new NeovimQt::MainWindow(c);
QObject::connect(instance(), SIGNAL(openFilesTriggered(const QList<QUrl>)),
win->shell(), SLOT(openFiles(const QList<QUrl>)));
if (parser.isSet("fullscreen")) {
win->delayedShow(NeovimQt::MainWindow::DelayedShow::FullScreen);
} else if (parser.isSet("maximized")) {
win->delayedShow(NeovimQt::MainWindow::DelayedShow::Maximized);
} else {
win->delayedShow();
}
#endif
}
/// Initialize CLI parser with all the nvim-qt options, process the
/// provided arguments and check for errors.
///
/// When appropriate this function will call QCommandLineParser::showHelp()
/// terminating the program.
void App::processCliOptions(QCommandLineParser &parser, const QStringList& arguments)
{
parser.addOption(QCommandLineOption("nvim",
QCoreApplication::translate("main", "nvim executable path"),
QCoreApplication::translate("main", "nvim_path"),
"nvim"));
parser.addOption(QCommandLineOption("timeout",
QCoreApplication::translate("main", "Error if nvim does not responde after count milliseconds"),
QCoreApplication::translate("main", "ms"),
"10000"));
parser.addOption(QCommandLineOption("geometry",
QCoreApplication::translate("main", "Initial window geometry"),
QCoreApplication::translate("main", "geometry")));
parser.addOption(QCommandLineOption("stylesheet",
QCoreApplication::translate("main", "Apply qss stylesheet from file"),
QCoreApplication::translate("main", "stylesheet")));
parser.addOption(QCommandLineOption("maximized",
QCoreApplication::translate("main", "Maximize the window on startup")));
parser.addOption(QCommandLineOption("fullscreen",
QCoreApplication::translate("main", "Open the window in fullscreen on startup")));
parser.addOption(QCommandLineOption("embed",
QCoreApplication::translate("main", "Communicate with Neovim over stdin/out")));
parser.addOption(QCommandLineOption("server",
QCoreApplication::translate("main", "Connect to existing Neovim instance"),
QCoreApplication::translate("main", "addr")));
parser.addOption(QCommandLineOption("spawn",
QCoreApplication::translate("main", "Treat positional arguments as the nvim argv")));
parser.addHelpOption();
#ifdef Q_OS_UNIX
parser.addOption(QCommandLineOption("nofork",
QCoreApplication::translate("main", "Run in foreground")));
#endif
parser.addPositionalArgument("file",
QCoreApplication::translate("main", "Edit specified file(s)"), "[file...]");
parser.addPositionalArgument("...", "Additional arguments are fowarded to Neovim", "[-- ...]");
parser.process(arguments);
if (parser.isSet("help")) {
parser.showHelp();
}
int exclusive = parser.isSet("server") + parser.isSet("embed") + parser.isSet("spawn");
if (exclusive > 1) {
qWarning() << "Options --server, --spawn and --embed are mutually exclusive\n";
::exit(-1);
}
if (!parser.positionalArguments().isEmpty() &&
(parser.isSet("embed") || parser.isSet("server"))) {
qWarning() << "--embed and --server do not accept positional arguments\n";
::exit(-1);
}
if (parser.positionalArguments().isEmpty() && parser.isSet("spawn")) {
qWarning() << "--spawn requires at least one positional argument\n";
::exit(-1);
}
bool valid_timeout;
int timeout_opt = parser.value("timeout").toInt(&valid_timeout);
if (!valid_timeout || timeout_opt <= 0) {
qWarning() << "Invalid argument for --timeout" << parser.value("timeout");
::exit(-1);
}
}
NeovimConnector* App::createConnector(const QCommandLineParser& parser)
{
if (parser.isSet("embed")) {
return NeovimQt::NeovimConnector::fromStdinOut();
} else if (parser.isSet("server")) {
QString server = parser.value("server");
return NeovimQt::NeovimConnector::connectToNeovim(server);
} else if (parser.isSet("spawn") && !parser.positionalArguments().isEmpty()) {
const QStringList& args = parser.positionalArguments();
return NeovimQt::NeovimConnector::spawn(args.mid(1), args.at(0));
} else {
QStringList neovimArgs;
neovimArgs << "--cmd";
neovimArgs << "set termguicolors";
auto path = qgetenv("NVIM_QT_RUNTIME_PATH");
if (QFileInfo(path).isDir()) {
neovimArgs.insert(0, "--cmd");
neovimArgs.insert(1, QString("let &rtp.=',%1'")
.arg(QString::fromLocal8Bit(path)));
}
#ifdef NVIM_QT_RUNTIME_PATH
else if (QFileInfo(NVIM_QT_RUNTIME_PATH).isDir()) {
neovimArgs.insert(0, "--cmd");
neovimArgs.insert(1, QString("let &rtp.=',%1'")
.arg(NVIM_QT_RUNTIME_PATH));
} else
#endif
{
// Look for the runtime relative to the nvim-qt binary
QDir d = QFileInfo(QCoreApplication::applicationDirPath()).dir();
#ifdef Q_OS_MAC
// within the bundle at ../Resources/runtime
d.cd("Resources");
d.cd("runtime");
#else
// ../share/nvim-qt/runtime
d.cd("share");
d.cd("nvim-qt");
d.cd("runtime");
#endif
if (d.exists()) {
neovimArgs.insert(0, "--cmd");
neovimArgs.insert(1, QString("let &rtp.=',%1'")
.arg(d.path()));
}
}
// Pass positional file arguments to Neovim
neovimArgs.append(parser.positionalArguments());
return NeovimQt::NeovimConnector::spawn(neovimArgs, parser.value("nvim"));
}
}
} // Namespace
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright (C) 2016-2017 Kitsune Ral <kitsune-ral@users.sf.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "printer.h"
#include "exception.h"
#include <algorithm>
#include <locale>
enum {
CannotReadTemplateFile = PrinterCodes, CannotWriteToFile,
};
using namespace std;
using namespace kainjow::mustache;
Printer::Printer(context_type&& context, const vector<string>& templateFileNames,
const string& inputBasePath, string outputBasePath,
const string& outFilesListPath)
: _context(context), _outputBasePath(std::move(outputBasePath))
{
// Enriching the context with "My Mustache library"
_context.set("@filePartial", lambda2 {
[inputBasePath, this](const string& s, const renderer& render) {
ifstream ifs { inputBasePath + s };
if (!ifs.good())
{
ifs.open(inputBasePath + s + ".mustache");
if (!ifs.good())
{
cerr << "Failed to open file for a partial: "
<< inputBasePath + s << endl;
// FIXME: Figure a better error reporting mechanism
return "/* Failed to open " + inputBasePath + s + " */";
}
}
string embeddedTemplate;
getline(ifs, embeddedTemplate, '\0'); // Won't work on files with NULs
return render(embeddedTemplate, false);
}
});
_context.set("@cap", lambda2 {
[](const string& s, const renderer& render)
{
return capitalizedCopy(render(s, false));
}
});
_context.set("@toupper", lambda2 {
[](string s, const renderer& render) {
s = render(s, false);
transform(s.begin(), s.end(), s.begin(),
[] (char c) { return toupper(c, locale::classic()); });
return s;
}
});
_context.set("@tolower", lambda2 {
[](string s, const renderer& render) {
s = render(s, false);
transform(s.begin(), s.end(), s.begin(),
[] (char c) { return tolower(c, locale::classic()); });
return s;
}
});
for (const auto& templateFileName: templateFileNames)
{
auto templateFilePath = inputBasePath + templateFileName;
cout << "Opening " << templateFilePath << endl;
ifstream ifs { templateFilePath };
if (!ifs.good())
{
cerr << "Failed to open " << templateFilePath << std::endl;
fail(CannotReadTemplateFile);
}
string templateContents;
if (!getline(ifs, templateContents, '\0')) // Won't work on files with NULs
{
cerr << "Failed to read from " << templateFilePath << std::endl;
fail(CannotReadTemplateFile);
}
mustache fileTemplate { templateContents };
fileTemplate.set_custom_escape([](const string& s) { return s; });
_templates.emplace_back(dropSuffix(templateFileName, ".mustache"),
std::move(fileTemplate));
}
if (!outFilesListPath.empty())
{
cout << "Opening " << _outputBasePath << outFilesListPath << endl;
_outFilesList.open(_outputBasePath + outFilesListPath);
if (!_outFilesList)
cerr << "No out files list set or cannot write to the file";
}
}
template <typename ObjT>
inline void setList(ObjT* object, const string& name, list&& list)
{
if (list.empty())
(*object)[name + '?'] = true;
else
{
using namespace placeholders;
(*object)[name + '?'] = false;
for_each(list.begin(), list.end() - 1,
bind(&data::set, _1, "hasMore", true));
}
(*object)[name] = list;
}
void Printer::print(const Model& model) const
{
auto context = _context;
context.set("filenameBase", model.filename);
{
// Imports
list mImports;
for (const auto& import: model.imports)
mImports.emplace_back(import);
setList(&context, "imports", std::move(mImports));
}
{
// Data definitions
list mTypes;
for (const auto& type: model.types)
{
object mType { { "classname", type.name } };
list mFields;
for (const auto& f: type.fields)
{
mFields.emplace_back(
object { { "datatype", f.type }
, { "name", f.name }
});
}
setList(&mType, "vars", move(mFields));
mTypes.emplace_back(object { { "model", move(mType) } });
}
if (!mTypes.empty())
context.set("models", mTypes);
}
{
// Operations
list mClasses;
for (const auto& callClass: model.callClasses)
{
for (const auto& call: callClass.callOverloads)
{
object mClass { { "operationId", callClass.operationId }
, { "httpMethod", call.verb }
, { "path", call.path }
};
list mPathParts;
for (const auto& pp: call.pathParts)
mPathParts.emplace_back(object { { "part", pp } });
setList(&mClass, "pathParts", move(mPathParts));
for (const auto& pp: {
make_pair("pathParams", call.pathParams),
make_pair("queryParams", call.queryParams),
make_pair("headerParams", call.headerParams),
make_pair("bodyParams", call.bodyParams),
make_pair("allParams", call.collateParams())
})
{
list mParams;
for (const auto& param: pp.second)
{
mParams.emplace_back(
object { { "dataType", param.type }
, { "baseName", param.name }
, { "paramName", param.name }
});
}
setList(&mClass, pp.first, move(mParams));
}
mClasses.emplace_back(move(mClass));
}
}
if (!mClasses.empty())
context.set("operations",
object { { "className", "!!!TODO:undefined!!!" },
{ "operation", mClasses } }
);
}
for (auto fileTemplate: _templates)
{
ostringstream fileNameStr;
fileNameStr << _outputBasePath << model.fileDir;
fileTemplate.first.render({ "base", model.filename }, fileNameStr);
if (!fileTemplate.first.error_message().empty())
{
cerr << "When rendering the filename:" << endl
<< fileTemplate.first.error_message() << endl;
continue; // FIXME: should be fail()
}
const auto fileName = fileNameStr.str();
cout << "Printing " << fileName << endl;
ofstream ofs { fileName };
if (!ofs.good())
{
cerr << "Couldn't open " << fileName << " for writing" << endl;
fail(CannotWriteToFile);
}
fileTemplate.second.set_custom_escape([](const string& s) { return s; });
fileTemplate.second.render(context, ofs);
if (fileTemplate.second.error_message().empty())
_outFilesList << fileName << endl;
else
cerr << "When rendering the file:" << endl
<< fileTemplate.second.error_message() << endl;
}
}
<commit_msg>Printer: Added a missing endl to an error message<commit_after>/******************************************************************************
* Copyright (C) 2016-2017 Kitsune Ral <kitsune-ral@users.sf.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "printer.h"
#include "exception.h"
#include <algorithm>
#include <locale>
enum {
CannotReadTemplateFile = PrinterCodes, CannotWriteToFile,
};
using namespace std;
using namespace kainjow::mustache;
Printer::Printer(context_type&& context, const vector<string>& templateFileNames,
const string& inputBasePath, string outputBasePath,
const string& outFilesListPath)
: _context(context), _outputBasePath(std::move(outputBasePath))
{
// Enriching the context with "My Mustache library"
_context.set("@filePartial", lambda2 {
[inputBasePath, this](const string& s, const renderer& render) {
ifstream ifs { inputBasePath + s };
if (!ifs.good())
{
ifs.open(inputBasePath + s + ".mustache");
if (!ifs.good())
{
cerr << "Failed to open file for a partial: "
<< inputBasePath + s << endl;
// FIXME: Figure a better error reporting mechanism
return "/* Failed to open " + inputBasePath + s + " */";
}
}
string embeddedTemplate;
getline(ifs, embeddedTemplate, '\0'); // Won't work on files with NULs
return render(embeddedTemplate, false);
}
});
_context.set("@cap", lambda2 {
[](const string& s, const renderer& render)
{
return capitalizedCopy(render(s, false));
}
});
_context.set("@toupper", lambda2 {
[](string s, const renderer& render) {
s = render(s, false);
transform(s.begin(), s.end(), s.begin(),
[] (char c) { return toupper(c, locale::classic()); });
return s;
}
});
_context.set("@tolower", lambda2 {
[](string s, const renderer& render) {
s = render(s, false);
transform(s.begin(), s.end(), s.begin(),
[] (char c) { return tolower(c, locale::classic()); });
return s;
}
});
for (const auto& templateFileName: templateFileNames)
{
auto templateFilePath = inputBasePath + templateFileName;
cout << "Opening " << templateFilePath << endl;
ifstream ifs { templateFilePath };
if (!ifs.good())
{
cerr << "Failed to open " << templateFilePath << std::endl;
fail(CannotReadTemplateFile);
}
string templateContents;
if (!getline(ifs, templateContents, '\0')) // Won't work on files with NULs
{
cerr << "Failed to read from " << templateFilePath << std::endl;
fail(CannotReadTemplateFile);
}
mustache fileTemplate { templateContents };
fileTemplate.set_custom_escape([](const string& s) { return s; });
_templates.emplace_back(dropSuffix(templateFileName, ".mustache"),
std::move(fileTemplate));
}
if (!outFilesListPath.empty())
{
cout << "Opening " << _outputBasePath << outFilesListPath << endl;
_outFilesList.open(_outputBasePath + outFilesListPath);
if (!_outFilesList)
cerr << "No out files list set or cannot write to the file" << endl;
}
}
template <typename ObjT>
inline void setList(ObjT* object, const string& name, list&& list)
{
if (list.empty())
(*object)[name + '?'] = true;
else
{
using namespace placeholders;
(*object)[name + '?'] = false;
for_each(list.begin(), list.end() - 1,
bind(&data::set, _1, "hasMore", true));
}
(*object)[name] = list;
}
void Printer::print(const Model& model) const
{
auto context = _context;
context.set("filenameBase", model.filename);
{
// Imports
list mImports;
for (const auto& import: model.imports)
mImports.emplace_back(import);
setList(&context, "imports", std::move(mImports));
}
{
// Data definitions
list mTypes;
for (const auto& type: model.types)
{
object mType { { "classname", type.name } };
list mFields;
for (const auto& f: type.fields)
{
mFields.emplace_back(
object { { "datatype", f.type }
, { "name", f.name }
});
}
setList(&mType, "vars", move(mFields));
mTypes.emplace_back(object { { "model", move(mType) } });
}
if (!mTypes.empty())
context.set("models", mTypes);
}
{
// Operations
list mClasses;
for (const auto& callClass: model.callClasses)
{
for (const auto& call: callClass.callOverloads)
{
object mClass { { "operationId", callClass.operationId }
, { "httpMethod", call.verb }
, { "path", call.path }
};
list mPathParts;
for (const auto& pp: call.pathParts)
mPathParts.emplace_back(object { { "part", pp } });
setList(&mClass, "pathParts", move(mPathParts));
for (const auto& pp: {
make_pair("pathParams", call.pathParams),
make_pair("queryParams", call.queryParams),
make_pair("headerParams", call.headerParams),
make_pair("bodyParams", call.bodyParams),
make_pair("allParams", call.collateParams())
})
{
list mParams;
for (const auto& param: pp.second)
{
mParams.emplace_back(
object { { "dataType", param.type }
, { "baseName", param.name }
, { "paramName", param.name }
});
}
setList(&mClass, pp.first, move(mParams));
}
mClasses.emplace_back(move(mClass));
}
}
if (!mClasses.empty())
context.set("operations",
object { { "className", "!!!TODO:undefined!!!" },
{ "operation", mClasses } }
);
}
for (auto fileTemplate: _templates)
{
ostringstream fileNameStr;
fileNameStr << _outputBasePath << model.fileDir;
fileTemplate.first.render({ "base", model.filename }, fileNameStr);
if (!fileTemplate.first.error_message().empty())
{
cerr << "When rendering the filename:" << endl
<< fileTemplate.first.error_message() << endl;
continue; // FIXME: should be fail()
}
const auto fileName = fileNameStr.str();
cout << "Printing " << fileName << endl;
ofstream ofs { fileName };
if (!ofs.good())
{
cerr << "Couldn't open " << fileName << " for writing" << endl;
fail(CannotWriteToFile);
}
fileTemplate.second.set_custom_escape([](const string& s) { return s; });
fileTemplate.second.render(context, ofs);
if (fileTemplate.second.error_message().empty())
_outFilesList << fileName << endl;
else
cerr << "When rendering the file:" << endl
<< fileTemplate.second.error_message() << endl;
}
}
<|endoftext|>
|
<commit_before>// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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 <array>
#include <chrono>
#include <thread>
#include <ostream>
#include <vector>
#include "BitFunnel/Utilities/Factories.h"
#include "TaskDistributor.h"
#include "gtest/gtest.h"
namespace BitFunnel
{
namespace TaskDistributorTest
{
// Hard NUM_TASKSis a hack. This was done when ripping out
// ThreadsafeCounter in favor of std::atomic because this resulted
// in the quickest possible change.
#define NUM_TASKS 100
void RunTest1(unsigned taskCount, int maxSleepInMS);
class TaskProcessor : public ITaskProcessor, NonCopyable
{
public:
TaskProcessor(std::array<std::atomic<uint64_t>, NUM_TASKS>& tasks,
int maxSleepInMS,
std::atomic<uint64_t>& activeThreadCount);
void ProcessTask(size_t taskId);
void Finished();
void Print(std::ostream& out);
private:
std::atomic<uint64_t>& m_activeThreadCount;
unsigned m_callCount;
std::vector<std::chrono::milliseconds> m_randomWaits;
std::array<std::atomic<uint64_t>, NUM_TASKS>& m_tasks;
};
//*************************************************************************
//
// TaskDistributorTest
//
//*************************************************************************
TEST(TaskDistributor, Basic)
{
RunTest1(NUM_TASKS, 0);
RunTest1(NUM_TASKS, 3);
}
void RunTest1(unsigned taskCount, int maxSleepInMS)
{
const int threadCount = 10;
// The tasks vector will count the number of times each task is processed.
std::array<std::atomic<uint64_t>, NUM_TASKS> tasks{{}};
// Create one processor for each thread.
// TODO: Review use of srand in BitFunnel and unit tests.
// Usually we use a different random number generator for a variety of reasons.
srand(12345);
std::atomic<uint64_t> activeThreadCount(threadCount);
std::vector<std::unique_ptr<ITaskProcessor>> processors;
for (int i = 0 ; i < threadCount; ++i)
{
processors.push_back(std::unique_ptr<ITaskProcessor>(new TaskProcessor(tasks, maxSleepInMS, activeThreadCount)));
}
std::unique_ptr<ITaskDistributor> distributor(Factories::CreateTaskDistributor(processors, taskCount));
distributor->WaitForCompletion();
// Verify that ITaskProcessor::Finished() was called one time for each thread.
ASSERT_EQ(activeThreadCount.load(), 0u);
// Verify results that each task was done exactly once.
for (unsigned i = 0; i < taskCount; ++i)
{
ASSERT_EQ(tasks[i].load(), 1u);
}
}
//*************************************************************************
//
// TaskProcessor
//
//*************************************************************************
TaskProcessor::TaskProcessor(std::array<std::atomic<uint64_t>, NUM_TASKS>& tasks,
int maxSleepInMS,
std::atomic<uint64_t>& activeThreadCount)
: m_activeThreadCount(activeThreadCount),
m_callCount(0),
m_tasks(tasks)
{
if (maxSleepInMS > 0)
{
// Generate random waits in constructor to make test more reproducible
// than one that calls rand() from multiple threads.
for (int i = 0; i < 100; ++i)
{
// TODO: rand() % foo is a really bad RNG.
m_randomWaits.
push_back(std::chrono::milliseconds
(rand() % maxSleepInMS));
}
}
}
void TaskProcessor::ProcessTask(size_t taskId)
{
++m_callCount;
++m_tasks[taskId];
if (m_randomWaits.size() > 0)
{
std::this_thread::sleep_for(m_randomWaits[m_callCount % m_randomWaits.size()]);
}
}
void TaskProcessor::Finished()
{
--m_activeThreadCount;
}
void TaskProcessor::Print(std::ostream& out)
{
out << "call count = " << m_callCount << std::endl;
}
}
}
<commit_msg>Add another header required for Linux build.<commit_after>// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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 <array>
#include <atomic>
#include <chrono>
#include <thread>
#include <ostream>
#include <vector>
#include "BitFunnel/Utilities/Factories.h"
#include "TaskDistributor.h"
#include "gtest/gtest.h"
namespace BitFunnel
{
namespace TaskDistributorTest
{
// Hard NUM_TASKSis a hack. This was done when ripping out
// ThreadsafeCounter in favor of std::atomic because this resulted
// in the quickest possible change.
#define NUM_TASKS 100
void RunTest1(unsigned taskCount, int maxSleepInMS);
class TaskProcessor : public ITaskProcessor, NonCopyable
{
public:
TaskProcessor(std::array<std::atomic<uint64_t>, NUM_TASKS>& tasks,
int maxSleepInMS,
std::atomic<uint64_t>& activeThreadCount);
void ProcessTask(size_t taskId);
void Finished();
void Print(std::ostream& out);
private:
std::atomic<uint64_t>& m_activeThreadCount;
unsigned m_callCount;
std::vector<std::chrono::milliseconds> m_randomWaits;
std::array<std::atomic<uint64_t>, NUM_TASKS>& m_tasks;
};
//*************************************************************************
//
// TaskDistributorTest
//
//*************************************************************************
TEST(TaskDistributor, Basic)
{
RunTest1(NUM_TASKS, 0);
RunTest1(NUM_TASKS, 3);
}
void RunTest1(unsigned taskCount, int maxSleepInMS)
{
const int threadCount = 10;
// The tasks vector will count the number of times each task is processed.
std::array<std::atomic<uint64_t>, NUM_TASKS> tasks{{}};
// Create one processor for each thread.
// TODO: Review use of srand in BitFunnel and unit tests.
// Usually we use a different random number generator for a variety of reasons.
srand(12345);
std::atomic<uint64_t> activeThreadCount(threadCount);
std::vector<std::unique_ptr<ITaskProcessor>> processors;
for (int i = 0 ; i < threadCount; ++i)
{
processors.push_back(std::unique_ptr<ITaskProcessor>(new TaskProcessor(tasks, maxSleepInMS, activeThreadCount)));
}
std::unique_ptr<ITaskDistributor> distributor(Factories::CreateTaskDistributor(processors, taskCount));
distributor->WaitForCompletion();
// Verify that ITaskProcessor::Finished() was called one time for each thread.
ASSERT_EQ(activeThreadCount.load(), 0u);
// Verify results that each task was done exactly once.
for (unsigned i = 0; i < taskCount; ++i)
{
ASSERT_EQ(tasks[i].load(), 1u);
}
}
//*************************************************************************
//
// TaskProcessor
//
//*************************************************************************
TaskProcessor::TaskProcessor(std::array<std::atomic<uint64_t>, NUM_TASKS>& tasks,
int maxSleepInMS,
std::atomic<uint64_t>& activeThreadCount)
: m_activeThreadCount(activeThreadCount),
m_callCount(0),
m_tasks(tasks)
{
if (maxSleepInMS > 0)
{
// Generate random waits in constructor to make test more reproducible
// than one that calls rand() from multiple threads.
for (int i = 0; i < 100; ++i)
{
// TODO: rand() % foo is a really bad RNG.
m_randomWaits.
push_back(std::chrono::milliseconds
(rand() % maxSleepInMS));
}
}
}
void TaskProcessor::ProcessTask(size_t taskId)
{
++m_callCount;
++m_tasks[taskId];
if (m_randomWaits.size() > 0)
{
std::this_thread::sleep_for(m_randomWaits[m_callCount % m_randomWaits.size()]);
}
}
void TaskProcessor::Finished()
{
--m_activeThreadCount;
}
void TaskProcessor::Print(std::ostream& out)
{
out << "call count = " << m_callCount << std::endl;
}
}
}
<|endoftext|>
|
<commit_before>#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest.h"
#include <duck/range/combinator.h>
#include <duck/range/range.h>
#include <forward_list>
#include <iterator>
#include <list>
#include <vector>
// FIXME
#include <iostream>
template <typename Derived>
static std::ostream & operator<< (std::ostream & os, const duck::Range::Base<Derived> & r) {
os << "Range(";
for (const auto & v : r.derived ())
os << v << ",";
return os << ")";
}
TYPE_TO_STRING (std::vector<int>);
TYPE_TO_STRING (std::list<int>);
TYPE_TO_STRING (std::forward_list<int>);
using BidirContainers = doctest::Types<std::vector<int>, std::list<int>>;
using ForwardContainers = doctest::Types<std::vector<int>, std::list<int>, std::forward_list<int>>;
namespace DRC = duck::Range::Combinator;
const auto values = {0, 1, 2, 3, 4};
TEST_CASE_TEMPLATE ("reverse", Container, BidirContainers) {
auto range = duck::range (Container{values}) | DRC::reverse ();
CHECK (range.size () == values.size ());
using RevIt = std::reverse_iterator<typename std::initializer_list<int>::iterator>;
CHECK (range == duck::range (RevIt{values.end ()}, RevIt{values.begin ()}));
CHECK ((duck::range (Container{}) | DRC::reverse ()).empty ());
}
TEST_CASE_TEMPLATE ("index", Container, ForwardContainers) {
for (auto & iv : duck::range (Container{values}) | DRC::index<int> ()) {
CHECK (iv.index == iv.value ());
}
// Empty, also check that index<Int> has a default
CHECK ((duck::range (Container{}) | DRC::index ()).empty ());
}
TEST_CASE_TEMPLATE ("filter", Container, ForwardContainers) {
auto r = duck::range (Container{values});
auto filtered_range = r | DRC::filter ([](int i) { return i % 2 == 0; });
CHECK (filtered_range.size () == 3);
CHECK (filtered_range == duck::range ({0, 2, 4}));
auto chained_filtered_range =
r | DRC::filter ([](int i) { return i < 2; }) | DRC::filter ([](int i) { return i > 0; });
CHECK (chained_filtered_range.size () == 1);
CHECK (chained_filtered_range.front () == 1);
CHECK ((duck::range (Container{}) | DRC::filter ([](int) { return true; })).empty ());
}
TEST_CASE_TEMPLATE ("apply", Container, ForwardContainers) {
auto applied_range = duck::range (Container{values}) | DRC::apply ([](int i) { return i - 2; }) |
DRC::filter ([](int i) { return i >= 0; });
CHECK (applied_range.size () == 3);
CHECK (applied_range == duck::range (0, 3));
CHECK ((duck::range (Container{}) | DRC::apply ([](int i) { return i; })).empty ());
}
<commit_msg>Gcc fix<commit_after>#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest.h"
#include <duck/range/combinator.h>
#include <duck/range/range.h>
#include <forward_list>
#include <iterator>
#include <list>
#include <vector>
// FIXME
#include <iostream>
template <typename Derived>
static std::ostream & operator<< (std::ostream & os, const duck::Range::Base<Derived> & r) {
os << "Range(";
for (const auto & v : r.derived ())
os << v << ",";
return os << ")";
}
TYPE_TO_STRING (std::vector<int>);
TYPE_TO_STRING (std::list<int>);
TYPE_TO_STRING (std::forward_list<int>);
using BidirContainers = doctest::Types<std::vector<int>, std::list<int>>;
using ForwardContainers = doctest::Types<std::vector<int>, std::list<int>, std::forward_list<int>>;
namespace DRC = duck::Range::Combinator;
auto values = {0, 1, 2, 3, 4};
TEST_CASE_TEMPLATE ("reverse", Container, BidirContainers) {
auto range = duck::range (Container{values}) | DRC::reverse ();
CHECK (range.size () == values.size ());
using RevIt = std::reverse_iterator<typename std::initializer_list<int>::iterator>;
CHECK (range == duck::range (RevIt{values.end ()}, RevIt{values.begin ()}));
CHECK ((duck::range (Container{}) | DRC::reverse ()).empty ());
}
TEST_CASE_TEMPLATE ("index", Container, ForwardContainers) {
for (auto & iv : duck::range (Container{values}) | DRC::index<int> ()) {
CHECK (iv.index == iv.value ());
}
// Empty, also check that index<Int> has a default
CHECK ((duck::range (Container{}) | DRC::index ()).empty ());
}
TEST_CASE_TEMPLATE ("filter", Container, ForwardContainers) {
auto r = duck::range (Container{values});
auto filtered_range = r | DRC::filter ([](int i) { return i % 2 == 0; });
CHECK (filtered_range.size () == 3);
CHECK (filtered_range == duck::range ({0, 2, 4}));
auto chained_filtered_range =
r | DRC::filter ([](int i) { return i < 2; }) | DRC::filter ([](int i) { return i > 0; });
CHECK (chained_filtered_range.size () == 1);
CHECK (chained_filtered_range.front () == 1);
CHECK ((duck::range (Container{}) | DRC::filter ([](int) { return true; })).empty ());
}
TEST_CASE_TEMPLATE ("apply", Container, ForwardContainers) {
auto applied_range = duck::range (Container{values}) | DRC::apply ([](int i) { return i - 2; }) |
DRC::filter ([](int i) { return i >= 0; });
CHECK (applied_range.size () == 3);
CHECK (applied_range == duck::range (0, 3));
CHECK ((duck::range (Container{}) | DRC::apply ([](int i) { return i; })).empty ());
}
<|endoftext|>
|
<commit_before>#include "YarrarMarkerParser.h"
#include "Util.h"
#include <cassert>
#include <cstdint>
namespace {
using namespace yarrar;
const int FIELD_SIZE = 8;
int getId(const cv::Mat& field)
{
// TODO: A real parser. This is only for testing.
// Final id is fourth line as binary converted to integer.
int id = 0;
for(int i = 0; i < FIELD_SIZE; ++i)
{
if(field.at<uint8_t>(3, i) == 1)
{
id = id | (uint8_t) (1 << (7 - i));
}
}
return id;
}
Rotation90 getZRotation(const cv::Mat& field)
{
// The rectangle in upper left corner is used to
// indicate the rotation.
if(field.at<uchar>(1, 1) == 1) return Rotation90::DEG_0;
else if(field.at<int8_t>(1, 6) == 1) return Rotation90::DEG_90;
else if(field.at<int8_t>(6, 6) == 1) return Rotation90::DEG_180;
else if(field.at<int8_t>(6, 1) == 1) return Rotation90::DEG_270;
return Rotation90::DEG_0;
}
}
namespace yarrar {
MarkerValue YarrarMarkerParser::getData(const cv::Mat& image)
{
assert(image.cols == image.rows && "Id parser expects square image");
cv::Mat binary;
cv::inRange(image, 0, 100, binary);
// Works by dividing the image to 8x8 matrix (byte per line).
// Then check if a cell is either black (1) or white (0).
const int dimension = FIELD_SIZE;
const int stepSize = image.cols / dimension;
const int start = stepSize / 2;
//DataField field;
cv::Mat field = cv::Mat::zeros(dimension, dimension, CV_8S);
for(int i = 0; i < dimension; ++i)
{
for(int j = 0; j < dimension; ++j)
{
const int col = start + i * stepSize;
const int row = start + j * stepSize;
const bool isBlack = binary.at<uint8_t>(col, row) > 0;
field.at<int8_t>(i, j) = isBlack ? 1 : 0;
}
}
// Get current rotation.
Rotation90 rot = getZRotation(field);
// Rotate the field, so that it's in default (DEG_0)
// rotation. This way id parsing doesn't
// have to care about rotations.
switch(rot)
{
case Rotation90::DEG_90:
std::cout << "rotation 90" << std::endl;
rotate(field, field, Rotation90::DEG_270);
break;
case Rotation90::DEG_180:
std::cout << "rotation 180" << std::endl;
rotate(field, field, Rotation90::DEG_180);
break;
case Rotation90::DEG_270:
std::cout << "rotation 270" << std::endl;
rotate(field, field, Rotation90::DEG_90);
break;
case Rotation90::DEG_0:
std::cout << "rotation 0" << std::endl;
break;
}
return {
getId(field),
rot
};
}
}
<commit_msg>Clean up.<commit_after>#include "YarrarMarkerParser.h"
#include "Util.h"
#include <cassert>
#include <cstdint>
namespace {
using namespace yarrar;
const int FIELD_SIZE = 8;
int getId(const cv::Mat& field)
{
// TODO: A real parser. This is only for testing.
// Final id is fourth line as binary converted to integer.
int id = 0;
for(int i = 0; i < FIELD_SIZE; ++i)
{
if(field.at<uint8_t>(3, i) == 1)
{
id = id | (uint8_t) (1 << (7 - i));
}
}
return id;
}
Rotation90 getZRotation(const cv::Mat& field)
{
// The rectangle in upper left corner is used to
// indicate the rotation.
if(field.at<uchar>(1, 1) == 1) return Rotation90::DEG_0;
else if(field.at<int8_t>(1, 6) == 1) return Rotation90::DEG_90;
else if(field.at<int8_t>(6, 6) == 1) return Rotation90::DEG_180;
else if(field.at<int8_t>(6, 1) == 1) return Rotation90::DEG_270;
return Rotation90::DEG_0;
}
}
namespace yarrar {
MarkerValue YarrarMarkerParser::getData(const cv::Mat& image)
{
assert(image.cols == image.rows && "Id parser expects square image");
cv::Mat binary;
cv::inRange(image, 0, 100, binary);
// Works by dividing the image to 8x8 matrix (byte per line).
// Then check if a cell is either black (1) or white (0).
const int dimension = FIELD_SIZE;
const int stepSize = image.cols / dimension;
const int start = stepSize / 2;
//DataField field;
cv::Mat field = cv::Mat::zeros(dimension, dimension, CV_8S);
for(int i = 0; i < dimension; ++i)
{
for(int j = 0; j < dimension; ++j)
{
const int col = start + i * stepSize;
const int row = start + j * stepSize;
const bool isBlack = binary.at<uint8_t>(col, row) > 0;
field.at<int8_t>(i, j) = isBlack ? 1 : 0;
}
}
// Get current rotation.
Rotation90 rot = getZRotation(field);
// Rotate the field, so that it's in default (DEG_0)
// rotation. This way id parsing doesn't
// have to care about rotations.
switch(rot)
{
case Rotation90::DEG_90:
rotate(field, field, Rotation90::DEG_270);
break;
case Rotation90::DEG_180:
rotate(field, field, Rotation90::DEG_180);
break;
case Rotation90::DEG_270:
rotate(field, field, Rotation90::DEG_90);
break;
case Rotation90::DEG_0:
break;
}
return {
getId(field),
rot
};
}
}
<|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QMutableListIterator>
#include <QtPlugin>
#include <QLibrary>
#include <QLibraryInfo>
#include <QDir>
#include <QPluginLoader>
#include "tasserverservicemanager.h"
#include "tascommandparser.h"
#include "tasconstants.h"
#include "taslogger.h"
#include "version.h"
/*!
\class TasServerServiceManager
\brief TasServerServiceManager manages the service commands used by qttasserver.
TasServerServiceManager is the manager for the commands in the service architecture
used by qttasserver. The service requests are implemented using a relatively
standard form of the chain of responsibility pattern. TasServerServiceManager class
takes care of the command execution and management. The command implementations
only need to concern with the actual command implementation.
The difference to TasServiceManager is that a waiter is started for the responses
which originate from the connected plugins.
Commands which are reqistered to the manager will be invoked on all
service requests untill on command consumed the request. This is done
by returning "true" from the execute method.
*/
/*!
Construct a new TasServerServiceManager
*/
TasServerServiceManager::TasServerServiceManager(QObject *parent)
:QObject(parent)
{
mClientManager = TasClientManager::instance();
loadExtensions();
}
/*!
Destructor. Destroys all of the reqistered commands.
*/
TasServerServiceManager::~TasServerServiceManager()
{
qDeleteAll(mCommands);
mCommands.clear();
mExtensions.clear();
}
/*!
Servers servicemanager first looks for a client to relay the message to. If none found then use the servers command chain
to handle the service request.
*/
void TasServerServiceManager::handleServiceRequest(TasCommandModel& commandModel, TasSocket* requester, qint32 responseId)
{
TasLogger::logger()->debug("TasServerServiceManager::handleServiceRequest: " + commandModel.service() + ": " + commandModel.id());
TasClient* targetClient = 0;
if (!commandModel.id().isEmpty() && commandModel.id() != "1"){
TasClient* crashedApp = mClientManager->findCrashedApplicationById(commandModel.id());
if (crashedApp){
TasResponse response(responseId);
response.setIsError(true);
response.setErrorMessage("The application " + crashedApp->applicationName() + " with Id " + crashedApp->processId() + " has crashed.");
requester->sendMessage(response);
return;
}
targetClient = mClientManager->findByProcessId(commandModel.id());
//no registered client check for platform specific handles for the process id
if(!targetClient){
foreach(TasExtensionInterface* extension, mExtensions){
QByteArray data;
if(extension->performCommand(commandModel, data)){
//remove possible client
if(commandModel.service() == CLOSE_APPLICATION){
TasLogger::logger()->debug("TasServerServiceManager::handleServiceRequest remove client");
mClientManager->removeClient(commandModel.id());
}
TasResponse response(responseId, new QByteArray(data));
requester->sendMessage(response);
TasLogger::logger()->debug("TasServerServiceManager::handleServiceRequest: plat service done, returning");
return;
}
}
}
if(!targetClient){
TasLogger::logger()->debug("TasServerServiceManager::handleServiceRequest: no target client send error...");
TasResponse response(responseId);
response.setIsError(true);
response.setErrorMessage("The application with Id " + commandModel.id() + " is no longer available.");
requester->sendMessage(response);
return;
}
}
if(!targetClient && (commandModel.service() == APPLICATION_STATE || commandModel.service() == SCREEN_SHOT
|| commandModel.service() == FIND_OBJECT_SERVICE)){
targetClient = mClientManager->findClient(commandModel);
}
else if (commandModel.service() == RESOURCE_LOGGING_SERVICE){
targetClient = mClientManager->logMemClient();
}
else{
}
if(targetClient){
ResponseWaiter* waiter = new ResponseWaiter(responseId, requester);
bool needFragment = false;
if(commandModel.service() == APPLICATION_STATE || commandModel.service() == FIND_OBJECT_SERVICE){
foreach(TasExtensionInterface* traverser, mExtensions){
QByteArray data = traverser->traverseApplication(targetClient->processId(), targetClient->applicationName());
if(!data.isNull()){
waiter->appendPlatformData(data);
needFragment = true;
}
}
}
if(commandModel.service() == CLOSE_APPLICATION && targetClient->process()){
waiter->setResponseFilter(new ClientRemoveFilter(commandModel));
}
connect(waiter, SIGNAL(responded(qint32)), this, SLOT(removeWaiter(qint32)));
reponseQueue.insert(responseId, waiter);
if(needFragment){
commandModel.addAttribute("needFragment", "true");
targetClient->socket()->sendRequest(responseId, commandModel.sourceString(false));
}
else{
targetClient->socket()->sendRequest(responseId, commandModel.sourceString());
}
}
else{
//check if platform specific handlers want to handle the request
foreach(TasExtensionInterface* extension, mExtensions){
QByteArray data;
if(extension->performCommand(commandModel, data)){
TasLogger::logger()->debug("TasServerServiceManager::handleServiceRequest platform handler completed request.");
TasResponse response(responseId, new QByteArray(data));
requester->sendMessage(response);
return;
}
}
if(commandModel.service() == SCREEN_SHOT){
ResponseWaiter* waiter = new ResponseWaiter(responseId, requester);
connect(waiter, SIGNAL(responded(qint32)), this, SLOT(removeWaiter(qint32)));
reponseQueue.insert(responseId, waiter);
QStringList args;
args << "-i" << QString::number(responseId) << "-a" << "screenshot";
QProcess::startDetached("qttasutilapp", args);
}
else{
TasResponse response(responseId);
response.setRequester(requester);
performService(commandModel, response);
//start app waits for register message and performs the response
if( (commandModel.service() != START_APPLICATION && commandModel.service() != RESOURCE_LOGGING_SERVICE) || response.isError()){
requester->sendMessage(response);
}
}
}
}
void TasServerServiceManager::loadExtensions()
{
TasLogger::logger()->debug("TasServerServiceManager::loadPlatformTraversers");
QString pluginDir = "tasextensions";
QStringList plugins = mPluginLoader.listPlugins(pluginDir);
TasLogger::logger()->debug("TasServerServiceManager::loadPlatformTraversers plugins found: " + plugins.join("'"));
QString path = QLibraryInfo::location(QLibraryInfo::PluginsPath) + "/"+pluginDir;
for (int i = 0; i < plugins.count(); ++i) {
QString fileName = plugins.at(i);
QString filePath = QDir::cleanPath(path + QLatin1Char('/') + fileName);
if(QLibrary::isLibrary(filePath)){
loadExtension(filePath);
}
}
}
/*!
Try to load a plugin from the given path. Returns null if no plugin loaded.
*/
void TasServerServiceManager::loadExtension(const QString& filePath)
{
TasExtensionInterface* interface = 0;
QObject *plugin = mPluginLoader.loadPlugin(filePath);
if(plugin){
interface = qobject_cast<TasExtensionInterface *>(plugin);
if (interface){
TasLogger::logger()->debug("TasServerServiceManager::loadTraverser added a traverser");
mExtensions.append(interface);
}
else{
TasLogger::logger()->warning("TasServerServiceManager::loadTraverser could not cast to TasApplicationTraverseInterface");
}
}
}
void TasServerServiceManager::serviceResponse(TasMessage& response)
{
if(reponseQueue.contains(response.messageId())){
reponseQueue.value(response.messageId())->sendResponse(response);
}
else{
TasLogger::logger()->warning("TasServerServiceManager::serviceResponse unexpected response. Nobody interested!");
}
}
void TasServerServiceManager::removeWaiter(qint32 responseId)
{
//TasLogger::logger()->debug("TasServerServiceManager::removeWaiter remove " + QString::number(responseId));
reponseQueue.remove(responseId);
}
QByteArray TasServerServiceManager::responseHeader()
{
QString name = "qt";
#ifdef Q_OS_SYMBIAN
name = "symbian";
#endif
QString header = "<tasMessage dateTime=\"" +
QDateTime::currentDateTime().toString("yyyy.MM.dd hh:mm:ss.zzz") +
"\" version=\""+TAS_VERSION+"\"><tasInfo id=\""+qVersion()+"\" name=\""+name+"\" type=\"sut\">";
return header.toUtf8();
}
ResponseWaiter::ResponseWaiter(qint32 responseId, TasSocket* relayTarget, int timeout)
{
mPlatformData = 0;
mFilter = 0;
mSocket = relayTarget;
mResponseId = responseId;
mWaiter.setSingleShot(true);
connect(&mWaiter, SIGNAL(timeout()), this, SLOT(timeout()));
connect(mSocket, SIGNAL(socketClosed()), this, SLOT(socketClosed()));
mWaiter.start(timeout);
}
ResponseWaiter::~ResponseWaiter()
{
mWaiter.stop();
if(mFilter){
delete mFilter;
}
if(mPlatformData){
delete mPlatformData;
}
}
void ResponseWaiter::appendPlatformData(QByteArray data)
{
if(!mPlatformData){
TasLogger::logger()->debug("ResponseWaiter::appendPlatformData make data container and add root");
//make header for the document made from fragments
mPlatformData = new QByteArray(TasServerServiceManager::responseHeader());
}
mPlatformData->append(data);
}
/*!
If set the response will be passed on to the filter before sent to the
requesting socket. Ownership is taken.
*/
void ResponseWaiter::setResponseFilter(ResponseFilter* filter)
{
mFilter = filter;
}
void ResponseWaiter::sendResponse(TasMessage& response)
{
TasLogger::logger()->debug("ResponseWaiter::sendResponse");
mWaiter.stop();
if(mFilter){
mFilter->filterResponse(response);
}
if(mPlatformData && !mPlatformData->isEmpty()){
TasLogger::logger()->debug("ResponseWaiter::sendResponse add plat stuf");
response.uncompressData();
mPlatformData->append(response.data()->data());
mPlatformData->append(QString("</tasInfo></tasMessage>").toUtf8());
response.setData(mPlatformData);
//ownership transferred to response
mPlatformData = 0;
}
//TasLogger::logger()->debug(response.dataAsString());
if(!mSocket->sendMessage(response)){
TasLogger::logger()->error("ResponseWaiter::sendResponse socket not writable!");
}
emit responded(mResponseId);
deleteLater();
}
void ResponseWaiter::timeout()
{
TasLogger::logger()->error("ResponseWaiter::timeout for message: " + QString::number(mResponseId));
TasResponse response(mResponseId);
response.setErrorMessage("Connection to plugin timedout!");
if(mFilter){
mFilter->filterResponse(response);
}
if(!mSocket->sendMessage(response)){
TasLogger::logger()->error("ResponseWaiter::timeout socket not writable!");
}
emit responded(mResponseId);
deleteLater();
}
void ResponseWaiter::socketClosed()
{
mWaiter.stop();
TasLogger::logger()->error("ResponseWaiter::socketClosed. Connection to this waiter closed. Cannot respond. " );
emit responded(mResponseId);
deleteLater();
}
<commit_msg>Removefilter added back<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QMutableListIterator>
#include <QtPlugin>
#include <QLibrary>
#include <QLibraryInfo>
#include <QDir>
#include <QPluginLoader>
#include "tasserverservicemanager.h"
#include "tascommandparser.h"
#include "tasconstants.h"
#include "taslogger.h"
#include "version.h"
/*!
\class TasServerServiceManager
\brief TasServerServiceManager manages the service commands used by qttasserver.
TasServerServiceManager is the manager for the commands in the service architecture
used by qttasserver. The service requests are implemented using a relatively
standard form of the chain of responsibility pattern. TasServerServiceManager class
takes care of the command execution and management. The command implementations
only need to concern with the actual command implementation.
The difference to TasServiceManager is that a waiter is started for the responses
which originate from the connected plugins.
Commands which are reqistered to the manager will be invoked on all
service requests untill on command consumed the request. This is done
by returning "true" from the execute method.
*/
/*!
Construct a new TasServerServiceManager
*/
TasServerServiceManager::TasServerServiceManager(QObject *parent)
:QObject(parent)
{
mClientManager = TasClientManager::instance();
loadExtensions();
}
/*!
Destructor. Destroys all of the reqistered commands.
*/
TasServerServiceManager::~TasServerServiceManager()
{
qDeleteAll(mCommands);
mCommands.clear();
mExtensions.clear();
}
/*!
Servers servicemanager first looks for a client to relay the message to. If none found then use the servers command chain
to handle the service request.
*/
void TasServerServiceManager::handleServiceRequest(TasCommandModel& commandModel, TasSocket* requester, qint32 responseId)
{
TasLogger::logger()->debug("TasServerServiceManager::handleServiceRequest: " + commandModel.service() + ": " + commandModel.id());
TasClient* targetClient = 0;
if (!commandModel.id().isEmpty() && commandModel.id() != "1"){
TasClient* crashedApp = mClientManager->findCrashedApplicationById(commandModel.id());
if (crashedApp){
TasResponse response(responseId);
response.setIsError(true);
response.setErrorMessage("The application " + crashedApp->applicationName() + " with Id " + crashedApp->processId() + " has crashed.");
requester->sendMessage(response);
return;
}
targetClient = mClientManager->findByProcessId(commandModel.id());
//no registered client check for platform specific handles for the process id
if(!targetClient){
foreach(TasExtensionInterface* extension, mExtensions){
QByteArray data;
if(extension->performCommand(commandModel, data)){
//remove possible client
if(commandModel.service() == CLOSE_APPLICATION){
TasLogger::logger()->debug("TasServerServiceManager::handleServiceRequest remove client");
mClientManager->removeClient(commandModel.id());
}
TasResponse response(responseId, new QByteArray(data));
requester->sendMessage(response);
TasLogger::logger()->debug("TasServerServiceManager::handleServiceRequest: plat service done, returning");
return;
}
}
}
if(!targetClient){
TasLogger::logger()->debug("TasServerServiceManager::handleServiceRequest: no target client send error...");
TasResponse response(responseId);
response.setIsError(true);
response.setErrorMessage("The application with Id " + commandModel.id() + " is no longer available.");
requester->sendMessage(response);
return;
}
}
if(!targetClient && (commandModel.service() == APPLICATION_STATE || commandModel.service() == SCREEN_SHOT
|| commandModel.service() == FIND_OBJECT_SERVICE)){
targetClient = mClientManager->findClient(commandModel);
}
else if (commandModel.service() == RESOURCE_LOGGING_SERVICE){
targetClient = mClientManager->logMemClient();
}
else{
}
if(targetClient){
ResponseWaiter* waiter = new ResponseWaiter(responseId, requester);
bool needFragment = false;
if(commandModel.service() == APPLICATION_STATE || commandModel.service() == FIND_OBJECT_SERVICE){
foreach(TasExtensionInterface* traverser, mExtensions){
QByteArray data = traverser->traverseApplication(targetClient->processId(), targetClient->applicationName());
if(!data.isNull()){
waiter->appendPlatformData(data);
needFragment = true;
}
}
}
if(commandModel.service() == CLOSE_APPLICATION){
waiter->setResponseFilter(new ClientRemoveFilter(commandModel));
}
connect(waiter, SIGNAL(responded(qint32)), this, SLOT(removeWaiter(qint32)));
reponseQueue.insert(responseId, waiter);
if(needFragment){
commandModel.addAttribute("needFragment", "true");
targetClient->socket()->sendRequest(responseId, commandModel.sourceString(false));
}
else{
targetClient->socket()->sendRequest(responseId, commandModel.sourceString());
}
}
else{
//check if platform specific handlers want to handle the request
foreach(TasExtensionInterface* extension, mExtensions){
QByteArray data;
if(extension->performCommand(commandModel, data)){
TasLogger::logger()->debug("TasServerServiceManager::handleServiceRequest platform handler completed request.");
TasResponse response(responseId, new QByteArray(data));
requester->sendMessage(response);
return;
}
}
if(commandModel.service() == SCREEN_SHOT){
ResponseWaiter* waiter = new ResponseWaiter(responseId, requester);
connect(waiter, SIGNAL(responded(qint32)), this, SLOT(removeWaiter(qint32)));
reponseQueue.insert(responseId, waiter);
QStringList args;
args << "-i" << QString::number(responseId) << "-a" << "screenshot";
QProcess::startDetached("qttasutilapp", args);
}
else{
TasResponse response(responseId);
response.setRequester(requester);
performService(commandModel, response);
//start app waits for register message and performs the response
if( (commandModel.service() != START_APPLICATION && commandModel.service() != RESOURCE_LOGGING_SERVICE) || response.isError()){
requester->sendMessage(response);
}
}
}
}
void TasServerServiceManager::loadExtensions()
{
TasLogger::logger()->debug("TasServerServiceManager::loadPlatformTraversers");
QString pluginDir = "tasextensions";
QStringList plugins = mPluginLoader.listPlugins(pluginDir);
TasLogger::logger()->debug("TasServerServiceManager::loadPlatformTraversers plugins found: " + plugins.join("'"));
QString path = QLibraryInfo::location(QLibraryInfo::PluginsPath) + "/"+pluginDir;
for (int i = 0; i < plugins.count(); ++i) {
QString fileName = plugins.at(i);
QString filePath = QDir::cleanPath(path + QLatin1Char('/') + fileName);
if(QLibrary::isLibrary(filePath)){
loadExtension(filePath);
}
}
}
/*!
Try to load a plugin from the given path. Returns null if no plugin loaded.
*/
void TasServerServiceManager::loadExtension(const QString& filePath)
{
TasExtensionInterface* interface = 0;
QObject *plugin = mPluginLoader.loadPlugin(filePath);
if(plugin){
interface = qobject_cast<TasExtensionInterface *>(plugin);
if (interface){
TasLogger::logger()->debug("TasServerServiceManager::loadTraverser added a traverser");
mExtensions.append(interface);
}
else{
TasLogger::logger()->warning("TasServerServiceManager::loadTraverser could not cast to TasApplicationTraverseInterface");
}
}
}
void TasServerServiceManager::serviceResponse(TasMessage& response)
{
if(reponseQueue.contains(response.messageId())){
reponseQueue.value(response.messageId())->sendResponse(response);
}
else{
TasLogger::logger()->warning("TasServerServiceManager::serviceResponse unexpected response. Nobody interested!");
}
}
void TasServerServiceManager::removeWaiter(qint32 responseId)
{
//TasLogger::logger()->debug("TasServerServiceManager::removeWaiter remove " + QString::number(responseId));
reponseQueue.remove(responseId);
}
QByteArray TasServerServiceManager::responseHeader()
{
QString name = "qt";
#ifdef Q_OS_SYMBIAN
name = "symbian";
#endif
QString header = "<tasMessage dateTime=\"" +
QDateTime::currentDateTime().toString("yyyy.MM.dd hh:mm:ss.zzz") +
"\" version=\""+TAS_VERSION+"\"><tasInfo id=\""+qVersion()+"\" name=\""+name+"\" type=\"sut\">";
return header.toUtf8();
}
ResponseWaiter::ResponseWaiter(qint32 responseId, TasSocket* relayTarget, int timeout)
{
mPlatformData = 0;
mFilter = 0;
mSocket = relayTarget;
mResponseId = responseId;
mWaiter.setSingleShot(true);
connect(&mWaiter, SIGNAL(timeout()), this, SLOT(timeout()));
connect(mSocket, SIGNAL(socketClosed()), this, SLOT(socketClosed()));
mWaiter.start(timeout);
}
ResponseWaiter::~ResponseWaiter()
{
mWaiter.stop();
if(mFilter){
delete mFilter;
}
if(mPlatformData){
delete mPlatformData;
}
}
void ResponseWaiter::appendPlatformData(QByteArray data)
{
if(!mPlatformData){
TasLogger::logger()->debug("ResponseWaiter::appendPlatformData make data container and add root");
//make header for the document made from fragments
mPlatformData = new QByteArray(TasServerServiceManager::responseHeader());
}
mPlatformData->append(data);
}
/*!
If set the response will be passed on to the filter before sent to the
requesting socket. Ownership is taken.
*/
void ResponseWaiter::setResponseFilter(ResponseFilter* filter)
{
mFilter = filter;
}
void ResponseWaiter::sendResponse(TasMessage& response)
{
TasLogger::logger()->debug("ResponseWaiter::sendResponse");
mWaiter.stop();
if(mFilter){
mFilter->filterResponse(response);
}
if(mPlatformData && !mPlatformData->isEmpty()){
TasLogger::logger()->debug("ResponseWaiter::sendResponse add plat stuf");
response.uncompressData();
mPlatformData->append(response.data()->data());
mPlatformData->append(QString("</tasInfo></tasMessage>").toUtf8());
response.setData(mPlatformData);
//ownership transferred to response
mPlatformData = 0;
}
//TasLogger::logger()->debug(response.dataAsString());
if(!mSocket->sendMessage(response)){
TasLogger::logger()->error("ResponseWaiter::sendResponse socket not writable!");
}
emit responded(mResponseId);
deleteLater();
}
void ResponseWaiter::timeout()
{
TasLogger::logger()->error("ResponseWaiter::timeout for message: " + QString::number(mResponseId));
TasResponse response(mResponseId);
response.setErrorMessage("Connection to plugin timedout!");
if(mFilter){
mFilter->filterResponse(response);
}
if(!mSocket->sendMessage(response)){
TasLogger::logger()->error("ResponseWaiter::timeout socket not writable!");
}
emit responded(mResponseId);
deleteLater();
}
void ResponseWaiter::socketClosed()
{
mWaiter.stop();
TasLogger::logger()->error("ResponseWaiter::socketClosed. Connection to this waiter closed. Cannot respond. " );
emit responded(mResponseId);
deleteLater();
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2011, 2012 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// A test harness for the implementation report of
// the CSS2.1 Conformance Test Suite
// http://test.csswg.org/suites/css2.1/20110323/
#include <unistd.h>
#include <sys/wait.h>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <boost/version.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
enum {
INTERACTIVE,
HEADLESS,
REPORT,
UPDATE
};
int processOutput(std::istream& stream, std::string& result)
{
std::string output;
bool completed = false;
while (std::getline(stream, output)) {
if (!completed) {
if (output == "## complete")
completed = true;
continue;
}
if (output == "##")
break;
result += output + '\n';
}
return 0;
}
int runTest(int argc, char* argv[], std::string userStyle, std::string testFonts, std::string url, std::string& result, unsigned timeout)
{
int pipefd[2];
pipe(pipefd);
pid_t pid = fork();
if (pid == -1) {
std::cerr << "error: no more process to create\n";
return -1;
}
if (pid == 0) {
close(1);
dup(pipefd[1]);
close(pipefd[0]);
int argi = argc - 1;
if (!userStyle.empty())
argv[argi++] = strdup(userStyle.c_str());
if (testFonts == "on")
argv[argi++] ="-testfonts";
url = "http://localhost:8000/" + url;
// url = "http://test.csswg.org/suites/css2.1/20110323/" + url;
argv[argi++] = strdup(url.c_str());
argv[argi] = 0;
if (timeout)
alarm(timeout); // Terminate the process if it does not complete in 'timeout' seconds.
execvp(argv[0], argv);
exit(EXIT_FAILURE);
}
close(pipefd[1]);
#if 104400 <= BOOST_VERSION
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], boost::iostreams::close_handle);
#else
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], true);
#endif
processOutput(stream, result);
return pid;
}
void killTest(int pid)
{
int status;
kill(pid, SIGTERM);
if (wait(&status) == -1)
std::cerr << "error: failed to wait for a test process to complete\n";
}
bool loadLog(const std::string& path, std::string& result, std::string& log)
{
std::ifstream file(path.c_str());
if (!file) {
result = "?";
return false;
}
std::string line;
std::getline(file, line);
size_t pos = line.find('\t');
if (pos != std::string::npos)
result = line.substr(pos + 1);
else {
result = "?";
return false;
}
log.clear();
while (std::getline(file, line))
log += line + '\n';
return true;
}
bool saveLog(const std::string& path, const std::string& url, const std::string& result, const std::string& log)
{
std::ofstream file(path.c_str(), std::ios_base::out | std::ios_base::trunc);
if (!file) {
std::cerr << "error: failed to open the report file\n";
return false;
}
file << "# " << url.c_str() << '\t' << result << '\n' << log;
file.flush();
file.close();
return true;
}
int main(int argc, char* argv[])
{
int mode = HEADLESS;
unsigned timeout = 10;
int argi = 1;
while (*argv[argi] == '-') {
switch (argv[argi][1]) {
case 'i':
mode = INTERACTIVE;
timeout = 0;
break;
case 'r':
mode = REPORT;
break;
case 'u':
mode = UPDATE;
break;
default:
break;
}
++argi;
}
if (argc < argi + 2) {
std::cout << "usage: " << argv[0] << " [-i] report.data command [argument ...]\n";
return EXIT_FAILURE;
}
std::ifstream data(argv[argi]);
if (!data) {
std::cerr << "error: " << argv[argi] << ": no such file\n";
return EXIT_FAILURE;
}
std::ofstream report("report.data", std::ios_base::out | std::ios_base::trunc);
if (!report) {
std::cerr << "error: failed to open the report file\n";
return EXIT_FAILURE;
}
char* args[argc - argi + 3];
for (int i = 2; i < argc; ++i)
args[i - 2] = argv[i + argi - 1];
args[argc - argi] = args[argc - argi + 1] = args[argc - argi + 2] = 0;
std::string result;
std::string url;
std::string undo;
std::string userStyle;
std::string testFonts;
bool redo = false;
while (data) {
if (result == "undo") {
std::swap(url, undo);
redo = true;
} else if (redo) {
std::swap(url, undo);
redo = false;
} else {
std::string line;
std::getline(data, line);
if (line.empty() || line == "testname result comment") {
report << line << '\n';
continue;
}
if (line[0] == '#') {
if (line.compare(1, 9, "userstyle") == 0) {
if (10 < line.length()) {
std::stringstream s(line.substr(10), std::stringstream::in);
s >> userStyle;
} else
userStyle.clear();
} else if (line.compare(1, 9, "testfonts") == 0) {
if (10 < line.length()) {
std::stringstream s(line.substr(10), std::stringstream::in);
s >> testFonts;
} else
testFonts.clear();
}
report << line << '\n';
continue;
}
undo = url;
std::stringstream s(line, std::stringstream::in);
s >> url;
}
if (url.empty())
continue;
std::string path(url);
size_t pos = path.rfind('.');
if (pos != std::string::npos) {
path.erase(pos);
path += ".log";
}
std::string evaluation;
std::string log;
loadLog(path, evaluation, log);
pid_t pid = -1;
std::string output;
switch (mode) {
case REPORT:
break;
case UPDATE:
if (evaluation[0] == '?')
break;
// FALL THROUGH
default:
pid = runTest(argc - argi, args, userStyle, testFonts, url, output, timeout);
break;
}
if (0 < pid && output.empty())
result = "fatal";
else if (mode == INTERACTIVE) {
std::cout << "## complete\n" << output;
std::cout << '[' << url << "] ";
if (evaluation.empty() || evaluation[0] == '?')
std::cout << "pass? ";
else {
std::cout << evaluation << "? ";
if (evaluation != "pass")
std::cout << '\a';
}
std::getline(std::cin, result);
if (result.empty()) {
if (evaluation.empty() || evaluation[0] == '?')
result = "pass";
else
result = evaluation;
} else if (result == "p" || result == "\x1b")
result = "pass";
else if (result == "f")
result = "fail";
else if (result == "i")
result = "invalid";
else if (result == "k") // keep
result = evaluation;
else if (result == "n")
result = "na";
else if (result == "s")
result = "skip";
else if (result == "u")
result = "uncertain";
else if (result == "q" || result == "quit")
break;
else if (result == "z")
result = "undo";
if (result != "undo" && !saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
return EXIT_FAILURE;
}
} else if (mode == HEADLESS) {
if (evaluation != "?" && output != log)
result = "uncertain";
else
result = evaluation;
} else if (mode == REPORT) {
result = evaluation;
} else if (mode == UPDATE) {
result = evaluation;
if (result[0] != '?') {
if (!saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
return EXIT_FAILURE;
}
}
}
if (0 < pid)
killTest(pid);
if (result != "undo")
report << url << '\t' << result << '\n';
if (mode != INTERACTIVE && result[0] != '?')
std::cout << url << '\t' << result << '\n';
}
report.close();
}
<commit_msg>(harness) : Support the -j[jobs] option to run simultaneously.<commit_after>/*
* Copyright 2011, 2012 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// A test harness for the implementation report of
// the CSS2.1 Conformance Test Suite
// http://test.csswg.org/suites/css2.1/20110323/
#include <unistd.h>
#include <sys/wait.h>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <boost/version.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
enum {
INTERACTIVE,
HEADLESS,
REPORT,
UPDATE
};
int forkMax = 1;
int forkCount = 0;
int processOutput(std::istream& stream, std::string& result)
{
std::string output;
bool completed = false;
while (std::getline(stream, output)) {
if (!completed) {
if (output == "## complete")
completed = true;
continue;
}
if (output == "##")
break;
result += output + '\n';
}
return 0;
}
int runTest(int argc, char* argv[], std::string userStyle, std::string testFonts, std::string url, std::string& result, unsigned timeout)
{
int pipefd[2];
pipe(pipefd);
pid_t pid = fork();
if (pid == -1) {
std::cerr << "error: no more process to create\n";
return -1;
}
if (pid == 0) {
close(1);
dup(pipefd[1]);
close(pipefd[0]);
int argi = argc - 1;
if (!userStyle.empty())
argv[argi++] = strdup(userStyle.c_str());
if (testFonts == "on")
argv[argi++] ="-testfonts";
url = "http://localhost:8000/" + url;
// url = "http://test.csswg.org/suites/css2.1/20110323/" + url;
argv[argi++] = strdup(url.c_str());
argv[argi] = 0;
if (timeout)
alarm(timeout); // Terminate the process if it does not complete in 'timeout' seconds.
execvp(argv[0], argv);
exit(EXIT_FAILURE);
}
close(pipefd[1]);
#if 104400 <= BOOST_VERSION
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], boost::iostreams::close_handle);
#else
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], true);
#endif
processOutput(stream, result);
return pid;
}
void killTest(int pid)
{
int status;
kill(pid, SIGTERM);
if (wait(&status) == -1)
std::cerr << "error: failed to wait for a test process to complete\n";
}
bool loadLog(const std::string& path, std::string& result, std::string& log)
{
std::ifstream file(path.c_str());
if (!file) {
result = "?";
return false;
}
std::string line;
std::getline(file, line);
size_t pos = line.find('\t');
if (pos != std::string::npos)
result = line.substr(pos + 1);
else {
result = "?";
return false;
}
log.clear();
while (std::getline(file, line))
log += line + '\n';
return true;
}
bool saveLog(const std::string& path, const std::string& url, const std::string& result, const std::string& log)
{
std::ofstream file(path.c_str(), std::ios_base::out | std::ios_base::trunc);
if (!file) {
std::cerr << "error: failed to open the report file\n";
return false;
}
file << "# " << url.c_str() << '\t' << result << '\n' << log;
file.flush();
file.close();
return true;
}
std::string test(int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout)
{
std::string path(url);
size_t pos = path.rfind('.');
if (pos != std::string::npos) {
path.erase(pos);
path += ".log";
}
std::string evaluation;
std::string log;
loadLog(path, evaluation, log);
pid_t pid = -1;
std::string output;
switch (mode) {
case REPORT:
break;
case UPDATE:
if (evaluation[0] == '?')
break;
// FALL THROUGH
default:
pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout);
break;
}
std::string result;
if (0 < pid && output.empty())
result = "fatal";
else if (mode == INTERACTIVE) {
std::cout << "## complete\n" << output;
std::cout << '[' << url << "] ";
if (evaluation.empty() || evaluation[0] == '?')
std::cout << "pass? ";
else {
std::cout << evaluation << "? ";
if (evaluation != "pass")
std::cout << '\a';
}
std::getline(std::cin, result);
if (result.empty()) {
if (evaluation.empty() || evaluation[0] == '?')
result = "pass";
else
result = evaluation;
} else if (result == "p" || result == "\x1b")
result = "pass";
else if (result == "f")
result = "fail";
else if (result == "i")
result = "invalid";
else if (result == "k") // keep
result = evaluation;
else if (result == "n")
result = "na";
else if (result == "s")
result = "skip";
else if (result == "u")
result = "uncertain";
else if (result == "q" || result == "quit")
exit(EXIT_FAILURE);
else if (result == "z")
result = "undo";
if (result != "undo" && !saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
} else if (mode == HEADLESS) {
if (evaluation != "?" && output != log)
result = "uncertain";
else
result = evaluation;
} else if (mode == REPORT) {
result = evaluation;
} else if (mode == UPDATE) {
result = evaluation;
if (result[0] != '?') {
if (!saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
}
}
if (0 < pid)
killTest(pid);
if (mode != INTERACTIVE && result[0] != '?')
std::cout << url << '\t' << result << '\n';
return result;
}
std::string map(int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout)
{
pid_t pid = fork();
if (pid == -1) {
std::cerr << "error: no more process to create\n";
exit(EXIT_FAILURE);
}
if (pid == 0) {
std::string path(url);
size_t pos = path.rfind('.');
if (pos != std::string::npos) {
path.erase(pos);
path += ".log";
}
std::string evaluation;
std::string log;
loadLog(path, evaluation, log);
pid_t pid = -1;
std::string output;
switch (mode) {
case UPDATE:
if (evaluation[0] == '?')
break;
// FALL THROUGH
default:
pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout);
break;
}
std::string result;
if (0 < pid && output.empty())
result = "fatal";
else if (mode == HEADLESS) {
if (evaluation != "?" && output != log)
result = "uncertain";
else
result = evaluation;
} else if (mode == UPDATE) {
result = evaluation;
if (result[0] != '?') {
if (!saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
}
}
if (0 < pid)
killTest(pid);
if (result[0] != '?')
std::cout << url << '\t' << result << '\n';
exit(EXIT_SUCCESS);
}
if (++forkCount == forkMax) {
for (int j = 0; j < forkCount; ++j) {
int status;
wait(&status);
}
forkCount = 0;
}
return "na";
}
int main(int argc, char* argv[])
{
int mode = HEADLESS;
unsigned timeout = 10;
int argi = 1;
while (*argv[argi] == '-') {
switch (argv[argi][1]) {
case 'i':
mode = INTERACTIVE;
timeout = 0;
break;
case 'r':
mode = REPORT;
break;
case 'u':
mode = UPDATE;
break;
case 'j':
forkMax = strtoul(argv[argi] + 2, 0, 10);
break;
default:
break;
}
++argi;
}
if (argc < argi + 2) {
std::cout << "usage: " << argv[0] << " [-i] report.data command [argument ...]\n";
return EXIT_FAILURE;
}
std::ifstream data(argv[argi]);
if (!data) {
std::cerr << "error: " << argv[argi] << ": no such file\n";
return EXIT_FAILURE;
}
std::ofstream report("report.data", std::ios_base::out | std::ios_base::trunc);
if (!report) {
std::cerr << "error: failed to open the report file\n";
return EXIT_FAILURE;
}
char* args[argc - argi + 3];
for (int i = 2; i < argc; ++i)
args[i - 2] = argv[i + argi - 1];
args[argc - argi] = args[argc - argi + 1] = args[argc - argi + 2] = 0;
std::string result;
std::string url;
std::string undo;
std::string userStyle;
std::string testFonts;
bool redo = false;
for (;;) {
while (data) {
if (result == "undo") {
std::swap(url, undo);
redo = true;
} else if (redo) {
std::swap(url, undo);
redo = false;
} else {
std::string line;
std::getline(data, line);
if (line.empty() || line == "testname result comment") {
report << line << '\n';
continue;
}
if (line[0] == '#') {
if (line.compare(1, 9, "userstyle") == 0) {
if (10 < line.length()) {
std::stringstream s(line.substr(10), std::stringstream::in);
s >> userStyle;
} else
userStyle.clear();
} else if (line.compare(1, 9, "testfonts") == 0) {
if (10 < line.length()) {
std::stringstream s(line.substr(10), std::stringstream::in);
s >> testFonts;
} else
testFonts.clear();
}
report << line << '\n';
continue;
}
undo = url;
std::stringstream s(line, std::stringstream::in);
s >> url;
}
if (url.empty())
continue;
switch (mode) {
case HEADLESS:
case UPDATE:
result = map(mode, argc - argi, args, url, userStyle, testFonts, timeout);
break;
default:
result = test(mode, argc - argi, args, url, userStyle, testFonts, timeout);
if (result != "undo")
report << url << '\t' << result << '\n';
break;
}
}
if (mode == HEADLESS || mode == UPDATE) {
for (int j = 0; j < forkCount; ++j) {
int status;
wait(&status);
}
mode = REPORT;
data.clear();
data.seekg(0);
} else
break;
}
report.close();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: scimpexpmsg.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 18:29:13 $
*
* 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
*
************************************************************************/
#ifdef PCH
#include "core_pch.hxx"
#endif
#pragma hdrstop
// INCLUDE ---------------------------------------------------------------
#include "document.hxx"
#include "scimpexpmsg.hxx"
#include <tools/string.hxx>
void ScDocument::AddToImpExpLog( const ScImpExpLogMsg& r )
{
}
void ScDocument::AddToImpExpLog( ScImpExpLogMsg* p )
{
delete p;
}
ScImpExpLogMsg::ScImpExpLogMsg( ScImpExpMsg e ) : eId( e ), pPos( NULL ), pHint( NULL )
{
}
ScImpExpLogMsg::ScImpExpLogMsg( ScImpExpMsg e, const String& r ) : eId( e ), pHint( NULL )
{
pPos = new String( r );
}
ScImpExpLogMsg::ScImpExpLogMsg( ScImpExpMsg e, const String& rP, const String& rH ) : eId( e )
{
pPos = new String( rP );
pHint = new String( rH );
}
ScImpExpLogMsg::ScImpExpLogMsg( const ScImpExpLogMsg& r ) : eId( r.eId )
{
if( r.pPos )
pPos = new String( *r.pPos );
else
pPos = NULL;
if( r.pHint )
pHint = new String( *r.pHint );
else
pHint = NULL;
}
ScImpExpLogMsg::~ScImpExpLogMsg()
{
if( pPos )
delete pPos;
if( pHint )
delete pHint;
}
void ScImpExpLogMsg::Set( ScImpExpMsg e, const String* pP, const String* pH )
{
eId = e;
if( pPos )
delete pPos;
if( pHint )
delete pHint;
if( pP )
pPos = new String( *pP );
else
pPos = NULL;
if( pH )
pHint = new String( *pH );
}
String ScImpExpLogMsg::GetMsg( ScImpExpMsg e )
{
const sal_Char* p;
switch( e )
{
case SC_IMPEXPMSG_UNKNOWN: p = "unknown log message"; break;
default: p = "Not specified type of log message";
}
String aRet;
aRet.AssignAscii( p );
return aRet;
}
<commit_msg>INTEGRATION: CWS pchfix01 (1.2.216); FILE MERGED 2006/07/12 10:01:35 kaib 1.2.216.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: scimpexpmsg.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2006-07-21 11:08:05 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// INCLUDE ---------------------------------------------------------------
#include "document.hxx"
#include "scimpexpmsg.hxx"
#include <tools/string.hxx>
void ScDocument::AddToImpExpLog( const ScImpExpLogMsg& r )
{
}
void ScDocument::AddToImpExpLog( ScImpExpLogMsg* p )
{
delete p;
}
ScImpExpLogMsg::ScImpExpLogMsg( ScImpExpMsg e ) : eId( e ), pPos( NULL ), pHint( NULL )
{
}
ScImpExpLogMsg::ScImpExpLogMsg( ScImpExpMsg e, const String& r ) : eId( e ), pHint( NULL )
{
pPos = new String( r );
}
ScImpExpLogMsg::ScImpExpLogMsg( ScImpExpMsg e, const String& rP, const String& rH ) : eId( e )
{
pPos = new String( rP );
pHint = new String( rH );
}
ScImpExpLogMsg::ScImpExpLogMsg( const ScImpExpLogMsg& r ) : eId( r.eId )
{
if( r.pPos )
pPos = new String( *r.pPos );
else
pPos = NULL;
if( r.pHint )
pHint = new String( *r.pHint );
else
pHint = NULL;
}
ScImpExpLogMsg::~ScImpExpLogMsg()
{
if( pPos )
delete pPos;
if( pHint )
delete pHint;
}
void ScImpExpLogMsg::Set( ScImpExpMsg e, const String* pP, const String* pH )
{
eId = e;
if( pPos )
delete pPos;
if( pHint )
delete pHint;
if( pP )
pPos = new String( *pP );
else
pPos = NULL;
if( pH )
pHint = new String( *pH );
}
String ScImpExpLogMsg::GetMsg( ScImpExpMsg e )
{
const sal_Char* p;
switch( e )
{
case SC_IMPEXPMSG_UNKNOWN: p = "unknown log message"; break;
default: p = "Not specified type of log message";
}
String aRet;
aRet.AssignAscii( p );
return aRet;
}
<|endoftext|>
|
<commit_before>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <regex>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
#include "process.h"
#include "swap.h"
using namespace std;
// for matching /proc/<pid> entries
static const regex is_number("\\d+");
bool is_valid_pid(const string& value)
{
return regex_match(value, is_number);
}
string get_process_name(const string& pid)
{
const string filename = "/proc/" + pid + "/comm";
string line = UNKNOWN_PROCESS_NAME;
ifstream in(filename);
if (in.is_open())
{
getline(in, line);
in.close();
}
return line;
}
ProcessInfo get_process_info(const string& pid)
{
return {pid, get_process_name(pid), get_swap_for_pid(pid)};
}
vector<ProcessInfo> get_process_info()
{
vector<ProcessInfo> procs;
DIR* dir = opendir("/proc");
if (dir != NULL)
{
struct dirent* entry;
while ((entry = readdir(dir)) != NULL)
{
const char* name = entry->d_name;
const string pid = name;
if (is_valid_pid(pid))
{
long swap = get_swap_for_pid(pid);
if (swap > 0)
{
ProcessInfo proc = {pid, get_process_name(pid), swap};
procs.push_back(proc);
}
}
}
closedir(dir);
}
return procs;
}
<commit_msg>no need for extra variable<commit_after>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <regex>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
#include "process.h"
#include "swap.h"
using namespace std;
// for matching /proc/<pid> entries
static const regex is_number("\\d+");
bool is_valid_pid(const string& value)
{
return regex_match(value, is_number);
}
string get_process_name(const string& pid)
{
const string filename = "/proc/" + pid + "/comm";
string line = UNKNOWN_PROCESS_NAME;
ifstream in(filename);
if (in.is_open())
{
getline(in, line);
in.close();
}
return line;
}
ProcessInfo get_process_info(const string& pid)
{
return {pid, get_process_name(pid), get_swap_for_pid(pid)};
}
vector<ProcessInfo> get_process_info()
{
vector<ProcessInfo> procs;
DIR* dir = opendir("/proc");
if (dir != NULL)
{
struct dirent* entry;
while ((entry = readdir(dir)) != NULL)
{
const string pid = entry->d_name;
if (is_valid_pid(pid))
{
long swap = get_swap_for_pid(pid);
if (swap > 0)
{
ProcessInfo proc = {pid, get_process_name(pid), swap};
procs.push_back(proc);
}
}
}
closedir(dir);
}
return procs;
}
<|endoftext|>
|
<commit_before>//
// Urho3D Engine
// Copyright (c) 2008-2011 Lasse rni
//
// 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 "Precompiled.h"
#include "Context.h"
#include "File.h"
#include "FileSystem.h"
#include "Image.h"
#include "Log.h"
#include <cstring>
#include <ddraw.h>
#include <stb_image.h>
#include <stb_image_write.h>
#include "DebugNew.h"
OBJECTTYPESTATIC(Image);
Image::Image(Context* context) :
Resource(context),
width_(0),
height_(0),
components_(0)
{
}
Image::~Image()
{
}
void Image::RegisterObject(Context* context)
{
context->RegisterFactory<Image>();
}
bool Image::Load(Deserializer& source)
{
// Check for DDS compressed format
if (source.ReadID() != "DDS ")
{
// Not DDS, use STBImage to load other image formats as uncompressed
source.Seek(0);
int width, height;
unsigned components;
unsigned char* pixelData = GetImageData(source, width, height, components);
if (!pixelData)
{
LOGERROR("Could not load image: " + String(stbi_failure_reason()));
return false;
}
SetSize(width, height, components);
SetData(pixelData);
FreeImageData(pixelData);
}
else
{
// DDS compressed format
DDSURFACEDESC2 ddsd;
source.Read(&ddsd, sizeof(ddsd));
switch (ddsd.ddpfPixelFormat.dwFourCC)
{
case FOURCC_DXT1:
compressedFormat_ = CF_DXT1;
components_ = 3;
break;
case FOURCC_DXT3:
compressedFormat_ = CF_DXT3;
components_ = 4;
break;
case FOURCC_DXT5:
compressedFormat_ = CF_DXT5;
components_ = 4;
break;
default:
LOGERROR("Unsupported DDS format");
return false;
}
unsigned dataSize = source.GetSize() - source.GetPosition();
data_ = new unsigned char[dataSize];
width_ = ddsd.dwWidth;
height_ = ddsd.dwHeight;
numCompressedLevels_ = ddsd.dwMipMapCount;
if (!numCompressedLevels_)
numCompressedLevels_ = 1;
SetMemoryUse(dataSize);
source.Read(data_.GetPtr(), dataSize);
}
return true;
}
void Image::SetSize(unsigned width, unsigned height, unsigned components)
{
if ((width == width_) && (height == height_) && (components == components_))
return;
if ((width <= 0) || (height <= 0))
return;
data_ = new unsigned char[width * height * components];
width_ = width;
height_ = height;
components_ = components;
compressedFormat_ = CF_NONE;
numCompressedLevels_ = 0;
SetMemoryUse(width * height * components);
}
void Image::SetData(const unsigned char* pixelData)
{
memcpy(data_.GetPtr(), pixelData, width_ * height_ * components_);
}
bool Image::SaveBMP(const String& fileName)
{
FileSystem* fileSystem = GetSubsystem<FileSystem>();
if ((fileSystem) && (!fileSystem->CheckAccess(GetPath(fileName))))
{
LOGERROR("Access denied to " + fileName);
return false;
}
if (IsCompressed())
{
LOGERROR("Can not save compressed image to BMP");
return false;
}
if (data_)
return stbi_write_bmp(fileName.CString(), width_, height_, components_, data_.GetPtr()) != 0;
else
return false;
}
bool Image::SaveTGA(const String& fileName)
{
FileSystem* fileSystem = GetSubsystem<FileSystem>();
if ((fileSystem) && (!fileSystem->CheckAccess(GetPath(fileName))))
{
LOGERROR("Access denied to " + fileName);
return false;
}
if (IsCompressed())
{
LOGERROR("Can not save compressed image to TGA");
return false;
}
if (data_)
return stbi_write_tga(fileName.CString(), width_, height_, components_, data_.GetPtr()) != 0;
else
return false;
}
unsigned char* Image::GetImageData(Deserializer& source, int& width, int& height, unsigned& components)
{
unsigned dataSize = source.GetSize();
SharedArrayPtr<unsigned char> buffer(new unsigned char[dataSize]);
source.Read(buffer.GetPtr(), dataSize);
return stbi_load_from_memory(buffer.GetPtr(), dataSize, &width, &height, (int *)&components, 0);
}
void Image::FreeImageData(unsigned char* pixelData)
{
if (!pixelData)
return;
stbi_image_free(pixelData);
}
SharedPtr<Image> Image::GetNextLevel() const
{
if (IsCompressed())
{
LOGERROR("Can not generate mip level from compressed data");
return SharedPtr<Image>();
}
if ((components_ < 1) || (components_ > 4))
{
LOGERROR("Illegal number of image components for mip level generation");
return SharedPtr<Image>();
}
int widthOut = width_ / 2;
int heightOut = height_ / 2;
if (widthOut < 1)
widthOut = 1;
if (heightOut < 1)
heightOut = 1;
SharedPtr<Image> mipImage(new Image(context_));
mipImage->SetSize(widthOut, heightOut, components_);
const unsigned char* pixelDataIn = data_.GetPtr();
unsigned char* pixelDataOut = mipImage->data_.GetPtr();
// 1D case
if ((height_ == 1) || (width_ == 1))
{
// Loop using the larger dimension
if (widthOut < heightOut)
widthOut = heightOut;
switch (components_)
{
case 1:
for (int x = 0; x < widthOut; ++x)
pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+1]) >> 1;
break;
case 2:
for (int x = 0; x < widthOut*2; x += 2)
{
pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+2]) >> 1;
pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+3]) >> 1;
}
break;
case 3:
for (int x = 0; x < widthOut*3; x += 3)
{
pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+3]) >> 1;
pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+4]) >> 1;
pixelDataOut[x+2] = ((unsigned)pixelDataIn[x*2+2] + pixelDataIn[x*2+5]) >> 1;
}
break;
case 4:
for (int x = 0; x < widthOut*4; x += 4)
{
pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+4]) >> 1;
pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+5]) >> 1;
pixelDataOut[x+2] = ((unsigned)pixelDataIn[x*2+2] + pixelDataIn[x*2+6]) >> 1;
pixelDataOut[x+3] = ((unsigned)pixelDataIn[x*2+3] + pixelDataIn[x*2+7]) >> 1;
}
break;
}
}
// 2D case
else
{
switch (components_)
{
case 1:
for (int y = 0; y < heightOut; ++y)
{
const unsigned char* inUpper = &pixelDataIn[(y*2)*width_];
const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_];
unsigned char* out = &pixelDataOut[y*widthOut];
for (int x = 0; x < widthOut; ++x)
{
out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+1] + inLower[x*2] + inLower[x*2+1]) >> 2;
}
}
break;
case 2:
for (int y = 0; y < heightOut; ++y)
{
const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*2];
const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*2];
unsigned char* out = &pixelDataOut[y*widthOut*2];
for (int x = 0; x < widthOut*2; x += 2)
{
out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+2] + inLower[x*2] + inLower[x*2+2]) >> 2;
out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+3] + inLower[x*2+1] + inLower[x*2+3]) >> 2;
}
}
break;
case 3:
for (int y = 0; y < heightOut; ++y)
{
const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*3];
const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*3];
unsigned char* out = &pixelDataOut[y*widthOut*3];
for (int x = 0; x < widthOut*3; x += 3)
{
out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+3] + inLower[x*2] + inLower[x*2+3]) >> 2;
out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+4] + inLower[x*2+1] + inLower[x*2+4]) >> 2;
out[x+2] = ((unsigned)inUpper[x*2+2] + inUpper[x*2+5] + inLower[x*2+2] + inLower[x*2+5]) >> 2;
}
}
break;
case 4:
for (int y = 0; y < heightOut; ++y)
{
const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*4];
const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*4];
unsigned char* out = &pixelDataOut[y*widthOut*4];
for (int x = 0; x < widthOut*4; x += 4)
{
out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+4] + inLower[x*2] + inLower[x*2+4]) >> 2;
out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+5] + inLower[x*2+1] + inLower[x*2+5]) >> 2;
out[x+2] = ((unsigned)inUpper[x*2+2] + inUpper[x*2+6] + inLower[x*2+2] + inLower[x*2+6]) >> 2;
out[x+3] = ((unsigned)inUpper[x*2+3] + inUpper[x*2+7] + inLower[x*2+3] + inLower[x*2+7]) >> 2;
}
}
break;
}
}
return mipImage;
}
CompressedLevel Image::GetCompressedLevel(unsigned index) const
{
CompressedLevel level;
if (compressedFormat_ == CF_NONE)
{
LOGERROR("Image is not compressed");
return level;
}
if (index >= numCompressedLevels_)
{
LOGERROR("Compressed image mip level out of bounds");
return level;
}
level.width_ = width_;
level.height_ = height_;
level.blockSize_ = (compressedFormat_ == CF_DXT1) ? 8 : 16;
unsigned i = 0;
unsigned offset = 0;
for (;;)
{
if (!level.width_)
level.width_ = 1;
if (!level.height_)
level.height_ = 1;
level.rowSize_ = ((level.width_ + 3) / 4) * level.blockSize_;
level.rows_ = ((level.height_ + 3) / 4);
level.data_ = data_.GetPtr() + offset;
level.dataSize_ = level.rows_ * level.rowSize_;
if (offset + level.dataSize_ > GetMemoryUse())
{
LOGERROR("Compressed level is outside image data. Offset: " + String(offset) + " Size: " + String(level.dataSize_) +
" Datasize: " + String(GetMemoryUse()));
level.data_ = 0;
return level;
}
if (i == index)
return level;
offset += level.dataSize_;
level.width_ /= 2;
level.height_ /= 2;
++i;
}
}
<commit_msg>Image.cpp no longer relies on ddraw.h.<commit_after>//
// Urho3D Engine
// Copyright (c) 2008-2011 Lasse rni
//
// 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 "Precompiled.h"
#include "Context.h"
#include "File.h"
#include "FileSystem.h"
#include "Image.h"
#include "Log.h"
#include <cstring>
#include <stb_image.h>
#include <stb_image_write.h>
#include "DebugNew.h"
#ifndef DUMMYUNIONNAMEN
#if defined(__cplusplus) || !defined(NONAMELESSUNION)
#define DUMMYUNIONNAMEN(n)
#else
#define DUMMYUNIONNAMEN(n) u##n
#endif
#endif
#ifndef MAKEFOURCC
#define MAKEFOURCC(ch0, ch1, ch2, ch3) ((unsigned)(ch0) | ((unsigned)(ch1) << 8) | ((unsigned)(ch2) << 16) | ((unsigned)(ch3) << 24))
#endif
#define FOURCC_DXT1 (MAKEFOURCC('D','X','T','1'))
#define FOURCC_DXT2 (MAKEFOURCC('D','X','T','2'))
#define FOURCC_DXT3 (MAKEFOURCC('D','X','T','3'))
#define FOURCC_DXT4 (MAKEFOURCC('D','X','T','4'))
#define FOURCC_DXT5 (MAKEFOURCC('D','X','T','5'))
typedef struct _DDCOLORKEY
{
unsigned dwColorSpaceLowValue;
unsigned dwColorSpaceHighValue;
} DDCOLORKEY;
typedef struct _DDPIXELFORMAT
{
unsigned dwSize;
unsigned dwFlags;
unsigned dwFourCC;
union
{
unsigned dwRGBBitCount;
unsigned dwYUVBitCount;
unsigned dwZBufferBitDepth;
unsigned dwAlphaBitDepth;
unsigned dwLuminanceBitCount;
unsigned dwBumpBitCount;
unsigned dwPrivateFormatBitCount;
} DUMMYUNIONNAMEN(1);
union
{
unsigned dwRBitMask;
unsigned dwYBitMask;
unsigned dwStencilBitDepth;
unsigned dwLuminanceBitMask;
unsigned dwBumpDuBitMask;
unsigned dwOperations;
} DUMMYUNIONNAMEN(2);
union
{
unsigned dwGBitMask;
unsigned dwUBitMask;
unsigned dwZBitMask;
unsigned dwBumpDvBitMask;
struct
{
unsigned short wFlipMSTypes;
unsigned short wBltMSTypes;
} MultiSampleCaps;
} DUMMYUNIONNAMEN(3);
union
{
unsigned dwBBitMask;
unsigned dwVBitMask;
unsigned dwStencilBitMask;
unsigned dwBumpLuminanceBitMask;
} DUMMYUNIONNAMEN(4);
union
{
unsigned dwRGBAlphaBitMask;
unsigned dwYUVAlphaBitMask;
unsigned dwLuminanceAlphaBitMask;
unsigned dwRGBZBitMask;
unsigned dwYUVZBitMask;
} DUMMYUNIONNAMEN(5);
} DDPIXELFORMAT;
typedef struct _DDSCAPS2
{
unsigned dwCaps;
unsigned dwCaps2;
unsigned dwCaps3;
union
{
unsigned dwCaps4;
unsigned dwVolumeDepth;
} DUMMYUNIONNAMEN(1);
} DDSCAPS2;
typedef struct _DDSURFACEDESC2
{
unsigned dwSize;
unsigned dwFlags;
unsigned dwHeight;
unsigned dwWidth;
union
{
long lPitch;
unsigned dwLinearSize;
} DUMMYUNIONNAMEN(1);
union
{
unsigned dwBackBufferCount;
unsigned dwDepth;
} DUMMYUNIONNAMEN(5);
union
{
unsigned dwMipMapCount;
unsigned dwRefreshRate;
unsigned dwSrcVBHandle;
} DUMMYUNIONNAMEN(2);
unsigned dwAlphaBitDepth;
unsigned dwReserved;
void* lpSurface;
union
{
DDCOLORKEY ddckCKDestOverlay;
unsigned dwEmptyFaceColor;
} DUMMYUNIONNAMEN(3);
DDCOLORKEY ddckCKDestBlt;
DDCOLORKEY ddckCKSrcOverlay;
DDCOLORKEY ddckCKSrcBlt;
union
{
DDPIXELFORMAT ddpfPixelFormat;
unsigned dwFVF;
} DUMMYUNIONNAMEN(4);
DDSCAPS2 ddsCaps;
unsigned dwTextureStage;
} DDSURFACEDESC2;
OBJECTTYPESTATIC(Image);
Image::Image(Context* context) :
Resource(context),
width_(0),
height_(0),
components_(0)
{
}
Image::~Image()
{
}
void Image::RegisterObject(Context* context)
{
context->RegisterFactory<Image>();
}
bool Image::Load(Deserializer& source)
{
// Check for DDS compressed format
if (source.ReadID() != "DDS ")
{
// Not DDS, use STBImage to load other image formats as uncompressed
source.Seek(0);
int width, height;
unsigned components;
unsigned char* pixelData = GetImageData(source, width, height, components);
if (!pixelData)
{
LOGERROR("Could not load image: " + String(stbi_failure_reason()));
return false;
}
SetSize(width, height, components);
SetData(pixelData);
FreeImageData(pixelData);
}
else
{
// DDS compressed format
DDSURFACEDESC2 ddsd;
source.Read(&ddsd, sizeof(ddsd));
switch (ddsd.ddpfPixelFormat.dwFourCC)
{
case FOURCC_DXT1:
compressedFormat_ = CF_DXT1;
components_ = 3;
break;
case FOURCC_DXT3:
compressedFormat_ = CF_DXT3;
components_ = 4;
break;
case FOURCC_DXT5:
compressedFormat_ = CF_DXT5;
components_ = 4;
break;
default:
LOGERROR("Unsupported DDS format");
return false;
}
unsigned dataSize = source.GetSize() - source.GetPosition();
data_ = new unsigned char[dataSize];
width_ = ddsd.dwWidth;
height_ = ddsd.dwHeight;
numCompressedLevels_ = ddsd.dwMipMapCount;
if (!numCompressedLevels_)
numCompressedLevels_ = 1;
SetMemoryUse(dataSize);
source.Read(data_.GetPtr(), dataSize);
}
return true;
}
void Image::SetSize(unsigned width, unsigned height, unsigned components)
{
if ((width == width_) && (height == height_) && (components == components_))
return;
if ((width <= 0) || (height <= 0))
return;
data_ = new unsigned char[width * height * components];
width_ = width;
height_ = height;
components_ = components;
compressedFormat_ = CF_NONE;
numCompressedLevels_ = 0;
SetMemoryUse(width * height * components);
}
void Image::SetData(const unsigned char* pixelData)
{
memcpy(data_.GetPtr(), pixelData, width_ * height_ * components_);
}
bool Image::SaveBMP(const String& fileName)
{
FileSystem* fileSystem = GetSubsystem<FileSystem>();
if ((fileSystem) && (!fileSystem->CheckAccess(GetPath(fileName))))
{
LOGERROR("Access denied to " + fileName);
return false;
}
if (IsCompressed())
{
LOGERROR("Can not save compressed image to BMP");
return false;
}
if (data_)
return stbi_write_bmp(fileName.CString(), width_, height_, components_, data_.GetPtr()) != 0;
else
return false;
}
bool Image::SaveTGA(const String& fileName)
{
FileSystem* fileSystem = GetSubsystem<FileSystem>();
if ((fileSystem) && (!fileSystem->CheckAccess(GetPath(fileName))))
{
LOGERROR("Access denied to " + fileName);
return false;
}
if (IsCompressed())
{
LOGERROR("Can not save compressed image to TGA");
return false;
}
if (data_)
return stbi_write_tga(fileName.CString(), width_, height_, components_, data_.GetPtr()) != 0;
else
return false;
}
unsigned char* Image::GetImageData(Deserializer& source, int& width, int& height, unsigned& components)
{
unsigned dataSize = source.GetSize();
SharedArrayPtr<unsigned char> buffer(new unsigned char[dataSize]);
source.Read(buffer.GetPtr(), dataSize);
return stbi_load_from_memory(buffer.GetPtr(), dataSize, &width, &height, (int *)&components, 0);
}
void Image::FreeImageData(unsigned char* pixelData)
{
if (!pixelData)
return;
stbi_image_free(pixelData);
}
SharedPtr<Image> Image::GetNextLevel() const
{
if (IsCompressed())
{
LOGERROR("Can not generate mip level from compressed data");
return SharedPtr<Image>();
}
if ((components_ < 1) || (components_ > 4))
{
LOGERROR("Illegal number of image components for mip level generation");
return SharedPtr<Image>();
}
int widthOut = width_ / 2;
int heightOut = height_ / 2;
if (widthOut < 1)
widthOut = 1;
if (heightOut < 1)
heightOut = 1;
SharedPtr<Image> mipImage(new Image(context_));
mipImage->SetSize(widthOut, heightOut, components_);
const unsigned char* pixelDataIn = data_.GetPtr();
unsigned char* pixelDataOut = mipImage->data_.GetPtr();
// 1D case
if ((height_ == 1) || (width_ == 1))
{
// Loop using the larger dimension
if (widthOut < heightOut)
widthOut = heightOut;
switch (components_)
{
case 1:
for (int x = 0; x < widthOut; ++x)
pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+1]) >> 1;
break;
case 2:
for (int x = 0; x < widthOut*2; x += 2)
{
pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+2]) >> 1;
pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+3]) >> 1;
}
break;
case 3:
for (int x = 0; x < widthOut*3; x += 3)
{
pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+3]) >> 1;
pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+4]) >> 1;
pixelDataOut[x+2] = ((unsigned)pixelDataIn[x*2+2] + pixelDataIn[x*2+5]) >> 1;
}
break;
case 4:
for (int x = 0; x < widthOut*4; x += 4)
{
pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+4]) >> 1;
pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+5]) >> 1;
pixelDataOut[x+2] = ((unsigned)pixelDataIn[x*2+2] + pixelDataIn[x*2+6]) >> 1;
pixelDataOut[x+3] = ((unsigned)pixelDataIn[x*2+3] + pixelDataIn[x*2+7]) >> 1;
}
break;
}
}
// 2D case
else
{
switch (components_)
{
case 1:
for (int y = 0; y < heightOut; ++y)
{
const unsigned char* inUpper = &pixelDataIn[(y*2)*width_];
const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_];
unsigned char* out = &pixelDataOut[y*widthOut];
for (int x = 0; x < widthOut; ++x)
{
out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+1] + inLower[x*2] + inLower[x*2+1]) >> 2;
}
}
break;
case 2:
for (int y = 0; y < heightOut; ++y)
{
const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*2];
const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*2];
unsigned char* out = &pixelDataOut[y*widthOut*2];
for (int x = 0; x < widthOut*2; x += 2)
{
out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+2] + inLower[x*2] + inLower[x*2+2]) >> 2;
out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+3] + inLower[x*2+1] + inLower[x*2+3]) >> 2;
}
}
break;
case 3:
for (int y = 0; y < heightOut; ++y)
{
const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*3];
const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*3];
unsigned char* out = &pixelDataOut[y*widthOut*3];
for (int x = 0; x < widthOut*3; x += 3)
{
out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+3] + inLower[x*2] + inLower[x*2+3]) >> 2;
out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+4] + inLower[x*2+1] + inLower[x*2+4]) >> 2;
out[x+2] = ((unsigned)inUpper[x*2+2] + inUpper[x*2+5] + inLower[x*2+2] + inLower[x*2+5]) >> 2;
}
}
break;
case 4:
for (int y = 0; y < heightOut; ++y)
{
const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*4];
const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*4];
unsigned char* out = &pixelDataOut[y*widthOut*4];
for (int x = 0; x < widthOut*4; x += 4)
{
out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+4] + inLower[x*2] + inLower[x*2+4]) >> 2;
out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+5] + inLower[x*2+1] + inLower[x*2+5]) >> 2;
out[x+2] = ((unsigned)inUpper[x*2+2] + inUpper[x*2+6] + inLower[x*2+2] + inLower[x*2+6]) >> 2;
out[x+3] = ((unsigned)inUpper[x*2+3] + inUpper[x*2+7] + inLower[x*2+3] + inLower[x*2+7]) >> 2;
}
}
break;
}
}
return mipImage;
}
CompressedLevel Image::GetCompressedLevel(unsigned index) const
{
CompressedLevel level;
if (compressedFormat_ == CF_NONE)
{
LOGERROR("Image is not compressed");
return level;
}
if (index >= numCompressedLevels_)
{
LOGERROR("Compressed image mip level out of bounds");
return level;
}
level.width_ = width_;
level.height_ = height_;
level.blockSize_ = (compressedFormat_ == CF_DXT1) ? 8 : 16;
unsigned i = 0;
unsigned offset = 0;
for (;;)
{
if (!level.width_)
level.width_ = 1;
if (!level.height_)
level.height_ = 1;
level.rowSize_ = ((level.width_ + 3) / 4) * level.blockSize_;
level.rows_ = ((level.height_ + 3) / 4);
level.data_ = data_.GetPtr() + offset;
level.dataSize_ = level.rows_ * level.rowSize_;
if (offset + level.dataSize_ > GetMemoryUse())
{
LOGERROR("Compressed level is outside image data. Offset: " + String(offset) + " Size: " + String(level.dataSize_) +
" Datasize: " + String(GetMemoryUse()));
level.data_ = 0;
return level;
}
if (i == index)
return level;
offset += level.dataSize_;
level.width_ /= 2;
level.height_ /= 2;
++i;
}
}
<|endoftext|>
|
<commit_before>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10_HH
#define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10_HH
#include <memory>
#include <vector>
#include <utility>
#include <sstream>
#include <dune/common/static_assert.hh>
#include <dune/common/fmatrix.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/constant.hh>
#include <dune/stuff/functions/combined.hh>
#include <dune/stuff/functions/spe10.hh>
#include <dune/stuff/playground/functions/indicator.hh>
#include <dune/pymor/functions/default.hh>
#include "../../../linearelliptic/problems/default.hh"
namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace Problems {
namespace Spe10 {
template< class E, class D, int d, class R, int r = 1 >
class Model1
: public ProblemInterface< E, D, d, R, r >
{
Model1() { static_assert(AlwaysFalse< E >::value, "Not available for these dimensions!"); }
};
template< class E, class D, class R >
class Model1< E, D, 2, R, 1 >
: public Problems::Default< E, D, 2, R, 1 >
{
typedef Problems::Default< E, D, 2, R, 1 > BaseType;
typedef Model1< E, D, 2, R, 1 > ThisType;
typedef Stuff::Functions::Constant< E, D, 2, R, 1 > ConstantFunctionType;
typedef Stuff::Functions::Indicator< E, D, 2, R, 1 > IndicatorFunctionType;
typedef Stuff::Functions::Spe10::Model1< E, D, 2, R, 2, 2 > Spe10FunctionType;
public:
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const unsigned int dimRange = BaseType::dimRange;
static const bool available = true;
static std::string static_id()
{
return BaseType::BaseType::static_id() + ".spe10.model1";
}
static Stuff::Common::Configuration default_config(const std::string sub_name = "")
{
std::istringstream ss("# no channel, just to show the definition of a channel (analogue to forces)\n"
"channel.0.domain = [0.5 1.0; 0.2 0.3]\n"
"channel.0.value = 0.0\n"
"# force\n"
"forces.0.domain = [0.95 1.10; 0.30 0.45]\n"
"forces.0.value = 2000\n"
"forces.1.domain = [3.00 3.15; 0.75 0.90]\n"
"forces.1.value = -1000\n"
"forces.2.domain = [4.25 4.40; 0.25 0.40]\n"
"forces.2.value = -1000");
Stuff::Common::Configuration config(ss);
config["filename"] = Stuff::Functions::Spe10::internal::model1_filename;
config["lower_left"] = "[0.0 0.0]";
config["upper_right"] = "[5.0 1.0]";
config["parametric_channel"] = "false";
if (sub_name.empty())
return config;
else {
Stuff::Common::Configuration tmp;
tmp.add(config, sub_name);
return tmp;
}
} // ... default_config(...)
static std::unique_ptr< ThisType > create(const Stuff::Common::Configuration config = default_config(),
const std::string sub_name = static_id())
{
const Stuff::Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;
const Stuff::Common::Configuration def_cfg = default_config();
return Stuff::Common::make_unique< ThisType >(
cfg.get("filename", def_cfg.get< std::string >("filename")),
cfg.get("lower_left", def_cfg.get< DomainType >("lower_left")),
cfg.get("upper_right", def_cfg.get< DomainType >("upper_right")),
get_values(cfg, "channel"),
get_values(cfg, "forces"),
cfg.get("parametric_channel", def_cfg.get< bool >("parametric_channel")));
} // ... create(...)
Model1(const std::string filename,
const DomainType& lower_left,
const DomainType& upper_right,
const std::vector< std::tuple< DomainType, DomainType, RangeFieldType > >& channel_values,
const std::vector< std::tuple< DomainType, DomainType, RangeFieldType > >& force_values,
const bool parametric_channel = false)
: BaseType(create_base(filename, lower_left, upper_right, channel_values, force_values, parametric_channel))
{}
private:
typedef std::vector< std::tuple< DomainType, DomainType, RangeFieldType > > Values;
static BaseType create_base(const std::string filename,
const DomainType& lower_left,
const DomainType& upper_right,
const Values& channel_values,
const Values& force_values,
const bool parametric_channel)
{
auto one = std::make_shared< ConstantFunctionType >(1, "one");
auto channel = std::make_shared< IndicatorFunctionType >(channel_values, "channel");
auto diffusion_tensor = std::make_shared< Spe10FunctionType >(filename,
lower_left,
upper_right,
Stuff::Functions::Spe10::internal::model1_min_value,
Stuff::Functions::Spe10::internal::model1_max_value,
"diffusion_tensor");
auto force = std::make_shared< IndicatorFunctionType >(force_values, "force");
auto dirichlet = std::make_shared< ConstantFunctionType >(0, "dirichlet");
auto neumann = std::make_shared< ConstantFunctionType >(0, "neumann");
if (parametric_channel) {
typedef Pymor::Functions::NonparametricDefault< E, D, 2, R, 1 > ScalarWrapper;
typedef Pymor::Functions::NonparametricDefault< E, D, 2, R, 2, 2 > MatrixWrapper;
typedef Pymor::Functions::AffinelyDecomposableDefault< E, D, 2, R, 1 > ParametricFunctionType;
auto diffusion_factor = std::make_shared< ParametricFunctionType >("diffusion_factor");
diffusion_factor->register_affine_part(Stuff::Functions::make_sum(one, channel));
diffusion_factor->register_component(channel,
new Pymor::ParameterFunctional("channel", 1, "-1.0*channel"));
return BaseType(diffusion_factor,
std::make_shared< MatrixWrapper >(diffusion_tensor),
std::make_shared< ScalarWrapper >(force),
std::make_shared< ScalarWrapper >(dirichlet),
std::make_shared< ScalarWrapper >(neumann));
} else {
auto zero_pt_nine = std::make_shared< ConstantFunctionType >(0.9, "0.9");
return BaseType(Stuff::Functions::make_sum(one,
Stuff::Functions::make_product(zero_pt_nine,
channel,
"scaled_channel"),
"diffusion_factor"),
diffusion_tensor,
force,
dirichlet,
neumann);
}
} // ... create_base(...)
static Values get_values(const Stuff::Common::Configuration& cfg, const std::string id)
{
Values values;
DomainType tmp_lower;
DomainType tmp_upper;
if (cfg.has_sub(id)) {
const Stuff::Common::Configuration sub_cfg = cfg.sub(id);
size_t cc = 0;
while (sub_cfg.has_sub(DSC::toString(cc))) {
const Stuff::Common::Configuration local_cfg = sub_cfg.sub(DSC::toString(cc));
if (local_cfg.has_key("domain") && local_cfg.has_key("value")) {
auto domains = local_cfg.get< FieldMatrix< DomainFieldType, 2, 2 > >("domain");
tmp_lower[0] = domains[0][0];
tmp_lower[1] = domains[1][0];
tmp_upper[0] = domains[0][1];
tmp_upper[1] = domains[1][1];
auto val = local_cfg.get< RangeFieldType >("value");
values.emplace_back(tmp_lower, tmp_upper, val);
} else
break;
++cc;
}
}
return values;
} // ... get_values(...)
}; // class Model1< ..., 2, ... 1 >
} // namespace Spe10
} // namespace Problems
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10_HH
<commit_msg>[linearelliptic.problems.spe10] add switch between indicator and flattop<commit_after>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10_HH
#define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10_HH
#include <memory>
#include <vector>
#include <utility>
#include <sstream>
#include <dune/common/static_assert.hh>
#include <dune/common/fmatrix.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/common/fvector.hh>
#include <dune/stuff/common/float_cmp.hh>
#include <dune/stuff/functions/constant.hh>
#include <dune/stuff/functions/combined.hh>
#include <dune/stuff/functions/flattop.hh>
#include <dune/stuff/functions/spe10.hh>
#include <dune/stuff/playground/functions/indicator.hh>
#include <dune/pymor/functions/default.hh>
#include "../../../linearelliptic/problems/default.hh"
namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace Problems {
namespace Spe10 {
template< class E, class D, int d, class R, int r = 1 >
class Model1
: public ProblemInterface< E, D, d, R, r >
{
Model1() { static_assert(AlwaysFalse< E >::value, "Not available for these dimensions!"); }
};
template< class E, class D, class R >
class Model1< E, D, 2, R, 1 >
: public Problems::Default< E, D, 2, R, 1 >
{
typedef Problems::Default< E, D, 2, R, 1 > BaseType;
typedef Model1< E, D, 2, R, 1 > ThisType;
typedef Stuff::Functions::Constant< E, D, 2, R, 1 > ConstantFunctionType;
typedef Stuff::Functions::FlatTop< E, D, 2, R, 1 > FlatTopFunctionType;
typedef Stuff::Functions::Indicator< E, D, 2, R, 1 > IndicatorFunctionType;
typedef Stuff::Functions::Spe10::Model1< E, D, 2, R, 2, 2 > Spe10FunctionType;
public:
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const unsigned int dimRange = BaseType::dimRange;
static const bool available = true;
static std::string static_id()
{
return BaseType::BaseType::static_id() + ".spe10.model1";
}
static Stuff::Common::Configuration default_config(const std::string sub_name = "")
{
std::istringstream ss("# a definition of a channel would be analogue to the one of forces\n"
"forces.0.domain = [0.95 1.10; 0.30 0.45]\n"
"forces.0.value = 2000\n"
"forces.1.domain = [3.00 3.15; 0.75 0.90]\n"
"forces.1.value = -1000\n"
"forces.2.domain = [4.25 4.40; 0.25 0.40]\n"
"forces.2.value = -1000");
Stuff::Common::Configuration config(ss);
config["filename"] = Stuff::Functions::Spe10::internal::model1_filename;
config["lower_left"] = "[0.0 0.0]";
config["upper_right"] = "[5.0 1.0]";
config["parametric_channel"] = "false";
config.set("channel_boundary_layer", FlatTopFunctionType::default_config().template get< std::string >("boundary_layer"));
if (sub_name.empty())
return config;
else {
Stuff::Common::Configuration tmp;
tmp.add(config, sub_name);
return tmp;
}
} // ... default_config(...)
static std::unique_ptr< ThisType > create(const Stuff::Common::Configuration config = default_config(),
const std::string sub_name = static_id())
{
const Stuff::Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;
const Stuff::Common::Configuration def_cfg = default_config();
return Stuff::Common::make_unique< ThisType >(
cfg.get("filename", def_cfg.get< std::string >("filename")),
cfg.get("lower_left", def_cfg.get< DomainType >("lower_left")),
cfg.get("upper_right", def_cfg.get< DomainType >("upper_right")),
get_values(cfg, "channel"),
get_values(cfg, "forces"),
cfg.get("channel_boundary_layer", def_cfg.get< DomainType >("channel_boundary_layer")),
cfg.get("parametric_channel", def_cfg.get< bool >("parametric_channel")));
} // ... create(...)
Model1(const std::string filename,
const DomainType& lower_left,
const DomainType& upper_right,
const std::vector< std::tuple< DomainType, DomainType, RangeFieldType > >& channel_values,
const std::vector< std::tuple< DomainType, DomainType, RangeFieldType > >& force_values,
const DomainType& channel_boundary_layer = default_config().get< DomainType >("channel_boundary_layer"),
const bool parametric_channel = default_config().get< bool >("parametric_channel"))
: BaseType(create_base(filename,
lower_left,
upper_right,
channel_values,
force_values,
channel_boundary_layer,
parametric_channel))
{}
private:
typedef std::vector< std::tuple< DomainType, DomainType, RangeFieldType > > Values;
typedef typename BaseType::DiffusionFactorType::NonparametricType FlatTopIndicatorType;
static BaseType create_base(const std::string filename,
const DomainType& lower_left,
const DomainType& upper_right,
const Values& channel_values,
const Values& force_values,
const DomainType& channel_boundary_layer,
const bool parametric_channel)
{
// build the channel as a sum of flattop functions
std::shared_ptr< FlatTopIndicatorType > channel(nullptr);
if (channel_values.empty())
channel = std::make_shared< ConstantFunctionType >(0, "zero");
else
channel = create_indicator(channel_values[0], channel_boundary_layer);
for (size_t ii = 1; ii < channel_values.size(); ++ii)
channel = Stuff::Functions::make_sum(channel,
create_indicator(channel_values[ii], channel_boundary_layer),
"channel");
// build the rest
auto one = std::make_shared< ConstantFunctionType >(1, "one");
auto diffusion_tensor = std::make_shared< Spe10FunctionType >(filename,
lower_left,
upper_right,
Stuff::Functions::Spe10::internal::model1_min_value,
Stuff::Functions::Spe10::internal::model1_max_value,
"diffusion_tensor");
auto force = std::make_shared< IndicatorFunctionType >(force_values, "force");
auto dirichlet = std::make_shared< ConstantFunctionType >(0, "dirichlet");
auto neumann = std::make_shared< ConstantFunctionType >(0, "neumann");
if (parametric_channel) {
typedef Pymor::Functions::NonparametricDefault< E, D, 2, R, 1 > ScalarWrapper;
typedef Pymor::Functions::NonparametricDefault< E, D, 2, R, 2, 2 > MatrixWrapper;
typedef Pymor::Functions::AffinelyDecomposableDefault< E, D, 2, R, 1 > ParametricFunctionType;
auto diffusion_factor = std::make_shared< ParametricFunctionType >("diffusion_factor");
diffusion_factor->register_affine_part(Stuff::Functions::make_sum(one, channel));
diffusion_factor->register_component(channel,
new Pymor::ParameterFunctional("mu", 1, "-1.0*mu"));
return BaseType(diffusion_factor,
std::make_shared< MatrixWrapper >(diffusion_tensor),
std::make_shared< ScalarWrapper >(force),
std::make_shared< ScalarWrapper >(dirichlet),
std::make_shared< ScalarWrapper >(neumann));
} else {
auto zero_pt_nine = std::make_shared< ConstantFunctionType >(0.9, "0.9");
return BaseType(Stuff::Functions::make_sum(one,
Stuff::Functions::make_product(zero_pt_nine,
channel,
"scaled_channel"),
"diffusion_factor"),
diffusion_tensor,
force,
dirichlet,
neumann);
}
} // ... create_base(...)
static Values get_values(const Stuff::Common::Configuration& cfg, const std::string id)
{
Values values;
DomainType tmp_lower;
DomainType tmp_upper;
if (cfg.has_sub(id)) {
const Stuff::Common::Configuration sub_cfg = cfg.sub(id);
size_t cc = 0;
while (sub_cfg.has_sub(DSC::toString(cc))) {
const Stuff::Common::Configuration local_cfg = sub_cfg.sub(DSC::toString(cc));
if (local_cfg.has_key("domain") && local_cfg.has_key("value")) {
auto domains = local_cfg.get< FieldMatrix< DomainFieldType, 2, 2 > >("domain");
tmp_lower[0] = domains[0][0];
tmp_lower[1] = domains[1][0];
tmp_upper[0] = domains[0][1];
tmp_upper[1] = domains[1][1];
auto val = local_cfg.get< RangeFieldType >("value");
values.emplace_back(tmp_lower, tmp_upper, val);
} else
break;
++cc;
}
}
return values;
} // ... get_values(...)
static std::shared_ptr< FlatTopIndicatorType > create_indicator(const typename Values::value_type& value,
const DomainType& channel_boundary_layer)
{
if (Stuff::Common::FloatCmp::eq(channel_boundary_layer, DomainType(0))) {
return std::make_shared< IndicatorFunctionType >(Values(1, value), "channel");
} else
return std::make_shared< FlatTopFunctionType >(std::get< 0 >(value),
std::get< 1 >(value),
channel_boundary_layer,
std::get< 2 >(value),
"channel");
} // ... create_indicator(...)
}; // class Model1< ..., 2, ... 1 >
} // namespace Spe10
} // namespace Problems
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_SPE10_HH
<|endoftext|>
|
<commit_before>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
* Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file gaussian_filter_kf.hpp
* \date October 2014
* \author Jan Issac (jan.issac@gmail.com)
*/
#ifndef FL__FILTER__GAUSSIAN__GAUSSIAN_FILTER_KF_HPP
#define FL__FILTER__GAUSSIAN__GAUSSIAN_FILTER_KF_HPP
#include <utility>
#include <fl/util/meta.hpp>
#include <fl/util/traits.hpp>
#include <fl/util/profiling.hpp>
#include <fl/exception/exception.hpp>
#include <fl/filter/filter_interface.hpp>
#include <fl/model/process/linear_state_transition_model.hpp>
#include <fl/model/observation/linear_gaussian_observation_model.hpp>
namespace fl
{
/**
* \defgroup linear_gaussian_filter Linear Gaussian Filter (Kalman Filter)
* \ingroup filters
*/
// Gaussian filter forward declaration
template <typename...> class GaussianFilter;
/**
* \internal
* \ingroup linear_gaussian_filter
*
* Traits of the Linear GaussianFilter (KalmanFilter)
*/
template <typename LinearStateTransitionModel, typename LinearObservationModel>
struct Traits<
GaussianFilter<
LinearStateTransitionModel,
LinearObservationModel>>
{
typedef typename LinearStateTransitionModel::State State;
typedef typename LinearStateTransitionModel::Input Input;
typedef typename LinearObservationModel::Obsrv Obsrv;
typedef Gaussian<State> Belief;
};
/**
* \ingroup linear_gaussian_filter
*
* \brief GaussianFilter resembles the Kalman filter.
*
* \tparam State State type defining the state space
* \tparam Input Process model input type
* \tparam Obsrv Observation type of the linear observation Gaussian model
*
* The KalmanFilter type is represented by the GaussianFilter using
* the linear Gaussian Models.
*
*/
template <
typename LinearStateTransitionModel,
typename LinearObservationModel
>
class GaussianFilter<
LinearStateTransitionModel,
LinearObservationModel>
:
/* Implement the conceptual filter interface */
public
FilterInterface<
GaussianFilter<
typename ForwardLinearModelOnly<LinearStateTransitionModel>::Type,
typename ForwardLinearModelOnly<LinearObservationModel>::Type>>
{
public:
typedef typename LinearStateTransitionModel::State State;
typedef typename LinearStateTransitionModel::Input Input;
typedef typename LinearObservationModel::Obsrv Obsrv;
/**
* \brief Represents the underlying distribution of the estimated state.
* In the case of the Kalman filter, the distribution is a simple Gaussian
* with the dimension of the \c State
*/
typedef Gaussian<State> Belief;
public:
/**
* Creates a linear Gaussian filter (a KalmanFilter)
*
* \param process_model Process model instance
* \param obsrv_model Obsrv model instance
*/
GaussianFilter(const LinearStateTransitionModel& process_model,
const LinearObservationModel& obsrv_model)
: process_model_(process_model),
obsrv_model_(obsrv_model)
{ }
/**
* \brief Overridable default destructor
*/
virtual ~GaussianFilter() { }
/**
* \copydoc FilterInterface::predict
*
* KalmanFilter prediction step
*
* Given the following matrices
*
* - \f$ A \f$: Dynamics Matrix
* - \f$ B \f$: Dynamics Noise Covariance
*
* and the current state distribution
* \f$ {\cal N}(x_t\mid \hat{x}_t, \hat{\Sigma}_{t}) \f$,
*
* the prediction steps is the discrete linear mapping
*
* \f$ \bar{x}_{t} = A \hat{x}_t\f$ and
*
* \f$ \bar{\Sigma}_{t} = A\hat{\Sigma}_{t}A^T + Q \f$
*/
virtual void predict(const Belief& prior_belief,
const Input& input,
Belief& predicted_belief)
{
auto A = process_model_.dynamics_matrix();
auto B = process_model_.input_matrix();
auto Q = process_model_.noise_covariance();
predicted_belief.mean(
A * prior_belief.mean() + B * input);
predicted_belief.covariance(
A * prior_belief.covariance() * A.transpose() + Q);
}
/**
* \copydoc FilterInterface::update
*
* Given the following matrices
*
* - \f$ H \f$: Sensor Matrix
* - \f$ R \f$: Sensor Noise Covariance
*
* and the current predicted state distribution
* \f$ {\cal N}(x_t\mid \bar{x}_t, \bar{\Sigma}_{t}) \f$,
*
* the update steps is the discrete linear mapping
*
* \f$ \hat{x}_{t+1} = \bar{x}_t + K (y - H\bar{x}_t)\f$ and
*
* \f$ \hat{\Sigma}_{t} = (I - KH) \bar{\Sigma}_{t}\f$
*
* with the KalmanGain
*
* \f$ K = \bar{\Sigma}_{t}H^T (H\bar{\Sigma}_{t}H^T+R)^{-1}\f$.
*/
virtual void update(const Belief& predicted_belief,
const Obsrv& y,
Belief& posterior_belief)
{
auto H = obsrv_model_.sensor_matrix();
auto R = obsrv_model_.noise_covariance();
auto mean = predicted_belief.mean();
auto cov_xx = predicted_belief.covariance();
auto S = (H * cov_xx * H.transpose() + R).eval();
auto K = (cov_xx * H.transpose() * S.inverse()).eval();
// PV(cov_xx);
// PV(K);
// PV((y - H * mean));
posterior_belief.mean(mean + K * (y - H * mean));
posterior_belief.covariance(cov_xx - K * H * cov_xx);
}
virtual Belief create_belief() const
{
auto belief = Belief(process_model().state_dimension());
return belief;
}
virtual std::string name() const
{
return "GaussianFilter<"
+ this->list_arguments(
process_model().name(),
obsrv_model().name())
+ ">";
}
virtual std::string description() const
{
return "Linear Gaussian filter (the Kalman Filter) with"
+ this->list_descriptions(
process_model().description(),
obsrv_model().description());
}
LinearStateTransitionModel& process_model() { return process_model_; }
LinearObservationModel& obsrv_model() { return obsrv_model_; }
const LinearStateTransitionModel& process_model() const { return process_model_; }
const LinearObservationModel& obsrv_model() const { return obsrv_model_; }
protected:
/** \cond internal */
LinearStateTransitionModel process_model_;
LinearObservationModel obsrv_model_;
/** \endcond */
};
}
#endif
<commit_msg>:lipstick:<commit_after>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
* Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file gaussian_filter_kf.hpp
* \date October 2014
* \author Jan Issac (jan.issac@gmail.com)
*/
#ifndef FL__FILTER__GAUSSIAN__GAUSSIAN_FILTER_KF_HPP
#define FL__FILTER__GAUSSIAN__GAUSSIAN_FILTER_KF_HPP
#include <utility>
#include <fl/util/meta.hpp>
#include <fl/util/traits.hpp>
#include <fl/util/profiling.hpp>
#include <fl/exception/exception.hpp>
#include <fl/filter/filter_interface.hpp>
#include <fl/model/process/linear_state_transition_model.hpp>
#include <fl/model/observation/linear_gaussian_observation_model.hpp>
namespace fl
{
/**
* \defgroup linear_gaussian_filter Linear Gaussian Filter (Kalman Filter)
* \ingroup filters
*/
// Gaussian filter forward declaration
template <typename...> class GaussianFilter;
/**
* \internal
* \ingroup linear_gaussian_filter
*
* Traits of the Linear GaussianFilter (KalmanFilter)
*/
template <typename LinearStateTransitionModel, typename LinearObservationModel>
struct Traits<
GaussianFilter<
LinearStateTransitionModel,
LinearObservationModel>>
{
typedef typename LinearStateTransitionModel::State State;
typedef typename LinearStateTransitionModel::Input Input;
typedef typename LinearObservationModel::Obsrv Obsrv;
typedef Gaussian<State> Belief;
};
/**
* \ingroup linear_gaussian_filter
*
* \brief GaussianFilter resembles the Kalman filter.
*
* \tparam State State type defining the state space
* \tparam Input Process model input type
* \tparam Obsrv Observation type of the linear observation Gaussian model
*
* The KalmanFilter type is represented by the GaussianFilter using
* the linear Gaussian Models.
*
*/
template <
typename LinearStateTransitionModel,
typename LinearObservationModel
>
class GaussianFilter<
LinearStateTransitionModel,
LinearObservationModel>
:
/* Implement the conceptual filter interface */
public
FilterInterface<
GaussianFilter<
typename ForwardLinearModelOnly<LinearStateTransitionModel>::Type,
typename ForwardLinearModelOnly<LinearObservationModel>::Type>>
{
public:
typedef typename LinearStateTransitionModel::State State;
typedef typename LinearStateTransitionModel::Input Input;
typedef typename LinearObservationModel::Obsrv Obsrv;
/**
* \brief Represents the underlying distribution of the estimated state.
* In the case of the Kalman filter, the distribution is a simple Gaussian
* with the dimension of the \c State
*/
typedef Gaussian<State> Belief;
public:
/**
* Creates a linear Gaussian filter (a KalmanFilter)
*
* \param process_model Process model instance
* \param obsrv_model Obsrv model instance
*/
GaussianFilter(const LinearStateTransitionModel& process_model,
const LinearObservationModel& obsrv_model)
: process_model_(process_model),
obsrv_model_(obsrv_model)
{ }
/**
* \brief Overridable default destructor
*/
virtual ~GaussianFilter() { }
/**
* \copydoc FilterInterface::predict
*
* KalmanFilter prediction step
*
* Given the following matrices
*
* - \f$ A \f$: Dynamics Matrix
* - \f$ B \f$: Dynamics Noise Covariance
*
* and the current state distribution
* \f$ {\cal N}(x_t\mid \hat{x}_t, \hat{\Sigma}_{t}) \f$,
*
* the prediction steps is the discrete linear mapping
*
* \f$ \bar{x}_{t} = A \hat{x}_t\f$ and
*
* \f$ \bar{\Sigma}_{t} = A\hat{\Sigma}_{t}A^T + Q \f$
*/
virtual void predict(const Belief& prior_belief,
const Input& input,
Belief& predicted_belief)
{
auto A = process_model_.dynamics_matrix();
auto B = process_model_.input_matrix();
auto Q = process_model_.noise_covariance();
predicted_belief.mean(
A * prior_belief.mean() + B * input);
predicted_belief.covariance(
A * prior_belief.covariance() * A.transpose() + Q);
}
/**
* \copydoc FilterInterface::update
*
* Given the following matrices
*
* - \f$ H \f$: Sensor Matrix
* - \f$ R \f$: Sensor Noise Covariance
*
* and the current predicted state distribution
* \f$ {\cal N}(x_t\mid \bar{x}_t, \bar{\Sigma}_{t}) \f$,
*
* the update steps is the discrete linear mapping
*
* \f$ \hat{x}_{t+1} = \bar{x}_t + K (y - H\bar{x}_t)\f$ and
*
* \f$ \hat{\Sigma}_{t} = (I - KH) \bar{\Sigma}_{t}\f$
*
* with the KalmanGain
*
* \f$ K = \bar{\Sigma}_{t}H^T (H\bar{\Sigma}_{t}H^T+R)^{-1}\f$.
*/
virtual void update(const Belief& predicted_belief,
const Obsrv& y,
Belief& posterior_belief)
{
auto H = obsrv_model_.sensor_matrix();
auto R = obsrv_model_.noise_covariance();
auto mean = predicted_belief.mean();
auto cov_xx = predicted_belief.covariance();
auto S = (H * cov_xx * H.transpose() + R).eval();
auto K = (cov_xx * H.transpose() * S.inverse()).eval();
posterior_belief.mean(mean + K * (y - H * mean));
posterior_belief.covariance(cov_xx - K * H * cov_xx);
}
virtual Belief create_belief() const
{
auto belief = Belief(process_model().state_dimension());
return belief;
}
virtual std::string name() const
{
return "GaussianFilter<"
+ this->list_arguments(
process_model().name(),
obsrv_model().name())
+ ">";
}
virtual std::string description() const
{
return "Linear Gaussian filter (the Kalman Filter) with"
+ this->list_descriptions(
process_model().description(),
obsrv_model().description());
}
LinearStateTransitionModel& process_model() { return process_model_; }
LinearObservationModel& obsrv_model() { return obsrv_model_; }
const LinearStateTransitionModel& process_model() const { return process_model_; }
const LinearObservationModel& obsrv_model() const { return obsrv_model_; }
protected:
/** \cond internal */
LinearStateTransitionModel process_model_;
LinearObservationModel obsrv_model_;
/** \endcond */
};
}
#endif
<|endoftext|>
|
<commit_before>// Time: O(nlogn)
// Space: O(1)
class Solution {
public:
int minArea(vector<vector<char>>& image, int x, int y) {
const auto searchColumns =
[](const int mid, const vector<vector<char>>& image, bool has_one) {
return has_one == any_of(image.cbegin(), image.cend(),
[=](const vector<char>& row) { return row[mid] == '1'; });
};
const int left = binarySearch(image, 0, y - 1, searchColumns, true);
const int right = binarySearch(image, y + 1, int(image[0].size()) - 1, searchColumns, false);
const auto searchRows =
[](const int mid, const vector<vector<char>>& image, bool has_one) {
return has_one == any_of(image[mid].cbegin(), image[mid].cend(),
[](const char& col) { return col == '1'; });
};
const int top = binarySearch(image, 0, x - 1, searchRows, true);
const int bottom = binarySearch(image, x + 1, int(image.size()) - 1, searchRows, false);
return (right - left) * (bottom - top);
}
private:
int binarySearch(const vector<vector<char>>& image, int left, int right,
const function<bool(const int mid,
const vector<vector<char>>& image,
bool has_one)>& find,
bool has_one) {
while (left <= right) {
const int mid = left + (right - left) / 2;
if (find(mid, image, has_one)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
};
<commit_msg>Update smallest-rectangle-enclosing-black-pixels.cpp<commit_after>// Time: O(nlogn)
// Space: O(1)
class Solution {
public:
int minArea(vector<vector<char>>& image, int x, int y) {
const auto searchColumns =
[](const int mid, const vector<vector<char>>& image, bool has_one) {
return has_one == any_of(image.cbegin(), image.cend(),
[=](const vector<char>& row) { return row[mid] == '1'; });
};
const int left = binarySearch(image, 0, y - 1, searchColumns, true);
const int right = binarySearch(image, y + 1, int(image[0].size()) - 1, searchColumns, false);
const auto searchRows =
[](const int mid, const vector<vector<char>>& image, bool has_one) {
return has_one == any_of(image[mid].cbegin(), image[mid].cend(),
[](const char& col) { return col == '1'; });
};
const int top = binarySearch(image, 0, x - 1, searchRows, true);
const int bottom = binarySearch(image, x + 1, int(image.size()) - 1, searchRows, false);
return (right - left) * (bottom - top);
}
private:
int binarySearch(const vector<vector<char>>& image, int left, int right,
const function<bool(const int mid,
const vector<vector<char>>& image,
bool has_one)>& find,
bool has_one) {
while (left <= right) {
const int mid = left + (right - left) / 2;
if (find(mid, image, has_one)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
};
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (c) 2013 Jan Rheinländer *
* <jrheinlaender@users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Inventor/nodes/SoSeparator.h>
# include <Inventor/nodes/SoCoordinate3.h>
#endif
#include <Mod/Part/Gui/SoBrepFaceSet.h>
#include <Mod/Part/Gui/SoBrepEdgeSet.h>
#include <Mod/PartDesign/App/DatumPlane.h>
#include "ViewProviderDatumPlane.h"
using namespace PartDesignGui;
PROPERTY_SOURCE(PartDesignGui::ViewProviderDatumPlane,PartDesignGui::ViewProviderDatum)
ViewProviderDatumPlane::ViewProviderDatumPlane()
{
sPixmap = "PartDesign_Plane.svg";
pCoords = new SoCoordinate3();
pCoords->ref ();
}
ViewProviderDatumPlane::~ViewProviderDatumPlane()
{
pCoords->unref ();
}
void ViewProviderDatumPlane::attach ( App::DocumentObject *obj ) {
ViewProviderDatum::attach ( obj );
ViewProviderDatum::setExtents ( defaultBoundBox () );
getShapeRoot ()->addChild(pCoords);
PartGui::SoBrepEdgeSet* lineSet = new PartGui::SoBrepEdgeSet();
lineSet->coordIndex.setNum(6);
lineSet->coordIndex.set1Value(0, 0);
lineSet->coordIndex.set1Value(1, 1);
lineSet->coordIndex.set1Value(2, 2);
lineSet->coordIndex.set1Value(3, 3);
lineSet->coordIndex.set1Value(4, 0);
lineSet->coordIndex.set1Value(5, SO_END_LINE_INDEX);
getShapeRoot ()->addChild(lineSet);
PartGui::SoBrepFaceSet *faceSet = new PartGui::SoBrepFaceSet();
// SoBrepFaceSet supports only triangles (otherwise we receive incorrect highlighting)
faceSet->partIndex.set1Value(0, 2); // One face, two triangles
faceSet->coordIndex.setNum(8);
// first triangle
faceSet->coordIndex.set1Value(0, 0);
faceSet->coordIndex.set1Value(1, 1);
faceSet->coordIndex.set1Value(2, 2);
faceSet->coordIndex.set1Value(3, SO_END_FACE_INDEX);
// second triangle
faceSet->coordIndex.set1Value(4, 2);
faceSet->coordIndex.set1Value(5, 3);
faceSet->coordIndex.set1Value(6, 0);
faceSet->coordIndex.set1Value(7, SO_END_FACE_INDEX);
getShapeRoot ()->addChild(faceSet);
}
void ViewProviderDatumPlane::updateData(const App::Property* prop)
{
// Gets called whenever a property of the attached object changes
if (strcmp(prop->getName(),"Placement") == 0) {
updateExtents ();
}
else if (strcmp(prop->getName(),"Length") == 0 ||
strcmp(prop->getName(),"Width") == 0) {
PartDesign::Plane* pcDatum = static_cast<PartDesign::Plane*>(this->getObject());
if (pcDatum->ResizeMode.getValue() != 0)
setExtents(pcDatum->Length.getValue(), pcDatum->Width.getValue());
}
ViewProviderDatum::updateData(prop);
}
void ViewProviderDatumPlane::setExtents (Base::BoundBox3d bbox) {
PartDesign::Plane* pcDatum = static_cast<PartDesign::Plane*>(this->getObject());
if (pcDatum->ResizeMode.getValue() != 0) {
setExtents(pcDatum->Length.getValue(), pcDatum->Width.getValue());
return;
}
Base::Placement plm = pcDatum->Placement.getValue ().inverse ();
// Transform the box to the line's coordinates, the result line will be larger than the bbox
bbox = bbox.Transformed ( plm.toMatrix() );
// Add origin of the plane to the box if it's not
bbox.Add ( Base::Vector3d (0, 0, 0) );
double margin = sqrt(bbox.LengthX ()*bbox.LengthY ()) * marginFactor ();
pcDatum->Length.setValue(bbox.LengthX() + 2*margin);
pcDatum->Width.setValue(bbox.LengthY() + 2*margin);
// Change the coordinates of the line
pCoords->point.setNum (4);
pCoords->point.set1Value(0, bbox.MaxX + margin, bbox.MaxY + margin, 0 );
pCoords->point.set1Value(1, bbox.MinX - margin, bbox.MaxY + margin, 0 );
pCoords->point.set1Value(2, bbox.MinX - margin, bbox.MinY - margin, 0 );
pCoords->point.set1Value(3, bbox.MaxX + margin, bbox.MinY - margin, 0 );
}
void ViewProviderDatumPlane::setExtents(double l, double w)
{
// Change the coordinates of the line
pCoords->point.setNum (4);
pCoords->point.set1Value(0, l, w, 0);
pCoords->point.set1Value(1, 0, w, 0);
pCoords->point.set1Value(2, 0, 0, 0);
pCoords->point.set1Value(3, l, 0, 0);
}
<commit_msg>Manual dimension centers the plane's view<commit_after>/***************************************************************************
* Copyright (c) 2013 Jan Rheinländer *
* <jrheinlaender@users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Inventor/nodes/SoSeparator.h>
# include <Inventor/nodes/SoCoordinate3.h>
#endif
#include <Mod/Part/Gui/SoBrepFaceSet.h>
#include <Mod/Part/Gui/SoBrepEdgeSet.h>
#include <Mod/PartDesign/App/DatumPlane.h>
#include "ViewProviderDatumPlane.h"
using namespace PartDesignGui;
PROPERTY_SOURCE(PartDesignGui::ViewProviderDatumPlane,PartDesignGui::ViewProviderDatum)
ViewProviderDatumPlane::ViewProviderDatumPlane()
{
sPixmap = "PartDesign_Plane.svg";
pCoords = new SoCoordinate3();
pCoords->ref ();
}
ViewProviderDatumPlane::~ViewProviderDatumPlane()
{
pCoords->unref ();
}
void ViewProviderDatumPlane::attach ( App::DocumentObject *obj ) {
ViewProviderDatum::attach ( obj );
ViewProviderDatum::setExtents ( defaultBoundBox () );
getShapeRoot ()->addChild(pCoords);
PartGui::SoBrepEdgeSet* lineSet = new PartGui::SoBrepEdgeSet();
lineSet->coordIndex.setNum(6);
lineSet->coordIndex.set1Value(0, 0);
lineSet->coordIndex.set1Value(1, 1);
lineSet->coordIndex.set1Value(2, 2);
lineSet->coordIndex.set1Value(3, 3);
lineSet->coordIndex.set1Value(4, 0);
lineSet->coordIndex.set1Value(5, SO_END_LINE_INDEX);
getShapeRoot ()->addChild(lineSet);
PartGui::SoBrepFaceSet *faceSet = new PartGui::SoBrepFaceSet();
// SoBrepFaceSet supports only triangles (otherwise we receive incorrect highlighting)
faceSet->partIndex.set1Value(0, 2); // One face, two triangles
faceSet->coordIndex.setNum(8);
// first triangle
faceSet->coordIndex.set1Value(0, 0);
faceSet->coordIndex.set1Value(1, 1);
faceSet->coordIndex.set1Value(2, 2);
faceSet->coordIndex.set1Value(3, SO_END_FACE_INDEX);
// second triangle
faceSet->coordIndex.set1Value(4, 2);
faceSet->coordIndex.set1Value(5, 3);
faceSet->coordIndex.set1Value(6, 0);
faceSet->coordIndex.set1Value(7, SO_END_FACE_INDEX);
getShapeRoot ()->addChild(faceSet);
}
void ViewProviderDatumPlane::updateData(const App::Property* prop)
{
// Gets called whenever a property of the attached object changes
if (strcmp(prop->getName(),"Placement") == 0) {
updateExtents ();
}
else if (strcmp(prop->getName(),"Length") == 0 ||
strcmp(prop->getName(),"Width") == 0) {
PartDesign::Plane* pcDatum = static_cast<PartDesign::Plane*>(this->getObject());
if (pcDatum->ResizeMode.getValue() != 0)
setExtents(pcDatum->Length.getValue(), pcDatum->Width.getValue());
}
ViewProviderDatum::updateData(prop);
}
void ViewProviderDatumPlane::setExtents (Base::BoundBox3d bbox) {
PartDesign::Plane* pcDatum = static_cast<PartDesign::Plane*>(this->getObject());
if (pcDatum->ResizeMode.getValue() != 0) {
setExtents(pcDatum->Length.getValue(), pcDatum->Width.getValue());
return;
}
Base::Placement plm = pcDatum->Placement.getValue ().inverse ();
// Transform the box to the line's coordinates, the result line will be larger than the bbox
bbox = bbox.Transformed ( plm.toMatrix() );
// Add origin of the plane to the box if it's not
bbox.Add ( Base::Vector3d (0, 0, 0) );
double margin = sqrt(bbox.LengthX ()*bbox.LengthY ()) * marginFactor ();
pcDatum->Length.setValue(bbox.LengthX() + 2*margin);
pcDatum->Width.setValue(bbox.LengthY() + 2*margin);
// Change the coordinates of the line
pCoords->point.setNum (4);
pCoords->point.set1Value(0, bbox.MaxX + margin, bbox.MaxY + margin, 0 );
pCoords->point.set1Value(1, bbox.MinX - margin, bbox.MaxY + margin, 0 );
pCoords->point.set1Value(2, bbox.MinX - margin, bbox.MinY - margin, 0 );
pCoords->point.set1Value(3, bbox.MaxX + margin, bbox.MinY - margin, 0 );
}
void ViewProviderDatumPlane::setExtents(double l, double w)
{
// Change the coordinates of the line
pCoords->point.setNum (4);
pCoords->point.set1Value(0, l/2, w/2, 0);
pCoords->point.set1Value(1, -l/2, w/2, 0);
pCoords->point.set1Value(2, -l/2, -w/2, 0);
pCoords->point.set1Value(3, l/2, -w/2, 0);
}
<|endoftext|>
|
<commit_before>#ifndef VIENNAMETA_STORAGE_ALGORITHM_HPP
#define VIENNAMETA_STORAGE_ALGORITHM_HPP
/* =======================================================================
Copyright (c) 2011-2014, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include "viennagrid/storage/collection.hpp"
#include "viennagrid/storage/container_collection.hpp"
#include "viennagrid/storage/view.hpp"
#include "viennagrid/meta/algorithm.hpp"
/** @file viennagrid/storage/algorithm.hpp
@brief Provides STL-like algorithms for manipulating containers in ViennaGrid.
*/
namespace viennagrid
{
namespace detail
{
template<typename collection_type, typename functor>
struct for_each_functor
{
for_each_functor(collection_type & collection, functor f) : collection_(collection), f_(f) {}
template<typename key_type, typename value_type>
void operator()( viennagrid::detail::tag< viennagrid::static_pair<key_type, value_type> > )
{ f_( viennagrid::get<key_type>(collection_) ); }
collection_type & collection_;
functor f_;
};
template<typename collection_type, typename functor>
void for_each( collection_type & collection, functor f)
{
for_each_functor<collection_type, functor> ff(collection, f);
viennagrid::detail::for_each< typename collection_type::typemap >(ff);
}
template<typename typelist, typename collection_type, typename functor>
void for_each_typelist(collection_type & collection, functor & f)
{
for_each_functor<collection_type, functor> ff(collection, f);
viennagrid::detail::for_each<typelist>(ff);
}
template<typename collection_type_1, typename collection_type_2, typename functor>
class dual_for_each_functor
{
public:
dual_for_each_functor(
collection_type_1 & container_collection_1,
collection_type_2 & container_collection_2,
functor f) :
container_collection_1_(container_collection_1),
container_collection_2_(container_collection_2),
f_(f) {}
template<typename type>
void operator() ( viennagrid::detail::tag<type> )
{
f_(
viennagrid::get<type>(container_collection_1_),
viennagrid::get<type>(container_collection_2_)
);
}
private:
collection_type_1 & container_collection_1_;
collection_type_2 & container_collection_2_;
functor f_;
};
template<typename predicate>
class copy_functor
{
public:
copy_functor(predicate pred) : pred_(pred) {}
template<typename src_container_type, typename dst_container_type>
void operator() (const src_container_type & src_container, dst_container_type & dst_container)
{
for (typename src_container_type::const_iterator it = src_container.begin(); it != src_container.end(); ++it)
if (pred_(*it))
dst_container.insert( *it );
}
private:
predicate pred_;
};
template<typename src_container_typelist, typename dst_container_typelist>
void copy(const collection<src_container_typelist> & src, collection<dst_container_typelist> & dst)
{
detail::dual_for_each_functor<
const collection<src_container_typelist>,
collection<dst_container_typelist>,
copy_functor<viennagrid::detail::true_predicate>
> functor(src, dst, copy_functor<viennagrid::detail::true_predicate>(viennagrid::detail::true_predicate()));
typedef typename viennagrid::result_of::common_values<
collection<src_container_typelist>,
collection<dst_container_typelist>
>::type typelist;
viennagrid::detail::for_each<typelist>(functor);
}
template<typename src_container_typelist, typename dst_container_typelist, typename predicate>
void copy_if(const collection<src_container_typelist> & src, collection<dst_container_typelist> & dst, predicate pred)
{
detail::dual_for_each_functor<
const collection<src_container_typelist>,
collection<dst_container_typelist>,
copy_functor<predicate>
> functor(src, dst, copy_functor<predicate>(pred));
typedef typename viennagrid::result_of::common_values<
collection<src_container_typelist>,
collection<dst_container_typelist>
>::type typelist;
viennagrid::detail::for_each<typelist>(functor);
}
template<typename predicate>
class handle_functor
{
public:
handle_functor(predicate pred) : pred_(pred) {}
template<typename container_type, typename base_container_type, typename handle_container_tag>
void operator() (container_type & src_container, viennagrid::view<base_container_type, handle_container_tag> & dst_view)
{
for (typename container_type::iterator it = src_container.begin(); it != src_container.end(); ++it)
if (pred_( *it ))
dst_view.insert_handle( it.handle() );
}
private:
predicate pred_;
};
template<typename src_container_typelist, typename dst_container_typelist>
void handle(collection<src_container_typelist> & src, collection<dst_container_typelist> & dst)
{
detail::dual_for_each_functor<
collection<src_container_typelist>,
collection<dst_container_typelist>,
handle_functor<viennagrid::detail::true_predicate>
> functor(src, dst, handle_functor<viennagrid::detail::true_predicate>(viennagrid::detail::true_predicate()));
typedef typename viennagrid::result_of::common_values<
collection<src_container_typelist>,
collection<dst_container_typelist>
>::type typelist;
viennagrid::detail::for_each<typelist>(functor);
}
template<typename src_container_typelist, typename dst_container_typelist, typename predicate>
void handle_if(collection<src_container_typelist> & src, collection<dst_container_typelist> & dst, predicate pred)
{
detail::dual_for_each_functor<
collection<src_container_typelist>,
collection<dst_container_typelist>,
handle_functor<predicate>
> functor(src, dst, handle_functor<predicate>(pred));
typedef typename viennagrid::result_of::common_values<
collection<src_container_typelist>,
collection<dst_container_typelist>
>::type typelist;
viennagrid::detail::for_each<typelist>(functor);
}
}
}
#endif
<commit_msg>storage/algorithm: Fixed include guard.<commit_after>#ifndef VIENNAGRID_STORAGE_ALGORITHM_HPP
#define VIENNAGRID_STORAGE_ALGORITHM_HPP
/* =======================================================================
Copyright (c) 2011-2014, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include "viennagrid/storage/collection.hpp"
#include "viennagrid/storage/container_collection.hpp"
#include "viennagrid/storage/view.hpp"
#include "viennagrid/meta/algorithm.hpp"
/** @file viennagrid/storage/algorithm.hpp
@brief Provides STL-like algorithms for manipulating containers in ViennaGrid.
*/
namespace viennagrid
{
namespace detail
{
template<typename collection_type, typename functor>
struct for_each_functor
{
for_each_functor(collection_type & collection, functor f) : collection_(collection), f_(f) {}
template<typename key_type, typename value_type>
void operator()( viennagrid::detail::tag< viennagrid::static_pair<key_type, value_type> > )
{ f_( viennagrid::get<key_type>(collection_) ); }
collection_type & collection_;
functor f_;
};
template<typename collection_type, typename functor>
void for_each( collection_type & collection, functor f)
{
for_each_functor<collection_type, functor> ff(collection, f);
viennagrid::detail::for_each< typename collection_type::typemap >(ff);
}
template<typename typelist, typename collection_type, typename functor>
void for_each_typelist(collection_type & collection, functor & f)
{
for_each_functor<collection_type, functor> ff(collection, f);
viennagrid::detail::for_each<typelist>(ff);
}
template<typename collection_type_1, typename collection_type_2, typename functor>
class dual_for_each_functor
{
public:
dual_for_each_functor(
collection_type_1 & container_collection_1,
collection_type_2 & container_collection_2,
functor f) :
container_collection_1_(container_collection_1),
container_collection_2_(container_collection_2),
f_(f) {}
template<typename type>
void operator() ( viennagrid::detail::tag<type> )
{
f_(
viennagrid::get<type>(container_collection_1_),
viennagrid::get<type>(container_collection_2_)
);
}
private:
collection_type_1 & container_collection_1_;
collection_type_2 & container_collection_2_;
functor f_;
};
template<typename predicate>
class copy_functor
{
public:
copy_functor(predicate pred) : pred_(pred) {}
template<typename src_container_type, typename dst_container_type>
void operator() (const src_container_type & src_container, dst_container_type & dst_container)
{
for (typename src_container_type::const_iterator it = src_container.begin(); it != src_container.end(); ++it)
if (pred_(*it))
dst_container.insert( *it );
}
private:
predicate pred_;
};
template<typename src_container_typelist, typename dst_container_typelist>
void copy(const collection<src_container_typelist> & src, collection<dst_container_typelist> & dst)
{
detail::dual_for_each_functor<
const collection<src_container_typelist>,
collection<dst_container_typelist>,
copy_functor<viennagrid::detail::true_predicate>
> functor(src, dst, copy_functor<viennagrid::detail::true_predicate>(viennagrid::detail::true_predicate()));
typedef typename viennagrid::result_of::common_values<
collection<src_container_typelist>,
collection<dst_container_typelist>
>::type typelist;
viennagrid::detail::for_each<typelist>(functor);
}
template<typename src_container_typelist, typename dst_container_typelist, typename predicate>
void copy_if(const collection<src_container_typelist> & src, collection<dst_container_typelist> & dst, predicate pred)
{
detail::dual_for_each_functor<
const collection<src_container_typelist>,
collection<dst_container_typelist>,
copy_functor<predicate>
> functor(src, dst, copy_functor<predicate>(pred));
typedef typename viennagrid::result_of::common_values<
collection<src_container_typelist>,
collection<dst_container_typelist>
>::type typelist;
viennagrid::detail::for_each<typelist>(functor);
}
template<typename predicate>
class handle_functor
{
public:
handle_functor(predicate pred) : pred_(pred) {}
template<typename container_type, typename base_container_type, typename handle_container_tag>
void operator() (container_type & src_container, viennagrid::view<base_container_type, handle_container_tag> & dst_view)
{
for (typename container_type::iterator it = src_container.begin(); it != src_container.end(); ++it)
if (pred_( *it ))
dst_view.insert_handle( it.handle() );
}
private:
predicate pred_;
};
template<typename src_container_typelist, typename dst_container_typelist>
void handle(collection<src_container_typelist> & src, collection<dst_container_typelist> & dst)
{
detail::dual_for_each_functor<
collection<src_container_typelist>,
collection<dst_container_typelist>,
handle_functor<viennagrid::detail::true_predicate>
> functor(src, dst, handle_functor<viennagrid::detail::true_predicate>(viennagrid::detail::true_predicate()));
typedef typename viennagrid::result_of::common_values<
collection<src_container_typelist>,
collection<dst_container_typelist>
>::type typelist;
viennagrid::detail::for_each<typelist>(functor);
}
template<typename src_container_typelist, typename dst_container_typelist, typename predicate>
void handle_if(collection<src_container_typelist> & src, collection<dst_container_typelist> & dst, predicate pred)
{
detail::dual_for_each_functor<
collection<src_container_typelist>,
collection<dst_container_typelist>,
handle_functor<predicate>
> functor(src, dst, handle_functor<predicate>(pred));
typedef typename viennagrid::result_of::common_values<
collection<src_container_typelist>,
collection<dst_container_typelist>
>::type typelist;
viennagrid::detail::for_each<typelist>(functor);
}
}
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright 2011, 2012 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// A test harness for the implementation report of
// the CSS2.1 Conformance Test Suite
// http://test.csswg.org/suites/css2.1/20110323/
#include <unistd.h>
#include <sys/wait.h>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <boost/version.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
enum {
INTERACTIVE = 0,
HEADLESS,
REPORT,
UPDATE,
// exit status codes
ES_PASS = 0,
ES_FATAL,
ES_FAIL,
ES_INVALID,
ES_NA,
ES_SKIP,
ES_UNCERTAIN
};
const char* StatusStrings[] = {
"pass",
"fatal",
"fail",
"invalid",
"?",
"skip",
"uncertain",
};
struct ForkStatus {
pid_t pid;
std::string url;
int code;
public:
ForkStatus() : pid(-1), code(0) {}
};
size_t forkMax = 1;
size_t forkCount = 0;
std::vector<ForkStatus> forkStates(1);
int processOutput(std::istream& stream, std::string& result)
{
std::string output;
bool completed = false;
while (std::getline(stream, output)) {
if (!completed) {
if (output == "## complete")
completed = true;
continue;
}
if (output == "##")
break;
result += output + '\n';
}
return 0;
}
int runTest(int argc, char* argv[], std::string userStyle, std::string testFonts, std::string url, std::string& result, unsigned timeout)
{
int pipefd[2];
pipe(pipefd);
pid_t pid = fork();
if (pid == -1) {
std::cerr << "error: no more process to create\n";
return -1;
}
if (pid == 0) {
close(1);
dup(pipefd[1]);
close(pipefd[0]);
int argi = argc - 1;
if (!userStyle.empty())
argv[argi++] = strdup(userStyle.c_str());
if (testFonts == "on")
argv[argi++] ="-testfonts";
url = "http://localhost:8000/" + url;
// url = "http://test.csswg.org/suites/css2.1/20110323/" + url;
argv[argi++] = strdup(url.c_str());
argv[argi] = 0;
if (timeout)
alarm(timeout); // Terminate the process if it does not complete in 'timeout' seconds.
execvp(argv[0], argv);
exit(EXIT_FAILURE);
}
close(pipefd[1]);
#if 104400 <= BOOST_VERSION
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], boost::iostreams::close_handle);
#else
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], true);
#endif
processOutput(stream, result);
return pid;
}
void killTest(int pid)
{
int status;
kill(pid, SIGTERM);
if (wait(&status) == -1)
std::cerr << "error: failed to wait for a test process to complete\n";
}
bool loadLog(const std::string& path, std::string& result, std::string& log)
{
std::ifstream file(path.c_str());
if (!file) {
result = "?";
return false;
}
std::string line;
std::getline(file, line);
size_t pos = line.find('\t');
if (pos != std::string::npos)
result = line.substr(pos + 1);
else {
result = "?";
return false;
}
log.clear();
while (std::getline(file, line))
log += line + '\n';
return true;
}
bool saveLog(const std::string& path, const std::string& url, const std::string& result, const std::string& log)
{
std::ofstream file(path.c_str(), std::ios_base::out | std::ios_base::trunc);
if (!file) {
std::cerr << "error: failed to open the report file\n";
return false;
}
file << "# " << url.c_str() << '\t' << result << '\n' << log;
file.flush();
file.close();
return true;
}
std::string test(int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout)
{
std::string path(url);
size_t pos = path.rfind('.');
if (pos != std::string::npos) {
path.erase(pos);
path += ".log";
}
std::string evaluation;
std::string log;
loadLog(path, evaluation, log);
pid_t pid = -1;
std::string output;
switch (mode) {
case REPORT:
break;
case UPDATE:
if (evaluation[0] == '?')
break;
// FALL THROUGH
default:
pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout);
break;
}
std::string result;
if (0 < pid && output.empty())
result = "fatal";
else if (mode == INTERACTIVE) {
std::cout << "## complete\n" << output;
std::cout << '[' << url << "] ";
if (evaluation.empty() || evaluation[0] == '?')
std::cout << "pass? ";
else {
std::cout << evaluation << "? ";
if (evaluation != "pass")
std::cout << '\a';
}
std::getline(std::cin, result);
if (result.empty()) {
if (evaluation.empty() || evaluation[0] == '?')
result = "pass";
else
result = evaluation;
} else if (result == "p" || result == "\x1b")
result = "pass";
else if (result == "f")
result = "fail";
else if (result == "i")
result = "invalid";
else if (result == "k") // keep
result = evaluation;
else if (result == "n")
result = "na";
else if (result == "s")
result = "skip";
else if (result == "u")
result = "uncertain";
else if (result == "q" || result == "quit")
exit(EXIT_FAILURE);
else if (result == "z")
result = "undo";
if (result != "undo" && !saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
} else if (mode == HEADLESS) {
if (evaluation != "?" && output != log)
result = "uncertain";
else
result = evaluation;
} else if (mode == REPORT) {
result = evaluation;
} else if (mode == UPDATE) {
result = evaluation;
if (result[0] != '?') {
if (!saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
}
}
if (0 < pid)
killTest(pid);
if (mode != INTERACTIVE && result[0] != '?')
std::cout << url << '\t' << result << '\n';
return result;
}
void reduce(std::ostream& report)
{
for (int i = 0; i < forkCount; ++i) {
int status;
pid_t pid = wait(&status);
for (int j = 0; j < forkCount; ++j) {
if (forkStates[j].pid == pid) {
forkStates[j].pid = -1;
forkStates[j].code = WIFEXITED(status) ? WEXITSTATUS(status) : ES_FATAL;
break;
}
}
}
for (int i = 0; i < forkCount; ++i) {
if (forkStates[i].code != ES_NA)
std::cout << forkStates[i].url << '\t' << StatusStrings[forkStates[i].code] << '\n';
report << forkStates[i].url << '\t' << StatusStrings[forkStates[i].code] << '\n';
}
forkCount = 0;
}
void map(std::ostream& report, int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout)
{
pid_t pid = fork();
if (pid == -1) {
std::cerr << "error: no more process to create\n";
exit(EXIT_FAILURE);
}
if (pid == 0) {
std::string path(url);
size_t pos = path.rfind('.');
if (pos != std::string::npos) {
path.erase(pos);
path += ".log";
}
std::string evaluation;
std::string log;
loadLog(path, evaluation, log);
pid_t pid = -1;
std::string output;
switch (mode) {
case UPDATE:
if (evaluation[0] == '?')
break;
// FALL THROUGH
default:
pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout);
break;
}
std::string result;
if (0 < pid && output.empty())
result = "fatal";
else if (mode == HEADLESS) {
if (evaluation != "?" && output != log)
result = "uncertain";
else
result = evaluation;
} else if (mode == UPDATE) {
result = evaluation;
if (result[0] != '?') {
if (!saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
}
}
if (0 < pid)
killTest(pid);
int status = ES_NA;
if (!result.compare(0, 4, "pass"))
status = ES_PASS;
else if (!result.compare(0, 5, "fatal"))
status = ES_FATAL;
else if (!result.compare(0, 4, "fail"))
status = ES_FAIL;
else if (!result.compare(0, 7, "invalid"))
status = ES_INVALID;
else if (!result.compare(0, 4, "skip"))
status = ES_SKIP;
else if (!result.compare(0, 9, "uncertain"))
status = ES_UNCERTAIN;
exit(status);
} else {
forkStates[forkCount].url = url;
forkStates[forkCount].pid = pid;
}
if (++forkCount == forkMax)
reduce(report);
}
int main(int argc, char* argv[])
{
int mode = HEADLESS;
unsigned timeout = 10;
int argi = 1;
while (*argv[argi] == '-') {
switch (argv[argi][1]) {
case 'i':
mode = INTERACTIVE;
timeout = 0;
break;
case 'r':
mode = REPORT;
break;
case 'u':
mode = UPDATE;
break;
case 'j':
forkMax = strtoul(argv[argi] + 2, 0, 10);
if (forkMax == 0)
forkMax = 1;
forkStates.resize(forkMax);
break;
default:
break;
}
++argi;
}
if (argc < argi + 2) {
std::cout << "usage: " << argv[0] << " [-i] report.data command [argument ...]\n";
return EXIT_FAILURE;
}
std::ifstream data(argv[argi]);
if (!data) {
std::cerr << "error: " << argv[argi] << ": no such file\n";
return EXIT_FAILURE;
}
std::ofstream report("report.data", std::ios_base::out | std::ios_base::trunc);
if (!report) {
std::cerr << "error: failed to open the report file\n";
return EXIT_FAILURE;
}
char* args[argc - argi + 3];
for (int i = 2; i < argc; ++i)
args[i - 2] = argv[i + argi - 1];
args[argc - argi] = args[argc - argi + 1] = args[argc - argi + 2] = 0;
std::string result;
std::string url;
std::string undo;
std::string userStyle;
std::string testFonts;
bool redo = false;
while (data) {
if (result == "undo") {
std::swap(url, undo);
redo = true;
} else if (redo) {
std::swap(url, undo);
redo = false;
} else {
std::string line;
std::getline(data, line);
if (line.empty())
continue;
if (line == "testname result comment") {
report << line << '\n';
continue;
}
if (line[0] == '#') {
if (line.compare(1, 9, "userstyle") == 0) {
if (10 < line.length()) {
std::stringstream s(line.substr(10), std::stringstream::in);
s >> userStyle;
} else
userStyle.clear();
} else if (line.compare(1, 9, "testfonts") == 0) {
if (10 < line.length()) {
std::stringstream s(line.substr(10), std::stringstream::in);
s >> testFonts;
} else
testFonts.clear();
}
reduce(report);
report << line << '\n';
continue;
}
undo = url;
std::stringstream s(line, std::stringstream::in);
s >> url;
}
if (url.empty())
continue;
switch (mode) {
case HEADLESS:
case UPDATE:
map(report, mode, argc - argi, args, url, userStyle, testFonts, timeout);
break;
default:
result = test(mode, argc - argi, args, url, userStyle, testFonts, timeout);
if (result != "undo")
report << url << '\t' << result << '\n';
break;
}
}
if (mode == HEADLESS || mode == UPDATE)
reduce(report);
report.close();
}
<commit_msg>(harness) : Set the exit code to EXIT_SUCCESS when there's no changes, and EXIT_FAILURE otherwise in the headless and update mode.<commit_after>/*
* Copyright 2011, 2012 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// A test harness for the implementation report of
// the CSS2.1 Conformance Test Suite
// http://test.csswg.org/suites/css2.1/20110323/
#include <unistd.h>
#include <sys/wait.h>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <boost/version.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
enum {
INTERACTIVE = 0,
HEADLESS,
REPORT,
UPDATE,
// exit status codes
ES_PASS = 0,
ES_FATAL,
ES_FAIL,
ES_INVALID,
ES_NA,
ES_SKIP,
ES_UNCERTAIN
};
const char* StatusStrings[] = {
"pass",
"fatal",
"fail",
"invalid",
"?",
"skip",
"uncertain",
};
struct ForkStatus {
pid_t pid;
std::string url;
int code;
public:
ForkStatus() : pid(-1), code(0) {}
};
size_t forkMax = 1;
size_t forkCount = 0;
std::vector<ForkStatus> forkStates(1);
size_t uncertainCount = 0;
int processOutput(std::istream& stream, std::string& result)
{
std::string output;
bool completed = false;
while (std::getline(stream, output)) {
if (!completed) {
if (output == "## complete")
completed = true;
continue;
}
if (output == "##")
break;
result += output + '\n';
}
return 0;
}
int runTest(int argc, char* argv[], std::string userStyle, std::string testFonts, std::string url, std::string& result, unsigned timeout)
{
int pipefd[2];
pipe(pipefd);
pid_t pid = fork();
if (pid == -1) {
std::cerr << "error: no more process to create\n";
return -1;
}
if (pid == 0) {
close(1);
dup(pipefd[1]);
close(pipefd[0]);
int argi = argc - 1;
if (!userStyle.empty())
argv[argi++] = strdup(userStyle.c_str());
if (testFonts == "on")
argv[argi++] ="-testfonts";
url = "http://localhost:8000/" + url;
// url = "http://test.csswg.org/suites/css2.1/20110323/" + url;
argv[argi++] = strdup(url.c_str());
argv[argi] = 0;
if (timeout)
alarm(timeout); // Terminate the process if it does not complete in 'timeout' seconds.
execvp(argv[0], argv);
exit(EXIT_FAILURE);
}
close(pipefd[1]);
#if 104400 <= BOOST_VERSION
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], boost::iostreams::close_handle);
#else
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], true);
#endif
processOutput(stream, result);
return pid;
}
void killTest(int pid)
{
int status;
kill(pid, SIGTERM);
if (wait(&status) == -1)
std::cerr << "error: failed to wait for a test process to complete\n";
}
bool loadLog(const std::string& path, std::string& result, std::string& log)
{
std::ifstream file(path.c_str());
if (!file) {
result = "?";
return false;
}
std::string line;
std::getline(file, line);
size_t pos = line.find('\t');
if (pos != std::string::npos)
result = line.substr(pos + 1);
else {
result = "?";
return false;
}
log.clear();
while (std::getline(file, line))
log += line + '\n';
return true;
}
bool saveLog(const std::string& path, const std::string& url, const std::string& result, const std::string& log)
{
std::ofstream file(path.c_str(), std::ios_base::out | std::ios_base::trunc);
if (!file) {
std::cerr << "error: failed to open the report file\n";
return false;
}
file << "# " << url.c_str() << '\t' << result << '\n' << log;
file.flush();
file.close();
return true;
}
std::string test(int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout)
{
std::string path(url);
size_t pos = path.rfind('.');
if (pos != std::string::npos) {
path.erase(pos);
path += ".log";
}
std::string evaluation;
std::string log;
loadLog(path, evaluation, log);
pid_t pid = -1;
std::string output;
switch (mode) {
case REPORT:
break;
case UPDATE:
if (evaluation[0] == '?')
break;
// FALL THROUGH
default:
pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout);
break;
}
std::string result;
if (0 < pid && output.empty())
result = "fatal";
else if (mode == INTERACTIVE) {
std::cout << "## complete\n" << output;
std::cout << '[' << url << "] ";
if (evaluation.empty() || evaluation[0] == '?')
std::cout << "pass? ";
else {
std::cout << evaluation << "? ";
if (evaluation != "pass")
std::cout << '\a';
}
std::getline(std::cin, result);
if (result.empty()) {
if (evaluation.empty() || evaluation[0] == '?')
result = "pass";
else
result = evaluation;
} else if (result == "p" || result == "\x1b")
result = "pass";
else if (result == "f")
result = "fail";
else if (result == "i")
result = "invalid";
else if (result == "k") // keep
result = evaluation;
else if (result == "n")
result = "na";
else if (result == "s")
result = "skip";
else if (result == "u")
result = "uncertain";
else if (result == "q" || result == "quit")
exit(EXIT_FAILURE);
else if (result == "z")
result = "undo";
if (result != "undo" && !saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
} else if (mode == HEADLESS) {
if (evaluation != "?" && output != log)
result = "uncertain";
else
result = evaluation;
} else if (mode == REPORT) {
result = evaluation;
} else if (mode == UPDATE) {
result = evaluation;
if (result[0] != '?') {
if (!saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
}
}
if (0 < pid)
killTest(pid);
if (mode != INTERACTIVE && result[0] != '?')
std::cout << url << '\t' << result << '\n';
return result;
}
void reduce(std::ostream& report)
{
for (int i = 0; i < forkCount; ++i) {
int status;
pid_t pid = wait(&status);
for (int j = 0; j < forkCount; ++j) {
if (forkStates[j].pid == pid) {
forkStates[j].pid = -1;
forkStates[j].code = WIFEXITED(status) ? WEXITSTATUS(status) : ES_FATAL;
break;
}
}
}
for (int i = 0; i < forkCount; ++i) {
if (forkStates[i].code == ES_UNCERTAIN)
++uncertainCount;
if (forkStates[i].code != ES_NA)
std::cout << forkStates[i].url << '\t' << StatusStrings[forkStates[i].code] << '\n';
report << forkStates[i].url << '\t' << StatusStrings[forkStates[i].code] << '\n';
}
forkCount = 0;
}
void map(std::ostream& report, int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout)
{
pid_t pid = fork();
if (pid == -1) {
std::cerr << "error: no more process to create\n";
exit(EXIT_FAILURE);
}
if (pid == 0) {
std::string path(url);
size_t pos = path.rfind('.');
if (pos != std::string::npos) {
path.erase(pos);
path += ".log";
}
std::string evaluation;
std::string log;
loadLog(path, evaluation, log);
pid_t pid = -1;
std::string output;
switch (mode) {
case UPDATE:
if (evaluation[0] == '?')
break;
// FALL THROUGH
default:
pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout);
break;
}
std::string result;
if (0 < pid && output.empty())
result = "fatal";
else if (mode == HEADLESS) {
if (evaluation != "?" && output != log)
result = "uncertain";
else
result = evaluation;
} else if (mode == UPDATE) {
result = evaluation;
if (result[0] != '?') {
if (!saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
}
}
if (0 < pid)
killTest(pid);
int status = ES_NA;
if (!result.compare(0, 4, "pass"))
status = ES_PASS;
else if (!result.compare(0, 5, "fatal"))
status = ES_FATAL;
else if (!result.compare(0, 4, "fail"))
status = ES_FAIL;
else if (!result.compare(0, 7, "invalid"))
status = ES_INVALID;
else if (!result.compare(0, 4, "skip"))
status = ES_SKIP;
else if (!result.compare(0, 9, "uncertain"))
status = ES_UNCERTAIN;
exit(status);
} else {
forkStates[forkCount].url = url;
forkStates[forkCount].pid = pid;
}
if (++forkCount == forkMax)
reduce(report);
}
int main(int argc, char* argv[])
{
int mode = HEADLESS;
unsigned timeout = 10;
int argi = 1;
while (*argv[argi] == '-') {
switch (argv[argi][1]) {
case 'i':
mode = INTERACTIVE;
timeout = 0;
break;
case 'r':
mode = REPORT;
break;
case 'u':
mode = UPDATE;
break;
case 'j':
forkMax = strtoul(argv[argi] + 2, 0, 10);
if (forkMax == 0)
forkMax = 1;
forkStates.resize(forkMax);
break;
default:
break;
}
++argi;
}
if (argc < argi + 2) {
std::cout << "usage: " << argv[0] << " [-i] report.data command [argument ...]\n";
return EXIT_FAILURE;
}
std::ifstream data(argv[argi]);
if (!data) {
std::cerr << "error: " << argv[argi] << ": no such file\n";
return EXIT_FAILURE;
}
std::ofstream report("report.data", std::ios_base::out | std::ios_base::trunc);
if (!report) {
std::cerr << "error: failed to open the report file\n";
return EXIT_FAILURE;
}
char* args[argc - argi + 3];
for (int i = 2; i < argc; ++i)
args[i - 2] = argv[i + argi - 1];
args[argc - argi] = args[argc - argi + 1] = args[argc - argi + 2] = 0;
std::string result;
std::string url;
std::string undo;
std::string userStyle;
std::string testFonts;
bool redo = false;
while (data) {
if (result == "undo") {
std::swap(url, undo);
redo = true;
} else if (redo) {
std::swap(url, undo);
redo = false;
} else {
std::string line;
std::getline(data, line);
if (line.empty())
continue;
if (line == "testname result comment") {
report << line << '\n';
continue;
}
if (line[0] == '#') {
if (line.compare(1, 9, "userstyle") == 0) {
if (10 < line.length()) {
std::stringstream s(line.substr(10), std::stringstream::in);
s >> userStyle;
} else
userStyle.clear();
} else if (line.compare(1, 9, "testfonts") == 0) {
if (10 < line.length()) {
std::stringstream s(line.substr(10), std::stringstream::in);
s >> testFonts;
} else
testFonts.clear();
}
reduce(report);
report << line << '\n';
continue;
}
undo = url;
std::stringstream s(line, std::stringstream::in);
s >> url;
}
if (url.empty())
continue;
switch (mode) {
case HEADLESS:
case UPDATE:
map(report, mode, argc - argi, args, url, userStyle, testFonts, timeout);
break;
default:
result = test(mode, argc - argi, args, url, userStyle, testFonts, timeout);
if (result != "undo")
report << url << '\t' << result << '\n';
break;
}
}
if (mode == HEADLESS || mode == UPDATE)
reduce(report);
report.close();
return (0 < uncertainCount) ? EXIT_FAILURE : EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
* This file is part of signon
*
* Copyright (C) 2010 Nokia Corporation.
*
* Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "signondisposable.h"
namespace SignonDaemonNS {
static QList<SignonDisposable *> disposableObjects;
SignonDisposable::SignonDisposable(int maxInactivity, QObject *parent)
: QObject(parent)
, maxInactivity(maxInactivity)
, autoDestruct(true)
{
disposableObjects.append(this);
// mark as used
keepInUse();
}
SignonDisposable::~SignonDisposable()
{
disposableObjects.removeOne(this);
}
void SignonDisposable::keepInUse() const
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
qWarning("Couldn't get time from monotonic clock");
return;
}
lastActivity = ts.tv_sec;
}
void SignonDisposable::setAutoDestruct(bool value) const
{
autoDestruct = value;
keepInUse();
}
void SignonDisposable::destroyUnused()
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
qWarning("Couldn't get time from monotonic clock");
return;
}
foreach (SignonDisposable *object, disposableObjects) {
if (object->autoDestruct && (ts.tv_sec - object->lastActivity > object->maxInactivity)) {
TRACE() << "Object unused, deleting: " << object;
object->destroy();
}
}
}
} //namespace SignonDaemonNS
<commit_msg>signond: immediate removal of SignonDisposables<commit_after>/*
* This file is part of signon
*
* Copyright (C) 2010 Nokia Corporation.
*
* Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "signondisposable.h"
namespace SignonDaemonNS {
static QList<SignonDisposable *> disposableObjects;
SignonDisposable::SignonDisposable(int maxInactivity, QObject *parent)
: QObject(parent)
, maxInactivity(maxInactivity)
, autoDestruct(true)
{
disposableObjects.append(this);
// mark as used
keepInUse();
}
SignonDisposable::~SignonDisposable()
{
disposableObjects.removeOne(this);
}
void SignonDisposable::keepInUse() const
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
qWarning("Couldn't get time from monotonic clock");
return;
}
lastActivity = ts.tv_sec;
}
void SignonDisposable::setAutoDestruct(bool value) const
{
autoDestruct = value;
keepInUse();
}
void SignonDisposable::destroyUnused()
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
qWarning("Couldn't get time from monotonic clock");
return;
}
foreach (SignonDisposable *object, disposableObjects) {
if (object->autoDestruct && (ts.tv_sec - object->lastActivity > object->maxInactivity)) {
TRACE() << "Object unused, deleting: " << object;
object->destroy();
disposableObjects.removeOne(object);
}
}
}
} //namespace SignonDaemonNS
<|endoftext|>
|
<commit_before> #include "b9.h"
Instruction program[] = {
decl (0,8), // (args,temps) assume max 8 temps
decl (0,0), // 0: space for JIT address
decl (0,0), // 1: space for JIT address
// Local variable a offset 0
createInstruction(PUSH_CONSTANT,100), // number constant 100
createInstruction(POP_INTO_VAR,0), // variable a
// Local variable b offset 1
createInstruction(PUSH_CONSTANT,10), // number constant 10
createInstruction(POP_INTO_VAR,1), // variable b
createInstruction(PUSH_FROM_VAR,1), // variable b
createInstruction(PUSH_CONSTANT,1), // number constant 1
createInstruction(SUB,0), // // generating var--
createInstruction(POP_INTO_VAR,1), // variable b
createInstruction(PUSH_CONSTANT,100), // number constant 100
createInstruction(PUSH_CONSTANT,9), // number constant 9
createInstruction(CALL,1), // Offset of:
createInstruction(PUSH_CONSTANT,5), // number constant 5
createInstruction(PUSH_CONSTANT,6), // number constant 6
createInstruction(CALL,2), // Offset of:
createInstruction(PUSH_FROM_VAR,0), // variable a
createInstruction(PUSH_FROM_VAR,1), // variable b
createInstruction(SUB,0),
createInstruction(RETURN,0), // forced = false
createInstruction(NO_MORE_BYTECODES, 0)}; // end of function
Instruction call_sub[] = {
decl (2,8), // (args,temps) assume max 8 temps
decl (0,0), // 0: space for JIT address
decl (0,0), // 1: space for JIT address
// Local variable c offset 2
createInstruction(PUSH_FROM_VAR,0), // variable a
createInstruction(PUSH_FROM_VAR,1), // variable b
createInstruction(SUB,0),
createInstruction(POP_INTO_VAR,2), // variable c
createInstruction(PUSH_FROM_VAR,2), // variable c
createInstruction(RETURN,0), // forced = false
createInstruction(NO_MORE_BYTECODES, 0)}; // end of function
Instruction call_add[] = {
decl (2,8), // (args,temps) assume max 8 temps
decl (0,0), // 0: space for JIT address
decl (0,0), // 1: space for JIT address
// Local variable c offset 2
createInstruction(PUSH_FROM_VAR,0), // variable a
createInstruction(PUSH_FROM_VAR,1), // variable b
createInstruction(ADD,0),
createInstruction(POP_INTO_VAR,2), // variable c
createInstruction(PUSH_FROM_VAR,2), // variable c
createInstruction(RETURN,0), // forced = false
createInstruction(NO_MORE_BYTECODES, 0)}; // end of function
Instruction *b9_exported_functions[] = {
program,
call_sub,
call_add,
};
<commit_msg>Delete program.cpp<commit_after><|endoftext|>
|
<commit_before>#include "mbed.h"
#include "Display.hpp"
Display *Display::mInstance = NULL;
Display *Display::getInstance() {
if(mInstance == NULL) {
mInstance = new Display();
}
return mInstance;
}
void Display::set(int row, int col) { buffers[backBuffer][row][col] = true; }
void Display::reset(int row, int col) { buffers[backBuffer][row][col] = false; }
void Display::flush() {
if(surfaceBuffer == 0) {
surfaceBuffer = 1;
backBuffer = 0;
} else {
surfaceBuffer = 0;
backBuffer = 1;
}
clearBuffer(buffers[backBuffer]);
}
void Display::clear() { clearBuffer(buffers[backBuffer]); }
bool Display::getBuffer(int row, int col) {
return buffers[surfaceBuffer][row][col];
}
Display::Display() {
sig = new DigitalOut(dp2);
sclk = new DigitalOut(dp6);
rclk = new DigitalOut(dp4);
surfaceBuffer = 0;
backBuffer = 1;
clearBuffer(buffers[surfaceBuffer]);
clearBuffer(buffers[backBuffer]);
ticker.attach_us(this, &Display::shiftCol, 80);
}
Display::~Display() { ticker.detach(); }
void Display::clearBuffer(bool buffer[height][width]) {
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
buffer[i][j] = false;
}
}
}
void Display::shiftCol() {
static int currentCol = 0;
currentCol &= 0b1111;
sendShiftRegisterCode(generateShiftRegisterCode(currentCol));
currentCol++;
}
int Display::generateShiftRegisterCode(int col) {
static int rowMap[] = {7, 5, 4, 6, 0, 3, 1, 2};
static int colMap[] = {10, 15, 14, 8, 13, 9, 11, 12, 2, 7, 6, 0, 5, 1, 3, 4};
int colCode = (1 << colMap[col]);
int rowCode = 0;
for(int i = 0; i < height; i++) {
if(buffers[surfaceBuffer][i][col]) {
rowCode |= (1 << rowMap[i]);
}
}
return ((rowCode << width) | colCode);
}
void Display::sendShiftRegisterCode(int code) {
for(int i = 0; i < height + width; i++) {
*sig = (code & (1 << ((height + width - 1) - i)));
*sclk = 0;
*sclk = 1;
}
*rclk = 0;
*rclk = 1;
}
<commit_msg>ledの周波数の修正<commit_after>#include "mbed.h"
#include "Display.hpp"
Display *Display::mInstance = NULL;
Display *Display::getInstance() {
if(mInstance == NULL) {
mInstance = new Display();
}
return mInstance;
}
void Display::set(int row, int col) { buffers[backBuffer][row][col] = true; }
void Display::reset(int row, int col) { buffers[backBuffer][row][col] = false; }
void Display::flush() {
if(surfaceBuffer == 0) {
surfaceBuffer = 1;
backBuffer = 0;
} else {
surfaceBuffer = 0;
backBuffer = 1;
}
clearBuffer(buffers[backBuffer]);
}
void Display::clear() { clearBuffer(buffers[backBuffer]); }
bool Display::getBuffer(int row, int col) {
return buffers[surfaceBuffer][row][col];
}
Display::Display() {
sig = new DigitalOut(dp2);
sclk = new DigitalOut(dp6);
rclk = new DigitalOut(dp4);
surfaceBuffer = 0;
backBuffer = 1;
clearBuffer(buffers[surfaceBuffer]);
clearBuffer(buffers[backBuffer]);
ticker.attach_us(this, &Display::shiftCol, 100);
}
Display::~Display() { ticker.detach(); }
void Display::clearBuffer(bool buffer[height][width]) {
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
buffer[i][j] = false;
}
}
}
void Display::shiftCol() {
static int currentCol = 0;
currentCol &= 0b1111;
sendShiftRegisterCode(generateShiftRegisterCode(currentCol));
currentCol++;
}
int Display::generateShiftRegisterCode(int col) {
static int rowMap[] = {7, 5, 4, 6, 0, 3, 1, 2};
static int colMap[] = {10, 15, 14, 8, 13, 9, 11, 12, 2, 7, 6, 0, 5, 1, 3, 4};
int colCode = (1 << colMap[col]);
int rowCode = 0;
for(int i = 0; i < height; i++) {
if(buffers[surfaceBuffer][i][col]) {
rowCode |= (1 << rowMap[i]);
}
}
return ((rowCode << width) | colCode);
}
void Display::sendShiftRegisterCode(int code) {
for(int i = 0; i < height + width; i++) {
*sig = (code & (1 << ((height + width - 1) - i)));
*sclk = 0;
*sclk = 1;
}
*rclk = 0;
*rclk = 1;
}
<|endoftext|>
|
<commit_before>#include <elfio/elfio.hpp>
#include <machine.hpp>
#include <cstring>
using namespace dbt;
#ifdef DEBUG
#define CORRECT_ASSERT() assert(Addr>=DataMemOffset && "Error on correcting address. Data memory offset Value < 0!")
#else
#define CORRECT_ASSERT()
#endif //DEBUG
#define STACK_SIZE 512 * 1024 * 1024 /*512mb*/
#define HEAP_SIZE 512 * 1024 * 1024 /*512mb*/
#define MAX_ARGUMENT_SIZE 1024 * 1024 /* 1mb */
union HalfUn {
char asC_[2];
uint16_t asH_;
};
void copystr(char* Target, const char* Source, uint32_t Size) {
for (uint32_t i = 0; i < Size; ++i)
Target[i] = Source[i];
}
void Machine::setCodeMemory(uint32_t StartAddress, uint32_t Size, const char* CodeBuffer) {
CodeMemOffset = StartAddress;
CodeMemory = uptr<Word[]>(new Word[Size]);
CodeMemLimit = Size + CodeMemOffset;
for (uint32_t i = 0; i < Size; i++) {
Word Bytes = {CodeBuffer[i], CodeBuffer[i+1], CodeBuffer[i+2], CodeBuffer[i+3]};
CodeMemory[i] = Bytes;
}
}
void Machine::allocDataMemory(uint32_t Offset, uint32_t TotalSize) {
DataMemOffset = Offset;
DataMemLimit = Offset + TotalSize;
DataMemory = std::unique_ptr<char[]>(new char[TotalSize]);
}
void Machine::addDataMemory(uint32_t StartAddress, uint32_t Size, const char* DataBuffer) {
uint32_t Offset = StartAddress - DataMemOffset;
DataMemLimit += Size;
copystr(DataMemory.get() + Offset, DataBuffer, Size);
}
int Machine::setCommandLineArguments(std::string parameters)
{
unsigned int totalSize = 0, offset, spDataLimit = getRegister(29);
std::istringstream iss(parameters);
std::vector<std::string> argv(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>());
<<<<<<< HEAD
argv.insert(argv.cbegin(), BinPath);
for(auto argument : argv)
totalSize += argument.length()+1;
if(totalSize >= MAX_ARGUMENT_SIZE)
{
std::cerr << "Error: Arguments size is " << totalSize << ". Higher than MAX_ARGUMENT_SIZE (" << MAX_ARGUMENT_SIZE << ")";
return -1;
}
setMemValueAt(spDataLimit, (uint32_t) argv.size()+1);
spDataLimit -= 4;
offset = DataMemOffset+STACK_SIZE/4;
//Reversed, then argc
for(auto argument : argv)
{
unsigned argSize = argument.length()+1;
copystr(DataMemory.get() + offset, argument.c_str(), argSize);
setMemValueAt(spDataLimit, offset);
spDataLimit -= 4;
offset -= argSize;
}
return 0;
=======
setMemValueAt(getRegister(29), argv.size()+1);
// offset = DataMemLimit - BinPath.length() + parameters.size();
/*strcpy(&(DataMemory[DataMemLimit]), BinPath.c_str());
for (auto argument : argv) {
offset += argument.length()-1;
strcpy(&(DataMemory[offset]), argument.c_str());
}*/
>>>>>>> bdbae63e66d7ece29c65931d77477b5bcd11e52d
}
uint32_t Machine::getPC() {
return PC;
}
uint32_t Machine::getLastPC() {
return LastPC;
}
void Machine::incPC() {
PC += 4;
}
void Machine::setPC(uint32_t NewPC) {
LastPC = PC;
PC = NewPC;
}
Word Machine::getInstAt(uint32_t Addr) {
return CodeMemory[Addr - CodeMemOffset];
}
Word Machine::getInstAtPC() {
return getInstAt(PC);
}
Word Machine::getNextInst() {
++PC;
return getInstAtPC();
}
void Machine::setMemByteAt(uint32_t Addr, uint8_t Value) {
uint32_t CorrectAddr = Addr - DataMemOffset;
CORRECT_ASSERT();
DataMemory[CorrectAddr] = Value;
}
uint8_t Machine::getMemByteAt(uint32_t Addr) {
uint32_t CorrectAddr = Addr - DataMemOffset;
CORRECT_ASSERT();
return DataMemory[CorrectAddr];
}
uint16_t Machine::getMemHalfAt(uint32_t Addr) {
uint32_t CorrectAddr = Addr - DataMemOffset;
CORRECT_ASSERT();
HalfUn Half = {DataMemory[CorrectAddr], DataMemory[CorrectAddr+1]};
return Half.asH_;
}
Word Machine::getMemValueAt(uint32_t Addr) {
uint32_t CorrectAddr = Addr - DataMemOffset;
assert((Addr % 4) == 0 && "Address not aligned!");
Word Bytes;
CORRECT_ASSERT();
Bytes.asI_ = *((uint32_t*)(DataMemory.get() + CorrectAddr));
return Bytes;
}
void Machine::setMemValueAt(uint32_t Addr, uint32_t Value) {
uint32_t CorrectAddr = Addr - DataMemOffset;
assert((Addr % 4) == 0 && "Address not aligned!");
CORRECT_ASSERT();
*((uint32_t*)(DataMemory.get() + CorrectAddr)) = Value;
}
uint32_t Machine::getNumInst() {
return (CodeMemLimit - CodeMemOffset)/4;
}
uint32_t Machine::getCodeStartAddrs() {
return CodeMemOffset;
}
uint32_t Machine::getCodeEndAddrs() {
return CodeMemLimit;
}
uint32_t Machine::getDataMemOffset() {
return DataMemOffset;
}
int32_t Machine::getRegister(uint16_t R) {
return Register[R];
}
float Machine::getFloatRegister(uint16_t R) {
return ((float*) Register)[R + 66];
}
double Machine::getDoubleRegister(uint16_t R) {
return ((double*)Register)[R + 65];
}
void Machine::setRegister(uint16_t R, int32_t V) {
Register[R] = V;
}
void Machine::setFloatRegister(uint16_t R, float V) {
((float*)Register)[R + 66] = V;
}
void Machine::setDoubleRegister(uint16_t R, double V) {
((double*)Register)[R + 65] = V;
}
int32_t* Machine::getRegisterPtr() {
return Register;
}
char* Machine::getByteMemoryPtr() {
return DataMemory.get();
}
uint32_t* Machine::getMemoryPtr() {
return (uint32_t*) DataMemory.get();
}
bool Machine::isOnNativeExecution() {
return OnNativeExecution;
}
uint32_t Machine::getRegionBeingExecuted() {
return RegionBeingExecuted;
}
void Machine::setOnNativeExecution(uint32_t EntryRegionAddrs) {
OnNativeExecution = true;
RegionBeingExecuted = EntryRegionAddrs;
}
void Machine::setOffNativeExecution() {
OnNativeExecution = false;
}
bool Machine::isMethodEntry(uint32_t Addr) {
return Symbols.count(Addr) != 0;
}
uint32_t Machine::getMethodEnd(uint32_t Addr) {
return Symbols[Addr].second;
}
std::string Machine::getMethodName(uint32_t Addr) {
return Symbols[Addr].first;
}
std::vector<uint32_t> Machine::getVectorOfMethodEntries() {
std::vector<uint32_t> R;
for (auto KV : Symbols)
R.push_back(KV.first);
return R;
}
using namespace ELFIO;
void Machine::reset() {
loadELF(BinPath);
}
int Machine::loadELF(const std::string ElfPath) {
BinPath = ElfPath;
elfio reader;
if (!reader.load(ElfPath))
return 0;
Elf_Half sec_num = reader.sections.size();
uint32_t TotalDataSize = 0;
uint32_t AddressOffset = 0;
bool Started = false;
bool First = false;
for (int i = 0; i < sec_num; ++i) {
section* psec = reader.sections[i];
if (Started && (psec->get_flags() & 0x2) != 0) {
TotalDataSize += psec->get_size();
if (!First) {
AddressOffset = psec->get_address();
First = true;
}
}
if (psec->get_name() == ".text")
Started = true;
}
allocDataMemory(AddressOffset, (TotalDataSize + STACK_SIZE + HEAP_SIZE) + (4 - (TotalDataSize + STACK_SIZE + HEAP_SIZE) % 4));
std::unordered_map<uint32_t, std::string> SymbolNames;
std::set<uint32_t> SymbolStartAddresses;
Started = false;
for (int i = 0; i < sec_num; ++i) {
section* psec = reader.sections[i];
if (Started && (psec->get_flags() & 0x2) != 0 && psec->get_data() != nullptr) {
addDataMemory(psec->get_address(), psec->get_size(), psec->get_data());
}
if (psec->get_name() == ".text") {
setCodeMemory(psec->get_address(), psec->get_size(), psec->get_data());
SymbolStartAddresses.insert(psec->get_address() + psec->get_size());
Started = true;
}
if (psec->get_name() == ".symtab") {
const symbol_section_accessor symbols(reader, psec);
std::string name = "";
Elf64_Addr value = 0;
Elf_Xword size;
unsigned char bind;
unsigned char type = 0;
Elf_Half section_index;
unsigned char other;
for ( unsigned int j = 0; j < symbols.get_symbols_num(); ++j ) {
symbols.get_symbol( j, name, value, size, bind, type, section_index, other );
if (type == 0 && name != "" && value != 0) {
SymbolStartAddresses.insert(value);
SymbolNames[value] = name;
}
}
}
}
for (auto I = SymbolStartAddresses.begin(); I != SymbolStartAddresses.end(); ++I)
Symbols[*I] = {SymbolNames[*I], *SymbolStartAddresses.upper_bound(*I)};
<<<<<<< HEAD
setRegister(29, (DataMemLimit-STACK_SIZE/4)-(((DataMemLimit-STACK_SIZE/4)%4))); //StackPointer
setRegister(30, (DataMemLimit-STACK_SIZE/4)-(((DataMemLimit-STACK_SIZE/4)%4))); //StackPointer
=======
uint32_t StackAddr = DataMemLimit-STACK_SIZE/4;
setRegister(29, StackAddr - (StackAddr%4)); //StackPointer
setRegister(30, StackAddr - (StackAddr%4)); //StackPointer
>>>>>>> bdbae63e66d7ece29c65931d77477b5bcd11e52d
setPC(reader.get_entry());
return 1;
}
<commit_msg>Command Line Arguments<commit_after>#include <elfio/elfio.hpp>
#include <machine.hpp>
#include <cstring>
using namespace dbt;
#ifdef DEBUG
#define CORRECT_ASSERT() assert(Addr>=DataMemOffset && "Error on correcting address. Data memory offset Value < 0!")
#else
#define CORRECT_ASSERT()
#endif //DEBUG
#define STACK_SIZE 512 * 1024 * 1024 /*512mb*/
#define HEAP_SIZE 512 * 1024 * 1024 /*512mb*/
#define MAX_ARGUMENT_SIZE 1024 * 1024 /* 1mb */
union HalfUn {
char asC_[2];
uint16_t asH_;
};
void copystr(char* Target, const char* Source, uint32_t Size) {
for (uint32_t i = 0; i < Size; ++i)
Target[i] = Source[i];
}
void Machine::setCodeMemory(uint32_t StartAddress, uint32_t Size, const char* CodeBuffer) {
CodeMemOffset = StartAddress;
CodeMemory = uptr<Word[]>(new Word[Size]);
CodeMemLimit = Size + CodeMemOffset;
for (uint32_t i = 0; i < Size; i++) {
Word Bytes = {CodeBuffer[i], CodeBuffer[i+1], CodeBuffer[i+2], CodeBuffer[i+3]};
CodeMemory[i] = Bytes;
}
}
void Machine::allocDataMemory(uint32_t Offset, uint32_t TotalSize) {
DataMemOffset = Offset;
DataMemLimit = Offset + TotalSize;
DataMemory = std::unique_ptr<char[]>(new char[TotalSize]);
}
void Machine::addDataMemory(uint32_t StartAddress, uint32_t Size, const char* DataBuffer) {
uint32_t Offset = StartAddress - DataMemOffset;
DataMemLimit += Size;
copystr(DataMemory.get() + Offset, DataBuffer, Size);
}
int Machine::setCommandLineArguments(std::string parameters)
{
unsigned int totalSize = 0, offset, spDataLimit = getRegister(29);
std::istringstream iss(parameters);
std::vector<std::string> argv(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>());
argv.insert(argv.cbegin(), BinPath);
for(auto argument : argv)
totalSize += argument.length()+1;
if(totalSize >= MAX_ARGUMENT_SIZE)
{
std::cerr << "Error: Arguments size is " << totalSize << ". Higher than MAX_ARGUMENT_SIZE (" << MAX_ARGUMENT_SIZE << ")";
return -1;
}
setMemValueAt(spDataLimit, (uint32_t) argv.size()+1);
spDataLimit -= 4;
offset = DataMemOffset+STACK_SIZE/4;
//Reversed, then argc
for(auto argument : argv)
{
unsigned argSize = argument.length()+1;
copystr(DataMemory.get() + offset, argument.c_str(), argSize);
setMemValueAt(spDataLimit, offset);
spDataLimit -= 4;
offset -= argSize;
}
return 0;
}
uint32_t Machine::getPC() {
return PC;
}
uint32_t Machine::getLastPC() {
return LastPC;
}
void Machine::incPC() {
PC += 4;
}
void Machine::setPC(uint32_t NewPC) {
LastPC = PC;
PC = NewPC;
}
Word Machine::getInstAt(uint32_t Addr) {
return CodeMemory[Addr - CodeMemOffset];
}
Word Machine::getInstAtPC() {
return getInstAt(PC);
}
Word Machine::getNextInst() {
++PC;
return getInstAtPC();
}
void Machine::setMemByteAt(uint32_t Addr, uint8_t Value) {
uint32_t CorrectAddr = Addr - DataMemOffset;
CORRECT_ASSERT();
DataMemory[CorrectAddr] = Value;
}
uint8_t Machine::getMemByteAt(uint32_t Addr) {
uint32_t CorrectAddr = Addr - DataMemOffset;
CORRECT_ASSERT();
return DataMemory[CorrectAddr];
}
uint16_t Machine::getMemHalfAt(uint32_t Addr) {
uint32_t CorrectAddr = Addr - DataMemOffset;
CORRECT_ASSERT();
HalfUn Half = {DataMemory[CorrectAddr], DataMemory[CorrectAddr+1]};
return Half.asH_;
}
Word Machine::getMemValueAt(uint32_t Addr) {
uint32_t CorrectAddr = Addr - DataMemOffset;
assert((Addr % 4) == 0 && "Address not aligned!");
Word Bytes;
CORRECT_ASSERT();
Bytes.asI_ = *((uint32_t*)(DataMemory.get() + CorrectAddr));
return Bytes;
}
void Machine::setMemValueAt(uint32_t Addr, uint32_t Value) {
uint32_t CorrectAddr = Addr - DataMemOffset;
assert((Addr % 4) == 0 && "Address not aligned!");
CORRECT_ASSERT();
*((uint32_t*)(DataMemory.get() + CorrectAddr)) = Value;
}
uint32_t Machine::getNumInst() {
return (CodeMemLimit - CodeMemOffset)/4;
}
uint32_t Machine::getCodeStartAddrs() {
return CodeMemOffset;
}
uint32_t Machine::getCodeEndAddrs() {
return CodeMemLimit;
}
uint32_t Machine::getDataMemOffset() {
return DataMemOffset;
}
int32_t Machine::getRegister(uint16_t R) {
return Register[R];
}
float Machine::getFloatRegister(uint16_t R) {
return ((float*) Register)[R + 66];
}
double Machine::getDoubleRegister(uint16_t R) {
return ((double*)Register)[R + 65];
}
void Machine::setRegister(uint16_t R, int32_t V) {
Register[R] = V;
}
void Machine::setFloatRegister(uint16_t R, float V) {
((float*)Register)[R + 66] = V;
}
void Machine::setDoubleRegister(uint16_t R, double V) {
((double*)Register)[R + 65] = V;
}
int32_t* Machine::getRegisterPtr() {
return Register;
}
char* Machine::getByteMemoryPtr() {
return DataMemory.get();
}
uint32_t* Machine::getMemoryPtr() {
return (uint32_t*) DataMemory.get();
}
bool Machine::isOnNativeExecution() {
return OnNativeExecution;
}
uint32_t Machine::getRegionBeingExecuted() {
return RegionBeingExecuted;
}
void Machine::setOnNativeExecution(uint32_t EntryRegionAddrs) {
OnNativeExecution = true;
RegionBeingExecuted = EntryRegionAddrs;
}
void Machine::setOffNativeExecution() {
OnNativeExecution = false;
}
bool Machine::isMethodEntry(uint32_t Addr) {
return Symbols.count(Addr) != 0;
}
uint32_t Machine::getMethodEnd(uint32_t Addr) {
return Symbols[Addr].second;
}
std::string Machine::getMethodName(uint32_t Addr) {
return Symbols[Addr].first;
}
std::vector<uint32_t> Machine::getVectorOfMethodEntries() {
std::vector<uint32_t> R;
for (auto KV : Symbols)
R.push_back(KV.first);
return R;
}
using namespace ELFIO;
void Machine::reset() {
loadELF(BinPath);
}
int Machine::loadELF(const std::string ElfPath) {
BinPath = ElfPath;
elfio reader;
if (!reader.load(ElfPath))
return 0;
Elf_Half sec_num = reader.sections.size();
uint32_t TotalDataSize = 0;
uint32_t AddressOffset = 0;
bool Started = false;
bool First = false;
for (int i = 0; i < sec_num; ++i) {
section* psec = reader.sections[i];
if (Started && (psec->get_flags() & 0x2) != 0) {
TotalDataSize += psec->get_size();
if (!First) {
AddressOffset = psec->get_address();
First = true;
}
}
if (psec->get_name() == ".text")
Started = true;
}
allocDataMemory(AddressOffset, (TotalDataSize + STACK_SIZE + HEAP_SIZE) + (4 - (TotalDataSize + STACK_SIZE + HEAP_SIZE) % 4));
std::unordered_map<uint32_t, std::string> SymbolNames;
std::set<uint32_t> SymbolStartAddresses;
Started = false;
for (int i = 0; i < sec_num; ++i) {
section* psec = reader.sections[i];
if (Started && (psec->get_flags() & 0x2) != 0 && psec->get_data() != nullptr) {
addDataMemory(psec->get_address(), psec->get_size(), psec->get_data());
}
if (psec->get_name() == ".text") {
setCodeMemory(psec->get_address(), psec->get_size(), psec->get_data());
SymbolStartAddresses.insert(psec->get_address() + psec->get_size());
Started = true;
}
if (psec->get_name() == ".symtab") {
const symbol_section_accessor symbols(reader, psec);
std::string name = "";
Elf64_Addr value = 0;
Elf_Xword size;
unsigned char bind;
unsigned char type = 0;
Elf_Half section_index;
unsigned char other;
for ( unsigned int j = 0; j < symbols.get_symbols_num(); ++j ) {
symbols.get_symbol( j, name, value, size, bind, type, section_index, other );
if (type == 0 && name != "" && value != 0) {
SymbolStartAddresses.insert(value);
SymbolNames[value] = name;
}
}
}
}
for (auto I = SymbolStartAddresses.begin(); I != SymbolStartAddresses.end(); ++I)
Symbols[*I] = {SymbolNames[*I], *SymbolStartAddresses.upper_bound(*I)};
uint32_t StackAddr = DataMemLimit-STACK_SIZE/4;
setRegister(29, StackAddr - (StackAddr%4)); //StackPointer
setRegister(30, StackAddr - (StackAddr%4)); //StackPointer
setPC(reader.get_entry());
return 1;
}
<|endoftext|>
|
<commit_before>#ifndef MIMOSA_ENDIAN_HH
# define MIMOSA_ENDIAN_HH
# ifdef __FreeBSD__
# include <sys/endian.h>
# else
# include <endian.h>
# endif
#endif /* !MIMOSA_ENDIAN_HH */
<commit_msg>Endian support on MacOSX<commit_after>#ifndef MIMOSA_ENDIAN_HH
# define MIMOSA_ENDIAN_HH
# ifdef __FreeBSD__
# include <sys/endian.h>
# elif defined(__MACH__)
# include <machine/endian.h>
# else
# include <endian.h>
# endif
#endif /* !MIMOSA_ENDIAN_HH */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: lotimpop.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: vg $ $Date: 2007-02-27 12:38:53 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include "lotimpop.hxx"
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#include "attrib.hxx"
#include "document.hxx"
#include "rangenam.hxx"
#include "cell.hxx"
#include "patattr.hxx"
#include "docpool.hxx"
#include "compiler.hxx"
#include "global.hxx"
#include "root.hxx"
#include "lotfntbf.hxx"
#include "lotform.hxx"
#include "tool.h"
#include "namebuff.hxx"
#include "lotrange.hxx"
#include "lotattr.hxx"
static NAMESPACE_VOS( OMutex ) aLotImpSemaphore;
ImportLotus::ImportLotus( SvStream& aStream, ScDocument* pDoc, CharSet eQ ) :
ImportTyp( pDoc, eQ ),
pIn( &aStream ),
aConv( *pIn, eQ, FALSE )
{
// good point to start locking of import lotus
aLotImpSemaphore.acquire();
pLotusRoot = new LOTUS_ROOT;
pLotusRoot->pDoc = pDoc;
pLotusRoot->pRangeNames = new LotusRangeList;
pLotusRoot->pScRangeName = pDoc->GetRangeName();
pLotusRoot->eCharsetQ = eQ;
pLotusRoot->eFirstType = Lotus_X;
pLotusRoot->eActType = Lotus_X;
pLotusRoot->pRngNmBffWK3 = new RangeNameBufferWK3;
pFontBuff = pLotusRoot->pFontBuff = new LotusFontBuffer;
pLotusRoot->pAttrTable = new LotAttrTable;
}
ImportLotus::~ImportLotus()
{
delete pLotusRoot->pRangeNames;
delete pLotusRoot->pRngNmBffWK3;
delete pFontBuff;
delete pLotusRoot->pAttrTable;
delete pLotusRoot;
#ifdef DBG_UTIL
pLotusRoot = NULL;
#endif
// no need 4 pLotusRoot anymore
aLotImpSemaphore.release();
}
void ImportLotus::Bof( void )
{
UINT16 nFileCode, nFileSub, nSaveCnt;
BYTE nMajorId, nMinorId, nFlags;
Read( nFileCode );
Read( nFileSub );
Read( pLotusRoot->aActRange );
Read( nSaveCnt );
Read( nMajorId );
Read( nMinorId );
Skip( 1 );
Read( nFlags );
if( nFileSub == 0x0004 )
{
if( nFileCode == 0x1000 )
{// <= WK3
pLotusRoot->eFirstType = pLotusRoot->eActType = Lotus_WK3;
}
else if( nFileCode == 0x1002 )
{// WK4
pLotusRoot->eFirstType = pLotusRoot->eActType = Lotus_WK4;
}
}
}
BOOL ImportLotus::BofFm3( void )
{
UINT16 nFileCode, nFileSub;
Read( nFileCode );
Read( nFileSub );
return ( nFileCode == 0x8007 && ( nFileSub == 0x0000 || nFileSub == 0x00001 ) );
}
void ImportLotus::Columnwidth( UINT16 nRecLen )
{
DBG_ASSERT( nRecLen >= 4, "*ImportLotus::Columnwidth(): Record zu kurz!" );
BYTE nLTab, nWindow2;
UINT16 nCnt = ( nRecLen - 4 ) / 2;
Read( nLTab );
Read( nWindow2 );
if( !pD->HasTable( static_cast<SCTAB> (nLTab) ) )
pD->MakeTable( static_cast<SCTAB> (nLTab) );
if( !nWindow2 )
{
Skip( 2 );
BYTE nCol, nSpaces;
while( nCnt )
{
Read( nCol );
Read( nSpaces );
// ACHTUNG: Korrekturfaktor nach 'Augenmass' ermittelt!
pD->SetColWidth( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nLTab), ( UINT16 ) ( TWIPS_PER_CHAR * 1.28 * nSpaces ) );
nCnt--;
}
}
}
void ImportLotus::Hiddencolumn( UINT16 nRecLen )
{
DBG_ASSERT( nRecLen >= 4, "*ImportLotus::Hiddencolumn(): Record zu kurz!" );
BYTE nLTab, nWindow2;
UINT16 nCnt = ( nRecLen - 4 ) / 2;
Read( nLTab );
Read( nWindow2 );
if( !nWindow2 )
{
Skip( 2 );
BYTE nCol;
while( nCnt )
{
Read( nCol );
pD->SetColFlags( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nLTab), pD->GetColFlags( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nLTab) ) | CR_HIDDEN );
nCnt--;
}
}
}
void ImportLotus::Userrange( void )
{
UINT16 nRangeType;
ScRange aScRange;
sal_Char* pBuffer = new sal_Char[ 32 ];
Read( nRangeType );
pIn->Read( pBuffer, 16 );
pBuffer[ 16 ] = ( sal_Char ) 0x00; // zur Sicherheit...
String aName( pBuffer, eQuellChar );
Read( aScRange );
pLotusRoot->pRngNmBffWK3->Add( aName, aScRange );
delete[] pBuffer;
}
void ImportLotus::Errcell( void )
{
ScAddress aA;
Read( aA );
pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( CREATE_STRING( "#ERR!" ) ), (BOOL)TRUE );
}
void ImportLotus::Nacell( void )
{
ScAddress aA;
Read( aA );
pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( CREATE_STRING( "#NA!" ) ), (BOOL)TRUE );
}
void ImportLotus::Labelcell( void )
{
ScAddress aA;
String aLabel;
sal_Char cAlign;
Read( aA );
Read( cAlign );
Read( aLabel );
// aLabel.Convert( pLotusRoot->eCharsetQ );
pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( aLabel ), (BOOL)TRUE );
}
void ImportLotus::Numbercell( void )
{
ScAddress aAddr;
double fVal;
Read( aAddr );
Read( fVal );
pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(),
new ScValueCell( fVal ), (BOOL)TRUE );
}
void ImportLotus::Smallnumcell( void )
{
ScAddress aAddr;
INT16 nVal;
Read( aAddr );
Read( nVal );
pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(),
new ScValueCell( SnumToDouble( nVal ) ), ( BOOL ) TRUE );
}
ScFormulaCell *ImportLotus::Formulacell( UINT16 n )
{
DBG_ASSERT( pIn, "-ImportLotus::Formulacell(): Null-Stream -> Rums!" );
ScAddress aAddr;
Read( aAddr );
Skip( 10 );
n -= 14;
const ScTokenArray* pErg;
INT32 nRest = n;
aConv.Reset( aAddr );
aConv.SetWK3();
aConv.Convert( pErg, nRest );
ScFormulaCell* pZelle = new ScFormulaCell( pD, aAddr, pErg );
pZelle->AddRecalcMode( RECALCMODE_ONLOAD_ONCE );
pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(), pZelle, (BOOL)TRUE );
return NULL;
}
void ImportLotus::Read( String &r )
{
ScfTools::AppendCString( *pIn, r, eQuellChar );
}
void ImportLotus::RowPresentation( UINT16 nRecLen )
{
DBG_ASSERT( nRecLen > 4, "*ImportLotus::RowPresentation(): Record zu kurz!" );
BYTE nLTab, nFlags;
UINT16 nRow, nHeight;
UINT16 nCnt = ( nRecLen - 4 ) / 8;
Read( nLTab );
Skip( 1 );
while( nCnt )
{
Read( nRow );
Read( nHeight );
Skip( 2 );
Read( nFlags );
Skip( 1 );
if( nFlags & 0x02 ) // Fixed / Strech to fit fonts
{ // fixed
// Height in Lotus in 1/32 Points
nHeight *= 20; // -> 32 * TWIPS
nHeight /= 32; // -> TWIPS
pD->SetRowFlags( static_cast<SCROW> (nRow), static_cast<SCTAB> (nLTab), pD->GetRowFlags( static_cast<SCROW> (nRow), static_cast<SCTAB> (nLTab) ) | CR_MANUALSIZE );
pD->SetRowHeight( static_cast<SCROW> (nRow), static_cast<SCTAB> (nLTab), nHeight );
}
nCnt--;
}
}
void ImportLotus::NamedSheet( void )
{
UINT16 nLTab;
String aName;
Read( nLTab );
Read( aName );
if( pD->HasTable( static_cast<SCTAB> (nLTab) ) )
pD->RenameTab( static_cast<SCTAB> (nLTab), aName );
else
pD->InsertTab( static_cast<SCTAB> (nLTab), aName );
}
void ImportLotus::Font_Face( void )
{
BYTE nNum;
String aName;
Read( nNum );
// ACHTUNG: QUICK-HACK gegen unerklaerliche Loops
if( nNum > 7 )
return;
// ACHTUNG
Read( aName );
pFontBuff->SetName( nNum, aName );
}
void ImportLotus::Font_Type( void )
{
static const UINT16 nAnz = 8;
UINT16 nCnt;
UINT16 nType;
for( nCnt = 0 ; nCnt < nAnz ; nCnt++ )
{
Read( nType );
pFontBuff->SetType( nCnt, nType );
}
}
void ImportLotus::Font_Ysize( void )
{
static const UINT16 nAnz = 8;
UINT16 nCnt;
UINT16 nSize;
for( nCnt = 0 ; nCnt < nAnz ; nCnt++ )
{
Read( nSize );
pFontBuff->SetHeight( nCnt, nSize );
}
}
void ImportLotus::_Row( const UINT16 nRecLen )
{
DBG_ASSERT( nExtTab >= 0, "*ImportLotus::_Row(): Kann hier nicht sein!" );
UINT16 nRow;
UINT16 nHeight;
UINT16 nCntDwn = ( nRecLen - 4 ) / 5;
SCCOL nColCnt = 0;
UINT8 nRepeats;
LotAttrWK3 aAttr;
BOOL bCenter = FALSE;
SCCOL nCenterStart = 0, nCenterEnd = 0;
Read( nRow );
Read( nHeight );
nHeight &= 0x0FFF;
nHeight *= 22;
if( nHeight )
pD->SetRowHeight( static_cast<SCROW> (nRow), static_cast<SCTAB> (nExtTab), nHeight );
while( nCntDwn )
{
Read( aAttr );
Read( nRepeats );
if( aAttr.HasStyles() )
pLotusRoot->pAttrTable->SetAttr(
nColCnt, static_cast<SCCOL> ( nColCnt + nRepeats ), static_cast<SCROW> (nRow), aAttr );
// hier und NICHT in class LotAttrTable, weil nur Attributiert wird,
// wenn die anderen Attribute gesetzt sind
// -> bei Center-Attribute wird generell zentriert gesetzt
if( aAttr.IsCentered() )
{
if( bCenter )
{
if( pD->HasData( nColCnt, static_cast<SCROW> (nRow), static_cast<SCTAB> (nExtTab) ) )
{// neue Center nach vorheriger Center
pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
nCenterStart = nColCnt;
}
}
else
{// ganz neue Center
bCenter = TRUE;
nCenterStart = nColCnt;
}
nCenterEnd = nColCnt + static_cast<SCCOL>(nRepeats);
}
else
{
if( bCenter )
{// evtl. alte Center bemachen
pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
bCenter = FALSE;
}
}
nColCnt = nColCnt + static_cast<SCCOL>(nRepeats);
nColCnt++;
nCntDwn--;
}
if( bCenter )
// evtl. alte Center bemachen
pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.12.330); FILE MERGED 2008/04/01 15:30:21 thb 1.12.330.2: #i85898# Stripping all external header guards 2008/03/31 17:14:49 rt 1.12.330.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: lotimpop.cxx,v $
* $Revision: 1.13 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include "lotimpop.hxx"
#include <vos/mutex.hxx>
#include "attrib.hxx"
#include "document.hxx"
#include "rangenam.hxx"
#include "cell.hxx"
#include "patattr.hxx"
#include "docpool.hxx"
#include "compiler.hxx"
#include "global.hxx"
#include "root.hxx"
#include "lotfntbf.hxx"
#include "lotform.hxx"
#include "tool.h"
#include "namebuff.hxx"
#include "lotrange.hxx"
#include "lotattr.hxx"
static NAMESPACE_VOS( OMutex ) aLotImpSemaphore;
ImportLotus::ImportLotus( SvStream& aStream, ScDocument* pDoc, CharSet eQ ) :
ImportTyp( pDoc, eQ ),
pIn( &aStream ),
aConv( *pIn, eQ, FALSE )
{
// good point to start locking of import lotus
aLotImpSemaphore.acquire();
pLotusRoot = new LOTUS_ROOT;
pLotusRoot->pDoc = pDoc;
pLotusRoot->pRangeNames = new LotusRangeList;
pLotusRoot->pScRangeName = pDoc->GetRangeName();
pLotusRoot->eCharsetQ = eQ;
pLotusRoot->eFirstType = Lotus_X;
pLotusRoot->eActType = Lotus_X;
pLotusRoot->pRngNmBffWK3 = new RangeNameBufferWK3;
pFontBuff = pLotusRoot->pFontBuff = new LotusFontBuffer;
pLotusRoot->pAttrTable = new LotAttrTable;
}
ImportLotus::~ImportLotus()
{
delete pLotusRoot->pRangeNames;
delete pLotusRoot->pRngNmBffWK3;
delete pFontBuff;
delete pLotusRoot->pAttrTable;
delete pLotusRoot;
#ifdef DBG_UTIL
pLotusRoot = NULL;
#endif
// no need 4 pLotusRoot anymore
aLotImpSemaphore.release();
}
void ImportLotus::Bof( void )
{
UINT16 nFileCode, nFileSub, nSaveCnt;
BYTE nMajorId, nMinorId, nFlags;
Read( nFileCode );
Read( nFileSub );
Read( pLotusRoot->aActRange );
Read( nSaveCnt );
Read( nMajorId );
Read( nMinorId );
Skip( 1 );
Read( nFlags );
if( nFileSub == 0x0004 )
{
if( nFileCode == 0x1000 )
{// <= WK3
pLotusRoot->eFirstType = pLotusRoot->eActType = Lotus_WK3;
}
else if( nFileCode == 0x1002 )
{// WK4
pLotusRoot->eFirstType = pLotusRoot->eActType = Lotus_WK4;
}
}
}
BOOL ImportLotus::BofFm3( void )
{
UINT16 nFileCode, nFileSub;
Read( nFileCode );
Read( nFileSub );
return ( nFileCode == 0x8007 && ( nFileSub == 0x0000 || nFileSub == 0x00001 ) );
}
void ImportLotus::Columnwidth( UINT16 nRecLen )
{
DBG_ASSERT( nRecLen >= 4, "*ImportLotus::Columnwidth(): Record zu kurz!" );
BYTE nLTab, nWindow2;
UINT16 nCnt = ( nRecLen - 4 ) / 2;
Read( nLTab );
Read( nWindow2 );
if( !pD->HasTable( static_cast<SCTAB> (nLTab) ) )
pD->MakeTable( static_cast<SCTAB> (nLTab) );
if( !nWindow2 )
{
Skip( 2 );
BYTE nCol, nSpaces;
while( nCnt )
{
Read( nCol );
Read( nSpaces );
// ACHTUNG: Korrekturfaktor nach 'Augenmass' ermittelt!
pD->SetColWidth( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nLTab), ( UINT16 ) ( TWIPS_PER_CHAR * 1.28 * nSpaces ) );
nCnt--;
}
}
}
void ImportLotus::Hiddencolumn( UINT16 nRecLen )
{
DBG_ASSERT( nRecLen >= 4, "*ImportLotus::Hiddencolumn(): Record zu kurz!" );
BYTE nLTab, nWindow2;
UINT16 nCnt = ( nRecLen - 4 ) / 2;
Read( nLTab );
Read( nWindow2 );
if( !nWindow2 )
{
Skip( 2 );
BYTE nCol;
while( nCnt )
{
Read( nCol );
pD->SetColFlags( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nLTab), pD->GetColFlags( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nLTab) ) | CR_HIDDEN );
nCnt--;
}
}
}
void ImportLotus::Userrange( void )
{
UINT16 nRangeType;
ScRange aScRange;
sal_Char* pBuffer = new sal_Char[ 32 ];
Read( nRangeType );
pIn->Read( pBuffer, 16 );
pBuffer[ 16 ] = ( sal_Char ) 0x00; // zur Sicherheit...
String aName( pBuffer, eQuellChar );
Read( aScRange );
pLotusRoot->pRngNmBffWK3->Add( aName, aScRange );
delete[] pBuffer;
}
void ImportLotus::Errcell( void )
{
ScAddress aA;
Read( aA );
pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( CREATE_STRING( "#ERR!" ) ), (BOOL)TRUE );
}
void ImportLotus::Nacell( void )
{
ScAddress aA;
Read( aA );
pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( CREATE_STRING( "#NA!" ) ), (BOOL)TRUE );
}
void ImportLotus::Labelcell( void )
{
ScAddress aA;
String aLabel;
sal_Char cAlign;
Read( aA );
Read( cAlign );
Read( aLabel );
// aLabel.Convert( pLotusRoot->eCharsetQ );
pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( aLabel ), (BOOL)TRUE );
}
void ImportLotus::Numbercell( void )
{
ScAddress aAddr;
double fVal;
Read( aAddr );
Read( fVal );
pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(),
new ScValueCell( fVal ), (BOOL)TRUE );
}
void ImportLotus::Smallnumcell( void )
{
ScAddress aAddr;
INT16 nVal;
Read( aAddr );
Read( nVal );
pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(),
new ScValueCell( SnumToDouble( nVal ) ), ( BOOL ) TRUE );
}
ScFormulaCell *ImportLotus::Formulacell( UINT16 n )
{
DBG_ASSERT( pIn, "-ImportLotus::Formulacell(): Null-Stream -> Rums!" );
ScAddress aAddr;
Read( aAddr );
Skip( 10 );
n -= 14;
const ScTokenArray* pErg;
INT32 nRest = n;
aConv.Reset( aAddr );
aConv.SetWK3();
aConv.Convert( pErg, nRest );
ScFormulaCell* pZelle = new ScFormulaCell( pD, aAddr, pErg );
pZelle->AddRecalcMode( RECALCMODE_ONLOAD_ONCE );
pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(), pZelle, (BOOL)TRUE );
return NULL;
}
void ImportLotus::Read( String &r )
{
ScfTools::AppendCString( *pIn, r, eQuellChar );
}
void ImportLotus::RowPresentation( UINT16 nRecLen )
{
DBG_ASSERT( nRecLen > 4, "*ImportLotus::RowPresentation(): Record zu kurz!" );
BYTE nLTab, nFlags;
UINT16 nRow, nHeight;
UINT16 nCnt = ( nRecLen - 4 ) / 8;
Read( nLTab );
Skip( 1 );
while( nCnt )
{
Read( nRow );
Read( nHeight );
Skip( 2 );
Read( nFlags );
Skip( 1 );
if( nFlags & 0x02 ) // Fixed / Strech to fit fonts
{ // fixed
// Height in Lotus in 1/32 Points
nHeight *= 20; // -> 32 * TWIPS
nHeight /= 32; // -> TWIPS
pD->SetRowFlags( static_cast<SCROW> (nRow), static_cast<SCTAB> (nLTab), pD->GetRowFlags( static_cast<SCROW> (nRow), static_cast<SCTAB> (nLTab) ) | CR_MANUALSIZE );
pD->SetRowHeight( static_cast<SCROW> (nRow), static_cast<SCTAB> (nLTab), nHeight );
}
nCnt--;
}
}
void ImportLotus::NamedSheet( void )
{
UINT16 nLTab;
String aName;
Read( nLTab );
Read( aName );
if( pD->HasTable( static_cast<SCTAB> (nLTab) ) )
pD->RenameTab( static_cast<SCTAB> (nLTab), aName );
else
pD->InsertTab( static_cast<SCTAB> (nLTab), aName );
}
void ImportLotus::Font_Face( void )
{
BYTE nNum;
String aName;
Read( nNum );
// ACHTUNG: QUICK-HACK gegen unerklaerliche Loops
if( nNum > 7 )
return;
// ACHTUNG
Read( aName );
pFontBuff->SetName( nNum, aName );
}
void ImportLotus::Font_Type( void )
{
static const UINT16 nAnz = 8;
UINT16 nCnt;
UINT16 nType;
for( nCnt = 0 ; nCnt < nAnz ; nCnt++ )
{
Read( nType );
pFontBuff->SetType( nCnt, nType );
}
}
void ImportLotus::Font_Ysize( void )
{
static const UINT16 nAnz = 8;
UINT16 nCnt;
UINT16 nSize;
for( nCnt = 0 ; nCnt < nAnz ; nCnt++ )
{
Read( nSize );
pFontBuff->SetHeight( nCnt, nSize );
}
}
void ImportLotus::_Row( const UINT16 nRecLen )
{
DBG_ASSERT( nExtTab >= 0, "*ImportLotus::_Row(): Kann hier nicht sein!" );
UINT16 nRow;
UINT16 nHeight;
UINT16 nCntDwn = ( nRecLen - 4 ) / 5;
SCCOL nColCnt = 0;
UINT8 nRepeats;
LotAttrWK3 aAttr;
BOOL bCenter = FALSE;
SCCOL nCenterStart = 0, nCenterEnd = 0;
Read( nRow );
Read( nHeight );
nHeight &= 0x0FFF;
nHeight *= 22;
if( nHeight )
pD->SetRowHeight( static_cast<SCROW> (nRow), static_cast<SCTAB> (nExtTab), nHeight );
while( nCntDwn )
{
Read( aAttr );
Read( nRepeats );
if( aAttr.HasStyles() )
pLotusRoot->pAttrTable->SetAttr(
nColCnt, static_cast<SCCOL> ( nColCnt + nRepeats ), static_cast<SCROW> (nRow), aAttr );
// hier und NICHT in class LotAttrTable, weil nur Attributiert wird,
// wenn die anderen Attribute gesetzt sind
// -> bei Center-Attribute wird generell zentriert gesetzt
if( aAttr.IsCentered() )
{
if( bCenter )
{
if( pD->HasData( nColCnt, static_cast<SCROW> (nRow), static_cast<SCTAB> (nExtTab) ) )
{// neue Center nach vorheriger Center
pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
nCenterStart = nColCnt;
}
}
else
{// ganz neue Center
bCenter = TRUE;
nCenterStart = nColCnt;
}
nCenterEnd = nColCnt + static_cast<SCCOL>(nRepeats);
}
else
{
if( bCenter )
{// evtl. alte Center bemachen
pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
bCenter = FALSE;
}
}
nColCnt = nColCnt + static_cast<SCCOL>(nRepeats);
nColCnt++;
nCntDwn--;
}
if( bCenter )
// evtl. alte Center bemachen
pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
}
<|endoftext|>
|
<commit_before>#include <unordered_map>
#include <string>
#include <cassert>
#include "string.hpp"
#include "arraylist.hpp"
#ifndef CPROCESSING_HASHMAP_
#define CPROCESSING_HASHMAP_
template <class T>
class HashMap {
public:
std::unordered_map<const char *, T> hm;
HashMap() {}
HashMap(int initialCapacity) {
hm.reserve(initialCapacity);
}
HashMap(int initialCapacity, float loadFactor) {
hm.reserve(initialCapacity);
hm.max_load_factor();
}
HashMap(HashMap& map) {}
//Returns a Set view of the keys contained in this map.
ArrayList<const char *> keySet() {
ArrayList<const char *> keys(ceil(hm.size/2));
for(auto kv : hm) keys.add(kv.first);
return keys;
}
//Returns a Collection view of the values contained in this map.
ArrayList<T> values() {
ArrayList<T> vals(floor(hm.size/2));
for(auto kv : hm) vals.add(kv.second);
return vals;
}
//Associates the specified value with the specified key in this map.
void put(const char * key, const T& value) { hm[key] = value; }
inline void put(String * key, const T& value) { put(key->toCharArray(), value); }
//Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
T get(const char * key) { return hm.at(key); }
inline T get(String * key) { return get(key->toCharArray()); }
//Copies all of the mappings from the specified map to this map.
//void putAll(Map<? extends K,? extends V> m)
//Returns the number of key-value mappings in this map.
inline int size() { return hm.size(); }
//Returns true if this map contains no key-value mappings.
inline bool isEmpty() { return hm.empty(); }
//Removes all of the mappings from this map.
inline void clear() { hm.clear(); }
//Removes an element by its key
bool remove(const char * s) { return ((hm.erase(s) > 0) ? true : false); }
inline bool remove(String * s) { return remove(s->toCharArray()); }
//Returns true if this map contains a mapping for the specified key.
bool containsKey(const char * s) { return ((hm.count(s) > 0) ? true :false); }
inline bool containsKey(String * s) { return containsKey(s->toCharArray()); }
//Returns true if this map maps one or more keys to the specified value.
//bool containsValue(T) { return ((hm.count(T) > 0) ? true :false); }
};
#endif
<commit_msg>move includes to main header<commit_after>#include "cprocessing.hpp"
#ifndef CPROCESSING_HASHMAP_
#define CPROCESSING_HASHMAP_
template <class T>
class HashMap {
public:
std::unordered_map<const char *, T> hm;
HashMap() {}
HashMap(int initialCapacity) {
hm.reserve(initialCapacity);
}
HashMap(int initialCapacity, float loadFactor) {
hm.reserve(initialCapacity);
hm.max_load_factor();
}
HashMap(HashMap& map) {}
//Returns a Set view of the keys contained in this map.
ArrayList<const char *> keySet() {
ArrayList<const char *> keys(ceil(hm.size/2));
for(auto kv : hm) keys.add(kv.first);
return keys;
}
//Returns a Collection view of the values contained in this map.
ArrayList<T> values() {
ArrayList<T> vals(floor(hm.size/2));
for(auto kv : hm) vals.add(kv.second);
return vals;
}
//Associates the specified value with the specified key in this map.
void put(const char * key, const T& value) { hm[key] = value; }
inline void put(String * key, const T& value) { put(key->toCharArray(), value); }
//Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
T get(const char * key) { return hm.at(key); }
inline T get(String * key) { return get(key->toCharArray()); }
//Copies all of the mappings from the specified map to this map.
//void putAll(Map<? extends K,? extends V> m)
//Returns the number of key-value mappings in this map.
inline int size() { return hm.size(); }
//Returns true if this map contains no key-value mappings.
inline bool isEmpty() { return hm.empty(); }
//Removes all of the mappings from this map.
inline void clear() { hm.clear(); }
//Removes an element by its key
bool remove(const char * s) { return ((hm.erase(s) > 0) ? true : false); }
inline bool remove(String * s) { return remove(s->toCharArray()); }
//Returns true if this map contains a mapping for the specified key.
bool containsKey(const char * s) { return ((hm.count(s) > 0) ? true :false); }
inline bool containsKey(String * s) { return containsKey(s->toCharArray()); }
//Returns true if this map maps one or more keys to the specified value.
//bool containsValue(T) { return ((hm.count(T) > 0) ? true :false); }
};
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: scuiimoptdlg.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-03-22 12:10:26 $
*
* 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
*
************************************************************************/
#undef SC_DLLIMPLEMENTATION
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
#include "scuiimoptdlg.hxx"
#include "scresid.hxx"
#include "imoptdlg.hrc"
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
//========================================================================
// ScDelimiterTable
//========================================================================
class ScDelimiterTable
{
public:
ScDelimiterTable( const String& rDelTab )
: theDelTab ( rDelTab ),
cSep ( '\t' ),
nCount ( rDelTab.GetTokenCount('\t') ),
nIter ( 0 )
{}
USHORT GetCode( const String& rDelimiter ) const;
String GetDelimiter( sal_Unicode nCode ) const;
String FirstDel() { nIter = 0; return theDelTab.GetToken( nIter, cSep ); }
String NextDel() { nIter +=2; return theDelTab.GetToken( nIter, cSep ); }
private:
const String theDelTab;
const sal_Unicode cSep;
const xub_StrLen nCount;
xub_StrLen nIter;
};
//------------------------------------------------------------------------
USHORT ScDelimiterTable::GetCode( const String& rDel ) const
{
sal_Unicode nCode = 0;
xub_StrLen i = 0;
if ( nCount >= 2 )
{
while ( i<nCount )
{
if ( rDel == theDelTab.GetToken( i, cSep ) )
{
nCode = (sal_Unicode) theDelTab.GetToken( i+1, cSep ).ToInt32();
i = nCount;
}
else
i += 2;
}
}
return nCode;
}
//------------------------------------------------------------------------
String ScDelimiterTable::GetDelimiter( sal_Unicode nCode ) const
{
String aStrDel;
xub_StrLen i = 0;
if ( nCount >= 2 )
{
while ( i<nCount )
{
if ( nCode == (sal_Unicode) theDelTab.GetToken( i+1, cSep ).ToInt32() )
{
aStrDel = theDelTab.GetToken( i, cSep );
i = nCount;
}
else
i += 2;
}
}
return aStrDel;
}
//========================================================================
// ScImportOptionsDlg
//========================================================================
ScImportOptionsDlg::ScImportOptionsDlg(
Window* pParent,
BOOL bAscii,
const ScImportOptions* pOptions,
const String* pStrTitle,
BOOL bMultiByte,
BOOL bOnlyDbtoolsEncodings,
BOOL bImport )
: ModalDialog ( pParent, ScResId( RID_SCDLG_IMPORTOPT ) ),
aBtnOk ( this, ScResId( BTN_OK ) ),
aBtnCancel ( this, ScResId( BTN_CANCEL ) ),
aBtnHelp ( this, ScResId( BTN_HELP ) ),
aFtFieldSep ( this, ScResId( FT_FIELDSEP ) ),
aEdFieldSep ( this, ScResId( ED_FIELDSEP ) ),
aFtTextSep ( this, ScResId( FT_TEXTSEP ) ),
aEdTextSep ( this, ScResId( ED_TEXTSEP ) ),
aFtFont ( this, ScResId( FT_FONT ) ),
aLbFont ( this, ScResId( bAscii ? DDLB_FONT : LB_FONT ) ),
aFlFieldOpt ( this, ScResId( FL_FIELDOPT ) ),
aCbFixed ( this, ScResId( CB_FIXEDWIDTH ) ),
aCbShown ( this, ScResId( CB_SAVESHOWN ) )
{
// im Ctor-Initializer nicht moeglich (MSC kann das nicht):
pFieldSepTab = new ScDelimiterTable( String(ScResId(SCSTR_FIELDSEP)) );
pTextSepTab = new ScDelimiterTable( String(ScResId(SCSTR_TEXTSEP)) );
String aStr = pFieldSepTab->FirstDel();
sal_Unicode nCode;
while ( aStr.Len() > 0 )
{
aEdFieldSep.InsertEntry( aStr );
aStr = pFieldSepTab->NextDel();
}
aStr = pTextSepTab->FirstDel();
while ( aStr.Len() > 0 )
{
aEdTextSep.InsertEntry( aStr );
aStr = pTextSepTab->NextDel();
}
aEdFieldSep.SetText( aEdFieldSep.GetEntry(0) );
aEdTextSep.SetText( aEdTextSep.GetEntry(0) );
if ( bOnlyDbtoolsEncodings )
{ //!TODO: Unicode and MultiByte would need work in each filter
// Think of field lengths in dBase export
if ( bMultiByte )
aLbFont.FillFromDbTextEncodingMap( bImport, RTL_TEXTENCODING_INFO_UNICODE );
else
aLbFont.FillFromDbTextEncodingMap( bImport, RTL_TEXTENCODING_INFO_UNICODE |
RTL_TEXTENCODING_INFO_MULTIBYTE );
}
else if ( !bAscii )
{ //!TODO: Unicode would need work in each filter
if ( bMultiByte )
aLbFont.FillFromTextEncodingTable( bImport, RTL_TEXTENCODING_INFO_UNICODE );
else
aLbFont.FillFromTextEncodingTable( bImport, RTL_TEXTENCODING_INFO_UNICODE |
RTL_TEXTENCODING_INFO_MULTIBYTE );
}
else
{
if ( pOptions )
{
nCode = pOptions->nFieldSepCode;
aStr = pFieldSepTab->GetDelimiter( nCode );
if ( !aStr.Len() )
aEdFieldSep.SetText( String((sal_Unicode)nCode) );
else
aEdFieldSep.SetText( aStr );
nCode = pOptions->nTextSepCode;
aStr = pTextSepTab->GetDelimiter( nCode );
if ( !aStr.Len() )
aEdTextSep.SetText( String((sal_Unicode)nCode) );
else
aEdTextSep.SetText( aStr );
}
// all encodings allowed, even Unicode
aLbFont.FillFromTextEncodingTable( bImport );
}
if( bAscii )
{
Size aWinSize( GetSizePixel() );
aWinSize.Height() = aCbFixed.GetPosPixel().Y() + aCbFixed.GetSizePixel().Height();
Size aDiffSize( LogicToPixel( Size( 0, 6 ), MapMode( MAP_APPFONT ) ) );
aWinSize.Height() += aDiffSize.Height();
SetSizePixel( aWinSize );
aCbFixed.Show();
aCbFixed.SetClickHdl( LINK( this, ScImportOptionsDlg, FixedWidthHdl ) );
aCbFixed.Check( FALSE );
aCbShown.Show();
aCbShown.Check( TRUE );
}
else
{
aFlFieldOpt.SetText( aFtFont.GetText() );
aFtFieldSep.Hide();
aFtTextSep.Hide();
aFtFont.Hide();
aEdFieldSep.Hide();
aEdTextSep.Hide();
aCbFixed.Hide();
aCbShown.Hide();
aLbFont.GrabFocus();
aLbFont.SetDoubleClickHdl( LINK( this, ScImportOptionsDlg, DoubleClickHdl ) );
}
aLbFont.SelectTextEncoding( pOptions ? pOptions->eCharSet :
gsl_getSystemTextEncoding() );
// optionaler Titel:
if ( pStrTitle )
SetText( *pStrTitle );
FreeResource();
}
//------------------------------------------------------------------------
__EXPORT ScImportOptionsDlg::~ScImportOptionsDlg()
{
delete pFieldSepTab;
delete pTextSepTab;
}
//------------------------------------------------------------------------
void ScImportOptionsDlg::GetImportOptions( ScImportOptions& rOptions ) const
{
rOptions.SetTextEncoding( aLbFont.GetSelectTextEncoding() );
if ( aCbFixed.IsVisible() )
{
rOptions.nFieldSepCode = GetCodeFromCombo( aEdFieldSep );
rOptions.nTextSepCode = GetCodeFromCombo( aEdTextSep );
rOptions.bFixedWidth = aCbFixed.IsChecked();
rOptions.bSaveAsShown = aCbShown.IsChecked();
}
}
//------------------------------------------------------------------------
USHORT ScImportOptionsDlg::GetCodeFromCombo( const ComboBox& rEd ) const
{
ScDelimiterTable* pTab;
String aStr( rEd.GetText() );
USHORT nCode;
if ( &rEd == &aEdTextSep )
pTab = pTextSepTab;
else
pTab = pFieldSepTab;
if ( !aStr.Len() )
{
nCode = 0; // kein Trennzeichen
}
else
{
nCode = pTab->GetCode( aStr );
if ( nCode == 0 )
nCode = (USHORT)aStr.GetChar(0);
}
return nCode;
}
//------------------------------------------------------------------------
IMPL_LINK( ScImportOptionsDlg, FixedWidthHdl, CheckBox*, pCheckBox )
{
if( pCheckBox == &aCbFixed )
{
BOOL bEnable = !aCbFixed.IsChecked();
aFtFieldSep.Enable( bEnable );
aEdFieldSep.Enable( bEnable );
aFtTextSep.Enable( bEnable );
aEdTextSep.Enable( bEnable );
aCbShown.Enable( bEnable );
}
return 0;
}
IMPL_LINK( ScImportOptionsDlg, DoubleClickHdl, ListBox*, pLb )
{
if ( pLb == &aLbFont )
{
aBtnOk.Click();
}
return 0;
}
<commit_msg>INTEGRATION: CWS pchfix01 (1.5.102); FILE MERGED 2006/07/12 10:02:28 kaib 1.5.102.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: scuiimoptdlg.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2006-07-21 13:28:33 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#undef SC_DLLIMPLEMENTATION
#include "scuiimoptdlg.hxx"
#include "scresid.hxx"
#include "imoptdlg.hrc"
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
//========================================================================
// ScDelimiterTable
//========================================================================
class ScDelimiterTable
{
public:
ScDelimiterTable( const String& rDelTab )
: theDelTab ( rDelTab ),
cSep ( '\t' ),
nCount ( rDelTab.GetTokenCount('\t') ),
nIter ( 0 )
{}
USHORT GetCode( const String& rDelimiter ) const;
String GetDelimiter( sal_Unicode nCode ) const;
String FirstDel() { nIter = 0; return theDelTab.GetToken( nIter, cSep ); }
String NextDel() { nIter +=2; return theDelTab.GetToken( nIter, cSep ); }
private:
const String theDelTab;
const sal_Unicode cSep;
const xub_StrLen nCount;
xub_StrLen nIter;
};
//------------------------------------------------------------------------
USHORT ScDelimiterTable::GetCode( const String& rDel ) const
{
sal_Unicode nCode = 0;
xub_StrLen i = 0;
if ( nCount >= 2 )
{
while ( i<nCount )
{
if ( rDel == theDelTab.GetToken( i, cSep ) )
{
nCode = (sal_Unicode) theDelTab.GetToken( i+1, cSep ).ToInt32();
i = nCount;
}
else
i += 2;
}
}
return nCode;
}
//------------------------------------------------------------------------
String ScDelimiterTable::GetDelimiter( sal_Unicode nCode ) const
{
String aStrDel;
xub_StrLen i = 0;
if ( nCount >= 2 )
{
while ( i<nCount )
{
if ( nCode == (sal_Unicode) theDelTab.GetToken( i+1, cSep ).ToInt32() )
{
aStrDel = theDelTab.GetToken( i, cSep );
i = nCount;
}
else
i += 2;
}
}
return aStrDel;
}
//========================================================================
// ScImportOptionsDlg
//========================================================================
ScImportOptionsDlg::ScImportOptionsDlg(
Window* pParent,
BOOL bAscii,
const ScImportOptions* pOptions,
const String* pStrTitle,
BOOL bMultiByte,
BOOL bOnlyDbtoolsEncodings,
BOOL bImport )
: ModalDialog ( pParent, ScResId( RID_SCDLG_IMPORTOPT ) ),
aBtnOk ( this, ScResId( BTN_OK ) ),
aBtnCancel ( this, ScResId( BTN_CANCEL ) ),
aBtnHelp ( this, ScResId( BTN_HELP ) ),
aFtFieldSep ( this, ScResId( FT_FIELDSEP ) ),
aEdFieldSep ( this, ScResId( ED_FIELDSEP ) ),
aFtTextSep ( this, ScResId( FT_TEXTSEP ) ),
aEdTextSep ( this, ScResId( ED_TEXTSEP ) ),
aFtFont ( this, ScResId( FT_FONT ) ),
aLbFont ( this, ScResId( bAscii ? DDLB_FONT : LB_FONT ) ),
aFlFieldOpt ( this, ScResId( FL_FIELDOPT ) ),
aCbFixed ( this, ScResId( CB_FIXEDWIDTH ) ),
aCbShown ( this, ScResId( CB_SAVESHOWN ) )
{
// im Ctor-Initializer nicht moeglich (MSC kann das nicht):
pFieldSepTab = new ScDelimiterTable( String(ScResId(SCSTR_FIELDSEP)) );
pTextSepTab = new ScDelimiterTable( String(ScResId(SCSTR_TEXTSEP)) );
String aStr = pFieldSepTab->FirstDel();
sal_Unicode nCode;
while ( aStr.Len() > 0 )
{
aEdFieldSep.InsertEntry( aStr );
aStr = pFieldSepTab->NextDel();
}
aStr = pTextSepTab->FirstDel();
while ( aStr.Len() > 0 )
{
aEdTextSep.InsertEntry( aStr );
aStr = pTextSepTab->NextDel();
}
aEdFieldSep.SetText( aEdFieldSep.GetEntry(0) );
aEdTextSep.SetText( aEdTextSep.GetEntry(0) );
if ( bOnlyDbtoolsEncodings )
{ //!TODO: Unicode and MultiByte would need work in each filter
// Think of field lengths in dBase export
if ( bMultiByte )
aLbFont.FillFromDbTextEncodingMap( bImport, RTL_TEXTENCODING_INFO_UNICODE );
else
aLbFont.FillFromDbTextEncodingMap( bImport, RTL_TEXTENCODING_INFO_UNICODE |
RTL_TEXTENCODING_INFO_MULTIBYTE );
}
else if ( !bAscii )
{ //!TODO: Unicode would need work in each filter
if ( bMultiByte )
aLbFont.FillFromTextEncodingTable( bImport, RTL_TEXTENCODING_INFO_UNICODE );
else
aLbFont.FillFromTextEncodingTable( bImport, RTL_TEXTENCODING_INFO_UNICODE |
RTL_TEXTENCODING_INFO_MULTIBYTE );
}
else
{
if ( pOptions )
{
nCode = pOptions->nFieldSepCode;
aStr = pFieldSepTab->GetDelimiter( nCode );
if ( !aStr.Len() )
aEdFieldSep.SetText( String((sal_Unicode)nCode) );
else
aEdFieldSep.SetText( aStr );
nCode = pOptions->nTextSepCode;
aStr = pTextSepTab->GetDelimiter( nCode );
if ( !aStr.Len() )
aEdTextSep.SetText( String((sal_Unicode)nCode) );
else
aEdTextSep.SetText( aStr );
}
// all encodings allowed, even Unicode
aLbFont.FillFromTextEncodingTable( bImport );
}
if( bAscii )
{
Size aWinSize( GetSizePixel() );
aWinSize.Height() = aCbFixed.GetPosPixel().Y() + aCbFixed.GetSizePixel().Height();
Size aDiffSize( LogicToPixel( Size( 0, 6 ), MapMode( MAP_APPFONT ) ) );
aWinSize.Height() += aDiffSize.Height();
SetSizePixel( aWinSize );
aCbFixed.Show();
aCbFixed.SetClickHdl( LINK( this, ScImportOptionsDlg, FixedWidthHdl ) );
aCbFixed.Check( FALSE );
aCbShown.Show();
aCbShown.Check( TRUE );
}
else
{
aFlFieldOpt.SetText( aFtFont.GetText() );
aFtFieldSep.Hide();
aFtTextSep.Hide();
aFtFont.Hide();
aEdFieldSep.Hide();
aEdTextSep.Hide();
aCbFixed.Hide();
aCbShown.Hide();
aLbFont.GrabFocus();
aLbFont.SetDoubleClickHdl( LINK( this, ScImportOptionsDlg, DoubleClickHdl ) );
}
aLbFont.SelectTextEncoding( pOptions ? pOptions->eCharSet :
gsl_getSystemTextEncoding() );
// optionaler Titel:
if ( pStrTitle )
SetText( *pStrTitle );
FreeResource();
}
//------------------------------------------------------------------------
__EXPORT ScImportOptionsDlg::~ScImportOptionsDlg()
{
delete pFieldSepTab;
delete pTextSepTab;
}
//------------------------------------------------------------------------
void ScImportOptionsDlg::GetImportOptions( ScImportOptions& rOptions ) const
{
rOptions.SetTextEncoding( aLbFont.GetSelectTextEncoding() );
if ( aCbFixed.IsVisible() )
{
rOptions.nFieldSepCode = GetCodeFromCombo( aEdFieldSep );
rOptions.nTextSepCode = GetCodeFromCombo( aEdTextSep );
rOptions.bFixedWidth = aCbFixed.IsChecked();
rOptions.bSaveAsShown = aCbShown.IsChecked();
}
}
//------------------------------------------------------------------------
USHORT ScImportOptionsDlg::GetCodeFromCombo( const ComboBox& rEd ) const
{
ScDelimiterTable* pTab;
String aStr( rEd.GetText() );
USHORT nCode;
if ( &rEd == &aEdTextSep )
pTab = pTextSepTab;
else
pTab = pFieldSepTab;
if ( !aStr.Len() )
{
nCode = 0; // kein Trennzeichen
}
else
{
nCode = pTab->GetCode( aStr );
if ( nCode == 0 )
nCode = (USHORT)aStr.GetChar(0);
}
return nCode;
}
//------------------------------------------------------------------------
IMPL_LINK( ScImportOptionsDlg, FixedWidthHdl, CheckBox*, pCheckBox )
{
if( pCheckBox == &aCbFixed )
{
BOOL bEnable = !aCbFixed.IsChecked();
aFtFieldSep.Enable( bEnable );
aEdFieldSep.Enable( bEnable );
aFtTextSep.Enable( bEnable );
aEdTextSep.Enable( bEnable );
aCbShown.Enable( bEnable );
}
return 0;
}
IMPL_LINK( ScImportOptionsDlg, DoubleClickHdl, ListBox*, pLb )
{
if ( pLb == &aLbFont )
{
aBtnOk.Click();
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012, Ben Noordhuis <info@bnoordhuis.nl>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include "node.h" // Picks up BUILDING_NODE_EXTENSION on Windows, see #30.
#include "compat-inl.h"
#include "uv.h"
#include "v8-profiler.h"
#include "v8.h"
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <assert.h>
namespace {
static const int kMaxPath = 4096;
static const int kForkFlag = 1;
static const int kSignalFlag = 2;
inline bool WriteSnapshot(v8::Isolate* isolate, const char* filename);
inline bool WriteSnapshotHelper(v8::Isolate* isolate, const char* filename);
inline void InvokeCallback(const char* filename);
inline void PlatformInit(v8::Isolate* isolate, int flags);
inline void RandomSnapshotFilename(char* buffer, size_t size);
static ::compat::Persistent<v8::Function> on_complete_callback;
} // namespace anonymous
#ifdef _WIN32
#include "heapdump-win32.h"
#else
#include "heapdump-posix.h"
#endif
namespace {
using v8::Context;
using v8::Function;
using v8::FunctionTemplate;
using v8::Handle;
using v8::HandleScope;
using v8::HeapSnapshot;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::OutputStream;
using v8::Persistent;
using v8::String;
using v8::V8;
using v8::Value;
namespace C = ::compat;
class FileOutputStream : public OutputStream {
public:
FileOutputStream(FILE* stream) : stream_(stream) {}
virtual int GetChunkSize() {
return 65536; // big chunks == faster
}
virtual void EndOfStream() {}
virtual WriteResult WriteAsciiChunk(char* data, int size) {
const size_t len = static_cast<size_t>(size);
size_t off = 0;
while (off < len && !feof(stream_) && !ferror(stream_))
off += fwrite(data + off, 1, len - off, stream_);
return off == len ? kContinue : kAbort;
}
private:
FILE* stream_;
};
inline C::ReturnType WriteSnapshot(const C::ArgumentType& args) {
C::ReturnableHandleScope handle_scope(args);
Isolate* const isolate = args.GetIsolate();
Local<Value> maybe_function = args[0];
if (1 < args.Length()) {
maybe_function = args[1];
}
if (maybe_function->IsFunction()) {
Local<Function> function = maybe_function.As<Function>();
on_complete_callback.Reset(isolate, function);
}
char filename[kMaxPath];
if (args[0]->IsString()) {
String::Utf8Value filename_string(args[0]);
snprintf(filename, sizeof(filename), "%s", *filename_string);
} else {
RandomSnapshotFilename(filename, sizeof(filename));
}
// Throwing on error is too disruptive, just return a boolean indicating
// success.
const bool success = WriteSnapshot(isolate, filename);
return handle_scope.Return(success);
}
inline bool WriteSnapshotHelper(Isolate* isolate, const char* filename) {
FILE* fp = fopen(filename, "w");
if (fp == NULL) return false;
const HeapSnapshot* const snap = C::HeapProfiler::TakeHeapSnapshot(isolate);
FileOutputStream stream(fp);
snap->Serialize(&stream, HeapSnapshot::kJSON);
fclose(fp);
// Only necessary on Windows because the snapshot is created inside the
// main process. On UNIX platforms, it's created from a fork that exits
// after writing the snapshot to disk.
#if defined(_WIN32)
const_cast<HeapSnapshot*>(snap)->Delete();
#endif
return true;
}
inline void InvokeCallback(const char* filename) {
if (on_complete_callback.IsEmpty()) return;
Isolate* isolate = Isolate::GetCurrent();
C::HandleScope handle_scope(isolate);
Local<Function> callback = on_complete_callback.ToLocal(isolate);
Local<Value> argv[] = {C::Null(isolate),
C::String::NewFromUtf8(isolate, filename)};
const int argc = sizeof(argv) / sizeof(*argv);
#if defined(COMPAT_NODE_VERSION_10)
node::MakeCallback(Context::GetCurrent()->Global(), callback, argc, argv);
#elif defined(COMPAT_NODE_VERSION_12)
node::MakeCallback(isolate, isolate->GetCurrentContext()->Global(), callback,
argc, argv);
#else
#error "Unsupported node.js version."
#endif
}
inline void RandomSnapshotFilename(char* buffer, size_t size) {
const uint64_t now = uv_hrtime();
const unsigned long sec = static_cast<unsigned long>(now / 1000000);
const unsigned long usec = static_cast<unsigned long>(now % 1000000);
snprintf(buffer, size, "heapdump-%lu.%lu.heapsnapshot", sec, usec);
}
inline C::ReturnType Configure(const C::ArgumentType& args) {
C::ReturnableHandleScope handle_scope(args);
PlatformInit(args.GetIsolate(), args[0]->IntegerValue());
return handle_scope.Return();
}
inline void Initialize(Local<Object> binding) {
Isolate* const isolate = Isolate::GetCurrent();
binding->Set(C::String::NewFromUtf8(isolate, "kForkFlag"),
C::Integer::New(isolate, kForkFlag));
binding->Set(C::String::NewFromUtf8(isolate, "kSignalFlag"),
C::Integer::New(isolate, kSignalFlag));
binding->Set(C::String::NewFromUtf8(isolate, "configure"),
C::FunctionTemplate::New(isolate, Configure)->GetFunction());
binding->Set(C::String::NewFromUtf8(isolate, "writeSnapshot"),
C::FunctionTemplate::New(isolate, WriteSnapshot)->GetFunction());
}
NODE_MODULE(addon, Initialize)
} // namespace anonymous
<commit_msg>src: fix benign C4244 VS warning<commit_after>// Copyright (c) 2012, Ben Noordhuis <info@bnoordhuis.nl>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include "node.h" // Picks up BUILDING_NODE_EXTENSION on Windows, see #30.
#include "compat-inl.h"
#include "uv.h"
#include "v8-profiler.h"
#include "v8.h"
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <assert.h>
namespace {
static const int kMaxPath = 4096;
static const int kForkFlag = 1;
static const int kSignalFlag = 2;
inline bool WriteSnapshot(v8::Isolate* isolate, const char* filename);
inline bool WriteSnapshotHelper(v8::Isolate* isolate, const char* filename);
inline void InvokeCallback(const char* filename);
inline void PlatformInit(v8::Isolate* isolate, int flags);
inline void RandomSnapshotFilename(char* buffer, size_t size);
static ::compat::Persistent<v8::Function> on_complete_callback;
} // namespace anonymous
#ifdef _WIN32
#include "heapdump-win32.h"
#else
#include "heapdump-posix.h"
#endif
namespace {
using v8::Context;
using v8::Function;
using v8::FunctionTemplate;
using v8::Handle;
using v8::HandleScope;
using v8::HeapSnapshot;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::OutputStream;
using v8::Persistent;
using v8::String;
using v8::V8;
using v8::Value;
namespace C = ::compat;
class FileOutputStream : public OutputStream {
public:
FileOutputStream(FILE* stream) : stream_(stream) {}
virtual int GetChunkSize() {
return 65536; // big chunks == faster
}
virtual void EndOfStream() {}
virtual WriteResult WriteAsciiChunk(char* data, int size) {
const size_t len = static_cast<size_t>(size);
size_t off = 0;
while (off < len && !feof(stream_) && !ferror(stream_))
off += fwrite(data + off, 1, len - off, stream_);
return off == len ? kContinue : kAbort;
}
private:
FILE* stream_;
};
inline C::ReturnType WriteSnapshot(const C::ArgumentType& args) {
C::ReturnableHandleScope handle_scope(args);
Isolate* const isolate = args.GetIsolate();
Local<Value> maybe_function = args[0];
if (1 < args.Length()) {
maybe_function = args[1];
}
if (maybe_function->IsFunction()) {
Local<Function> function = maybe_function.As<Function>();
on_complete_callback.Reset(isolate, function);
}
char filename[kMaxPath];
if (args[0]->IsString()) {
String::Utf8Value filename_string(args[0]);
snprintf(filename, sizeof(filename), "%s", *filename_string);
} else {
RandomSnapshotFilename(filename, sizeof(filename));
}
// Throwing on error is too disruptive, just return a boolean indicating
// success.
const bool success = WriteSnapshot(isolate, filename);
return handle_scope.Return(success);
}
inline bool WriteSnapshotHelper(Isolate* isolate, const char* filename) {
FILE* fp = fopen(filename, "w");
if (fp == NULL) return false;
const HeapSnapshot* const snap = C::HeapProfiler::TakeHeapSnapshot(isolate);
FileOutputStream stream(fp);
snap->Serialize(&stream, HeapSnapshot::kJSON);
fclose(fp);
// Only necessary on Windows because the snapshot is created inside the
// main process. On UNIX platforms, it's created from a fork that exits
// after writing the snapshot to disk.
#if defined(_WIN32)
const_cast<HeapSnapshot*>(snap)->Delete();
#endif
return true;
}
inline void InvokeCallback(const char* filename) {
if (on_complete_callback.IsEmpty()) return;
Isolate* isolate = Isolate::GetCurrent();
C::HandleScope handle_scope(isolate);
Local<Function> callback = on_complete_callback.ToLocal(isolate);
Local<Value> argv[] = {C::Null(isolate),
C::String::NewFromUtf8(isolate, filename)};
const int argc = sizeof(argv) / sizeof(*argv);
#if defined(COMPAT_NODE_VERSION_10)
node::MakeCallback(Context::GetCurrent()->Global(), callback, argc, argv);
#elif defined(COMPAT_NODE_VERSION_12)
node::MakeCallback(isolate, isolate->GetCurrentContext()->Global(), callback,
argc, argv);
#else
#error "Unsupported node.js version."
#endif
}
inline void RandomSnapshotFilename(char* buffer, size_t size) {
const uint64_t now = uv_hrtime();
const unsigned long sec = static_cast<unsigned long>(now / 1000000);
const unsigned long usec = static_cast<unsigned long>(now % 1000000);
snprintf(buffer, size, "heapdump-%lu.%lu.heapsnapshot", sec, usec);
}
inline C::ReturnType Configure(const C::ArgumentType& args) {
C::ReturnableHandleScope handle_scope(args);
PlatformInit(args.GetIsolate(), args[0]->Int32Value());
return handle_scope.Return();
}
inline void Initialize(Local<Object> binding) {
Isolate* const isolate = Isolate::GetCurrent();
binding->Set(C::String::NewFromUtf8(isolate, "kForkFlag"),
C::Integer::New(isolate, kForkFlag));
binding->Set(C::String::NewFromUtf8(isolate, "kSignalFlag"),
C::Integer::New(isolate, kSignalFlag));
binding->Set(C::String::NewFromUtf8(isolate, "configure"),
C::FunctionTemplate::New(isolate, Configure)->GetFunction());
binding->Set(C::String::NewFromUtf8(isolate, "writeSnapshot"),
C::FunctionTemplate::New(isolate, WriteSnapshot)->GetFunction());
}
NODE_MODULE(addon, Initialize)
} // namespace anonymous
<|endoftext|>
|
<commit_before>#include "all_defines.hpp"
#include "history.hpp"
#include "processes.hpp"
#include "bytecodes.hpp"
#include "reader.hpp"
#include "types.hpp"
void History::entry(void) {
if(known_type<Closure>(stack[0])->kontinuation) {
/*called a continuation: remove tail calls using this continuation*/
known_type<Closure>(stack[0])->kontinuation->clear();
} else {
/*called an ordinary function: add to tail calls on current continuation*/
if(stack.size() < 2) return;
Closure* pkclos = maybe_type<Closure>(stack[1]);
if(!pkclos) return;
Closure& kclos = *pkclos;
if(!kclos.kontinuation) return;
InnerRing& inner_ring = *kclos.kontinuation;
inner_ring.push_front(Item());
// ?? for some reason, after insertion capacity must be set again
inner_ring.repeat_set_capacity();
Item& it = inner_ring.front();
it.resize(stack.size() - 1, Object::nil());
it[0] = stack[0];
/*skip stack[1] in the debug dump*/
for(size_t i = 1; i < (stack.size() - 1); ++i) {
it[i] = stack[i + 1];
}
}
}
// returned list is of type
// ((functon arg1 ... argn) ...)
void History::to_list(Process & proc) {
ProcessStack & s = proc.stack;
size_t count = 0; // number of elements in the history
Closure* pkclos;
pkclos = maybe_type<Closure>(stack[1]);
if(pkclos && pkclos->kontinuation) goto outer_loop;
pkclos = maybe_type<Closure>(stack[0]);
if(pkclos && pkclos->kontinuation) goto outer_loop;
goto end_outer_loop;
outer_loop:
/*go through the kontinuation*/
{ InnerRing& ring = *pkclos->kontinuation;
for(InnerRing::iterator it = ring.begin();
it != ring.end();
++it) {
Item& item = *it;
{ size_t count = 0;
for(Item::iterator it = item.begin();
it != item.end();
++it) {
proc.stack.push(*it);
++count;
}
proc.stack.push(Object::nil());
for(; count; --count) {
bytecode_cons(proc, stack);
}
}
++count;
}
}
/*search for a parent continuation*/
for(size_t i = 0; i < pkclos->size(); ++i) {
Closure* npkclos = maybe_type<Closure>((*pkclos)[i]);
if(npkclos) {
if(npkclos->kontinuation) {
pkclos = npkclos;
goto outer_loop;
}
}
}
end_outer_loop:
proc.stack.push(Object::nil());
// build the list
for (; count; --count) {
bytecode_cons(proc, proc.stack);
}
}
void History::InnerRing::traverse_references(GenericTraverser* gt) {
for(iterator it = begin(); it != end(); ++it) {
for(Item::iterator vit = it->begin(); vit != it->end(); ++vit) {
gt->traverse(*vit);
}
}
}
<commit_msg>history: moved repeat_set_capacity before element insertion, otherwise it seems to remove the vector inserted before<commit_after>#include "all_defines.hpp"
#include "history.hpp"
#include "processes.hpp"
#include "bytecodes.hpp"
#include "reader.hpp"
#include "types.hpp"
void History::entry(void) {
if(known_type<Closure>(stack[0])->kontinuation) {
/*called a continuation: remove tail calls using this continuation*/
known_type<Closure>(stack[0])->kontinuation->clear();
} else {
/*called an ordinary function: add to tail calls on current continuation*/
if(stack.size() < 2) return;
Closure* pkclos = maybe_type<Closure>(stack[1]);
if(!pkclos) return;
Closure& kclos = *pkclos;
if(!kclos.kontinuation) return;
InnerRing& inner_ring = *kclos.kontinuation;
// ?? for some reason, after insertion capacity must be set again
inner_ring.repeat_set_capacity();
inner_ring.push_front(Item());
Item& it = inner_ring.front();
it.resize(stack.size() - 1, Object::nil());
it[0] = stack[0];
/*skip stack[1] in the debug dump*/
for(size_t i = 1; i < (stack.size() - 1); ++i) {
it[i] = stack[i + 1];
}
}
}
// returned list is of type
// ((functon arg1 ... argn) ...)
void History::to_list(Process & proc) {
ProcessStack & s = proc.stack;
size_t count = 0; // number of elements in the history
Closure* pkclos;
pkclos = maybe_type<Closure>(stack[1]);
if(pkclos && pkclos->kontinuation) goto outer_loop;
pkclos = maybe_type<Closure>(stack[0]);
if(pkclos && pkclos->kontinuation) goto outer_loop;
goto end_outer_loop;
outer_loop:
/*go through the kontinuation*/
{ InnerRing& ring = *pkclos->kontinuation;
for(InnerRing::iterator it = ring.begin();
it != ring.end();
++it) {
Item& item = *it;
{ size_t count = 0;
for(Item::iterator it = item.begin();
it != item.end();
++it) {
proc.stack.push(*it);
++count;
}
proc.stack.push(Object::nil());
for(; count; --count) {
bytecode_cons(proc, stack);
}
}
++count;
}
}
/*search for a parent continuation*/
for(size_t i = 0; i < pkclos->size(); ++i) {
Closure* npkclos = maybe_type<Closure>((*pkclos)[i]);
if(npkclos) {
if(npkclos->kontinuation) {
pkclos = npkclos;
goto outer_loop;
}
}
}
end_outer_loop:
proc.stack.push(Object::nil());
// build the list
for (; count; --count) {
bytecode_cons(proc, proc.stack);
}
}
void History::InnerRing::traverse_references(GenericTraverser* gt) {
for(iterator it = begin(); it != end(); ++it) {
for(Item::iterator vit = it->begin(); vit != it->end(); ++vit) {
gt->traverse(*vit);
}
}
}
<|endoftext|>
|
<commit_before>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQNotes.cpp,v $
// $Revision: 1.6 $
// $Name: $
// $Author: shoops $
// $Date: 2010/08/12 23:19:13 $
// End CVS Header
// Copyright (C) 2010 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
/*
* CQNotes.cpp
*
* Created on: Aug 11, 2010
* Author: shoops
*/
#include <QWebFrame>
#include <QProcess>
#include "CQNotes.h"
#include "CQIcons.h"
#include "CQMessageBox.h"
#include "qtUtilities.h"
#include "model/CModelValue.h"
#include "model/CReaction.h"
#include "function/CFunction.h"
#include "report/CKeyFactory.h"
#include "copasi/report/CCopasiRootContainer.h"
#include "commandline/CConfigurationFile.h"
CQNotes::CQNotes(QWidget* parent, const char* name) :
CopasiWidget(parent, name)
{
setupUi(this);
mEditMode = false;
mpEdit->hide();
mpWebView->show();
mpBtnToggleEdit->setIcon(CQIcons::getIcon(CQIcons::Edit));
mpWebView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
}
CQNotes::~CQNotes()
{}
// virtual
bool CQNotes::update(ListViews::ObjectType /* objectType */, ListViews::Action action, const std::string & key)
{
if (key == mKey &&
action == ListViews::CHANGE)
{
load();
}
return true;
}
// virtual
bool CQNotes::leave()
{
mpBtnToggleEdit->setFocus();
save();
return true;
}
// virtual
bool CQNotes::enterProtected()
{
load();
return true;
}
void CQNotes::slotToggleMode()
{
mEditMode = !mEditMode;
if (mEditMode)
{
mpWebView->hide();
mpEdit->show();
mpBtnToggleEdit->setIcon(CQIcons::getIcon(CQIcons::View));
}
else
{
save();
load();
mpEdit->hide();
mpWebView->show();
mpBtnToggleEdit->setIcon(CQIcons::getIcon(CQIcons::Edit));
}
}
void CQNotes::load()
{
if (mpObject != NULL)
{
const std::string * pNotes = NULL;
if (dynamic_cast< CModelEntity * >(mpObject))
pNotes =
&dynamic_cast< CModelEntity * >(mpObject)->getNotes();
else if (dynamic_cast< CReaction * >(mpObject))
pNotes =
&dynamic_cast< CReaction * >(mpObject)->getNotes();
else if (dynamic_cast< CFunction * >(mpObject))
pNotes =
&dynamic_cast< CFunction * >(mpObject)->getNotes();
if (pNotes && *pNotes != "")
{
// The notes are UTF8 encoded however the html does not specify an encoding
// thus Qt uses locale settings.
mpWebView->setHtml(FROM_UTF8(*pNotes));
mpEdit->setPlainText(FROM_UTF8(*pNotes));
}
}
mChanged = false;
return;
}
void CQNotes::save()
{
// TODO CRITICAL We need to validate that we have proper XML.
// We can use QXmlSimpleReader for doing this as we are only interested the fact that
// we have valid XML.
if (mpObject != NULL)
{
const std::string * pNotes = NULL;
if (dynamic_cast< CModelEntity * >(mpObject))
pNotes =
&static_cast< CModelEntity * >(mpObject)->getNotes();
else if (dynamic_cast< CReaction * >(mpObject))
pNotes =
&static_cast< CReaction * >(mpObject)->getNotes();
else if (dynamic_cast< CFunction * >(mpObject))
pNotes =
&static_cast< CFunction * >(mpObject)->getNotes();
if (pNotes &&
mpEdit->toPlainText() != FROM_UTF8(*pNotes))
{
if (dynamic_cast< CModelEntity * >(mpObject))
static_cast< CModelEntity * >(mpObject)->setNotes(TO_UTF8(mpEdit->toPlainText()));
/*
else if (dynamic_cast< CReaction * >(mpObject))
static_cast< CReaction * >(mpObject)->setNotes(TO_UTF8(mpEdit->toPlainText()));
else if (dynamic_cast< CFunction * >(mpObject))
static_cast< CFunction * >(mpObject)->setNotes(TO_UTF8(mpEdit->toPlainText()));
*/
mChanged = true;
}
}
if (mChanged)
{
if (mpDataModel != NULL)
{
mpDataModel->changed();
}
protectedNotify(ListViews::MODEL, ListViews::CHANGE, mKey);
}
mChanged = false;
return;
}
void CQNotes::slotOpenUrl(const QUrl & url)
{
QString Commandline = FROM_UTF8(CCopasiRootContainer::getConfiguration()->getWebBrowser());
if (Commandline == "")
{
#ifdef Q_WS_MAC
Commandline = "open %1";
#else
# ifdef Q_WS_WIN
Commandline = "cmd /c start %1";
# else
CQMessageBox::critical(this, "Unable to open link",
"COPASI requires you to specify an application for opening URLs for links to work.\n\nPlease go to the preferences and set an appropriate application in the format:\n command [options] %1.");
return;
# endif // Q_WS_WIN
#endif // Q_WS_MAC
CCopasiRootContainer::getConfiguration()->setWebBrowser(TO_UTF8(Commandline));
}
#ifdef Q_WS_WIN
if (Commandline == "cmd /c start %1")
{
if (QProcess::execute(Commandline.arg(url.toString())))
{
CQMessageBox::critical(this, "Unable to open link",
"COPASI requires you to specify an application for opening URLs for links to work.\n\nPlease go to the preferences and set an appropriate application in the format:\n application [options] %1");
}
return;
}
#endif // Q_WS_WIN
if (!QProcess::startDetached(Commandline.arg(url.toString())))
{
CQMessageBox::critical(this, "Unable to open link",
"COPASI requires you to specify an application for opening URLs for links to work.\n\nPlease go to the preferences and set an appropriate application in the format:\n application [options] %1");
}
return;
}
<commit_msg>Corrected typo.<commit_after>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQNotes.cpp,v $
// $Revision: 1.7 $
// $Name: $
// $Author: shoops $
// $Date: 2010/08/12 23:28:25 $
// End CVS Header
// Copyright (C) 2010 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
/*
* CQNotes.cpp
*
* Created on: Aug 11, 2010
* Author: shoops
*/
#include <QWebFrame>
#include <QProcess>
#include "CQNotes.h"
#include "CQIcons.h"
#include "CQMessageBox.h"
#include "qtUtilities.h"
#include "model/CModelValue.h"
#include "model/CReaction.h"
#include "function/CFunction.h"
#include "report/CKeyFactory.h"
#include "copasi/report/CCopasiRootContainer.h"
#include "commandline/CConfigurationFile.h"
CQNotes::CQNotes(QWidget* parent, const char* name) :
CopasiWidget(parent, name)
{
setupUi(this);
mEditMode = false;
mpEdit->hide();
mpWebView->show();
mpBtnToggleEdit->setIcon(CQIcons::getIcon(CQIcons::Edit));
mpWebView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
}
CQNotes::~CQNotes()
{}
// virtual
bool CQNotes::update(ListViews::ObjectType /* objectType */, ListViews::Action action, const std::string & key)
{
if (key == mKey &&
action == ListViews::CHANGE)
{
load();
}
return true;
}
// virtual
bool CQNotes::leave()
{
mpBtnToggleEdit->setFocus();
save();
return true;
}
// virtual
bool CQNotes::enterProtected()
{
load();
return true;
}
void CQNotes::slotToggleMode()
{
mEditMode = !mEditMode;
if (mEditMode)
{
mpWebView->hide();
mpEdit->show();
mpBtnToggleEdit->setIcon(CQIcons::getIcon(CQIcons::View));
}
else
{
save();
load();
mpEdit->hide();
mpWebView->show();
mpBtnToggleEdit->setIcon(CQIcons::getIcon(CQIcons::Edit));
}
}
void CQNotes::load()
{
if (mpObject != NULL)
{
const std::string * pNotes = NULL;
if (dynamic_cast< CModelEntity * >(mpObject))
pNotes =
&dynamic_cast< CModelEntity * >(mpObject)->getNotes();
else if (dynamic_cast< CReaction * >(mpObject))
pNotes =
&dynamic_cast< CReaction * >(mpObject)->getNotes();
else if (dynamic_cast< CFunction * >(mpObject))
pNotes =
&dynamic_cast< CFunction * >(mpObject)->getNotes();
if (pNotes && *pNotes != "")
{
// The notes are UTF8 encoded however the html does not specify an encoding
// thus Qt uses locale settings.
mpWebView->setHtml(FROM_UTF8(*pNotes));
mpEdit->setPlainText(FROM_UTF8(*pNotes));
}
}
mChanged = false;
return;
}
void CQNotes::save()
{
// TODO CRITICAL We need to validate that we have proper XML.
// We can use QXmlSimpleReader for doing this as we are only interested the fact that
// we have valid XML.
if (mpObject != NULL)
{
const std::string * pNotes = NULL;
if (dynamic_cast< CModelEntity * >(mpObject))
pNotes =
&static_cast< CModelEntity * >(mpObject)->getNotes();
else if (dynamic_cast< CReaction * >(mpObject))
pNotes =
&static_cast< CReaction * >(mpObject)->getNotes();
else if (dynamic_cast< CFunction * >(mpObject))
pNotes =
&static_cast< CFunction * >(mpObject)->getNotes();
if (pNotes &&
mpEdit->toPlainText() != FROM_UTF8(*pNotes))
{
if (dynamic_cast< CModelEntity * >(mpObject))
static_cast< CModelEntity * >(mpObject)->setNotes(TO_UTF8(mpEdit->toPlainText()));
/*
else if (dynamic_cast< CReaction * >(mpObject))
static_cast< CReaction * >(mpObject)->setNotes(TO_UTF8(mpEdit->toPlainText()));
else if (dynamic_cast< CFunction * >(mpObject))
static_cast< CFunction * >(mpObject)->setNotes(TO_UTF8(mpEdit->toPlainText()));
*/
mChanged = true;
}
}
if (mChanged)
{
if (mpDataModel != NULL)
{
mpDataModel->changed();
}
protectedNotify(ListViews::MODEL, ListViews::CHANGE, mKey);
}
mChanged = false;
return;
}
void CQNotes::slotOpenUrl(const QUrl & url)
{
QString Commandline = FROM_UTF8(CCopasiRootContainer::getConfiguration()->getWebBrowser());
if (Commandline == "")
{
#ifdef Q_WS_MAC
Commandline = "open %1";
#else
# ifdef Q_WS_WIN
Commandline = "cmd /c start %1";
# else
CQMessageBox::critical(this, "Unable to open link",
"COPASI requires you to specify an application for opening URLs for links to work.\n\nPlease go to the preferences and set an appropriate application in the format:\n command [options] %1");
return;
# endif // Q_WS_WIN
#endif // Q_WS_MAC
CCopasiRootContainer::getConfiguration()->setWebBrowser(TO_UTF8(Commandline));
}
#ifdef Q_WS_WIN
if (Commandline == "cmd /c start %1")
{
if (QProcess::execute(Commandline.arg(url.toString())))
{
CQMessageBox::critical(this, "Unable to open link",
"COPASI requires you to specify an application for opening URLs for links to work.\n\nPlease go to the preferences and set an appropriate application in the format:\n application [options] %1");
}
return;
}
#endif // Q_WS_WIN
if (!QProcess::startDetached(Commandline.arg(url.toString())))
{
CQMessageBox::critical(this, "Unable to open link",
"COPASI requires you to specify an application for opening URLs for links to work.\n\nPlease go to the preferences and set an appropriate application in the format:\n application [options] %1");
}
return;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2015, Novartis Institutes for BioMedical Research 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 Novartis Institutes for BioMedical Research 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 <RDGeneral/RDLog.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/FileParsers/MolSupplier.h>
#include <GraphMol/FilterCatalog/FilterCatalog.h>
#include <iostream>
#include <map>
#include <algorithm>
#include <boost/foreach.hpp>
using namespace RDKit;
using namespace std;
struct IntPair {
int first;
int second;
};
template<class T>
void dump(std::string name, const T &v) {
std::cerr << name << " = { " << std::endl;
for (size_t i=0; i<v.size(); ++i) {
std::cerr << "\t" << v[i].first << "," << v[i].second << "}," << std::endl;;
}
std::cerr << "}" << std::endl;
}
bool check(MatchVectType v, MatchVectType match) {
dump("v", v);
dump("match", match);
for (size_t i=0; i<v.size(); ++i) {
if (v[i].first != match[i].first) {
return false;
}
if (v[i].second != match[i].second) {
return false;
}
}
return true;
}
void testFilterCatalog() {
BOOST_LOG(rdInfoLog) << "-----------------------\n Testing sf.net issue 2313979: aromaticity assignment hangs " << std::endl;
{
std::string pathName=getenv("RDBASE");
pathName += "/Code/GraphMol/test_data/";
SmilesMolSupplier suppl(pathName+"pains.smi");
FilterCatalogParams params;
params.addCatalog(FilterCatalogParams::PAINS_A);
params.addCatalog(FilterCatalogParams::PAINS_B);
params.addCatalog(FilterCatalogParams::PAINS_C);
FilterCatalog catalog(params);
boost::scoped_ptr<ROMol> mol;
const IntPair match1[10] = {{0,23},{1,22},{2,20},{3,19},{4,25},{5,24},
{6,18},{7,17},{8,16},{9,21}};
MatchVectType matchvec1;
for (int i=0; i<10; ++i)
matchvec1.push_back(std::make_pair(match1[i].first,
match1[i].second));
const IntPair match2[13] = {{0,11},{1,12},{2,13},{3,14},{4,15},{5,10},
{6,9},{7,8},{8,7},{9,6},{10,5},{11,17},{12,16}};
MatchVectType matchvec2;
for (int i=0; i<13; ++i)
matchvec2.push_back(std::make_pair(match2[i].first,
match2[i].second));
const IntPair match3[12] = {{0,0},{1,1},{2,2},{3,4},{4,5},{5,6},{6,7},
{7,8},{8,9},{9,14},{10,15},{11,16}};
MatchVectType matchvec3;
for (int i=0; i<12; ++i)
matchvec3.push_back(std::make_pair(match3[i].first,
match3[i].second));
int count = 0;
while(!suppl.atEnd()){
mol.reset(suppl.next());
std::string name = mol->getProp<std::string>(common_properties::_Name);
TEST_ASSERT(mol.get());
if (catalog.hasMatch(*mol)) {
std::cerr << "Warning: molecule failed filter " << std::endl;
}
// More detailed
FilterCatalog::CONST_SENTRY entry = catalog.getFirstMatch(*mol);
if (entry) {
std::cerr << "Warning: molecule failed filter: reason " <<
entry->getDescription() << std::endl;
switch(count) {
case 0: TEST_ASSERT(entry->getDescription() == "hzone_phenol_A(479)"); break;
case 1: TEST_ASSERT(entry->getDescription() == "cyano_imine_B(17)"); break;
case 2: TEST_ASSERT(entry->getDescription() == "keto_keto_gamma(5)"); break;
}
TEST_ASSERT(entry->getDescription() == name);
// get the substructure atoms for visualization
std::vector<FilterMatch> matches;
if (entry->getFilterMatches(*mol, matches)) {
for(std::vector<FilterMatch>::const_iterator it = matches.begin();
it != matches.end(); ++it) {
// Get the FilterMatcherBase that matched
const FilterMatch & fm = (*it);
boost::shared_ptr<FilterMatcherBase> matchingFilter = \
fm.filterMatch;
// Get the matching atom indices
const MatchVectType &vect = fm.atomPairs;
switch(count) {
case 0: TEST_ASSERT(check(vect, matchvec1)); break;
case 1: TEST_ASSERT(check(vect, matchvec2)); break;
case 2: TEST_ASSERT(check(vect, matchvec3)); break;
}
// do something with these...
}
}
}
count ++;
} // end while
}
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
int main(){
RDLog::InitLogs();
//boost::logging::enable_logs("rdApp.debug");
testFilterCatalog();
return 0;
}
<commit_msg>Added more C++ tests include setProp(const char*)<commit_after>// Copyright (c) 2015, Novartis Institutes for BioMedical Research 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 Novartis Institutes for BioMedical Research 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 <RDGeneral/RDLog.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/FileParsers/MolSupplier.h>
#include <GraphMol/FilterCatalog/FilterCatalog.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <iostream>
#include <map>
#include <algorithm>
#include <boost/foreach.hpp>
using namespace RDKit;
using namespace std;
struct IntPair {
int first;
int second;
};
template<class T>
void dump(std::string name, const T &v) {
std::cerr << name << " = { " << std::endl;
for (size_t i=0; i<v.size(); ++i) {
std::cerr << "\t" << v[i].first << "," << v[i].second << "}," << std::endl;;
}
std::cerr << "}" << std::endl;
}
bool check(MatchVectType v, MatchVectType match) {
dump("v", v);
dump("match", match);
for (size_t i=0; i<v.size(); ++i) {
if (v[i].first != match[i].first) {
return false;
}
if (v[i].second != match[i].second) {
return false;
}
}
return true;
}
void testFilterCatalog() {
BOOST_LOG(rdInfoLog) << "-----------------------\n Testing sf.net issue 2313979: aromaticity assignment hangs " << std::endl;
{
std::string pathName=getenv("RDBASE");
pathName += "/Code/GraphMol/test_data/";
SmilesMolSupplier suppl(pathName+"pains.smi");
FilterCatalogParams params;
params.addCatalog(FilterCatalogParams::PAINS_A);
params.addCatalog(FilterCatalogParams::PAINS_B);
params.addCatalog(FilterCatalogParams::PAINS_C);
FilterCatalog catalog(params);
boost::scoped_ptr<ROMol> mol;
const IntPair match1[10] = {{0,23},{1,22},{2,20},{3,19},{4,25},{5,24},
{6,18},{7,17},{8,16},{9,21}};
MatchVectType matchvec1;
for (int i=0; i<10; ++i)
matchvec1.push_back(std::make_pair(match1[i].first,
match1[i].second));
const IntPair match2[13] = {{0,11},{1,12},{2,13},{3,14},{4,15},{5,10},
{6,9},{7,8},{8,7},{9,6},{10,5},{11,17},{12,16}};
MatchVectType matchvec2;
for (int i=0; i<13; ++i)
matchvec2.push_back(std::make_pair(match2[i].first,
match2[i].second));
const IntPair match3[12] = {{0,0},{1,1},{2,2},{3,4},{4,5},{5,6},{6,7},
{7,8},{8,9},{9,14},{10,15},{11,16}};
MatchVectType matchvec3;
for (int i=0; i<12; ++i)
matchvec3.push_back(std::make_pair(match3[i].first,
match3[i].second));
int count = 0;
while(!suppl.atEnd()){
mol.reset(suppl.next());
std::string name = mol->getProp<std::string>(common_properties::_Name);
TEST_ASSERT(mol.get());
if (catalog.hasMatch(*mol)) {
std::cerr << "Warning: molecule failed filter " << std::endl;
}
// More detailed
FilterCatalog::CONST_SENTRY entry = catalog.getFirstMatch(*mol);
if (entry) {
std::cerr << "Warning: molecule failed filter: reason " <<
entry->getDescription() << std::endl;
switch(count) {
case 0: TEST_ASSERT(entry->getDescription() == "hzone_phenol_A(479)"); break;
case 1: TEST_ASSERT(entry->getDescription() == "cyano_imine_B(17)"); break;
case 2: TEST_ASSERT(entry->getDescription() == "keto_keto_gamma(5)"); break;
}
TEST_ASSERT(entry->getDescription() == name);
// get the substructure atoms for visualization
std::vector<FilterMatch> matches;
if (entry->getFilterMatches(*mol, matches)) {
for(std::vector<FilterMatch>::const_iterator it = matches.begin();
it != matches.end(); ++it) {
// Get the FilterMatcherBase that matched
const FilterMatch & fm = (*it);
boost::shared_ptr<FilterMatcherBase> matchingFilter = \
fm.filterMatch;
// Get the matching atom indices
const MatchVectType &vect = fm.atomPairs;
switch(count) {
case 0: TEST_ASSERT(check(vect, matchvec1)); break;
case 1: TEST_ASSERT(check(vect, matchvec2)); break;
case 2: TEST_ASSERT(check(vect, matchvec3)); break;
}
// do something with these...
}
}
}
count ++;
} // end while
}
BOOST_LOG(rdInfoLog) << "Finished" << std::endl;
}
void testFilterCatalogEntry() {
SmartsMatcher *sm = new SmartsMatcher("Aromatic carbon chain");
boost::shared_ptr<FilterMatcherBase> matcher(sm);
TEST_ASSERT(not matcher->isValid());
const int debugParse = 0;
const bool mergeHs = true;
ROMOL_SPTR pattern(SmartsToMol("c:c:c:c:c", debugParse, mergeHs));
TEST_ASSERT(pattern.get() != 0);
sm->setPattern(pattern);
sm->setMinCount(1);
FilterCatalogEntry entry("Bar", matcher);
TEST_ASSERT(entry.getDescription() == "Bar");
TEST_ASSERT(sm->getMinCount() == 1);
TEST_ASSERT(sm->getMaxCount() == (unsigned int)-1);
entry.setDescription("Foo");
TEST_ASSERT(entry.getDescription() == "Foo");
entry.setProp("foo", "foo");
TEST_ASSERT(entry.getProp<std::string>("foo") == "foo");
entry.setProp(std::string("bar"), "bar");
TEST_ASSERT(entry.getProp<std::string>("bar") == "bar");
RWMol * newM = SmilesToMol("c1ccccc1",0,true);
TEST_ASSERT(entry.hasFilterMatch(*newM));
delete newM;
}
int main(){
RDLog::InitLogs();
//boost::logging::enable_logs("rdApp.debug");
testFilterCatalog();
testFilterCatalogEntry();
return 0;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <gtl/gtl.hpp>
namespace gtl {
/*!
\class vec2 vec2.hpp geometry/vec2.hpp
\brief 2 dimensional vector.
\ingroup base
This class is used by many other classes.
\sa vec3
*/
template <typename Type>
struct vec2 {
union {
struct {
Type x, y;
};
struct {
Type u, v;
};
Type data[2];
};
//! The default constructor.The vector will be null.
vec2()
: x(0)
, y(0)
{
}
//! Constructs an instance with initial values from \a v.
vec2(const Type v[2])
: x(v[0])
, y(v[1])
{
}
//! Constructs an instance with the initial values from \a a_x and \a a_y.
vec2(Type a_x, Type a_y)
: x(a_x)
, y(a_y)
{
}
//! Constructs an instance with initial values from \a a_vec.
vec2(const vec2<Type>& a_vec)
: x(a_vec.x)
, y(a_vec.y)
{
}
//! Set new x and y coordinates for the vector. Returns reference to self.
vec2<Type>& setValue(const Type v[2])
{
x = v[0];
y = v[1];
return *this;
}
//! Set new x and y coordinates for the vector. Returns reference to self.
vec2<Type>& setValue(Type a_x, Type a_y)
{
x = a_x;
y = a_y;
return *this;
}
//! Returns a pointer to an array containing the coordinates of the vector.
const Type* getValue() const
{
return data;
}
//! Calculates and returns the dot product of this vector with \a a_vec.
Type dot(const vec2<Type>& a_vec) const
{
return (x * a_vec.x + y * a_vec.y);
}
//! Return length of vector.
Type length() const
{
return (Type)std::sqrt(x * x + y * y);
}
//! Return squared length of vector.
Type sqrLength() const
{
return (x * x + y * y);
}
//! Normalize the vector to unit length. Return value is the original length of the vector before normalization.
Type normalize()
{
const Type magnitude = length();
if (magnitude > 0)
*this /= magnitude;
return magnitude;
}
//! Returns the normalized unit vector form of this vector.
vec2<Type> normalized() const
{
vec2<Type> v(*this);
v.normalize();
return v;
}
//! Returns the cross product of this vector with \a a_vec.
Type cross(const vec2<Type>& a_vec)
{
return (x * a_vec.y - y * a_vec.x);
}
//! Negate the vector (i.e. point it in the opposite direction).
void negate()
{
x = -x;
y = -y;
}
//! Return this vector reflected off the surface with the given normal \a N. N should be normalized.
vec2<Type> reflect(const vec2<Type>& N) const
{
const vec2<Type>& I(*this);
return I - 2 * N.dot(I) * N;
}
//! Refract this vector through a surface with the given normal \a N and ratio of indices of refraction \a eta.
vec2<Type> refract(const vec2<Type>& N, Type eta) const
{
const vec2<Type>& I(*this);
const Type k = 1.0 - eta * eta * (1.0 - N.dot(I) * N.dot(I));
return (k < 0.0) ? 0 : eta * I - (eta * N.dot(I) + std::sqrt(k)) * N;
}
//! Index operator. Returns modifiable x or y value.
Type& operator[](int i)
{
return reinterpret_cast<Type*>(this)[i];
}
//! Index operator. Returns x or y value.
const Type& operator[](int i) const
{
return reinterpret_cast<const Type*>(this)[i];
}
//! Multiply components of vector with value \a d. Returns reference to self.
vec2<Type>& operator*=(const Type d)
{
x *= d;
y *= d;
return *this;
}
//! Divides components of vector with value \a d. Returns reference to self.
vec2<Type>& operator/=(const Type d)
{
const Type inv = 1.0f / d;
x *= inv;
y *= inv;
return *this;
}
//! Multiply components of vector with value \a a_vec.
vec2<Type>& operator*=(const vec2<Type>& a_vec)
{
x *= a_vec.x;
y *= a_vec.y;
return *this;
}
//! Adds this vector and vector \a a_vec. Returns reference to self.
vec2<Type>& operator+=(const vec2<Type>& a_vec)
{
x += a_vec.x;
y += a_vec.y;
return *this;
}
//! Subtracts vector \a a_vec from this vector. Returns reference to self.
vec2<Type>& operator-=(const vec2<Type>& a_vec)
{
x -= a_vec.x;
y -= a_vec.y;
return *this;
}
//! Non-destructive negation operator.
vec2<Type> operator-() const
{
return vec2<Type>(-x, -y);
}
friend vec2<Type> operator*(const vec2<Type>& a_vec, const Type d)
{
return vec2<Type>(a_vec.x * d, a_vec.y * d);
}
friend vec2<Type> operator*(const Type d, const vec2<Type>& a_vec)
{
return a_vec * d;
}
friend vec2<Type> operator/(const vec2<Type>& a_vec, const Type d)
{
return vec2<Type>(a_vec.x / d, a_vec.y / d);
}
friend vec2<Type> operator*(const vec2<Type>& v1, const vec2<Type>& v2)
{
return vec2<Type>(v1.x * v2.x, v1.y * v2.y);
}
friend vec2<Type> operator+(const vec2<Type>& v1, const vec2<Type>& v2)
{
return vec2<Type>(v1.x + v2.x, v1.y + v2.y);
}
friend vec2<Type> operator-(const vec2<Type>& v1, const vec2<Type>& v2)
{
return vec2<Type>(v1.x - v2.x, v1.y - v2.y);
}
//! Check the two given vector for equality.
friend bool operator==(const vec2<Type>& v1, const vec2<Type>& v2)
{
return v1.x == v2.x && v1.y == v2.y;
}
//! Check the two given vector for inequality.
friend bool operator!=(const vec2<Type>& v1, const vec2<Type>& v2)
{
return !(v1 == v2);
}
//! Check for equality with given tolerance.
bool equals(const vec2<Type>& a_vec, const Type a_tolerance = 1E-2) const
{
return ((*this - a_vec).sqrLength() <= a_tolerance * a_tolerance);
}
friend std::ostream& operator<<(std::ostream& os, const vec2<Type>& vect)
{
return os << vect.x << " " << vect.y;
}
//! Largest representable vector
static vec2<Type> max()
{
return vec2<Type>(std::numeric_limits<Type>::max(), std::numeric_limits<Type>::max());
}
};
typedef vec2<int> vec2i;
typedef vec2<float> vec2f;
typedef vec2<double> vec2d;
} // namespace gtl
<commit_msg>Add a missing const<commit_after>#pragma once
#include <gtl/gtl.hpp>
namespace gtl {
/*!
\class vec2 vec2.hpp geometry/vec2.hpp
\brief 2 dimensional vector.
\ingroup base
This class is used by many other classes.
\sa vec3
*/
template <typename Type>
struct vec2 {
union {
struct {
Type x, y;
};
struct {
Type u, v;
};
Type data[2];
};
//! The default constructor.The vector will be null.
vec2()
: x(0)
, y(0)
{
}
//! Constructs an instance with initial values from \a v.
vec2(const Type v[2])
: x(v[0])
, y(v[1])
{
}
//! Constructs an instance with the initial values from \a a_x and \a a_y.
vec2(Type a_x, Type a_y)
: x(a_x)
, y(a_y)
{
}
//! Constructs an instance with initial values from \a a_vec.
vec2(const vec2<Type>& a_vec)
: x(a_vec.x)
, y(a_vec.y)
{
}
//! Set new x and y coordinates for the vector. Returns reference to self.
vec2<Type>& setValue(const Type v[2])
{
x = v[0];
y = v[1];
return *this;
}
//! Set new x and y coordinates for the vector. Returns reference to self.
vec2<Type>& setValue(Type a_x, Type a_y)
{
x = a_x;
y = a_y;
return *this;
}
//! Returns a pointer to an array containing the coordinates of the vector.
const Type* getValue() const
{
return data;
}
//! Calculates and returns the dot product of this vector with \a a_vec.
Type dot(const vec2<Type>& a_vec) const
{
return (x * a_vec.x + y * a_vec.y);
}
//! Return length of vector.
Type length() const
{
return (Type)std::sqrt(x * x + y * y);
}
//! Return squared length of vector.
Type sqrLength() const
{
return (x * x + y * y);
}
//! Normalize the vector to unit length. Return value is the original length of the vector before normalization.
Type normalize()
{
const Type magnitude = length();
if (magnitude > 0)
*this /= magnitude;
return magnitude;
}
//! Returns the normalized unit vector form of this vector.
vec2<Type> normalized() const
{
vec2<Type> v(*this);
v.normalize();
return v;
}
//! Returns the cross product of this vector with \a a_vec.
Type cross(const vec2<Type>& a_vec) const
{
return (x * a_vec.y - y * a_vec.x);
}
//! Negate the vector (i.e. point it in the opposite direction).
void negate()
{
x = -x;
y = -y;
}
//! Return this vector reflected off the surface with the given normal \a N. N should be normalized.
vec2<Type> reflect(const vec2<Type>& N) const
{
const vec2<Type>& I(*this);
return I - 2 * N.dot(I) * N;
}
//! Refract this vector through a surface with the given normal \a N and ratio of indices of refraction \a eta.
vec2<Type> refract(const vec2<Type>& N, Type eta) const
{
const vec2<Type>& I(*this);
const Type k = 1.0 - eta * eta * (1.0 - N.dot(I) * N.dot(I));
return (k < 0.0) ? 0 : eta * I - (eta * N.dot(I) + std::sqrt(k)) * N;
}
//! Index operator. Returns modifiable x or y value.
Type& operator[](int i)
{
return reinterpret_cast<Type*>(this)[i];
}
//! Index operator. Returns x or y value.
const Type& operator[](int i) const
{
return reinterpret_cast<const Type*>(this)[i];
}
//! Multiply components of vector with value \a d. Returns reference to self.
vec2<Type>& operator*=(const Type d)
{
x *= d;
y *= d;
return *this;
}
//! Divides components of vector with value \a d. Returns reference to self.
vec2<Type>& operator/=(const Type d)
{
const Type inv = 1.0f / d;
x *= inv;
y *= inv;
return *this;
}
//! Multiply components of vector with value \a a_vec.
vec2<Type>& operator*=(const vec2<Type>& a_vec)
{
x *= a_vec.x;
y *= a_vec.y;
return *this;
}
//! Adds this vector and vector \a a_vec. Returns reference to self.
vec2<Type>& operator+=(const vec2<Type>& a_vec)
{
x += a_vec.x;
y += a_vec.y;
return *this;
}
//! Subtracts vector \a a_vec from this vector. Returns reference to self.
vec2<Type>& operator-=(const vec2<Type>& a_vec)
{
x -= a_vec.x;
y -= a_vec.y;
return *this;
}
//! Non-destructive negation operator.
vec2<Type> operator-() const
{
return vec2<Type>(-x, -y);
}
friend vec2<Type> operator*(const vec2<Type>& a_vec, const Type d)
{
return vec2<Type>(a_vec.x * d, a_vec.y * d);
}
friend vec2<Type> operator*(const Type d, const vec2<Type>& a_vec)
{
return a_vec * d;
}
friend vec2<Type> operator/(const vec2<Type>& a_vec, const Type d)
{
return vec2<Type>(a_vec.x / d, a_vec.y / d);
}
friend vec2<Type> operator*(const vec2<Type>& v1, const vec2<Type>& v2)
{
return vec2<Type>(v1.x * v2.x, v1.y * v2.y);
}
friend vec2<Type> operator+(const vec2<Type>& v1, const vec2<Type>& v2)
{
return vec2<Type>(v1.x + v2.x, v1.y + v2.y);
}
friend vec2<Type> operator-(const vec2<Type>& v1, const vec2<Type>& v2)
{
return vec2<Type>(v1.x - v2.x, v1.y - v2.y);
}
//! Check the two given vector for equality.
friend bool operator==(const vec2<Type>& v1, const vec2<Type>& v2)
{
return v1.x == v2.x && v1.y == v2.y;
}
//! Check the two given vector for inequality.
friend bool operator!=(const vec2<Type>& v1, const vec2<Type>& v2)
{
return !(v1 == v2);
}
//! Check for equality with given tolerance.
bool equals(const vec2<Type>& a_vec, const Type a_tolerance = 1E-2) const
{
return ((*this - a_vec).sqrLength() <= a_tolerance * a_tolerance);
}
friend std::ostream& operator<<(std::ostream& os, const vec2<Type>& vect)
{
return os << vect.x << " " << vect.y;
}
//! Largest representable vector
static vec2<Type> max()
{
return vec2<Type>(std::numeric_limits<Type>::max(), std::numeric_limits<Type>::max());
}
};
typedef vec2<int> vec2i;
typedef vec2<float> vec2f;
typedef vec2<double> vec2d;
} // namespace gtl
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2014 Ruben Nijveld, Aaron van Geffen
* See LICENSE for license.
*/
#include "../config.h"
#include "sqlite.h"
#include <sqlite3.h>
#include <stdio.h>
#include <iostream>
namespace dazeus {
namespace db {
/**
* Cleanup all prepared queries and close the connection.
*/
SQLiteDatabase::~SQLiteDatabase()
{
if (conn_) {
sqlite3_finalize(find_property);
sqlite3_finalize(remove_property);
sqlite3_finalize(update_property);
sqlite3_finalize(properties);
sqlite3_finalize(add_permission);
sqlite3_finalize(remove_permission);
sqlite3_finalize(has_permission);
int res = sqlite3_close(conn_);
assert(res == SQLITE_OK);
}
}
void SQLiteDatabase::open()
{
// Connect the lot!
int fail = sqlite3_open_v2(dbc_.filename.c_str(), &conn_,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
NULL);
if (fail) {
auto error = "Can't open database (code " + std::to_string(fail) + "): " +
sqlite3_errmsg(conn_);
throw exception(error);
}
upgradeDB();
bootstrapDB();
}
/**
* @brief Try to create a prepared statement on the SQLite3 connection.
*/
void SQLiteDatabase::tryPrepare(const std::string &stmt,
sqlite3_stmt **target) const
{
int result = sqlite3_prepare_v2(conn_, stmt.c_str(), stmt.length(), target,
NULL);
if (result != SQLITE_OK) {
throw exception(
std::string("Failed to prepare SQL statement, got an error: ") +
sqlite3_errmsg(conn_));
}
}
/**
* @brief Try to bind a parameter to a prepared statement.
*/
void SQLiteDatabase::tryBind(sqlite3_stmt *target, int param,
const std::string &value) const
{
int result = sqlite3_bind_text(target, param, value.c_str(), value.length(),
SQLITE_TRANSIENT);
if (result != SQLITE_OK) {
throw exception("Failed to bind parameter " + std::to_string(param) +
" to query with error: " + sqlite3_errmsg(conn_) +
" (errorcode " + std::to_string(result) + ")");
}
}
/**
* @brief Prepare all SQL statements used by the database layer
*/
void SQLiteDatabase::bootstrapDB()
{
tryPrepare(
"SELECT value FROM dazeus_properties "
"WHERE key = ?1 "
" AND (network = ?2 OR network = '') "
" AND (receiver = ?3 OR receiver = '') "
" AND (sender = ?4 OR sender = '') "
"ORDER BY network DESC, receiver DESC, sender DESC "
"LIMIT 1",
&find_property);
tryPrepare(
"DELETE FROM dazeus_properties "
"WHERE key = ?1 "
" AND network = ?3 AND receiver = ?4 AND sender = ?5",
&remove_property);
tryPrepare(
"INSERT OR REPLACE INTO dazeus_properties "
"(key, value, network, receiver, sender) "
"VALUES (?1, ?2, ?3, ?4, ?5) ",
&update_property);
tryPrepare(
"SELECT key FROM dazeus_properties "
"WHERE SUBSTR(key, 1, LENGTH(?1)) = ?1 "
" AND network = ?2 AND receiver = ?3 AND sender = ?4",
&properties);
tryPrepare(
"INSERT OR REPLACE INTO dazeus_permissions "
"(permission, network, receiver, sender) "
"VALUES (?1, ?2, ?3, ?4) ",
&add_permission);
tryPrepare(
"DELETE FROM dazeus_permissions "
"WHERE permission = ?1 "
" AND network = ?2 AND receiver = ?3 AND sender = ?4",
&remove_permission);
tryPrepare(
"SELECT * FROM dazeus_permissions "
"WHERE permission = ?1 "
" AND network = ?2 AND receiver = ?3 AND sender = ?4",
&has_permission);
}
/**
* @brief Upgrade the database to the latest version.
*/
void SQLiteDatabase::upgradeDB()
{
bool found = false;
int errc = sqlite3_exec(conn_,
"SELECT name FROM sqlite_master WHERE type = 'table' "
"AND name = 'dazeus_properties'",
[](void* found, int, char**, char**)
{
*(static_cast<bool*>(found)) = true;
return 0;
}, static_cast<void*>(&found), NULL);
if (errc != SQLITE_OK) {
throw exception(std::string("Failed to retrieve database version: ") +
sqlite3_errmsg(conn_));
}
int db_version = 0;
if (errc == SQLITE_OK) {
if (found) {
// table exists, query for latest version
errc = sqlite3_exec(conn_,
"SELECT value FROM dazeus_properties "
"WHERE key = 'dazeus_version' LIMIT 1",
[](void* dbver, int columns, char** values, char**)
{
if (columns > 0) {
*(static_cast<int*>(dbver)) = std::stoi(values[0]);
}
return 0;
}, static_cast<void*>(&db_version), NULL);
}
}
const char *upgrades[] = {
"CREATE TABLE dazeus_properties( "
"key VARCHAR(255) NOT NULL, "
"value TEXT NOT NULL, "
"network VARCHAR(255) NOT NULL, "
"receiver VARCHAR(255) NOT NULL, "
"sender VARCHAR(255) NOT NULL, "
"created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"PRIMARY KEY(key, network, receiver, sender) "
")"
,
"CREATE TABLE dazeus_permissions( "
"permission VARCHAR(255) NOT NULL, "
"network VARCHAR(255) NOT NULL, "
"receiver VARCHAR(255) NOT NULL, "
"sender VARCHAR(255) NOT NULL, "
"created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"PRIMARY KEY(permission, network, receiver, sender) "
")"
};
// run any outstanding updates
static int target_version = std::end(upgrades) - std::begin(upgrades);
if (db_version < target_version) {
std::cout << "Will now upgrade database from version " << db_version
<< " to version " << target_version << "." << std::endl;
for (int i = db_version; i < target_version; ++i) {
int result = sqlite3_exec(conn_, upgrades[i], NULL, NULL, NULL);
if (result != SQLITE_OK) {
throw exception("Could not run upgrade " + std::to_string(i) +
", got error: " + sqlite3_errmsg(conn_));
}
}
std::cout << "Upgrade completed. Will now update dazeus_version to "
<< target_version << std::endl;
errc = sqlite3_exec(conn_,
("INSERT OR REPLACE INTO dazeus_properties "
"(key, value, network, receiver, sender) "
"VALUES ('dazeus_version', '" + std::to_string(target_version) + "', "
" '', '', '') ").c_str(),
NULL, NULL, NULL);
if (errc != SQLITE_OK) {
throw exception(
"Could not set dazeus_version to latest version, got error: " +
std::string(sqlite3_errmsg(conn_)));
}
}
}
std::string SQLiteDatabase::property(const std::string &variable,
const std::string &networkScope,
const std::string &receiverScope,
const std::string &senderScope)
{
tryBind(find_property, 1, variable);
tryBind(find_property, 2, networkScope);
tryBind(find_property, 3, receiverScope);
tryBind(find_property, 4, senderScope);
int errc = sqlite3_step(find_property);
if (errc == SQLITE_ROW) {
std::string value = reinterpret_cast<const char *>(sqlite3_column_text(find_property, 0));
sqlite3_reset(find_property);
return value;
} else if (errc == SQLITE_DONE) {
// TODO: define behavior when no result is found
sqlite3_reset(find_property);
return "";
} else {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(find_property);
throw exception(msg);
}
}
void SQLiteDatabase::setProperty(const std::string &variable,
const std::string &value, const std::string &networkScope,
const std::string &receiverScope,
const std::string &senderScope)
{
sqlite3_stmt *stmt = value == "" ? remove_property : update_property;
tryBind(stmt, 1, variable);
tryBind(stmt, 2, value);
tryBind(stmt, 3, networkScope);
tryBind(stmt, 4, receiverScope);
tryBind(stmt, 5, senderScope);
int errc = sqlite3_step(stmt);
if (errc != SQLITE_OK && errc != SQLITE_DONE) {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(stmt);
throw exception(msg);
}
sqlite3_reset(stmt);
}
std::vector<std::string> SQLiteDatabase::propertyKeys(const std::string &prefix,
const std::string &networkScope,
const std::string &receiverScope,
const std::string &senderScope)
{
// Return a vector of all the property keys matching the criteria.
std::vector<std::string> keys = std::vector<std::string>();
tryBind(properties, 1, prefix);
tryBind(properties, 2, networkScope);
tryBind(properties, 3, receiverScope);
tryBind(properties, 4, senderScope);
while (true) {
int errc = sqlite3_step(properties);
if (errc == SQLITE_ROW) {
std::string value = reinterpret_cast<const char *>(sqlite3_column_text(properties, 0));
keys.push_back(value);
} else if (errc == SQLITE_DONE) {
sqlite3_reset(properties);
break;
} else {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(properties);
throw exception(msg);
}
}
return keys;
}
bool SQLiteDatabase::hasPermission(const std::string &perm_name,
const std::string &network, const std::string &channel,
const std::string &sender, bool defaultPermission) const
{
tryBind(has_permission, 1, perm_name);
tryBind(has_permission, 2, network);
tryBind(has_permission, 3, channel);
tryBind(has_permission, 4, sender);
int errc = sqlite3_step(has_permission);
if (errc == SQLITE_ROW) {
sqlite3_reset(has_permission);
return true;
} else if (errc == SQLITE_DONE) {
sqlite3_reset(has_permission);
return defaultPermission;
} else {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(has_permission);
throw exception(msg);
}
}
void SQLiteDatabase::unsetPermission(const std::string &perm_name,
const std::string &network, const std::string &receiver,
const std::string &sender)
{
tryBind(remove_permission, 1, perm_name);
tryBind(remove_permission, 2, network);
tryBind(remove_permission, 3, receiver);
tryBind(remove_permission, 4, sender);
int errc = sqlite3_step(remove_permission);
if (errc != SQLITE_OK && errc != SQLITE_DONE) {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(remove_permission);
throw exception(msg);
}
sqlite3_reset(remove_permission);
}
void SQLiteDatabase::setPermission(bool permission, const std::string &perm_name,
const std::string &network, const std::string &receiver,
const std::string &sender)
{
tryBind(add_permission, 1, perm_name);
tryBind(add_permission, 2, network);
tryBind(add_permission, 3, receiver);
tryBind(add_permission, 4, sender);
int errc = sqlite3_step(add_permission);
if (errc != SQLITE_OK && errc != SQLITE_DONE) {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(add_permission);
throw exception(msg);
}
sqlite3_reset(add_permission);
}
} // namespace db
} // namespace dazeus
<commit_msg>Fix a warning in release mode.<commit_after>/**
* Copyright (c) 2014 Ruben Nijveld, Aaron van Geffen
* See LICENSE for license.
*/
#include "../config.h"
#include "sqlite.h"
#include <sqlite3.h>
#include <stdio.h>
#include <iostream>
namespace dazeus {
namespace db {
/**
* Cleanup all prepared queries and close the connection.
*/
SQLiteDatabase::~SQLiteDatabase()
{
if (conn_) {
sqlite3_finalize(find_property);
sqlite3_finalize(remove_property);
sqlite3_finalize(update_property);
sqlite3_finalize(properties);
sqlite3_finalize(add_permission);
sqlite3_finalize(remove_permission);
sqlite3_finalize(has_permission);
int res = sqlite3_close(conn_);
assert(res == SQLITE_OK);
(void)res; // avoid unused warnings in release mode
}
}
void SQLiteDatabase::open()
{
// Connect the lot!
int fail = sqlite3_open_v2(dbc_.filename.c_str(), &conn_,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
NULL);
if (fail) {
auto error = "Can't open database (code " + std::to_string(fail) + "): " +
sqlite3_errmsg(conn_);
throw exception(error);
}
upgradeDB();
bootstrapDB();
}
/**
* @brief Try to create a prepared statement on the SQLite3 connection.
*/
void SQLiteDatabase::tryPrepare(const std::string &stmt,
sqlite3_stmt **target) const
{
int result = sqlite3_prepare_v2(conn_, stmt.c_str(), stmt.length(), target,
NULL);
if (result != SQLITE_OK) {
throw exception(
std::string("Failed to prepare SQL statement, got an error: ") +
sqlite3_errmsg(conn_));
}
}
/**
* @brief Try to bind a parameter to a prepared statement.
*/
void SQLiteDatabase::tryBind(sqlite3_stmt *target, int param,
const std::string &value) const
{
int result = sqlite3_bind_text(target, param, value.c_str(), value.length(),
SQLITE_TRANSIENT);
if (result != SQLITE_OK) {
throw exception("Failed to bind parameter " + std::to_string(param) +
" to query with error: " + sqlite3_errmsg(conn_) +
" (errorcode " + std::to_string(result) + ")");
}
}
/**
* @brief Prepare all SQL statements used by the database layer
*/
void SQLiteDatabase::bootstrapDB()
{
tryPrepare(
"SELECT value FROM dazeus_properties "
"WHERE key = ?1 "
" AND (network = ?2 OR network = '') "
" AND (receiver = ?3 OR receiver = '') "
" AND (sender = ?4 OR sender = '') "
"ORDER BY network DESC, receiver DESC, sender DESC "
"LIMIT 1",
&find_property);
tryPrepare(
"DELETE FROM dazeus_properties "
"WHERE key = ?1 "
" AND network = ?3 AND receiver = ?4 AND sender = ?5",
&remove_property);
tryPrepare(
"INSERT OR REPLACE INTO dazeus_properties "
"(key, value, network, receiver, sender) "
"VALUES (?1, ?2, ?3, ?4, ?5) ",
&update_property);
tryPrepare(
"SELECT key FROM dazeus_properties "
"WHERE SUBSTR(key, 1, LENGTH(?1)) = ?1 "
" AND network = ?2 AND receiver = ?3 AND sender = ?4",
&properties);
tryPrepare(
"INSERT OR REPLACE INTO dazeus_permissions "
"(permission, network, receiver, sender) "
"VALUES (?1, ?2, ?3, ?4) ",
&add_permission);
tryPrepare(
"DELETE FROM dazeus_permissions "
"WHERE permission = ?1 "
" AND network = ?2 AND receiver = ?3 AND sender = ?4",
&remove_permission);
tryPrepare(
"SELECT * FROM dazeus_permissions "
"WHERE permission = ?1 "
" AND network = ?2 AND receiver = ?3 AND sender = ?4",
&has_permission);
}
/**
* @brief Upgrade the database to the latest version.
*/
void SQLiteDatabase::upgradeDB()
{
bool found = false;
int errc = sqlite3_exec(conn_,
"SELECT name FROM sqlite_master WHERE type = 'table' "
"AND name = 'dazeus_properties'",
[](void* found, int, char**, char**)
{
*(static_cast<bool*>(found)) = true;
return 0;
}, static_cast<void*>(&found), NULL);
if (errc != SQLITE_OK) {
throw exception(std::string("Failed to retrieve database version: ") +
sqlite3_errmsg(conn_));
}
int db_version = 0;
if (errc == SQLITE_OK) {
if (found) {
// table exists, query for latest version
errc = sqlite3_exec(conn_,
"SELECT value FROM dazeus_properties "
"WHERE key = 'dazeus_version' LIMIT 1",
[](void* dbver, int columns, char** values, char**)
{
if (columns > 0) {
*(static_cast<int*>(dbver)) = std::stoi(values[0]);
}
return 0;
}, static_cast<void*>(&db_version), NULL);
}
}
const char *upgrades[] = {
"CREATE TABLE dazeus_properties( "
"key VARCHAR(255) NOT NULL, "
"value TEXT NOT NULL, "
"network VARCHAR(255) NOT NULL, "
"receiver VARCHAR(255) NOT NULL, "
"sender VARCHAR(255) NOT NULL, "
"created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"PRIMARY KEY(key, network, receiver, sender) "
")"
,
"CREATE TABLE dazeus_permissions( "
"permission VARCHAR(255) NOT NULL, "
"network VARCHAR(255) NOT NULL, "
"receiver VARCHAR(255) NOT NULL, "
"sender VARCHAR(255) NOT NULL, "
"created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"PRIMARY KEY(permission, network, receiver, sender) "
")"
};
// run any outstanding updates
static int target_version = std::end(upgrades) - std::begin(upgrades);
if (db_version < target_version) {
std::cout << "Will now upgrade database from version " << db_version
<< " to version " << target_version << "." << std::endl;
for (int i = db_version; i < target_version; ++i) {
int result = sqlite3_exec(conn_, upgrades[i], NULL, NULL, NULL);
if (result != SQLITE_OK) {
throw exception("Could not run upgrade " + std::to_string(i) +
", got error: " + sqlite3_errmsg(conn_));
}
}
std::cout << "Upgrade completed. Will now update dazeus_version to "
<< target_version << std::endl;
errc = sqlite3_exec(conn_,
("INSERT OR REPLACE INTO dazeus_properties "
"(key, value, network, receiver, sender) "
"VALUES ('dazeus_version', '" + std::to_string(target_version) + "', "
" '', '', '') ").c_str(),
NULL, NULL, NULL);
if (errc != SQLITE_OK) {
throw exception(
"Could not set dazeus_version to latest version, got error: " +
std::string(sqlite3_errmsg(conn_)));
}
}
}
std::string SQLiteDatabase::property(const std::string &variable,
const std::string &networkScope,
const std::string &receiverScope,
const std::string &senderScope)
{
tryBind(find_property, 1, variable);
tryBind(find_property, 2, networkScope);
tryBind(find_property, 3, receiverScope);
tryBind(find_property, 4, senderScope);
int errc = sqlite3_step(find_property);
if (errc == SQLITE_ROW) {
std::string value = reinterpret_cast<const char *>(sqlite3_column_text(find_property, 0));
sqlite3_reset(find_property);
return value;
} else if (errc == SQLITE_DONE) {
// TODO: define behavior when no result is found
sqlite3_reset(find_property);
return "";
} else {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(find_property);
throw exception(msg);
}
}
void SQLiteDatabase::setProperty(const std::string &variable,
const std::string &value, const std::string &networkScope,
const std::string &receiverScope,
const std::string &senderScope)
{
sqlite3_stmt *stmt = value == "" ? remove_property : update_property;
tryBind(stmt, 1, variable);
tryBind(stmt, 2, value);
tryBind(stmt, 3, networkScope);
tryBind(stmt, 4, receiverScope);
tryBind(stmt, 5, senderScope);
int errc = sqlite3_step(stmt);
if (errc != SQLITE_OK && errc != SQLITE_DONE) {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(stmt);
throw exception(msg);
}
sqlite3_reset(stmt);
}
std::vector<std::string> SQLiteDatabase::propertyKeys(const std::string &prefix,
const std::string &networkScope,
const std::string &receiverScope,
const std::string &senderScope)
{
// Return a vector of all the property keys matching the criteria.
std::vector<std::string> keys = std::vector<std::string>();
tryBind(properties, 1, prefix);
tryBind(properties, 2, networkScope);
tryBind(properties, 3, receiverScope);
tryBind(properties, 4, senderScope);
while (true) {
int errc = sqlite3_step(properties);
if (errc == SQLITE_ROW) {
std::string value = reinterpret_cast<const char *>(sqlite3_column_text(properties, 0));
keys.push_back(value);
} else if (errc == SQLITE_DONE) {
sqlite3_reset(properties);
break;
} else {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(properties);
throw exception(msg);
}
}
return keys;
}
bool SQLiteDatabase::hasPermission(const std::string &perm_name,
const std::string &network, const std::string &channel,
const std::string &sender, bool defaultPermission) const
{
tryBind(has_permission, 1, perm_name);
tryBind(has_permission, 2, network);
tryBind(has_permission, 3, channel);
tryBind(has_permission, 4, sender);
int errc = sqlite3_step(has_permission);
if (errc == SQLITE_ROW) {
sqlite3_reset(has_permission);
return true;
} else if (errc == SQLITE_DONE) {
sqlite3_reset(has_permission);
return defaultPermission;
} else {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(has_permission);
throw exception(msg);
}
}
void SQLiteDatabase::unsetPermission(const std::string &perm_name,
const std::string &network, const std::string &receiver,
const std::string &sender)
{
tryBind(remove_permission, 1, perm_name);
tryBind(remove_permission, 2, network);
tryBind(remove_permission, 3, receiver);
tryBind(remove_permission, 4, sender);
int errc = sqlite3_step(remove_permission);
if (errc != SQLITE_OK && errc != SQLITE_DONE) {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(remove_permission);
throw exception(msg);
}
sqlite3_reset(remove_permission);
}
void SQLiteDatabase::setPermission(bool permission, const std::string &perm_name,
const std::string &network, const std::string &receiver,
const std::string &sender)
{
tryBind(add_permission, 1, perm_name);
tryBind(add_permission, 2, network);
tryBind(add_permission, 3, receiver);
tryBind(add_permission, 4, sender);
int errc = sqlite3_step(add_permission);
if (errc != SQLITE_OK && errc != SQLITE_DONE) {
std::string msg = "Got an error while executing an SQL query (code " +
std::to_string(errc) + "): " + sqlite3_errmsg(conn_);
sqlite3_reset(add_permission);
throw exception(msg);
}
sqlite3_reset(add_permission);
}
} // namespace db
} // namespace dazeus
<|endoftext|>
|
<commit_before>#include "FastPID.h"
#include <iostream>
using namespace std;
#ifdef ARDUINO
#define __millis() millis()
#else
static uint32_t __timer = 0;
static uint32_t __t() {
__timer += 1000;
return __timer;
}
#define __millis() __t()
#endif
FastPID::~FastPID() {
}
void FastPID::clear() {
_last_sp = 0;
_last_out = 0;
_sum = 0;
_last_err = 0;
_last_run = 0;
_ctl = 0;
_cfg_err = false;
#ifndef ARDUINO
__timer = 0;
#endif
}
bool FastPID::configure(float kp, float ki, float kd, uint16_t db, int bits, bool sign) {
clear();
// Set parameters
_p = floatToParam(kp);
_i = floatToParam(ki);
_d = floatToParam(kd);
// Set deadband
if (_i == 0 && _d == 0) {
// Deadband causes permanent offsets in P controllers.
// don't let a user do this.
_db = 0;
}
else {
_db = uint32_t(db) * PARAM_MULT;
}
// Set output bits
if (bits > 16 || bits < 1) {
_cfg_err = true;
}
else {
if (sign) {
_outmax = ((0x1ULL << (bits - 1)) - 1) * PARAM_MULT;
_outmin = -((0x1ULL << (bits - 1))) * PARAM_MULT;
}
else {
_outmax = ((0x1ULL << bits) - 1) * PARAM_MULT;
_outmin = 0;
}
}
return !_cfg_err;
}
uint32_t FastPID::floatToParam(float in) {
if (in > PARAM_MAX || in < 0) {
_cfg_err = true;
return 0;
}
return in * PARAM_MULT;
}
int16_t FastPID::step(int16_t sp, int16_t fb) {
// Calculate delta T
// millis(): Frequencies less than 1Hz become 1Hz.
// max freqency 1 kHz (XXX: is this too low?)
uint32_t now = __millis();
uint32_t hz = 0;
if (_last_run == 0) {
// Ignore I and D on the first step. They will be
// unreliable because no time has really passed.
hz = 0;
}
else {
if (now < _last_run) {
// 47-day timebomb
hz = uint32_t(1000) / (now + (~_last_run));
}
else {
hz = uint32_t(1000) / (now - _last_run);
}
if (hz == 0)
hz = 1;
}
_last_run = now;
// int16 + int16 = int17
int32_t err = int32_t(sp) - int32_t(fb);
int64_t P = 0, I = 0, D = 0;
if (_p) {
// uint23 * int16 = int39
P = int64_t(_p) * int64_t(err);
}
if (_i && hz) {
// (int16 * uint32) + int31 = int32
_sum += int32_t(err) / int32_t(hz);
// Limit sum to 31-bit signed value so that it saturates, never overflows.
if (_sum > INTEG_MAX)
_sum = INTEG_MAX;
else if (_sum < INTEG_MIN)
_sum = INTEG_MIN;
// uint23 * int31 = int54
I = int64_t(_i) * int64_t(_sum);
}
if (_d && hz) {
// int17 - (int16 - int16) = int19
int32_t deriv = (sp - _last_sp) - (err - _last_err);
_last_sp = sp;
_last_err = err;
// uint23 * int19 * uint16 = int58
D = int64_t(_d) * int64_t(deriv) * int64_t(hz);
}
// int39 (P) + int54 (I) + int58 (D) = int61
int64_t diff = P + I + D;
// Apply the deadband.
if (_db && diff != 0) {
if (diff < 0) {
if (-diff < _db) {
diff = 0;
}
}
else {
if (diff < _db) {
diff = 0;
}
}
}
// int62 (ctl) + int61 = int63
_ctl += diff;
// Make the output saturate
if (_ctl > _outmax)
_ctl = _outmax;
else if (_ctl < _outmin)
_ctl = _outmin;
// Remove the integer scaling factor.
int16_t out = _ctl >> PARAM_SHIFT;
// Fair rounding.
if (_ctl & (0x1ULL << (PARAM_SHIFT - 1))) {
out++;
}
return out;
}
void FastPID::setCfgErr() {
_cfg_err = true;
_p = _i = _d = 0;
}
<commit_msg>Fixed Arduino compile error.<commit_after>#include "FastPID.h"
using namespace std;
#ifdef ARDUINO
#include <Arduino.h>
#else
#include <iostream>
static uint32_t __timer = 0;
static uint32_t __t() {
__timer += 1000;
return __timer;
}
#define millis() __t()
#endif
FastPID::~FastPID() {
}
void FastPID::clear() {
_last_sp = 0;
_last_out = 0;
_sum = 0;
_last_err = 0;
_last_run = 0;
_ctl = 0;
_cfg_err = false;
#ifndef ARDUINO
__timer = 0;
#endif
}
bool FastPID::configure(float kp, float ki, float kd, uint16_t db, int bits, bool sign) {
clear();
// Set parameters
_p = floatToParam(kp);
_i = floatToParam(ki);
_d = floatToParam(kd);
// Set deadband
if (_i == 0 && _d == 0) {
// Deadband causes permanent offsets in P controllers.
// don't let a user do this.
_db = 0;
}
else {
_db = uint32_t(db) * PARAM_MULT;
}
// Set output bits
if (bits > 16 || bits < 1) {
_cfg_err = true;
}
else {
if (sign) {
_outmax = ((0x1ULL << (bits - 1)) - 1) * PARAM_MULT;
_outmin = -((0x1ULL << (bits - 1))) * PARAM_MULT;
}
else {
_outmax = ((0x1ULL << bits) - 1) * PARAM_MULT;
_outmin = 0;
}
}
return !_cfg_err;
}
uint32_t FastPID::floatToParam(float in) {
if (in > PARAM_MAX || in < 0) {
_cfg_err = true;
return 0;
}
return in * PARAM_MULT;
}
int16_t FastPID::step(int16_t sp, int16_t fb) {
// Calculate delta T
// millis(): Frequencies less than 1Hz become 1Hz.
// max freqency 1 kHz (XXX: is this too low?)
uint32_t now = millis();
uint32_t hz = 0;
if (_last_run == 0) {
// Ignore I and D on the first step. They will be
// unreliable because no time has really passed.
hz = 0;
}
else {
if (now < _last_run) {
// 47-day timebomb
hz = uint32_t(1000) / (now + (~_last_run));
}
else {
hz = uint32_t(1000) / (now - _last_run);
}
if (hz == 0)
hz = 1;
}
_last_run = now;
// int16 + int16 = int17
int32_t err = int32_t(sp) - int32_t(fb);
int64_t P = 0, I = 0, D = 0;
if (_p) {
// uint23 * int16 = int39
P = int64_t(_p) * int64_t(err);
}
if (_i && hz) {
// (int16 * uint32) + int31 = int32
_sum += int32_t(err) / int32_t(hz);
// Limit sum to 31-bit signed value so that it saturates, never overflows.
if (_sum > INTEG_MAX)
_sum = INTEG_MAX;
else if (_sum < INTEG_MIN)
_sum = INTEG_MIN;
// uint23 * int31 = int54
I = int64_t(_i) * int64_t(_sum);
}
if (_d && hz) {
// int17 - (int16 - int16) = int19
int32_t deriv = (sp - _last_sp) - (err - _last_err);
_last_sp = sp;
_last_err = err;
// uint23 * int19 * uint16 = int58
D = int64_t(_d) * int64_t(deriv) * int64_t(hz);
}
// int39 (P) + int54 (I) + int58 (D) = int61
int64_t diff = P + I + D;
// Apply the deadband.
if (_db && diff != 0) {
if (diff < 0) {
if (-diff < _db) {
diff = 0;
}
}
else {
if (diff < _db) {
diff = 0;
}
}
}
// int62 (ctl) + int61 = int63
_ctl += diff;
// Make the output saturate
if (_ctl > _outmax)
_ctl = _outmax;
else if (_ctl < _outmin)
_ctl = _outmin;
// Remove the integer scaling factor.
int16_t out = _ctl >> PARAM_SHIFT;
// Fair rounding.
if (_ctl & (0x1ULL << (PARAM_SHIFT - 1))) {
out++;
}
return out;
}
void FastPID::setCfgErr() {
_cfg_err = true;
_p = _i = _d = 0;
}
<|endoftext|>
|
<commit_before>/* DO NOT EDIT THIS FILE! It was generated by utils/apivergen.abc. */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL+"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
[0,player,full]=660:FP_9_0
[0,air,full]=661:AIR_1_0
[1,player,full]=662:FP_10_0
[1,air,full]=663:AIR_1_5
[2,air,full]=664:AIR_1_5_1
[3,player,full]=665:FP_10_0_32
[3,air,full]=666:AIR_1_5_2
[4,player,full]=667:FP_10_1
[4,air,full]=668:AIR_2_0
[5,air,full]=669:AIR_2_5
[6,player,full]=670:FP_10_2
[6,air,full]=671:AIR_2_6
[7,player,full]=672:SWF_12
[7,player,system]=674:FP_SYS
[7,air,full]=673:AIR_2_7
[7,air,system]=675:AIR_SYS
*/
namespace avmplus {
int32_t const kApiCompat[kApiVersion_count] = {
0xffff,
0xab5a,
0xfffc,
0xab58,
0xab50,
0xffe0,
0xab40,
0xff80,
0xab00,
0xaa00,
0xfc00,
0xa800,
0xf000,
0xa000,
0xc000,
0x8000
};
const char* const kApiVersionNames[kApiVersion_count] = {
"FP_9_0",
"AIR_1_0",
"FP_10_0",
"AIR_1_5",
"AIR_1_5_1",
"FP_10_0_32",
"AIR_1_5_2",
"FP_10_1",
"AIR_2_0",
"AIR_2_5",
"FP_10_2",
"AIR_2_6",
"SWF_12",
"AIR_2_7",
"FP_SYS",
"AIR_SYS"
};
}<commit_msg>Added one missing newline at the end of core/api-versions.cpp<commit_after>/* DO NOT EDIT THIS FILE! It was generated by utils/apivergen.abc. */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL+"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
[0,player,full]=660:FP_9_0
[0,air,full]=661:AIR_1_0
[1,player,full]=662:FP_10_0
[1,air,full]=663:AIR_1_5
[2,air,full]=664:AIR_1_5_1
[3,player,full]=665:FP_10_0_32
[3,air,full]=666:AIR_1_5_2
[4,player,full]=667:FP_10_1
[4,air,full]=668:AIR_2_0
[5,air,full]=669:AIR_2_5
[6,player,full]=670:FP_10_2
[6,air,full]=671:AIR_2_6
[7,player,full]=672:SWF_12
[7,player,system]=674:FP_SYS
[7,air,full]=673:AIR_2_7
[7,air,system]=675:AIR_SYS
*/
namespace avmplus {
int32_t const kApiCompat[kApiVersion_count] = {
0xffff,
0xab5a,
0xfffc,
0xab58,
0xab50,
0xffe0,
0xab40,
0xff80,
0xab00,
0xaa00,
0xfc00,
0xa800,
0xf000,
0xa000,
0xc000,
0x8000
};
const char* const kApiVersionNames[kApiVersion_count] = {
"FP_9_0",
"AIR_1_0",
"FP_10_0",
"AIR_1_5",
"AIR_1_5_1",
"FP_10_0_32",
"AIR_1_5_2",
"FP_10_1",
"AIR_2_0",
"AIR_2_5",
"FP_10_2",
"AIR_2_6",
"SWF_12",
"AIR_2_7",
"FP_SYS",
"AIR_SYS"
};
}
<|endoftext|>
|
<commit_before>/*
* Copyright by Michal Majczak & Krzysztof Taperek, 2016
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Author: Krzysztof Taperek <krzysztoftaperek@gmail.com>
*/
#include <GBuffer.hpp>
GBuffer::GBuffer() {
m_fbo = 0;
m_depthTexture = 0;
memset(m_textures, 0, sizeof(m_textures));
}
GBuffer::~GBuffer() {
if (m_fbo != 0) {
glDeleteFramebuffers(1, &m_fbo);
}
if (m_textures[0] != 0) {
glDeleteTextures(sizeof(m_textures) / sizeof(m_textures[0]), m_textures);
}
if (m_depthTexture != 0) {
glDeleteTextures(1, &m_depthTexture);
}
CHECK_GL_ERR();
}
bool GBuffer::Init(unsigned int width, unsigned int height) {
CHECK_GL_ERR();
glGenFramebuffers(1, &m_fbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo);
int objSize = sizeof(m_textures) / sizeof(m_textures[0]);
glGenTextures(objSize, m_textures);
glGenTextures(1, &m_depthTexture);
for (unsigned int i = 0 ; i < objSize ; i++) {
glBindTexture(GL_TEXTURE_2D, m_textures[i]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, width, height, 0, GL_RGB, GL_FLOAT, NULL);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, m_textures[i], 0);
}
// depth
glBindTexture(GL_TEXTURE_2D, m_depthTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT,
NULL);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthTexture, 0);
GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };
glDrawBuffers(sizeof(drawBuffers) / sizeof(drawBuffers[0]), drawBuffers);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
LOGE("FrameBuffer error, status: {}", status);
return false;
}
// restore default FBO
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
CHECK_GL_ERR();
return true;
}
void GBuffer::BindForWriting() {
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo);
}
void GBuffer::BindForReading() {
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
int objSize = sizeof(m_textures) / sizeof(m_textures[0]);
for (unsigned int i = 0; i < objSize; i++) {
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, m_textures[GBUFFER_TEXTURE_TYPE_POSITION + i]);
}
glActiveTexture(GL_TEXTURE0);
}
void GBuffer::SetReadBuffer(GBUFFER_TEXTURE_TYPE textureType) {
glReadBuffer(GL_COLOR_ATTACHMENT0 + textureType);
}
void GBuffer::DebugDraw(float width, float height) {
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo);
SetReadBuffer(GBuffer::GBUFFER_TEXTURE_TYPE_POSITION);
glBlitFramebuffer(0, 0, width, height, 0, 0, width / 2.0f, height / 2.0f, GL_COLOR_BUFFER_BIT, GL_LINEAR);
SetReadBuffer(GBuffer::GBUFFER_TEXTURE_TYPE_DIFFUSE);
glBlitFramebuffer(0, 0, width, height, 0, height / 2.0f, width / 2.0f, height, GL_COLOR_BUFFER_BIT, GL_LINEAR);
SetReadBuffer(GBuffer::GBUFFER_TEXTURE_TYPE_NORMAL);
glBlitFramebuffer(0, 0, width, height, width / 2.0f, height / 2.0f, width, height, GL_COLOR_BUFFER_BIT, GL_LINEAR);
SetReadBuffer(GBuffer::GBUFFER_TEXTURE_TYPE_TEXCOORD);
glBlitFramebuffer(0, 0, width, height, width / 2.0f, 0, width, height / 2.0f, GL_COLOR_BUFFER_BIT, GL_LINEAR);
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
}
<commit_msg>Change of format to work on some linux machines<commit_after>/*
* Copyright by Michal Majczak & Krzysztof Taperek, 2016
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Author: Krzysztof Taperek <krzysztoftaperek@gmail.com>
*/
#include <GBuffer.hpp>
GBuffer::GBuffer() {
m_fbo = 0;
m_depthTexture = 0;
memset(m_textures, 0, sizeof(m_textures));
}
GBuffer::~GBuffer() {
if (m_fbo != 0) {
glDeleteFramebuffers(1, &m_fbo);
}
if (m_textures[0] != 0) {
glDeleteTextures(sizeof(m_textures) / sizeof(m_textures[0]), m_textures);
}
if (m_depthTexture != 0) {
glDeleteTextures(1, &m_depthTexture);
}
CHECK_GL_ERR();
}
bool GBuffer::Init(unsigned int width, unsigned int height) {
CHECK_GL_ERR();
glGenFramebuffers(1, &m_fbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo);
int objSize = sizeof(m_textures) / sizeof(m_textures[0]);
glGenTextures(objSize, m_textures);
glGenTextures(1, &m_depthTexture);
for (unsigned int i = 0 ; i < objSize ; i++) {
glBindTexture(GL_TEXTURE_2D, m_textures[i]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_FLOAT, NULL);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, m_textures[i], 0);
}
// depth
glBindTexture(GL_TEXTURE_2D, m_depthTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT,
NULL);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthTexture, 0);
GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };
glDrawBuffers(sizeof(drawBuffers) / sizeof(drawBuffers[0]), drawBuffers);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
LOGE("FrameBuffer error, status: {}", status);
return false;
}
// restore default FBO
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
CHECK_GL_ERR();
return true;
}
void GBuffer::BindForWriting() {
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo);
}
void GBuffer::BindForReading() {
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
int objSize = sizeof(m_textures) / sizeof(m_textures[0]);
for (unsigned int i = 0; i < objSize; i++) {
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, m_textures[GBUFFER_TEXTURE_TYPE_POSITION + i]);
}
glActiveTexture(GL_TEXTURE0);
}
void GBuffer::SetReadBuffer(GBUFFER_TEXTURE_TYPE textureType) {
glReadBuffer(GL_COLOR_ATTACHMENT0 + textureType);
}
void GBuffer::DebugDraw(float width, float height) {
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo);
SetReadBuffer(GBuffer::GBUFFER_TEXTURE_TYPE_POSITION);
glBlitFramebuffer(0, 0, width, height, 0, 0, width / 2.0f, height / 2.0f, GL_COLOR_BUFFER_BIT, GL_LINEAR);
SetReadBuffer(GBuffer::GBUFFER_TEXTURE_TYPE_DIFFUSE);
glBlitFramebuffer(0, 0, width, height, 0, height / 2.0f, width / 2.0f, height, GL_COLOR_BUFFER_BIT, GL_LINEAR);
SetReadBuffer(GBuffer::GBUFFER_TEXTURE_TYPE_NORMAL);
glBlitFramebuffer(0, 0, width, height, width / 2.0f, height / 2.0f, width, height, GL_COLOR_BUFFER_BIT, GL_LINEAR);
SetReadBuffer(GBuffer::GBUFFER_TEXTURE_TYPE_TEXCOORD);
glBlitFramebuffer(0, 0, width, height, width / 2.0f, 0, width, height / 2.0f, GL_COLOR_BUFFER_BIT, GL_LINEAR);
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
}
<|endoftext|>
|
<commit_before>/*
* This file is part of accounts-ui
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "service-selection-page.h"
#include "provider-plugin-process.h"
#include "service-settings-widget.h"
//Qt
#include <QStringListModel>
#include <QItemSelection>
#include <QDebug>
//Meegotouch
#include <MLayout>
#include <MList>
#include <MGridLayoutPolicy>
#include <MLinearLayoutPolicy>
#include <MButton>
#include <MWidgetCreator>
#include <MContainer>
namespace AccountsUI {
M_REGISTER_WIDGET_NO_CREATE(ServiceSelectionPage)
//TODO: write the service plugins
class ServiceSelectionPagePrivate
{
public:
ServiceSelectionPagePrivate()
: serviceList(0),
accountInstallButton(0),
context(0),
syncHandler(0)
{}
~ServiceSelectionPagePrivate() {}
MList *serviceList;
MButton *accountInstallButton;
AbstractAccountSetupContext *context;
QList<AbstractServiceSetupContext*> serviceContextList;
QList<AbstractSetupContext*> abstractContexts;
AccountSyncHandler *syncHandler;
};
ServiceSelectionPage::ServiceSelectionPage(AbstractAccountSetupContext *context,
QList<AbstractServiceSetupContext*>
&serviceContextList,
QGraphicsItem *parent)
: MApplicationPage(parent),
d_ptr(new ServiceSelectionPagePrivate())
{
Q_D(ServiceSelectionPage);
setStyleName("ServicePage");
d->context = context;
d->context->account()->selectService(NULL);
d->context->account()->setEnabled(true);
d->serviceContextList = serviceContextList;
d->abstractContexts.append(d->context);
QString providerName(d->context->account()->providerName());
//% "Add new account"
setTitle(qtTrId("qtn_acc_add_new_account_title"));
setEscapeMode(MApplicationPageModel::EscapeManualBack);
d->accountInstallButton = new MButton(this);
d->accountInstallButton->setStyleName("serviceaccountInstallButton");
//% "Finalize Setup"
d->accountInstallButton->setText(qtTrId("qtn_comm_command_done"));
d->syncHandler = new AccountSyncHandler(this);
connect(d->syncHandler, SIGNAL(syncStateChanged(const SyncState&)),
this, SLOT(onSyncStateChanged(const SyncState&)));
connect(d->accountInstallButton,SIGNAL(clicked()),
this, SLOT(onAccountInstallButton()));
connect(d->serviceList,SIGNAL(itemClicked(QModelIndex)),
this,SLOT(serviceSelected(QModelIndex)));
connect(this, SIGNAL(backButtonClicked()),
this, SLOT(close()));
}
void ServiceSelectionPage::serviceSelected(QModelIndex index)
{
Q_UNUSED(index);
}
ServiceSelectionPage::~ServiceSelectionPage()
{
delete d_ptr;
}
void ServiceSelectionPage::createContent()
{
Q_D(ServiceSelectionPage);
MWidget *centralWidget = new MWidget(this);
MLayout *mainLayout = new MLayout(centralWidget);
MLinearLayoutPolicy *mainLayoutPolicy = new MLinearLayoutPolicy(mainLayout, Qt::Vertical);
for (int i = 0; i < d->serviceContextList.count(); i++) {
//ServiceSettingsWidget sets the display widget of the changing settings
ServiceSettingsWidget *settingsWidget =
new ServiceSettingsWidget(d->serviceContextList.at(i), this, false, false);
settingsWidget->setHeaderVisible(false);
mainLayoutPolicy->addItem(settingsWidget);
d->abstractContexts.append(d->serviceContextList.at(i));
}
mainLayoutPolicy->setItemSpacing(d->serviceContextList.count(),20);
mainLayoutPolicy->addItem(d->accountInstallButton);
mainLayoutPolicy->addStretch();
setCentralWidget(centralWidget);
}
void ServiceSelectionPage::onAccountInstallButton()
{
Q_D(ServiceSelectionPage);
disconnect(d->accountInstallButton,SIGNAL(clicked()),
this, SLOT(onAccountInstallButton()));
setProgressIndicatorVisible(true);
d->syncHandler->validate(d->abstractContexts);
}
void ServiceSelectionPage::onSyncStateChanged(const SyncState &state)
{
Q_D(ServiceSelectionPage);
switch (state) {
case Validated:
d->syncHandler->store(d->abstractContexts);
break;
case Stored:
connect(d->context->account(), SIGNAL(synced()),
ProviderPluginProcess::instance(), SLOT(quit()));
d->context->account()->sync();
break;
default:
connect(d->accountInstallButton,SIGNAL(clicked()),
this, SLOT(onAccountInstallButton()));
setProgressIndicatorVisible(false);
return;
}
}
} //namespace
<commit_msg>forgotten parameter value: in the beginning all services are disabled<commit_after>/*
* This file is part of accounts-ui
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "service-selection-page.h"
#include "provider-plugin-process.h"
#include "service-settings-widget.h"
//Qt
#include <QStringListModel>
#include <QItemSelection>
#include <QDebug>
//Meegotouch
#include <MLayout>
#include <MList>
#include <MGridLayoutPolicy>
#include <MLinearLayoutPolicy>
#include <MButton>
#include <MWidgetCreator>
#include <MContainer>
namespace AccountsUI {
M_REGISTER_WIDGET_NO_CREATE(ServiceSelectionPage)
//TODO: write the service plugins
class ServiceSelectionPagePrivate
{
public:
ServiceSelectionPagePrivate()
: serviceList(0),
accountInstallButton(0),
context(0),
syncHandler(0)
{}
~ServiceSelectionPagePrivate() {}
MList *serviceList;
MButton *accountInstallButton;
AbstractAccountSetupContext *context;
QList<AbstractServiceSetupContext*> serviceContextList;
QList<AbstractSetupContext*> abstractContexts;
AccountSyncHandler *syncHandler;
};
ServiceSelectionPage::ServiceSelectionPage(AbstractAccountSetupContext *context,
QList<AbstractServiceSetupContext*>
&serviceContextList,
QGraphicsItem *parent)
: MApplicationPage(parent),
d_ptr(new ServiceSelectionPagePrivate())
{
Q_D(ServiceSelectionPage);
setStyleName("ServicePage");
d->context = context;
d->context->account()->selectService(NULL);
d->context->account()->setEnabled(true);
d->serviceContextList = serviceContextList;
d->abstractContexts.append(d->context);
QString providerName(d->context->account()->providerName());
//% "Add new account"
setTitle(qtTrId("qtn_acc_add_new_account_title"));
setEscapeMode(MApplicationPageModel::EscapeManualBack);
d->accountInstallButton = new MButton(this);
d->accountInstallButton->setStyleName("serviceaccountInstallButton");
//% "Finalize Setup"
d->accountInstallButton->setText(qtTrId("qtn_comm_command_done"));
d->syncHandler = new AccountSyncHandler(this);
connect(d->syncHandler, SIGNAL(syncStateChanged(const SyncState&)),
this, SLOT(onSyncStateChanged(const SyncState&)));
connect(d->accountInstallButton,SIGNAL(clicked()),
this, SLOT(onAccountInstallButton()));
connect(d->serviceList,SIGNAL(itemClicked(QModelIndex)),
this,SLOT(serviceSelected(QModelIndex)));
connect(this, SIGNAL(backButtonClicked()),
this, SLOT(close()));
}
void ServiceSelectionPage::serviceSelected(QModelIndex index)
{
Q_UNUSED(index);
}
ServiceSelectionPage::~ServiceSelectionPage()
{
delete d_ptr;
}
void ServiceSelectionPage::createContent()
{
Q_D(ServiceSelectionPage);
MWidget *centralWidget = new MWidget(this);
MLayout *mainLayout = new MLayout(centralWidget);
MLinearLayoutPolicy *mainLayoutPolicy = new MLinearLayoutPolicy(mainLayout, Qt::Vertical);
for (int i = 0; i < d->serviceContextList.count(); i++) {
//ServiceSettingsWidget sets the display widget of the changing settings
ServiceSettingsWidget *settingsWidget =
new ServiceSettingsWidget(d->serviceContextList.at(i), this, false, false, false);
settingsWidget->setHeaderVisible(false);
mainLayoutPolicy->addItem(settingsWidget);
d->abstractContexts.append(d->serviceContextList.at(i));
}
mainLayoutPolicy->setItemSpacing(d->serviceContextList.count(),20);
mainLayoutPolicy->addItem(d->accountInstallButton);
mainLayoutPolicy->addStretch();
setCentralWidget(centralWidget);
}
void ServiceSelectionPage::onAccountInstallButton()
{
Q_D(ServiceSelectionPage);
disconnect(d->accountInstallButton,SIGNAL(clicked()),
this, SLOT(onAccountInstallButton()));
setProgressIndicatorVisible(true);
d->syncHandler->validate(d->abstractContexts);
}
void ServiceSelectionPage::onSyncStateChanged(const SyncState &state)
{
Q_D(ServiceSelectionPage);
switch (state) {
case Validated:
d->syncHandler->store(d->abstractContexts);
break;
case Stored:
connect(d->context->account(), SIGNAL(synced()),
ProviderPluginProcess::instance(), SLOT(quit()));
d->context->account()->sync();
break;
default:
connect(d->accountInstallButton,SIGNAL(clicked()),
this, SLOT(onAccountInstallButton()));
setProgressIndicatorVisible(false);
return;
}
}
} //namespace
<|endoftext|>
|
<commit_before>//===- lib/CodeGen/GlobalISel/GISelKnownBits.cpp --------------*- C++ *-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
/// Provides analysis for querying information about KnownBits during GISel
/// passes.
//
//===------------------
#include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/CodeGen/GlobalISel/Utils.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetOpcodes.h"
#define DEBUG_TYPE "gisel-known-bits"
using namespace llvm;
char llvm::GISelKnownBitsAnalysis::ID = 0;
INITIALIZE_PASS_BEGIN(GISelKnownBitsAnalysis, DEBUG_TYPE,
"Analysis for ComputingKnownBits", false, true)
INITIALIZE_PASS_END(GISelKnownBitsAnalysis, DEBUG_TYPE,
"Analysis for ComputingKnownBits", false, true)
GISelKnownBits::GISelKnownBits(MachineFunction &MF)
: MF(MF), MRI(MF.getRegInfo()), TL(*MF.getSubtarget().getTargetLowering()),
DL(MF.getFunction().getParent()->getDataLayout()) {}
unsigned GISelKnownBits::inferAlignmentForFrameIdx(int FrameIdx, int Offset,
const MachineFunction &MF) {
const MachineFrameInfo &MFI = MF.getFrameInfo();
return MinAlign(Offset, MFI.getObjectAlignment(FrameIdx));
// TODO: How to handle cases with Base + Offset?
}
unsigned GISelKnownBits::inferPtrAlignment(const MachineInstr &MI) {
if (MI.getOpcode() == TargetOpcode::G_FRAME_INDEX) {
int FrameIdx = MI.getOperand(1).getIndex();
return inferAlignmentForFrameIdx(FrameIdx, 0, *MI.getMF());
}
return 0;
}
void GISelKnownBits::computeKnownBitsForFrameIndex(Register R, KnownBits &Known,
const APInt &DemandedElts,
unsigned Depth) {
const MachineInstr &MI = *MRI.getVRegDef(R);
computeKnownBitsForAlignment(Known, inferPtrAlignment(MI));
}
void GISelKnownBits::computeKnownBitsForAlignment(KnownBits &Known,
unsigned Align) {
if (Align)
// The low bits are known zero if the pointer is aligned.
Known.Zero.setLowBits(Log2_32(Align));
}
KnownBits GISelKnownBits::getKnownBits(MachineInstr &MI) {
return getKnownBits(MI.getOperand(0).getReg());
}
KnownBits GISelKnownBits::getKnownBits(Register R) {
KnownBits Known;
LLT Ty = MRI.getType(R);
APInt DemandedElts =
Ty.isVector() ? APInt::getAllOnesValue(Ty.getNumElements()) : APInt(1, 1);
computeKnownBitsImpl(R, Known, DemandedElts);
return Known;
}
bool GISelKnownBits::signBitIsZero(Register R) {
LLT Ty = MRI.getType(R);
unsigned BitWidth = Ty.getScalarSizeInBits();
return maskedValueIsZero(R, APInt::getSignMask(BitWidth));
}
APInt GISelKnownBits::getKnownZeroes(Register R) {
return getKnownBits(R).Zero;
}
APInt GISelKnownBits::getKnownOnes(Register R) { return getKnownBits(R).One; }
void GISelKnownBits::computeKnownBitsImpl(Register R, KnownBits &Known,
const APInt &DemandedElts,
unsigned Depth) {
MachineInstr &MI = *MRI.getVRegDef(R);
unsigned Opcode = MI.getOpcode();
LLT DstTy = MRI.getType(R);
unsigned BitWidth = DstTy.getSizeInBits();
Known = KnownBits(BitWidth); // Don't know anything
if (DstTy.isVector())
return; // TODO: Handle vectors.
if (Depth == getMaxDepth())
return;
if (!DemandedElts)
return; // No demanded elts, better to assume we don't know anything.
KnownBits Known2;
switch (Opcode) {
default:
TL.computeKnownBitsForTargetInstr(R, Known, DemandedElts, MRI, Depth);
break;
case TargetOpcode::G_CONSTANT: {
auto CstVal = getConstantVRegVal(R, MRI);
Known.One = *CstVal;
Known.Zero = ~Known.One;
break;
}
case TargetOpcode::G_FRAME_INDEX: {
computeKnownBitsForFrameIndex(R, Known, DemandedElts);
break;
}
case TargetOpcode::G_SUB: {
// If low bits are known to be zero in both operands, then we know they are
// going to be 0 in the result. Both addition and complement operations
// preserve the low zero bits.
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
Depth + 1);
unsigned KnownZeroLow = Known2.countMinTrailingZeros();
if (KnownZeroLow == 0)
break;
computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
Depth + 1);
KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
Known.Zero.setLowBits(KnownZeroLow);
break;
}
case TargetOpcode::G_XOR: {
computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
Depth + 1);
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
Depth + 1);
// Output known-0 bits are known if clear or set in both the LHS & RHS.
APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
// Output known-1 are known to be set if set in only one of the LHS, RHS.
Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
Known.Zero = KnownZeroOut;
break;
}
// G_GEP is like G_ADD. FIXME: Is this true for all targets?
case TargetOpcode::G_GEP:
case TargetOpcode::G_ADD: {
// Output known-0 bits are known if clear or set in both the low clear bits
// common to both LHS & RHS. For example, 8+(X<<3) is known to have the
// low 3 bits clear.
// Output known-0 bits are also known if the top bits of each input are
// known to be clear. For example, if one input has the top 10 bits clear
// and the other has the top 8 bits clear, we know the top 7 bits of the
// output must be clear.
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
Depth + 1);
unsigned KnownZeroHigh = Known2.countMinLeadingZeros();
unsigned KnownZeroLow = Known2.countMinTrailingZeros();
computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
Depth + 1);
KnownZeroHigh = std::min(KnownZeroHigh, Known2.countMinLeadingZeros());
KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
Known.Zero.setLowBits(KnownZeroLow);
if (KnownZeroHigh > 1)
Known.Zero.setHighBits(KnownZeroHigh - 1);
break;
}
case TargetOpcode::G_AND: {
// If either the LHS or the RHS are Zero, the result is zero.
computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
Depth + 1);
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
Depth + 1);
// Output known-1 bits are only known if set in both the LHS & RHS.
Known.One &= Known2.One;
// Output known-0 are known to be clear if zero in either the LHS | RHS.
Known.Zero |= Known2.Zero;
break;
}
case TargetOpcode::G_OR: {
// If either the LHS or the RHS are Zero, the result is zero.
computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
Depth + 1);
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
Depth + 1);
// Output known-0 bits are only known if clear in both the LHS & RHS.
Known.Zero &= Known2.Zero;
// Output known-1 are known to be set if set in either the LHS | RHS.
Known.One |= Known2.One;
break;
}
case TargetOpcode::G_MUL: {
computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
Depth + 1);
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
Depth + 1);
// If low bits are zero in either operand, output low known-0 bits.
// Also compute a conservative estimate for high known-0 bits.
// More trickiness is possible, but this is sufficient for the
// interesting case of alignment computation.
unsigned TrailZ =
Known.countMinTrailingZeros() + Known2.countMinTrailingZeros();
unsigned LeadZ =
std::max(Known.countMinLeadingZeros() + Known2.countMinLeadingZeros(),
BitWidth) -
BitWidth;
Known.resetAll();
Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
break;
}
case TargetOpcode::G_SELECT: {
computeKnownBitsImpl(MI.getOperand(3).getReg(), Known, DemandedElts,
Depth + 1);
// If we don't know any bits, early out.
if (Known.isUnknown())
break;
computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
Depth + 1);
// Only known if known in both the LHS and RHS.
Known.One &= Known2.One;
Known.Zero &= Known2.Zero;
break;
}
case TargetOpcode::G_FCMP:
case TargetOpcode::G_ICMP: {
if (TL.getBooleanContents(DstTy.isVector(),
Opcode == TargetOpcode::G_FCMP) ==
TargetLowering::ZeroOrOneBooleanContent &&
BitWidth > 1)
Known.Zero.setBitsFrom(1);
break;
}
case TargetOpcode::G_SEXT: {
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
Depth + 1);
// If the sign bit is known to be zero or one, then sext will extend
// it to the top bits, else it will just zext.
Known = Known.sext(BitWidth);
break;
}
case TargetOpcode::G_ANYEXT: {
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
Depth + 1);
Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
break;
}
case TargetOpcode::G_LOAD: {
if (MI.hasOneMemOperand()) {
const MachineMemOperand *MMO = *MI.memoperands_begin();
if (const MDNode *Ranges = MMO->getRanges()) {
computeKnownBitsFromRangeMetadata(*Ranges, Known);
}
}
break;
}
case TargetOpcode::G_ZEXTLOAD: {
// Everything above the retrieved bits is zero
if (MI.hasOneMemOperand())
Known.Zero.setBitsFrom((*MI.memoperands_begin())->getSizeInBits());
break;
}
case TargetOpcode::G_ASHR:
case TargetOpcode::G_LSHR:
case TargetOpcode::G_SHL: {
KnownBits RHSKnown;
computeKnownBitsImpl(MI.getOperand(2).getReg(), RHSKnown, DemandedElts,
Depth + 1);
if (!RHSKnown.isConstant()) {
LLVM_DEBUG(
MachineInstr *RHSMI = MRI.getVRegDef(MI.getOperand(2).getReg());
dbgs() << '[' << Depth << "] Shift not known constant: " << *RHSMI);
break;
}
uint64_t Shift = RHSKnown.getConstant().getZExtValue();
LLVM_DEBUG(dbgs() << '[' << Depth << "] Shift is " << Shift << '\n');
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
Depth + 1);
switch (Opcode) {
case TargetOpcode::G_ASHR:
Known.Zero = Known.Zero.ashr(Shift);
Known.One = Known.One.ashr(Shift);
break;
case TargetOpcode::G_LSHR:
Known.Zero = Known.Zero.lshr(Shift);
Known.One = Known.One.lshr(Shift);
Known.Zero.setBitsFrom(Known.Zero.getBitWidth() - Shift);
break;
case TargetOpcode::G_SHL:
Known.Zero = Known.Zero.shl(Shift);
Known.One = Known.One.shl(Shift);
Known.Zero.setBits(0, Shift);
break;
}
break;
}
case TargetOpcode::G_INTTOPTR:
case TargetOpcode::G_PTRTOINT:
// Fall through and handle them the same as zext/trunc.
LLVM_FALLTHROUGH;
case TargetOpcode::G_ZEXT:
case TargetOpcode::G_TRUNC: {
Register SrcReg = MI.getOperand(1).getReg();
LLT SrcTy = MRI.getType(SrcReg);
unsigned SrcBitWidth = SrcTy.isPointer()
? DL.getIndexSizeInBits(SrcTy.getAddressSpace())
: SrcTy.getSizeInBits();
assert(SrcBitWidth && "SrcBitWidth can't be zero");
Known = Known.zextOrTrunc(SrcBitWidth, true);
computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
Known = Known.zextOrTrunc(BitWidth, true);
if (BitWidth > SrcBitWidth)
Known.Zero.setBitsFrom(SrcBitWidth);
break;
}
}
assert(!Known.hasConflict() && "Bits known to be one AND zero?");
LLVM_DEBUG(dbgs() << "[" << Depth << "] Compute known bits: " << MI << "["
<< Depth << "] Computed for: " << MI << "[" << Depth
<< "] Known: 0x"
<< (Known.Zero | Known.One).toString(16, false) << "\n"
<< "[" << Depth << "] Zero: 0x"
<< Known.Zero.toString(16, false) << "\n"
<< "[" << Depth << "] One: 0x"
<< Known.One.toString(16, false) << "\n");
}
void GISelKnownBitsAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
MachineFunctionPass::getAnalysisUsage(AU);
}
bool GISelKnownBitsAnalysis::runOnMachineFunction(MachineFunction &MF) {
return false;
}
<commit_msg>GlobalISel: Don't compute known bits for non-integral GEP<commit_after>//===- lib/CodeGen/GlobalISel/GISelKnownBits.cpp --------------*- C++ *-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
/// Provides analysis for querying information about KnownBits during GISel
/// passes.
//
//===------------------
#include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/CodeGen/GlobalISel/Utils.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetOpcodes.h"
#define DEBUG_TYPE "gisel-known-bits"
using namespace llvm;
char llvm::GISelKnownBitsAnalysis::ID = 0;
INITIALIZE_PASS_BEGIN(GISelKnownBitsAnalysis, DEBUG_TYPE,
"Analysis for ComputingKnownBits", false, true)
INITIALIZE_PASS_END(GISelKnownBitsAnalysis, DEBUG_TYPE,
"Analysis for ComputingKnownBits", false, true)
GISelKnownBits::GISelKnownBits(MachineFunction &MF)
: MF(MF), MRI(MF.getRegInfo()), TL(*MF.getSubtarget().getTargetLowering()),
DL(MF.getFunction().getParent()->getDataLayout()) {}
unsigned GISelKnownBits::inferAlignmentForFrameIdx(int FrameIdx, int Offset,
const MachineFunction &MF) {
const MachineFrameInfo &MFI = MF.getFrameInfo();
return MinAlign(Offset, MFI.getObjectAlignment(FrameIdx));
// TODO: How to handle cases with Base + Offset?
}
unsigned GISelKnownBits::inferPtrAlignment(const MachineInstr &MI) {
if (MI.getOpcode() == TargetOpcode::G_FRAME_INDEX) {
int FrameIdx = MI.getOperand(1).getIndex();
return inferAlignmentForFrameIdx(FrameIdx, 0, *MI.getMF());
}
return 0;
}
void GISelKnownBits::computeKnownBitsForFrameIndex(Register R, KnownBits &Known,
const APInt &DemandedElts,
unsigned Depth) {
const MachineInstr &MI = *MRI.getVRegDef(R);
computeKnownBitsForAlignment(Known, inferPtrAlignment(MI));
}
void GISelKnownBits::computeKnownBitsForAlignment(KnownBits &Known,
unsigned Align) {
if (Align)
// The low bits are known zero if the pointer is aligned.
Known.Zero.setLowBits(Log2_32(Align));
}
KnownBits GISelKnownBits::getKnownBits(MachineInstr &MI) {
return getKnownBits(MI.getOperand(0).getReg());
}
KnownBits GISelKnownBits::getKnownBits(Register R) {
KnownBits Known;
LLT Ty = MRI.getType(R);
APInt DemandedElts =
Ty.isVector() ? APInt::getAllOnesValue(Ty.getNumElements()) : APInt(1, 1);
computeKnownBitsImpl(R, Known, DemandedElts);
return Known;
}
bool GISelKnownBits::signBitIsZero(Register R) {
LLT Ty = MRI.getType(R);
unsigned BitWidth = Ty.getScalarSizeInBits();
return maskedValueIsZero(R, APInt::getSignMask(BitWidth));
}
APInt GISelKnownBits::getKnownZeroes(Register R) {
return getKnownBits(R).Zero;
}
APInt GISelKnownBits::getKnownOnes(Register R) { return getKnownBits(R).One; }
void GISelKnownBits::computeKnownBitsImpl(Register R, KnownBits &Known,
const APInt &DemandedElts,
unsigned Depth) {
MachineInstr &MI = *MRI.getVRegDef(R);
unsigned Opcode = MI.getOpcode();
LLT DstTy = MRI.getType(R);
unsigned BitWidth = DstTy.getSizeInBits();
Known = KnownBits(BitWidth); // Don't know anything
if (DstTy.isVector())
return; // TODO: Handle vectors.
if (Depth == getMaxDepth())
return;
if (!DemandedElts)
return; // No demanded elts, better to assume we don't know anything.
KnownBits Known2;
switch (Opcode) {
default:
TL.computeKnownBitsForTargetInstr(R, Known, DemandedElts, MRI, Depth);
break;
case TargetOpcode::G_CONSTANT: {
auto CstVal = getConstantVRegVal(R, MRI);
Known.One = *CstVal;
Known.Zero = ~Known.One;
break;
}
case TargetOpcode::G_FRAME_INDEX: {
computeKnownBitsForFrameIndex(R, Known, DemandedElts);
break;
}
case TargetOpcode::G_SUB: {
// If low bits are known to be zero in both operands, then we know they are
// going to be 0 in the result. Both addition and complement operations
// preserve the low zero bits.
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
Depth + 1);
unsigned KnownZeroLow = Known2.countMinTrailingZeros();
if (KnownZeroLow == 0)
break;
computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
Depth + 1);
KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
Known.Zero.setLowBits(KnownZeroLow);
break;
}
case TargetOpcode::G_XOR: {
computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
Depth + 1);
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
Depth + 1);
// Output known-0 bits are known if clear or set in both the LHS & RHS.
APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
// Output known-1 are known to be set if set in only one of the LHS, RHS.
Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
Known.Zero = KnownZeroOut;
break;
}
case TargetOpcode::G_GEP: {
// G_GEP is like G_ADD. FIXME: Is this true for all targets?
LLT Ty = MRI.getType(MI.getOperand(1).getReg());
if (DL.isNonIntegralAddressSpace(Ty.getAddressSpace()))
break;
LLVM_FALLTHROUGH;
}
case TargetOpcode::G_ADD: {
// Output known-0 bits are known if clear or set in both the low clear bits
// common to both LHS & RHS. For example, 8+(X<<3) is known to have the
// low 3 bits clear.
// Output known-0 bits are also known if the top bits of each input are
// known to be clear. For example, if one input has the top 10 bits clear
// and the other has the top 8 bits clear, we know the top 7 bits of the
// output must be clear.
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
Depth + 1);
unsigned KnownZeroHigh = Known2.countMinLeadingZeros();
unsigned KnownZeroLow = Known2.countMinTrailingZeros();
computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
Depth + 1);
KnownZeroHigh = std::min(KnownZeroHigh, Known2.countMinLeadingZeros());
KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
Known.Zero.setLowBits(KnownZeroLow);
if (KnownZeroHigh > 1)
Known.Zero.setHighBits(KnownZeroHigh - 1);
break;
}
case TargetOpcode::G_AND: {
// If either the LHS or the RHS are Zero, the result is zero.
computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
Depth + 1);
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
Depth + 1);
// Output known-1 bits are only known if set in both the LHS & RHS.
Known.One &= Known2.One;
// Output known-0 are known to be clear if zero in either the LHS | RHS.
Known.Zero |= Known2.Zero;
break;
}
case TargetOpcode::G_OR: {
// If either the LHS or the RHS are Zero, the result is zero.
computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
Depth + 1);
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
Depth + 1);
// Output known-0 bits are only known if clear in both the LHS & RHS.
Known.Zero &= Known2.Zero;
// Output known-1 are known to be set if set in either the LHS | RHS.
Known.One |= Known2.One;
break;
}
case TargetOpcode::G_MUL: {
computeKnownBitsImpl(MI.getOperand(2).getReg(), Known, DemandedElts,
Depth + 1);
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known2, DemandedElts,
Depth + 1);
// If low bits are zero in either operand, output low known-0 bits.
// Also compute a conservative estimate for high known-0 bits.
// More trickiness is possible, but this is sufficient for the
// interesting case of alignment computation.
unsigned TrailZ =
Known.countMinTrailingZeros() + Known2.countMinTrailingZeros();
unsigned LeadZ =
std::max(Known.countMinLeadingZeros() + Known2.countMinLeadingZeros(),
BitWidth) -
BitWidth;
Known.resetAll();
Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
break;
}
case TargetOpcode::G_SELECT: {
computeKnownBitsImpl(MI.getOperand(3).getReg(), Known, DemandedElts,
Depth + 1);
// If we don't know any bits, early out.
if (Known.isUnknown())
break;
computeKnownBitsImpl(MI.getOperand(2).getReg(), Known2, DemandedElts,
Depth + 1);
// Only known if known in both the LHS and RHS.
Known.One &= Known2.One;
Known.Zero &= Known2.Zero;
break;
}
case TargetOpcode::G_FCMP:
case TargetOpcode::G_ICMP: {
if (TL.getBooleanContents(DstTy.isVector(),
Opcode == TargetOpcode::G_FCMP) ==
TargetLowering::ZeroOrOneBooleanContent &&
BitWidth > 1)
Known.Zero.setBitsFrom(1);
break;
}
case TargetOpcode::G_SEXT: {
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
Depth + 1);
// If the sign bit is known to be zero or one, then sext will extend
// it to the top bits, else it will just zext.
Known = Known.sext(BitWidth);
break;
}
case TargetOpcode::G_ANYEXT: {
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
Depth + 1);
Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
break;
}
case TargetOpcode::G_LOAD: {
if (MI.hasOneMemOperand()) {
const MachineMemOperand *MMO = *MI.memoperands_begin();
if (const MDNode *Ranges = MMO->getRanges()) {
computeKnownBitsFromRangeMetadata(*Ranges, Known);
}
}
break;
}
case TargetOpcode::G_ZEXTLOAD: {
// Everything above the retrieved bits is zero
if (MI.hasOneMemOperand())
Known.Zero.setBitsFrom((*MI.memoperands_begin())->getSizeInBits());
break;
}
case TargetOpcode::G_ASHR:
case TargetOpcode::G_LSHR:
case TargetOpcode::G_SHL: {
KnownBits RHSKnown;
computeKnownBitsImpl(MI.getOperand(2).getReg(), RHSKnown, DemandedElts,
Depth + 1);
if (!RHSKnown.isConstant()) {
LLVM_DEBUG(
MachineInstr *RHSMI = MRI.getVRegDef(MI.getOperand(2).getReg());
dbgs() << '[' << Depth << "] Shift not known constant: " << *RHSMI);
break;
}
uint64_t Shift = RHSKnown.getConstant().getZExtValue();
LLVM_DEBUG(dbgs() << '[' << Depth << "] Shift is " << Shift << '\n');
computeKnownBitsImpl(MI.getOperand(1).getReg(), Known, DemandedElts,
Depth + 1);
switch (Opcode) {
case TargetOpcode::G_ASHR:
Known.Zero = Known.Zero.ashr(Shift);
Known.One = Known.One.ashr(Shift);
break;
case TargetOpcode::G_LSHR:
Known.Zero = Known.Zero.lshr(Shift);
Known.One = Known.One.lshr(Shift);
Known.Zero.setBitsFrom(Known.Zero.getBitWidth() - Shift);
break;
case TargetOpcode::G_SHL:
Known.Zero = Known.Zero.shl(Shift);
Known.One = Known.One.shl(Shift);
Known.Zero.setBits(0, Shift);
break;
}
break;
}
case TargetOpcode::G_INTTOPTR:
case TargetOpcode::G_PTRTOINT:
// Fall through and handle them the same as zext/trunc.
LLVM_FALLTHROUGH;
case TargetOpcode::G_ZEXT:
case TargetOpcode::G_TRUNC: {
Register SrcReg = MI.getOperand(1).getReg();
LLT SrcTy = MRI.getType(SrcReg);
unsigned SrcBitWidth = SrcTy.isPointer()
? DL.getIndexSizeInBits(SrcTy.getAddressSpace())
: SrcTy.getSizeInBits();
assert(SrcBitWidth && "SrcBitWidth can't be zero");
Known = Known.zextOrTrunc(SrcBitWidth, true);
computeKnownBitsImpl(SrcReg, Known, DemandedElts, Depth + 1);
Known = Known.zextOrTrunc(BitWidth, true);
if (BitWidth > SrcBitWidth)
Known.Zero.setBitsFrom(SrcBitWidth);
break;
}
}
assert(!Known.hasConflict() && "Bits known to be one AND zero?");
LLVM_DEBUG(dbgs() << "[" << Depth << "] Compute known bits: " << MI << "["
<< Depth << "] Computed for: " << MI << "[" << Depth
<< "] Known: 0x"
<< (Known.Zero | Known.One).toString(16, false) << "\n"
<< "[" << Depth << "] Zero: 0x"
<< Known.Zero.toString(16, false) << "\n"
<< "[" << Depth << "] One: 0x"
<< Known.One.toString(16, false) << "\n");
}
void GISelKnownBitsAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
MachineFunctionPass::getAnalysisUsage(AU);
}
bool GISelKnownBitsAnalysis::runOnMachineFunction(MachineFunction &MF) {
return false;
}
<|endoftext|>
|
<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
#ifdef __GNUG__
#pragma implementation
#endif
#include "config_ais_tool.h"
static char rcsid[] not_used = {"$Id$"};
#include <GetOpt.h>
#include "AISDODSFilter.h"
#include "debug.h"
AISDODSFilter::AISDODSFilter(int argc, char *argv[])
{
initialize(argc, argv);
}
/** This method is used to process command line options feed into the filter.
This is a virtual method and is called by DODSFilter's constructor. This
version uses the code in the DODSFilter version plus some new code. This
is probably \i not the best way to handle this sort of thing, but
splitting up the option processing is hard to do with GetOpt. */
int
AISDODSFilter::process_options(int argc, char *argv[]) throw(Error)
{
DBG(cerr << "Entering process_options... ");
d_object = unknown_type;
d_ais_db = "";
GetOpt getopt (argc, argv, "asDB:Vce:v:d:f:r:t:l:h?");
int option_char;
while ((option_char = getopt()) != EOF) {
switch (option_char) {
case 'a': d_object = dods_das; break;
case 's': d_object = dods_dds; break;
case 'D': d_object = dods_data; break;
case 'B': d_ais_db = getopt.optarg; break;
// case 'V': {cerr << "ais_tool: " << VERSION << endl; exit(0);}
case 'c': d_comp = true; break;
case 'e': d_ce = getopt.optarg; break;
case 'v': d_cgi_ver = getopt.optarg; break;
#if 0
case 'V': d_ver = true; break;
#endif
case 'd': d_anc_dir = getopt.optarg; break;
case 'f': d_anc_file = getopt.optarg; break;
case 'r': d_cache_dir = getopt.optarg; break;
case 'l':
d_conditional_request = true;
d_if_modified_since
= static_cast<time_t>(strtol(getopt.optarg, NULL, 10));
break;
default: d_bad_options = true; break;
}
}
DBGN(cerr << "exiting." << endl);
return getopt.optind; // Index of next option.
}
<commit_msg>AIS now uses the dap-server config.h header.<commit_after>
// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
#ifdef __GNUG__
#pragma implementation
#endif
#include "config.h"
static char rcsid[] not_used = {"$Id$"};
#include <GetOpt.h>
#include "AISDODSFilter.h"
#include "debug.h"
AISDODSFilter::AISDODSFilter(int argc, char *argv[])
{
initialize(argc, argv);
}
/** This method is used to process command line options feed into the filter.
This is a virtual method and is called by DODSFilter's constructor. This
version uses the code in the DODSFilter version plus some new code. This
is probably \i not the best way to handle this sort of thing, but
splitting up the option processing is hard to do with GetOpt. */
int
AISDODSFilter::process_options(int argc, char *argv[]) throw(Error)
{
DBG(cerr << "Entering process_options... ");
d_object = unknown_type;
d_ais_db = "";
GetOpt getopt (argc, argv, "asDB:Vce:v:d:f:r:t:l:h?");
int option_char;
while ((option_char = getopt()) != EOF) {
switch (option_char) {
case 'a': d_object = dods_das; break;
case 's': d_object = dods_dds; break;
case 'D': d_object = dods_data; break;
case 'B': d_ais_db = getopt.optarg; break;
// case 'V': {cerr << "ais_tool: " << VERSION << endl; exit(0);}
case 'c': d_comp = true; break;
case 'e': d_ce = getopt.optarg; break;
case 'v': d_cgi_ver = getopt.optarg; break;
#if 0
case 'V': d_ver = true; break;
#endif
case 'd': d_anc_dir = getopt.optarg; break;
case 'f': d_anc_file = getopt.optarg; break;
case 'r': d_cache_dir = getopt.optarg; break;
case 'l':
d_conditional_request = true;
d_if_modified_since
= static_cast<time_t>(strtol(getopt.optarg, NULL, 10));
break;
default: d_bad_options = true; break;
}
}
DBGN(cerr << "exiting." << endl);
return getopt.optind; // Index of next option.
}
<|endoftext|>
|
<commit_before>#include <cmath>
#include <limits>
#include <sstream>
#include <string>
#include <angles/angles.h>
#include <jaguar/diff_drive.h>
using can::JaguarBridge;
namespace jaguar {
template <typename T>
inline T sgn(T x)
{
if (x > 0) return 1;
else if (x < 0) return -1;
else return 0;
}
DiffDriveRobot::DiffDriveRobot(DiffDriveSettings const &settings)
: bridge_(settings.port)
, jag_broadcast_(bridge_)
, jag_left_(bridge_, settings.id_left)
, jag_right_(bridge_, settings.id_right)
, diag_init_(false)
// These are set by dynamic_reconfigure. However, there is a race condition
// in waiting for the callback. These are sane defaults to prevent
// generating +/-infinity or NaN during the race.
, accel_max_(settings.accel_max_mps2)
, wheel_circum_(0.0), wheel_sep_(0.0)
{
// This is necessary for the Jaguars to work after a fresh boot, even if
// we never called system_halt() or system_reset().
// FIXME: Convert from revolutions to meters using the robot model.
block(
jag_left_.config_brake_set(settings.brake),
jag_right_.config_brake_set(settings.brake)
);
speed_init();
odom_init();
diag_init();
jag_broadcast_.system_resume();
}
DiffDriveRobot::~DiffDriveRobot(void)
{
}
void DiffDriveRobot::drive(double v, double omega)
{
if (wheel_circum_ == 0 || wheel_sep_ == 0) return;
double const v_left = v - 0.5 * wheel_sep_ * omega;
double const v_right = v + 0.5 * wheel_sep_ * omega;
drive_raw(v_left, v_right);
}
void DiffDriveRobot::drive_raw(double v_left, double v_right)
{
if (wheel_circum_ == 0 || wheel_sep_ == 0) return;
target_rpm_left_ = v_left * 60 / wheel_circum_;
target_rpm_right_ = v_right * 60 / wheel_circum_;
}
void DiffDriveRobot::drive_spin(double dt)
{
if (wheel_circum_ == 0 || wheel_sep_ == 0) return;
double const residual_rpm_left = target_rpm_left_ - current_rpm_left_;
double const residual_rpm_right = target_rpm_right_ - current_rpm_right_;
// Cap the acceleration at the limiting value.
double const drpm_max = accel_max_ * dt * 60 / wheel_circum_;
if (fabs(residual_rpm_left) <= drpm_max) {
current_rpm_left_ = target_rpm_left_;
} else {
current_rpm_left_ += sgn(residual_rpm_left) * drpm_max;
}
if (fabs(residual_rpm_right) <= drpm_max) {
current_rpm_right_ = target_rpm_right_;
} else {
current_rpm_right_ += sgn(residual_rpm_right) * drpm_max;
}
block(
jag_left_.speed_set(current_rpm_left_),
jag_right_.speed_set(current_rpm_right_)
);
}
void DiffDriveRobot::drive_brake(bool braking)
{
jaguar::BrakeCoastSetting::Enum value;
if (braking) {
value = jaguar::BrakeCoastSetting::kOverrideBrake;
} else {
value = jaguar::BrakeCoastSetting::kOverrideCoast;
}
block(
jag_left_.config_brake_set(value),
jag_right_.config_brake_set(value)
);
}
void DiffDriveRobot::odom_set_circumference(double circum_m)
{
wheel_circum_ = circum_m;
}
void DiffDriveRobot::odom_set_separation(double separation_m)
{
wheel_sep_ = separation_m;
}
void DiffDriveRobot::odom_set_encoders(uint16_t cpr)
{
block(
jag_left_.config_encoders_set(cpr),
jag_right_.config_encoders_set(cpr)
);
}
void DiffDriveRobot::odom_set_rate(uint8_t rate_ms)
{
block(
jag_left_.periodic_enable(0, rate_ms),
jag_right_.periodic_enable(0, rate_ms)
);
}
void DiffDriveRobot::diag_set_rate(uint8_t rate_ms)
{
block(
jag_left_.periodic_enable(1, rate_ms),
jag_right_.periodic_enable(1, rate_ms)
);
}
void DiffDriveRobot::heartbeat(void)
{
jag_broadcast_.heartbeat();
}
/*
* Wheel Odometry
*/
void DiffDriveRobot::odom_init(void)
{
x_ = 0.0;
y_ = 0.0;
theta_ = 0.0;
// Ignore the first odometry message to establish the reference point.:
// TODO: This is wrong.
odom_left_.side = kLeft;
odom_left_.init = false;
odom_right_.side = kRight;
odom_right_.init = false;
// Just in case. This shouldn't really matter.
odom_left_.pos_prev = 0;
odom_left_.pos_curr = 0;
odom_right_.pos_prev = 0;
odom_right_.pos_curr = 0;
// Configure the Jaguars to use optical encoders. They are used as both a
// speed reference for velocity control and position reference for
// odometry. As such, they must be configured for position control even
// though we are are using speed control mode.
block(
jag_left_.position_set_reference(PositionReference::kQuadratureEncoder),
jag_right_.position_set_reference(PositionReference::kQuadratureEncoder)
);
block(
jag_left_.periodic_config_odom(0,
boost::bind(&DiffDriveRobot::odom_update, this,
boost::ref(odom_left_), _1, _2)),
jag_right_.periodic_config_odom(0,
boost::bind(&DiffDriveRobot::odom_update, this,
boost::ref(odom_right_), _1, _2))
);
}
void DiffDriveRobot::odom_attach(boost::function<OdometryCallback> callback)
{
odom_signal_.connect(callback);
}
void DiffDriveRobot::diag_attach(
boost::function<DiagnosticsCallback> callback_left,
boost::function<DiagnosticsCallback> callback_right)
{
diag_left_signal_.connect(callback_left);
diag_right_signal_.connect(callback_right);
}
void DiffDriveRobot::estop_attach(boost::function<EStopCallback> callback)
{
estop_signal_.connect(callback);
}
void DiffDriveRobot::odom_update(Odometry &odom, double pos, double vel)
{
if (wheel_circum_ == 0 || wheel_sep_ == 0) return;
odom.pos_prev = odom.pos_curr;
odom.pos_curr = pos;
odom.vel = vel;
// Skip the first sample from each wheel. This is necessary in case the
// encoders came up in an unknown state.
if (!odom.init) {
odom.pos_prev = pos;
odom.pos_curr = pos;
odom.init = true;
return;
}
// Update the state variables to indicate which odometry readings we
// already have. Trigger a callback once we've received a pair of readings.
if (odom_state_ == kNone) {
odom_state_ = odom.side;
} else if (odom.side != odom_state_) {
// Compute the difference between the last two updates. Speed is
// measured in RPMs, so all of these values are measured in
// revolutions.
double revs_left = odom_left_.pos_curr - odom_left_.pos_prev;
double revs_right = odom_right_.pos_curr - odom_right_.pos_prev;
std::swap(revs_left, revs_right);
// Convert from revolutions to meters.
double const meters_left = revs_left * wheel_circum_;
double const meters_right = revs_right * wheel_circum_;
// Use the robot model to convert from wheel odometry to
// two-dimensional motion.
// TODO: Switch to a better odometry model.
double const meters = (meters_left + meters_right) / 2;
double const radians = (meters_left - meters_right) / wheel_sep_;
x_ += meters * cos(theta_);
y_ += meters * sin(theta_);
theta_ = angles::normalize_angle(theta_ + radians);
// Estimate the robot's current velocity.
double const v_linear = (odom_right_.vel + odom_left_.vel) / 2;
double const omega = (odom_right_.vel - odom_left_.vel) / wheel_sep_;
odom_signal_(x_, y_, theta_, v_linear, omega, meters_left, meters_right);
odom_state_ = kNone;
} else {
std::cerr << "war: periodic update message was dropped" << std::endl;
}
}
/*
* Diagnostics
*/
void DiffDriveRobot::diag_init(void)
{
block(
jag_left_.periodic_config_diag(1,
boost::bind(&DiffDriveRobot::diag_update, this,
kLeft, boost::ref(diag_left_), _1, _2, _3, _4)
),
jag_right_.periodic_config_diag(1,
boost::bind(&DiffDriveRobot::diag_update, this,
kRight, boost::ref(diag_right_), _1, _2, _3, _4)
)
);
// TODO: Make this a parameter.
block(
jag_left_.periodic_enable(1, 500),
jag_right_.periodic_enable(1, 500)
);
}
void DiffDriveRobot::diag_update(
Side side, Diagnostics &diag,
LimitStatus::Enum limits, Fault::Enum faults,
double voltage, double temperature)
{
bool const estop_before = diag_left_.stopped || diag_right_.stopped;
// TODO: Check for a fault.
diag.stopped = !(limits & 0x03);
diag.voltage = voltage;
diag.temperature = temperature;
bool const estop_after = diag_left_.stopped || diag_right_.stopped;
// Only trigger an e-stop callback if the state changed. We don't know the
// initial state, so the first update always triggers a callback.
if (!diag_init_ || estop_after != estop_before) {
estop_signal_(estop_after);
}
diag_init_ = true;
// Other diagnostics (i.e. bus voltage and temperature) use separate left
// and right callbacks.
if (side == kLeft) {
diag_left_signal_(voltage, temperature);
} else if (side == kRight) {
diag_right_signal_(voltage, temperature);
}
}
/*
* Speed Control
*/
void DiffDriveRobot::speed_set_p(double p)
{
block(
jag_left_.speed_set_p(p),
jag_right_.speed_set_p(p)
);
}
void DiffDriveRobot::speed_set_i(double i)
{
block(
jag_left_.speed_set_i(i),
jag_right_.speed_set_i(i)
);
}
void DiffDriveRobot::speed_set_d(double d)
{
block(
jag_left_.speed_set_d(d),
jag_right_.speed_set_d(d)
);
}
void DiffDriveRobot::speed_init(void)
{
block(
jag_left_.speed_set_reference(SpeedReference::kQuadratureEncoder),
jag_right_.speed_set_reference(SpeedReference::kQuadratureEncoder)
);
block(
jag_left_.speed_enable(),
jag_right_.speed_enable()
);
}
/*
* Helper Methods
*/
void DiffDriveRobot::block(can::TokenPtr t1, can::TokenPtr t2)
{
t1->block();
t2->block();
}
};
<commit_msg>improved differential drive model<commit_after>#include <cmath>
#include <limits>
#include <sstream>
#include <string>
#include <angles/angles.h>
#include <jaguar/diff_drive.h>
using can::JaguarBridge;
namespace jaguar {
template <typename T>
inline T sgn(T x)
{
if (x > 0) return 1;
else if (x < 0) return -1;
else return 0;
}
DiffDriveRobot::DiffDriveRobot(DiffDriveSettings const &settings)
: bridge_(settings.port)
, jag_broadcast_(bridge_)
, jag_left_(bridge_, settings.id_left)
, jag_right_(bridge_, settings.id_right)
, diag_init_(false)
// These are set by dynamic_reconfigure. However, there is a race condition
// in waiting for the callback. These are sane defaults to prevent
// generating +/-infinity or NaN during the race.
, accel_max_(settings.accel_max_mps2)
, wheel_circum_(0.0), wheel_sep_(0.0)
{
// This is necessary for the Jaguars to work after a fresh boot, even if
// we never called system_halt() or system_reset().
block(
jag_left_.config_brake_set(settings.brake),
jag_right_.config_brake_set(settings.brake)
);
speed_init();
odom_init();
diag_init();
jag_broadcast_.system_resume();
}
DiffDriveRobot::~DiffDriveRobot(void)
{
}
void DiffDriveRobot::drive(double v, double omega)
{
if (wheel_circum_ == 0 || wheel_sep_ == 0) return;
double const v_left = v - 0.5 * wheel_sep_ * omega;
double const v_right = v + 0.5 * wheel_sep_ * omega;
drive_raw(v_left, v_right);
}
void DiffDriveRobot::drive_raw(double v_left, double v_right)
{
if (wheel_circum_ == 0 || wheel_sep_ == 0) return;
target_rpm_left_ = v_left * 60 / wheel_circum_;
target_rpm_right_ = v_right * 60 / wheel_circum_;
}
void DiffDriveRobot::drive_spin(double dt)
{
if (wheel_circum_ == 0 || wheel_sep_ == 0) return;
double const residual_rpm_left = target_rpm_left_ - current_rpm_left_;
double const residual_rpm_right = target_rpm_right_ - current_rpm_right_;
// Cap the acceleration at the limiting value.
double const drpm_max = accel_max_ * dt * 60 / wheel_circum_;
if (fabs(residual_rpm_left) <= drpm_max) {
current_rpm_left_ = target_rpm_left_;
} else {
current_rpm_left_ += sgn(residual_rpm_left) * drpm_max;
}
if (fabs(residual_rpm_right) <= drpm_max) {
current_rpm_right_ = target_rpm_right_;
} else {
current_rpm_right_ += sgn(residual_rpm_right) * drpm_max;
}
block(
jag_left_.speed_set(current_rpm_left_),
jag_right_.speed_set(current_rpm_right_)
);
}
void DiffDriveRobot::drive_brake(bool braking)
{
jaguar::BrakeCoastSetting::Enum value;
if (braking) {
value = jaguar::BrakeCoastSetting::kOverrideBrake;
} else {
value = jaguar::BrakeCoastSetting::kOverrideCoast;
}
block(
jag_left_.config_brake_set(value),
jag_right_.config_brake_set(value)
);
}
void DiffDriveRobot::odom_set_circumference(double circum_m)
{
wheel_circum_ = circum_m;
}
void DiffDriveRobot::odom_set_separation(double separation_m)
{
wheel_sep_ = separation_m;
}
void DiffDriveRobot::odom_set_encoders(uint16_t cpr)
{
block(
jag_left_.config_encoders_set(cpr),
jag_right_.config_encoders_set(cpr)
);
}
void DiffDriveRobot::odom_set_rate(uint8_t rate_ms)
{
block(
jag_left_.periodic_enable(0, rate_ms),
jag_right_.periodic_enable(0, rate_ms)
);
}
void DiffDriveRobot::diag_set_rate(uint8_t rate_ms)
{
block(
jag_left_.periodic_enable(1, rate_ms),
jag_right_.periodic_enable(1, rate_ms)
);
}
void DiffDriveRobot::heartbeat(void)
{
jag_broadcast_.heartbeat();
}
/*
* Wheel Odometry
*/
void DiffDriveRobot::odom_init(void)
{
x_ = 0.0;
y_ = 0.0;
theta_ = 0.0;
// Ignore the first odometry message to establish the reference point.:
// TODO: This is wrong.
odom_left_.side = kLeft;
odom_left_.init = false;
odom_right_.side = kRight;
odom_right_.init = false;
// Just in case. This shouldn't really matter.
odom_left_.pos_prev = 0;
odom_left_.pos_curr = 0;
odom_right_.pos_prev = 0;
odom_right_.pos_curr = 0;
// Configure the Jaguars to use optical encoders. They are used as both a
// speed reference for velocity control and position reference for
// odometry. As such, they must be configured for position control even
// though we are are using speed control mode.
block(
jag_left_.position_set_reference(PositionReference::kQuadratureEncoder),
jag_right_.position_set_reference(PositionReference::kQuadratureEncoder)
);
block(
jag_left_.periodic_config_odom(0,
boost::bind(&DiffDriveRobot::odom_update, this,
boost::ref(odom_left_), _1, _2)),
jag_right_.periodic_config_odom(0,
boost::bind(&DiffDriveRobot::odom_update, this,
boost::ref(odom_right_), _1, _2))
);
}
void DiffDriveRobot::odom_attach(boost::function<OdometryCallback> callback)
{
odom_signal_.connect(callback);
}
void DiffDriveRobot::diag_attach(
boost::function<DiagnosticsCallback> callback_left,
boost::function<DiagnosticsCallback> callback_right)
{
diag_left_signal_.connect(callback_left);
diag_right_signal_.connect(callback_right);
}
void DiffDriveRobot::estop_attach(boost::function<EStopCallback> callback)
{
estop_signal_.connect(callback);
}
void DiffDriveRobot::odom_update(Odometry &odom, double pos, double vel)
{
if (wheel_circum_ == 0 || wheel_sep_ == 0) return;
odom.pos_prev = odom.pos_curr;
odom.pos_curr = pos;
odom.vel = vel;
// Skip the first sample from each wheel. This is necessary in case the
// encoders came up in an unknown state.
if (!odom.init) {
odom.pos_prev = pos;
odom.pos_curr = pos;
odom.init = true;
return;
}
// Update the state variables to indicate which odometry readings we
// already have. Trigger a callback once we've received a pair of readings.
if (odom_state_ == kNone) {
odom_state_ = odom.side;
} else if (odom.side != odom_state_) {
// Compute the difference between the last two updates. Speed is
// measured in RPMs, so all of these values are measured in
// revolutions.
double revs_left = odom_left_.pos_curr - odom_left_.pos_prev;
double revs_right = odom_right_.pos_curr - odom_right_.pos_prev;
std::swap(revs_left, revs_right);
// Convert from revolutions to meters.
double const meters_left = revs_left * wheel_circum_;
double const meters_right = revs_right * wheel_circum_;
// Use the robot model to convert from wheel odometry to
// two-dimensional motion.
// TODO: Switch to a better odometry model.
double const meters = (meters_left + meters_right) / 2;
double const radians = (meters_left - meters_right) / wheel_sep_;
x_ += meters * cos(theta_ + radians / 2);
y_ += meters * sin(theta_ + radians / 2);
theta_ = angles::normalize_angle(theta_ + radians);
// Estimate the robot's current velocity.
double const v_linear = (odom_right_.vel + odom_left_.vel) / 2;
double const omega = (odom_right_.vel - odom_left_.vel) / wheel_sep_;
odom_signal_(x_, y_, theta_, v_linear, omega, meters_left, meters_right);
odom_state_ = kNone;
} else {
std::cerr << "war: periodic update message was dropped" << std::endl;
}
}
/*
* Diagnostics
*/
void DiffDriveRobot::diag_init(void)
{
block(
jag_left_.periodic_config_diag(1,
boost::bind(&DiffDriveRobot::diag_update, this,
kLeft, boost::ref(diag_left_), _1, _2, _3, _4)
),
jag_right_.periodic_config_diag(1,
boost::bind(&DiffDriveRobot::diag_update, this,
kRight, boost::ref(diag_right_), _1, _2, _3, _4)
)
);
// TODO: Make this a parameter.
block(
jag_left_.periodic_enable(1, 500),
jag_right_.periodic_enable(1, 500)
);
}
void DiffDriveRobot::diag_update(
Side side, Diagnostics &diag,
LimitStatus::Enum limits, Fault::Enum faults,
double voltage, double temperature)
{
bool const estop_before = diag_left_.stopped || diag_right_.stopped;
// TODO: Check for a fault.
diag.stopped = !(limits & 0x03);
diag.voltage = voltage;
diag.temperature = temperature;
bool const estop_after = diag_left_.stopped || diag_right_.stopped;
// Only trigger an e-stop callback if the state changed. We don't know the
// initial state, so the first update always triggers a callback.
if (!diag_init_ || estop_after != estop_before) {
estop_signal_(estop_after);
}
diag_init_ = true;
// Other diagnostics (i.e. bus voltage and temperature) use separate left
// and right callbacks.
if (side == kLeft) {
diag_left_signal_(voltage, temperature);
} else if (side == kRight) {
diag_right_signal_(voltage, temperature);
}
}
/*
* Speed Control
*/
void DiffDriveRobot::speed_set_p(double p)
{
block(
jag_left_.speed_set_p(p),
jag_right_.speed_set_p(p)
);
}
void DiffDriveRobot::speed_set_i(double i)
{
block(
jag_left_.speed_set_i(i),
jag_right_.speed_set_i(i)
);
}
void DiffDriveRobot::speed_set_d(double d)
{
block(
jag_left_.speed_set_d(d),
jag_right_.speed_set_d(d)
);
}
void DiffDriveRobot::speed_init(void)
{
block(
jag_left_.speed_set_reference(SpeedReference::kQuadratureEncoder),
jag_right_.speed_set_reference(SpeedReference::kQuadratureEncoder)
);
block(
jag_left_.speed_enable(),
jag_right_.speed_enable()
);
}
/*
* Helper Methods
*/
void DiffDriveRobot::block(can::TokenPtr t1, can::TokenPtr t2)
{
t1->block();
t2->block();
}
};
<|endoftext|>
|
<commit_before>/*
* This file is part of SKATRAK Playground.
*
* SKATRAK Playground is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/> or
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
* Floor, Boston, MA 02110-1301 USA
*
* Sergio M. Afonso Fumero <theSkatrak@gmail.com>
*/
/* Inclusin de cabeceras necesarias */
// Cabecera de la clase
#include "inifile.hpp"
// Estndar
#include <string>
#include <fstream>
using std::string;
using std::ifstream;
// Propias
#include "SKATRAK_PLAYGROUND.hpp"
#include "str_operations.hpp"
/**
* @brief Constructor. Inicializacin de variables.
*/
inifile_t::inifile_t(): error(NOERROR)
{
}
/**
* @brief Constructor. Inicializa variables y abre un fichero .ini
* @param path Ruta del fichero .ini a abrir.
* @note La extensin del fichero no tiene por qu ser '.ini', pero se recomienda que sea as.
*/
inifile_t::inifile_t(string path): error(NOERROR) {
open(path);
}
/**
* @brief Destructor. Cierra el fichero asociado.
*/
inifile_t::~inifile_t(){
if(input.is_open())
input.close();
}
/**
* @brief Abre un fichero para la lectura de los datos.
* @param path Ruta del fichero .ini a abrir.
*/
void inifile_t::open(string path){
string compPath = INI_PATH;
compPath += path;
if(input.is_open())
input.close();
input.open(compPath.c_str());
if(input.is_open())
error = NOERROR;
else {
fprintf(stderr, "inifile_t::open: No se ha podido abrir \"%s\".\n", compPath.c_str());
error = FILENOFOUND;
}
}
/**
* @brief Lee un entero guardado en una variable en el archivo .ini.
* @param section Nombre de la seccin donde est guardada la variable. No se debe poner entre corchetes.
* @param varName Nombre de la variable a buscar en el archivo.
* @return El valor de la variable o '0' si hubo un error.
* @note Si devuelve el valor '0', utilizar errorStatus para decidir si fue un error o la variable tiene ese valor.
*/
int inifile_t::readInt(string section, string varName){
// Comprobamos que haya un archivo cargado correctamente
if(!input.is_open()){
fprintf(stderr, "inifile_t::readInt: No se ha abierto un archivo, as que no se pueden leer valores.\n");
error = NOTOPENED;
return 0;
}
// Leemos el contenido de la variable y lo traducimos a entero
string content = readString(section, varName);
int value = str_op::strtoint(content.c_str());
// Comprobamos que la lectura haya sido correcta y devolvemos el resultado
if(value != ERROR_INT_VAL){
error = NOERROR;
return value;
}
else {
fprintf(stderr, "inifile_t::readInt: El contenido de la variable \"%s\" no es un entero.\n", varName.c_str());
error = WRONGTYPE;
return 0;
}
}
/**
* @brief Lee un flotante de doble precisin guardado en una variable en el archivo .ini.
* @param section Nombre de la seccin donde est guardada la variable. No se debe poner entre corchetes.
* @param varName Nombre de la variable a buscar en el archivo.
* @return El valor de la variable o '0' si hubo un error.
* @note Si devuelve el valor '0', utilizar errorStatus para decidir si fue un error o la variable tiene ese valor.
*/
double inifile_t::readDouble(string section, string varName){
// Comprobamos que haya un archivo cargado correctamente
if(!input.is_open()){
fprintf(stderr, "inifile_t::readDouble: No se ha abierto un archivo, as que no se pueden leer valores.\n");
error = NOTOPENED;
return 0.0;
}
// Leemos el contenido de la variable y lo traducimos a flotante
string content = readString(section, varName);
double value = str_op::strtodouble(content.c_str());
// Comprobamos que la lectura haya sido correcta y devolvemos el resultado
if(value != ERROR_DOUBLE_VAL){
error = NOERROR;
return value;
}
else {
fprintf(stderr, "inifile_t::readDouble: El contenido de la variable \"%s\" no es un nmero decimal.\n", varName.c_str());
error = WRONGTYPE;
return ERROR_DOUBLE_VAL;
}
}
/**
* @brief Lee una cadena de caracteres guardada en una variable en el archivo .ini.
* @param section Nombre de la seccin donde est guardada la variable. No se debe poner entre corchetes.
* @param varName Nombre de la variable a buscar en el archivo.
* @return El valor de la variable o la cadena vaca si hubo un error.
* @note Si devuelve la cadena vaca, utilizar errorStatus para decidir si fue un error o la variable tiene ese valor.
*/
string inifile_t::readString(string section, string varName){
// Comprobamos que haya un archivo cargado correctamente
if(!input.is_open()){
fprintf(stderr, "inifile_t::readString: No se ha abierto un archivo, as que no se pueden leer valores.\n");
error = NOTOPENED;
return "";
}
int i;
string temp = ""; // Esta variable va leyendo cada lnea del fichero
string temp2 = "[";
temp2 += section; // temp2 = "[SECCION]"
temp2 += "]";
// Recolocamos el puntero de lectura al principio del fichero
input.seekg(std::ios::beg);
while(!input.eof()){
// Buscamos la seccin
getline(input, temp);
if(temp2 == temp){
temp2 = varName; // temp2 = NombreDeLaVariable
while(!input.eof()){
temp = "";
getline(input, temp);
// Comprobamos que no hemos pasado de seccin
if(temp[0] != '['){
// Comprobamos que no sea un comentario
if(temp[0] != '#'){
// Nos situamos en el primer '=' de la cadena (o al final si no hay ninguno)
for(i = 0; temp[i] != '=' && temp[i] != '\0'; i++);
// Comprobamos que tiene contenido
if(temp[i] != '\0'){
// Comprobamos que las variables tienen el mismo nombre
if(strncmp(temp.c_str(), temp2.c_str(), i) == 0){
// Borramos la cadena desde el principio hasta el '=' includo
temp.erase(0, i+1);
error = NOERROR;
// Devolvemos el valor interpretado
return temp;
}
// Si no tienen el mismo nombre, seguimos buscando
}
// No sabemos qu es esto, as que seguimos buscando
}
// Si es un comentario seguimos buscando
}
// Como nos hemos pasado de seccin, quiere decir que la variable no existe en esa seccin
else {
fprintf(stderr, "inifile_t::readString: No se encuentra la variable \"%s\" en la seccin \"[%s]\" en el archivo.\n", varName.c_str(), section.c_str());
error = NOEXISTVAR;
return "";
}
}
}
temp = "";
}
fprintf(stderr, "inifile_t::readString: No se encuentra la seccin \"[%s]\" en el archivo.\n", section.c_str());
error = NOEXISTSECTION;
return "";
}
/**
* @brief Lee un booleano guardado en una variable en el archivo .ini.
* @param section Nombre de la seccin donde est guardada la variable. No se debe poner entre corchetes.
* @param varName Nombre de la variable a buscar en el archivo.
* @return El valor de la variable o 'false' si hubo un error.
* @note Si devuelve el valor 'false', utilizar errorStatus para decidir si fue un error o la variable tiene ese valor.
*/
bool inifile_t::readBool(string section, string varName){
string temp = readString(section, varName);
if(strcasecmp(temp.c_str(), "true") == 0 || strcasecmp(temp.c_str(), "1") == 0){
error = NOERROR;
return true;
}
if(strcasecmp(temp.c_str(), "false") == 0 || strcasecmp(temp.c_str(), "0") == 0){
error = NOERROR;
return false;
}
fprintf(stderr, "inifile_t::readBool: El contenido de la variable \"%s\" no es un valor booleano.\n", varName.c_str());
error = WRONGTYPE;
return false;
}
/**
* @brif Devuelve una cadena que describe el estado de error de la ltima operacin.
* @return Cadena de descripcin.
*/
string inifile_t::errorString(void){
string aux;
switch(error){
case NOERROR:
aux = "La ltima operacin concluy sin errores";
break;
case FILENOFOUND:
aux = "Se ha intentado abrir un archivo inexistente";
break;
case NOTOPENED:
aux = "Se ha inentado acceder a datos sin abrir ningn archivo";
break;
case WRONGTYPE:
aux = "Se ha intentado leer una variable de un tipo distinto";
break;
case NOEXISTVAR:
aux = "La variable con el nombre especificado no existe en la seccin especificada";
break;
case NOEXISTSECTION:
aux = "La seccin especificada no existe";
break;
}
return aux;
}
<commit_msg>Librería que faltaba añadida<commit_after>/*
* This file is part of SKATRAK Playground.
*
* SKATRAK Playground is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/> or
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
* Floor, Boston, MA 02110-1301 USA
*
* Sergio M. Afonso Fumero <theSkatrak@gmail.com>
*/
/* Inclusin de cabeceras necesarias */
// Cabecera de la clase
#include "inifile.hpp"
// Estndar
#include <string>
#include <cstring>
#include <fstream>
using std::string;
using std::ifstream;
// Propias
#include "SKATRAK_PLAYGROUND.hpp"
#include "str_operations.hpp"
/**
* @brief Constructor. Inicializacin de variables.
*/
inifile_t::inifile_t(): error(NOERROR)
{
}
/**
* @brief Constructor. Inicializa variables y abre un fichero .ini
* @param path Ruta del fichero .ini a abrir.
* @note La extensin del fichero no tiene por qu ser '.ini', pero se recomienda que sea as.
*/
inifile_t::inifile_t(string path): error(NOERROR) {
open(path);
}
/**
* @brief Destructor. Cierra el fichero asociado.
*/
inifile_t::~inifile_t(){
if(input.is_open())
input.close();
}
/**
* @brief Abre un fichero para la lectura de los datos.
* @param path Ruta del fichero .ini a abrir.
*/
void inifile_t::open(string path){
string compPath = INI_PATH;
compPath += path;
if(input.is_open())
input.close();
input.open(compPath.c_str());
if(input.is_open())
error = NOERROR;
else {
fprintf(stderr, "inifile_t::open: No se ha podido abrir \"%s\".\n", compPath.c_str());
error = FILENOFOUND;
}
}
/**
* @brief Lee un entero guardado en una variable en el archivo .ini.
* @param section Nombre de la seccin donde est guardada la variable. No se debe poner entre corchetes.
* @param varName Nombre de la variable a buscar en el archivo.
* @return El valor de la variable o '0' si hubo un error.
* @note Si devuelve el valor '0', utilizar errorStatus para decidir si fue un error o la variable tiene ese valor.
*/
int inifile_t::readInt(string section, string varName){
// Comprobamos que haya un archivo cargado correctamente
if(!input.is_open()){
fprintf(stderr, "inifile_t::readInt: No se ha abierto un archivo, as que no se pueden leer valores.\n");
error = NOTOPENED;
return 0;
}
// Leemos el contenido de la variable y lo traducimos a entero
string content = readString(section, varName);
int value = str_op::strtoint(content.c_str());
// Comprobamos que la lectura haya sido correcta y devolvemos el resultado
if(value != ERROR_INT_VAL){
error = NOERROR;
return value;
}
else {
fprintf(stderr, "inifile_t::readInt: El contenido de la variable \"%s\" no es un entero.\n", varName.c_str());
error = WRONGTYPE;
return 0;
}
}
/**
* @brief Lee un flotante de doble precisin guardado en una variable en el archivo .ini.
* @param section Nombre de la seccin donde est guardada la variable. No se debe poner entre corchetes.
* @param varName Nombre de la variable a buscar en el archivo.
* @return El valor de la variable o '0' si hubo un error.
* @note Si devuelve el valor '0', utilizar errorStatus para decidir si fue un error o la variable tiene ese valor.
*/
double inifile_t::readDouble(string section, string varName){
// Comprobamos que haya un archivo cargado correctamente
if(!input.is_open()){
fprintf(stderr, "inifile_t::readDouble: No se ha abierto un archivo, as que no se pueden leer valores.\n");
error = NOTOPENED;
return 0.0;
}
// Leemos el contenido de la variable y lo traducimos a flotante
string content = readString(section, varName);
double value = str_op::strtodouble(content.c_str());
// Comprobamos que la lectura haya sido correcta y devolvemos el resultado
if(value != ERROR_DOUBLE_VAL){
error = NOERROR;
return value;
}
else {
fprintf(stderr, "inifile_t::readDouble: El contenido de la variable \"%s\" no es un nmero decimal.\n", varName.c_str());
error = WRONGTYPE;
return ERROR_DOUBLE_VAL;
}
}
/**
* @brief Lee una cadena de caracteres guardada en una variable en el archivo .ini.
* @param section Nombre de la seccin donde est guardada la variable. No se debe poner entre corchetes.
* @param varName Nombre de la variable a buscar en el archivo.
* @return El valor de la variable o la cadena vaca si hubo un error.
* @note Si devuelve la cadena vaca, utilizar errorStatus para decidir si fue un error o la variable tiene ese valor.
*/
string inifile_t::readString(string section, string varName){
// Comprobamos que haya un archivo cargado correctamente
if(!input.is_open()){
fprintf(stderr, "inifile_t::readString: No se ha abierto un archivo, as que no se pueden leer valores.\n");
error = NOTOPENED;
return "";
}
int i;
string temp = ""; // Esta variable va leyendo cada lnea del fichero
string temp2 = "[";
temp2 += section; // temp2 = "[SECCION]"
temp2 += "]";
// Recolocamos el puntero de lectura al principio del fichero
input.seekg(std::ios::beg);
while(!input.eof()){
// Buscamos la seccin
getline(input, temp);
if(temp2 == temp){
temp2 = varName; // temp2 = NombreDeLaVariable
while(!input.eof()){
temp = "";
getline(input, temp);
// Comprobamos que no hemos pasado de seccin
if(temp[0] != '['){
// Comprobamos que no sea un comentario
if(temp[0] != '#'){
// Nos situamos en el primer '=' de la cadena (o al final si no hay ninguno)
for(i = 0; temp[i] != '=' && temp[i] != '\0'; i++);
// Comprobamos que tiene contenido
if(temp[i] != '\0'){
// Comprobamos que las variables tienen el mismo nombre
if(strncmp(temp.c_str(), temp2.c_str(), i) == 0){
// Borramos la cadena desde el principio hasta el '=' includo
temp.erase(0, i+1);
error = NOERROR;
// Devolvemos el valor interpretado
return temp;
}
// Si no tienen el mismo nombre, seguimos buscando
}
// No sabemos qu es esto, as que seguimos buscando
}
// Si es un comentario seguimos buscando
}
// Como nos hemos pasado de seccin, quiere decir que la variable no existe en esa seccin
else {
fprintf(stderr, "inifile_t::readString: No se encuentra la variable \"%s\" en la seccin \"[%s]\" en el archivo.\n", varName.c_str(), section.c_str());
error = NOEXISTVAR;
return "";
}
}
}
temp = "";
}
fprintf(stderr, "inifile_t::readString: No se encuentra la seccin \"[%s]\" en el archivo.\n", section.c_str());
error = NOEXISTSECTION;
return "";
}
/**
* @brief Lee un booleano guardado en una variable en el archivo .ini.
* @param section Nombre de la seccin donde est guardada la variable. No se debe poner entre corchetes.
* @param varName Nombre de la variable a buscar en el archivo.
* @return El valor de la variable o 'false' si hubo un error.
* @note Si devuelve el valor 'false', utilizar errorStatus para decidir si fue un error o la variable tiene ese valor.
*/
bool inifile_t::readBool(string section, string varName){
string temp = readString(section, varName);
if(strcasecmp(temp.c_str(), "true") == 0 || strcasecmp(temp.c_str(), "1") == 0){
error = NOERROR;
return true;
}
if(strcasecmp(temp.c_str(), "false") == 0 || strcasecmp(temp.c_str(), "0") == 0){
error = NOERROR;
return false;
}
fprintf(stderr, "inifile_t::readBool: El contenido de la variable \"%s\" no es un valor booleano.\n", varName.c_str());
error = WRONGTYPE;
return false;
}
/**
* @brif Devuelve una cadena que describe el estado de error de la ltima operacin.
* @return Cadena de descripcin.
*/
string inifile_t::errorString(void){
string aux;
switch(error){
case NOERROR:
aux = "La ltima operacin concluy sin errores";
break;
case FILENOFOUND:
aux = "Se ha intentado abrir un archivo inexistente";
break;
case NOTOPENED:
aux = "Se ha inentado acceder a datos sin abrir ningn archivo";
break;
case WRONGTYPE:
aux = "Se ha intentado leer una variable de un tipo distinto";
break;
case NOEXISTVAR:
aux = "La variable con el nombre especificado no existe en la seccin especificada";
break;
case NOEXISTSECTION:
aux = "La seccin especificada no existe";
break;
}
return aux;
}
<|endoftext|>
|
<commit_before>//
// hopf.cpp
// allovsr
//
// Created by Pablo Colapinto on 11/28/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
//vsr Includes
#include "vsr/vsr.h"
#include "vsr/vsr_op.h"
#include "vsr/vsr_draw.h"
#include "vsr/vsr_camera.h"
#include "vsr/vsr_fiber.h"
//allo includes
#include "allocore/al_Allocore.hpp"
#include "allocore/io/al_ControlNav.hpp"
#include "alloGLV/al_controlGLV.hpp"
//Glue
#include "allovsr/al_vsrInterface.hpp"
#include <iostream>
using namespace al;
using namespace vsr;
#define PRESET \
static bool bSet = 0;\
if (!bSet) { \
bSet = 1;
void knot(al::VsrApp& app){
HopfFiber hf;
//A Circle you can touch (in the xz plane)
static Circle ca = CXZ(1);
app.interface.touch(ca);
//The Axis of the Circle
DualLine cb = Inf(1) <= ca;
//Normalized . . .
cb = cb.runit();
//A Point you can Touch
static Point pt = PT(1,0,0);
app.interface.touch(pt);
//GUI
static double m,n,amt,iter;
static double theta, phi;
PRESET
app.glv.gui(m,"m",0,10)(n,"n",0,10)(amt,"amt",-10,10)(iter,"iter",1,1000);
app.glv.gui(theta)(phi);
m = 1; n = 5; amt = .005; iter = 1000;
}
vector<Cir> cp = hf.poles(-1 + theta * 2,phi);
DRAW(cp[0]); DRAW(cp[1]);
//A Point Pair "Boost" Generator . . .
PointPair tp = ca.dual() * PI/m + cb * PI/n;
//A Point Pair "Boost" Generator . . .
PointPair tp2 = cp[0].dual() * PI/m + cp[1].dual() * PI/n;
vector<Pnt> vp;
Point np = pt;
for (int i = 0; i < iter; ++i){
np = Ro::loc( np.sp( Gen::bst( tp2*amt ) ) );
vp.push_back(np);
}
//DRAW ROUTINES:
//Draw the Circle and its Axis, and the Point
DRAW3(ca,0,0,1); DRAW3(cb,0,1,0); DRAW3(pt,1,0,0);
//DRAW the Knot Strip
glBegin(GL_LINE_STRIP);
for (int i = 0; i < vp.size(); ++i){
GL::vertex(vp[i].w());
}
glEnd();
}
class MyApp : public al::VsrApp {
public:
MyApp() : al::VsrApp() {
}
virtual void onDraw(Graphics& gl){
//Model Transform
Rot t = Gen::aa( scene().model.rot() );
GL::rotate( t.w() );
knot(*this);
}
};
MyApp app;
int main(int argc, const char * argv[]){
app.create(Window::Dim(800, 600), "Allovsr Demo: Hopf Fibration");
MainLoop::start();
return 0;
}
<commit_msg>fix allovsr knot example<commit_after>//
// hopf.cpp
// allovsr
//
// Created by Pablo Colapinto on 11/28/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
//vsr Includes
#include "vsr/vsr.h"
#include "vsr/vsr_op.h"
#include "vsr/vsr_draw.h"
#include "vsr/vsr_camera.h"
#include "vsr/vsr_fiber.h"
//allo includes
#include "allocore/al_Allocore.hpp"
#include "allocore/io/al_ControlNav.hpp"
#include "alloGLV/al_ControlGLV.hpp"
//Glue
#include "allovsr/al_vsrInterface.hpp"
#include <iostream>
using namespace al;
using namespace vsr;
#define PRESET \
static bool bSet = 0;\
if (!bSet) { \
bSet = 1;
void knot(al::VsrApp& app){
HopfFiber hf;
//A Circle you can touch (in the xz plane)
static Circle ca = CXZ(1);
app.interface.touch(ca);
//The Axis of the Circle
DualLine cb = Inf(1) <= ca;
//Normalized . . .
cb = cb.runit();
//A Point you can Touch
static Point pt = PT(1,0,0);
app.interface.touch(pt);
//GUI
static double m,n,amt,iter;
static double theta, phi;
PRESET
app.glv.gui(m,"m",0,10)(n,"n",0,10)(amt,"amt",-10,10)(iter,"iter",1,1000);
app.glv.gui(theta)(phi);
m = 1; n = 5; amt = .005; iter = 1000;
}
vector<Cir> cp = hf.poles(-1 + theta * 2,phi);
DRAW(cp[0]); DRAW(cp[1]);
//A Point Pair "Boost" Generator . . .
PointPair tp = ca.dual() * PI/m + cb * PI/n;
//A Point Pair "Boost" Generator . . .
PointPair tp2 = cp[0].dual() * PI/m + cp[1].dual() * PI/n;
vector<Pnt> vp;
Point np = pt;
for (int i = 0; i < iter; ++i){
np = Ro::loc( np.sp( Gen::bst( tp2*amt ) ) );
vp.push_back(np);
}
//DRAW ROUTINES:
//Draw the Circle and its Axis, and the Point
DRAW3(ca,0,0,1); DRAW3(cb,0,1,0); DRAW3(pt,1,0,0);
//DRAW the Knot Strip
glBegin(GL_LINE_STRIP);
for (int i = 0; i < vp.size(); ++i){
GL::vertex(vp[i].w());
}
glEnd();
}
class MyApp : public al::VsrApp {
public:
MyApp() : al::VsrApp() {
}
virtual void onDraw(Graphics& gl){
//Model Transform
Rot t = Gen::aa( scene().model.rot() );
GL::rotate( t.w() );
knot(*this);
}
};
MyApp app;
int main(int argc, const char * argv[]){
app.create(Window::Dim(800, 600), "Allovsr Demo: Hopf Fibration");
MainLoop::start();
return 0;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
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 "mitkConnectPointsInteractor.h"
#include <mitkLineOperation.h>
#include <mitkPositionEvent.h>
#include "mitkMesh.h"
#include <mitkDataTreeNode.h>
#include <mitkInteractionConst.h>
#include "mitkAction.h"
//how precise must the user pick the point
//default value
const int PRECISION = 5;
mitk::ConnectPointsInteractor::ConnectPointsInteractor(const char * type, DataTreeNode* dataTreeNode, int n)
:Interactor(type, dataTreeNode), m_N(n), m_CurrentCellId(0), m_Precision(PRECISION)
{
m_LastPoint.Fill(0);
m_SumVec.Fill(0);
}
mitk::ConnectPointsInteractor::~ConnectPointsInteractor()
{
}
void mitk::ConnectPointsInteractor::SetPrecision(unsigned int precision)
{
m_Precision = precision;
}
//##Documentation
//## overwritten cause this class can handle it better!
float mitk::ConnectPointsInteractor::CalculateJurisdiction(StateEvent const* stateEvent) const
{
float returnvalue = 0.0;
//if it is a key event that can be handled in the current state, then return 0.5
mitk::DisplayPositionEvent const *disPosEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
//Key event handling:
if (disPosEvent == NULL)
{
//check, if the current state has a transition waiting for that key event.
if (this->GetCurrentState()->GetTransition(stateEvent->GetId())!=NULL)
{
return 0.5;
}
else
{
return 0;
}
}
//on MouseMove do nothing!
if (stateEvent->GetEvent()->GetType() == mitk::Type_MouseMove)
{
return 0;
}
//if we don't have a Point in our PointSet, then return with 0.5
mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>(m_DataTreeNode->GetData());
if (pointSet != NULL)
{
mitk::PointSet::DataType *itkPointSet = pointSet->GetPointSet();
if (pointSet->GetSize()<1)
returnvalue = 0.5;
}
return returnvalue;
}
bool mitk::ConnectPointsInteractor::ExecuteAction( Action* action, mitk::StateEvent const* stateEvent )
{
bool ok = false;//for return type bool
//checking corresponding Data; has to be a Mesh or a subclass
mitk::Mesh* mesh = dynamic_cast<mitk::Mesh*>(m_DataTreeNode->GetData());
if (mesh == NULL)
return false;
//for reading on the points, Id's etc
mitk::PointSet::DataType *itkpointSet = mesh->GetPointSet();
mitk::PointSet::PointsContainer *points = itkpointSet->GetPoints();
/*Each case must watch the type of the event!*/
switch (action->GetActionId())
{
case AcDONOTHING:
ok = true;
break;
case AcADDPOINT:
{
mitk::DisplayPositionEvent const *posEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
if (posEvent == NULL)
return false;
mitk::Point3D worldPoint;
worldPoint = posEvent->GetWorldPosition();
int position = mesh->SearchPoint(worldPoint, m_Precision);
if (position>=0)//found a point near enough to the given point
{
// if the point is the last in current cell, remove it (this has to be moved in a separate action)
bool deleteLine=false;
if(mesh->GetMesh()->GetCells()->Size() > 0)
{
Mesh::CellAutoPointer cellAutoPointer;
ok = mesh->GetMesh()->GetCell(m_CurrentCellId, cellAutoPointer);
if(ok)
{
Mesh::PointIdIterator last = cellAutoPointer->PointIdsEnd();
--last;
deleteLine = (mesh->SearchFirstCell(position) == m_CurrentCellId) && (*last == position);
}
}
if(deleteLine)
{
LineOperation* doOp = new mitk::LineOperation(OpDELETELINE, m_CurrentCellId, position);
if (m_UndoEnabled)
{
LineOperation* undoOp = new mitk::LineOperation(OpADDLINE, m_CurrentCellId, position);
OperationEvent *operationEvent = new OperationEvent(mesh, doOp, undoOp);
m_UndoController->SetOperationEvent(operationEvent);
}
//execute the Operation
mesh->ExecuteOperation(doOp );
}
else
{
// add new cell if necessary
if(mesh->GetNewCellId() == 0) //allow single line only
//allow multiple lines: if((mesh->SearchFirstCell(position) >= 0) || ((m_CurrentCellId == 0) && (mesh->GetNewCellId() == 0)))
{
//get the next cellId and set m_CurrentCellId
m_CurrentCellId = mesh->GetNewCellId();
//now reserv a new cell in m_ItkData
LineOperation* doOp = new mitk::LineOperation(OpNEWCELL, m_CurrentCellId);
if (m_UndoEnabled)
{
LineOperation* undoOp = new mitk::LineOperation(OpDELETECELL, m_CurrentCellId);
OperationEvent *operationEvent = new OperationEvent(mesh, doOp, undoOp);
m_UndoController->SetOperationEvent(operationEvent);
}
mesh->ExecuteOperation(doOp);
}
// add line if point is not yet included in current cell
if(mesh->SearchFirstCell(position) < 0)
{
LineOperation* doOp = new mitk::LineOperation(OpADDLINE, m_CurrentCellId, position);
if (m_UndoEnabled)
{
LineOperation* undoOp = new mitk::LineOperation(OpDELETELINE, m_CurrentCellId, position);
OperationEvent *operationEvent = new OperationEvent(mesh, doOp, undoOp);
m_UndoController->SetOperationEvent(operationEvent);
}
//execute the Operation
mesh->ExecuteOperation(doOp );
}
}
}
ok = true;
break;
}
case AcREMOVEPOINT:
{
//mitk::DisplayPositionEvent const *posEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
//if (posEvent == NULL)
// return false;
//mitk::Point3D worldPoint;
//worldPoint = posEvent->GetWorldPosition();
//int position = mesh->SearchPoint(worldPoint, m_Precision);
//if (position>=0)//found a point near enough to the given point
//{
// // if the point is in the current cell, remove it (this has to be moved in a separate action)
// if(mesh->SearchFirstCell(position) == m_CurrentCellId)
// {
// LineOperation* doOp = new mitk::LineOperation(OpDELETELINE, m_CurrentCellId, position);
// if (m_UndoEnabled)
// {
// LineOperation* undoOp = new mitk::LineOperation(OpADDLINE, m_CurrentCellId, position);
// OperationEvent *operationEvent = new OperationEvent(mesh, doOp, undoOp);
// m_UndoController->SetOperationEvent(operationEvent);
// }
// //execute the Operation
// mesh->ExecuteOperation(doOp );
// }
//}
ok = true;
break;
}
case AcCHECKELEMENT:
/*checking if the Point transmitted is close enough to one point. Then generate a new event with the point and let this statemaschine handle the event.*/
{
mitk::DisplayPositionEvent const *posEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
if (posEvent != NULL)
{
mitk::Point3D worldPoint = posEvent->GetWorldPosition();
int position = mesh->SearchPoint(worldPoint, m_Precision);
if (position>=0)//found a point near enough to the given point
{
PointSet::PointType pt = mesh->GetPoint(position);//get that point, the one meant by the user!
mitk::Point2D displPoint;
displPoint[0] = worldPoint[0]; displPoint[1] = worldPoint[1];
//new Event with information YES and with the correct point
mitk::PositionEvent const* newPosEvent = new mitk::PositionEvent(posEvent->GetSender(), Type_None, BS_NoButton, BS_NoButton, Key_none, displPoint, pt);
mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDYES, newPosEvent);
//call HandleEvent to leave the guard-state
this->HandleEvent( newStateEvent );
ok = true;
}
else
{
//new Event with information NO
mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDNO, posEvent);
this->HandleEvent(newStateEvent );
ok = true;
}
}
else
{
mitk::DisplayPositionEvent const *disPosEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
if (disPosEvent != NULL)
{//2d Koordinates for 3D Interaction; return false to redo the last statechange
mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDNO, posEvent);
this->HandleEvent(newStateEvent );
ok = true;
}
}
break;
}
case AcCHECKNMINUS1://generate Events if the set will be full after the addition of the point or not.
{
if (m_N<0)//number of points not limited->pass on "Amount of points in Set is smaller then N-1"
{
mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDSTSMALERNMINUS1, stateEvent->GetEvent());
this->HandleEvent( newStateEvent );
ok = true;
}
else
{
if (mesh->GetSize()<(m_N-1))
//pointset after addition won't be full
{
mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDSTSMALERNMINUS1, stateEvent->GetEvent());
this->HandleEvent( newStateEvent );
ok = true;
}
else //(mesh->GetSize()>=(m_N-1))
//after the addition of a point, the container will be full
{
mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDSTLARGERNMINUS1, stateEvent->GetEvent());
this->HandleEvent(newStateEvent );
ok = true;
}//else
}//else
}
break;
case AcCHECKEQUALS1:
{
if (mesh->GetSize()<=1)//the number of points in the list is 1 (or smaler)
{
mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDYES, stateEvent->GetEvent());
this->HandleEvent( newStateEvent );
ok = true;
}
else //more than 1 points in list, so stay in the state!
{
mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDNO, stateEvent->GetEvent());
this->HandleEvent(newStateEvent );
ok = true;
}
}
break;
default:
return Superclass::ExecuteAction( action, stateEvent );
//mitk::StatusBar::DisplayText("Message from mitkConnectPointsInteractor: I do not understand the Action!", 10000);
//ok = false;
//a false here causes the statemachine to undo its last statechange.
//otherwise it will end up in a different state, but without done Action.
//if a transition really has no Action, than call donothing
}
return ok;
}
<commit_msg>FIX: removed warnings: unused variable and unsigned/signed mismatch<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
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 "mitkConnectPointsInteractor.h"
#include <mitkLineOperation.h>
#include <mitkPositionEvent.h>
#include "mitkMesh.h"
#include <mitkDataTreeNode.h>
#include <mitkInteractionConst.h>
#include "mitkAction.h"
//how precise must the user pick the point
//default value
const int PRECISION = 5;
mitk::ConnectPointsInteractor::ConnectPointsInteractor(const char * type, DataTreeNode* dataTreeNode, int n)
:Interactor(type, dataTreeNode), m_N(n), m_CurrentCellId(0), m_Precision(PRECISION)
{
m_LastPoint.Fill(0);
m_SumVec.Fill(0);
}
mitk::ConnectPointsInteractor::~ConnectPointsInteractor()
{
}
void mitk::ConnectPointsInteractor::SetPrecision(unsigned int precision)
{
m_Precision = precision;
}
//##Documentation
//## overwritten cause this class can handle it better!
float mitk::ConnectPointsInteractor::CalculateJurisdiction(StateEvent const* stateEvent) const
{
float returnvalue = 0.0;
//if it is a key event that can be handled in the current state, then return 0.5
mitk::DisplayPositionEvent const *disPosEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
//Key event handling:
if (disPosEvent == NULL)
{
//check, if the current state has a transition waiting for that key event.
if (this->GetCurrentState()->GetTransition(stateEvent->GetId())!=NULL)
{
return 0.5;
}
else
{
return 0;
}
}
//on MouseMove do nothing!
if (stateEvent->GetEvent()->GetType() == mitk::Type_MouseMove)
{
return 0;
}
//if we don't have a Point in our PointSet, then return with 0.5
mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>(m_DataTreeNode->GetData());
if (pointSet != NULL)
{
if (pointSet->GetSize()<1)
returnvalue = 0.5;
}
return returnvalue;
}
bool mitk::ConnectPointsInteractor::ExecuteAction( Action* action, mitk::StateEvent const* stateEvent )
{
bool ok = false;//for return type bool
//checking corresponding Data; has to be a Mesh or a subclass
mitk::Mesh* mesh = dynamic_cast<mitk::Mesh*>(m_DataTreeNode->GetData());
if (mesh == NULL)
return false;
//for reading on the points, Id's etc
mitk::PointSet::DataType *itkpointSet = mesh->GetPointSet();
//mitk::PointSet::PointsContainer *points = itkpointSet->GetPoints();//Warning Fix: not used!
/*Each case must watch the type of the event!*/
switch (action->GetActionId())
{
case AcDONOTHING:
ok = true;
break;
case AcADDPOINT:
{
mitk::DisplayPositionEvent const *posEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
if (posEvent == NULL)
return false;
mitk::Point3D worldPoint;
worldPoint = posEvent->GetWorldPosition();
int position = mesh->SearchPoint(worldPoint, m_Precision);
if (position>=0)//found a point near enough to the given point
{
// if the point is the last in current cell, remove it (this has to be moved in a separate action)
bool deleteLine=false;
if(mesh->GetMesh()->GetCells()->Size() > 0)
{
Mesh::CellAutoPointer cellAutoPointer;
ok = mesh->GetMesh()->GetCell(m_CurrentCellId, cellAutoPointer);
if(ok)
{
Mesh::PointIdIterator last = cellAutoPointer->PointIdsEnd();
--last;
deleteLine = ((unsigned)(mesh->SearchFirstCell(position)) == m_CurrentCellId) && (*last == position);
}
}
if(deleteLine)
{
LineOperation* doOp = new mitk::LineOperation(OpDELETELINE, m_CurrentCellId, position);
if (m_UndoEnabled)
{
LineOperation* undoOp = new mitk::LineOperation(OpADDLINE, m_CurrentCellId, position);
OperationEvent *operationEvent = new OperationEvent(mesh, doOp, undoOp);
m_UndoController->SetOperationEvent(operationEvent);
}
//execute the Operation
mesh->ExecuteOperation(doOp );
}
else
{
// add new cell if necessary
if(mesh->GetNewCellId() == 0) //allow single line only
//allow multiple lines: if((mesh->SearchFirstCell(position) >= 0) || ((m_CurrentCellId == 0) && (mesh->GetNewCellId() == 0)))
{
//get the next cellId and set m_CurrentCellId
m_CurrentCellId = mesh->GetNewCellId();
//now reserv a new cell in m_ItkData
LineOperation* doOp = new mitk::LineOperation(OpNEWCELL, m_CurrentCellId);
if (m_UndoEnabled)
{
LineOperation* undoOp = new mitk::LineOperation(OpDELETECELL, m_CurrentCellId);
OperationEvent *operationEvent = new OperationEvent(mesh, doOp, undoOp);
m_UndoController->SetOperationEvent(operationEvent);
}
mesh->ExecuteOperation(doOp);
}
// add line if point is not yet included in current cell
if(mesh->SearchFirstCell(position) < 0)
{
LineOperation* doOp = new mitk::LineOperation(OpADDLINE, m_CurrentCellId, position);
if (m_UndoEnabled)
{
LineOperation* undoOp = new mitk::LineOperation(OpDELETELINE, m_CurrentCellId, position);
OperationEvent *operationEvent = new OperationEvent(mesh, doOp, undoOp);
m_UndoController->SetOperationEvent(operationEvent);
}
//execute the Operation
mesh->ExecuteOperation(doOp );
}
}
}
ok = true;
break;
}
case AcREMOVEPOINT:
{
//mitk::DisplayPositionEvent const *posEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
//if (posEvent == NULL)
// return false;
//mitk::Point3D worldPoint;
//worldPoint = posEvent->GetWorldPosition();
//int position = mesh->SearchPoint(worldPoint, m_Precision);
//if (position>=0)//found a point near enough to the given point
//{
// // if the point is in the current cell, remove it (this has to be moved in a separate action)
// if(mesh->SearchFirstCell(position) == m_CurrentCellId)
// {
// LineOperation* doOp = new mitk::LineOperation(OpDELETELINE, m_CurrentCellId, position);
// if (m_UndoEnabled)
// {
// LineOperation* undoOp = new mitk::LineOperation(OpADDLINE, m_CurrentCellId, position);
// OperationEvent *operationEvent = new OperationEvent(mesh, doOp, undoOp);
// m_UndoController->SetOperationEvent(operationEvent);
// }
// //execute the Operation
// mesh->ExecuteOperation(doOp );
// }
//}
ok = true;
break;
}
case AcCHECKELEMENT:
/*checking if the Point transmitted is close enough to one point. Then generate a new event with the point and let this statemaschine handle the event.*/
{
mitk::DisplayPositionEvent const *posEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
if (posEvent != NULL)
{
mitk::Point3D worldPoint = posEvent->GetWorldPosition();
int position = mesh->SearchPoint(worldPoint, m_Precision);
if (position>=0)//found a point near enough to the given point
{
PointSet::PointType pt = mesh->GetPoint(position);//get that point, the one meant by the user!
mitk::Point2D displPoint;
displPoint[0] = worldPoint[0]; displPoint[1] = worldPoint[1];
//new Event with information YES and with the correct point
mitk::PositionEvent const* newPosEvent = new mitk::PositionEvent(posEvent->GetSender(), Type_None, BS_NoButton, BS_NoButton, Key_none, displPoint, pt);
mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDYES, newPosEvent);
//call HandleEvent to leave the guard-state
this->HandleEvent( newStateEvent );
ok = true;
}
else
{
//new Event with information NO
mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDNO, posEvent);
this->HandleEvent(newStateEvent );
ok = true;
}
}
else
{
mitk::DisplayPositionEvent const *disPosEvent = dynamic_cast <const mitk::DisplayPositionEvent *> (stateEvent->GetEvent());
if (disPosEvent != NULL)
{//2d Koordinates for 3D Interaction; return false to redo the last statechange
mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDNO, posEvent);
this->HandleEvent(newStateEvent );
ok = true;
}
}
break;
}
case AcCHECKNMINUS1://generate Events if the set will be full after the addition of the point or not.
{
if (m_N<0)//number of points not limited->pass on "Amount of points in Set is smaller then N-1"
{
mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDSTSMALERNMINUS1, stateEvent->GetEvent());
this->HandleEvent( newStateEvent );
ok = true;
}
else
{
if (mesh->GetSize()<(m_N-1))
//pointset after addition won't be full
{
mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDSTSMALERNMINUS1, stateEvent->GetEvent());
this->HandleEvent( newStateEvent );
ok = true;
}
else //(mesh->GetSize()>=(m_N-1))
//after the addition of a point, the container will be full
{
mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDSTLARGERNMINUS1, stateEvent->GetEvent());
this->HandleEvent(newStateEvent );
ok = true;
}//else
}//else
}
break;
case AcCHECKEQUALS1:
{
if (mesh->GetSize()<=1)//the number of points in the list is 1 (or smaler)
{
mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDYES, stateEvent->GetEvent());
this->HandleEvent( newStateEvent );
ok = true;
}
else //more than 1 points in list, so stay in the state!
{
mitk::StateEvent* newStateEvent = new mitk::StateEvent(EIDNO, stateEvent->GetEvent());
this->HandleEvent(newStateEvent );
ok = true;
}
}
break;
default:
return Superclass::ExecuteAction( action, stateEvent );
//mitk::StatusBar::DisplayText("Message from mitkConnectPointsInteractor: I do not understand the Action!", 10000);
//ok = false;
//a false here causes the statemachine to undo its last statechange.
//otherwise it will end up in a different state, but without done Action.
//if a transition really has no Action, than call donothing
}
return ok;
}
<|endoftext|>
|
<commit_before>#include "mat5.h"
#include <ostream>
#include <fstream>
#include "istream_std.h"
#include "istream_zlib.h"
namespace nano
{
using std::uint32_t;
inline uint32_t make_uint32(const char* data)
{
return *reinterpret_cast<const uint32_t*>(data);
}
template <typename tinteger>
inline mat5_data_type make_data_type(const tinteger code)
{
switch (code)
{
case 1: return mat5_data_type::miINT8;
case 2: return mat5_data_type::miUINT8;
case 3: return mat5_data_type::miINT16;
case 4: return mat5_data_type::miUINT16;
case 5: return mat5_data_type::miINT32;
case 6: return mat5_data_type::miUINT32;
case 7: return mat5_data_type::miSINGLE;
case 9: return mat5_data_type::miDOUBLE;
case 12: return mat5_data_type::miINT64;
case 13: return mat5_data_type::miUINT64;
case 14: return mat5_data_type::miMATRIX;
case 15: return mat5_data_type::miCOMPRESSED;
case 16: return mat5_data_type::miUTF8;
case 17: return mat5_data_type::miUTF16;
case 18: return mat5_data_type::miUTF32;
default: return mat5_data_type::miUNKNOWN;
}
}
inline std::streamsize to_bytes(const mat5_data_type& type)
{
switch (type)
{
case mat5_data_type::miINT8: return 1;
case mat5_data_type::miUINT8: return 1;
case mat5_data_type::miINT16: return 2;
case mat5_data_type::miUINT16: return 2;
case mat5_data_type::miINT32: return 4;
case mat5_data_type::miUINT32: return 4;
case mat5_data_type::miSINGLE: return 4;
case mat5_data_type::miDOUBLE: return 8;
case mat5_data_type::miINT64: return 8;
case mat5_data_type::miUINT64: return 8;
case mat5_data_type::miMATRIX: return 0;
case mat5_data_type::miCOMPRESSED: return 0;
case mat5_data_type::miUTF8: return 0;
case mat5_data_type::miUTF16: return 0;
case mat5_data_type::miUTF32: return 0;
default: return 0;
}
}
std::string to_string(const mat5_data_type type)
{
switch (type)
{
case mat5_data_type::miINT8: return "miINT8";
case mat5_data_type::miUINT8: return "miUINT8";
case mat5_data_type::miINT16: return "miINT16";
case mat5_data_type::miUINT16: return "miUINT16";
case mat5_data_type::miINT32: return "miINT32";
case mat5_data_type::miUINT32: return "miUINT32";
case mat5_data_type::miSINGLE: return "miSINGLE";
case mat5_data_type::miDOUBLE: return "miDOUBLE";
case mat5_data_type::miINT64: return "miINT64";
case mat5_data_type::miUINT64: return "miUINT64";
case mat5_data_type::miMATRIX: return "miMATRIX";
case mat5_data_type::miCOMPRESSED: return "miCOMPRESSED";
case mat5_data_type::miUTF8: return "miUTF8";
case mat5_data_type::miUTF16: return "miUTF16";
case mat5_data_type::miUTF32: return "miUTF32";
default: return "miUNKNOWN";
}
}
std::string to_string(const mat5_format_type type)
{
switch (type)
{
case mat5_format_type::small: return "small";
case mat5_format_type::regular: return "regular";
default: return "unknown";
}
}
std::string to_string(const mat5_parent_type type)
{
switch (type)
{
case mat5_parent_type::none: return ".";
case mat5_parent_type::miMATRIX: return "miMATRIX";
default: return "unknown";
}
}
bool mat5_header_t::load(istream_t& stream)
{
return stream.read(m_description) &&
stream.read(m_offset) &&
stream.read(m_endian);
}
std::string mat5_header_t::description() const
{
return std::string(m_description, m_description + sizeof(m_description));
}
mat5_section_t::mat5_section_t(const mat5_parent_type ptype) :
m_size(0),
m_dsize(0),
m_dtype(mat5_data_type::miUNKNOWN),
m_ftype(mat5_format_type::small),
m_ptype(ptype),
m_bytes(0)
{
}
bool mat5_section_t::load(istream_t& stream)
{
uint32_t dtype, bytes;
if ( !stream.read(dtype) ||
!stream.read(bytes))
{
return false;
}
// small data format
if ((dtype >> 16) != 0)
{
m_size = 8;
m_dsize = 4;
m_dtype = make_data_type((dtype << 16) >> 16);
m_ftype = mat5_format_type::small;
m_bytes = bytes;
}
// regular format
else
{
const auto compressed = make_data_type(dtype) == mat5_data_type::miCOMPRESSED;
const auto modulo8 = bytes % 8;
m_size = compressed ? (8 + bytes) : (8 + bytes + (modulo8 ? 8 - modulo8 : 0));
m_dsize = m_size - 8;
m_dtype = make_data_type(dtype);
m_ftype = mat5_format_type::regular;
}
return true;
}
bool mat5_section_t::skip(istream_t& stream) const
{
switch (m_ftype)
{
case mat5_format_type::regular:
return stream.skip(m_dsize);
case mat5_format_type::small:
default:
return true;
}
}
bool mat5_section_t::string(istream_t& stream, std::string& str) const
{
buffer_t buffer = make_buffer(m_dsize);
switch (m_ftype)
{
case mat5_format_type::regular:
// todo: in C++17 can write directly in std::string (std::string::data can be non-const)
if (stream.read(buffer.data(), m_dsize) != m_dsize)
{
return false;
}
str.assign(buffer.data(), buffer.size());
return true;
case mat5_format_type::small:
default:
str.assign(reinterpret_cast<const char*>(&m_bytes), sizeof(m_bytes));
return true;
}
}
template <typename tstorage, typename tvalue>
static bool read_values(istream_t& stream, std::streamsize bytes, std::vector<tvalue>& values)
{
const auto value_size = static_cast<std::streamsize>(sizeof(tstorage));
values.clear();
while (bytes >= value_size)
{
tstorage value;
if (!stream.read(value))
{
return false;
}
values.push_back(static_cast<tvalue>(value));
bytes -= value_size;
}
return bytes == 0;
}
bool mat5_section_t::values(istream_t& stream, std::vector<int>& values) const
{
switch (m_ftype)
{
case mat5_format_type::regular:
switch (m_dtype)
{
case mat5_data_type::miINT32: return read_values<int32_t>(stream, m_dsize, values);
default: return false;
}
case mat5_format_type::small:
default:
return false;
}
}
std::ostream& operator<<(std::ostream& ostream, const mat5_section_t& sect)
{
ostream << "type = " << to_string(sect.m_ptype) << "/" << to_string(sect.m_dtype)
<< ", format = " << to_string(sect.m_ftype)
<< ", size = " << sect.m_size << "B"
<< ", data size = " << sect.m_dsize << "B";
return ostream;
}
static bool load_mat5(istream_t& stream,
const mat5_section_callback_t& scallback,
const mat5_error_callback_t& ecallback,
const mat5_parent_type ptype = mat5_parent_type::none)
{
while (stream)
{
mat5_section_t section(ptype);
if (!section.load(stream))
{
ecallback("failed to load section!");
return false;
}
switch (section.m_dtype)
{
case mat5_data_type::miCOMPRESSED:
{
// gzip compressed section
zlib_istream_t zstream(stream, section.m_dsize);
if (!load_mat5(zstream, scallback, ecallback))
{
return false;
}
}
break;
case mat5_data_type::miMATRIX:
{
// array/matrix section, so read the sub-elements
if (!load_mat5(stream, scallback, ecallback, mat5_parent_type::miMATRIX))
{
return false;
}
}
break;
default:
if (!scallback(section, stream))
{
return false;
}
}
}
return true;
}
bool load_mat5(const std::string& path,
const mat5_header_callback_t& hcallback,
const mat5_section_callback_t& scallback,
const mat5_error_callback_t& ecallback)
{
std::ifstream istream(path.c_str(), std::ios::binary | std::ios::in);
if (!istream.is_open())
{
ecallback("failed to open file <" + path + ">!");
return false;
}
std_istream_t stream(istream);
// load header
mat5_header_t header;
if (!header.load(stream))
{
ecallback("failed to load header!");
return false;
}
if (!hcallback(header))
{
return false;
}
// load sections
return load_mat5(stream, scallback, ecallback);
}
}
<commit_msg>extent mat5_section_t to load different scalars<commit_after>#include "mat5.h"
#include <ostream>
#include <fstream>
#include "istream_mem.h"
#include "istream_std.h"
#include "istream_zlib.h"
namespace nano
{
using std::uint32_t;
inline uint32_t make_uint32(const char* data)
{
return *reinterpret_cast<const uint32_t*>(data);
}
template <typename tinteger>
inline mat5_data_type make_data_type(const tinteger code)
{
switch (code)
{
case 1: return mat5_data_type::miINT8;
case 2: return mat5_data_type::miUINT8;
case 3: return mat5_data_type::miINT16;
case 4: return mat5_data_type::miUINT16;
case 5: return mat5_data_type::miINT32;
case 6: return mat5_data_type::miUINT32;
case 7: return mat5_data_type::miSINGLE;
case 9: return mat5_data_type::miDOUBLE;
case 12: return mat5_data_type::miINT64;
case 13: return mat5_data_type::miUINT64;
case 14: return mat5_data_type::miMATRIX;
case 15: return mat5_data_type::miCOMPRESSED;
case 16: return mat5_data_type::miUTF8;
case 17: return mat5_data_type::miUTF16;
case 18: return mat5_data_type::miUTF32;
default: return mat5_data_type::miUNKNOWN;
}
}
inline std::streamsize to_bytes(const mat5_data_type& type)
{
switch (type)
{
case mat5_data_type::miINT8: return 1;
case mat5_data_type::miUINT8: return 1;
case mat5_data_type::miINT16: return 2;
case mat5_data_type::miUINT16: return 2;
case mat5_data_type::miINT32: return 4;
case mat5_data_type::miUINT32: return 4;
case mat5_data_type::miSINGLE: return 4;
case mat5_data_type::miDOUBLE: return 8;
case mat5_data_type::miINT64: return 8;
case mat5_data_type::miUINT64: return 8;
case mat5_data_type::miMATRIX: return 0;
case mat5_data_type::miCOMPRESSED: return 0;
case mat5_data_type::miUTF8: return 0;
case mat5_data_type::miUTF16: return 0;
case mat5_data_type::miUTF32: return 0;
default: return 0;
}
}
std::string to_string(const mat5_data_type type)
{
switch (type)
{
case mat5_data_type::miINT8: return "miINT8";
case mat5_data_type::miUINT8: return "miUINT8";
case mat5_data_type::miINT16: return "miINT16";
case mat5_data_type::miUINT16: return "miUINT16";
case mat5_data_type::miINT32: return "miINT32";
case mat5_data_type::miUINT32: return "miUINT32";
case mat5_data_type::miSINGLE: return "miSINGLE";
case mat5_data_type::miDOUBLE: return "miDOUBLE";
case mat5_data_type::miINT64: return "miINT64";
case mat5_data_type::miUINT64: return "miUINT64";
case mat5_data_type::miMATRIX: return "miMATRIX";
case mat5_data_type::miCOMPRESSED: return "miCOMPRESSED";
case mat5_data_type::miUTF8: return "miUTF8";
case mat5_data_type::miUTF16: return "miUTF16";
case mat5_data_type::miUTF32: return "miUTF32";
default: return "miUNKNOWN";
}
}
std::string to_string(const mat5_format_type type)
{
switch (type)
{
case mat5_format_type::small: return "small";
case mat5_format_type::regular: return "regular";
default: return "unknown";
}
}
std::string to_string(const mat5_parent_type type)
{
switch (type)
{
case mat5_parent_type::none: return ".";
case mat5_parent_type::miMATRIX: return "miMATRIX";
default: return "unknown";
}
}
bool mat5_header_t::load(istream_t& stream)
{
return stream.read(m_description) &&
stream.read(m_offset) &&
stream.read(m_endian);
}
std::string mat5_header_t::description() const
{
return std::string(m_description, m_description + sizeof(m_description));
}
mat5_section_t::mat5_section_t(const mat5_parent_type ptype) :
m_size(0),
m_dsize(0),
m_dtype(mat5_data_type::miUNKNOWN),
m_ftype(mat5_format_type::small),
m_ptype(ptype),
m_bytes(0)
{
}
bool mat5_section_t::load(istream_t& stream)
{
uint32_t dtype, bytes;
if ( !stream.read(dtype) ||
!stream.read(bytes))
{
return false;
}
// small data format
if ((dtype >> 16) != 0)
{
m_size = 8;
m_dsize = 4;
m_dtype = make_data_type((dtype << 16) >> 16);
m_ftype = mat5_format_type::small;
m_bytes = bytes;
}
// regular format
else
{
const auto compressed = make_data_type(dtype) == mat5_data_type::miCOMPRESSED;
const auto modulo8 = bytes % 8;
m_size = compressed ? (8 + bytes) : (8 + bytes + (modulo8 ? 8 - modulo8 : 0));
m_dsize = m_size - 8;
m_dtype = make_data_type(dtype);
m_ftype = mat5_format_type::regular;
}
return true;
}
bool mat5_section_t::skip(istream_t& stream) const
{
switch (m_ftype)
{
case mat5_format_type::regular:
return stream.skip(m_dsize);
case mat5_format_type::small:
default:
return true;
}
}
template <typename tdata, typename tstream, typename tvalue>
static bool read_values(tstream&& stream, std::streamsize bytes,
std::vector<tvalue>& values)
{
const auto value_size = static_cast<std::streamsize>(sizeof(tvalue));
values.resize(static_cast<size_t>(bytes / value_size));
return sizeof(tdata) == sizeof(tvalue) &&
(bytes % value_size == 0) &&
stream.read(reinterpret_cast<char*>(values.data()), bytes) == bytes;
}
template <typename tstream, typename tvalue>
static bool read_values(tstream&& stream, const mat5_data_type dtype, const std::streamsize dsize,
std::vector<tvalue>& values)
{
switch (dtype)
{
case mat5_data_type::miINT8: return read_values<int8_t>(stream, dsize, values);
case mat5_data_type::miINT32: return read_values<int32_t>(stream, dsize, values);
default: return false;
}
}
template <typename tstream, typename tvalue>
static bool read_values(tstream&& stream, const mat5_format_type ftype, const uint32_t bytes, const mat5_data_type dtype, const std::streamsize dsize,
std::vector<tvalue>& values)
{
switch (ftype)
{
case mat5_format_type::regular:
return read_values(stream, dtype, dsize, values);
case mat5_format_type::small:
default:
return read_values(mem_istream_t(reinterpret_cast<const char*>(&bytes), sizeof(bytes)), dtype, dsize, values);
}
}
bool mat5_section_t::string(istream_t& stream, std::string& str) const
{
//
std::vector<char> cstr;
if (!read_values(stream, m_ftype, m_bytes, m_dtype, m_dsize, cstr))
{
return false;
}
else
{
str.assign(cstr.data(), cstr.size());
return true;
}
}
bool mat5_section_t::values(istream_t& stream, std::vector<int>& values) const
{
return read_values(stream, m_ftype, m_bytes, m_dtype, m_dsize, values);
}
std::ostream& operator<<(std::ostream& ostream, const mat5_section_t& sect)
{
ostream << "type = " << to_string(sect.m_ptype) << "/" << to_string(sect.m_dtype)
<< ", format = " << to_string(sect.m_ftype)
<< ", size = " << sect.m_size << "B"
<< ", data size = " << sect.m_dsize << "B";
return ostream;
}
static bool load_mat5(istream_t& stream,
const mat5_section_callback_t& scallback,
const mat5_error_callback_t& ecallback,
const mat5_parent_type ptype = mat5_parent_type::none)
{
while (stream)
{
mat5_section_t section(ptype);
if (!section.load(stream))
{
ecallback("failed to load section!");
return false;
}
switch (section.m_dtype)
{
case mat5_data_type::miCOMPRESSED:
{
// gzip compressed section
zlib_istream_t zstream(stream, section.m_dsize);
if (!load_mat5(zstream, scallback, ecallback))
{
return false;
}
}
break;
case mat5_data_type::miMATRIX:
{
// array/matrix section, so read the sub-elements
if (!load_mat5(stream, scallback, ecallback, mat5_parent_type::miMATRIX))
{
return false;
}
}
break;
default:
if (!scallback(section, stream))
{
return false;
}
}
}
return true;
}
bool load_mat5(const std::string& path,
const mat5_header_callback_t& hcallback,
const mat5_section_callback_t& scallback,
const mat5_error_callback_t& ecallback)
{
std::ifstream istream(path.c_str(), std::ios::binary | std::ios::in);
if (!istream.is_open())
{
ecallback("failed to open file <" + path + ">!");
return false;
}
std_istream_t stream(istream);
// load header
mat5_header_t header;
if (!header.load(stream))
{
ecallback("failed to load header!");
return false;
}
if (!hcallback(header))
{
return false;
}
// load sections
return load_mat5(stream, scallback, ecallback);
}
}
<|endoftext|>
|
<commit_before>//===--------------------- ResourceManager.cpp ------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// The classes here represent processor resource units and their management
/// strategy. These classes are managed by the Scheduler.
///
//===----------------------------------------------------------------------===//
#include "llvm/MCA/HardwareUnits/ResourceManager.h"
#include "llvm/MCA/Support.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
namespace llvm {
namespace mca {
#define DEBUG_TYPE "llvm-mca"
ResourceStrategy::~ResourceStrategy() = default;
uint64_t DefaultResourceStrategy::select(uint64_t ReadyMask) {
// This method assumes that ReadyMask cannot be zero.
uint64_t CandidateMask = ReadyMask & NextInSequenceMask;
if (CandidateMask) {
CandidateMask = PowerOf2Floor(CandidateMask);
NextInSequenceMask &= (CandidateMask | (CandidateMask - 1));
return CandidateMask;
}
NextInSequenceMask = ResourceUnitMask ^ RemovedFromNextInSequence;
RemovedFromNextInSequence = 0;
CandidateMask = ReadyMask & NextInSequenceMask;
if (CandidateMask) {
CandidateMask = PowerOf2Floor(CandidateMask);
NextInSequenceMask &= (CandidateMask | (CandidateMask - 1));
return CandidateMask;
}
NextInSequenceMask = ResourceUnitMask;
CandidateMask = PowerOf2Floor(ReadyMask & NextInSequenceMask);
NextInSequenceMask &= (CandidateMask | (CandidateMask - 1));
return CandidateMask;
}
void DefaultResourceStrategy::used(uint64_t Mask) {
if (Mask > NextInSequenceMask) {
RemovedFromNextInSequence |= Mask;
return;
}
NextInSequenceMask &= (~Mask);
if (NextInSequenceMask)
return;
NextInSequenceMask = ResourceUnitMask ^ RemovedFromNextInSequence;
RemovedFromNextInSequence = 0;
}
ResourceState::ResourceState(const MCProcResourceDesc &Desc, unsigned Index,
uint64_t Mask)
: ProcResourceDescIndex(Index), ResourceMask(Mask),
BufferSize(Desc.BufferSize), IsAGroup(countPopulation(ResourceMask)>1) {
if (IsAGroup)
ResourceSizeMask = ResourceMask ^ PowerOf2Floor(ResourceMask);
else
ResourceSizeMask = (1ULL << Desc.NumUnits) - 1;
ReadyMask = ResourceSizeMask;
AvailableSlots = BufferSize == -1 ? 0U : static_cast<unsigned>(BufferSize);
Unavailable = false;
}
bool ResourceState::isReady(unsigned NumUnits) const {
return (!isReserved() || isADispatchHazard()) &&
countPopulation(ReadyMask) >= NumUnits;
}
ResourceStateEvent ResourceState::isBufferAvailable() const {
if (isADispatchHazard() && isReserved())
return RS_RESERVED;
if (!isBuffered() || AvailableSlots)
return RS_BUFFER_AVAILABLE;
return RS_BUFFER_UNAVAILABLE;
}
#ifndef NDEBUG
void ResourceState::dump() const {
dbgs() << "MASK=" << format_hex(ResourceMask, 8)
<< ", SZMASK=" << format_hex(ResourceSizeMask, 8)
<< ", RDYMASK=" << format_hex(ReadyMask, 8)
<< ", BufferSize=" << BufferSize
<< ", AvailableSlots=" << AvailableSlots
<< ", Reserved=" << Unavailable << '\n';
}
#endif
static unsigned getResourceStateIndex(uint64_t Mask) {
return std::numeric_limits<uint64_t>::digits - countLeadingZeros(Mask);
}
static std::unique_ptr<ResourceStrategy>
getStrategyFor(const ResourceState &RS) {
if (RS.isAResourceGroup() || RS.getNumUnits() > 1)
return llvm::make_unique<DefaultResourceStrategy>(RS.getReadyMask());
return std::unique_ptr<ResourceStrategy>(nullptr);
}
ResourceManager::ResourceManager(const MCSchedModel &SM) {
computeProcResourceMasks(SM, ProcResID2Mask);
Resources.resize(SM.getNumProcResourceKinds());
Strategies.resize(SM.getNumProcResourceKinds());
for (unsigned I = 0, E = SM.getNumProcResourceKinds(); I < E; ++I) {
uint64_t Mask = ProcResID2Mask[I];
unsigned Index = getResourceStateIndex(Mask);
Resources[Index] =
llvm::make_unique<ResourceState>(*SM.getProcResource(I), I, Mask);
Strategies[Index] = getStrategyFor(*Resources[Index]);
}
}
void ResourceManager::setCustomStrategyImpl(std::unique_ptr<ResourceStrategy> S,
uint64_t ResourceMask) {
unsigned Index = getResourceStateIndex(ResourceMask);
assert(Index < Resources.size() && "Invalid processor resource index!");
assert(S && "Unexpected null strategy in input!");
Strategies[Index] = std::move(S);
}
unsigned ResourceManager::resolveResourceMask(uint64_t Mask) const {
return Resources[getResourceStateIndex(Mask)]->getProcResourceID();
}
unsigned ResourceManager::getNumUnits(uint64_t ResourceID) const {
return Resources[getResourceStateIndex(ResourceID)]->getNumUnits();
}
// Returns the actual resource consumed by this Use.
// First, is the primary resource ID.
// Second, is the specific sub-resource ID.
ResourceRef ResourceManager::selectPipe(uint64_t ResourceID) {
unsigned Index = getResourceStateIndex(ResourceID);
ResourceState &RS = *Resources[Index];
assert(RS.isReady() && "No available units to select!");
// Special case where RS is not a group, and it only declares a single
// resource unit.
if (!RS.isAResourceGroup() && RS.getNumUnits() == 1)
return std::make_pair(ResourceID, RS.getReadyMask());
uint64_t SubResourceID = Strategies[Index]->select(RS.getReadyMask());
if (RS.isAResourceGroup())
return selectPipe(SubResourceID);
return std::make_pair(ResourceID, SubResourceID);
}
void ResourceManager::use(const ResourceRef &RR) {
// Mark the sub-resource referenced by RR as used.
unsigned RSID = getResourceStateIndex(RR.first);
ResourceState &RS = *Resources[RSID];
RS.markSubResourceAsUsed(RR.second);
// Remember to update the resource strategy for non-group resources with
// multiple units.
if (RS.getNumUnits() > 1)
Strategies[RSID]->used(RR.second);
// If there are still available units in RR.first,
// then we are done.
if (RS.isReady())
return;
// Notify to other resources that RR.first is no longer available.
for (std::unique_ptr<ResourceState> &Res : Resources) {
ResourceState &Current = *Res;
if (!Current.isAResourceGroup() || Current.getResourceMask() == RR.first)
continue;
if (Current.containsResource(RR.first)) {
unsigned Index = getResourceStateIndex(Current.getResourceMask());
Current.markSubResourceAsUsed(RR.first);
Strategies[Index]->used(RR.first);
}
}
}
void ResourceManager::release(const ResourceRef &RR) {
ResourceState &RS = *Resources[getResourceStateIndex(RR.first)];
bool WasFullyUsed = !RS.isReady();
RS.releaseSubResource(RR.second);
if (!WasFullyUsed)
return;
for (std::unique_ptr<ResourceState> &Res : Resources) {
ResourceState &Current = *Res;
if (!Current.isAResourceGroup() || Current.getResourceMask() == RR.first)
continue;
if (Current.containsResource(RR.first))
Current.releaseSubResource(RR.first);
}
}
ResourceStateEvent
ResourceManager::canBeDispatched(ArrayRef<uint64_t> Buffers) const {
ResourceStateEvent Result = ResourceStateEvent::RS_BUFFER_AVAILABLE;
for (uint64_t Buffer : Buffers) {
ResourceState &RS = *Resources[getResourceStateIndex(Buffer)];
Result = RS.isBufferAvailable();
if (Result != ResourceStateEvent::RS_BUFFER_AVAILABLE)
break;
}
return Result;
}
void ResourceManager::reserveBuffers(ArrayRef<uint64_t> Buffers) {
for (const uint64_t Buffer : Buffers) {
ResourceState &RS = *Resources[getResourceStateIndex(Buffer)];
assert(RS.isBufferAvailable() == ResourceStateEvent::RS_BUFFER_AVAILABLE);
RS.reserveBuffer();
if (RS.isADispatchHazard()) {
assert(!RS.isReserved());
RS.setReserved();
}
}
}
void ResourceManager::releaseBuffers(ArrayRef<uint64_t> Buffers) {
for (const uint64_t R : Buffers)
Resources[getResourceStateIndex(R)]->releaseBuffer();
}
bool ResourceManager::canBeIssued(const InstrDesc &Desc) const {
return all_of(
Desc.Resources, [&](const std::pair<uint64_t, const ResourceUsage> &E) {
unsigned NumUnits = E.second.isReserved() ? 0U : E.second.NumUnits;
unsigned Index = getResourceStateIndex(E.first);
return Resources[Index]->isReady(NumUnits);
});
}
// Returns true if all resources are in-order, and there is at least one
// resource which is a dispatch hazard (BufferSize = 0).
bool ResourceManager::mustIssueImmediately(const InstrDesc &Desc) const {
if (!canBeIssued(Desc))
return false;
bool AllInOrderResources = all_of(Desc.Buffers, [&](uint64_t BufferMask) {
unsigned Index = getResourceStateIndex(BufferMask);
const ResourceState &Resource = *Resources[Index];
return Resource.isInOrder() || Resource.isADispatchHazard();
});
if (!AllInOrderResources)
return false;
return any_of(Desc.Buffers, [&](uint64_t BufferMask) {
return Resources[getResourceStateIndex(BufferMask)]->isADispatchHazard();
});
}
void ResourceManager::issueInstruction(
const InstrDesc &Desc,
SmallVectorImpl<std::pair<ResourceRef, ResourceCycles>> &Pipes) {
for (const std::pair<uint64_t, ResourceUsage> &R : Desc.Resources) {
const CycleSegment &CS = R.second.CS;
if (!CS.size()) {
releaseResource(R.first);
continue;
}
assert(CS.begin() == 0 && "Invalid {Start, End} cycles!");
if (!R.second.isReserved()) {
ResourceRef Pipe = selectPipe(R.first);
use(Pipe);
BusyResources[Pipe] += CS.size();
// Replace the resource mask with a valid processor resource index.
const ResourceState &RS = *Resources[getResourceStateIndex(Pipe.first)];
Pipe.first = RS.getProcResourceID();
Pipes.emplace_back(std::pair<ResourceRef, ResourceCycles>(
Pipe, ResourceCycles(CS.size())));
} else {
assert((countPopulation(R.first) > 1) && "Expected a group!");
// Mark this group as reserved.
assert(R.second.isReserved());
reserveResource(R.first);
BusyResources[ResourceRef(R.first, R.first)] += CS.size();
}
}
}
void ResourceManager::cycleEvent(SmallVectorImpl<ResourceRef> &ResourcesFreed) {
for (std::pair<ResourceRef, unsigned> &BR : BusyResources) {
if (BR.second)
BR.second--;
if (!BR.second) {
// Release this resource.
const ResourceRef &RR = BR.first;
if (countPopulation(RR.first) == 1)
release(RR);
releaseResource(RR.first);
ResourcesFreed.push_back(RR);
}
}
for (const ResourceRef &RF : ResourcesFreed)
BusyResources.erase(RF);
}
void ResourceManager::reserveResource(uint64_t ResourceID) {
ResourceState &Resource = *Resources[getResourceStateIndex(ResourceID)];
assert(!Resource.isReserved());
Resource.setReserved();
}
void ResourceManager::releaseResource(uint64_t ResourceID) {
ResourceState &Resource = *Resources[getResourceStateIndex(ResourceID)];
Resource.clearReserved();
}
} // namespace mca
} // namespace llvm
<commit_msg>[MCA] Minor refactoring of method DefaultResourceStrategy::select. NFCI<commit_after>//===--------------------- ResourceManager.cpp ------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// The classes here represent processor resource units and their management
/// strategy. These classes are managed by the Scheduler.
///
//===----------------------------------------------------------------------===//
#include "llvm/MCA/HardwareUnits/ResourceManager.h"
#include "llvm/MCA/Support.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
namespace llvm {
namespace mca {
#define DEBUG_TYPE "llvm-mca"
ResourceStrategy::~ResourceStrategy() = default;
static uint64_t selectImpl(uint64_t CandidateMask,
uint64_t &NextInSequenceMask) {
CandidateMask = 1ULL << (countLeadingZeros(CandidateMask) ^
(std::numeric_limits<uint64_t>::digits - 1));
NextInSequenceMask &= (CandidateMask ^ (CandidateMask - 1));
return CandidateMask;
}
uint64_t DefaultResourceStrategy::select(uint64_t ReadyMask) {
// This method assumes that ReadyMask cannot be zero.
uint64_t CandidateMask = ReadyMask & NextInSequenceMask;
if (CandidateMask)
return selectImpl(CandidateMask, NextInSequenceMask);
NextInSequenceMask = ResourceUnitMask ^ RemovedFromNextInSequence;
RemovedFromNextInSequence = 0;
CandidateMask = ReadyMask & NextInSequenceMask;
if (CandidateMask)
return selectImpl(CandidateMask, NextInSequenceMask);
NextInSequenceMask = ResourceUnitMask;
CandidateMask = ReadyMask & NextInSequenceMask;
return selectImpl(CandidateMask, NextInSequenceMask);
}
void DefaultResourceStrategy::used(uint64_t Mask) {
if (Mask > NextInSequenceMask) {
RemovedFromNextInSequence |= Mask;
return;
}
NextInSequenceMask &= (~Mask);
if (NextInSequenceMask)
return;
NextInSequenceMask = ResourceUnitMask ^ RemovedFromNextInSequence;
RemovedFromNextInSequence = 0;
}
ResourceState::ResourceState(const MCProcResourceDesc &Desc, unsigned Index,
uint64_t Mask)
: ProcResourceDescIndex(Index), ResourceMask(Mask),
BufferSize(Desc.BufferSize), IsAGroup(countPopulation(ResourceMask) > 1) {
if (IsAGroup) {
ResourceSizeMask =
ResourceMask ^ (1ULL << (countLeadingZeros(ResourceMask) ^
(std::numeric_limits<uint64_t>::digits - 1)));
} else {
ResourceSizeMask = (1ULL << Desc.NumUnits) - 1;
}
ReadyMask = ResourceSizeMask;
AvailableSlots = BufferSize == -1 ? 0U : static_cast<unsigned>(BufferSize);
Unavailable = false;
}
bool ResourceState::isReady(unsigned NumUnits) const {
return (!isReserved() || isADispatchHazard()) &&
countPopulation(ReadyMask) >= NumUnits;
}
ResourceStateEvent ResourceState::isBufferAvailable() const {
if (isADispatchHazard() && isReserved())
return RS_RESERVED;
if (!isBuffered() || AvailableSlots)
return RS_BUFFER_AVAILABLE;
return RS_BUFFER_UNAVAILABLE;
}
#ifndef NDEBUG
void ResourceState::dump() const {
dbgs() << "MASK=" << format_hex(ResourceMask, 8)
<< ", SZMASK=" << format_hex(ResourceSizeMask, 8)
<< ", RDYMASK=" << format_hex(ReadyMask, 8)
<< ", BufferSize=" << BufferSize
<< ", AvailableSlots=" << AvailableSlots
<< ", Reserved=" << Unavailable << '\n';
}
#endif
static unsigned getResourceStateIndex(uint64_t Mask) {
return std::numeric_limits<uint64_t>::digits - countLeadingZeros(Mask);
}
static std::unique_ptr<ResourceStrategy>
getStrategyFor(const ResourceState &RS) {
if (RS.isAResourceGroup() || RS.getNumUnits() > 1)
return llvm::make_unique<DefaultResourceStrategy>(RS.getReadyMask());
return std::unique_ptr<ResourceStrategy>(nullptr);
}
ResourceManager::ResourceManager(const MCSchedModel &SM) {
computeProcResourceMasks(SM, ProcResID2Mask);
Resources.resize(SM.getNumProcResourceKinds());
Strategies.resize(SM.getNumProcResourceKinds());
for (unsigned I = 0, E = SM.getNumProcResourceKinds(); I < E; ++I) {
uint64_t Mask = ProcResID2Mask[I];
unsigned Index = getResourceStateIndex(Mask);
Resources[Index] =
llvm::make_unique<ResourceState>(*SM.getProcResource(I), I, Mask);
Strategies[Index] = getStrategyFor(*Resources[Index]);
}
}
void ResourceManager::setCustomStrategyImpl(std::unique_ptr<ResourceStrategy> S,
uint64_t ResourceMask) {
unsigned Index = getResourceStateIndex(ResourceMask);
assert(Index < Resources.size() && "Invalid processor resource index!");
assert(S && "Unexpected null strategy in input!");
Strategies[Index] = std::move(S);
}
unsigned ResourceManager::resolveResourceMask(uint64_t Mask) const {
return Resources[getResourceStateIndex(Mask)]->getProcResourceID();
}
unsigned ResourceManager::getNumUnits(uint64_t ResourceID) const {
return Resources[getResourceStateIndex(ResourceID)]->getNumUnits();
}
// Returns the actual resource consumed by this Use.
// First, is the primary resource ID.
// Second, is the specific sub-resource ID.
ResourceRef ResourceManager::selectPipe(uint64_t ResourceID) {
unsigned Index = getResourceStateIndex(ResourceID);
ResourceState &RS = *Resources[Index];
assert(RS.isReady() && "No available units to select!");
// Special case where RS is not a group, and it only declares a single
// resource unit.
if (!RS.isAResourceGroup() && RS.getNumUnits() == 1)
return std::make_pair(ResourceID, RS.getReadyMask());
uint64_t SubResourceID = Strategies[Index]->select(RS.getReadyMask());
if (RS.isAResourceGroup())
return selectPipe(SubResourceID);
return std::make_pair(ResourceID, SubResourceID);
}
void ResourceManager::use(const ResourceRef &RR) {
// Mark the sub-resource referenced by RR as used.
unsigned RSID = getResourceStateIndex(RR.first);
ResourceState &RS = *Resources[RSID];
RS.markSubResourceAsUsed(RR.second);
// Remember to update the resource strategy for non-group resources with
// multiple units.
if (RS.getNumUnits() > 1)
Strategies[RSID]->used(RR.second);
// If there are still available units in RR.first,
// then we are done.
if (RS.isReady())
return;
// Notify to other resources that RR.first is no longer available.
for (std::unique_ptr<ResourceState> &Res : Resources) {
ResourceState &Current = *Res;
if (!Current.isAResourceGroup() || Current.getResourceMask() == RR.first)
continue;
if (Current.containsResource(RR.first)) {
unsigned Index = getResourceStateIndex(Current.getResourceMask());
Current.markSubResourceAsUsed(RR.first);
Strategies[Index]->used(RR.first);
}
}
}
void ResourceManager::release(const ResourceRef &RR) {
ResourceState &RS = *Resources[getResourceStateIndex(RR.first)];
bool WasFullyUsed = !RS.isReady();
RS.releaseSubResource(RR.second);
if (!WasFullyUsed)
return;
for (std::unique_ptr<ResourceState> &Res : Resources) {
ResourceState &Current = *Res;
if (!Current.isAResourceGroup() || Current.getResourceMask() == RR.first)
continue;
if (Current.containsResource(RR.first))
Current.releaseSubResource(RR.first);
}
}
ResourceStateEvent
ResourceManager::canBeDispatched(ArrayRef<uint64_t> Buffers) const {
ResourceStateEvent Result = ResourceStateEvent::RS_BUFFER_AVAILABLE;
for (uint64_t Buffer : Buffers) {
ResourceState &RS = *Resources[getResourceStateIndex(Buffer)];
Result = RS.isBufferAvailable();
if (Result != ResourceStateEvent::RS_BUFFER_AVAILABLE)
break;
}
return Result;
}
void ResourceManager::reserveBuffers(ArrayRef<uint64_t> Buffers) {
for (const uint64_t Buffer : Buffers) {
ResourceState &RS = *Resources[getResourceStateIndex(Buffer)];
assert(RS.isBufferAvailable() == ResourceStateEvent::RS_BUFFER_AVAILABLE);
RS.reserveBuffer();
if (RS.isADispatchHazard()) {
assert(!RS.isReserved());
RS.setReserved();
}
}
}
void ResourceManager::releaseBuffers(ArrayRef<uint64_t> Buffers) {
for (const uint64_t R : Buffers)
Resources[getResourceStateIndex(R)]->releaseBuffer();
}
bool ResourceManager::canBeIssued(const InstrDesc &Desc) const {
return all_of(
Desc.Resources, [&](const std::pair<uint64_t, const ResourceUsage> &E) {
unsigned NumUnits = E.second.isReserved() ? 0U : E.second.NumUnits;
unsigned Index = getResourceStateIndex(E.first);
return Resources[Index]->isReady(NumUnits);
});
}
// Returns true if all resources are in-order, and there is at least one
// resource which is a dispatch hazard (BufferSize = 0).
bool ResourceManager::mustIssueImmediately(const InstrDesc &Desc) const {
if (!canBeIssued(Desc))
return false;
bool AllInOrderResources = all_of(Desc.Buffers, [&](uint64_t BufferMask) {
unsigned Index = getResourceStateIndex(BufferMask);
const ResourceState &Resource = *Resources[Index];
return Resource.isInOrder() || Resource.isADispatchHazard();
});
if (!AllInOrderResources)
return false;
return any_of(Desc.Buffers, [&](uint64_t BufferMask) {
return Resources[getResourceStateIndex(BufferMask)]->isADispatchHazard();
});
}
void ResourceManager::issueInstruction(
const InstrDesc &Desc,
SmallVectorImpl<std::pair<ResourceRef, ResourceCycles>> &Pipes) {
for (const std::pair<uint64_t, ResourceUsage> &R : Desc.Resources) {
const CycleSegment &CS = R.second.CS;
if (!CS.size()) {
releaseResource(R.first);
continue;
}
assert(CS.begin() == 0 && "Invalid {Start, End} cycles!");
if (!R.second.isReserved()) {
ResourceRef Pipe = selectPipe(R.first);
use(Pipe);
BusyResources[Pipe] += CS.size();
// Replace the resource mask with a valid processor resource index.
const ResourceState &RS = *Resources[getResourceStateIndex(Pipe.first)];
Pipe.first = RS.getProcResourceID();
Pipes.emplace_back(std::pair<ResourceRef, ResourceCycles>(
Pipe, ResourceCycles(CS.size())));
} else {
assert((countPopulation(R.first) > 1) && "Expected a group!");
// Mark this group as reserved.
assert(R.second.isReserved());
reserveResource(R.first);
BusyResources[ResourceRef(R.first, R.first)] += CS.size();
}
}
}
void ResourceManager::cycleEvent(SmallVectorImpl<ResourceRef> &ResourcesFreed) {
for (std::pair<ResourceRef, unsigned> &BR : BusyResources) {
if (BR.second)
BR.second--;
if (!BR.second) {
// Release this resource.
const ResourceRef &RR = BR.first;
if (countPopulation(RR.first) == 1)
release(RR);
releaseResource(RR.first);
ResourcesFreed.push_back(RR);
}
}
for (const ResourceRef &RF : ResourcesFreed)
BusyResources.erase(RF);
}
void ResourceManager::reserveResource(uint64_t ResourceID) {
ResourceState &Resource = *Resources[getResourceStateIndex(ResourceID)];
assert(!Resource.isReserved());
Resource.setReserved();
}
void ResourceManager::releaseResource(uint64_t ResourceID) {
ResourceState &Resource = *Resources[getResourceStateIndex(ResourceID)];
Resource.clearReserved();
}
} // namespace mca
} // namespace llvm
<|endoftext|>
|
<commit_before>#include "platform/platform.h"
bool Platform::openWebBrowser(const char* webAddress)
{
String startingURL(webAddress);
String filteredURL;
U16 length = startingURL.length();
for(U16 i = 0; i < length; i++)
{
filteredURL = filteredURL + '\\' + startingURL[i];
}
String runCommand = "URL=" + filteredURL + "; xdg-open $URL > /dev/null 2> /dev/null";
S16 statusCode;
statusCode = system(runCommand.c_str());
if(statusCode == 0)
{
return true;
}
return false;
}
#ifdef TORQUE_DEDICATED
// XA: New class for the unix unicode font
class PlatformFont;
PlatformFont *createPlatformFont(const char *name, dsize_t size, U32 charset /* = TGE_ANSI_CHARSET */) { return NULL; }
#endif
<commit_msg>Change shorts to ints<commit_after>#include "platform/platform.h"
bool Platform::openWebBrowser(const char* webAddress)
{
String startingURL(webAddress);
String filteredURL;
U32 length = startingURL.length();
for(U32 i = 0; i < length; i++)
{
filteredURL = filteredURL + '\\' + startingURL[i];
}
String runCommand = "URL=" + filteredURL + "; xdg-open $URL > /dev/null 2> /dev/null";
S32 statusCode;
statusCode = system(runCommand.c_str());
if(statusCode == 0)
{
return true;
}
return false;
}
#ifdef TORQUE_DEDICATED
// XA: New class for the unix unicode font
class PlatformFont;
PlatformFont *createPlatformFont(const char *name, dsize_t size, U32 charset /* = TGE_ANSI_CHARSET */) { return NULL; }
#endif
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "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/02/01 22:34:31 peiyongz
* sane_include
*
* Revision 1.7 2001/10/26 11:55:46 tng
* Nest entire test in an inner block for reference counting to recover all document storage when this block exits before XMLPlatformUtils::Terminate is called.
*
* Revision 1.6 2001/10/19 19:02:42 tng
* [Bug 3909] return non-zero an exit code when error was encounted.
* And other modification for consistent help display and return code across samples.
*
* Revision 1.5 2000/03/02 19:53:39 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:47:17 rahulj
* Year 2K copyright swat.
*
* Revision 1.3 2000/01/19 00:17:50 rahulj
* Added makefile for unix builds. Fixed the comments and usage
* string.
*
* Revision 1.2 2000/01/18 23:57:35 rahulj
* Now exploting C++ features to compact the sample code.
*
* Revision 1.1 2000/01/18 23:22:18 rahulj
* Added new sample to illustrate how to create a DOM tree in
* memory.
*
*/
/*
* This sample illustrates how you can create a DOM tree in memory.
* It then prints the count of elements in the tree.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/dom/DOM.hpp>
#include <iostream.h>
// ---------------------------------------------------------------------------
// main
// ---------------------------------------------------------------------------
int main(int argC, char* argV[])
{
// Initialize the XML4C2 system.
try
{
XMLPlatformUtils::Initialize();
}
catch(const XMLException& toCatch)
{
char *pMsg = XMLString::transcode(toCatch.getMessage());
cerr << "Error during Xerces-c Initialization.\n"
<< " Exception message:"
<< pMsg;
delete pMsg;
return 1;
}
// Watch for special case help request
if (argC > 1)
{
cout << "\nUsage:\n"
" CreateDOMDocument\n\n"
"This program creates a new DOM document from scratch in memory.\n"
"It then prints the count of elements in the tree.\n"
<< endl;
XMLPlatformUtils::Terminate();
return 1;
}
{
// Nest entire test in an inner block.
// Reference counting should recover all document
// storage when this block exits.
// The tree we create below is the same that the DOMParser would
// have created, except that no whitespace text nodes would be created.
// <company>
// <product>Xerces-C</product>
// <category idea='great'>XML Parsing Tools</category>
// <developedBy>Apache Software Foundation</developedBy>
// </company>
DOM_DOMImplementation impl;
DOM_Document doc = impl.createDocument(
0, // root element namespace URI.
"company", // root element name
DOM_DocumentType()); // document type object (DTD).
DOM_Element rootElem = doc.getDocumentElement();
DOM_Element prodElem = doc.createElement("product");
rootElem.appendChild(prodElem);
DOM_Text prodDataVal = doc.createTextNode("Xerces-C");
prodElem.appendChild(prodDataVal);
DOM_Element catElem = doc.createElement("category");
rootElem.appendChild(catElem);
catElem.setAttribute("idea", "great");
DOM_Text catDataVal = doc.createTextNode("XML Parsing Tools");
catElem.appendChild(catDataVal);
DOM_Element devByElem = doc.createElement("developedBy");
rootElem.appendChild(devByElem);
DOM_Text devByDataVal = doc.createTextNode("Apache Software Foundation");
devByElem.appendChild(devByDataVal);
//
// Now count the number of elements in the above DOM tree.
//
unsigned int elementCount = doc.getElementsByTagName("*").getLength();
cout << "The tree just created contains: " << elementCount
<< " elements." << endl;
//
// The DOM document and its contents are reference counted, and need
// no explicit deletion.
//
}
XMLPlatformUtils::Terminate();
return 0;
}
<commit_msg>Memory leak fix in samples / test cases.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "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/02/04 18:46:33 tng
* Memory leak fix in samples / test cases.
*
* Revision 1.8 2002/02/01 22:34:31 peiyongz
* sane_include
*
* Revision 1.7 2001/10/26 11:55:46 tng
* Nest entire test in an inner block for reference counting to recover all document storage when this block exits before XMLPlatformUtils::Terminate is called.
*
* Revision 1.6 2001/10/19 19:02:42 tng
* [Bug 3909] return non-zero an exit code when error was encounted.
* And other modification for consistent help display and return code across samples.
*
* Revision 1.5 2000/03/02 19:53:39 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:47:17 rahulj
* Year 2K copyright swat.
*
* Revision 1.3 2000/01/19 00:17:50 rahulj
* Added makefile for unix builds. Fixed the comments and usage
* string.
*
* Revision 1.2 2000/01/18 23:57:35 rahulj
* Now exploting C++ features to compact the sample code.
*
* Revision 1.1 2000/01/18 23:22:18 rahulj
* Added new sample to illustrate how to create a DOM tree in
* memory.
*
*/
/*
* This sample illustrates how you can create a DOM tree in memory.
* It then prints the count of elements in the tree.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/dom/DOM.hpp>
#include <iostream.h>
// ---------------------------------------------------------------------------
// main
// ---------------------------------------------------------------------------
int main(int argC, char* argV[])
{
// Initialize the XML4C2 system.
try
{
XMLPlatformUtils::Initialize();
}
catch(const XMLException& toCatch)
{
char *pMsg = XMLString::transcode(toCatch.getMessage());
cerr << "Error during Xerces-c Initialization.\n"
<< " Exception message:"
<< pMsg;
delete [] pMsg;
return 1;
}
// Watch for special case help request
if (argC > 1)
{
cout << "\nUsage:\n"
" CreateDOMDocument\n\n"
"This program creates a new DOM document from scratch in memory.\n"
"It then prints the count of elements in the tree.\n"
<< endl;
XMLPlatformUtils::Terminate();
return 1;
}
{
// Nest entire test in an inner block.
// Reference counting should recover all document
// storage when this block exits.
// The tree we create below is the same that the DOMParser would
// have created, except that no whitespace text nodes would be created.
// <company>
// <product>Xerces-C</product>
// <category idea='great'>XML Parsing Tools</category>
// <developedBy>Apache Software Foundation</developedBy>
// </company>
DOM_DOMImplementation impl;
DOM_Document doc = impl.createDocument(
0, // root element namespace URI.
"company", // root element name
DOM_DocumentType()); // document type object (DTD).
DOM_Element rootElem = doc.getDocumentElement();
DOM_Element prodElem = doc.createElement("product");
rootElem.appendChild(prodElem);
DOM_Text prodDataVal = doc.createTextNode("Xerces-C");
prodElem.appendChild(prodDataVal);
DOM_Element catElem = doc.createElement("category");
rootElem.appendChild(catElem);
catElem.setAttribute("idea", "great");
DOM_Text catDataVal = doc.createTextNode("XML Parsing Tools");
catElem.appendChild(catDataVal);
DOM_Element devByElem = doc.createElement("developedBy");
rootElem.appendChild(devByElem);
DOM_Text devByDataVal = doc.createTextNode("Apache Software Foundation");
devByElem.appendChild(devByDataVal);
//
// Now count the number of elements in the above DOM tree.
//
unsigned int elementCount = doc.getElementsByTagName("*").getLength();
cout << "The tree just created contains: " << elementCount
<< " elements." << endl;
//
// The DOM document and its contents are reference counted, and need
// no explicit deletion.
//
}
XMLPlatformUtils::Terminate();
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright 2016 John Bailey
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 "LimitLibrary.hpp"
#include "MetricOptions.hpp"
#include <llvm/Support/Regex.h>
#include <llvm/ADT/StringRef.h>
#include <iostream>
static const std::set<std::string> knownOperators = { ">", "<", "<=", ">=" };
LimitLibrary::LimitLibrary()
{
}
void LimitLibrary::parseCsvLine(csv::ifstream& p_is)
{
std::string metricName;
limitPattern_t pattern;
std::string global;
std::string file;
float limit;
p_is >> metricName >> global >> file >> pattern.fileName >> pattern.funcName >> pattern.operand >> limit >> pattern.text;
#if 0
std::cout << "Read: " << metricName << " / " << pattern.fileName << " / " << pattern.funcName << " / " << pattern.operand << " / " << pattern.limit << std::endl;
#endif
if (global.length())
{
pattern.global = true;
}
else
{
pattern.global = false;
}
if (file.length())
{
pattern.file = true;
}
else
{
pattern.file = false;
}
/* TODO: deal with scaling */
if (metricName[0] != ';')
{
MetricType_e metric = MetricUnit::getMetricByShortName(metricName);
if (metric != METRIC_TYPE_MAX)
{
#if 0
std::cout << "Metric is " << metric << std::endl;
#endif
if ( knownOperators.find( pattern.operand ) == knownOperators.end() )
{
std::cerr << "Unknown operator in limits file '" << pattern.operand << "'\n";
exit(EXIT_FAILURE);
}
pattern.limit = limit * MetricUnit::getMetricScaling(metric);
m_patternMap[metric].push_back(pattern);
}
else
{
std::cerr << "Ignoring limits file line starting " << metricName << "\n";
exit(EXIT_FAILURE);
}
}
else
{
/* It's a comment line - ignore */
}
}
bool LimitLibrary::load(const std::vector<std::string>& p_fileNames)
{
bool ret_val = true;
for (std::vector<std::string>::const_iterator it = p_fileNames.begin();
it != p_fileNames.end();
it++)
{
if (!load(*it))
{
ret_val = false;
break;
}
}
return ret_val;
}
bool LimitLibrary::load( const std::string p_fileName )
{
bool ret_val = false;
csv::ifstream is(p_fileName.c_str());
is.enable_trim_quote_on_str(true,'"');
is.enable_terminate_on_blank_line(false);
if( is.is_open() )
{
while (is.read_line())
{
parseCsvLine(is);
}
ret_val = true;
}
else
{
std::cerr << "Failed to open limits file '" << p_fileName << "'\n";
exit(EXIT_FAILURE);
}
return ret_val;
}
const LimitLibrary::limitPattern_t* LimitLibrary::findHighestPresidenceRule(const patternSet_t& p_set, const MetricUnit& p_unit, const MetricOptions& p_options) const
{
const limitPattern_t* pattern = NULL;
for (patternSet_t::const_iterator pit = p_set.begin();
pit != p_set.end();
pit++)
{
if (unitMatchesLimitPattern(p_unit, p_options, &(*pit)))
{
pattern = &(*pit);
}
}
return pattern;
}
void LimitLibrary::checkLimit(const MetricUnit& p_unit, const MetricOptions& p_options) const
{
unsigned loop;
for (loop = 0;
loop < METRIC_TYPE_MAX;
loop++)
{
const MetricType_e metric = static_cast<MetricType_e>(loop);
if (MetricUnit::doesMetricApplyForUnit(metric,p_unit.GetType()))
{
patternMap_t::const_iterator it = m_patternMap.find(metric);
const limitPattern_t* pattern = NULL;
/* Are there any limits against this metric at all? */
if (it != m_patternMap.end())
{
/* Find the highest precident rule where the rule pattern matches this unit (if there is one) */
pattern = findHighestPresidenceRule(it->second, p_unit, p_options);
checkUnitPassesMetricLimit(p_unit, p_options, metric, pattern);
}
}
}
}
void LimitLibrary::checkUnitPassesMetricLimit(const MetricUnit& p_unit, const MetricOptions& p_options, const MetricType_e p_metric, const limitPattern_t* const p_pattern)
{
if (p_pattern != NULL)
{
MetricUnit::counter_t val = p_unit.getCounter(p_metric, MetricUnit::isMetricCumulative(p_metric));
#if 0
std::cout << "Checking " << p_unit.getUnitName(p_options) << " for '" << MetricUnit::getMetricName(it->first) << "'\n";
#endif
if (((p_pattern->operand == "<") && (val < p_pattern->limit)) ||
((p_pattern->operand == ">") && (val > p_pattern->limit)) ||
((p_pattern->operand == ">=") && (val >= p_pattern->limit)) ||
((p_pattern->operand == "<=") && (val <= p_pattern->limit)))
{
/* Passed check */
}
else
{
std::ostream& out = p_options.getOutput();
// TODO: Qualify the unitName - is it a function? Is it a file? Global?
out << p_unit.getUnitName(p_options) << " failed limits check '" << MetricUnit::getMetricName(p_metric) << "' (actual: "
<< MetricUnit::getScaledMetricString(p_metric,val) << " expected: " << p_pattern->operand
<< MetricUnit::getScaledMetricString(p_metric, p_pattern->limit) << ")";
if (p_pattern->text.length())
{
out << ": " << p_pattern->text;
}
out << "\n";
}
}
}
bool LimitLibrary::unitMatchesLimitPattern(const MetricUnit& p_unit, const MetricOptions& p_options, const limitPattern_t* const p_pattern)
{
bool matches = false;
switch (p_unit.GetType())
{
case METRIC_UNIT_GLOBAL:
if (p_pattern->global)
{
matches = true;
}
break;
case METRIC_UNIT_FILE:
if (p_pattern->file)
{
llvm::Regex regex(p_pattern->fileName);
if (regex.match(p_unit.getUnitName(p_options)))
{
matches = true;
}
}
break;
case METRIC_UNIT_FUNCTION:
if (p_pattern->funcName.length())
{
llvm::Regex regex(p_pattern->funcName);
if (regex.match(p_unit.getUnitName(p_options)))
{
llvm::Regex fileRegex(p_pattern->fileName);
if (fileRegex.match(p_unit.getParent()->getUnitName(p_options)))
{
matches = true;
}
}
}
break;
default:
break;
}
return matches;
}
<commit_msg>Clean-up TODO comments which are no longer relevant<commit_after>/*
Copyright 2016 John Bailey
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 "LimitLibrary.hpp"
#include "MetricOptions.hpp"
#include <llvm/Support/Regex.h>
#include <llvm/ADT/StringRef.h>
#include <iostream>
static const std::set<std::string> knownOperators = { ">", "<", "<=", ">=" };
LimitLibrary::LimitLibrary()
{
}
void LimitLibrary::parseCsvLine(csv::ifstream& p_is)
{
std::string metricName;
limitPattern_t pattern;
std::string global;
std::string file;
float limit;
p_is >> metricName >> global >> file >> pattern.fileName >> pattern.funcName >> pattern.operand >> limit >> pattern.text;
#if 0
std::cout << "Read: " << metricName << " / " << pattern.fileName << " / " << pattern.funcName << " / " << pattern.operand << " / " << pattern.limit << std::endl;
#endif
if (global.length())
{
pattern.global = true;
}
else
{
pattern.global = false;
}
if (file.length())
{
pattern.file = true;
}
else
{
pattern.file = false;
}
if (metricName[0] != ';')
{
MetricType_e metric = MetricUnit::getMetricByShortName(metricName);
if (metric != METRIC_TYPE_MAX)
{
#if 0
std::cout << "Metric is " << metric << std::endl;
#endif
if ( knownOperators.find( pattern.operand ) == knownOperators.end() )
{
std::cerr << "Unknown operator in limits file '" << pattern.operand << "'\n";
exit(EXIT_FAILURE);
}
pattern.limit = limit * MetricUnit::getMetricScaling(metric);
m_patternMap[metric].push_back(pattern);
}
else
{
std::cerr << "Ignoring limits file line starting " << metricName << "\n";
exit(EXIT_FAILURE);
}
}
else
{
/* It's a comment line - ignore */
}
}
bool LimitLibrary::load(const std::vector<std::string>& p_fileNames)
{
bool ret_val = true;
for (std::vector<std::string>::const_iterator it = p_fileNames.begin();
it != p_fileNames.end();
it++)
{
if (!load(*it))
{
ret_val = false;
break;
}
}
return ret_val;
}
bool LimitLibrary::load( const std::string p_fileName )
{
bool ret_val = false;
csv::ifstream is(p_fileName.c_str());
is.enable_trim_quote_on_str(true,'"');
is.enable_terminate_on_blank_line(false);
if( is.is_open() )
{
while (is.read_line())
{
parseCsvLine(is);
}
ret_val = true;
}
else
{
std::cerr << "Failed to open limits file '" << p_fileName << "'\n";
exit(EXIT_FAILURE);
}
return ret_val;
}
const LimitLibrary::limitPattern_t* LimitLibrary::findHighestPresidenceRule(const patternSet_t& p_set, const MetricUnit& p_unit, const MetricOptions& p_options) const
{
const limitPattern_t* pattern = NULL;
for (patternSet_t::const_iterator pit = p_set.begin();
pit != p_set.end();
pit++)
{
if (unitMatchesLimitPattern(p_unit, p_options, &(*pit)))
{
pattern = &(*pit);
}
}
return pattern;
}
void LimitLibrary::checkLimit(const MetricUnit& p_unit, const MetricOptions& p_options) const
{
unsigned loop;
for (loop = 0;
loop < METRIC_TYPE_MAX;
loop++)
{
const MetricType_e metric = static_cast<MetricType_e>(loop);
if (MetricUnit::doesMetricApplyForUnit(metric,p_unit.GetType()))
{
patternMap_t::const_iterator it = m_patternMap.find(metric);
const limitPattern_t* pattern = NULL;
/* Are there any limits against this metric at all? */
if (it != m_patternMap.end())
{
/* Find the highest precident rule where the rule pattern matches this unit (if there is one) */
pattern = findHighestPresidenceRule(it->second, p_unit, p_options);
checkUnitPassesMetricLimit(p_unit, p_options, metric, pattern);
}
}
}
}
void LimitLibrary::checkUnitPassesMetricLimit(const MetricUnit& p_unit, const MetricOptions& p_options, const MetricType_e p_metric, const limitPattern_t* const p_pattern)
{
if (p_pattern != NULL)
{
MetricUnit::counter_t val = p_unit.getCounter(p_metric, MetricUnit::isMetricCumulative(p_metric));
#if 0
std::cout << "Checking " << p_unit.getUnitName(p_options) << " for '" << MetricUnit::getMetricName(it->first) << "'\n";
#endif
if (((p_pattern->operand == "<") && (val < p_pattern->limit)) ||
((p_pattern->operand == ">") && (val > p_pattern->limit)) ||
((p_pattern->operand == ">=") && (val >= p_pattern->limit)) ||
((p_pattern->operand == "<=") && (val <= p_pattern->limit)))
{
/* Passed check */
}
else
{
std::ostream& out = p_options.getOutput();
out << p_unit.getUnitName(p_options) << " failed limits check '" << MetricUnit::getMetricName(p_metric) << "' (actual: "
<< MetricUnit::getScaledMetricString(p_metric,val) << " expected: " << p_pattern->operand
<< MetricUnit::getScaledMetricString(p_metric, p_pattern->limit) << ")";
if (p_pattern->text.length())
{
out << ": " << p_pattern->text;
}
out << "\n";
}
}
}
bool LimitLibrary::unitMatchesLimitPattern(const MetricUnit& p_unit, const MetricOptions& p_options, const limitPattern_t* const p_pattern)
{
bool matches = false;
switch (p_unit.GetType())
{
case METRIC_UNIT_GLOBAL:
if (p_pattern->global)
{
matches = true;
}
break;
case METRIC_UNIT_FILE:
if (p_pattern->file)
{
llvm::Regex regex(p_pattern->fileName);
if (regex.match(p_unit.getUnitName(p_options)))
{
matches = true;
}
}
break;
case METRIC_UNIT_FUNCTION:
if (p_pattern->funcName.length())
{
llvm::Regex regex(p_pattern->funcName);
if (regex.match(p_unit.getUnitName(p_options)))
{
llvm::Regex fileRegex(p_pattern->fileName);
if (fileRegex.match(p_unit.getParent()->getUnitName(p_options)))
{
matches = true;
}
}
}
break;
default:
break;
}
return matches;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.