text stringlengths 54 60.6k |
|---|
<commit_before>
#include <nstd/Console.h>
#include <nstd/Process.h>
#include "Tools/Word.h"
#include "Client.h"
void_t help()
{
Console::printf("listUsers - Show list of users.\n");
Console::printf("addUser <name> <pw> - Add a new user.\n");
Console::printf("list - Show list of tables.\n");
Console::printf("create <name> - Create a new table.\n");
Console::printf("query [<id>] - Query data from selected table.\n");
Console::printf("select <num> - Select a table for further requests.\n");
//Console::printf("add <value> - Add string data to selected table.\n");
//Console::printf("addData <len> - Add <len> bytes to selected table.\n");
Console::printf("subscribe - Subscribe to selected table.\n");
Console::printf("sync - Get time synchronization data of the selected table.\n");
Console::printf("exit - Quit the session.\n");
}
int_t main(int_t argc, char_t* argv[])
{
String password("root");
String user("root");
String address("127.0.0.1:13211");
{
Process::Option options[] = {
{'p', "password", Process::argumentFlag},
{'u', "user", Process::argumentFlag},
};
Process::Arguments arguments(argc, argv, options);
int_t character;
String argument;
while(arguments.read(character, argument))
switch(character)
{
case 'p':
password = argument;
break;
case 'u':
user = argument;
break;
case 0:
address = argument;
break;
case '?':
Console::errorf("Unknown option: %s.\n", (const char_t*)argument);
return 1;
case ':':
Console::errorf("Option %s required an argument.\n", (const char_t*)argument);
return 1;
default:
Console::errorf("Usage: %s [-u <user>] [-p <password>] [<address>]\n");
return 1;
}
}
Console::Prompt prompt;
Client client;
if(!client.connect(user, password, address))
{
Console::errorf("error: Could not establish connection: %s\n", (const char_t*)client.getLastError());
return 1;
}
for(;;)
{
String result = prompt.getLine("zlimdb> ");
Console::printf(String("zlimdb> ") + result + "\n");
List<String> args;
Word::split(result, args);
String cmd = args.isEmpty() ? String() : args.front();
if(cmd == "exit" || cmd == "quit")
break;
else if(cmd == "help")
help();
else if(cmd == "listUsers")
client.listUsers();
else if(cmd == "addUser")
{
if(args.size() < 3)
Console::errorf("error: Missing arguments: addUser <name> <pw>\n");
else
{
String name = *(++args.begin());
String password = *(++(++args.begin()));
client.addUser(name, password);
}
}
else if(cmd == "list")
client.listTables();
else if(cmd == "create")
{
if(args.size() < 2)
Console::errorf("error: Missing argument: create <name>\n");
else
{
String name = *(++args.begin());
client.createTable(name);
}
}
else if(cmd == "select")
{
if(args.size() < 2)
Console::errorf("error: Missing argument: select <num>\n");
else
{
String num = *(++args.begin());
client.selectTable(num.toUInt());
}
}
else if(cmd == "query")
{
if(args.size() >= 2)
{
uint64_t id = (++args.begin())->toUInt64();
client.query(id);
}
else
client.query();
}
//else if(cmd == "add")
//{
// if(args.size() < 2)
// Console::errorf("error: Missing argument: select <num>\n");
// else
// {
// String value = *(++args.begin());
// client.add(value);
// }
//}
//else if(cmd == "addData")
//{
// if(args.size() < 2)
// Console::errorf("error: Missing argument: select <num>\n");
// else
// {
// size_t len = (++args.begin())->toUInt();
// size_t count = args.size() < 3 ? 1 : (++(++args.begin()))->toUInt();
// String value;
// value.resize(len);
// Memory::fill((char_t*)value, 'a', len);
// for(size_t i = 0; i < count; ++i)
// client.add(value);
// }
//}
else if(cmd == "subscribe")
{
client.subscribe();
}
else if(cmd == "sync")
{
client.sync();
}
else if(!cmd.isEmpty())
Console::errorf("error: Unknown command: %s\n", (const char_t*)cmd);
}
client.disconnect();
return 0;
}
<commit_msg>Add help option<commit_after>
#include <nstd/Console.h>
#include <nstd/Process.h>
#include "Tools/Word.h"
#include "Client.h"
void_t help()
{
Console::printf("listUsers - Show list of users.\n");
Console::printf("addUser <name> <pw> - Add a new user.\n");
Console::printf("list - Show list of tables.\n");
Console::printf("create <name> - Create a new table.\n");
Console::printf("query [<id>] - Query data from selected table.\n");
Console::printf("select <num> - Select a table for further requests.\n");
//Console::printf("add <value> - Add string data to selected table.\n");
//Console::printf("addData <len> - Add <len> bytes to selected table.\n");
Console::printf("subscribe - Subscribe to selected table.\n");
Console::printf("sync - Get time synchronization data of the selected table.\n");
Console::printf("exit - Quit the session.\n");
}
int_t main(int_t argc, char_t* argv[])
{
String password("root");
String user("root");
String address("127.0.0.1:13211");
{
Process::Option options[] = {
{'p', "password", Process::argumentFlag},
{'u', "user", Process::argumentFlag},
{'h', "help", Process::optionFlag},
};
Process::Arguments arguments(argc, argv, options);
int_t character;
String argument;
while(arguments.read(character, argument))
switch(character)
{
case 'p':
password = argument;
break;
case 'u':
user = argument;
break;
case 0:
address = argument;
break;
case '?':
Console::errorf("Unknown option: %s.\n", (const char_t*)argument);
return 1;
case ':':
Console::errorf("Option %s required an argument.\n", (const char_t*)argument);
return 1;
default:
Console::errorf("Usage: %s [-u <user>] [-p <password>] [<address>]\n", argv[0]);
return 1;
}
}
Console::Prompt prompt;
Client client;
if(!client.connect(user, password, address))
{
Console::errorf("error: Could not establish connection: %s\n", (const char_t*)client.getLastError());
return 1;
}
for(;;)
{
String result = prompt.getLine("zlimdb> ");
Console::printf(String("zlimdb> ") + result + "\n");
List<String> args;
Word::split(result, args);
String cmd = args.isEmpty() ? String() : args.front();
if(cmd == "exit" || cmd == "quit")
break;
else if(cmd == "help")
help();
else if(cmd == "listUsers")
client.listUsers();
else if(cmd == "addUser")
{
if(args.size() < 3)
Console::errorf("error: Missing arguments: addUser <name> <pw>\n");
else
{
String name = *(++args.begin());
String password = *(++(++args.begin()));
client.addUser(name, password);
}
}
else if(cmd == "list")
client.listTables();
else if(cmd == "create")
{
if(args.size() < 2)
Console::errorf("error: Missing argument: create <name>\n");
else
{
String name = *(++args.begin());
client.createTable(name);
}
}
else if(cmd == "select")
{
if(args.size() < 2)
Console::errorf("error: Missing argument: select <num>\n");
else
{
String num = *(++args.begin());
client.selectTable(num.toUInt());
}
}
else if(cmd == "query")
{
if(args.size() >= 2)
{
uint64_t id = (++args.begin())->toUInt64();
client.query(id);
}
else
client.query();
}
//else if(cmd == "add")
//{
// if(args.size() < 2)
// Console::errorf("error: Missing argument: select <num>\n");
// else
// {
// String value = *(++args.begin());
// client.add(value);
// }
//}
//else if(cmd == "addData")
//{
// if(args.size() < 2)
// Console::errorf("error: Missing argument: select <num>\n");
// else
// {
// size_t len = (++args.begin())->toUInt();
// size_t count = args.size() < 3 ? 1 : (++(++args.begin()))->toUInt();
// String value;
// value.resize(len);
// Memory::fill((char_t*)value, 'a', len);
// for(size_t i = 0; i < count; ++i)
// client.add(value);
// }
//}
else if(cmd == "subscribe")
{
client.subscribe();
}
else if(cmd == "sync")
{
client.sync();
}
else if(!cmd.isEmpty())
Console::errorf("error: Unknown command: %s\n", (const char_t*)cmd);
}
client.disconnect();
return 0;
}
<|endoftext|> |
<commit_before>#include <cstdio>
int main(){
double n, d[] = {100.0, 50.0, 20.0, 10.0, 5.0, 2.0}, m[] = {1.0, 0.5, 0.25, 0.10, 0.05, 0.01};
int t = 0, c;
scanf("%lf", &n);
printf("NOTAS:\n");
do {
printf("%d nota(s) de R$ %.2f\n", (int)n / (int)d[t], d[t]);
if (n >= d[t])
n -= d[t] * (int)(n / d[t]);
} while(d[t++] != 2.0);
t = 0;
printf("MOEDAS:\n");
do {
c = 0;
while(n >= m[t]){
n -= m[t];
c++;
}
printf("%d moeda(s) de R$ %.2f\n", c, m[t]);
t++;
} while(n >= 0.01);
return 0;
}
<commit_msg>Refatorando 1021.<commit_after>#include <cstdio>
int main(){
double n, d[] = {100.0, 50.0, 20.0, 10.0, 5.0, 2.0, 1.0, 0.5, 0.25, 0.10, 0.05, 0.01};
int t = 0, c;
scanf("%lf", &n);
printf("NOTAS:\n");
t = 0;
while (n >= 0.01){
c = 0;
while (n >= d[t]){
n -= d[t];
c++;
}
if (d[t] == 1.0)
printf("MOEDAS:\n");
if (d[t] >= 2.0 )
printf("%d nota(s) de R$ %.2f\n", c, d[t]);
else
printf("%d moeda(s) de R$ %.2f\n", c, d[t]);
t++;
}
return 0;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: ImageRegistration13.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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.
=========================================================================*/
// Software Guide : BeginLatex
//
// This example illustrates how to do registration with a 2D Rigid Transform
// and with MutualInformation metric.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkImageRegistrationMethod.h"
#include "itkCenteredRigid2DTransform.h"
#include "itkCenteredTransformInitializer.h"
#include "itkMattesMutualInformationImageToImageMetric.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkRegularStepGradientDescentOptimizer.h"
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkResampleImageFilter.h"
#include "itkCastImageFilter.h"
// The following section of code implements a Command observer
// used to monitor the evolution of the registration process.
//
#include "itkCommand.h"
class CommandIterationUpdate : public itk::Command
{
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro( Self );
protected:
CommandIterationUpdate() {};
public:
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
typedef const OptimizerType * OptimizerPointer;
void Execute(itk::Object *caller, const itk::EventObject & event)
{
Execute( (const itk::Object *)caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject & event)
{
OptimizerPointer optimizer =
dynamic_cast< OptimizerPointer >( object );
if( typeid( event ) != typeid( itk::IterationEvent ) )
{
return;
}
std::cout << optimizer->GetCurrentIteration() << " ";
std::cout << optimizer->GetValue() << " ";
std::cout << optimizer->GetCurrentPosition() << std::endl;
}
};
int main( int argc, char *argv[] )
{
if( argc < 3 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " fixedImageFile movingImageFile ";
std::cerr << "outputImagefile [differenceImage]" << std::endl;
return 1;
}
const unsigned int Dimension = 2;
typedef unsigned short PixelType;
typedef itk::Image< PixelType, Dimension > FixedImageType;
typedef itk::Image< PixelType, Dimension > MovingImageType;
typedef itk::CenteredRigid2DTransform< double > TransformType;
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
typedef itk::LinearInterpolateImageFunction<
MovingImageType,
double > InterpolatorType;
typedef itk::ImageRegistrationMethod<
FixedImageType,
MovingImageType > RegistrationType;
typedef itk::MattesMutualInformationImageToImageMetric<
FixedImageType,
MovingImageType > MetricType;
TransformType::Pointer transform = TransformType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
InterpolatorType::Pointer interpolator = InterpolatorType::New();
RegistrationType::Pointer registration = RegistrationType::New();
registration->SetOptimizer( optimizer );
registration->SetTransform( transform );
registration->SetInterpolator( interpolator );
MetricType::Pointer metric = MetricType::New();
registration->SetMetric( metric );
metric->SetNumberOfHistogramBins( 20 );
metric->SetNumberOfSpatialSamples( 10000 );
typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;
typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;
FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();
MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();
fixedImageReader->SetFileName( argv[1] );
movingImageReader->SetFileName( argv[2] );
registration->SetFixedImage( fixedImageReader->GetOutput() );
registration->SetMovingImage( movingImageReader->GetOutput() );
fixedImageReader->Update();
registration->SetFixedImageRegion(
fixedImageReader->GetOutput()->GetBufferedRegion() );
typedef itk::CenteredTransformInitializer<
TransformType,
FixedImageType,
MovingImageType > TransformInitializerType;
TransformInitializerType::Pointer initializer = TransformInitializerType::New();
initializer->SetTransform( transform );
initializer->SetFixedImage( fixedImageReader->GetOutput() );
initializer->SetMovingImage( movingImageReader->GetOutput() );
initializer->GeometryOn();
initializer->InitializeTransform();
transform->SetAngle( 0.0 );
registration->SetInitialTransformParameters( transform->GetParameters() );
typedef OptimizerType::ScalesType OptimizerScalesType;
OptimizerScalesType optimizerScales( transform->GetNumberOfParameters() );
const double translationScale = 1.0 / 1000.0;
optimizerScales[0] = 1.0;
optimizerScales[1] = translationScale;
optimizerScales[2] = translationScale;
optimizerScales[3] = translationScale;
optimizerScales[4] = translationScale;
optimizer->SetScales( optimizerScales );
optimizer->SetMaximumStepLength( 0.1 );
optimizer->SetMinimumStepLength( 0.001 );
optimizer->SetNumberOfIterations( 400 );
// Create the Command observer and register it with the optimizer.
//
CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();
optimizer->AddObserver( itk::IterationEvent(), observer );
try
{
registration->StartRegistration();
}
catch( itk::ExceptionObject & err )
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
typedef RegistrationType::ParametersType ParametersType;
ParametersType finalParameters = registration->GetLastTransformParameters();
const double finalAngle = finalParameters[0];
const double finalRotationCenterX = finalParameters[1];
const double finalRotationCenterY = finalParameters[2];
const double finalTranslationX = finalParameters[3];
const double finalTranslationY = finalParameters[4];
unsigned int numberOfIterations = optimizer->GetCurrentIteration();
double bestValue = optimizer->GetValue();
// Print out results
//
const double finalAngleInDegrees = finalAngle * 45.0 / atan(1.0);
std::cout << "Result = " << std::endl;
std::cout << " Angle (radians) " << finalAngle << std::endl;
std::cout << " Angle (degrees) " << finalAngleInDegrees << std::endl;
std::cout << " Center X = " << finalRotationCenterX << std::endl;
std::cout << " Center Y = " << finalRotationCenterY << std::endl;
std::cout << " Translation X = " << finalTranslationX << std::endl;
std::cout << " Translation Y = " << finalTranslationY << std::endl;
std::cout << " Iterations = " << numberOfIterations << std::endl;
std::cout << " Metric value = " << bestValue << std::endl;
typedef itk::ResampleImageFilter<
MovingImageType,
FixedImageType > ResampleFilterType;
TransformType::Pointer finalTransform = TransformType::New();
finalTransform->SetParameters( finalParameters );
ResampleFilterType::Pointer resample = ResampleFilterType::New();
resample->SetTransform( finalTransform );
resample->SetInput( movingImageReader->GetOutput() );
FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();
resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() );
resample->SetOutputOrigin( fixedImage->GetOrigin() );
resample->SetOutputSpacing( fixedImage->GetSpacing() );
resample->SetDefaultPixelValue( 100 );
typedef unsigned char OutputPixelType;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
typedef itk::CastImageFilter<
FixedImageType,
OutputImageType > CastFilterType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
CastFilterType::Pointer caster = CastFilterType::New();
writer->SetFileName( argv[3] );
caster->SetInput( resample->GetOutput() );
writer->SetInput( caster->GetOutput() );
writer->Update();
// Software Guide : EndCodeSnippet
return 0;
}
<commit_msg>ENH: Simplifying the example. Using PixelType = unsigned char and removing the cast filter on the output.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: ImageRegistration13.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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.
=========================================================================*/
// Software Guide : BeginLatex
//
// This example illustrates how to do registration with a 2D Rigid Transform
// and with MutualInformation metric.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkImageRegistrationMethod.h"
#include "itkCenteredRigid2DTransform.h"
#include "itkCenteredTransformInitializer.h"
#include "itkMattesMutualInformationImageToImageMetric.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkRegularStepGradientDescentOptimizer.h"
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkResampleImageFilter.h"
#include "itkCastImageFilter.h"
// The following section of code implements a Command observer
// used to monitor the evolution of the registration process.
//
#include "itkCommand.h"
class CommandIterationUpdate : public itk::Command
{
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro( Self );
protected:
CommandIterationUpdate() {};
public:
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
typedef const OptimizerType * OptimizerPointer;
void Execute(itk::Object *caller, const itk::EventObject & event)
{
Execute( (const itk::Object *)caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject & event)
{
OptimizerPointer optimizer =
dynamic_cast< OptimizerPointer >( object );
if( typeid( event ) != typeid( itk::IterationEvent ) )
{
return;
}
std::cout << optimizer->GetCurrentIteration() << " ";
std::cout << optimizer->GetValue() << " ";
std::cout << optimizer->GetCurrentPosition() << std::endl;
}
};
int main( int argc, char *argv[] )
{
if( argc < 3 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " fixedImageFile movingImageFile ";
std::cerr << "outputImagefile [differenceImage]" << std::endl;
return 1;
}
const unsigned int Dimension = 2;
typedef unsigned char PixelType;
typedef itk::Image< PixelType, Dimension > FixedImageType;
typedef itk::Image< PixelType, Dimension > MovingImageType;
typedef itk::CenteredRigid2DTransform< double > TransformType;
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
typedef itk::LinearInterpolateImageFunction<
MovingImageType,
double > InterpolatorType;
typedef itk::ImageRegistrationMethod<
FixedImageType,
MovingImageType > RegistrationType;
typedef itk::MattesMutualInformationImageToImageMetric<
FixedImageType,
MovingImageType > MetricType;
TransformType::Pointer transform = TransformType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
InterpolatorType::Pointer interpolator = InterpolatorType::New();
RegistrationType::Pointer registration = RegistrationType::New();
registration->SetOptimizer( optimizer );
registration->SetTransform( transform );
registration->SetInterpolator( interpolator );
MetricType::Pointer metric = MetricType::New();
registration->SetMetric( metric );
metric->SetNumberOfHistogramBins( 20 );
metric->SetNumberOfSpatialSamples( 10000 );
typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;
typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;
FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();
MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();
fixedImageReader->SetFileName( argv[1] );
movingImageReader->SetFileName( argv[2] );
registration->SetFixedImage( fixedImageReader->GetOutput() );
registration->SetMovingImage( movingImageReader->GetOutput() );
fixedImageReader->Update();
registration->SetFixedImageRegion(
fixedImageReader->GetOutput()->GetBufferedRegion() );
typedef itk::CenteredTransformInitializer<
TransformType,
FixedImageType,
MovingImageType > TransformInitializerType;
TransformInitializerType::Pointer initializer = TransformInitializerType::New();
initializer->SetTransform( transform );
initializer->SetFixedImage( fixedImageReader->GetOutput() );
initializer->SetMovingImage( movingImageReader->GetOutput() );
initializer->GeometryOn();
initializer->InitializeTransform();
transform->SetAngle( 0.0 );
registration->SetInitialTransformParameters( transform->GetParameters() );
typedef OptimizerType::ScalesType OptimizerScalesType;
OptimizerScalesType optimizerScales( transform->GetNumberOfParameters() );
const double translationScale = 1.0 / 1000.0;
optimizerScales[0] = 1.0;
optimizerScales[1] = translationScale;
optimizerScales[2] = translationScale;
optimizerScales[3] = translationScale;
optimizerScales[4] = translationScale;
optimizer->SetScales( optimizerScales );
optimizer->SetMaximumStepLength( 0.1 );
optimizer->SetMinimumStepLength( 0.001 );
optimizer->SetNumberOfIterations( 400 );
// Create the Command observer and register it with the optimizer.
//
CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();
optimizer->AddObserver( itk::IterationEvent(), observer );
try
{
registration->StartRegistration();
}
catch( itk::ExceptionObject & err )
{
std::cout << "ExceptionObject caught !" << std::endl;
std::cout << err << std::endl;
return -1;
}
typedef RegistrationType::ParametersType ParametersType;
ParametersType finalParameters = registration->GetLastTransformParameters();
const double finalAngle = finalParameters[0];
const double finalRotationCenterX = finalParameters[1];
const double finalRotationCenterY = finalParameters[2];
const double finalTranslationX = finalParameters[3];
const double finalTranslationY = finalParameters[4];
unsigned int numberOfIterations = optimizer->GetCurrentIteration();
double bestValue = optimizer->GetValue();
// Print out results
//
const double finalAngleInDegrees = finalAngle * 45.0 / atan(1.0);
std::cout << "Result = " << std::endl;
std::cout << " Angle (radians) " << finalAngle << std::endl;
std::cout << " Angle (degrees) " << finalAngleInDegrees << std::endl;
std::cout << " Center X = " << finalRotationCenterX << std::endl;
std::cout << " Center Y = " << finalRotationCenterY << std::endl;
std::cout << " Translation X = " << finalTranslationX << std::endl;
std::cout << " Translation Y = " << finalTranslationY << std::endl;
std::cout << " Iterations = " << numberOfIterations << std::endl;
std::cout << " Metric value = " << bestValue << std::endl;
typedef itk::ResampleImageFilter<
MovingImageType,
FixedImageType > ResampleFilterType;
TransformType::Pointer finalTransform = TransformType::New();
finalTransform->SetParameters( finalParameters );
ResampleFilterType::Pointer resample = ResampleFilterType::New();
resample->SetTransform( finalTransform );
resample->SetInput( movingImageReader->GetOutput() );
FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();
resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() );
resample->SetOutputOrigin( fixedImage->GetOrigin() );
resample->SetOutputSpacing( fixedImage->GetSpacing() );
resample->SetDefaultPixelValue( 100 );
typedef itk::Image< PixelType, Dimension > OutputImageType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[3] );
writer->SetInput( resample->GetOutput() );
writer->Update();
// Software Guide : EndCodeSnippet
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015 Baidu, 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.
// Authors: Ge,Jun (gejun@baidu.com)
#include <ostream>
#include <vector> // std::vector
#include <set>
#include <gflags/gflags.h> // GetAllFlags
// CommandLineFlagInfo
#include "butil/string_printf.h"
#include "butil/string_splitter.h"
#include "brpc/closure_guard.h" // ClosureGuard
#include "brpc/controller.h" // Controller
#include "brpc/errno.pb.h"
#include "brpc/server.h"
#include "brpc/builtin/common.h"
#include "brpc/builtin/flags_service.h"
namespace brpc {
DEFINE_bool(immutable_flags, false, "gflags on /flags page can't be modified");
// Replace some characters with html replacements. If the input string does
// not need to be changed, return its const reference directly, otherwise put
// the replaced string in backing string and return its const reference.
// TODO(gejun): Make this function more general.
static std::string HtmlReplace(const std::string& s) {
std::string b;
size_t last_pos = 0;
while (1) {
size_t new_pos = s.find_first_of("<>&", last_pos);
if (new_pos == std::string::npos) {
if (b.empty()) { // no special characters.
return s;
}
b.append(s.data() + last_pos, s.size() - last_pos);
return b;
}
b.append(s.data() + last_pos, new_pos - last_pos);
switch (s[new_pos]) {
case '<' : b.append("<"); break;
case '>' : b.append(">"); break;
case '&' : b.append("&"); break;
default: b.push_back(s[new_pos]); break;
}
last_pos = new_pos + 1;
}
}
static void PrintFlag(std::ostream& os, const GFLAGS_NS::CommandLineFlagInfo& flag,
bool use_html) {
if (use_html) {
os << "<tr><td>";
}
os << flag.name;
if (flag.has_validator_fn) {
if (use_html) {
os << " (<a href='/flags/" << flag.name
<< "?setvalue&withform'>R</a>)";
} else {
os << " (R)";
}
}
os << (use_html ? "</td><td>" : " | ");
if (!flag.is_default && use_html) {
os << "<span style='color:#FF0000'>";
}
if (!flag.current_value.empty()) {
os << (use_html ? HtmlReplace(flag.current_value)
: flag.current_value);
} else {
os << (use_html ? " " : " ");
}
if (!flag.is_default) {
if (flag.default_value != flag.current_value) {
os << " (default:" << (use_html ?
HtmlReplace(flag.default_value) :
flag.current_value) << ')';
}
if (use_html) {
os << "</span>";
}
}
os << (use_html ? "</td><td>" : " | ") << flag.description
<< (use_html ? "</td><td>" : " | ") << flag.filename;
if (use_html) {
os << "</td></tr>";
}
}
void FlagsService::set_value_page(Controller* cntl,
::google::protobuf::Closure* done) {
ClosureGuard done_guard(done);
const std::string& name = cntl->http_request().unresolved_path();
GFLAGS_NS::CommandLineFlagInfo info;
if (!GFLAGS_NS::GetCommandLineFlagInfo(name.c_str(), &info)) {
cntl->SetFailed(ENOMETHOD, "No such gflag");
return;
}
butil::IOBufBuilder os;
const bool is_string = (info.type == "string");
os << "<!DOCTYPE html><html><body>"
"<form action='' method='get'>"
" Set `" << name << "' from ";
if (is_string) {
os << '"';
}
os << info.current_value;
if (is_string) {
os << '"';
}
os << " to <input name='setvalue' value=''>"
" <button>go</button>"
"</form>"
"</body></html>";
os.move_to(cntl->response_attachment());
}
void FlagsService::default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::FlagsRequest*,
::brpc::FlagsResponse*,
::google::protobuf::Closure* done) {
ClosureGuard done_guard(done);
Controller *cntl = static_cast<Controller*>(cntl_base);
const std::string* value_str =
cntl->http_request().uri().GetQuery(SETVALUE_STR);
const std::string& constraint = cntl->http_request().unresolved_path();
const bool use_html = UseHTML(cntl->http_request());
cntl->http_response().set_content_type(
use_html ? "text/html" : "text/plain");
if (value_str != NULL) {
// reload value if ?setvalue=VALUE is present.
if (constraint.empty()) {
cntl->SetFailed(ENOMETHOD, "Require gflag name");
return;
}
if (use_html && cntl->http_request().uri().GetQuery("withform")) {
return set_value_page(cntl, done_guard.release());
}
GFLAGS_NS::CommandLineFlagInfo info;
if (!GFLAGS_NS::GetCommandLineFlagInfo(constraint.c_str(), &info)) {
cntl->SetFailed(ENOMETHOD, "No such gflag");
return;
}
if (!info.has_validator_fn) {
cntl->SetFailed(EPERM, "A reloadable gflag must have validator");
return;
}
if (FLAGS_immutable_flags) {
cntl->SetFailed(EPERM, "Cannot modify `%s' because -immutable_flags is on",
constraint.c_str());
return;
}
if (GFLAGS_NS::SetCommandLineOption(constraint.c_str(),
value_str->c_str()).empty()) {
cntl->SetFailed(EPERM, "Fail to set `%s' to %s",
constraint.c_str(),
(value_str->empty() ? "empty string" : value_str->c_str()));
return;
}
butil::IOBufBuilder os;
os << "Set `" << constraint << "' to " << *value_str;
if (use_html) {
os << "<br><a href='/flags'>[back to flags]</a>";
}
os.move_to(cntl->response_attachment());
return;
}
// Parse query-string which is comma-separated flagnames/wildcards.
std::vector<std::string> wildcards;
std::set<std::string> exact;
if (!constraint.empty()) {
for (butil::StringMultiSplitter sp(constraint.c_str(), ",;"); sp != NULL; ++sp) {
std::string name(sp.field(), sp.length());
if (name.find_first_of("$*") != std::string::npos) {
wildcards.push_back(name);
} else {
exact.insert(name);
}
}
}
// Print header of the table
butil::IOBufBuilder os;
if (use_html) {
os << "<!DOCTYPE html><html><head>\n" << gridtable_style()
<< "<script language=\"javascript\" type=\"text/javascript\" src=\"/js/jquery_min\"></script>\n"
<< TabsHead()
<< "</head><body>";
cntl->server()->PrintTabsBody(os, "flags");
os << "<table class=\"gridtable\" border=\"1\"><tr><th>Name</th><th>Value</th>"
"<th>Description</th><th>Defined At</th></tr>\n";
} else {
os << "Name | Value | Description | Defined At\n"
"---------------------------------------\n";
}
if (!constraint.empty() && wildcards.empty()) {
// Only exact names. We don't have to iterate all flags in this case.
for (std::set<std::string>::iterator it = exact.begin();
it != exact.end(); ++it) {
GFLAGS_NS::CommandLineFlagInfo info;
if (GFLAGS_NS::GetCommandLineFlagInfo(it->c_str(), &info)) {
PrintFlag(os, info, use_html);
os << '\n';
}
}
} else {
// Iterate all flags and filter.
std::vector<GFLAGS_NS::CommandLineFlagInfo> flag_list;
flag_list.reserve(128);
GFLAGS_NS::GetAllFlags(&flag_list);
for (std::vector<GFLAGS_NS::CommandLineFlagInfo>::iterator
it = flag_list.begin(); it != flag_list.end(); ++it) {
if (!constraint.empty() &&
exact.find(it->name) == exact.end() &&
!MatchAnyWildcard(it->name, wildcards)) {
continue;
}
PrintFlag(os, *it, use_html);
os << '\n';
}
}
if (use_html) {
os << "</table></body></html>\n";
}
os.move_to(cntl->response_attachment());
cntl->set_response_compress_type(COMPRESS_TYPE_GZIP);
}
void FlagsService::GetTabInfo(TabInfoList* info_list) const {
TabInfo* info = info_list->add();
info->path = "/flags";
info->tab_name = "flags";
}
} // namespace brpc
<commit_msg>fix the display of gflag default values of builtin<commit_after>// Copyright (c) 2015 Baidu, 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.
// Authors: Ge,Jun (gejun@baidu.com)
#include <ostream>
#include <vector> // std::vector
#include <set>
#include <gflags/gflags.h> // GetAllFlags
// CommandLineFlagInfo
#include "butil/string_printf.h"
#include "butil/string_splitter.h"
#include "brpc/closure_guard.h" // ClosureGuard
#include "brpc/controller.h" // Controller
#include "brpc/errno.pb.h"
#include "brpc/server.h"
#include "brpc/builtin/common.h"
#include "brpc/builtin/flags_service.h"
namespace brpc {
DEFINE_bool(immutable_flags, false, "gflags on /flags page can't be modified");
// Replace some characters with html replacements. If the input string does
// not need to be changed, return its const reference directly, otherwise put
// the replaced string in backing string and return its const reference.
// TODO(gejun): Make this function more general.
static std::string HtmlReplace(const std::string& s) {
std::string b;
size_t last_pos = 0;
while (1) {
size_t new_pos = s.find_first_of("<>&", last_pos);
if (new_pos == std::string::npos) {
if (b.empty()) { // no special characters.
return s;
}
b.append(s.data() + last_pos, s.size() - last_pos);
return b;
}
b.append(s.data() + last_pos, new_pos - last_pos);
switch (s[new_pos]) {
case '<' : b.append("<"); break;
case '>' : b.append(">"); break;
case '&' : b.append("&"); break;
default: b.push_back(s[new_pos]); break;
}
last_pos = new_pos + 1;
}
}
static void PrintFlag(std::ostream& os, const GFLAGS_NS::CommandLineFlagInfo& flag,
bool use_html) {
if (use_html) {
os << "<tr><td>";
}
os << flag.name;
if (flag.has_validator_fn) {
if (use_html) {
os << " (<a href='/flags/" << flag.name
<< "?setvalue&withform'>R</a>)";
} else {
os << " (R)";
}
}
os << (use_html ? "</td><td>" : " | ");
if (!flag.is_default && use_html) {
os << "<span style='color:#FF0000'>";
}
if (!flag.current_value.empty()) {
os << (use_html ? HtmlReplace(flag.current_value)
: flag.current_value);
} else {
os << (use_html ? " " : " ");
}
if (!flag.is_default) {
if (flag.default_value != flag.current_value) {
os << " (default:" << (use_html ?
HtmlReplace(flag.default_value) :
flag.default_value) << ')';
}
if (use_html) {
os << "</span>";
}
}
os << (use_html ? "</td><td>" : " | ") << flag.description
<< (use_html ? "</td><td>" : " | ") << flag.filename;
if (use_html) {
os << "</td></tr>";
}
}
void FlagsService::set_value_page(Controller* cntl,
::google::protobuf::Closure* done) {
ClosureGuard done_guard(done);
const std::string& name = cntl->http_request().unresolved_path();
GFLAGS_NS::CommandLineFlagInfo info;
if (!GFLAGS_NS::GetCommandLineFlagInfo(name.c_str(), &info)) {
cntl->SetFailed(ENOMETHOD, "No such gflag");
return;
}
butil::IOBufBuilder os;
const bool is_string = (info.type == "string");
os << "<!DOCTYPE html><html><body>"
"<form action='' method='get'>"
" Set `" << name << "' from ";
if (is_string) {
os << '"';
}
os << info.current_value;
if (is_string) {
os << '"';
}
os << " to <input name='setvalue' value=''>"
" <button>go</button>"
"</form>"
"</body></html>";
os.move_to(cntl->response_attachment());
}
void FlagsService::default_method(::google::protobuf::RpcController* cntl_base,
const ::brpc::FlagsRequest*,
::brpc::FlagsResponse*,
::google::protobuf::Closure* done) {
ClosureGuard done_guard(done);
Controller *cntl = static_cast<Controller*>(cntl_base);
const std::string* value_str =
cntl->http_request().uri().GetQuery(SETVALUE_STR);
const std::string& constraint = cntl->http_request().unresolved_path();
const bool use_html = UseHTML(cntl->http_request());
cntl->http_response().set_content_type(
use_html ? "text/html" : "text/plain");
if (value_str != NULL) {
// reload value if ?setvalue=VALUE is present.
if (constraint.empty()) {
cntl->SetFailed(ENOMETHOD, "Require gflag name");
return;
}
if (use_html && cntl->http_request().uri().GetQuery("withform")) {
return set_value_page(cntl, done_guard.release());
}
GFLAGS_NS::CommandLineFlagInfo info;
if (!GFLAGS_NS::GetCommandLineFlagInfo(constraint.c_str(), &info)) {
cntl->SetFailed(ENOMETHOD, "No such gflag");
return;
}
if (!info.has_validator_fn) {
cntl->SetFailed(EPERM, "A reloadable gflag must have validator");
return;
}
if (FLAGS_immutable_flags) {
cntl->SetFailed(EPERM, "Cannot modify `%s' because -immutable_flags is on",
constraint.c_str());
return;
}
if (GFLAGS_NS::SetCommandLineOption(constraint.c_str(),
value_str->c_str()).empty()) {
cntl->SetFailed(EPERM, "Fail to set `%s' to %s",
constraint.c_str(),
(value_str->empty() ? "empty string" : value_str->c_str()));
return;
}
butil::IOBufBuilder os;
os << "Set `" << constraint << "' to " << *value_str;
if (use_html) {
os << "<br><a href='/flags'>[back to flags]</a>";
}
os.move_to(cntl->response_attachment());
return;
}
// Parse query-string which is comma-separated flagnames/wildcards.
std::vector<std::string> wildcards;
std::set<std::string> exact;
if (!constraint.empty()) {
for (butil::StringMultiSplitter sp(constraint.c_str(), ",;"); sp != NULL; ++sp) {
std::string name(sp.field(), sp.length());
if (name.find_first_of("$*") != std::string::npos) {
wildcards.push_back(name);
} else {
exact.insert(name);
}
}
}
// Print header of the table
butil::IOBufBuilder os;
if (use_html) {
os << "<!DOCTYPE html><html><head>\n" << gridtable_style()
<< "<script language=\"javascript\" type=\"text/javascript\" src=\"/js/jquery_min\"></script>\n"
<< TabsHead()
<< "</head><body>";
cntl->server()->PrintTabsBody(os, "flags");
os << "<table class=\"gridtable\" border=\"1\"><tr><th>Name</th><th>Value</th>"
"<th>Description</th><th>Defined At</th></tr>\n";
} else {
os << "Name | Value | Description | Defined At\n"
"---------------------------------------\n";
}
if (!constraint.empty() && wildcards.empty()) {
// Only exact names. We don't have to iterate all flags in this case.
for (std::set<std::string>::iterator it = exact.begin();
it != exact.end(); ++it) {
GFLAGS_NS::CommandLineFlagInfo info;
if (GFLAGS_NS::GetCommandLineFlagInfo(it->c_str(), &info)) {
PrintFlag(os, info, use_html);
os << '\n';
}
}
} else {
// Iterate all flags and filter.
std::vector<GFLAGS_NS::CommandLineFlagInfo> flag_list;
flag_list.reserve(128);
GFLAGS_NS::GetAllFlags(&flag_list);
for (std::vector<GFLAGS_NS::CommandLineFlagInfo>::iterator
it = flag_list.begin(); it != flag_list.end(); ++it) {
if (!constraint.empty() &&
exact.find(it->name) == exact.end() &&
!MatchAnyWildcard(it->name, wildcards)) {
continue;
}
PrintFlag(os, *it, use_html);
os << '\n';
}
}
if (use_html) {
os << "</table></body></html>\n";
}
os.move_to(cntl->response_attachment());
cntl->set_response_compress_type(COMPRESS_TYPE_GZIP);
}
void FlagsService::GetTabInfo(TabInfoList* info_list) const {
TabInfo* info = info_list->add();
info->path = "/flags";
info->tab_name = "flags";
}
} // namespace brpc
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief 固定サイズ文字列クラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017, 2020 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <algorithm>
#include <cstring>
#include <iterator>
#include "common/string_utils.hpp"
namespace utils {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 固定サイズ文字列クラス
@param[in] SIZE 文字列サイズ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t SIZE>
class fixed_string {
uint32_t pos_;
char str_[SIZE + 1];
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクタ
@param[in] str 初期設定文字列
*/
//-----------------------------------------------------------------//
fixed_string(const char* str = nullptr) noexcept : pos_(0) {
if(str != nullptr) {
utils::str::strncpy_(str_, str, SIZE);
pos_ = std::strlen(str_);
}
str_[pos_] = 0;
str_[SIZE] = 0;
}
//-----------------------------------------------------------------//
/*!
@brief 格納可能な最大サイズを返す(終端の数を除外)
@return 格納可能な最大サイズ
*/
//-----------------------------------------------------------------//
uint32_t capacity() const noexcept { return SIZE; }
//-----------------------------------------------------------------//
/*!
@brief 現在のサイズを返す
@return 現在のサイズ
*/
//-----------------------------------------------------------------//
uint32_t size() const noexcept { return pos_; }
//-----------------------------------------------------------------//
/*!
@brief 空か調べる
@return 空の場合「true」
*/
//-----------------------------------------------------------------//
bool empty() const noexcept { return pos_ == 0; }
//-----------------------------------------------------------------//
/*!
@brief 文字列をクリア(リセット)
*/
//-----------------------------------------------------------------//
void clear() noexcept {
pos_ = 0;
str_[pos_] = 0;
}
//-----------------------------------------------------------------//
/*!
@brief 末尾の1要素を削除する。
*/
//-----------------------------------------------------------------//
void pop_back() noexcept {
if(pos_ > 0) {
--pos_;
str_[pos_] = 0;
}
}
//-----------------------------------------------------------------//
/*!
@brief 要素を削除する。
@param[in] org 先頭位置
@param[in] num 個数
@return 自分
*/
//-----------------------------------------------------------------//
fixed_string& erase(uint32_t org, uint32_t num) noexcept {
if(org < pos_ && (org + num) <= pos_) {
for(uint32_t i = 0; i < (pos_ - num); ++i) {
str_[org + i] = str_[org + i + num];
}
pos_ -= num;
str_[pos_] = 0;
}
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief 配列の先頭
@return 配列の先頭
*/
//-----------------------------------------------------------------//
const char* begin() const noexcept { return &str_[0]; }
//-----------------------------------------------------------------//
/*!
@brief 配列の先頭
@return 配列の先頭
*/
//-----------------------------------------------------------------//
char* begin() noexcept { return &str_[0]; }
//-----------------------------------------------------------------//
/*!
@brief 配列の終端
@return 配列の終端
*/
//-----------------------------------------------------------------//
const char* end() const noexcept { return &str_[pos_]; }
//-----------------------------------------------------------------//
/*!
@brief 配列の終端
@return 配列の終端
*/
//-----------------------------------------------------------------//
char* end() noexcept { return &str_[pos_]; }
//-----------------------------------------------------------------//
/*!
@brief 末尾要素への参照を取得する。
@return 末尾要素への参照
*/
//-----------------------------------------------------------------//
char& back() noexcept {
auto pos = pos_;
if(pos > 0) --pos;
return str_[pos];
}
//-----------------------------------------------------------------//
/*!
@brief 末尾要素への参照を取得する。
@return 末尾要素への参照
*/
//-----------------------------------------------------------------//
const char& back() const noexcept {
auto pos = pos_;
if(pos > 0) --pos;
return str_[pos];
}
//-----------------------------------------------------------------//
/*!
@brief 文字列を返す
@return 文字列
*/
//-----------------------------------------------------------------//
const char* c_str() const noexcept { return str_; }
//-----------------------------------------------------------------//
/*!
@brief 交換
@param[in] src ソース
@return 自分
*/
//-----------------------------------------------------------------//
void swap(fixed_string& src) noexcept {
std::swap(src.str_, str_);
std::swap(src.pos_, pos_);
}
//-----------------------------------------------------------------//
/*!
@brief 代入
@param[in] src ソース
@return 自分
*/
//-----------------------------------------------------------------//
fixed_string& operator = (const char* src) noexcept {
utils::str::strncpy_(str_, src, SIZE);
pos_ = std::strlen(str_);
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief 代入
@param[in] src ソース
@return 自分
*/
//-----------------------------------------------------------------//
fixed_string& operator = (const fixed_string& src) noexcept {
utils::str::strncpy_(str_, src.c_str(), SIZE);
pos_ = src.pos_;
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief 文字を追加
@param[in] ch 文字
@return 自分
*/
//-----------------------------------------------------------------//
fixed_string& operator += (char ch) noexcept {
if(pos_ < SIZE) {
str_[pos_] = ch;
++pos_;
str_[pos_] = 0;
}
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief 文字列を追加
@param[in] str 文字列
@return 自分
*/
//-----------------------------------------------------------------//
fixed_string& operator += (const char* str) noexcept {
if(str == nullptr) {
return *this;
}
uint32_t l = std::strlen(str);
if((pos_ + l) < SIZE) {
std::strcpy(&str_[pos_], str);
pos_ += l;
} else { // バッファが許す範囲でコピー
l = SIZE - pos_;
utils::str::strncpy_(&str_[pos_], str, l);
pos_ = SIZE;
}
str_[pos_] = 0;
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief 文字参照 @n
※範囲外ではテンポラリを返す(例外を投げない)
@param[in] pos 配列位置
@return 文字
*/
//-----------------------------------------------------------------//
char& operator [] (uint32_t pos) noexcept {
if(pos >= SIZE) {
static char tmp = 0;
return tmp;
}
return str_[pos];
}
//-----------------------------------------------------------------//
/*!
@brief 文字参照 const @n
※範囲外ではテンポラリを返す(例外を投げない)
@param[in] pos 配列位置
@return 文字
*/
//-----------------------------------------------------------------//
const char& operator [] (uint32_t pos) const noexcept {
if(pos >= SIZE) {
static char tmp = 0;
return tmp;
}
return str_[pos];
}
//-----------------------------------------------------------------//
/*!
@brief クラス一致比較
@param[in] th 文字列クラス
@return 同じなら「true」
*/
//-----------------------------------------------------------------//
int cmp(const fixed_string& th) const noexcept {
return std::strcmp(c_str(), th.c_str());
}
//-----------------------------------------------------------------//
/*!
@brief クラス一致比較(オペレーター)
@param[in] th 文字列クラス
@return 同じなら「true」
*/
//-----------------------------------------------------------------//
bool operator == (const fixed_string& th) const noexcept {
return std::strcmp(c_str(), th.c_str()) == 0;
}
//-----------------------------------------------------------------//
/*!
@brief クラス、不一致比較(オペレーター)
@param[in] th 文字列クラス
@return 同じなら「true」
*/
//-----------------------------------------------------------------//
bool operator != (const fixed_string& th) const noexcept {
return std::strcmp(c_str(), th.c_str()) != 0;
}
//-----------------------------------------------------------------//
/*!
@brief クラス大小比較(オペレーター)
@param[in] th 文字列クラス
@return 大小なら「true」
*/
//-----------------------------------------------------------------//
bool operator > (const fixed_string& th) const noexcept {
return std::strcmp(c_str(), th.c_str()) > 0;
}
//-----------------------------------------------------------------//
/*!
@brief クラス小大比較(オペレーター)
@param[in] th 文字列クラス
@return 小大なら「true」
*/
//-----------------------------------------------------------------//
bool operator < (const fixed_string& th) const noexcept {
return std::strcmp(c_str(), th.c_str()) < 0;
}
//-----------------------------------------------------------------//
/*!
@brief クラス大小一致比較(オペレーター)
@param[in] th 文字列
@return 大小一致なら「true」
*/
//-----------------------------------------------------------------//
bool operator >= (const fixed_string& th) const noexcept {
return std::strcmp(c_str(), th.c_str()) >= 0;
}
//-----------------------------------------------------------------//
/*!
@brief クラス小大一致比較(オペレーター)
@param[in] th 文字列クラス
@return 小大一致なら「true」
*/
//-----------------------------------------------------------------//
bool operator <= (const fixed_string& th) const noexcept {
return std::strcmp(c_str(), th.c_str()) <= 0;
}
};
typedef fixed_string<16> STR16;
typedef fixed_string<32> STR32;
typedef fixed_string<64> STR64;
typedef fixed_string<128> STR128;
typedef fixed_string<256> STR256;
}
<commit_msg>Update: cleanup<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief 固定サイズ文字列クラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017, 2022 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <algorithm>
#include <cstring>
#include <iterator>
#include "common/string_utils.hpp"
namespace utils {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 固定サイズ文字列クラス
@param[in] SIZE 文字列サイズ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t SIZE>
class fixed_string {
uint32_t pos_;
char str_[SIZE + 1];
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクタ
@param[in] str 初期設定文字列
*/
//-----------------------------------------------------------------//
fixed_string(const char* str = nullptr) noexcept : pos_(0) {
if(str != nullptr) {
utils::str::strncpy_(str_, str, SIZE);
pos_ = std::strlen(str_);
}
str_[pos_] = 0;
str_[SIZE] = 0;
}
//-----------------------------------------------------------------//
/*!
@brief 格納可能な最大サイズを返す(終端の数を除外)
@return 格納可能な最大サイズ
*/
//-----------------------------------------------------------------//
uint32_t capacity() const noexcept { return SIZE; }
//-----------------------------------------------------------------//
/*!
@brief 現在のサイズを返す
@return 現在のサイズ
*/
//-----------------------------------------------------------------//
uint32_t size() const noexcept { return pos_; }
//-----------------------------------------------------------------//
/*!
@brief 空か調べる
@return 空の場合「true」
*/
//-----------------------------------------------------------------//
bool empty() const noexcept { return pos_ == 0; }
//-----------------------------------------------------------------//
/*!
@brief 文字列をクリア(リセット)
*/
//-----------------------------------------------------------------//
void clear() noexcept {
pos_ = 0;
str_[pos_] = 0;
}
//-----------------------------------------------------------------//
/*!
@brief 末尾の1要素を削除する。
*/
//-----------------------------------------------------------------//
void pop_back() noexcept {
if(pos_ > 0) {
--pos_;
str_[pos_] = 0;
}
}
//-----------------------------------------------------------------//
/*!
@brief 要素を削除する。
@param[in] org 先頭位置
@param[in] num 個数
@return 自分
*/
//-----------------------------------------------------------------//
fixed_string& erase(uint32_t org, uint32_t num) noexcept {
if(org < pos_ && (org + num) <= pos_) {
for(uint32_t i = 0; i < (pos_ - num); ++i) {
str_[org + i] = str_[org + i + num];
}
pos_ -= num;
str_[pos_] = 0;
}
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief 配列の先頭
@return 配列の先頭
*/
//-----------------------------------------------------------------//
const char* begin() const noexcept { return &str_[0]; }
//-----------------------------------------------------------------//
/*!
@brief 配列の先頭
@return 配列の先頭
*/
//-----------------------------------------------------------------//
char* begin() noexcept { return &str_[0]; }
//-----------------------------------------------------------------//
/*!
@brief 配列の終端
@return 配列の終端
*/
//-----------------------------------------------------------------//
const char* end() const noexcept { return &str_[pos_]; }
//-----------------------------------------------------------------//
/*!
@brief 配列の終端
@return 配列の終端
*/
//-----------------------------------------------------------------//
char* end() noexcept { return &str_[pos_]; }
//-----------------------------------------------------------------//
/*!
@brief 末尾要素への参照を取得する。
@return 末尾要素への参照
*/
//-----------------------------------------------------------------//
char& back() noexcept {
auto pos = pos_;
if(pos > 0) --pos;
return str_[pos];
}
//-----------------------------------------------------------------//
/*!
@brief 末尾要素への参照を取得する。
@return 末尾要素への参照
*/
//-----------------------------------------------------------------//
const char& back() const noexcept {
auto pos = pos_;
if(pos > 0) --pos;
return str_[pos];
}
//-----------------------------------------------------------------//
/*!
@brief 文字列を返す
@return 文字列
*/
//-----------------------------------------------------------------//
const char* c_str() const noexcept { return str_; }
//-----------------------------------------------------------------//
/*!
@brief 交換
@param[in] src ソース
*/
//-----------------------------------------------------------------//
void swap(fixed_string& src) noexcept {
std::swap(src.str_, str_);
std::swap(src.pos_, pos_);
}
//-----------------------------------------------------------------//
/*!
@brief 代入
@param[in] src ソース
@return 自分
*/
//-----------------------------------------------------------------//
fixed_string& operator = (const char* src) noexcept {
utils::str::strncpy_(str_, src, SIZE);
pos_ = std::strlen(str_);
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief 代入
@param[in] src ソース
@return 自分
*/
//-----------------------------------------------------------------//
fixed_string& operator = (const fixed_string& src) noexcept {
utils::str::strncpy_(str_, src.c_str(), SIZE);
pos_ = src.pos_;
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief 文字を追加
@param[in] ch 文字
@return 自分
*/
//-----------------------------------------------------------------//
fixed_string& operator += (char ch) noexcept {
if(pos_ < SIZE) {
str_[pos_] = ch;
++pos_;
str_[pos_] = 0;
}
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief 文字列を追加
@param[in] str 文字列
@return 自分
*/
//-----------------------------------------------------------------//
fixed_string& operator += (const char* str) noexcept {
if(str == nullptr) {
return *this;
}
uint32_t l = std::strlen(str);
if((pos_ + l) < SIZE) {
std::strcpy(&str_[pos_], str);
pos_ += l;
} else { // バッファが許す範囲でコピー
l = SIZE - pos_;
utils::str::strncpy_(&str_[pos_], str, l);
pos_ = SIZE;
}
str_[pos_] = 0;
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief 文字参照 @n
※範囲外ではテンポラリを返す(例外を投げない)
@param[in] pos 配列位置
@return 文字
*/
//-----------------------------------------------------------------//
char& operator [] (uint32_t pos) noexcept {
if(pos >= SIZE) {
static char tmp = 0;
return tmp;
}
return str_[pos];
}
//-----------------------------------------------------------------//
/*!
@brief 文字参照 const @n
※範囲外ではテンポラリを返す(例外を投げない)
@param[in] pos 配列位置
@return 文字
*/
//-----------------------------------------------------------------//
const char& operator [] (uint32_t pos) const noexcept {
if(pos >= SIZE) {
static char tmp = 0;
return tmp;
}
return str_[pos];
}
//-----------------------------------------------------------------//
/*!
@brief クラス一致比較
@param[in] th 文字列クラス
@return 同じなら「true」
*/
//-----------------------------------------------------------------//
int cmp(const fixed_string& th) const noexcept {
return std::strcmp(c_str(), th.c_str());
}
//-----------------------------------------------------------------//
/*!
@brief クラス一致比較(オペレーター)
@param[in] th 文字列クラス
@return 同じなら「true」
*/
//-----------------------------------------------------------------//
bool operator == (const fixed_string& th) const noexcept {
return std::strcmp(c_str(), th.c_str()) == 0;
}
//-----------------------------------------------------------------//
/*!
@brief クラス、不一致比較(オペレーター)
@param[in] th 文字列クラス
@return 同じなら「true」
*/
//-----------------------------------------------------------------//
bool operator != (const fixed_string& th) const noexcept {
return std::strcmp(c_str(), th.c_str()) != 0;
}
//-----------------------------------------------------------------//
/*!
@brief クラス大小比較(オペレーター)
@param[in] th 文字列クラス
@return 大小なら「true」
*/
//-----------------------------------------------------------------//
bool operator > (const fixed_string& th) const noexcept {
return std::strcmp(c_str(), th.c_str()) > 0;
}
//-----------------------------------------------------------------//
/*!
@brief クラス小大比較(オペレーター)
@param[in] th 文字列クラス
@return 小大なら「true」
*/
//-----------------------------------------------------------------//
bool operator < (const fixed_string& th) const noexcept {
return std::strcmp(c_str(), th.c_str()) < 0;
}
//-----------------------------------------------------------------//
/*!
@brief クラス大小一致比較(オペレーター)
@param[in] th 文字列
@return 大小一致なら「true」
*/
//-----------------------------------------------------------------//
bool operator >= (const fixed_string& th) const noexcept {
return std::strcmp(c_str(), th.c_str()) >= 0;
}
//-----------------------------------------------------------------//
/*!
@brief クラス小大一致比較(オペレーター)
@param[in] th 文字列クラス
@return 小大一致なら「true」
*/
//-----------------------------------------------------------------//
bool operator <= (const fixed_string& th) const noexcept {
return std::strcmp(c_str(), th.c_str()) <= 0;
}
};
typedef fixed_string<16> STR16;
typedef fixed_string<32> STR32;
typedef fixed_string<64> STR64;
typedef fixed_string<128> STR128;
typedef fixed_string<256> STR256;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015 Semi Essessi
#include "Image.h"
bool Image::LoadFromCompressedVoyagerData( const void* const /*pFileData*/ )
{
return false;
}
<commit_msg>unfinished broken data loader (some mad pointer thing i need to work out from the reference code and docs)<commit_after>// Copyright (c) 2015 Semi Essessi
#include "Image.h"
#include <cstdlib>
#include <cstring>
void AdvancePastNextChar( const unsigned char*& pucByteStream, const char cChar )
{
while( *pucByteStream != static_cast< unsigned char >( cChar ) )
{
++pucByteStream;
}
++pucByteStream;
}
void AdvancePastNextNull( const unsigned char*& pucByteStream )
{
AdvancePastNextChar( pucByteStream, 0 );
}
int ExtractPseudoPointer( const unsigned char*& pucByteStream, const char* const szName )
{
const bool bHistogramCorrect =
strncmp( reinterpret_cast< const char* >( pucByteStream ),
szName,
strlen( szName ) ) == 0;
if( !bHistogramCorrect )
{
return -1;
}
AdvancePastNextChar( pucByteStream, '=' );
while( static_cast< const char >( *pucByteStream ) == ' ' )
{
++pucByteStream;
}
return atoi( reinterpret_cast< const char* >( pucByteStream ) );
}
// SE - TODO: length so that this is super safe?
bool Image::LoadFromCompressedVoyagerData( const void* const pFileData )
{
const unsigned char* pucByteStream = reinterpret_cast< const unsigned char* >( pFileData );
// SE - this 'compressed' data format is a big wasteful pile of text with some
// huffman tree inside of it somewhere...
int iPsuedoPointer = 1; // the file format uses "pointers" to the data, which I assume are indices of rows
// there seems to be some header - followed by null. skip it.
AdvancePastNextNull( pucByteStream );
++iPsuedoPointer;
// some SFDU_LABEL
AdvancePastNextNull( pucByteStream );
++iPsuedoPointer;
// some stray quote
AdvancePastNextNull( pucByteStream );
++iPsuedoPointer;
// some file format and length thing
AdvancePastNextNull( pucByteStream );
++iPsuedoPointer;
// some record type
AdvancePastNextNull( pucByteStream );
++iPsuedoPointer;
// record bytes, should be 836
static const int iRecordBytes = 836;
AdvancePastNextNull( pucByteStream );
++iPsuedoPointer;
// file record count, should be 860
static const int iRecordCount = 860;
AdvancePastNextNull( pucByteStream );
++iPsuedoPointer;
// label records.
AdvancePastNextNull( pucByteStream );
++iPsuedoPointer;
// some stray A
AdvancePastNextNull( pucByteStream );
++iPsuedoPointer;
// some comment telling us about pointer things
AdvancePastNextNull( pucByteStream );
++iPsuedoPointer;
// some stray %
AdvancePastNextNull( pucByteStream );
++iPsuedoPointer;
// some image histogram pointer (seems to be 55)
const int iImageHistogramPointer = ExtractPseudoPointer( pucByteStream, "^IMAGE_HISTOGRAM" );
AdvancePastNextNull( pucByteStream );
AdvancePastNextNull( pucByteStream );
iPsuedoPointer += 2;
if( iImageHistogramPointer == -1 )
{
return false;
}
// some encoding histogram pointer (57?)
const int iEncodingHistogramPointer = ExtractPseudoPointer( pucByteStream, "^ENCODING_HISTOGRAM" );
AdvancePastNextNull( pucByteStream );
AdvancePastNextNull( pucByteStream );
iPsuedoPointer += 2;
if( iEncodingHistogramPointer == -1 )
{
return false;
}
// engineering table (60?)
const int iEngineeringTablePointer = ExtractPseudoPointer( pucByteStream, "^ENGINEERING_TABLE" );
AdvancePastNextNull( pucByteStream );
AdvancePastNextNull( pucByteStream );
iPsuedoPointer += 2;
if( iEngineeringTablePointer == -1 )
{
return false;
}
// image data (61?)
const int iImagePointer = ExtractPseudoPointer( pucByteStream, "^IMAGE" );
AdvancePastNextNull( pucByteStream );
AdvancePastNextNull( pucByteStream );
iPsuedoPointer += 2;
if( iImagePointer == -1 )
{
return false;
}
int iSkipCount = iImageHistogramPointer;
for( int i = 0; i < iSkipCount; ++i )
{
AdvancePastNextNull( pucByteStream );
}
return false;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2010 Arjen Hiemstra <>
*
* 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 "projectdock.h"
#include "core/debughelper.h"
#include "engine/game.h"
#include "engine/gameobject.h"
#include "engine/scene.h"
#include "models/projectmodel.h"
#include <QtGui/QTreeView>
#include <QtGui/QMenu>
#include <KDebug>
#include <KInputDialog>
#include <KMessageBox>
#include <KLocalizedString>
using namespace GluonCreator;
class ProjectDock::ProjectDockPrivate
{
public:
ProjectDockPrivate(ProjectDock * parent)
{
q = parent;
view = 0;
}
ProjectDock * q;
ProjectModel* model;
QTreeView* view;
QModelIndex currentContextIndex;
QList<QAction*> menuForObject(QModelIndex index);
QList<QAction*> currentContextMenu;
};
QList< QAction* > ProjectDock::ProjectDockPrivate::menuForObject(QModelIndex index)
{
QList<QAction*> menuItems;
GluonCore::GluonObject * object = static_cast<GluonCore::GluonObject*>(index.internalPointer());
if (object)
{
const QMetaObject * mobj = object->metaObject();
if (mobj)
{
currentContextIndex = index;
QAction * action;
if (object->inherits("GluonEngine::Asset"))
{
action = new QAction("Asset actions go here", this->q);
action->setEnabled(false);
menuItems.append(action);
}
else
{
action = new QAction("New Folder...", this->q);
connect(action, SIGNAL(triggered()), q, SLOT(newSubMenuTriggered()));
menuItems.append(action);
}
action = new QAction(QString("Delete \"%1\"...").arg(object->name()), this->q);
connect(action, SIGNAL(triggered()), q, SLOT(deleteActionTriggered()));
menuItems.append(action);
}
}
currentContextMenu = QList<QAction*>(menuItems);
return menuItems;
}
ProjectDock::ProjectDock(const QString& title, QWidget* parent, Qt::WindowFlags flags): Dock(title, parent, flags)
{
setObjectName("ProjectDock");
d = new ProjectDockPrivate(this);
d->model = new ProjectModel(this);
d->view = new QTreeView(this);
d->view->setModel(d->model);
d->view->setAcceptDrops(true);
d->view->setContextMenuPolicy(Qt::CustomContextMenu);
connect(d->view, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showContextMenuRequested(const QPoint&)));
d->model->setProject(GluonEngine::Game::instance()->gameProject());
connect(GluonEngine::Game::instance(), SIGNAL(currentProjectChanged(GluonEngine::GameProject*)), d->model, SLOT(setProject(GluonEngine::GameProject*)));
connect(d->view, SIGNAL(activated(QModelIndex)), this, SLOT(activated(QModelIndex)));
setWidget(d->view);
}
ProjectDock::~ProjectDock()
{
delete d;
}
QAbstractItemModel* ProjectDock::model()
{
return d->model;
}
QAbstractItemView* ProjectDock::view()
{
return d->view;
}
void ProjectDock::setSelection(GluonCore::GluonObject* obj)
{
Q_UNUSED(obj)
}
void ProjectDock::activated(QModelIndex index)
{
if (!index.isValid())
{
return;
}
QObject* obj = static_cast<QObject*>(index.internalPointer());
if (!obj)
{
return;
}
GluonEngine::Scene* scene = qobject_cast<GluonEngine::Scene*>(obj);
if (scene)
{
if (GluonEngine::Game::instance()->currentScene() != scene)
{
GluonEngine::Game::instance()->setCurrentScene(scene);
GluonEngine::Game::instance()->initializeAll();
GluonEngine::Game::instance()->drawAll();
}
}
}
void ProjectDock::showContextMenuRequested(const QPoint& pos)
{
QModelIndex index = d->view->indexAt(pos);
if (index.isValid())
{
QMenu menu(static_cast<GluonCore::GluonObject*>(index.internalPointer())->name(), this);
menu.addActions(d->menuForObject(index));
menu.exec(d->view->mapToGlobal(pos));
connect(&menu, SIGNAL(aboutToHide()), this, SLOT(contextMenuHiding()));
}
}
void ProjectDock::contextMenuHiding()
{
d->currentContextIndex = QModelIndex();
qDeleteAll(d->currentContextMenu);
}
void ProjectDock::deleteActionTriggered()
{
DEBUG_FUNC_NAME
if (d->currentContextIndex.isValid())
{
GluonCore::GluonObject * object = static_cast<GluonCore::GluonObject*>(d->currentContextIndex.internalPointer());
DEBUG_TEXT(QString("Requested deletion of %1").arg(object->fullyQualifiedName()));
if (KMessageBox::questionYesNo(this, tr("Please confirm that you wish to delete the object %1. This will delete both this item and all its children!").arg(object->name()), tr("Really Delete?")) == KMessageBox::Yes)
{
d->view->selectionModel()->select(d->currentContextIndex.parent(), QItemSelectionModel::ClearAndSelect);
d->view->collapse(d->currentContextIndex.parent());
d->model->removeRows(d->currentContextIndex.row(), 1, d->currentContextIndex.parent());
}
}
}
void ProjectDock::newSubMenuTriggered()
{
DEBUG_FUNC_NAME
if (d->currentContextIndex.isValid())
{
GluonCore::GluonObject * object = static_cast<GluonCore::GluonObject*>(d->currentContextIndex.internalPointer());
DEBUG_TEXT(QString("Requested a new submenu under %1").arg(object->fullyQualifiedName()));
QString theName(KInputDialog::getText(i18n("Enter Name"), i18n("Please enter the name of the new folder in the text box below:"), i18n("New Folder"), 0, this));
if (!theName.isEmpty())
new GluonCore::GluonObject(theName, object);
}
}
<commit_msg>Launch files in an external program when you activate an item which is not a scene<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2010 Arjen Hiemstra <>
*
* 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 "projectdock.h"
#include "core/debughelper.h"
#include "engine/game.h"
#include "engine/gameobject.h"
#include "engine/scene.h"
#include "models/projectmodel.h"
#include "engine/gameproject.h"
#include <QtGui/QTreeView>
#include <QtGui/QMenu>
#include <KDebug>
#include <KInputDialog>
#include <KMessageBox>
#include <KLocalizedString>
#include <QFile>
#include <QFileInfo>
#include <KRun>
using namespace GluonCreator;
class ProjectDock::ProjectDockPrivate
{
public:
ProjectDockPrivate(ProjectDock * parent)
{
q = parent;
view = 0;
}
ProjectDock * q;
ProjectModel* model;
QTreeView* view;
QModelIndex currentContextIndex;
QList<QAction*> menuForObject(QModelIndex index);
QList<QAction*> currentContextMenu;
};
QList< QAction* > ProjectDock::ProjectDockPrivate::menuForObject(QModelIndex index)
{
QList<QAction*> menuItems;
GluonCore::GluonObject * object = static_cast<GluonCore::GluonObject*>(index.internalPointer());
if (object)
{
const QMetaObject * mobj = object->metaObject();
if (mobj)
{
currentContextIndex = index;
QAction * action;
if (object->inherits("GluonEngine::Asset"))
{
action = new QAction("Asset actions go here", this->q);
action->setEnabled(false);
menuItems.append(action);
}
else
{
action = new QAction("New Folder...", this->q);
connect(action, SIGNAL(triggered()), q, SLOT(newSubMenuTriggered()));
menuItems.append(action);
}
action = new QAction(QString("Delete \"%1\"...").arg(object->name()), this->q);
connect(action, SIGNAL(triggered()), q, SLOT(deleteActionTriggered()));
menuItems.append(action);
}
}
currentContextMenu = QList<QAction*>(menuItems);
return menuItems;
}
ProjectDock::ProjectDock(const QString& title, QWidget* parent, Qt::WindowFlags flags): Dock(title, parent, flags)
{
setObjectName("ProjectDock");
d = new ProjectDockPrivate(this);
d->model = new ProjectModel(this);
d->view = new QTreeView(this);
d->view->setModel(d->model);
d->view->setAcceptDrops(true);
d->view->setContextMenuPolicy(Qt::CustomContextMenu);
connect(d->view, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showContextMenuRequested(const QPoint&)));
d->model->setProject(GluonEngine::Game::instance()->gameProject());
connect(GluonEngine::Game::instance(), SIGNAL(currentProjectChanged(GluonEngine::GameProject*)), d->model, SLOT(setProject(GluonEngine::GameProject*)));
connect(d->view, SIGNAL(activated(QModelIndex)), this, SLOT(activated(QModelIndex)));
setWidget(d->view);
}
ProjectDock::~ProjectDock()
{
delete d;
}
QAbstractItemModel* ProjectDock::model()
{
return d->model;
}
QAbstractItemView* ProjectDock::view()
{
return d->view;
}
void ProjectDock::setSelection(GluonCore::GluonObject* obj)
{
Q_UNUSED(obj)
}
void ProjectDock::activated(QModelIndex index)
{
if (!index.isValid())
{
return;
}
QObject* obj = static_cast<QObject*>(index.internalPointer());
if (!obj)
{
return;
}
GluonEngine::Scene* scene = qobject_cast<GluonEngine::Scene*>(obj);
GluonEngine::Asset* asset = qobject_cast<GluonEngine::Asset*>(obj);
// Scene's a special asset, so we check for that first
if (scene)
{
if (GluonEngine::Game::instance()->currentScene() != scene)
{
GluonEngine::Game::instance()->setCurrentScene(scene);
GluonEngine::Game::instance()->initializeAll();
GluonEngine::Game::instance()->drawAll();
}
}
else if(asset)
{
QString filename = QUrl(QFileInfo(GluonEngine::Game::instance()->gameProject()->filename().toLocalFile()).canonicalPath() + '/' + asset->file().toLocalFile()).toLocalFile();
if(QFile::exists(filename))
{
KRun* runner = new KRun(filename, this);
Q_UNUSED(runner);
}
}
}
void ProjectDock::showContextMenuRequested(const QPoint& pos)
{
QModelIndex index = d->view->indexAt(pos);
if (index.isValid())
{
QMenu menu(static_cast<GluonCore::GluonObject*>(index.internalPointer())->name(), this);
menu.addActions(d->menuForObject(index));
menu.exec(d->view->mapToGlobal(pos));
connect(&menu, SIGNAL(aboutToHide()), this, SLOT(contextMenuHiding()));
}
}
void ProjectDock::contextMenuHiding()
{
d->currentContextIndex = QModelIndex();
qDeleteAll(d->currentContextMenu);
}
void ProjectDock::deleteActionTriggered()
{
DEBUG_FUNC_NAME
if (d->currentContextIndex.isValid())
{
GluonCore::GluonObject * object = static_cast<GluonCore::GluonObject*>(d->currentContextIndex.internalPointer());
DEBUG_TEXT(QString("Requested deletion of %1").arg(object->fullyQualifiedName()));
if (KMessageBox::questionYesNo(this, tr("Please confirm that you wish to delete the object %1. This will delete both this item and all its children!").arg(object->name()), tr("Really Delete?")) == KMessageBox::Yes)
{
d->view->selectionModel()->select(d->currentContextIndex.parent(), QItemSelectionModel::ClearAndSelect);
d->view->collapse(d->currentContextIndex.parent());
d->model->removeRows(d->currentContextIndex.row(), 1, d->currentContextIndex.parent());
}
}
}
void ProjectDock::newSubMenuTriggered()
{
DEBUG_FUNC_NAME
if (d->currentContextIndex.isValid())
{
GluonCore::GluonObject * object = static_cast<GluonCore::GluonObject*>(d->currentContextIndex.internalPointer());
DEBUG_TEXT(QString("Requested a new submenu under %1").arg(object->fullyQualifiedName()));
QString theName(KInputDialog::getText(i18n("Enter Name"), i18n("Please enter the name of the new folder in the text box below:"), i18n("New Folder"), 0, this));
if (!theName.isEmpty())
new GluonCore::GluonObject(theName, object);
}
}
<|endoftext|> |
<commit_before>//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code to emit Objective-C code as LLVM code.
//
//===----------------------------------------------------------------------===//
#include "CGObjCRuntime.h"
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclObjC.h"
#include "llvm/ADT/STLExtras.h"
using namespace clang;
using namespace CodeGen;
/// Emits an instance of NSConstantString representing the object.
llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E) {
std::string String(E->getString()->getStrData(), E->getString()->getByteLength());
llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(String);
// FIXME: This bitcast should just be made an invariant on the Runtime.
return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
}
/// Emit a selector.
llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
// Untyped selector.
// Note that this implementation allows for non-constant strings to be passed
// as arguments to @selector(). Currently, the only thing preventing this
// behaviour is the type checking in the front end.
return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
}
llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
// FIXME: This should pass the Decl not the name.
return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
}
RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E) {
// Only the lookup mechanism and first two arguments of the method
// implementation vary between runtimes. We can get the receiver and
// arguments in generic code.
CGObjCRuntime &Runtime = CGM.getObjCRuntime();
const Expr *ReceiverExpr = E->getReceiver();
bool isSuperMessage = false;
bool isClassMessage = false;
// Find the receiver
llvm::Value *Receiver;
if (!ReceiverExpr) {
const ObjCInterfaceDecl *OID = E->getClassInfo().first;
// Very special case, super send in class method. The receiver is
// self (the class object) and the send uses super semantics.
if (!OID) {
assert(!strcmp(E->getClassName()->getName(), "super") &&
"Unexpected missing class interface in message send.");
isSuperMessage = true;
Receiver = LoadObjCSelf();
} else {
Receiver = Runtime.GetClass(Builder, OID);
}
isClassMessage = true;
} else if (const PredefinedExpr *PDE =
dyn_cast<PredefinedExpr>(E->getReceiver())) {
assert(PDE->getIdentType() == PredefinedExpr::ObjCSuper);
isSuperMessage = true;
Receiver = LoadObjCSelf();
} else {
Receiver = EmitScalarExpr(E->getReceiver());
}
CallArgList Args;
for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
i != e; ++i)
EmitCallArg(*i, Args);
if (isSuperMessage) {
// super is only valid in an Objective-C method
const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
return Runtime.GenerateMessageSendSuper(*this, E->getType(),
E->getSelector(),
OMD->getClassInterface(),
Receiver,
isClassMessage,
Args);
}
return Runtime.GenerateMessageSend(*this, E->getType(), E->getSelector(),
Receiver, isClassMessage, Args);
}
/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
/// the LLVM function and sets the other context used by
/// CodeGenFunction.
// FIXME: This should really be merged with GenerateCode.
void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD) {
CurFn = CGM.getObjCRuntime().GenerateMethod(OMD);
llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", CurFn);
// Create a marker to make it easy to insert allocas into the entryblock
// later. Don't create this with the builder, because we don't want it
// folded.
llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
EntryBB);
FnRetTy = OMD->getResultType();
CurFuncDecl = OMD;
Builder.SetInsertPoint(EntryBB);
// Emit allocs for param decls. Give the LLVM Argument nodes names.
llvm::Function::arg_iterator AI = CurFn->arg_begin();
// Name the struct return argument.
if (hasAggregateLLVMType(OMD->getResultType())) {
AI->setName("agg.result");
++AI;
}
// Add implicit parameters to the decl map.
EmitParmDecl(*OMD->getSelfDecl(), AI);
++AI;
EmitParmDecl(*OMD->getCmdDecl(), AI);
++AI;
for (unsigned i = 0, e = OMD->getNumParams(); i != e; ++i, ++AI) {
assert(AI != CurFn->arg_end() && "Argument mismatch!");
EmitParmDecl(*OMD->getParamDecl(i), AI);
}
assert(AI == CurFn->arg_end() && "Argument mismatch");
}
/// Generate an Objective-C method. An Objective-C method is a C function with
/// its pointer, name, and types registered in the class struture.
void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
StartObjCMethod(OMD);
EmitStmt(OMD->getBody());
const CompoundStmt *S = dyn_cast<CompoundStmt>(OMD->getBody());
if (S) {
FinishFunction(S->getRBracLoc());
} else {
FinishFunction();
}
}
// FIXME: I wasn't sure about the synthesis approach. If we end up
// generating an AST for the whole body we can just fall back to
// having a GenerateFunction which takes the body Stmt.
/// GenerateObjCGetter - Generate an Objective-C property getter
/// function. The given Decl must be either an ObjCCategoryImplDecl
/// or an ObjCImplementationDecl.
void CodeGenFunction::GenerateObjCGetter(const ObjCPropertyImplDecl *PID) {
const ObjCPropertyDecl *PD = PID->getPropertyDecl();
ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
assert(OMD && "Invalid call to generate getter (empty method)");
// FIXME: This is rather murky, we create this here since they will
// not have been created by Sema for us.
OMD->createImplicitParams(getContext());
StartObjCMethod(OMD);
// FIXME: What about nonatomic?
SourceLocation Loc = PD->getLocation();
ValueDecl *Self = OMD->getSelfDecl();
ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
DeclRefExpr Base(Self, Self->getType(), Loc);
ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base,
true, true);
ReturnStmt Return(Loc, &IvarRef);
EmitStmt(&Return);
FinishFunction();
}
/// GenerateObjCSetter - Generate an Objective-C property setter
/// function. The given Decl must be either an ObjCCategoryImplDecl
/// or an ObjCImplementationDecl.
void CodeGenFunction::GenerateObjCSetter(const ObjCPropertyImplDecl *PID) {
const ObjCPropertyDecl *PD = PID->getPropertyDecl();
ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
assert(OMD && "Invalid call to generate setter (empty method)");
// FIXME: This is rather murky, we create this here since they will
// not have been created by Sema for us.
OMD->createImplicitParams(getContext());
StartObjCMethod(OMD);
switch (PD->getSetterKind()) {
case ObjCPropertyDecl::Assign: break;
case ObjCPropertyDecl::Copy:
CGM.ErrorUnsupported(PID, "Obj-C setter with 'copy'");
break;
case ObjCPropertyDecl::Retain:
CGM.ErrorUnsupported(PID, "Obj-C setter with 'retain'");
break;
}
// FIXME: What about nonatomic?
SourceLocation Loc = PD->getLocation();
ValueDecl *Self = OMD->getSelfDecl();
ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
DeclRefExpr Base(Self, Self->getType(), Loc);
ParmVarDecl *ArgDecl = OMD->getParamDecl(0);
DeclRefExpr Arg(ArgDecl, ArgDecl->getType(), Loc);
ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base,
true, true);
BinaryOperator Assign(&IvarRef, &Arg, BinaryOperator::Assign,
Ivar->getType(), Loc);
EmitStmt(&Assign);
FinishFunction();
}
llvm::Value *CodeGenFunction::LoadObjCSelf(void) {
const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
}
RValue CodeGenFunction::EmitObjCPropertyGet(const ObjCPropertyRefExpr *E) {
// Determine getter selector.
Selector S;
if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(E->getDecl())) {
S = MD->getSelector();
} else {
S = cast<ObjCPropertyDecl>(E->getDecl())->getGetterName();
}
return CGM.getObjCRuntime().
GenerateMessageSend(*this, E->getType(), S,
EmitScalarExpr(E->getBase()),
false, CallArgList());
}
void CodeGenFunction::EmitObjCPropertySet(const ObjCPropertyRefExpr *E,
RValue Src) {
Selector S;
if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(E->getDecl())) {
S = PD->getSetterName();
} else {
// FIXME: How can we have a method decl here?
ErrorUnsupported(E, "Objective-C property setter call");
return;
}
CallArgList Args;
EmitCallArg(Src, E->getType(), Args);
CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S,
EmitScalarExpr(E->getBase()),
false, Args);
}
void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S)
{
ErrorUnsupported(&S, "for ... in statement");
}
CGObjCRuntime::~CGObjCRuntime() {}
<commit_msg>Initial support for CodeGen of for ... in statements.<commit_after>//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code to emit Objective-C code as LLVM code.
//
//===----------------------------------------------------------------------===//
#include "CGObjCRuntime.h"
#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclObjC.h"
#include "llvm/ADT/STLExtras.h"
using namespace clang;
using namespace CodeGen;
/// Emits an instance of NSConstantString representing the object.
llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E) {
std::string String(E->getString()->getStrData(), E->getString()->getByteLength());
llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(String);
// FIXME: This bitcast should just be made an invariant on the Runtime.
return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
}
/// Emit a selector.
llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
// Untyped selector.
// Note that this implementation allows for non-constant strings to be passed
// as arguments to @selector(). Currently, the only thing preventing this
// behaviour is the type checking in the front end.
return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
}
llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
// FIXME: This should pass the Decl not the name.
return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
}
RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E) {
// Only the lookup mechanism and first two arguments of the method
// implementation vary between runtimes. We can get the receiver and
// arguments in generic code.
CGObjCRuntime &Runtime = CGM.getObjCRuntime();
const Expr *ReceiverExpr = E->getReceiver();
bool isSuperMessage = false;
bool isClassMessage = false;
// Find the receiver
llvm::Value *Receiver;
if (!ReceiverExpr) {
const ObjCInterfaceDecl *OID = E->getClassInfo().first;
// Very special case, super send in class method. The receiver is
// self (the class object) and the send uses super semantics.
if (!OID) {
assert(!strcmp(E->getClassName()->getName(), "super") &&
"Unexpected missing class interface in message send.");
isSuperMessage = true;
Receiver = LoadObjCSelf();
} else {
Receiver = Runtime.GetClass(Builder, OID);
}
isClassMessage = true;
} else if (const PredefinedExpr *PDE =
dyn_cast<PredefinedExpr>(E->getReceiver())) {
assert(PDE->getIdentType() == PredefinedExpr::ObjCSuper);
isSuperMessage = true;
Receiver = LoadObjCSelf();
} else {
Receiver = EmitScalarExpr(E->getReceiver());
}
CallArgList Args;
for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
i != e; ++i)
EmitCallArg(*i, Args);
if (isSuperMessage) {
// super is only valid in an Objective-C method
const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
return Runtime.GenerateMessageSendSuper(*this, E->getType(),
E->getSelector(),
OMD->getClassInterface(),
Receiver,
isClassMessage,
Args);
}
return Runtime.GenerateMessageSend(*this, E->getType(), E->getSelector(),
Receiver, isClassMessage, Args);
}
/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
/// the LLVM function and sets the other context used by
/// CodeGenFunction.
// FIXME: This should really be merged with GenerateCode.
void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD) {
CurFn = CGM.getObjCRuntime().GenerateMethod(OMD);
llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", CurFn);
// Create a marker to make it easy to insert allocas into the entryblock
// later. Don't create this with the builder, because we don't want it
// folded.
llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
EntryBB);
FnRetTy = OMD->getResultType();
CurFuncDecl = OMD;
Builder.SetInsertPoint(EntryBB);
// Emit allocs for param decls. Give the LLVM Argument nodes names.
llvm::Function::arg_iterator AI = CurFn->arg_begin();
// Name the struct return argument.
if (hasAggregateLLVMType(OMD->getResultType())) {
AI->setName("agg.result");
++AI;
}
// Add implicit parameters to the decl map.
EmitParmDecl(*OMD->getSelfDecl(), AI);
++AI;
EmitParmDecl(*OMD->getCmdDecl(), AI);
++AI;
for (unsigned i = 0, e = OMD->getNumParams(); i != e; ++i, ++AI) {
assert(AI != CurFn->arg_end() && "Argument mismatch!");
EmitParmDecl(*OMD->getParamDecl(i), AI);
}
assert(AI == CurFn->arg_end() && "Argument mismatch");
}
/// Generate an Objective-C method. An Objective-C method is a C function with
/// its pointer, name, and types registered in the class struture.
void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
StartObjCMethod(OMD);
EmitStmt(OMD->getBody());
const CompoundStmt *S = dyn_cast<CompoundStmt>(OMD->getBody());
if (S) {
FinishFunction(S->getRBracLoc());
} else {
FinishFunction();
}
}
// FIXME: I wasn't sure about the synthesis approach. If we end up
// generating an AST for the whole body we can just fall back to
// having a GenerateFunction which takes the body Stmt.
/// GenerateObjCGetter - Generate an Objective-C property getter
/// function. The given Decl must be either an ObjCCategoryImplDecl
/// or an ObjCImplementationDecl.
void CodeGenFunction::GenerateObjCGetter(const ObjCPropertyImplDecl *PID) {
const ObjCPropertyDecl *PD = PID->getPropertyDecl();
ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
assert(OMD && "Invalid call to generate getter (empty method)");
// FIXME: This is rather murky, we create this here since they will
// not have been created by Sema for us.
OMD->createImplicitParams(getContext());
StartObjCMethod(OMD);
// FIXME: What about nonatomic?
SourceLocation Loc = PD->getLocation();
ValueDecl *Self = OMD->getSelfDecl();
ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
DeclRefExpr Base(Self, Self->getType(), Loc);
ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base,
true, true);
ReturnStmt Return(Loc, &IvarRef);
EmitStmt(&Return);
FinishFunction();
}
/// GenerateObjCSetter - Generate an Objective-C property setter
/// function. The given Decl must be either an ObjCCategoryImplDecl
/// or an ObjCImplementationDecl.
void CodeGenFunction::GenerateObjCSetter(const ObjCPropertyImplDecl *PID) {
const ObjCPropertyDecl *PD = PID->getPropertyDecl();
ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
assert(OMD && "Invalid call to generate setter (empty method)");
// FIXME: This is rather murky, we create this here since they will
// not have been created by Sema for us.
OMD->createImplicitParams(getContext());
StartObjCMethod(OMD);
switch (PD->getSetterKind()) {
case ObjCPropertyDecl::Assign: break;
case ObjCPropertyDecl::Copy:
CGM.ErrorUnsupported(PID, "Obj-C setter with 'copy'");
break;
case ObjCPropertyDecl::Retain:
CGM.ErrorUnsupported(PID, "Obj-C setter with 'retain'");
break;
}
// FIXME: What about nonatomic?
SourceLocation Loc = PD->getLocation();
ValueDecl *Self = OMD->getSelfDecl();
ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
DeclRefExpr Base(Self, Self->getType(), Loc);
ParmVarDecl *ArgDecl = OMD->getParamDecl(0);
DeclRefExpr Arg(ArgDecl, ArgDecl->getType(), Loc);
ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base,
true, true);
BinaryOperator Assign(&IvarRef, &Arg, BinaryOperator::Assign,
Ivar->getType(), Loc);
EmitStmt(&Assign);
FinishFunction();
}
llvm::Value *CodeGenFunction::LoadObjCSelf(void) {
const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
}
RValue CodeGenFunction::EmitObjCPropertyGet(const ObjCPropertyRefExpr *E) {
// Determine getter selector.
Selector S;
if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(E->getDecl())) {
S = MD->getSelector();
} else {
S = cast<ObjCPropertyDecl>(E->getDecl())->getGetterName();
}
return CGM.getObjCRuntime().
GenerateMessageSend(*this, E->getType(), S,
EmitScalarExpr(E->getBase()),
false, CallArgList());
}
void CodeGenFunction::EmitObjCPropertySet(const ObjCPropertyRefExpr *E,
RValue Src) {
Selector S;
if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(E->getDecl())) {
S = PD->getSetterName();
} else {
// FIXME: How can we have a method decl here?
ErrorUnsupported(E, "Objective-C property setter call");
return;
}
CallArgList Args;
EmitCallArg(Src, E->getType(), Args);
CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S,
EmitScalarExpr(E->getBase()),
false, Args);
}
void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S)
{
llvm::Value *DeclAddress;
QualType ElementTy;
if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
EmitStmt(SD);
ElementTy = cast<ValueDecl>(SD->getDecl())->getType();
DeclAddress = LocalDeclMap[SD->getDecl()];
} else {
ElementTy = cast<Expr>(S.getElement())->getType();
DeclAddress = 0;
}
// Fast enumeration state.
QualType StateTy = getContext().getObjCFastEnumerationStateType();
llvm::AllocaInst *StatePtr = CreateTempAlloca(ConvertType(StateTy),
"state.ptr");
StatePtr->setAlignment(getContext().getTypeAlign(StateTy) >> 3);
EmitMemSetToZero(StatePtr,StateTy);
// Number of elements in the items array.
static const unsigned NumItems = 2;
// Get selector
llvm::SmallVector<IdentifierInfo*, 3> II;
II.push_back(&CGM.getContext().Idents.get("countByEnumeratingWithState"));
II.push_back(&CGM.getContext().Idents.get("objects"));
II.push_back(&CGM.getContext().Idents.get("count"));
Selector FastEnumSel = CGM.getContext().Selectors.getSelector(II.size(),
&II[0]);
QualType ItemsTy =
getContext().getConstantArrayType(getContext().getObjCIdType(),
llvm::APInt(32, NumItems),
ArrayType::Normal, 0);
llvm::Value *ItemsPtr = CreateTempAlloca(ConvertType(ItemsTy), "items.ptr");
llvm::Value *Collection = EmitScalarExpr(S.getCollection());
CallArgList Args;
Args.push_back(std::make_pair(StatePtr,
getContext().getPointerType(StateTy)));
Args.push_back(std::make_pair(ItemsPtr,
getContext().getPointerType(ItemsTy)));
const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Args.push_back(std::make_pair(Count, getContext().UnsignedLongTy));
RValue CountRV =
CGM.getObjCRuntime().GenerateMessageSend(*this,
getContext().UnsignedLongTy,
FastEnumSel,
Collection, false, Args);
llvm::Value *LimitPtr = CreateTempAlloca(UnsignedLongLTy, "limit.ptr");
Builder.CreateStore(CountRV.getScalarVal(), LimitPtr);
llvm::BasicBlock *NoElements = llvm::BasicBlock::Create("noelements");
llvm::BasicBlock *LoopStart = llvm::BasicBlock::Create("loopstart");
llvm::Value *Limit = Builder.CreateLoad(LimitPtr);
llvm::Value *Zero = llvm::Constant::getNullValue(UnsignedLongLTy);
llvm::Value *IsZero = Builder.CreateICmpEQ(Limit, Zero, "iszero");
Builder.CreateCondBr(IsZero, NoElements, LoopStart);
EmitBlock(LoopStart);
llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("loopbody");
llvm::Value *CounterPtr = CreateTempAlloca(UnsignedLongLTy, "counter.ptr");
Builder.CreateStore(Zero, CounterPtr);
EmitBlock(LoopBody);
llvm::Value *StateItemsPtr =
Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
llvm::Value *Counter = Builder.CreateLoad(CounterPtr, "counter");
llvm::Value *EnumStateItems = Builder.CreateLoad(StateItemsPtr,
"stateitems");
llvm::Value *CurrentItemPtr =
Builder.CreateGEP(EnumStateItems, Counter, "currentitem.ptr");
llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr, "currentitem");
// Cast the item to the right type.
CurrentItem = Builder.CreateBitCast(CurrentItem,
ConvertType(ElementTy), "tmp");
if (!DeclAddress) {
LValue LV = EmitLValue(cast<Expr>(S.getElement()));
// Set the value to null.
Builder.CreateStore(CurrentItem, LV.getAddress());
} else
Builder.CreateStore(CurrentItem, DeclAddress);
// Increment the counter.
Counter = Builder.CreateAdd(Counter,
llvm::ConstantInt::get(UnsignedLongLTy, 1));
Builder.CreateStore(Counter, CounterPtr);
llvm::BasicBlock *LoopEnd = llvm::BasicBlock::Create("loopend");
llvm::BasicBlock *AfterBody = llvm::BasicBlock::Create("afterbody");
BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
EmitStmt(S.getBody());
BreakContinueStack.pop_back();
EmitBlock(AfterBody);
llvm::BasicBlock *FetchMore = llvm::BasicBlock::Create("fetchmore");
llvm::Value *IsLess = Builder.CreateICmpULT(Counter, Limit, "isless");
Builder.CreateCondBr(IsLess, LoopBody, FetchMore);
// Fetch more elements.
EmitBlock(FetchMore);
CountRV =
CGM.getObjCRuntime().GenerateMessageSend(*this,
getContext().UnsignedLongTy,
FastEnumSel,
Collection, false, Args);
Builder.CreateStore(CountRV.getScalarVal(), LimitPtr);
Limit = Builder.CreateLoad(LimitPtr);
IsZero = Builder.CreateICmpEQ(Limit, Zero, "iszero");
Builder.CreateCondBr(IsZero, NoElements, LoopStart);
// No more elements.
EmitBlock(NoElements);
if (!DeclAddress) {
// If the element was not a declaration, set it to be null.
LValue LV = EmitLValue(cast<Expr>(S.getElement()));
// Set the value to null.
Builder.CreateStore(llvm::Constant::getNullValue(ConvertType(ElementTy)),
LV.getAddress());
}
EmitBlock(LoopEnd);
}
CGObjCRuntime::~CGObjCRuntime() {}
<|endoftext|> |
<commit_before>//===--- Link.cpp - Link in transparent SILFunctions from module ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SILPasses/Passes.h"
#include "swift/SILPasses/Transforms.h"
#include "swift/SIL/SILModule.h"
using namespace swift;
//===----------------------------------------------------------------------===//
// Top Level Driver
//===----------------------------------------------------------------------===//
void swift::performSILLinking(SILModule *M, bool LinkAll) {
auto LinkMode = LinkAll? SILModule::LinkingMode::LinkAll :
SILModule::LinkingMode::LinkNormal;
for (auto &Fn : *M)
M->linkFunction(&Fn, LinkMode);
if (!LinkAll)
return;
M->linkAllWitnessTables();
M->linkAllVTables();
}
namespace {
class SILLinker : public SILModuleTransform {
/// The entry point to the transformation.
void run() {
// Remove dead stores, merge duplicate loads, and forward stores to loads.
bool Changed = false;
SILModule &M = *getModule();
for (auto &Fn : M)
Changed |= M.linkFunction(&Fn, SILModule::LinkingMode::LinkAll);
if (Changed)
invalidateAnalysis(SILAnalysis::InvalidationKind::All);
}
StringRef getName() override { return "SIL Linker"; }
};
} // end anonymous namespace
SILTransform *swift::createSILLinker() {
return new SILLinker();
}
<commit_msg>Fix a stale comment.<commit_after>//===--- Link.cpp - Link in transparent SILFunctions from module ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SILPasses/Passes.h"
#include "swift/SILPasses/Transforms.h"
#include "swift/SIL/SILModule.h"
using namespace swift;
//===----------------------------------------------------------------------===//
// Top Level Driver
//===----------------------------------------------------------------------===//
void swift::performSILLinking(SILModule *M, bool LinkAll) {
auto LinkMode = LinkAll? SILModule::LinkingMode::LinkAll :
SILModule::LinkingMode::LinkNormal;
for (auto &Fn : *M)
M->linkFunction(&Fn, LinkMode);
if (!LinkAll)
return;
M->linkAllWitnessTables();
M->linkAllVTables();
}
namespace {
class SILLinker : public SILModuleTransform {
/// The entry point to the transformation.
void run() {
// Copies code from the standard library into the user program to enable
// optimizations.
bool Changed = false;
SILModule &M = *getModule();
for (auto &Fn : M)
Changed |= M.linkFunction(&Fn, SILModule::LinkingMode::LinkAll);
if (Changed)
invalidateAnalysis(SILAnalysis::InvalidationKind::All);
}
StringRef getName() override { return "SIL Linker"; }
};
} // end anonymous namespace
SILTransform *swift::createSILLinker() {
return new SILLinker();
}
<|endoftext|> |
<commit_before>//===-- asan_linux.cc -----------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// Linux-specific details.
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_platform.h"
#if SANITIZER_FREEBSD || SANITIZER_LINUX
#include "asan_interceptors.h"
#include "asan_internal.h"
#include "asan_thread.h"
#include "sanitizer_common/sanitizer_flags.h"
#include "sanitizer_common/sanitizer_libc.h"
#include "sanitizer_common/sanitizer_procmaps.h"
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <unwind.h>
#if SANITIZER_ANDROID
#include <ucontext.h>
extern "C" void* _DYNAMIC;
#else
#include <sys/ucontext.h>
#include <dlfcn.h>
#include <link.h>
#endif
// x86_64 FreeBSD 9.2 and older define 64-bit register names in both 64-bit
// and 32-bit modes.
#if SANITIZER_FREEBSD
#include <sys/param.h>
# if __FreeBSD_version <= 902001 // v9.2
# define mc_eip mc_rip
# define mc_ebp mc_rbp
# define mc_esp mc_rsp
# endif
#endif
typedef enum {
ASAN_RT_VERSION_UNDEFINED = 0,
ASAN_RT_VERSION_DYNAMIC,
ASAN_RT_VERSION_STATIC,
} asan_rt_version_t;
// FIXME: perhaps also store abi version here?
extern "C" {
SANITIZER_INTERFACE_ATTRIBUTE
asan_rt_version_t __asan_rt_version;
}
namespace __asan {
void MaybeReexec() {
// No need to re-exec on Linux.
}
void *AsanDoesNotSupportStaticLinkage() {
// This will fail to link with -static.
return &_DYNAMIC; // defined in link.h
}
#if !SANITIZER_ANDROID
static int FindFirstDSOCallback(struct dl_phdr_info *info, size_t size,
void *data) {
// Continue until the first dynamic library is found
if (!info->dlpi_name || info->dlpi_name[0] == 0)
return 0;
*(const char **)data = info->dlpi_name;
return 1;
}
#endif
static bool IsDynamicRTName(const char *libname) {
return internal_strstr(libname, "libclang_rt.asan") ||
internal_strstr(libname, "libasan.so");
}
void AsanCheckDynamicRTPrereqs() {
// FIXME: can we do something like this for Android?
#if !SANITIZER_ANDROID
// Ensure that dynamic RT is the first DSO in the list
const char *first_dso_name = 0;
dl_iterate_phdr(FindFirstDSOCallback, &first_dso_name);
if (first_dso_name && !IsDynamicRTName(first_dso_name)) {
Report("ASan runtime does not come first in initial library list; "
"you should either link runtime to your application or "
"manually preload it with LD_PRELOAD.\n");
Die();
}
#endif
}
void AsanCheckIncompatibleRT() {
#if !SANITIZER_ANDROID
if (ASAN_DYNAMIC) {
if (__asan_rt_version == ASAN_RT_VERSION_UNDEFINED) {
__asan_rt_version = ASAN_RT_VERSION_DYNAMIC;
} else if (__asan_rt_version != ASAN_RT_VERSION_DYNAMIC) {
Report("Your application is linked against "
"incompatible ASan runtimes.\n");
Die();
}
} else {
// Ensure that dynamic runtime is not present. We should detect it
// as early as possible, otherwise ASan interceptors could bind to
// the functions in dynamic ASan runtime instead of the functions in
// system libraries, causing crashes later in ASan initialization.
MemoryMappingLayout proc_maps(/*cache_enabled*/true);
char filename[128];
while (proc_maps.Next(0, 0, 0, filename, sizeof(filename), 0)) {
if (IsDynamicRTName(filename)) {
Report("Your application is linked against "
"incompatible ASan runtimes.\n");
Die();
}
}
CHECK_NE(__asan_rt_version, ASAN_RT_VERSION_DYNAMIC);
__asan_rt_version = ASAN_RT_VERSION_STATIC;
}
#endif
}
void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
#if defined(__arm__)
ucontext_t *ucontext = (ucontext_t*)context;
*pc = ucontext->uc_mcontext.arm_pc;
*bp = ucontext->uc_mcontext.arm_fp;
*sp = ucontext->uc_mcontext.arm_sp;
#elif defined(__aarch64__)
ucontext_t *ucontext = (ucontext_t*)context;
*pc = ucontext->uc_mcontext.pc;
*bp = ucontext->uc_mcontext.regs[29];
*sp = ucontext->uc_mcontext.sp;
#elif defined(__hppa__)
ucontext_t *ucontext = (ucontext_t*)context;
*pc = ucontext->uc_mcontext.sc_iaoq[0];
/* GCC uses %r3 whenever a frame pointer is needed. */
*bp = ucontext->uc_mcontext.sc_gr[3];
*sp = ucontext->uc_mcontext.sc_gr[30];
#elif defined(__x86_64__)
# if SANITIZER_FREEBSD
ucontext_t *ucontext = (ucontext_t*)context;
*pc = ucontext->uc_mcontext.mc_rip;
*bp = ucontext->uc_mcontext.mc_rbp;
*sp = ucontext->uc_mcontext.mc_rsp;
# else
ucontext_t *ucontext = (ucontext_t*)context;
*pc = ucontext->uc_mcontext.gregs[REG_RIP];
*bp = ucontext->uc_mcontext.gregs[REG_RBP];
*sp = ucontext->uc_mcontext.gregs[REG_RSP];
# endif
#elif defined(__i386__)
# if SANITIZER_FREEBSD
ucontext_t *ucontext = (ucontext_t*)context;
*pc = ucontext->uc_mcontext.mc_eip;
*bp = ucontext->uc_mcontext.mc_ebp;
*sp = ucontext->uc_mcontext.mc_esp;
# else
ucontext_t *ucontext = (ucontext_t*)context;
*pc = ucontext->uc_mcontext.gregs[REG_EIP];
*bp = ucontext->uc_mcontext.gregs[REG_EBP];
*sp = ucontext->uc_mcontext.gregs[REG_ESP];
# endif
#elif defined(__sparc__)
ucontext_t *ucontext = (ucontext_t*)context;
uptr *stk_ptr;
# if defined (__arch64__)
*pc = ucontext->uc_mcontext.mc_gregs[MC_PC];
*sp = ucontext->uc_mcontext.mc_gregs[MC_O6];
stk_ptr = (uptr *) (*sp + 2047);
*bp = stk_ptr[15];
# else
*pc = ucontext->uc_mcontext.gregs[REG_PC];
*sp = ucontext->uc_mcontext.gregs[REG_O6];
stk_ptr = (uptr *) *sp;
*bp = stk_ptr[15];
# endif
#elif defined(__mips__)
ucontext_t *ucontext = (ucontext_t*)context;
*pc = ucontext->uc_mcontext.gregs[31];
*bp = ucontext->uc_mcontext.gregs[30];
*sp = ucontext->uc_mcontext.gregs[29];
#else
# error "Unsupported arch"
#endif
}
bool AsanInterceptsSignal(int signum) {
return signum == SIGSEGV && common_flags()->handle_segv;
}
void AsanPlatformThreadInit() {
// Nothing here for now.
}
#if !SANITIZER_ANDROID
void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
ucontext_t *ucp = (ucontext_t*)context;
*stack = (uptr)ucp->uc_stack.ss_sp;
*ssize = ucp->uc_stack.ss_size;
}
#else
void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
UNIMPLEMENTED();
}
#endif
} // namespace __asan
#endif // SANITIZER_FREEBSD || SANITIZER_LINUX
<commit_msg>[ASan] One more attempt to fix Android build<commit_after>//===-- asan_linux.cc -----------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// Linux-specific details.
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_platform.h"
#if SANITIZER_FREEBSD || SANITIZER_LINUX
#include "asan_interceptors.h"
#include "asan_internal.h"
#include "asan_thread.h"
#include "sanitizer_common/sanitizer_flags.h"
#include "sanitizer_common/sanitizer_libc.h"
#include "sanitizer_common/sanitizer_procmaps.h"
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <unwind.h>
#if SANITIZER_ANDROID
#include <ucontext.h>
extern "C" void* _DYNAMIC;
#else
#include <sys/ucontext.h>
#include <dlfcn.h>
#include <link.h>
#endif
// x86_64 FreeBSD 9.2 and older define 64-bit register names in both 64-bit
// and 32-bit modes.
#if SANITIZER_FREEBSD
#include <sys/param.h>
# if __FreeBSD_version <= 902001 // v9.2
# define mc_eip mc_rip
# define mc_ebp mc_rbp
# define mc_esp mc_rsp
# endif
#endif
typedef enum {
ASAN_RT_VERSION_UNDEFINED = 0,
ASAN_RT_VERSION_DYNAMIC,
ASAN_RT_VERSION_STATIC,
} asan_rt_version_t;
// FIXME: perhaps also store abi version here?
extern "C" {
SANITIZER_INTERFACE_ATTRIBUTE
asan_rt_version_t __asan_rt_version;
}
namespace __asan {
void MaybeReexec() {
// No need to re-exec on Linux.
}
void *AsanDoesNotSupportStaticLinkage() {
// This will fail to link with -static.
return &_DYNAMIC; // defined in link.h
}
#if SANITIZER_ANDROID
// FIXME: should we do anything for Android?
void AsanCheckDynamicRTPrereqs() {}
void AsanCheckIncompatibleRT() {}
#else
static int FindFirstDSOCallback(struct dl_phdr_info *info, size_t size,
void *data) {
// Continue until the first dynamic library is found
if (!info->dlpi_name || info->dlpi_name[0] == 0)
return 0;
*(const char **)data = info->dlpi_name;
return 1;
}
static bool IsDynamicRTName(const char *libname) {
return internal_strstr(libname, "libclang_rt.asan") ||
internal_strstr(libname, "libasan.so");
}
void AsanCheckDynamicRTPrereqs() {
// Ensure that dynamic RT is the first DSO in the list
const char *first_dso_name = 0;
dl_iterate_phdr(FindFirstDSOCallback, &first_dso_name);
if (first_dso_name && !IsDynamicRTName(first_dso_name)) {
Report("ASan runtime does not come first in initial library list; "
"you should either link runtime to your application or "
"manually preload it with LD_PRELOAD.\n");
Die();
}
}
void AsanCheckIncompatibleRT() {
if (ASAN_DYNAMIC) {
if (__asan_rt_version == ASAN_RT_VERSION_UNDEFINED) {
__asan_rt_version = ASAN_RT_VERSION_DYNAMIC;
} else if (__asan_rt_version != ASAN_RT_VERSION_DYNAMIC) {
Report("Your application is linked against "
"incompatible ASan runtimes.\n");
Die();
}
} else {
// Ensure that dynamic runtime is not present. We should detect it
// as early as possible, otherwise ASan interceptors could bind to
// the functions in dynamic ASan runtime instead of the functions in
// system libraries, causing crashes later in ASan initialization.
MemoryMappingLayout proc_maps(/*cache_enabled*/true);
char filename[128];
while (proc_maps.Next(0, 0, 0, filename, sizeof(filename), 0)) {
if (IsDynamicRTName(filename)) {
Report("Your application is linked against "
"incompatible ASan runtimes.\n");
Die();
}
}
CHECK_NE(__asan_rt_version, ASAN_RT_VERSION_DYNAMIC);
__asan_rt_version = ASAN_RT_VERSION_STATIC;
}
}
#endif // SANITIZER_ANDROID
void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
#if defined(__arm__)
ucontext_t *ucontext = (ucontext_t*)context;
*pc = ucontext->uc_mcontext.arm_pc;
*bp = ucontext->uc_mcontext.arm_fp;
*sp = ucontext->uc_mcontext.arm_sp;
#elif defined(__aarch64__)
ucontext_t *ucontext = (ucontext_t*)context;
*pc = ucontext->uc_mcontext.pc;
*bp = ucontext->uc_mcontext.regs[29];
*sp = ucontext->uc_mcontext.sp;
#elif defined(__hppa__)
ucontext_t *ucontext = (ucontext_t*)context;
*pc = ucontext->uc_mcontext.sc_iaoq[0];
/* GCC uses %r3 whenever a frame pointer is needed. */
*bp = ucontext->uc_mcontext.sc_gr[3];
*sp = ucontext->uc_mcontext.sc_gr[30];
#elif defined(__x86_64__)
# if SANITIZER_FREEBSD
ucontext_t *ucontext = (ucontext_t*)context;
*pc = ucontext->uc_mcontext.mc_rip;
*bp = ucontext->uc_mcontext.mc_rbp;
*sp = ucontext->uc_mcontext.mc_rsp;
# else
ucontext_t *ucontext = (ucontext_t*)context;
*pc = ucontext->uc_mcontext.gregs[REG_RIP];
*bp = ucontext->uc_mcontext.gregs[REG_RBP];
*sp = ucontext->uc_mcontext.gregs[REG_RSP];
# endif
#elif defined(__i386__)
# if SANITIZER_FREEBSD
ucontext_t *ucontext = (ucontext_t*)context;
*pc = ucontext->uc_mcontext.mc_eip;
*bp = ucontext->uc_mcontext.mc_ebp;
*sp = ucontext->uc_mcontext.mc_esp;
# else
ucontext_t *ucontext = (ucontext_t*)context;
*pc = ucontext->uc_mcontext.gregs[REG_EIP];
*bp = ucontext->uc_mcontext.gregs[REG_EBP];
*sp = ucontext->uc_mcontext.gregs[REG_ESP];
# endif
#elif defined(__sparc__)
ucontext_t *ucontext = (ucontext_t*)context;
uptr *stk_ptr;
# if defined (__arch64__)
*pc = ucontext->uc_mcontext.mc_gregs[MC_PC];
*sp = ucontext->uc_mcontext.mc_gregs[MC_O6];
stk_ptr = (uptr *) (*sp + 2047);
*bp = stk_ptr[15];
# else
*pc = ucontext->uc_mcontext.gregs[REG_PC];
*sp = ucontext->uc_mcontext.gregs[REG_O6];
stk_ptr = (uptr *) *sp;
*bp = stk_ptr[15];
# endif
#elif defined(__mips__)
ucontext_t *ucontext = (ucontext_t*)context;
*pc = ucontext->uc_mcontext.gregs[31];
*bp = ucontext->uc_mcontext.gregs[30];
*sp = ucontext->uc_mcontext.gregs[29];
#else
# error "Unsupported arch"
#endif
}
bool AsanInterceptsSignal(int signum) {
return signum == SIGSEGV && common_flags()->handle_segv;
}
void AsanPlatformThreadInit() {
// Nothing here for now.
}
#if !SANITIZER_ANDROID
void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
ucontext_t *ucp = (ucontext_t*)context;
*stack = (uptr)ucp->uc_stack.ss_sp;
*ssize = ucp->uc_stack.ss_size;
}
#else
void ReadContextStack(void *context, uptr *stack, uptr *ssize) {
UNIMPLEMENTED();
}
#endif
} // namespace __asan
#endif // SANITIZER_FREEBSD || SANITIZER_LINUX
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved
*/
#ifndef _Stroika_Foundation_Streams_InternallySyncrhonizedOutputStream_inl_
#define _Stroika_Foundation_Streams_InternallySyncrhonizedOutputStream_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika {
namespace Foundation {
namespace Streams {
/*
********************************************************************************
*********** InternallySyncrhonizedOutputStream<ELEMENT_TYPE>::Rep_ *************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
class InternallySyncrhonizedOutputStream<ELEMENT_TYPE>::Rep_ : public OutputStream<ELEMENT_TYPE>::_IRep {
public:
Rep_ (const typename OutputStream<ELEMENT_TYPE>::Ptr& realOut)
: OutputStream<ELEMENT_TYPE>::_IRep ()
, fRealOut_ (realOut)
{
}
Rep_ () = delete;
Rep_ (const Rep_&) = delete;
virtual bool IsSeekable () const override
{
lock_guard<const mutex> critSec{fCriticalSection_};
return fRealOut_.IsSeekable ();
}
virtual SeekOffsetType GetWriteOffset () const override
{
lock_guard<const mutex> critSec{fCriticalSection_};
return fRealOut_.GetWriteOffset ();
}
virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override
{
lock_guard<const mutex> critSec{fCriticalSection_};
return fRealOut_.SeekWrite (whence, offset);
}
virtual void Write (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) override
{
lock_guard<const mutex> critSec{fCriticalSection_};
fRealOut_.Write (start, end);
}
virtual void Flush () override
{
lock_guard<const mutex> critSec{fCriticalSection_};
fRealOut_.Flush ();
}
private:
mutex fCriticalSection_;
typename OutputStream<ELEMENT_TYPE>::Ptr fRealOut_;
};
/*
********************************************************************************
*********** InternallySyncrhonizedOutputStream<ELEMENT_TYPE> *******************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
inline auto InternallySyncrhonizedOutputStream<ELEMENT_TYPE>::New (const typename OutputStream<ELEMENT_TYPE>::Ptr& stream2Wrap) -> Ptr
{
return make_shared<Rep_> (stream2Wrap);
}
/*
********************************************************************************
************* InternallySyncrhonizedOutputStream<ELEMENT_TYPE>::Ptr ************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
inline InternallySyncrhonizedOutputStream<ELEMENT_TYPE>::Ptr::Ptr (const shared_ptr<Rep_>& from)
: inherited (from)
{
}
template <typename ELEMENT_TYPE>
inline typename InternallySyncrhonizedOutputStream<ELEMENT_TYPE>::Ptr& InternallySyncrhonizedOutputStream<ELEMENT_TYPE>::Ptr::operator= (const InternallySyncrhonizedOutputStream<ELEMENT_TYPE>& rhs)
{
inherited::Ptr::operator= (rhs);
return *this;
}
}
}
}
#endif /*_Stroika_Foundation_Streams_InternallySyncrhonizedOutputStream_inl_*/
<commit_msg>make format-code<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved
*/
#ifndef _Stroika_Foundation_Streams_InternallySyncrhonizedOutputStream_inl_
#define _Stroika_Foundation_Streams_InternallySyncrhonizedOutputStream_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
namespace Stroika {
namespace Foundation {
namespace Streams {
/*
********************************************************************************
*********** InternallySyncrhonizedOutputStream<ELEMENT_TYPE>::Rep_ *************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
class InternallySyncrhonizedOutputStream<ELEMENT_TYPE>::Rep_ : public OutputStream<ELEMENT_TYPE>::_IRep {
public:
Rep_ (const typename OutputStream<ELEMENT_TYPE>::Ptr& realOut)
: OutputStream<ELEMENT_TYPE>::_IRep ()
, fRealOut_ (realOut)
{
}
Rep_ () = delete;
Rep_ (const Rep_&) = delete;
virtual bool IsSeekable () const override
{
lock_guard<const mutex> critSec{fCriticalSection_};
return fRealOut_.IsSeekable ();
}
virtual SeekOffsetType GetWriteOffset () const override
{
lock_guard<const mutex> critSec{fCriticalSection_};
return fRealOut_.GetWriteOffset ();
}
virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override
{
lock_guard<const mutex> critSec{fCriticalSection_};
return fRealOut_.SeekWrite (whence, offset);
}
virtual void Write (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) override
{
lock_guard<const mutex> critSec{fCriticalSection_};
fRealOut_.Write (start, end);
}
virtual void Flush () override
{
lock_guard<const mutex> critSec{fCriticalSection_};
fRealOut_.Flush ();
}
private:
mutex fCriticalSection_;
typename OutputStream<ELEMENT_TYPE>::Ptr fRealOut_;
};
/*
********************************************************************************
*********** InternallySyncrhonizedOutputStream<ELEMENT_TYPE> *******************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
inline auto InternallySyncrhonizedOutputStream<ELEMENT_TYPE>::New (const typename OutputStream<ELEMENT_TYPE>::Ptr& stream2Wrap) -> Ptr
{
return make_shared<Rep_> (stream2Wrap);
}
/*
********************************************************************************
************* InternallySyncrhonizedOutputStream<ELEMENT_TYPE>::Ptr ************
********************************************************************************
*/
template <typename ELEMENT_TYPE>
inline InternallySyncrhonizedOutputStream<ELEMENT_TYPE>::Ptr::Ptr (const shared_ptr<Rep_>& from)
: inherited (from)
{
}
template <typename ELEMENT_TYPE>
inline typename InternallySyncrhonizedOutputStream<ELEMENT_TYPE>::Ptr& InternallySyncrhonizedOutputStream<ELEMENT_TYPE>::Ptr::operator= (const InternallySyncrhonizedOutputStream<ELEMENT_TYPE>& rhs)
{
inherited::Ptr::operator= (rhs);
return *this;
}
}
}
}
#endif /*_Stroika_Foundation_Streams_InternallySyncrhonizedOutputStream_inl_*/
<|endoftext|> |
<commit_before>/*
* WrapperIO.cpp
* This file is part of FRESteamWorks.
*
* Created by Ventero <http://github.com/Ventero>
* Copyright (c) 2012-2014 Level Up Labs, LLC. All rights reserved.
*/
#include "WrapperIO.h"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <ios>
#include <iostream>
#include <iterator>
#include <sstream>
using namespace amf;
void sendData(Serializer& serializer) {
std::vector<u8> data = serializer.data();
if(data.size() > 1024) {
// due to output buffering, large outputs need to be sent via a tempfile
sendDataTempFile(serializer);
return;
}
serializer.clear();
// first, send a length prefix
std::vector<u8> length = AmfInteger(data.size()).serialize();
std::copy(length.begin(), length.end(), std::ostream_iterator<u8>(std::cout));
// send actual data
std::copy(data.begin(), data.end(), std::ostream_iterator<u8>(std::cout));
}
void sendDataTempFile(Serializer& serializer) {
std::vector<u8> data = serializer.data();
serializer.clear();
// send length via stdout
std::vector<u8> length = AmfInteger(data.size()).serialize();
std::copy(length.begin(), length.end(), std::ostream_iterator<u8>(std::cout));
std::string filename = std::tmpnam(nullptr);
std::fstream tmpfile(filename, std::ios::out | std::ios::binary);
std::copy(data.begin(), data.end(), std::ostream_iterator<u8>(tmpfile));
tmpfile.close();
send(filename);
}
void sendItem(const AmfItem& item) {
Serializer serializer;
serializer << item;
sendData(serializer);
}
void send(bool value) {
sendItem(AmfBool(value));
}
void send(int32 value) {
sendItem(AmfInteger(value));
}
void send(uint32 value) {
sendItem(AmfInteger(value));
}
void send(uint64 value) {
sendItem(AmfString(std::to_string(value)));
}
void send(float value) {
sendItem(AmfDouble(value));
}
void send(std::string value) {
sendItem(AmfString(value));
}
void send(const AmfItem& value) {
sendItem(value);
}
// sentinel for pseudo-void functions
void send(std::nullptr_t) { }
// TODO: replace this mess with AMF
bool get_bool() {
std::string item;
std::getline(std::cin, item);
return item == "true";
}
int32 get_int() {
std::string item;
std::getline(std::cin, item);
return std::stoi(item);
}
float get_float() {
std::string item;
std::getline(std::cin, item);
return std::stof(item);
}
std::string get_string() {
std::string item;
std::getline(std::cin, item);
size_t length = std::stoi(item);
if (length < 1) return "";
char* buf = new char[length];
if (length > 1024)
return readTempFileBuf(length);
std::cin.read(buf, length);
// remove trailing newline
std::string result(buf, length - 1);
delete[] buf;
return result;
}
std::string get_bytearray() {
std::string item;
std::getline(std::cin, item);
size_t length = std::stoi(item);
if (length < 1) return "";
return readTempFileBuf(length);
}
uint64 get_uint64() {
std::string str = get_string();
std::istringstream ss(str);
uint64 val;
if(!(ss >> val)) return 0;
return val;
}
std::vector<std::string> get_string_array() {
return get_array<std::string>(get_string);
}
std::string readTempFileBuf(size_t length) {
std::string filename;
std::getline(std::cin, filename);
std::ifstream tempfile(filename, std::ios::in | std::ios::binary);
char* buf = new char[length];
tempfile.read(buf, length);
std::string result(buf, length - 1);
delete[] buf;
tempfile.close();
std::remove(filename.c_str());
return result;
}
<commit_msg>Fix memory leak in get_string() for large responses.<commit_after>/*
* WrapperIO.cpp
* This file is part of FRESteamWorks.
*
* Created by Ventero <http://github.com/Ventero>
* Copyright (c) 2012-2014 Level Up Labs, LLC. All rights reserved.
*/
#include "WrapperIO.h"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <ios>
#include <iostream>
#include <iterator>
#include <sstream>
using namespace amf;
void sendData(Serializer& serializer) {
std::vector<u8> data = serializer.data();
if(data.size() > 1024) {
// due to output buffering, large outputs need to be sent via a tempfile
sendDataTempFile(serializer);
return;
}
serializer.clear();
// first, send a length prefix
std::vector<u8> length = AmfInteger(data.size()).serialize();
std::copy(length.begin(), length.end(), std::ostream_iterator<u8>(std::cout));
// send actual data
std::copy(data.begin(), data.end(), std::ostream_iterator<u8>(std::cout));
}
void sendDataTempFile(Serializer& serializer) {
std::vector<u8> data = serializer.data();
serializer.clear();
// send length via stdout
std::vector<u8> length = AmfInteger(data.size()).serialize();
std::copy(length.begin(), length.end(), std::ostream_iterator<u8>(std::cout));
std::string filename = std::tmpnam(nullptr);
std::fstream tmpfile(filename, std::ios::out | std::ios::binary);
std::copy(data.begin(), data.end(), std::ostream_iterator<u8>(tmpfile));
tmpfile.close();
send(filename);
}
void sendItem(const AmfItem& item) {
Serializer serializer;
serializer << item;
sendData(serializer);
}
void send(bool value) {
sendItem(AmfBool(value));
}
void send(int32 value) {
sendItem(AmfInteger(value));
}
void send(uint32 value) {
sendItem(AmfInteger(value));
}
void send(uint64 value) {
sendItem(AmfString(std::to_string(value)));
}
void send(float value) {
sendItem(AmfDouble(value));
}
void send(std::string value) {
sendItem(AmfString(value));
}
void send(const AmfItem& value) {
sendItem(value);
}
// sentinel for pseudo-void functions
void send(std::nullptr_t) { }
// TODO: replace this mess with AMF
bool get_bool() {
std::string item;
std::getline(std::cin, item);
return item == "true";
}
int32 get_int() {
std::string item;
std::getline(std::cin, item);
return std::stoi(item);
}
float get_float() {
std::string item;
std::getline(std::cin, item);
return std::stof(item);
}
std::string get_string() {
std::string item;
std::getline(std::cin, item);
size_t length = std::stoi(item);
if (length < 1) return "";
if (length > 1024)
return readTempFileBuf(length);
char* buf = new char[length];
std::cin.read(buf, length);
// remove trailing newline
std::string result(buf, length - 1);
delete[] buf;
return result;
}
std::string get_bytearray() {
std::string item;
std::getline(std::cin, item);
size_t length = std::stoi(item);
if (length < 1) return "";
return readTempFileBuf(length);
}
uint64 get_uint64() {
std::string str = get_string();
std::istringstream ss(str);
uint64 val;
if(!(ss >> val)) return 0;
return val;
}
std::vector<std::string> get_string_array() {
return get_array<std::string>(get_string);
}
std::string readTempFileBuf(size_t length) {
std::string filename;
std::getline(std::cin, filename);
std::ifstream tempfile(filename, std::ios::in | std::ios::binary);
char* buf = new char[length];
tempfile.read(buf, length);
std::string result(buf, length - 1);
delete[] buf;
tempfile.close();
std::remove(filename.c_str());
return result;
}
<|endoftext|> |
<commit_before>#pragma once
#include "controllers/hotkeys/HotkeyCategory.hpp"
#include <QKeySequence>
#include <QString>
namespace chatterino {
class Hotkey
{
public:
Hotkey(HotkeyCategory category, QKeySequence keySequence, QString action,
std::vector<QString> arguments, QString name);
virtual ~Hotkey() = default;
/**
* @brief Returns the OS-specific string representation of the hotkey
*
* Suitable for showing in the GUI
* e.g. Ctrl+F5 or Command+F5
*/
QString toString() const;
/**
* @brief Returns the portable string representation of the hotkey
*
* Suitable for saving to/loading from file
* e.g. Ctrl+F5 or Shift+Ctrl+R
*/
QString toPortableString() const;
/**
* @brief Returns the category where this hotkey is active. This is labeled the "Category" in the UI.
*
* See enum HotkeyCategory for more information about the various hotkey categories
*/
HotkeyCategory category() const;
/**
* @brief Returns the action which describes what this Hotkey is meant to do
*
* For example, in the Window category there's a "showSearch" action which opens a search popup
*/
QString action() const;
bool validAction() const;
/**
* @brief Returns a list of arguments this hotkey has bound to it
*
* Some actions require a set of arguments that the user can provide, for example the "openTab" action takes an argument for which tab to switch to. can be a number or a word like next or previous
*/
std::vector<QString> arguments() const;
/**
* @brief Returns the display name of the hotkey
*
* For example, in the Split category there's a "showSearch" action that has a default hotkey with the name "default show search"
*/
QString name() const;
/**
* @brief Returns the user-friendly text representation of the hotkeys category
*
* Suitable for showing in the GUI.
* e.g. Split input box for HotkeyCategory::SplitInput
*/
QString getCategory() const;
/**
* @brief Returns the programmating key sequence of the hotkey
*
* The actual key codes required for the hotkey to trigger specifically on e.g CTRL+F5
*/
const QKeySequence &keySequence() const;
private:
HotkeyCategory category_;
QKeySequence keySequence_;
QString action_;
std::vector<QString> arguments_;
QString name_;
/**
* @brief Returns the programmatic context of the hotkey to help Qt decide how to apply the hotkey
*
* The returned value is based off the hotkeys given category
*/
Qt::ShortcutContext getContext() const;
friend class HotkeyController;
};
} // namespace chatterino
<commit_msg>Add missing vector header (#3724)<commit_after>#pragma once
#include "controllers/hotkeys/HotkeyCategory.hpp"
#include <QKeySequence>
#include <QString>
#include <vector>
namespace chatterino {
class Hotkey
{
public:
Hotkey(HotkeyCategory category, QKeySequence keySequence, QString action,
std::vector<QString> arguments, QString name);
virtual ~Hotkey() = default;
/**
* @brief Returns the OS-specific string representation of the hotkey
*
* Suitable for showing in the GUI
* e.g. Ctrl+F5 or Command+F5
*/
QString toString() const;
/**
* @brief Returns the portable string representation of the hotkey
*
* Suitable for saving to/loading from file
* e.g. Ctrl+F5 or Shift+Ctrl+R
*/
QString toPortableString() const;
/**
* @brief Returns the category where this hotkey is active. This is labeled the "Category" in the UI.
*
* See enum HotkeyCategory for more information about the various hotkey categories
*/
HotkeyCategory category() const;
/**
* @brief Returns the action which describes what this Hotkey is meant to do
*
* For example, in the Window category there's a "showSearch" action which opens a search popup
*/
QString action() const;
bool validAction() const;
/**
* @brief Returns a list of arguments this hotkey has bound to it
*
* Some actions require a set of arguments that the user can provide, for example the "openTab" action takes an argument for which tab to switch to. can be a number or a word like next or previous
*/
std::vector<QString> arguments() const;
/**
* @brief Returns the display name of the hotkey
*
* For example, in the Split category there's a "showSearch" action that has a default hotkey with the name "default show search"
*/
QString name() const;
/**
* @brief Returns the user-friendly text representation of the hotkeys category
*
* Suitable for showing in the GUI.
* e.g. Split input box for HotkeyCategory::SplitInput
*/
QString getCategory() const;
/**
* @brief Returns the programmating key sequence of the hotkey
*
* The actual key codes required for the hotkey to trigger specifically on e.g CTRL+F5
*/
const QKeySequence &keySequence() const;
private:
HotkeyCategory category_;
QKeySequence keySequence_;
QString action_;
std::vector<QString> arguments_;
QString name_;
/**
* @brief Returns the programmatic context of the hotkey to help Qt decide how to apply the hotkey
*
* The returned value is based off the hotkeys given category
*/
Qt::ShortcutContext getContext() const;
friend class HotkeyController;
};
} // namespace chatterino
<|endoftext|> |
<commit_before>#include <cuda/api/device_properties.hpp>
#include <string>
#include <unordered_map>
#include <utility>
namespace cuda {
namespace device {
const char* compute_architecture_t::name(unsigned architecture_number)
{
static std::unordered_map<unsigned, std::string> arch_names =
{
{ 1, "Tesla" },
{ 2, "Fermi" },
{ 3, "Kepler" },
{ 5, "Maxwell" },
{ 6, "Pascal" },
{ 7, "Pascal" },
};
return arch_names.at(architecture_number).c_str();
// Will throw for invalid architecture numbers!
}
shared_memory_size_t compute_architecture_t::max_shared_memory_per_block() const
{
enum : shared_memory_size_t { KiB = 1024 };
// On some architectures, the shared memory / L1 balance is configurable,
// so you might not get the maxima here without making this configuration
// setting
static std::unordered_map<unsigned, unsigned> data =
{
{ 1, 16 * KiB },
{ 2, 48 * KiB },
{ 3, 48 * KiB },
{ 5, 64 * KiB },
{ 6, 64 * KiB },
{ 7, 96 * KiB },
// this is a speculative figure based on:
// https://devblogs.nvidia.com/parallelforall/inside-volta/
};
return data.at(major);
}
unsigned compute_architecture_t::max_resident_warps_per_processor() const {
static std::unordered_map<unsigned, unsigned> data =
{
{ 1, 24 },
{ 2, 48 },
{ 3, 64 },
{ 5, 64 },
{ 6, 64 },
{ 7, 64 },
};
return data.at(major);
}
unsigned compute_architecture_t::max_warp_schedulings_per_processor_cycle() const {
static std::unordered_map<unsigned, unsigned> data =
{
{ 1, 1 },
{ 2, 2 },
{ 3, 4 },
{ 5, 4 },
{ 6, 2 },
{ 7, 2 }, // speculation
};
return data.at(major);
}
unsigned compute_architecture_t::max_in_flight_threads_per_processor() const {
static std::unordered_map<unsigned, unsigned> data =
{
{ 1, 8 },
{ 2, 32 },
{ 3, 192 },
{ 5, 128 },
{ 6, 128 },
{ 7, 128 }, // speculation
};
return data.at(major);
}
shared_memory_size_t compute_capability_t::max_shared_memory_per_block() const
{
enum : shared_memory_size_t { KiB = 1024 };
static std::unordered_map<unsigned, unsigned> data =
{
{ 37, 112 * KiB },
{ 52, 96 * KiB },
{ 61, 96 * KiB },
};
auto cc = as_combined_number();
auto it = data.find(cc);
if (it != data.end()) { return it->second; }
return architecture().max_shared_memory_per_block();
}
unsigned compute_capability_t::max_resident_warps_per_processor() const {
static std::unordered_map<unsigned, unsigned> data =
{
{ 11, 24 },
{ 12, 32 },
{ 13, 32 },
};
auto cc = as_combined_number();
auto it = data.find(cc);
if (it != data.end()) { return it->second; }
return architecture().max_resident_warps_per_processor();
}
unsigned compute_capability_t::max_warp_schedulings_per_processor_cycle() const {
static std::unordered_map<unsigned, unsigned> data =
{
{ 61, 4 },
{ 62, 4 },
};
auto cc = as_combined_number();
auto it = data.find(cc);
if (it != data.end()) { return it->second; }
return architecture().max_warp_schedulings_per_processor_cycle();
}
unsigned compute_capability_t::max_in_flight_threads_per_processor() const {
static std::unordered_map<unsigned, unsigned> data =
{
{ 21, 48 },
{ 60, 64 },
};
auto cc = as_combined_number();
auto it = data.find(cc);
if (it != data.end()) { return it->second; }
return architecture().max_in_flight_threads_per_processor();
}
} // namespace device
} // namespace cuda
<commit_msg>Fixes #86<commit_after>#include <cuda/api/device_properties.hpp>
#include <string>
#include <unordered_map>
#include <utility>
// The values hard-coded in this file are based on the information from the following sources:
//
// https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html
// https://docs.nvidia.com/cuda/pascal-tuning-guide/index.html
// https://docs.nvidia.com/cuda/volta-tuning-guide/index.html
// https://docs.nvidia.com/cuda/turing-tuning-guide/index.html
// https://en.wikipedia.org/wiki/CUDA
//
// See specifically the sections on shared memory capacity in the Tuning and Programming
// guides -- it's a somewhat confusing issue.
namespace cuda {
namespace device {
const char* compute_architecture_t::name(unsigned architecture_number)
{
static std::unordered_map<unsigned, std::string> arch_names =
{
{ 1, "Tesla" },
{ 2, "Fermi" },
{ 3, "Kepler" },
{ 5, "Maxwell" },
{ 6, "Pascal" },
{ 7, "Volta/Turing" },
// Unfortunately, nVIDIA broke with the custom of having the numeric prefix
// designate the architecture name, with Turing (Compute Capability 7.5 _only_).
};
return arch_names.at(architecture_number).c_str();
// Will throw for invalid architecture numbers!
}
shared_memory_size_t compute_architecture_t::max_shared_memory_per_block() const
{
enum : shared_memory_size_t { KiB = 1024 };
// On some architectures, the shared memory / L1 balance is configurable,
// so you might not get the maxima here without making this configuration
// setting
static std::unordered_map<unsigned, unsigned> data =
{
{ 1, 16 * KiB },
{ 2, 48 * KiB },
{ 3, 48 * KiB },
{ 5, 48 * KiB },
{ 6, 48 * KiB },
{ 7, 96 * KiB },
// this is the Volta figure, Turing is different. Also, values above
// 48 require a call such as:
//
// cudaFuncSetAttribute(
// my_kernel,
// cudaFuncAttributePreferredSharedMemoryCarveout,
// cudaSharedmemCarveoutMaxShared
// );
//
// for details, see the CUDA C Programming Guide at:
// https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html
};
return data.at(major);
}
unsigned compute_architecture_t::max_resident_warps_per_processor() const {
static std::unordered_map<unsigned, unsigned> data =
{
{ 1, 24 },
{ 2, 48 },
{ 3, 64 },
{ 5, 64 },
{ 6, 64 },
{ 7, 64 }, // this is the Volta figure, Turing is different
};
return data.at(major);
}
unsigned compute_architecture_t::max_warp_schedulings_per_processor_cycle() const {
static std::unordered_map<unsigned, unsigned> data =
{
{ 1, 1 },
{ 2, 2 },
{ 3, 4 },
{ 5, 4 },
{ 6, 4 },
{ 7, 4 },
};
return data.at(major);
}
unsigned compute_architecture_t::max_in_flight_threads_per_processor() const {
static std::unordered_map<unsigned, unsigned> data =
{
{ 1, 8 },
{ 2, 32 },
{ 3, 192 },
{ 5, 128 },
{ 6, 128 },
{ 7, 128 }, // this is the Volta figure, Turing is different
};
return data.at(major);
}
shared_memory_size_t compute_capability_t::max_shared_memory_per_block() const
{
enum : shared_memory_size_t { KiB = 1024 };
static std::unordered_map<unsigned, unsigned> data =
{
{ 37, 112 * KiB },
{ 75, 64 * KiB },
// This is the Turing, rather than Volta, figure; but see
// the note regarding how to actually enable this
};
auto cc = as_combined_number();
auto it = data.find(cc);
if (it != data.end()) { return it->second; }
return architecture().max_shared_memory_per_block();
}
unsigned compute_capability_t::max_resident_warps_per_processor() const {
static std::unordered_map<unsigned, unsigned> data =
{
{ 11, 24 },
{ 12, 32 },
{ 13, 32 },
{ 75, 32 },
};
auto cc = as_combined_number();
auto it = data.find(cc);
if (it != data.end()) { return it->second; }
return architecture().max_resident_warps_per_processor();
}
unsigned compute_capability_t::max_warp_schedulings_per_processor_cycle() const {
static std::unordered_map<unsigned, unsigned> data =
{
{ 61, 4 },
{ 62, 4 },
};
auto cc = as_combined_number();
auto it = data.find(cc);
if (it != data.end()) { return it->second; }
return architecture().max_warp_schedulings_per_processor_cycle();
}
unsigned compute_capability_t::max_in_flight_threads_per_processor() const {
static std::unordered_map<unsigned, unsigned> data =
{
{ 21, 48 },
{ 60, 64 },
{ 75, 64 },
};
auto cc = as_combined_number();
auto it = data.find(cc);
if (it != data.end()) { return it->second; }
return architecture().max_in_flight_threads_per_processor();
}
} // namespace device
} // namespace cuda
<|endoftext|> |
<commit_before><commit_msg>Fix front_timestamp becoming less than start_timestamp<commit_after><|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2003 by *
* Unai Garro (ugarro@users.sourceforge.net) *
* Cyril Bosselut (bosselut@b1project.com) *
* Jason Kivlighn (jkivlighn@gmail.com) *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "selectrecipedialog.h"
#include <qsignalmapper.h>
#include <KTabWidget>
#include <qtooltip.h>
//Added by qt3to4:
#include <QGridLayout>
#include <QFrame>
#include <QPixmap>
#include <QLabel>
#include <QVBoxLayout>
#include <klocale.h>
#include <kdebug.h>
#include <kapplication.h>
#include <kprogressdialog.h>
#include <kmessagebox.h>
#include <kglobal.h>
#include <kconfig.h>
#include <kcursor.h>
#include <kvbox.h>
#include <KPushButton>
#include "advancedsearchdialog.h"
#include "datablocks/categorytree.h"
#include "backends/recipedb.h"
#include "datablocks/recipe.h"
#include "selectunitdialog.h"
#include "createelementdialog.h"
#include "recipefilter.h"
#include "widgets/recipelistview.h"
#include "widgets/categorylistview.h"
#include "widgets/categorycombobox.h"
SelectRecipeDialog::SelectRecipeDialog( QWidget *parent, RecipeDB* db )
: QWidget( parent )
{
//Store pointer to Recipe Database
database = db;
QVBoxLayout *tabLayout = new QVBoxLayout( this );
tabWidget = new KTabWidget( this );
tabWidget->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding ) );
tabLayout->addWidget( tabWidget );
basicSearchTab = new QFrame( this );
basicSearchTab->setFrameStyle( QFrame::NoFrame );
//basicSearchTab->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding ) );
//Design dialog
layout = new QGridLayout;
basicSearchTab->setLayout( layout );
layout->cellRect( 1, 1 );
layout->setMargin( 0 );
layout->setSpacing( 0 );
// Border Spacers
QSpacerItem* spacer_left = new QSpacerItem( 10, 10, QSizePolicy::Fixed, QSizePolicy::Minimum );
layout->addItem( spacer_left, 1, 0, 4, 0, 0 );
QSpacerItem* spacer_top = new QSpacerItem( 10, 10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem( spacer_top, 0, 1, 1, 4, 0 );
searchBar = new KHBox( basicSearchTab );
searchBar->setSpacing( 7 );
layout->addWidget( searchBar, 1, 1 );
searchLabel = new QLabel( searchBar );
searchLabel->setText( i18n( "Search:" ) );
searchLabel->setFixedWidth( searchLabel->fontMetrics().width( i18n( "Search:" ) ) + 5 );
searchBox = new KLineEdit( searchBar );
searchBox->setClearButtonShown( true );
connect( searchBox, SIGNAL(clearButtonClicked() ),this,SLOT( clearSearch() ) );
QSpacerItem* searchSpacer = new QSpacerItem( 10, 10, QSizePolicy::Fixed, QSizePolicy::Minimum );
layout->addItem( searchSpacer, 1, 2 );
#ifdef ENABLE_SLOW
categoryBox = new CategoryComboBox( basicSearchTab, database );
layout->addWidget( categoryBox, 1, 3 );
#endif
QSpacerItem* spacerFromSearchBar = new QSpacerItem( 10, 10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem( spacerFromSearchBar, 2, 1 );
recipeListView = new RecipeListView( basicSearchTab, database );
recipeListView->reload();
recipeListView->setSizePolicy( QSizePolicy::Ignored, QSizePolicy::Expanding );
layout->addWidget( recipeListView, 3, 1, 1, 3, 0 );
buttonBar = new KHBox( basicSearchTab );
layout->addWidget( buttonBar, 4, 1, 1, 3, 0 );
openButton = new KPushButton( buttonBar );
openButton->setText( i18n( "Open Recipe(s)" ) );
openButton->setDisabled( true );
openButton->setIcon( KIcon( "dialog-ok" ) );
editButton = new KPushButton( buttonBar );
editButton->setText( i18n( "Edit Recipe" ) );
editButton->setDisabled( true );
editButton->setIcon( KIcon( "document-edit" ) );
removeButton = new KPushButton( buttonBar );
removeButton->setText( i18n( "Delete" ) );
removeButton->setDisabled( true );
removeButton->setMaximumWidth( 100 );
removeButton->setIcon( KIcon("edit-delete-shred" ) );
tabWidget->insertTab( -1, basicSearchTab, i18n( "Basic" ) );
advancedSearch = new AdvancedSearchDialog( this, database );
tabWidget->insertTab( -1, advancedSearch, i18n( "Advanced" ) );
//Takes care of all recipe actions and provides a popup menu to 'recipeListView'
actionHandler = new RecipeActionsHandler( recipeListView, database );
recipeFilter = new RecipeFilter( recipeListView );
// Signals & Slots
connect( openButton, SIGNAL( clicked() ), actionHandler, SLOT( open() ) );
connect( this, SIGNAL( recipeSelected( bool ) ), openButton, SLOT( setEnabled( bool ) ) );
connect( editButton, SIGNAL( clicked() ), actionHandler, SLOT( edit() ) );
connect( this, SIGNAL( recipeSelected( bool ) ), editButton, SLOT( setEnabled( bool ) ) );
connect( removeButton, SIGNAL( clicked() ), actionHandler, SLOT( remove() ) );
connect( this, SIGNAL( recipeSelected( bool ) ), removeButton, SLOT( setEnabled( bool ) ) );
KConfigGroup config (KGlobal::config(), "Performance" );
if ( config.readEntry("SearchAsYouType",true) ) {
connect( searchBox, SIGNAL( returnPressed( const QString& ) ), recipeFilter, SLOT( filter( const QString& ) ) );
connect( searchBox, SIGNAL( textChanged( const QString& ) ), this, SLOT( ensurePopulated() ) );
connect( searchBox, SIGNAL( textChanged( const QString& ) ), recipeFilter, SLOT( filter( const QString& ) ) );
}
else {
connect( searchBox, SIGNAL( returnPressed( const QString& ) ), this, SLOT( ensurePopulated() ) );
connect( searchBox, SIGNAL( returnPressed( const QString& ) ), recipeFilter, SLOT( filter( const QString& ) ) );
}
connect( recipeListView, SIGNAL( selectionChanged() ), this, SLOT( haveSelectedItems() ) );
#ifdef ENABLE_SLOW
connect( recipeListView, SIGNAL( nextGroupLoaded() ), categoryBox, SLOT( loadNextGroup() ) );
connect( recipeListView, SIGNAL( prevGroupLoaded() ), categoryBox, SLOT( loadPrevGroup() ) );
connect( categoryBox, SIGNAL( activated( int ) ), this, SLOT( filterComboCategory( int ) ) );
#endif
connect( recipeListView, SIGNAL( nextGroupLoaded() ), SLOT( refilter() ) );
connect( recipeListView, SIGNAL( prevGroupLoaded() ), SLOT( refilter() ) );
connect( advancedSearch, SIGNAL( recipeSelected( int, int ) ), SIGNAL( recipeSelected( int, int ) ) );
connect( advancedSearch, SIGNAL( recipesSelected( const QList<int> &, int ) ), SIGNAL( recipesSelected( const QList<int> &, int ) ) );
connect( actionHandler, SIGNAL( recipeSelected( int, int ) ), SIGNAL( recipeSelected( int, int ) ) );
connect( actionHandler, SIGNAL( recipesSelected( const QList<int> &, int ) ), SIGNAL( recipesSelected( const QList<int> &, int ) ) );
}
SelectRecipeDialog::~SelectRecipeDialog()
{
delete recipeFilter;
}
void SelectRecipeDialog::clearSearch()
{
searchBox->setText( QString::null );
recipeFilter->filter( QString::null );
}
void SelectRecipeDialog::reload( ReloadFlags flag )
{
recipeListView->reload(flag);
#ifdef ENABLE_SLOW
categoryBox->reload();
filterComboCategory( categoryBox->currentIndex() );
#endif
}
void SelectRecipeDialog::refilter()
{
if ( !searchBox->text().isEmpty() ) {
ensurePopulated();
recipeFilter->filter(searchBox->text());
}
}
void SelectRecipeDialog::ensurePopulated()
{
recipeListView->populateAll();
}
void SelectRecipeDialog::haveSelectedItems()
{
if ( recipeListView->selectedItems().count() > 0 )
emit recipeSelected( true );
else
emit recipeSelected( false );
}
void SelectRecipeDialog::getCurrentRecipe( Recipe *recipe )
{
QList<Q3ListViewItem*> items = recipeListView->selectedItems();
if ( items.count() == 1 && items.at(0)->rtti() == 1000 ) {
RecipeListItem * recipe_it = ( RecipeListItem* )items.at(0);
database->loadRecipe( recipe, RecipeDB::All, recipe_it->recipeID() );
}
}
void SelectRecipeDialog::filterComboCategory( int row )
{
recipeListView->populateAll(); //TODO: this would be faster if we didn't need to load everything first
kDebug() << "I got row " << row << "\n";
//First get the category ID corresponding to this combo row
int categoryID = categoryBox->id( row );
//Now filter
recipeFilter->filterCategory( categoryID ); // if categoryID==-1 doesn't filter
recipeFilter->filter( searchBox->text() );
if ( categoryID != -1 ) {
Q3ListViewItemIterator it( recipeListView );
while ( it.current() ) {
Q3ListViewItem *item = it.current();
if ( item->isVisible() ) {
item->setOpen( true ); //will only open if already populated
//(could be the selected category's parent
if ( !item->firstChild() ) {
recipeListView->open( item ); //populates and opens the selected category
break;
}
}
++it;
}
}
}
RecipeActionsHandler* SelectRecipeDialog::getActionsHandler() const
{
if ( tabWidget->currentWidget() == basicSearchTab )
return actionHandler;
else
return advancedSearch->actionHandler;
}
#include "selectrecipedialog.moc"
<commit_msg>Removed uneccesary includes.<commit_after>/***************************************************************************
* Copyright (C) 2003 by *
* Unai Garro (ugarro@users.sourceforge.net) *
* Cyril Bosselut (bosselut@b1project.com) *
* Jason Kivlighn (jkivlighn@gmail.com) *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "selectrecipedialog.h"
#include <KTabWidget>
//Added by qt3to4:
#include <QGridLayout>
#include <QFrame>
#include <QPixmap>
#include <QLabel>
#include <QVBoxLayout>
#include <klocale.h>
#include <kdebug.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kvbox.h>
#include <KPushButton>
#include "advancedsearchdialog.h"
#include "datablocks/categorytree.h"
#include "backends/recipedb.h"
#include "datablocks/recipe.h"
#include "selectunitdialog.h"
#include "createelementdialog.h"
#include "recipefilter.h"
#include "widgets/recipelistview.h"
#include "widgets/categorylistview.h"
#include "widgets/categorycombobox.h"
SelectRecipeDialog::SelectRecipeDialog( QWidget *parent, RecipeDB* db )
: QWidget( parent )
{
//Store pointer to Recipe Database
database = db;
QVBoxLayout *tabLayout = new QVBoxLayout( this );
tabWidget = new KTabWidget( this );
tabWidget->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding ) );
tabLayout->addWidget( tabWidget );
basicSearchTab = new QFrame( this );
basicSearchTab->setFrameStyle( QFrame::NoFrame );
//basicSearchTab->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding ) );
//Design dialog
layout = new QGridLayout;
basicSearchTab->setLayout( layout );
layout->cellRect( 1, 1 );
layout->setMargin( 0 );
layout->setSpacing( 0 );
// Border Spacers
QSpacerItem* spacer_left = new QSpacerItem( 10, 10, QSizePolicy::Fixed, QSizePolicy::Minimum );
layout->addItem( spacer_left, 1, 0, 4, 0, 0 );
QSpacerItem* spacer_top = new QSpacerItem( 10, 10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem( spacer_top, 0, 1, 1, 4, 0 );
searchBar = new KHBox( basicSearchTab );
searchBar->setSpacing( 7 );
layout->addWidget( searchBar, 1, 1 );
searchLabel = new QLabel( searchBar );
searchLabel->setText( i18n( "Search:" ) );
searchLabel->setFixedWidth( searchLabel->fontMetrics().width( i18n( "Search:" ) ) + 5 );
searchBox = new KLineEdit( searchBar );
searchBox->setClearButtonShown( true );
connect( searchBox, SIGNAL(clearButtonClicked() ),this,SLOT( clearSearch() ) );
QSpacerItem* searchSpacer = new QSpacerItem( 10, 10, QSizePolicy::Fixed, QSizePolicy::Minimum );
layout->addItem( searchSpacer, 1, 2 );
#ifdef ENABLE_SLOW
categoryBox = new CategoryComboBox( basicSearchTab, database );
layout->addWidget( categoryBox, 1, 3 );
#endif
QSpacerItem* spacerFromSearchBar = new QSpacerItem( 10, 10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem( spacerFromSearchBar, 2, 1 );
recipeListView = new RecipeListView( basicSearchTab, database );
recipeListView->reload();
recipeListView->setSizePolicy( QSizePolicy::Ignored, QSizePolicy::Expanding );
layout->addWidget( recipeListView, 3, 1, 1, 3, 0 );
buttonBar = new KHBox( basicSearchTab );
layout->addWidget( buttonBar, 4, 1, 1, 3, 0 );
openButton = new KPushButton( buttonBar );
openButton->setText( i18n( "Open Recipe(s)" ) );
openButton->setDisabled( true );
openButton->setIcon( KIcon( "dialog-ok" ) );
editButton = new KPushButton( buttonBar );
editButton->setText( i18n( "Edit Recipe" ) );
editButton->setDisabled( true );
editButton->setIcon( KIcon( "document-edit" ) );
removeButton = new KPushButton( buttonBar );
removeButton->setText( i18n( "Delete" ) );
removeButton->setDisabled( true );
removeButton->setMaximumWidth( 100 );
removeButton->setIcon( KIcon("edit-delete-shred" ) );
tabWidget->insertTab( -1, basicSearchTab, i18n( "Basic" ) );
advancedSearch = new AdvancedSearchDialog( this, database );
tabWidget->insertTab( -1, advancedSearch, i18n( "Advanced" ) );
//Takes care of all recipe actions and provides a popup menu to 'recipeListView'
actionHandler = new RecipeActionsHandler( recipeListView, database );
recipeFilter = new RecipeFilter( recipeListView );
// Signals & Slots
connect( openButton, SIGNAL( clicked() ), actionHandler, SLOT( open() ) );
connect( this, SIGNAL( recipeSelected( bool ) ), openButton, SLOT( setEnabled( bool ) ) );
connect( editButton, SIGNAL( clicked() ), actionHandler, SLOT( edit() ) );
connect( this, SIGNAL( recipeSelected( bool ) ), editButton, SLOT( setEnabled( bool ) ) );
connect( removeButton, SIGNAL( clicked() ), actionHandler, SLOT( remove() ) );
connect( this, SIGNAL( recipeSelected( bool ) ), removeButton, SLOT( setEnabled( bool ) ) );
KConfigGroup config (KGlobal::config(), "Performance" );
if ( config.readEntry("SearchAsYouType",true) ) {
connect( searchBox, SIGNAL( returnPressed( const QString& ) ), recipeFilter, SLOT( filter( const QString& ) ) );
connect( searchBox, SIGNAL( textChanged( const QString& ) ), this, SLOT( ensurePopulated() ) );
connect( searchBox, SIGNAL( textChanged( const QString& ) ), recipeFilter, SLOT( filter( const QString& ) ) );
}
else {
connect( searchBox, SIGNAL( returnPressed( const QString& ) ), this, SLOT( ensurePopulated() ) );
connect( searchBox, SIGNAL( returnPressed( const QString& ) ), recipeFilter, SLOT( filter( const QString& ) ) );
}
connect( recipeListView, SIGNAL( selectionChanged() ), this, SLOT( haveSelectedItems() ) );
#ifdef ENABLE_SLOW
connect( recipeListView, SIGNAL( nextGroupLoaded() ), categoryBox, SLOT( loadNextGroup() ) );
connect( recipeListView, SIGNAL( prevGroupLoaded() ), categoryBox, SLOT( loadPrevGroup() ) );
connect( categoryBox, SIGNAL( activated( int ) ), this, SLOT( filterComboCategory( int ) ) );
#endif
connect( recipeListView, SIGNAL( nextGroupLoaded() ), SLOT( refilter() ) );
connect( recipeListView, SIGNAL( prevGroupLoaded() ), SLOT( refilter() ) );
connect( advancedSearch, SIGNAL( recipeSelected( int, int ) ), SIGNAL( recipeSelected( int, int ) ) );
connect( advancedSearch, SIGNAL( recipesSelected( const QList<int> &, int ) ), SIGNAL( recipesSelected( const QList<int> &, int ) ) );
connect( actionHandler, SIGNAL( recipeSelected( int, int ) ), SIGNAL( recipeSelected( int, int ) ) );
connect( actionHandler, SIGNAL( recipesSelected( const QList<int> &, int ) ), SIGNAL( recipesSelected( const QList<int> &, int ) ) );
}
SelectRecipeDialog::~SelectRecipeDialog()
{
delete recipeFilter;
}
void SelectRecipeDialog::clearSearch()
{
searchBox->setText( QString::null );
recipeFilter->filter( QString::null );
}
void SelectRecipeDialog::reload( ReloadFlags flag )
{
recipeListView->reload(flag);
#ifdef ENABLE_SLOW
categoryBox->reload();
filterComboCategory( categoryBox->currentIndex() );
#endif
}
void SelectRecipeDialog::refilter()
{
if ( !searchBox->text().isEmpty() ) {
ensurePopulated();
recipeFilter->filter(searchBox->text());
}
}
void SelectRecipeDialog::ensurePopulated()
{
recipeListView->populateAll();
}
void SelectRecipeDialog::haveSelectedItems()
{
if ( recipeListView->selectedItems().count() > 0 )
emit recipeSelected( true );
else
emit recipeSelected( false );
}
void SelectRecipeDialog::getCurrentRecipe( Recipe *recipe )
{
QList<Q3ListViewItem*> items = recipeListView->selectedItems();
if ( items.count() == 1 && items.at(0)->rtti() == 1000 ) {
RecipeListItem * recipe_it = ( RecipeListItem* )items.at(0);
database->loadRecipe( recipe, RecipeDB::All, recipe_it->recipeID() );
}
}
void SelectRecipeDialog::filterComboCategory( int row )
{
recipeListView->populateAll(); //TODO: this would be faster if we didn't need to load everything first
kDebug() << "I got row " << row << "\n";
//First get the category ID corresponding to this combo row
int categoryID = categoryBox->id( row );
//Now filter
recipeFilter->filterCategory( categoryID ); // if categoryID==-1 doesn't filter
recipeFilter->filter( searchBox->text() );
if ( categoryID != -1 ) {
Q3ListViewItemIterator it( recipeListView );
while ( it.current() ) {
Q3ListViewItem *item = it.current();
if ( item->isVisible() ) {
item->setOpen( true ); //will only open if already populated
//(could be the selected category's parent
if ( !item->firstChild() ) {
recipeListView->open( item ); //populates and opens the selected category
break;
}
}
++it;
}
}
}
RecipeActionsHandler* SelectRecipeDialog::getActionsHandler() const
{
if ( tabWidget->currentWidget() == basicSearchTab )
return actionHandler;
else
return advancedSearch->actionHandler;
}
#include "selectrecipedialog.moc"
<|endoftext|> |
<commit_before>/* This file is part of the Pangolin Project.
* http://github.com/stevenlovegrove/Pangolin
*
* Copyright (c) 2011 Steven Lovegrove
*
* 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 <pangolin/platform.h>
#include <pangolin/gl/glinclude.h>
#include <pangolin/display/display.h>
#include <pangolin/display/display_internal.h>
#include <windowsx.h>
namespace pangolin
{
extern __thread PangolinGl* context;
const char *className = "Pangolin";
WNDCLASS wndClass;
HWND hWnd;
HDC hDC;
HGLRC hGLRC;
HPALETTE hPalette;
void
setupPixelFormat(HDC hDC)
{
PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR), /* size */
1, /* version */
PFD_SUPPORT_OPENGL |
PFD_DRAW_TO_WINDOW |
PFD_DOUBLEBUFFER, /* support double-buffering */
PFD_TYPE_RGBA, /* color type */
24, /* prefered color depth */
0, 0, 0, 0, 0, 0, /* color bits (ignored) */
8, /* alpha bits */
0, /* alpha shift (ignored) */
0, /* no accumulation buffer */
0, 0, 0, 0, /* accum bits (ignored) */
32, /* depth buffer */
0, /* no stencil buffer */
0, /* no auxiliary buffers */
PFD_MAIN_PLANE, /* main layer */
0, /* reserved */
0, 0, 0, /* no layer, visible, damage masks */
};
int pixelFormat;
pixelFormat = ChoosePixelFormat(hDC, &pfd);
if (pixelFormat == 0) {
MessageBox(WindowFromDC(hDC), "ChoosePixelFormat failed.", "Error",
MB_ICONERROR | MB_OK);
exit(1);
}
if (SetPixelFormat(hDC, pixelFormat, &pfd) != TRUE) {
MessageBox(WindowFromDC(hDC), "SetPixelFormat failed.", "Error",
MB_ICONERROR | MB_OK);
exit(1);
}
}
void
setupPalette(HDC hDC)
{
int pixelFormat = GetPixelFormat(hDC);
PIXELFORMATDESCRIPTOR pfd;
LOGPALETTE* pPal;
int paletteSize;
DescribePixelFormat(hDC, pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
if (pfd.dwFlags & PFD_NEED_PALETTE) {
paletteSize = 1 << pfd.cColorBits;
}
else {
return;
}
pPal = (LOGPALETTE*)
malloc(sizeof(LOGPALETTE) + paletteSize * sizeof(PALETTEENTRY));
pPal->palVersion = 0x300;
pPal->palNumEntries = paletteSize;
/* build a simple RGB color palette */
{
int redMask = (1 << pfd.cRedBits) - 1;
int greenMask = (1 << pfd.cGreenBits) - 1;
int blueMask = (1 << pfd.cBlueBits) - 1;
int i;
for (i = 0; i<paletteSize; ++i) {
pPal->palPalEntry[i].peRed =
(((i >> pfd.cRedShift) & redMask) * 255) / redMask;
pPal->palPalEntry[i].peGreen =
(((i >> pfd.cGreenShift) & greenMask) * 255) / greenMask;
pPal->palPalEntry[i].peBlue =
(((i >> pfd.cBlueShift) & blueMask) * 255) / blueMask;
pPal->palPalEntry[i].peFlags = 0;
}
}
hPalette = CreatePalette(pPal);
free(pPal);
if (hPalette) {
SelectPalette(hDC, hPalette, FALSE);
RealizePalette(hDC);
}
}
unsigned char ConvertWinKeyToPangoKey(unsigned char key)
{
switch (key)
{
case VK_F1 : return PANGO_SPECIAL + PANGO_KEY_F1;
case VK_F2 : return PANGO_SPECIAL + PANGO_KEY_F2;
case VK_F3 : return PANGO_SPECIAL + PANGO_KEY_F3;
case VK_F4 : return PANGO_SPECIAL + PANGO_KEY_F4;
case VK_F5 : return PANGO_SPECIAL + PANGO_KEY_F5;
case VK_F6 : return PANGO_SPECIAL + PANGO_KEY_F6;
case VK_F7 : return PANGO_SPECIAL + PANGO_KEY_F7;
case VK_F8 : return PANGO_SPECIAL + PANGO_KEY_F8;
case VK_F9 : return PANGO_SPECIAL + PANGO_KEY_F9;
case VK_F10 : return PANGO_SPECIAL + PANGO_KEY_F10;
case VK_F11 : return PANGO_SPECIAL + PANGO_KEY_F11;
case VK_F12 : return PANGO_SPECIAL + PANGO_KEY_F12;
case VK_LEFT : return PANGO_SPECIAL + PANGO_KEY_LEFT;
case VK_UP : return PANGO_SPECIAL + PANGO_KEY_UP;
case VK_RIGHT : return PANGO_SPECIAL + PANGO_KEY_RIGHT;
case VK_DOWN : return PANGO_SPECIAL + PANGO_KEY_DOWN;
//case VK_ : return PANGO_SPECIAL + PANGO_KEY_PAGE_UP;
//case VK_ : return PANGO_SPECIAL + PANGO_KEY_PAGE_DOWN;
case VK_HOME : return PANGO_SPECIAL + PANGO_KEY_HOME;
case VK_END : return PANGO_SPECIAL + PANGO_KEY_END;
case VK_INSERT : return PANGO_SPECIAL + PANGO_KEY_INSERT;
default: return key;
}
}
LRESULT APIENTRY
WndProc(
HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam)
{
switch (message) {
case WM_CREATE:
/* initialize OpenGL rendering */
hDC = GetDC(hWnd);
setupPixelFormat(hDC);
setupPalette(hDC);
hGLRC = wglCreateContext(hDC);
wglMakeCurrent(hDC, hGLRC);
//init();
return 0;
case WM_DESTROY:
/* finish OpenGL rendering */
if (hGLRC) {
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hGLRC);
}
if (hPalette) {
DeleteObject(hPalette);
}
ReleaseDC(hWnd, hDC);
PostQuitMessage(0);
return 0;
case WM_SIZE:
/* track window size changes */
if (hGLRC) {
process::Resize((int)LOWORD(lParam), (int)HIWORD(lParam));
return 0;
}
case WM_PALETTECHANGED:
/* realize palette if this is *not* the current window */
if (hGLRC && hPalette && (HWND)wParam != hWnd) {
UnrealizeObject(hPalette);
SelectPalette(hDC, hPalette, FALSE);
RealizePalette(hDC);
//redraw();
break;
}
break;
case WM_QUERYNEWPALETTE:
/* realize palette if this is the current window */
if (hGLRC && hPalette) {
UnrealizeObject(hPalette);
SelectPalette(hDC, hPalette, FALSE);
RealizePalette(hDC);
//redraw();
return TRUE;
}
break;
case WM_PAINT:
{
//PAINTSTRUCT ps;
//BeginPaint(hWnd, &ps);
//if (hGLRC) {
// redraw();
//}
//EndPaint(hWnd, &ps);
//return 0;
}
break;
case WM_KEYDOWN:
process::Keyboard(ConvertWinKeyToPangoKey((unsigned char)wParam), 1, 1);
return 0;
case WM_KEYUP:
process::KeyboardUp(ConvertWinKeyToPangoKey((unsigned char)wParam), 1, 1);
return 0;
case WM_LBUTTONDOWN:
process::Mouse(0, 0, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_MBUTTONDOWN:
process::Mouse(1, 0, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_RBUTTONDOWN:
process::Mouse(2, 0, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_LBUTTONUP:
process::Mouse(0, 1, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_MBUTTONUP:
process::Mouse(1, 1, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_RBUTTONUP:
process::Mouse(2, 1, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_MOUSEMOVE:
if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) ) {
process::MouseMotion(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
} else{
process::PassiveMouseMotion(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
}
return 0;
case WM_MOUSEWHEEL:
process::Scroll(0.0f, GET_WHEEL_DELTA_WPARAM(wParam)/20.0f);
return 0;
default:
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
void ProcessQueuedWinMessages()
{
MSG msg;
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
if (msg.message == WM_QUIT) {
pangolin::Quit();
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
void FinishFrame()
{
RenderViews();
PostRender();
SwapBuffers(hDC);
ProcessQueuedWinMessages();
}
void CreateWindowAndBind(std::string window_title, int w, int h )
{
// Create Pangolin GL Context
BindToContext(window_title);
context->is_double_buffered = true;
// Create Window
const HMODULE hCurrentInst = GetModuleHandle(0);
const int nCmdShow = SW_SHOW;
/* register window class */
wndClass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
wndClass.lpfnWndProc = WndProc;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;
wndClass.hInstance = hCurrentInst;
wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wndClass.lpszMenuName = NULL;
wndClass.lpszClassName = className;
RegisterClass(&wndClass);
hWnd = CreateWindow(
className, window_title.c_str(),
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
0, 0, w, h,
NULL, NULL, hCurrentInst, NULL);
// Display Window
ShowWindow(hWnd, nCmdShow);
//UpdateWindow(hWnd);
// Process Messages
ProcessQueuedWinMessages();
glewInit();
}
void StartFullScreen() {
LONG dwExStyle = GetWindowLong(hWnd, GWL_EXSTYLE)
& ~(WS_EX_DLGMODALFRAME | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE);
LONG dwStyle = GetWindowLong(hWnd, GWL_STYLE)
& ~(WS_CAPTION | WS_THICKFRAME | WS_MINIMIZE | WS_MAXIMIZE | WS_SYSMENU);
SetWindowLong(hWnd, GWL_EXSTYLE, dwExStyle);
SetWindowLong(hWnd, GWL_STYLE, dwStyle);
GLint prev[2];
std::memcpy(prev, context->windowed_size, sizeof(prev));
ShowWindow(hWnd, SW_SHOWMAXIMIZED);
std::memcpy(context->windowed_size, prev, sizeof(prev));
}
void StopFullScreen() {
ChangeDisplaySettings(NULL, 0);
ShowCursor(TRUE);
LONG dwExStyle = GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
LONG dwStyle = GetWindowLong(hWnd, GWL_STYLE) | WS_OVERLAPPEDWINDOW;
SetWindowLong(hWnd, GWL_EXSTYLE, dwExStyle);
SetWindowLong(hWnd, GWL_STYLE, dwStyle);
SetWindowPos(hWnd,
HWND_TOP,
0, 0,
context->windowed_size[0], context->windowed_size[1],
SWP_FRAMECHANGED);
}
void SetFullscreen(bool fullscreen)
{
if( fullscreen != context->is_fullscreen )
{
if(fullscreen) {
StartFullScreen();
}else{
StopFullScreen();
}
context->is_fullscreen = fullscreen;
}
}
void PangolinPlatformInit(PangolinGl& /*context*/)
{
}
void PangolinPlatformDeinit(PangolinGl& /*context*/)
{
}
}
<commit_msg>Windows: Improve key input handling.<commit_after>/* This file is part of the Pangolin Project.
* http://github.com/stevenlovegrove/Pangolin
*
* Copyright (c) 2011 Steven Lovegrove
*
* 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 <pangolin/platform.h>
#include <pangolin/gl/glinclude.h>
#include <pangolin/display/display.h>
#include <pangolin/display/display_internal.h>
#include <windowsx.h>
namespace pangolin
{
extern __thread PangolinGl* context;
const char *className = "Pangolin";
WNDCLASS wndClass;
HWND hWnd;
HDC hDC;
HGLRC hGLRC;
HPALETTE hPalette;
void
setupPixelFormat(HDC hDC)
{
PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR), /* size */
1, /* version */
PFD_SUPPORT_OPENGL |
PFD_DRAW_TO_WINDOW |
PFD_DOUBLEBUFFER, /* support double-buffering */
PFD_TYPE_RGBA, /* color type */
24, /* prefered color depth */
0, 0, 0, 0, 0, 0, /* color bits (ignored) */
8, /* alpha bits */
0, /* alpha shift (ignored) */
0, /* no accumulation buffer */
0, 0, 0, 0, /* accum bits (ignored) */
32, /* depth buffer */
0, /* no stencil buffer */
0, /* no auxiliary buffers */
PFD_MAIN_PLANE, /* main layer */
0, /* reserved */
0, 0, 0, /* no layer, visible, damage masks */
};
int pixelFormat;
pixelFormat = ChoosePixelFormat(hDC, &pfd);
if (pixelFormat == 0) {
MessageBox(WindowFromDC(hDC), "ChoosePixelFormat failed.", "Error",
MB_ICONERROR | MB_OK);
exit(1);
}
if (SetPixelFormat(hDC, pixelFormat, &pfd) != TRUE) {
MessageBox(WindowFromDC(hDC), "SetPixelFormat failed.", "Error",
MB_ICONERROR | MB_OK);
exit(1);
}
}
void
setupPalette(HDC hDC)
{
int pixelFormat = GetPixelFormat(hDC);
PIXELFORMATDESCRIPTOR pfd;
LOGPALETTE* pPal;
int paletteSize;
DescribePixelFormat(hDC, pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
if (pfd.dwFlags & PFD_NEED_PALETTE) {
paletteSize = 1 << pfd.cColorBits;
}
else {
return;
}
pPal = (LOGPALETTE*)
malloc(sizeof(LOGPALETTE) + paletteSize * sizeof(PALETTEENTRY));
pPal->palVersion = 0x300;
pPal->palNumEntries = paletteSize;
/* build a simple RGB color palette */
{
int redMask = (1 << pfd.cRedBits) - 1;
int greenMask = (1 << pfd.cGreenBits) - 1;
int blueMask = (1 << pfd.cBlueBits) - 1;
int i;
for (i = 0; i<paletteSize; ++i) {
pPal->palPalEntry[i].peRed =
(((i >> pfd.cRedShift) & redMask) * 255) / redMask;
pPal->palPalEntry[i].peGreen =
(((i >> pfd.cGreenShift) & greenMask) * 255) / greenMask;
pPal->palPalEntry[i].peBlue =
(((i >> pfd.cBlueShift) & blueMask) * 255) / blueMask;
pPal->palPalEntry[i].peFlags = 0;
}
}
hPalette = CreatePalette(pPal);
free(pPal);
if (hPalette) {
SelectPalette(hDC, hPalette, FALSE);
RealizePalette(hDC);
}
}
unsigned char GetPangoKey(WPARAM wParam, LPARAM lParam)
{
switch (wParam)
{
case VK_F1: return PANGO_SPECIAL + PANGO_KEY_F1;
case VK_F2: return PANGO_SPECIAL + PANGO_KEY_F2;
case VK_F3: return PANGO_SPECIAL + PANGO_KEY_F3;
case VK_F4: return PANGO_SPECIAL + PANGO_KEY_F4;
case VK_F5: return PANGO_SPECIAL + PANGO_KEY_F5;
case VK_F6: return PANGO_SPECIAL + PANGO_KEY_F6;
case VK_F7: return PANGO_SPECIAL + PANGO_KEY_F7;
case VK_F8: return PANGO_SPECIAL + PANGO_KEY_F8;
case VK_F9: return PANGO_SPECIAL + PANGO_KEY_F9;
case VK_F10: return PANGO_SPECIAL + PANGO_KEY_F10;
case VK_F11: return PANGO_SPECIAL + PANGO_KEY_F11;
case VK_F12: return PANGO_SPECIAL + PANGO_KEY_F12;
case VK_LEFT: return PANGO_SPECIAL + PANGO_KEY_LEFT;
case VK_UP: return PANGO_SPECIAL + PANGO_KEY_UP;
case VK_RIGHT: return PANGO_SPECIAL + PANGO_KEY_RIGHT;
case VK_DOWN: return PANGO_SPECIAL + PANGO_KEY_DOWN;
case VK_HOME: return PANGO_SPECIAL + PANGO_KEY_HOME;
case VK_END: return PANGO_SPECIAL + PANGO_KEY_END;
case VK_INSERT: return PANGO_SPECIAL + PANGO_KEY_INSERT;
case VK_DELETE: return 127;
default:
const int lBufferSize = 2;
WCHAR lBuffer[lBufferSize];
BYTE State[256];
GetKeyboardState(State);
const UINT scanCode = (lParam >> 8) & 0xFFFFFF00;
if( ToUnicode(wParam, scanCode, State, lBuffer, lBufferSize, 0) >=1 ) {
return lBuffer[0];
}
}
return 0;
}
LRESULT APIENTRY
WndProc(
HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam)
{
switch (message) {
case WM_CREATE:
/* initialize OpenGL rendering */
hDC = GetDC(hWnd);
setupPixelFormat(hDC);
setupPalette(hDC);
hGLRC = wglCreateContext(hDC);
wglMakeCurrent(hDC, hGLRC);
//init();
return 0;
case WM_DESTROY:
/* finish OpenGL rendering */
if (hGLRC) {
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hGLRC);
}
if (hPalette) {
DeleteObject(hPalette);
}
ReleaseDC(hWnd, hDC);
PostQuitMessage(0);
return 0;
case WM_SIZE:
/* track window size changes */
if (hGLRC) {
process::Resize((int)LOWORD(lParam), (int)HIWORD(lParam));
return 0;
}
case WM_PALETTECHANGED:
/* realize palette if this is *not* the current window */
if (hGLRC && hPalette && (HWND)wParam != hWnd) {
UnrealizeObject(hPalette);
SelectPalette(hDC, hPalette, FALSE);
RealizePalette(hDC);
//redraw();
break;
}
break;
case WM_QUERYNEWPALETTE:
/* realize palette if this is the current window */
if (hGLRC && hPalette) {
UnrealizeObject(hPalette);
SelectPalette(hDC, hPalette, FALSE);
RealizePalette(hDC);
//redraw();
return TRUE;
}
break;
case WM_PAINT:
{
//PAINTSTRUCT ps;
//BeginPaint(hWnd, &ps);
//if (hGLRC) {
// redraw();
//}
//EndPaint(hWnd, &ps);
//return 0;
}
break;
case WM_KEYDOWN:
{
unsigned char key = GetPangoKey(wParam, lParam);
if(key>0) process::Keyboard(key, 1, 1);
return 0;
}
case WM_KEYUP:
{
unsigned char key = GetPangoKey(wParam, lParam);
if (key>0) process::KeyboardUp(key, 1, 1);
return 0;
}
case WM_LBUTTONDOWN:
process::Mouse(0, 0, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_MBUTTONDOWN:
process::Mouse(1, 0, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_RBUTTONDOWN:
process::Mouse(2, 0, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_LBUTTONUP:
process::Mouse(0, 1, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_MBUTTONUP:
process::Mouse(1, 1, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_RBUTTONUP:
process::Mouse(2, 1, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_MOUSEMOVE:
if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) ) {
process::MouseMotion(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
} else{
process::PassiveMouseMotion(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
}
return 0;
case WM_MOUSEWHEEL:
process::Scroll(0.0f, GET_WHEEL_DELTA_WPARAM(wParam)/20.0f);
return 0;
default:
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
void ProcessQueuedWinMessages()
{
MSG msg;
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
if (msg.message == WM_QUIT) {
pangolin::Quit();
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
void FinishFrame()
{
RenderViews();
PostRender();
SwapBuffers(hDC);
ProcessQueuedWinMessages();
}
void CreateWindowAndBind(std::string window_title, int w, int h )
{
// Create Pangolin GL Context
BindToContext(window_title);
context->is_double_buffered = true;
// Create Window
const HMODULE hCurrentInst = GetModuleHandle(0);
const int nCmdShow = SW_SHOW;
/* register window class */
wndClass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
wndClass.lpfnWndProc = WndProc;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;
wndClass.hInstance = hCurrentInst;
wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wndClass.lpszMenuName = NULL;
wndClass.lpszClassName = className;
RegisterClass(&wndClass);
hWnd = CreateWindow(
className, window_title.c_str(),
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
0, 0, w, h,
NULL, NULL, hCurrentInst, NULL);
// Display Window
ShowWindow(hWnd, nCmdShow);
//UpdateWindow(hWnd);
// Process Messages
ProcessQueuedWinMessages();
glewInit();
}
void StartFullScreen() {
LONG dwExStyle = GetWindowLong(hWnd, GWL_EXSTYLE)
& ~(WS_EX_DLGMODALFRAME | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE);
LONG dwStyle = GetWindowLong(hWnd, GWL_STYLE)
& ~(WS_CAPTION | WS_THICKFRAME | WS_MINIMIZE | WS_MAXIMIZE | WS_SYSMENU);
SetWindowLong(hWnd, GWL_EXSTYLE, dwExStyle);
SetWindowLong(hWnd, GWL_STYLE, dwStyle);
GLint prev[2];
std::memcpy(prev, context->windowed_size, sizeof(prev));
ShowWindow(hWnd, SW_SHOWMAXIMIZED);
std::memcpy(context->windowed_size, prev, sizeof(prev));
}
void StopFullScreen() {
ChangeDisplaySettings(NULL, 0);
ShowCursor(TRUE);
LONG dwExStyle = GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
LONG dwStyle = GetWindowLong(hWnd, GWL_STYLE) | WS_OVERLAPPEDWINDOW;
SetWindowLong(hWnd, GWL_EXSTYLE, dwExStyle);
SetWindowLong(hWnd, GWL_STYLE, dwStyle);
SetWindowPos(hWnd,
HWND_TOP,
0, 0,
context->windowed_size[0], context->windowed_size[1],
SWP_FRAMECHANGED);
}
void SetFullscreen(bool fullscreen)
{
if( fullscreen != context->is_fullscreen )
{
if(fullscreen) {
StartFullScreen();
}else{
StopFullScreen();
}
context->is_fullscreen = fullscreen;
}
}
void PangolinPlatformInit(PangolinGl& /*context*/)
{
}
void PangolinPlatformDeinit(PangolinGl& /*context*/)
{
}
}
<|endoftext|> |
<commit_before>
#include "bmi160.hpp"
#include <board_config.h>
/** driver 'main' command */
extern "C" { __EXPORT int bmi160_main(int argc, char *argv[]); }
/**
* Local functions in support of the shell command.
*/
namespace bmi160
{
BMI160 *g_dev_int; // on internal bus
BMI160 *g_dev_ext; // on external bus
void start(bool, enum Rotation);
void stop(bool);
void test(bool);
void reset(bool);
void info(bool);
void regdump(bool);
void testerror(bool);
void usage();
/**
* Start the driver.
*
* This function only returns if the driver is up and running
* or failed to detect the sensor.
*/
void
start(bool external_bus, enum Rotation rotation)
{
int fd;
BMI160 **g_dev_ptr = external_bus ? &g_dev_ext : &g_dev_int;
const char *path_accel = external_bus ? BMI160_DEVICE_PATH_ACCEL_EXT : BMI160_DEVICE_PATH_ACCEL;
const char *path_gyro = external_bus ? BMI160_DEVICE_PATH_GYRO_EXT : BMI160_DEVICE_PATH_GYRO;
if (*g_dev_ptr != nullptr)
/* if already started, the still command succeeded */
{
errx(0, "already started");
}
/* create the driver */
if (external_bus) {
#if defined(PX4_SPI_BUS_EXT) && defined(PX4_SPIDEV_EXT_BMI)
*g_dev_ptr = new BMI160(PX4_SPI_BUS_EXT, path_accel, path_gyro, (spi_dev_e)PX4_SPIDEV_EXT_BMI, rotation);
#else
errx(0, "External SPI not available");
#endif
} else {
*g_dev_ptr = new BMI160(PX4_SPI_BUS_SENSORS, path_accel, path_gyro, (spi_dev_e)PX4_SPIDEV_BMI, rotation);
}
if (*g_dev_ptr == nullptr) {
goto fail;
}
if (OK != (*g_dev_ptr)->init()) {
goto fail;
}
/* set the poll rate to default, starts automatic data collection */
fd = open(path_accel, O_RDONLY);
if (fd < 0) {
goto fail;
}
if (ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0) {
goto fail;
}
close(fd);
exit(0);
fail:
if (*g_dev_ptr != nullptr) {
delete(*g_dev_ptr);
*g_dev_ptr = nullptr;
}
errx(1, "driver start failed");
}
void
stop(bool external_bus)
{
BMI160 **g_dev_ptr = external_bus ? &g_dev_ext : &g_dev_int;
if (*g_dev_ptr != nullptr) {
delete *g_dev_ptr;
*g_dev_ptr = nullptr;
} else {
/* warn, but not an error */
warnx("already stopped.");
}
exit(0);
}
/**
* Perform some basic functional tests on the driver;
* make sure we can collect data from the sensor in polled
* and automatic modes.
*/
void
test(bool external_bus)
{
const char *path_accel = external_bus ? BMI160_DEVICE_PATH_ACCEL_EXT : BMI160_DEVICE_PATH_ACCEL;
const char *path_gyro = external_bus ? BMI160_DEVICE_PATH_GYRO_EXT : BMI160_DEVICE_PATH_GYRO;
accel_report a_report;
gyro_report g_report;
ssize_t sz;
/* get the driver */
int fd = open(path_accel, O_RDONLY);
if (fd < 0)
err(1, "%s open failed (try 'bmi160 start')",
path_accel);
/* get the driver */
int fd_gyro = open(path_gyro, O_RDONLY);
if (fd_gyro < 0) {
err(1, "%s open failed", path_gyro);
}
/* reset to manual polling */
if (ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_MANUAL) < 0) {
err(1, "reset to manual polling");
}
/* do a simple demand read */
sz = read(fd, &a_report, sizeof(a_report));
if (sz != sizeof(a_report)) {
warnx("ret: %d, expected: %d", sz, sizeof(a_report));
err(1, "immediate acc read failed");
}
warnx("single read");
warnx("time: %lld", a_report.timestamp);
warnx("acc x: \t%8.4f\tm/s^2", (double)a_report.x);
warnx("acc y: \t%8.4f\tm/s^2", (double)a_report.y);
warnx("acc z: \t%8.4f\tm/s^2", (double)a_report.z);
warnx("acc x: \t%d\traw 0x%0x", (short)a_report.x_raw, (unsigned short)a_report.x_raw);
warnx("acc y: \t%d\traw 0x%0x", (short)a_report.y_raw, (unsigned short)a_report.y_raw);
warnx("acc z: \t%d\traw 0x%0x", (short)a_report.z_raw, (unsigned short)a_report.z_raw);
warnx("acc range: %8.4f m/s^2 (%8.4f g)", (double)a_report.range_m_s2,
(double)(a_report.range_m_s2 / BMI160_ONE_G));
/* do a simple demand read */
sz = read(fd_gyro, &g_report, sizeof(g_report));
if (sz != sizeof(g_report)) {
warnx("ret: %d, expected: %d", sz, sizeof(g_report));
err(1, "immediate gyro read failed");
}
warnx("gyro x: \t% 9.5f\trad/s", (double)g_report.x);
warnx("gyro y: \t% 9.5f\trad/s", (double)g_report.y);
warnx("gyro z: \t% 9.5f\trad/s", (double)g_report.z);
warnx("gyro x: \t%d\traw", (int)g_report.x_raw);
warnx("gyro y: \t%d\traw", (int)g_report.y_raw);
warnx("gyro z: \t%d\traw", (int)g_report.z_raw);
warnx("gyro range: %8.4f rad/s (%d deg/s)", (double)g_report.range_rad_s,
(int)((g_report.range_rad_s / M_PI_F) * 180.0f + 0.5f));
warnx("temp: \t%8.4f\tdeg celsius", (double)a_report.temperature);
warnx("temp: \t%d\traw 0x%0x", (short)a_report.temperature_raw, (unsigned short)a_report.temperature_raw);
/* reset to default polling */
if (ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0) {
err(1, "reset to default polling");
}
close(fd);
close(fd_gyro);
/* XXX add poll-rate tests here too */
reset(external_bus);
errx(0, "PASS");
}
/**
* Reset the driver.
*/
void
reset(bool external_bus)
{
const char *path_accel = external_bus ? BMI160_DEVICE_PATH_ACCEL_EXT : BMI160_DEVICE_PATH_ACCEL;
int fd = open(path_accel, O_RDONLY);
if (fd < 0) {
err(1, "failed ");
}
if (ioctl(fd, SENSORIOCRESET, 0) < 0) {
err(1, "driver reset failed");
}
if (ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0) {
err(1, "driver poll restart failed");
}
close(fd);
exit(0);
}
/**
* Print a little info about the driver.
*/
void
info(bool external_bus)
{
BMI160 **g_dev_ptr = external_bus ? &g_dev_ext : &g_dev_int;
if (*g_dev_ptr == nullptr) {
errx(1, "driver not running");
}
printf("state @ %p\n", *g_dev_ptr);
(*g_dev_ptr)->print_info();
exit(0);
}
/**
* Dump the register information
*/
void
regdump(bool external_bus)
{
BMI160 **g_dev_ptr = external_bus ? &g_dev_ext : &g_dev_int;
if (*g_dev_ptr == nullptr) {
errx(1, "driver not running");
}
printf("regdump @ %p\n", *g_dev_ptr);
(*g_dev_ptr)->print_registers();
exit(0);
}
/**
* deliberately produce an error to test recovery
*/
void
testerror(bool external_bus)
{
BMI160 **g_dev_ptr = external_bus ? &g_dev_ext : &g_dev_int;
if (*g_dev_ptr == nullptr) {
errx(1, "driver not running");
}
(*g_dev_ptr)->test_error();
exit(0);
}
void
usage()
{
warnx("missing command: try 'start', 'info', 'test', 'stop',\n'reset', 'regdump', 'testerror'");
warnx("options:");
warnx(" -X (external bus)");
warnx(" -R rotation");
}
} // namespace
int
bmi160_main(int argc, char *argv[])
{
bool external_bus = false;
int ch;
enum Rotation rotation = ROTATION_NONE;
/* jump over start/off/etc and look at options first */
while ((ch = getopt(argc, argv, "XR:")) != EOF) {
switch (ch) {
case 'X':
external_bus = true;
break;
case 'R':
rotation = (enum Rotation)atoi(optarg);
break;
default:
bmi160::usage();
exit(0);
}
}
const char *verb = argv[optind];
/*
* Start/load the driver.
*/
if (!strcmp(verb, "start")) {
bmi160::start(external_bus, rotation);
}
if (!strcmp(verb, "stop")) {
bmi160::stop(external_bus);
}
/*
* Test the driver/device.
*/
if (!strcmp(verb, "test")) {
bmi160::test(external_bus);
}
/*
* Reset the driver.
*/
if (!strcmp(verb, "reset")) {
bmi160::reset(external_bus);
}
/*
* Print driver information.
*/
if (!strcmp(verb, "info")) {
bmi160::info(external_bus);
}
/*
* Print register information.
*/
if (!strcmp(verb, "regdump")) {
bmi160::regdump(external_bus);
}
if (!strcmp(verb, "testerror")) {
bmi160::testerror(external_bus);
}
bmi160::usage();
exit(1);
}
<commit_msg>astyle src/drivers/bmi160<commit_after>
#include "bmi160.hpp"
#include <board_config.h>
/** driver 'main' command */
extern "C" { __EXPORT int bmi160_main(int argc, char *argv[]); }
/**
* Local functions in support of the shell command.
*/
namespace bmi160
{
BMI160 *g_dev_int; // on internal bus
BMI160 *g_dev_ext; // on external bus
void start(bool, enum Rotation);
void stop(bool);
void test(bool);
void reset(bool);
void info(bool);
void regdump(bool);
void testerror(bool);
void usage();
/**
* Start the driver.
*
* This function only returns if the driver is up and running
* or failed to detect the sensor.
*/
void
start(bool external_bus, enum Rotation rotation)
{
int fd;
BMI160 **g_dev_ptr = external_bus ? &g_dev_ext : &g_dev_int;
const char *path_accel = external_bus ? BMI160_DEVICE_PATH_ACCEL_EXT : BMI160_DEVICE_PATH_ACCEL;
const char *path_gyro = external_bus ? BMI160_DEVICE_PATH_GYRO_EXT : BMI160_DEVICE_PATH_GYRO;
if (*g_dev_ptr != nullptr)
/* if already started, the still command succeeded */
{
errx(0, "already started");
}
/* create the driver */
if (external_bus) {
#if defined(PX4_SPI_BUS_EXT) && defined(PX4_SPIDEV_EXT_BMI)
*g_dev_ptr = new BMI160(PX4_SPI_BUS_EXT, path_accel, path_gyro, (spi_dev_e)PX4_SPIDEV_EXT_BMI, rotation);
#else
errx(0, "External SPI not available");
#endif
} else {
*g_dev_ptr = new BMI160(PX4_SPI_BUS_SENSORS, path_accel, path_gyro, (spi_dev_e)PX4_SPIDEV_BMI, rotation);
}
if (*g_dev_ptr == nullptr) {
goto fail;
}
if (OK != (*g_dev_ptr)->init()) {
goto fail;
}
/* set the poll rate to default, starts automatic data collection */
fd = open(path_accel, O_RDONLY);
if (fd < 0) {
goto fail;
}
if (ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0) {
goto fail;
}
close(fd);
exit(0);
fail:
if (*g_dev_ptr != nullptr) {
delete (*g_dev_ptr);
*g_dev_ptr = nullptr;
}
errx(1, "driver start failed");
}
void
stop(bool external_bus)
{
BMI160 **g_dev_ptr = external_bus ? &g_dev_ext : &g_dev_int;
if (*g_dev_ptr != nullptr) {
delete *g_dev_ptr;
*g_dev_ptr = nullptr;
} else {
/* warn, but not an error */
warnx("already stopped.");
}
exit(0);
}
/**
* Perform some basic functional tests on the driver;
* make sure we can collect data from the sensor in polled
* and automatic modes.
*/
void
test(bool external_bus)
{
const char *path_accel = external_bus ? BMI160_DEVICE_PATH_ACCEL_EXT : BMI160_DEVICE_PATH_ACCEL;
const char *path_gyro = external_bus ? BMI160_DEVICE_PATH_GYRO_EXT : BMI160_DEVICE_PATH_GYRO;
accel_report a_report;
gyro_report g_report;
ssize_t sz;
/* get the driver */
int fd = open(path_accel, O_RDONLY);
if (fd < 0)
err(1, "%s open failed (try 'bmi160 start')",
path_accel);
/* get the driver */
int fd_gyro = open(path_gyro, O_RDONLY);
if (fd_gyro < 0) {
err(1, "%s open failed", path_gyro);
}
/* reset to manual polling */
if (ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_MANUAL) < 0) {
err(1, "reset to manual polling");
}
/* do a simple demand read */
sz = read(fd, &a_report, sizeof(a_report));
if (sz != sizeof(a_report)) {
warnx("ret: %d, expected: %d", sz, sizeof(a_report));
err(1, "immediate acc read failed");
}
warnx("single read");
warnx("time: %lld", a_report.timestamp);
warnx("acc x: \t%8.4f\tm/s^2", (double)a_report.x);
warnx("acc y: \t%8.4f\tm/s^2", (double)a_report.y);
warnx("acc z: \t%8.4f\tm/s^2", (double)a_report.z);
warnx("acc x: \t%d\traw 0x%0x", (short)a_report.x_raw, (unsigned short)a_report.x_raw);
warnx("acc y: \t%d\traw 0x%0x", (short)a_report.y_raw, (unsigned short)a_report.y_raw);
warnx("acc z: \t%d\traw 0x%0x", (short)a_report.z_raw, (unsigned short)a_report.z_raw);
warnx("acc range: %8.4f m/s^2 (%8.4f g)", (double)a_report.range_m_s2,
(double)(a_report.range_m_s2 / BMI160_ONE_G));
/* do a simple demand read */
sz = read(fd_gyro, &g_report, sizeof(g_report));
if (sz != sizeof(g_report)) {
warnx("ret: %d, expected: %d", sz, sizeof(g_report));
err(1, "immediate gyro read failed");
}
warnx("gyro x: \t% 9.5f\trad/s", (double)g_report.x);
warnx("gyro y: \t% 9.5f\trad/s", (double)g_report.y);
warnx("gyro z: \t% 9.5f\trad/s", (double)g_report.z);
warnx("gyro x: \t%d\traw", (int)g_report.x_raw);
warnx("gyro y: \t%d\traw", (int)g_report.y_raw);
warnx("gyro z: \t%d\traw", (int)g_report.z_raw);
warnx("gyro range: %8.4f rad/s (%d deg/s)", (double)g_report.range_rad_s,
(int)((g_report.range_rad_s / M_PI_F) * 180.0f + 0.5f));
warnx("temp: \t%8.4f\tdeg celsius", (double)a_report.temperature);
warnx("temp: \t%d\traw 0x%0x", (short)a_report.temperature_raw, (unsigned short)a_report.temperature_raw);
/* reset to default polling */
if (ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0) {
err(1, "reset to default polling");
}
close(fd);
close(fd_gyro);
/* XXX add poll-rate tests here too */
reset(external_bus);
errx(0, "PASS");
}
/**
* Reset the driver.
*/
void
reset(bool external_bus)
{
const char *path_accel = external_bus ? BMI160_DEVICE_PATH_ACCEL_EXT : BMI160_DEVICE_PATH_ACCEL;
int fd = open(path_accel, O_RDONLY);
if (fd < 0) {
err(1, "failed ");
}
if (ioctl(fd, SENSORIOCRESET, 0) < 0) {
err(1, "driver reset failed");
}
if (ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0) {
err(1, "driver poll restart failed");
}
close(fd);
exit(0);
}
/**
* Print a little info about the driver.
*/
void
info(bool external_bus)
{
BMI160 **g_dev_ptr = external_bus ? &g_dev_ext : &g_dev_int;
if (*g_dev_ptr == nullptr) {
errx(1, "driver not running");
}
printf("state @ %p\n", *g_dev_ptr);
(*g_dev_ptr)->print_info();
exit(0);
}
/**
* Dump the register information
*/
void
regdump(bool external_bus)
{
BMI160 **g_dev_ptr = external_bus ? &g_dev_ext : &g_dev_int;
if (*g_dev_ptr == nullptr) {
errx(1, "driver not running");
}
printf("regdump @ %p\n", *g_dev_ptr);
(*g_dev_ptr)->print_registers();
exit(0);
}
/**
* deliberately produce an error to test recovery
*/
void
testerror(bool external_bus)
{
BMI160 **g_dev_ptr = external_bus ? &g_dev_ext : &g_dev_int;
if (*g_dev_ptr == nullptr) {
errx(1, "driver not running");
}
(*g_dev_ptr)->test_error();
exit(0);
}
void
usage()
{
warnx("missing command: try 'start', 'info', 'test', 'stop',\n'reset', 'regdump', 'testerror'");
warnx("options:");
warnx(" -X (external bus)");
warnx(" -R rotation");
}
} // namespace
int
bmi160_main(int argc, char *argv[])
{
bool external_bus = false;
int ch;
enum Rotation rotation = ROTATION_NONE;
/* jump over start/off/etc and look at options first */
while ((ch = getopt(argc, argv, "XR:")) != EOF) {
switch (ch) {
case 'X':
external_bus = true;
break;
case 'R':
rotation = (enum Rotation)atoi(optarg);
break;
default:
bmi160::usage();
exit(0);
}
}
const char *verb = argv[optind];
/*
* Start/load the driver.
*/
if (!strcmp(verb, "start")) {
bmi160::start(external_bus, rotation);
}
if (!strcmp(verb, "stop")) {
bmi160::stop(external_bus);
}
/*
* Test the driver/device.
*/
if (!strcmp(verb, "test")) {
bmi160::test(external_bus);
}
/*
* Reset the driver.
*/
if (!strcmp(verb, "reset")) {
bmi160::reset(external_bus);
}
/*
* Print driver information.
*/
if (!strcmp(verb, "info")) {
bmi160::info(external_bus);
}
/*
* Print register information.
*/
if (!strcmp(verb, "regdump")) {
bmi160::regdump(external_bus);
}
if (!strcmp(verb, "testerror")) {
bmi160::testerror(external_bus);
}
bmi160::usage();
exit(1);
}
<|endoftext|> |
<commit_before>#include "master.hpp"
namespace factor
{
/* Simple non-optimizing compiler.
This is one of the two compilers implementing Factor; the second one is written
in Factor and performs advanced optimizations. See core/compiler/compiler.factor.
The non-optimizing compiler compiles a quotation at a time by concatenating
machine code chunks; prolog, epilog, call word, jump to word, etc. These machine
code chunks are generated from Factor code in core/cpu/.../bootstrap.factor.
Calls to words and constant quotations (referenced by conditionals and dips)
are direct jumps to machine code blocks. Literals are also referenced directly
without going through the literal table.
It actually does do a little bit of very simple optimization:
1) Tail call optimization.
2) If a quotation is determined to not call any other words (except for a few
special words which are open-coded, see below), then no prolog/epilog is
generated.
3) When in tail position and immediately preceded by literal arguments, the
'if' is generated inline, instead of as a call to the 'if' word.
4) When preceded by a quotation, calls to 'dip', '2dip' and '3dip' are
open-coded as retain stack manipulation surrounding a subroutine call.
5) Sub-primitives are primitive words which are implemented in assembly and not
in the VM. They are open-coded and no subroutine call is generated. This
includes stack shufflers, some fixnum arithmetic words, and words such as tag,
slot and eq?. A primitive call is relatively expensive (two subroutine calls)
so this results in a big speedup for relatively little effort. */
bool quotation_jit::primitive_call_p(cell i, cell length)
{
return (i + 2) == length && array_nth(elements.untagged(),i + 1) == parent_vm->userenv[JIT_PRIMITIVE_WORD];
}
bool quotation_jit::fast_if_p(cell i, cell length)
{
return (i + 3) == length
&& tagged<object>(array_nth(elements.untagged(),i + 1)).type_p(QUOTATION_TYPE)
&& array_nth(elements.untagged(),i + 2) == parent_vm->userenv[JIT_IF_WORD];
}
bool quotation_jit::fast_dip_p(cell i, cell length)
{
return (i + 2) <= length && array_nth(elements.untagged(),i + 1) == parent_vm->userenv[JIT_DIP_WORD];
}
bool quotation_jit::fast_2dip_p(cell i, cell length)
{
return (i + 2) <= length && array_nth(elements.untagged(),i + 1) == parent_vm->userenv[JIT_2DIP_WORD];
}
bool quotation_jit::fast_3dip_p(cell i, cell length)
{
return (i + 2) <= length && array_nth(elements.untagged(),i + 1) == parent_vm->userenv[JIT_3DIP_WORD];
}
bool quotation_jit::mega_lookup_p(cell i, cell length)
{
return (i + 4) <= length
&& tagged<object>(array_nth(elements.untagged(),i + 1)).type_p(FIXNUM_TYPE)
&& tagged<object>(array_nth(elements.untagged(),i + 2)).type_p(ARRAY_TYPE)
&& array_nth(elements.untagged(),i + 3) == parent_vm->userenv[MEGA_LOOKUP_WORD];
}
bool quotation_jit::declare_p(cell i, cell length)
{
return (i + 2) <= length
&& array_nth(elements.untagged(),i + 1) == parent_vm->userenv[JIT_DECLARE_WORD];
}
bool quotation_jit::stack_frame_p()
{
fixnum length = array_capacity(elements.untagged());
fixnum i;
for(i = 0; i < length - 1; i++)
{
cell obj = array_nth(elements.untagged(),i);
switch(tagged<object>(obj).type())
{
case WORD_TYPE:
if(parent_vm->untag<word>(obj)->subprimitive == F)
return true;
break;
case QUOTATION_TYPE:
if(fast_dip_p(i,length) || fast_2dip_p(i,length) || fast_3dip_p(i,length))
return true;
break;
default:
break;
}
}
return false;
}
/* Allocates memory */
void quotation_jit::iterate_quotation()
{
bool stack_frame = stack_frame_p();
set_position(0);
if(stack_frame)
emit(parent_vm->userenv[JIT_PROLOG]);
cell i;
cell length = array_capacity(elements.untagged());
bool tail_call = false;
for(i = 0; i < length; i++)
{
set_position(i);
gc_root<object> obj(array_nth(elements.untagged(),i),parent_vm);
switch(obj.type())
{
case WORD_TYPE:
/* Intrinsics */
if(obj.as<word>()->subprimitive != F)
emit_subprimitive(obj.value());
/* The (execute) primitive is special-cased */
else if(obj.value() == parent_vm->userenv[JIT_EXECUTE_WORD])
{
if(i == length - 1)
{
if(stack_frame) emit(parent_vm->userenv[JIT_EPILOG]);
tail_call = true;
emit(parent_vm->userenv[JIT_EXECUTE_JUMP]);
}
else
emit(parent_vm->userenv[JIT_EXECUTE_CALL]);
}
/* Everything else */
else
{
if(i == length - 1)
{
if(stack_frame) emit(parent_vm->userenv[JIT_EPILOG]);
tail_call = true;
/* Inline cache misses are special-cased.
The calling convention for tail
calls stores the address of the next
instruction in a register. However,
PIC miss stubs themselves tail-call
the inline cache miss primitive, and
we don't want to clobber the saved
address. */
if(obj.value() == parent_vm->userenv[PIC_MISS_WORD]
|| obj.value() == parent_vm->userenv[PIC_MISS_TAIL_WORD])
{
word_special(obj.value());
}
else
{
word_jump(obj.value());
}
}
else
word_call(obj.value());
}
break;
case WRAPPER_TYPE:
push(obj.as<wrapper>()->object);
break;
case FIXNUM_TYPE:
/* Primitive calls */
if(primitive_call_p(i,length))
{
emit_with(parent_vm->userenv[JIT_PRIMITIVE],obj.value());
i++;
tail_call = true;
}
else
push(obj.value());
break;
case QUOTATION_TYPE:
/* 'if' preceeded by two literal quotations (this is why if and ? are
mutually recursive in the library, but both still work) */
if(fast_if_p(i,length))
{
if(stack_frame) emit(parent_vm->userenv[JIT_EPILOG]);
tail_call = true;
if(compiling)
{
parent_vm->jit_compile(array_nth(elements.untagged(),i),relocate);
parent_vm->jit_compile(array_nth(elements.untagged(),i + 1),relocate);
}
literal(array_nth(elements.untagged(),i));
literal(array_nth(elements.untagged(),i + 1));
emit(parent_vm->userenv[JIT_IF]);
i += 2;
}
/* dip */
else if(fast_dip_p(i,length))
{
if(compiling)
parent_vm->jit_compile(obj.value(),relocate);
emit_with(parent_vm->userenv[JIT_DIP],obj.value());
i++;
}
/* 2dip */
else if(fast_2dip_p(i,length))
{
if(compiling)
parent_vm->jit_compile(obj.value(),relocate);
emit_with(parent_vm->userenv[JIT_2DIP],obj.value());
i++;
}
/* 3dip */
else if(fast_3dip_p(i,length))
{
if(compiling)
parent_vm->jit_compile(obj.value(),relocate);
emit_with(parent_vm->userenv[JIT_3DIP],obj.value());
i++;
}
else
push(obj.value());
break;
case ARRAY_TYPE:
/* Method dispatch */
if(mega_lookup_p(i,length))
{
emit_mega_cache_lookup(
array_nth(elements.untagged(),i),
untag_fixnum(array_nth(elements.untagged(),i + 1)),
array_nth(elements.untagged(),i + 2));
i += 3;
tail_call = true;
}
/* Non-optimizing compiler ignores declarations */
else if(declare_p(i,length))
i++;
else
push(obj.value());
break;
default:
push(obj.value());
break;
}
}
if(!tail_call)
{
set_position(length);
if(stack_frame)
emit(parent_vm->userenv[JIT_EPILOG]);
emit(parent_vm->userenv[JIT_RETURN]);
}
}
void factor_vm::set_quot_xt(quotation *quot, code_block *code)
{
if(code->type != QUOTATION_TYPE)
critical_error("Bad param to set_quot_xt",(cell)code);
quot->code = code;
quot->xt = code->xt();
}
/* Allocates memory */
void factor_vm::jit_compile(cell quot_, bool relocating)
{
gc_root<quotation> quot(quot_,this);
if(quot->code) return;
quotation_jit compiler(quot.value(),true,relocating,this);
compiler.iterate_quotation();
code_block *compiled = compiler.to_code_block();
set_quot_xt(quot.untagged(),compiled);
if(relocating) relocate_code_block(compiled);
}
void factor_vm::primitive_jit_compile()
{
jit_compile(dpop(),true);
}
/* push a new quotation on the stack */
void factor_vm::primitive_array_to_quotation()
{
quotation *quot = allot<quotation>(sizeof(quotation));
quot->array = dpeek();
quot->cached_effect = F;
quot->cache_counter = F;
quot->xt = (void *)lazy_jit_compile;
quot->code = NULL;
drepl(tag<quotation>(quot));
}
void factor_vm::primitive_quotation_xt()
{
quotation *quot = untag_check<quotation>(dpeek());
drepl(allot_cell((cell)quot->xt));
}
void factor_vm::compile_all_words()
{
gc_root<array> words(find_all_words(),this);
cell i;
cell length = array_capacity(words.untagged());
for(i = 0; i < length; i++)
{
gc_root<word> word(array_nth(words.untagged(),i),this);
if(!word->code || !word_optimized_p(word.untagged()))
jit_compile_word(word.value(),word->def,false);
update_word_xt(word.value());
}
printf("done\n");
/* Update XTs in code heap */
word_updater updater(this);
iterate_code_heap(updater);
}
/* Allocates memory */
fixnum factor_vm::quot_code_offset_to_scan(cell quot_, cell offset)
{
gc_root<quotation> quot(quot_,this);
gc_root<array> array(quot->array,this);
quotation_jit compiler(quot.value(),false,false,this);
compiler.compute_position(offset);
compiler.iterate_quotation();
return compiler.get_position();
}
cell factor_vm::lazy_jit_compile_impl(cell quot_, stack_frame *stack)
{
gc_root<quotation> quot(quot_,this);
stack_chain->callstack_top = stack;
jit_compile(quot.value(),true);
return quot.value();
}
VM_ASM_API cell lazy_jit_compile_impl(cell quot_, stack_frame *stack, factor_vm *myvm)
{
ASSERTVM();
return VM_PTR->lazy_jit_compile_impl(quot_,stack);
}
void factor_vm::primitive_quot_compiled_p()
{
tagged<quotation> quot(dpop());
quot.untag_check(this);
dpush(tag_boolean(quot->code != NULL));
}
}
<commit_msg>vm: remove debug message<commit_after>#include "master.hpp"
namespace factor
{
/* Simple non-optimizing compiler.
This is one of the two compilers implementing Factor; the second one is written
in Factor and performs advanced optimizations. See core/compiler/compiler.factor.
The non-optimizing compiler compiles a quotation at a time by concatenating
machine code chunks; prolog, epilog, call word, jump to word, etc. These machine
code chunks are generated from Factor code in core/cpu/.../bootstrap.factor.
Calls to words and constant quotations (referenced by conditionals and dips)
are direct jumps to machine code blocks. Literals are also referenced directly
without going through the literal table.
It actually does do a little bit of very simple optimization:
1) Tail call optimization.
2) If a quotation is determined to not call any other words (except for a few
special words which are open-coded, see below), then no prolog/epilog is
generated.
3) When in tail position and immediately preceded by literal arguments, the
'if' is generated inline, instead of as a call to the 'if' word.
4) When preceded by a quotation, calls to 'dip', '2dip' and '3dip' are
open-coded as retain stack manipulation surrounding a subroutine call.
5) Sub-primitives are primitive words which are implemented in assembly and not
in the VM. They are open-coded and no subroutine call is generated. This
includes stack shufflers, some fixnum arithmetic words, and words such as tag,
slot and eq?. A primitive call is relatively expensive (two subroutine calls)
so this results in a big speedup for relatively little effort. */
bool quotation_jit::primitive_call_p(cell i, cell length)
{
return (i + 2) == length && array_nth(elements.untagged(),i + 1) == parent_vm->userenv[JIT_PRIMITIVE_WORD];
}
bool quotation_jit::fast_if_p(cell i, cell length)
{
return (i + 3) == length
&& tagged<object>(array_nth(elements.untagged(),i + 1)).type_p(QUOTATION_TYPE)
&& array_nth(elements.untagged(),i + 2) == parent_vm->userenv[JIT_IF_WORD];
}
bool quotation_jit::fast_dip_p(cell i, cell length)
{
return (i + 2) <= length && array_nth(elements.untagged(),i + 1) == parent_vm->userenv[JIT_DIP_WORD];
}
bool quotation_jit::fast_2dip_p(cell i, cell length)
{
return (i + 2) <= length && array_nth(elements.untagged(),i + 1) == parent_vm->userenv[JIT_2DIP_WORD];
}
bool quotation_jit::fast_3dip_p(cell i, cell length)
{
return (i + 2) <= length && array_nth(elements.untagged(),i + 1) == parent_vm->userenv[JIT_3DIP_WORD];
}
bool quotation_jit::mega_lookup_p(cell i, cell length)
{
return (i + 4) <= length
&& tagged<object>(array_nth(elements.untagged(),i + 1)).type_p(FIXNUM_TYPE)
&& tagged<object>(array_nth(elements.untagged(),i + 2)).type_p(ARRAY_TYPE)
&& array_nth(elements.untagged(),i + 3) == parent_vm->userenv[MEGA_LOOKUP_WORD];
}
bool quotation_jit::declare_p(cell i, cell length)
{
return (i + 2) <= length
&& array_nth(elements.untagged(),i + 1) == parent_vm->userenv[JIT_DECLARE_WORD];
}
bool quotation_jit::stack_frame_p()
{
fixnum length = array_capacity(elements.untagged());
fixnum i;
for(i = 0; i < length - 1; i++)
{
cell obj = array_nth(elements.untagged(),i);
switch(tagged<object>(obj).type())
{
case WORD_TYPE:
if(parent_vm->untag<word>(obj)->subprimitive == F)
return true;
break;
case QUOTATION_TYPE:
if(fast_dip_p(i,length) || fast_2dip_p(i,length) || fast_3dip_p(i,length))
return true;
break;
default:
break;
}
}
return false;
}
/* Allocates memory */
void quotation_jit::iterate_quotation()
{
bool stack_frame = stack_frame_p();
set_position(0);
if(stack_frame)
emit(parent_vm->userenv[JIT_PROLOG]);
cell i;
cell length = array_capacity(elements.untagged());
bool tail_call = false;
for(i = 0; i < length; i++)
{
set_position(i);
gc_root<object> obj(array_nth(elements.untagged(),i),parent_vm);
switch(obj.type())
{
case WORD_TYPE:
/* Intrinsics */
if(obj.as<word>()->subprimitive != F)
emit_subprimitive(obj.value());
/* The (execute) primitive is special-cased */
else if(obj.value() == parent_vm->userenv[JIT_EXECUTE_WORD])
{
if(i == length - 1)
{
if(stack_frame) emit(parent_vm->userenv[JIT_EPILOG]);
tail_call = true;
emit(parent_vm->userenv[JIT_EXECUTE_JUMP]);
}
else
emit(parent_vm->userenv[JIT_EXECUTE_CALL]);
}
/* Everything else */
else
{
if(i == length - 1)
{
if(stack_frame) emit(parent_vm->userenv[JIT_EPILOG]);
tail_call = true;
/* Inline cache misses are special-cased.
The calling convention for tail
calls stores the address of the next
instruction in a register. However,
PIC miss stubs themselves tail-call
the inline cache miss primitive, and
we don't want to clobber the saved
address. */
if(obj.value() == parent_vm->userenv[PIC_MISS_WORD]
|| obj.value() == parent_vm->userenv[PIC_MISS_TAIL_WORD])
{
word_special(obj.value());
}
else
{
word_jump(obj.value());
}
}
else
word_call(obj.value());
}
break;
case WRAPPER_TYPE:
push(obj.as<wrapper>()->object);
break;
case FIXNUM_TYPE:
/* Primitive calls */
if(primitive_call_p(i,length))
{
emit_with(parent_vm->userenv[JIT_PRIMITIVE],obj.value());
i++;
tail_call = true;
}
else
push(obj.value());
break;
case QUOTATION_TYPE:
/* 'if' preceeded by two literal quotations (this is why if and ? are
mutually recursive in the library, but both still work) */
if(fast_if_p(i,length))
{
if(stack_frame) emit(parent_vm->userenv[JIT_EPILOG]);
tail_call = true;
if(compiling)
{
parent_vm->jit_compile(array_nth(elements.untagged(),i),relocate);
parent_vm->jit_compile(array_nth(elements.untagged(),i + 1),relocate);
}
literal(array_nth(elements.untagged(),i));
literal(array_nth(elements.untagged(),i + 1));
emit(parent_vm->userenv[JIT_IF]);
i += 2;
}
/* dip */
else if(fast_dip_p(i,length))
{
if(compiling)
parent_vm->jit_compile(obj.value(),relocate);
emit_with(parent_vm->userenv[JIT_DIP],obj.value());
i++;
}
/* 2dip */
else if(fast_2dip_p(i,length))
{
if(compiling)
parent_vm->jit_compile(obj.value(),relocate);
emit_with(parent_vm->userenv[JIT_2DIP],obj.value());
i++;
}
/* 3dip */
else if(fast_3dip_p(i,length))
{
if(compiling)
parent_vm->jit_compile(obj.value(),relocate);
emit_with(parent_vm->userenv[JIT_3DIP],obj.value());
i++;
}
else
push(obj.value());
break;
case ARRAY_TYPE:
/* Method dispatch */
if(mega_lookup_p(i,length))
{
emit_mega_cache_lookup(
array_nth(elements.untagged(),i),
untag_fixnum(array_nth(elements.untagged(),i + 1)),
array_nth(elements.untagged(),i + 2));
i += 3;
tail_call = true;
}
/* Non-optimizing compiler ignores declarations */
else if(declare_p(i,length))
i++;
else
push(obj.value());
break;
default:
push(obj.value());
break;
}
}
if(!tail_call)
{
set_position(length);
if(stack_frame)
emit(parent_vm->userenv[JIT_EPILOG]);
emit(parent_vm->userenv[JIT_RETURN]);
}
}
void factor_vm::set_quot_xt(quotation *quot, code_block *code)
{
if(code->type != QUOTATION_TYPE)
critical_error("Bad param to set_quot_xt",(cell)code);
quot->code = code;
quot->xt = code->xt();
}
/* Allocates memory */
void factor_vm::jit_compile(cell quot_, bool relocating)
{
gc_root<quotation> quot(quot_,this);
if(quot->code) return;
quotation_jit compiler(quot.value(),true,relocating,this);
compiler.iterate_quotation();
code_block *compiled = compiler.to_code_block();
set_quot_xt(quot.untagged(),compiled);
if(relocating) relocate_code_block(compiled);
}
void factor_vm::primitive_jit_compile()
{
jit_compile(dpop(),true);
}
/* push a new quotation on the stack */
void factor_vm::primitive_array_to_quotation()
{
quotation *quot = allot<quotation>(sizeof(quotation));
quot->array = dpeek();
quot->cached_effect = F;
quot->cache_counter = F;
quot->xt = (void *)lazy_jit_compile;
quot->code = NULL;
drepl(tag<quotation>(quot));
}
void factor_vm::primitive_quotation_xt()
{
quotation *quot = untag_check<quotation>(dpeek());
drepl(allot_cell((cell)quot->xt));
}
void factor_vm::compile_all_words()
{
gc_root<array> words(find_all_words(),this);
cell i;
cell length = array_capacity(words.untagged());
for(i = 0; i < length; i++)
{
gc_root<word> word(array_nth(words.untagged(),i),this);
if(!word->code || !word_optimized_p(word.untagged()))
jit_compile_word(word.value(),word->def,false);
update_word_xt(word.value());
}
/* Update XTs in code heap */
word_updater updater(this);
iterate_code_heap(updater);
}
/* Allocates memory */
fixnum factor_vm::quot_code_offset_to_scan(cell quot_, cell offset)
{
gc_root<quotation> quot(quot_,this);
gc_root<array> array(quot->array,this);
quotation_jit compiler(quot.value(),false,false,this);
compiler.compute_position(offset);
compiler.iterate_quotation();
return compiler.get_position();
}
cell factor_vm::lazy_jit_compile_impl(cell quot_, stack_frame *stack)
{
gc_root<quotation> quot(quot_,this);
stack_chain->callstack_top = stack;
jit_compile(quot.value(),true);
return quot.value();
}
VM_ASM_API cell lazy_jit_compile_impl(cell quot_, stack_frame *stack, factor_vm *myvm)
{
ASSERTVM();
return VM_PTR->lazy_jit_compile_impl(quot_,stack);
}
void factor_vm::primitive_quot_compiled_p()
{
tagged<quotation> quot(dpop());
quot.untag_check(this);
dpush(tag_boolean(quot->code != NULL));
}
}
<|endoftext|> |
<commit_before>#include "atlas/utils/Application.hpp"
#include "atlas/utils/Scene.hpp"
#include "atlas/core/Log.hpp"
#include "atlas/core/Platform.hpp"
#include "atlas/gl/GL.hpp"
#include "atlas/core/GLFW.hpp"
#include "atlas/core/Float.hpp"
#include <vector>
namespace atlas
{
namespace utils
{
typedef std::unique_ptr<Scene> ScenePointer;
struct Application::ApplicationImpl
{
ApplicationImpl() :
currentWindow(nullptr)
{ }
~ApplicationImpl()
{ }
void insertScene(Scene* scene)
{
sceneList.push_back(ScenePointer(scene));
currentScene = sceneList.size() - 1;
sceneTicks.push_back(-1.0);
}
void getNextScene()
{
if (sceneList.size() == 1)
{
return;
}
sceneTicks[currentScene] = glfwGetTime();
currentScene = (currentScene + 1) % sceneList.size();
double newTime =
(core::areEqual<double>(-1.0, sceneTicks[currentScene])) ?
0 : sceneTicks[currentScene];
glfwSetTime(newTime);
}
void getPreviousScene()
{
if (sceneList.size() == 1)
{
return;
}
sceneTicks[currentScene] = glfwGetTime();
currentScene = (currentScene - 1) % sceneList.size();
double newTime =
(core::areEqual<double>(-1.0, sceneTicks[currentScene])) ?
0 : sceneTicks[currentScene];
glfwSetTime(newTime);
}
GLFWwindow* currentWindow;
std::vector<ScenePointer> sceneList;
std::vector<double> sceneTicks;
size_t currentScene;
};
static void mousePressCallback(GLFWwindow* window, int button,
int action, int mods)
{
UNUSED(window);
APPLICATION.getCurrentScene()->mousePressEvent(button, action,
mods);
}
static void mouseMoveCallback(GLFWwindow* window, double xPos,
double yPos)
{
UNUSED(window);
APPLICATION.getCurrentScene()->mouseMoveEvent(xPos, yPos);
}
static void keyPressCallback(GLFWwindow* window, int key,
int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, GL_TRUE);
}
else if (key == GLFW_KEY_TAB && action == GLFW_PRESS)
{
APPLICATION.nextScene();
}
else if (key == GLFW_KEY_TAB && action == GLFW_PRESS &&
mods == GLFW_KEY_LEFT_SHIFT)
{
APPLICATION.previousScene();
}
else
{
APPLICATION.getCurrentScene()->keyPressEvent(key, scancode,
action, mods);
}
}
static void windowSizeCallback(GLFWwindow* window, int width,
int height)
{
UNUSED(window);
width = (width < 1) ? 1 : width;
height = (height < 1) ? 1 : height;
APPLICATION.getCurrentScene()->screenResizeEvent(width, height);
}
static void errorCallback(int error, const char* message)
{
ERROR_LOG(std::to_string(error) + ":" + message);
}
static void windowCloseCallback(GLFWwindow* window)
{
if (APPLICATION.getCurrentScene()->sceneEnded())
{
glfwSetWindowShouldClose(window, GL_TRUE);
}
else
{
glfwSetWindowShouldClose(window, GL_FALSE);
glfwHideWindow(window);
}
}
Application::Application() :
mImpl(new ApplicationImpl)
{
glfwSetErrorCallback(errorCallback);
if (!glfwInit())
{
CRITICAL_LOG("Could not initialize GLFW");
exit(EXIT_FAILURE);
}
}
Application::~Application()
{
if (mImpl->currentWindow)
{
glfwDestroyWindow(mImpl->currentWindow);
}
glfwTerminate();
}
Application& Application::getInstance()
{
static Application instance;
return instance;
}
void Application::createWindow(int width, int height,
std::string const& title)
{
if (mImpl->currentWindow != nullptr)
{
ERROR_LOG("Multiple windows are currently not supported.");
return;
}
#if defined(ATLAS_PLATFORM_APPLE)
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
#endif
mImpl->currentWindow = glfwCreateWindow(width, height,
title.c_str(), NULL, NULL);
if (!mImpl->currentWindow)
{
glfwTerminate();
CRITICAL_LOG("Could not create window.");
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(mImpl->currentWindow);
if (glewInit() != GLEW_OK)
{
CRITICAL_LOG("Could not initialize GLEW.");
glfwDestroyWindow(mImpl->currentWindow);
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwSetKeyCallback(mImpl->currentWindow,
keyPressCallback);
glfwSetWindowSizeCallback(mImpl->currentWindow,
windowSizeCallback);
glfwSetMouseButtonCallback(mImpl->currentWindow,
mousePressCallback);
glfwSetCursorPosCallback(mImpl->currentWindow,
mouseMoveCallback);
glfwSetWindowCloseCallback(mImpl->currentWindow,
windowCloseCallback);
}
void Application::runApplication()
{
if (mImpl->currentWindow == nullptr)
{
WARN_LOG("Cannot run application without a window.");
return;
}
if (mImpl->sceneList.empty())
{
WARN_LOG("Cannot run application without a scene.");
return;
}
glfwShowWindow(mImpl->currentWindow);
int width, height;
size_t currentScene = mImpl->currentScene;
glfwGetWindowSize(mImpl->currentWindow, &width, &height);
mImpl->sceneList[currentScene]->screenResizeEvent(width, height);
glfwSetTime(0.0);
double currentTime;
while (!glfwWindowShouldClose(mImpl->currentWindow))
{
currentTime = glfwGetTime();
mImpl->sceneList[currentScene]->updateScene(currentTime);
mImpl->sceneList[currentScene]->renderScene();
glfwSwapBuffers(mImpl->currentWindow);
glfwPollEvents();
}
}
void Application::getCursorPosition(double* x, double *y)
{
glfwGetCursorPos(mImpl->currentWindow, x, y);
}
void Application::addScene(Scene* scene)
{
mImpl->insertScene(scene);
}
void Application::nextScene()
{
mImpl->getNextScene();
}
void Application::previousScene()
{
mImpl->getPreviousScene();
}
Scene* Application::getCurrentScene() const
{
return mImpl->sceneList[mImpl->currentScene].get();
}
}
}<commit_msg>[brief] Fixes display issues for OSX.<commit_after>#include "atlas/utils/Application.hpp"
#include "atlas/utils/Scene.hpp"
#include "atlas/core/Log.hpp"
#include "atlas/core/Platform.hpp"
#include "atlas/gl/GL.hpp"
#include "atlas/core/GLFW.hpp"
#include "atlas/core/Float.hpp"
#include <vector>
namespace atlas
{
namespace utils
{
typedef std::unique_ptr<Scene> ScenePointer;
struct Application::ApplicationImpl
{
ApplicationImpl() :
currentWindow(nullptr)
{ }
~ApplicationImpl()
{ }
void insertScene(Scene* scene)
{
sceneList.push_back(ScenePointer(scene));
currentScene = sceneList.size() - 1;
sceneTicks.push_back(-1.0);
}
void getNextScene()
{
if (sceneList.size() == 1)
{
return;
}
sceneTicks[currentScene] = glfwGetTime();
currentScene = (currentScene + 1) % sceneList.size();
double newTime =
(core::areEqual<double>(-1.0, sceneTicks[currentScene])) ?
0 : sceneTicks[currentScene];
glfwSetTime(newTime);
}
void getPreviousScene()
{
if (sceneList.size() == 1)
{
return;
}
sceneTicks[currentScene] = glfwGetTime();
currentScene = (currentScene - 1) % sceneList.size();
double newTime =
(core::areEqual<double>(-1.0, sceneTicks[currentScene])) ?
0 : sceneTicks[currentScene];
glfwSetTime(newTime);
}
GLFWwindow* currentWindow;
std::vector<ScenePointer> sceneList;
std::vector<double> sceneTicks;
size_t currentScene;
};
static void mousePressCallback(GLFWwindow* window, int button,
int action, int mods)
{
UNUSED(window);
APPLICATION.getCurrentScene()->mousePressEvent(button, action,
mods);
}
static void mouseMoveCallback(GLFWwindow* window, double xPos,
double yPos)
{
UNUSED(window);
APPLICATION.getCurrentScene()->mouseMoveEvent(xPos, yPos);
}
static void keyPressCallback(GLFWwindow* window, int key,
int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, GL_TRUE);
}
else if (key == GLFW_KEY_TAB && action == GLFW_PRESS)
{
APPLICATION.nextScene();
}
else if (key == GLFW_KEY_TAB && action == GLFW_PRESS &&
mods == GLFW_KEY_LEFT_SHIFT)
{
APPLICATION.previousScene();
}
else
{
APPLICATION.getCurrentScene()->keyPressEvent(key, scancode,
action, mods);
}
}
static void windowSizeCallback(GLFWwindow* window, int width,
int height)
{
UNUSED(window);
UNUSED(width);
UNUSED(height);
}
static void frameBufferSizeCallback(GLFWwindow* window, int width,
int height)
{
UNUSED(window);
width = (width < 1) ? 1 : width;
height = (height < 1) ? 1 : height;
APPLICATION.getCurrentScene()->screenResizeEvent(width, height);
}
static void errorCallback(int error, const char* message)
{
ERROR_LOG(std::to_string(error) + ":" + message);
}
static void windowCloseCallback(GLFWwindow* window)
{
if (APPLICATION.getCurrentScene()->sceneEnded())
{
glfwSetWindowShouldClose(window, GL_TRUE);
}
else
{
glfwSetWindowShouldClose(window, GL_FALSE);
glfwHideWindow(window);
}
}
Application::Application() :
mImpl(new ApplicationImpl)
{
glfwSetErrorCallback(errorCallback);
if (!glfwInit())
{
CRITICAL_LOG("Could not initialize GLFW");
exit(EXIT_FAILURE);
}
}
Application::~Application()
{
if (mImpl->currentWindow)
{
glfwDestroyWindow(mImpl->currentWindow);
}
glfwTerminate();
}
Application& Application::getInstance()
{
static Application instance;
return instance;
}
void Application::createWindow(int width, int height,
std::string const& title)
{
if (mImpl->currentWindow != nullptr)
{
ERROR_LOG("Multiple windows are currently not supported.");
return;
}
#if defined(ATLAS_PLATFORM_APPLE)
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
#endif
mImpl->currentWindow = glfwCreateWindow(width, height,
title.c_str(), NULL, NULL);
if (!mImpl->currentWindow)
{
glfwTerminate();
CRITICAL_LOG("Could not create window.");
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(mImpl->currentWindow);
if (glewInit() != GLEW_OK)
{
CRITICAL_LOG("Could not initialize GLEW.");
glfwDestroyWindow(mImpl->currentWindow);
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwSetKeyCallback(mImpl->currentWindow,
keyPressCallback);
glfwSetWindowSizeCallback(mImpl->currentWindow,
windowSizeCallback);
glfwSetFramebufferSizeCallback(mImpl->currentWindow,
frameBufferSizeCallback);
glfwSetMouseButtonCallback(mImpl->currentWindow,
mousePressCallback);
glfwSetCursorPosCallback(mImpl->currentWindow,
mouseMoveCallback);
glfwSetWindowCloseCallback(mImpl->currentWindow,
windowCloseCallback);
}
void Application::runApplication()
{
if (mImpl->currentWindow == nullptr)
{
WARN_LOG("Cannot run application without a window.");
return;
}
if (mImpl->sceneList.empty())
{
WARN_LOG("Cannot run application without a scene.");
return;
}
glfwShowWindow(mImpl->currentWindow);
int width, height;
size_t currentScene = mImpl->currentScene;
glfwGetFramebufferSize(mImpl->currentWindow, &width, &height);
mImpl->sceneList[currentScene]->screenResizeEvent(width, height);
glfwSetTime(0.0);
double currentTime;
while (!glfwWindowShouldClose(mImpl->currentWindow))
{
currentTime = glfwGetTime();
mImpl->sceneList[currentScene]->updateScene(currentTime);
mImpl->sceneList[currentScene]->renderScene();
glfwSwapBuffers(mImpl->currentWindow);
glfwPollEvents();
}
}
void Application::getCursorPosition(double* x, double *y)
{
glfwGetCursorPos(mImpl->currentWindow, x, y);
}
void Application::addScene(Scene* scene)
{
mImpl->insertScene(scene);
}
void Application::nextScene()
{
mImpl->getNextScene();
}
void Application::previousScene()
{
mImpl->getPreviousScene();
}
Scene* Application::getCurrentScene() const
{
return mImpl->sceneList[mImpl->currentScene].get();
}
}
}<|endoftext|> |
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2020 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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 "PalPrivateAddressControllerImpl.h"
#include "dm_api.h"
namespace ble {
namespace impl {
ble_error_t PalPrivateAddressController::initialize()
{
DmPrivInit();
return BLE_ERROR_NONE;
}
ble_error_t PalPrivateAddressController::terminate()
{
return BLE_ERROR_NONE;
}
ble_error_t PalPrivateAddressController::generate_resolvable_private_address(const irk_t& local_irk)
{
if (_generating_rpa) {
return BLE_ERROR_INVALID_STATE;
}
DmPrivGenerateAddr(const_cast<uint8_t*>(local_irk.data()), 0);
_generating_rpa = true;
return BLE_ERROR_NONE;
}
address_t PalPrivateAddressController::generate_non_resolvable_private_address()
{
address_t address;
SecRand(address.data(), address.size());
DM_RAND_ADDR_SET(address, DM_RAND_ADDR_NONRESOLV);
return address;
}
ble_error_t PalPrivateAddressController::resolve_private_address(
const address_t &address,
const irk_t& irk
)
{
if (_resolving_rpa) {
return BLE_ERROR_INVALID_STATE;
}
DmPrivResolveAddr(
const_cast<uint8_t*>(address.data()),
const_cast<uint8_t*>(irk.data()),
0
);
return BLE_ERROR_NONE;
}
bool PalPrivateAddressController::is_ll_privacy_supported()
{
return HciLlPrivacySupported();
}
ble_error_t PalPrivateAddressController::set_ll_address_resolution(bool enable)
{
DmPrivSetAddrResEnable(enable);
return BLE_ERROR_NONE;
}
ble_error_t PalPrivateAddressController::set_ll_resolvable_private_address_timeout(
resolvable_address_timeout_t timeout
)
{
if (HciLlPrivacySupported() == false) {
return BLE_ERROR_NOT_IMPLEMENTED;
}
DmPrivSetResolvablePrivateAddrTimeout(timeout.value());
return BLE_ERROR_NONE;
}
uint8_t PalPrivateAddressController::read_resolving_list_capacity()
{
return HciGetResolvingListSize();
}
ble_error_t PalPrivateAddressController::add_device_to_resolving_list(
target_peer_address_type_t peer_address_type,
const address_t &peer_identity_address,
const irk_t& peer_irk,
const irk_t& local_irk
)
{
if (is_ll_privacy_supported() == false) {
return BLE_ERROR_NOT_IMPLEMENTED;
}
DmPrivAddDevToResList(
peer_address_type.value(),
peer_identity_address.data(),
const_cast<uint8_t*>(peer_irk.data()),
const_cast<uint8_t*>(local_irk.data()),
true,
0
);
return BLE_ERROR_NONE;
}
ble_error_t PalPrivateAddressController::remove_device_from_resolving_list(
target_peer_address_type_t peer_address_type,
const address_t &peer_identity_address
)
{
if (is_ll_privacy_supported() == false) {
return BLE_ERROR_NOT_IMPLEMENTED;
}
DmPrivRemDevFromResList(peer_address_type.value(), peer_identity_address.data(), 0);
return BLE_ERROR_NONE;
}
ble_error_t PalPrivateAddressController::set_peer_privacy_mode(
target_peer_address_type_t peer_address_type,
const address_t &peer_address,
privacy_mode_t privacy_mode
)
{
if (is_ll_privacy_supported() == false) {
return BLE_ERROR_NOT_IMPLEMENTED;
}
DmPrivSetPrivacyMode(
peer_address_type.value(),
peer_address.data(),
privacy_mode.value()
);
return BLE_ERROR_NONE;
}
ble_error_t PalPrivateAddressController::clear_resolving_list()
{
if (is_ll_privacy_supported() == false) {
return BLE_ERROR_NOT_IMPLEMENTED;
}
DmPrivClearResList();
return BLE_ERROR_NONE;
}
void PalPrivateAddressController::set_event_handler(EventHandler *handler)
{
_event_handler = handler;
}
PalPrivateAddressController& PalPrivateAddressController::instance()
{
static impl::PalPrivateAddressController self;
return self;
}
bool PalPrivateAddressController::cordio_handler(const wsfMsgHdr_t *msg)
{
if (msg == nullptr) {
return false;
}
auto* handler = instance()._event_handler;
switch (msg->event) {
case DM_PRIV_GENERATE_ADDR_IND: {
instance()._generating_rpa = false;
if (!handler) {
return true;
}
const auto *evt = (const dmPrivGenAddrIndEvt_t*) msg;
if (evt->hdr.status == HCI_SUCCESS) {
handler->on_resolvable_private_address_generated(evt->addr);
} else {
handler->on_resolvable_private_address_generated(address_t{});
}
return true;
}
#if BLE_GAP_HOST_BASED_PRIVATE_ADDRESS_RESOLUTION
case DM_PRIV_RESOLVED_ADDR_IND: {
instance()._resolving_rpa = false;
if (!handler) {
return true;
}
handler->on_private_address_resolved(msg->status == HCI_SUCCESS);
return true;
}
#endif // BLE_GAP_HOST_BASED_PRIVATE_ADDRESS_RESOLUTION
case DM_PRIV_ADD_DEV_TO_RES_LIST_IND: // Device added to resolving list
case DM_PRIV_REM_DEV_FROM_RES_LIST_IND: // Device removed from resolving list
case DM_PRIV_CLEAR_RES_LIST_IND: // Resolving list cleared
{
if (!handler) {
return true;
}
// Previous command completed, we can move to the next control block
handler->on_resolving_list_action_complete();
return true;
}
default:
return false;
}
}
} // namespace impl
} // namespace ble
<commit_msg>Set privacy mode to device mode in LL. Do not enable address resolution when a new entry is added.<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2020 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*
* 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 "PalPrivateAddressControllerImpl.h"
#include "dm_api.h"
namespace ble {
namespace impl {
ble_error_t PalPrivateAddressController::initialize()
{
DmPrivInit();
return BLE_ERROR_NONE;
}
ble_error_t PalPrivateAddressController::terminate()
{
return BLE_ERROR_NONE;
}
ble_error_t PalPrivateAddressController::generate_resolvable_private_address(const irk_t& local_irk)
{
if (_generating_rpa) {
return BLE_ERROR_INVALID_STATE;
}
DmPrivGenerateAddr(const_cast<uint8_t*>(local_irk.data()), 0);
_generating_rpa = true;
return BLE_ERROR_NONE;
}
address_t PalPrivateAddressController::generate_non_resolvable_private_address()
{
address_t address;
SecRand(address.data(), address.size());
DM_RAND_ADDR_SET(address, DM_RAND_ADDR_NONRESOLV);
return address;
}
ble_error_t PalPrivateAddressController::resolve_private_address(
const address_t &address,
const irk_t& irk
)
{
if (_resolving_rpa) {
return BLE_ERROR_INVALID_STATE;
}
DmPrivResolveAddr(
const_cast<uint8_t*>(address.data()),
const_cast<uint8_t*>(irk.data()),
0
);
return BLE_ERROR_NONE;
}
bool PalPrivateAddressController::is_ll_privacy_supported()
{
return HciLlPrivacySupported();
}
ble_error_t PalPrivateAddressController::set_ll_address_resolution(bool enable)
{
DmPrivSetAddrResEnable(enable);
return BLE_ERROR_NONE;
}
ble_error_t PalPrivateAddressController::set_ll_resolvable_private_address_timeout(
resolvable_address_timeout_t timeout
)
{
if (HciLlPrivacySupported() == false) {
return BLE_ERROR_NOT_IMPLEMENTED;
}
DmPrivSetResolvablePrivateAddrTimeout(timeout.value());
return BLE_ERROR_NONE;
}
uint8_t PalPrivateAddressController::read_resolving_list_capacity()
{
return HciGetResolvingListSize();
}
ble_error_t PalPrivateAddressController::add_device_to_resolving_list(
target_peer_address_type_t peer_address_type,
const address_t &peer_identity_address,
const irk_t& peer_irk,
const irk_t& local_irk
)
{
if (is_ll_privacy_supported() == false) {
return BLE_ERROR_NOT_IMPLEMENTED;
}
DmPrivAddDevToResList(
peer_address_type.value(),
peer_identity_address.data(),
const_cast<uint8_t*>(peer_irk.data()),
const_cast<uint8_t*>(local_irk.data()),
false,
0
);
DmPrivSetPrivacyMode(
peer_address_type.value(),
peer_identity_address.data(),
DM_PRIV_MODE_DEVICE
);
return BLE_ERROR_NONE;
}
ble_error_t PalPrivateAddressController::remove_device_from_resolving_list(
target_peer_address_type_t peer_address_type,
const address_t &peer_identity_address
)
{
if (is_ll_privacy_supported() == false) {
return BLE_ERROR_NOT_IMPLEMENTED;
}
DmPrivRemDevFromResList(peer_address_type.value(), peer_identity_address.data(), 0);
return BLE_ERROR_NONE;
}
ble_error_t PalPrivateAddressController::set_peer_privacy_mode(
target_peer_address_type_t peer_address_type,
const address_t &peer_address,
privacy_mode_t privacy_mode
)
{
if (is_ll_privacy_supported() == false) {
return BLE_ERROR_NOT_IMPLEMENTED;
}
DmPrivSetPrivacyMode(
peer_address_type.value(),
peer_address.data(),
privacy_mode.value()
);
return BLE_ERROR_NONE;
}
ble_error_t PalPrivateAddressController::clear_resolving_list()
{
if (is_ll_privacy_supported() == false) {
return BLE_ERROR_NOT_IMPLEMENTED;
}
DmPrivClearResList();
return BLE_ERROR_NONE;
}
void PalPrivateAddressController::set_event_handler(EventHandler *handler)
{
_event_handler = handler;
}
PalPrivateAddressController& PalPrivateAddressController::instance()
{
static impl::PalPrivateAddressController self;
return self;
}
bool PalPrivateAddressController::cordio_handler(const wsfMsgHdr_t *msg)
{
if (msg == nullptr) {
return false;
}
auto* handler = instance()._event_handler;
switch (msg->event) {
case DM_PRIV_GENERATE_ADDR_IND: {
instance()._generating_rpa = false;
if (!handler) {
return true;
}
const auto *evt = (const dmPrivGenAddrIndEvt_t*) msg;
if (evt->hdr.status == HCI_SUCCESS) {
handler->on_resolvable_private_address_generated(evt->addr);
} else {
handler->on_resolvable_private_address_generated(address_t{});
}
return true;
}
#if BLE_GAP_HOST_BASED_PRIVATE_ADDRESS_RESOLUTION
case DM_PRIV_RESOLVED_ADDR_IND: {
instance()._resolving_rpa = false;
if (!handler) {
return true;
}
handler->on_private_address_resolved(msg->status == HCI_SUCCESS);
return true;
}
#endif // BLE_GAP_HOST_BASED_PRIVATE_ADDRESS_RESOLUTION
case DM_PRIV_ADD_DEV_TO_RES_LIST_IND: // Device added to resolving list
case DM_PRIV_REM_DEV_FROM_RES_LIST_IND: // Device removed from resolving list
case DM_PRIV_CLEAR_RES_LIST_IND: // Resolving list cleared
{
if (!handler) {
return true;
}
// Previous command completed, we can move to the next control block
handler->on_resolving_list_action_complete();
return true;
}
default:
return false;
}
}
} // namespace impl
} // namespace ble
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "3DChartObjects.hxx"
#include <vcl/virdev.hxx>
#include <vcl/svapp.hxx>
#include <vcl/opengl/GLMHelper.hxx>
#include <vcl/opengl/OpenGLHelper.hxx>
#include <vcl/bmpacc.hxx>
namespace chart {
namespace opengl3D {
Renderable3DObject::Renderable3DObject(OpenGL3DRenderer* pRenderer, sal_uInt32 nId):
mpRenderer(pRenderer),
mnUniqueId(nId)
{
}
void Renderable3DObject::render()
{
(void) mnUniqueId;
}
Bar::Bar(OpenGL3DRenderer* pRenderer, const glm::mat4& rPosition, sal_uInt32 aColor, sal_uInt32 nId)
: Renderable3DObject(pRenderer, nId)
, mbRoundedCorners(true)
, maPos(rPosition)
, maColor(aColor)
{
SAL_INFO("chart2.3dopengl", rPosition);
}
void Bar::render()
{
mpRenderer->AddShape3DExtrudeObject(mbRoundedCorners, maColor.GetColor(), 0xFFFFFF, maPos, mnUniqueId);
mpRenderer->EndAddShape3DExtrudeObject();
}
Line::Line(OpenGL3DRenderer* pRenderer, sal_uInt32 nId):
Renderable3DObject(pRenderer, nId)
{
}
void Line::render()
{
mpRenderer->AddShapePolygon3DObject(0, true, maLineColor.GetColor(), 0, 0, mnUniqueId);
mpRenderer->AddPolygon3DObjectPoint(maPosBegin.x, maPosBegin.y, maPosBegin.z);
mpRenderer->AddPolygon3DObjectPoint(maPosEnd.x, maPosEnd.y, maPosEnd.z);
mpRenderer->EndAddPolygon3DObjectPoint();
mpRenderer->EndAddShapePolygon3DObject();
}
void Line::setPosition(const glm::vec3& rBegin, const glm::vec3& rEnd)
{
maPosBegin = rBegin;
maPosEnd = rEnd;
}
void Line::setLineColor(const Color& rColor)
{
maLineColor = rColor;
}
const TextCacheItem& TextCache::getText(OUString const & rText, bool bIs3dText)
{
TextCacheType::const_iterator itr = maTextCache.find(rText);
if(itr != maTextCache.end())
return *itr->second;
ScopedVclPtrInstance< VirtualDevice > pDevice(*Application::GetDefaultDevice(), 0, 0);
vcl::Font aFont;
if(bIs3dText)
aFont = vcl::Font("Brillante St",Size(0,0));
else
aFont = pDevice->GetFont();
aFont.SetSize(Size(0, 96));
static bool bOldRender = getenv("OLDRENDER");
if (bOldRender)
aFont.SetColor(COL_BLACK);
else
aFont.SetColor(COL_GREEN); // RGB_COLORDATA(0xf0, 0xf0, 0xf0));
pDevice->SetFont(aFont);
pDevice->Erase();
pDevice->SetOutputSize(Size(pDevice->GetTextWidth(rText), pDevice->GetTextHeight()));
pDevice->SetBackground(Wallpaper(COL_TRANSPARENT));
pDevice->DrawText(Point(0,0), rText);
BitmapEx aText(pDevice->GetBitmapEx(Point(0,0), pDevice->GetOutputSize()));
// TextCacheItem *pItem = new TextCacheItem(OpenGLHelper::ConvertBitmapExToRGBABuffer(aText), aText.GetSizePixel());
Bitmap aBitmap (aText.GetBitmap());
BitmapReadAccess *pAcc = aBitmap.AcquireReadAccess();
sal_uInt8 *buf = (sal_uInt8 *)pAcc->GetBuffer();
long nBmpWidth = aText.GetSizePixel().Width();
long nBmpHeight = aText.GetSizePixel().Height();
sal_uInt8* pBitmapBuf(new sal_uInt8[3* nBmpWidth * nBmpHeight]);
memcpy(pBitmapBuf, buf, 3* nBmpWidth * nBmpHeight);
TextCacheItem *pItem = new TextCacheItem(pBitmapBuf, aText.GetSizePixel());
maTextCache.insert(rText, pItem);
return *maTextCache.find(rText)->second;
}
Text::Text(OpenGL3DRenderer* pRenderer, TextCache& rTextCache, const OUString& rStr, sal_uInt32 nId):
Renderable3DObject(pRenderer, nId),
maText(rTextCache.getText(rStr))
{
}
void Text::render()
{
glm::vec3 dir2 = maTopRight - maTopLeft;
glm::vec3 bottomLeft = maBottomRight - dir2;
mpRenderer->CreateTextTexture(maText.maPixels, maText.maSize,
maTopLeft, maTopRight, maBottomRight, bottomLeft,
mnUniqueId);
}
void Text::setPosition(const glm::vec3& rTopLeft, const glm::vec3& rTopRight, const glm::vec3& rBottomRight)
{
maTopLeft = rTopLeft;
maTopRight = rTopRight;
maBottomRight = rBottomRight;
}
ScreenText::ScreenText(OpenGL3DRenderer* pRenderer, TextCache& rTextCache,
const OUString& rStr, glm::vec4 rColor, sal_uInt32 nId, bool bIs3dText):
Renderable3DObject(pRenderer, nId),
maText(rTextCache.getText(rStr,bIs3dText)),
maColor(rColor)
{
}
void ScreenText::setPosition(const glm::vec2& rTopLeft, const glm::vec2& rBottomRight,
const glm::vec3& r3DPos)
{
maTopLeft = rTopLeft;
maBottomRight = rBottomRight;
ma3DPos = r3DPos;
}
void ScreenText::render()
{
mpRenderer->CreateScreenTextTexture(maText.maPixels, maText.maSize,
maTopLeft, maBottomRight, ma3DPos, maColor,
mnUniqueId);
}
Rectangle::Rectangle(OpenGL3DRenderer* pRenderer, sal_uInt32 nId):
Renderable3DObject(pRenderer, nId)
{
}
void Rectangle::render()
{
glm::vec3 dir1 = maBottomRight - maTopLeft;
glm::vec3 dir2 = maTopRight - maTopLeft;
glm::vec3 normal = glm::normalize(glm::cross(dir1, dir2));
mpRenderer->AddShapePolygon3DObject(maColor.GetColor(), false, 0, 1, 0xFFFFFF, mnUniqueId);
glm::vec3 bottomLeft = maBottomRight - dir2;
//set polygon points and normals
mpRenderer->AddPolygon3DObjectPoint(maBottomRight.x, maBottomRight.y, maBottomRight.z);
mpRenderer->AddPolygon3DObjectNormalPoint(normal.x, normal.y, normal.z);
mpRenderer->AddPolygon3DObjectPoint(maTopRight.x, maTopRight.y, maTopRight.z);
mpRenderer->AddPolygon3DObjectNormalPoint(normal.x, normal.y, normal.z);
mpRenderer->AddPolygon3DObjectPoint(maTopLeft.x, maTopLeft.y, maTopLeft.z);
mpRenderer->AddPolygon3DObjectNormalPoint(normal.x, normal.y, normal.z);
mpRenderer->AddPolygon3DObjectPoint(bottomLeft.x, bottomLeft.y, bottomLeft.z);
mpRenderer->AddPolygon3DObjectNormalPoint(normal.x, normal.y, normal.z);
mpRenderer->EndAddPolygon3DObjectPoint();
mpRenderer->EndAddPolygon3DObjectNormalPoint();
mpRenderer->EndAddShapePolygon3DObject();
//we should render the edge if the edge color is different from the fill color
if (maColor.GetColor() != maLineColor.GetColor())
{
mpRenderer->AddShapePolygon3DObject(0, true, maLineColor.GetColor(), 0, 0xFFFFFF, mnUniqueId);
mpRenderer->AddPolygon3DObjectPoint(maBottomRight.x, maBottomRight.y, maBottomRight.z);
mpRenderer->AddPolygon3DObjectPoint(maTopRight.x, maTopRight.y, maTopRight.z);
mpRenderer->AddPolygon3DObjectPoint(maTopLeft.x, maTopLeft.y, maTopLeft.z);
mpRenderer->AddPolygon3DObjectPoint(bottomLeft.x, bottomLeft.y, bottomLeft.z);
mpRenderer->EndAddPolygon3DObjectPoint();
mpRenderer->EndAddShapePolygon3DObject();
}
}
void Rectangle::setPosition(const glm::vec3& rTopLeft, const glm::vec3& rTopRight, const glm::vec3& rBottomRight)
{
maTopLeft = rTopLeft;
maTopRight = rTopRight;
maBottomRight = rBottomRight;
}
void Rectangle::setFillColor(const Color& rColor)
{
maColor = rColor;
}
void Rectangle::setLineColor(const Color& rColor)
{
maLineColor = rColor;
}
Camera::Camera(OpenGL3DRenderer* pRenderer):
Renderable3DObject(pRenderer, 0),
maPos(10,-50,20),
maUp(0, 0, 1),
maDirection(glm::vec3(0,0,0))
{
}
void Camera::render()
{
mpRenderer->SetCameraInfo(maPos, maDirection, maUp);
}
void Camera::setPosition(const glm::vec3& rPos)
{
maPos = rPos;
}
void Camera::setDirection(const glm::vec3& rDir)
{
maDirection = rDir;
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>loplugin:cstylecast: deal with those that are (technically) const_cast<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "3DChartObjects.hxx"
#include <vcl/virdev.hxx>
#include <vcl/svapp.hxx>
#include <vcl/opengl/GLMHelper.hxx>
#include <vcl/opengl/OpenGLHelper.hxx>
#include <vcl/bmpacc.hxx>
namespace chart {
namespace opengl3D {
Renderable3DObject::Renderable3DObject(OpenGL3DRenderer* pRenderer, sal_uInt32 nId):
mpRenderer(pRenderer),
mnUniqueId(nId)
{
}
void Renderable3DObject::render()
{
(void) mnUniqueId;
}
Bar::Bar(OpenGL3DRenderer* pRenderer, const glm::mat4& rPosition, sal_uInt32 aColor, sal_uInt32 nId)
: Renderable3DObject(pRenderer, nId)
, mbRoundedCorners(true)
, maPos(rPosition)
, maColor(aColor)
{
SAL_INFO("chart2.3dopengl", rPosition);
}
void Bar::render()
{
mpRenderer->AddShape3DExtrudeObject(mbRoundedCorners, maColor.GetColor(), 0xFFFFFF, maPos, mnUniqueId);
mpRenderer->EndAddShape3DExtrudeObject();
}
Line::Line(OpenGL3DRenderer* pRenderer, sal_uInt32 nId):
Renderable3DObject(pRenderer, nId)
{
}
void Line::render()
{
mpRenderer->AddShapePolygon3DObject(0, true, maLineColor.GetColor(), 0, 0, mnUniqueId);
mpRenderer->AddPolygon3DObjectPoint(maPosBegin.x, maPosBegin.y, maPosBegin.z);
mpRenderer->AddPolygon3DObjectPoint(maPosEnd.x, maPosEnd.y, maPosEnd.z);
mpRenderer->EndAddPolygon3DObjectPoint();
mpRenderer->EndAddShapePolygon3DObject();
}
void Line::setPosition(const glm::vec3& rBegin, const glm::vec3& rEnd)
{
maPosBegin = rBegin;
maPosEnd = rEnd;
}
void Line::setLineColor(const Color& rColor)
{
maLineColor = rColor;
}
const TextCacheItem& TextCache::getText(OUString const & rText, bool bIs3dText)
{
TextCacheType::const_iterator itr = maTextCache.find(rText);
if(itr != maTextCache.end())
return *itr->second;
ScopedVclPtrInstance< VirtualDevice > pDevice(*Application::GetDefaultDevice(), 0, 0);
vcl::Font aFont;
if(bIs3dText)
aFont = vcl::Font("Brillante St",Size(0,0));
else
aFont = pDevice->GetFont();
aFont.SetSize(Size(0, 96));
static bool bOldRender = getenv("OLDRENDER");
if (bOldRender)
aFont.SetColor(COL_BLACK);
else
aFont.SetColor(COL_GREEN); // RGB_COLORDATA(0xf0, 0xf0, 0xf0));
pDevice->SetFont(aFont);
pDevice->Erase();
pDevice->SetOutputSize(Size(pDevice->GetTextWidth(rText), pDevice->GetTextHeight()));
pDevice->SetBackground(Wallpaper(COL_TRANSPARENT));
pDevice->DrawText(Point(0,0), rText);
BitmapEx aText(pDevice->GetBitmapEx(Point(0,0), pDevice->GetOutputSize()));
// TextCacheItem *pItem = new TextCacheItem(OpenGLHelper::ConvertBitmapExToRGBABuffer(aText), aText.GetSizePixel());
Bitmap aBitmap (aText.GetBitmap());
BitmapReadAccess *pAcc = aBitmap.AcquireReadAccess();
sal_uInt8 *buf = reinterpret_cast<sal_uInt8 *>(pAcc->GetBuffer());
long nBmpWidth = aText.GetSizePixel().Width();
long nBmpHeight = aText.GetSizePixel().Height();
sal_uInt8* pBitmapBuf(new sal_uInt8[3* nBmpWidth * nBmpHeight]);
memcpy(pBitmapBuf, buf, 3* nBmpWidth * nBmpHeight);
TextCacheItem *pItem = new TextCacheItem(pBitmapBuf, aText.GetSizePixel());
maTextCache.insert(rText, pItem);
return *maTextCache.find(rText)->second;
}
Text::Text(OpenGL3DRenderer* pRenderer, TextCache& rTextCache, const OUString& rStr, sal_uInt32 nId):
Renderable3DObject(pRenderer, nId),
maText(rTextCache.getText(rStr))
{
}
void Text::render()
{
glm::vec3 dir2 = maTopRight - maTopLeft;
glm::vec3 bottomLeft = maBottomRight - dir2;
mpRenderer->CreateTextTexture(maText.maPixels, maText.maSize,
maTopLeft, maTopRight, maBottomRight, bottomLeft,
mnUniqueId);
}
void Text::setPosition(const glm::vec3& rTopLeft, const glm::vec3& rTopRight, const glm::vec3& rBottomRight)
{
maTopLeft = rTopLeft;
maTopRight = rTopRight;
maBottomRight = rBottomRight;
}
ScreenText::ScreenText(OpenGL3DRenderer* pRenderer, TextCache& rTextCache,
const OUString& rStr, glm::vec4 rColor, sal_uInt32 nId, bool bIs3dText):
Renderable3DObject(pRenderer, nId),
maText(rTextCache.getText(rStr,bIs3dText)),
maColor(rColor)
{
}
void ScreenText::setPosition(const glm::vec2& rTopLeft, const glm::vec2& rBottomRight,
const glm::vec3& r3DPos)
{
maTopLeft = rTopLeft;
maBottomRight = rBottomRight;
ma3DPos = r3DPos;
}
void ScreenText::render()
{
mpRenderer->CreateScreenTextTexture(maText.maPixels, maText.maSize,
maTopLeft, maBottomRight, ma3DPos, maColor,
mnUniqueId);
}
Rectangle::Rectangle(OpenGL3DRenderer* pRenderer, sal_uInt32 nId):
Renderable3DObject(pRenderer, nId)
{
}
void Rectangle::render()
{
glm::vec3 dir1 = maBottomRight - maTopLeft;
glm::vec3 dir2 = maTopRight - maTopLeft;
glm::vec3 normal = glm::normalize(glm::cross(dir1, dir2));
mpRenderer->AddShapePolygon3DObject(maColor.GetColor(), false, 0, 1, 0xFFFFFF, mnUniqueId);
glm::vec3 bottomLeft = maBottomRight - dir2;
//set polygon points and normals
mpRenderer->AddPolygon3DObjectPoint(maBottomRight.x, maBottomRight.y, maBottomRight.z);
mpRenderer->AddPolygon3DObjectNormalPoint(normal.x, normal.y, normal.z);
mpRenderer->AddPolygon3DObjectPoint(maTopRight.x, maTopRight.y, maTopRight.z);
mpRenderer->AddPolygon3DObjectNormalPoint(normal.x, normal.y, normal.z);
mpRenderer->AddPolygon3DObjectPoint(maTopLeft.x, maTopLeft.y, maTopLeft.z);
mpRenderer->AddPolygon3DObjectNormalPoint(normal.x, normal.y, normal.z);
mpRenderer->AddPolygon3DObjectPoint(bottomLeft.x, bottomLeft.y, bottomLeft.z);
mpRenderer->AddPolygon3DObjectNormalPoint(normal.x, normal.y, normal.z);
mpRenderer->EndAddPolygon3DObjectPoint();
mpRenderer->EndAddPolygon3DObjectNormalPoint();
mpRenderer->EndAddShapePolygon3DObject();
//we should render the edge if the edge color is different from the fill color
if (maColor.GetColor() != maLineColor.GetColor())
{
mpRenderer->AddShapePolygon3DObject(0, true, maLineColor.GetColor(), 0, 0xFFFFFF, mnUniqueId);
mpRenderer->AddPolygon3DObjectPoint(maBottomRight.x, maBottomRight.y, maBottomRight.z);
mpRenderer->AddPolygon3DObjectPoint(maTopRight.x, maTopRight.y, maTopRight.z);
mpRenderer->AddPolygon3DObjectPoint(maTopLeft.x, maTopLeft.y, maTopLeft.z);
mpRenderer->AddPolygon3DObjectPoint(bottomLeft.x, bottomLeft.y, bottomLeft.z);
mpRenderer->EndAddPolygon3DObjectPoint();
mpRenderer->EndAddShapePolygon3DObject();
}
}
void Rectangle::setPosition(const glm::vec3& rTopLeft, const glm::vec3& rTopRight, const glm::vec3& rBottomRight)
{
maTopLeft = rTopLeft;
maTopRight = rTopRight;
maBottomRight = rBottomRight;
}
void Rectangle::setFillColor(const Color& rColor)
{
maColor = rColor;
}
void Rectangle::setLineColor(const Color& rColor)
{
maLineColor = rColor;
}
Camera::Camera(OpenGL3DRenderer* pRenderer):
Renderable3DObject(pRenderer, 0),
maPos(10,-50,20),
maUp(0, 0, 1),
maDirection(glm::vec3(0,0,0))
{
}
void Camera::render()
{
mpRenderer->SetCameraInfo(maPos, maDirection, maUp);
}
void Camera::setPosition(const glm::vec3& rPos)
{
maPos = rPos;
}
void Camera::setDirection(const glm::vec3& rDir)
{
maDirection = rDir;
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <shlwapi.h>
#include <sstream>
#include <string>
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "chrome/browser/automation/url_request_mock_http_job.h"
#include "chrome/browser/automation/url_request_slow_download_job.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "net/url_request/url_request_unittest.h"
using std::wstring;
namespace {
const wchar_t kDocRoot[] = L"chrome/test/data";
// Checks if the volume supports Alternate Data Streams. This is required for
// the Zone Identifier implementation.
bool VolumeSupportsADS(const std::wstring path) {
wchar_t drive[MAX_PATH] = {0};
wcscpy_s(drive, MAX_PATH, path.c_str());
EXPECT_TRUE(PathStripToRootW(drive));
DWORD fs_flags = 0;
EXPECT_TRUE(GetVolumeInformationW(drive, NULL, 0, 0, NULL, &fs_flags, NULL,
0));
if (fs_flags & FILE_NAMED_STREAMS)
return true;
return false;
}
// Checks if the ZoneIdentifier is correctly set to "Internet" (3)
void CheckZoneIdentifier(const std::wstring full_path) {
const DWORD kShare = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
std::wstring path = full_path + L":Zone.Identifier";
HANDLE file = CreateFile(path.c_str(), GENERIC_READ, kShare, NULL,
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
ASSERT_TRUE(INVALID_HANDLE_VALUE != file);
char buffer[100] = {0};
DWORD read = 0;
ASSERT_TRUE(ReadFile(file, buffer, 100, &read, NULL));
CloseHandle(file);
const char kIdentifier[] = "[ZoneTransfer]\nZoneId=3";
ASSERT_EQ(arraysize(kIdentifier), read);
ASSERT_EQ(0, strcmp(kIdentifier, buffer));
}
class DownloadTest : public UITest {
protected:
DownloadTest() : UITest() {}
void CleanUpDownload(const std::wstring& client_filename,
const std::wstring& server_filename) {
// Find the path on the client.
std::wstring file_on_client(download_prefix_);
file_on_client.append(client_filename);
EXPECT_TRUE(file_util::PathExists(file_on_client));
// Find the path on the server.
std::wstring file_on_server;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA,
&file_on_server));
file_on_server.append(L"\\");
file_on_server.append(server_filename);
ASSERT_TRUE(file_util::PathExists(file_on_server));
// Check that we downloaded the file correctly.
EXPECT_TRUE(file_util::ContentsEqual(file_on_server,
file_on_client));
// Check if the Zone Identifier is correclty set.
if (VolumeSupportsADS(file_on_client))
CheckZoneIdentifier(file_on_client);
// Delete the client copy of the file.
EXPECT_TRUE(file_util::Delete(file_on_client, false));
}
void CleanUpDownload(const std::wstring& file) {
CleanUpDownload(file, file);
}
virtual void SetUp() {
UITest::SetUp();
download_prefix_ = GetDownloadDirectory();
download_prefix_ += FilePath::kSeparators[0];
}
protected:
void RunSizeTest(const wstring& url,
const wstring& expected_title_in_progress,
const wstring& expected_title_finished) {
{
EXPECT_EQ(1, GetTabCount());
NavigateToURL(GURL(url));
// Downloads appear in the shelf
WaitUntilTabCount(1);
// TODO(tc): check download status text
// Complete sending the request. We do this by loading a second URL in a
// separate tab.
scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
EXPECT_TRUE(window->AppendTab(GURL(
URLRequestSlowDownloadJob::kFinishDownloadUrl)));
EXPECT_EQ(2, GetTabCount());
// TODO(tc): check download status text
// Make sure the download shelf is showing.
scoped_ptr<TabProxy> dl_tab(window->GetTab(0));
ASSERT_TRUE(dl_tab.get());
EXPECT_TRUE(WaitForDownloadShelfVisible(dl_tab.get()));
}
std::wstring filename = file_util::GetFilenameFromPath(url);
EXPECT_TRUE(file_util::PathExists(download_prefix_ + filename));
// Delete the file we just downloaded.
for (int i = 0; i < 10; ++i) {
if (file_util::Delete(download_prefix_ + filename, false))
break;
PlatformThread::Sleep(action_max_timeout_ms() / 10);
}
EXPECT_FALSE(file_util::PathExists(download_prefix_ + filename));
}
wstring download_prefix_;
};
} // namespace
// Download a file with non-viewable content, verify that the
// download tab opened and the file exists.
TEST_F(DownloadTest, DownloadMimeType) {
wstring file = L"download-test1.lib";
wstring expected_title = L"100% - " + file;
EXPECT_EQ(1, GetTabCount());
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file));
// No new tabs created, downloads appear in the current tab's download shelf.
WaitUntilTabCount(1);
// Wait until the file is downloaded.
PlatformThread::Sleep(action_timeout_ms());
CleanUpDownload(file);
scoped_ptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
EXPECT_TRUE(WaitForDownloadShelfVisible(tab_proxy.get()));
}
// Access a file with a viewable mime-type, verify that a download
// did not initiate.
TEST_F(DownloadTest, NoDownload) {
wstring file = L"download-test2.html";
wstring file_path = download_prefix_;
file_util::AppendToPath(&file_path, file);
if (file_util::PathExists(file_path))
ASSERT_TRUE(file_util::Delete(file_path, false));
EXPECT_EQ(1, GetTabCount());
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file));
WaitUntilTabCount(1);
// Wait to see if the file will be downloaded.
PlatformThread::Sleep(action_timeout_ms());
EXPECT_FALSE(file_util::PathExists(file_path));
if (file_util::PathExists(file_path))
ASSERT_TRUE(file_util::Delete(file_path, false));
scoped_ptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
EXPECT_FALSE(WaitForDownloadShelfVisible(tab_proxy.get()));
}
// Download a 0-size file with a content-disposition header, verify that the
// download tab opened and the file exists as the filename specified in the
// header. This also ensures we properly handle empty file downloads.
TEST_F(DownloadTest, ContentDisposition) {
wstring file = L"download-test3.gif";
wstring download_file = L"download-test3-attachment.gif";
wstring expected_title = L"100% - " + download_file;
EXPECT_EQ(1, GetTabCount());
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file));
WaitUntilTabCount(1);
// Wait until the file is downloaded.
PlatformThread::Sleep(action_timeout_ms());
CleanUpDownload(download_file, file);
// Ensure the download shelf is visible on the current tab.
scoped_ptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
EXPECT_TRUE(WaitForDownloadShelfVisible(tab_proxy.get()));
}
// UnknownSize and KnownSize are tests which depend on
// URLRequestSlowDownloadJob to serve content in a certain way. Data will be
// sent in two chunks where the first chunk is 35K and the second chunk is 10K.
// The test will first attempt to download a file; but the server will "pause"
// in the middle until the server receives a second request for
// "download-finish. At that time, the download will finish.
TEST_F(DownloadTest, UnknownSize) {
std::wstring url(URLRequestSlowDownloadJob::kUnknownSizeUrl);
std::wstring filename = file_util::GetFilenameFromPath(url);
RunSizeTest(url, L"32.0 KB - " + filename, L"100% - " + filename);
}
// http://b/1158253
TEST_F(DownloadTest, DISABLED_KnownSize) {
std::wstring url(URLRequestSlowDownloadJob::kKnownSizeUrl);
std::wstring filename = file_util::GetFilenameFromPath(url);
RunSizeTest(url, L"71% - " + filename, L"100% - " + filename);
}
<commit_msg>Disable DownloadTest.UnknownSize because it is flaky.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <shlwapi.h>
#include <sstream>
#include <string>
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "chrome/browser/automation/url_request_mock_http_job.h"
#include "chrome/browser/automation/url_request_slow_download_job.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "net/url_request/url_request_unittest.h"
using std::wstring;
namespace {
const wchar_t kDocRoot[] = L"chrome/test/data";
// Checks if the volume supports Alternate Data Streams. This is required for
// the Zone Identifier implementation.
bool VolumeSupportsADS(const std::wstring path) {
wchar_t drive[MAX_PATH] = {0};
wcscpy_s(drive, MAX_PATH, path.c_str());
EXPECT_TRUE(PathStripToRootW(drive));
DWORD fs_flags = 0;
EXPECT_TRUE(GetVolumeInformationW(drive, NULL, 0, 0, NULL, &fs_flags, NULL,
0));
if (fs_flags & FILE_NAMED_STREAMS)
return true;
return false;
}
// Checks if the ZoneIdentifier is correctly set to "Internet" (3)
void CheckZoneIdentifier(const std::wstring full_path) {
const DWORD kShare = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
std::wstring path = full_path + L":Zone.Identifier";
HANDLE file = CreateFile(path.c_str(), GENERIC_READ, kShare, NULL,
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
ASSERT_TRUE(INVALID_HANDLE_VALUE != file);
char buffer[100] = {0};
DWORD read = 0;
ASSERT_TRUE(ReadFile(file, buffer, 100, &read, NULL));
CloseHandle(file);
const char kIdentifier[] = "[ZoneTransfer]\nZoneId=3";
ASSERT_EQ(arraysize(kIdentifier), read);
ASSERT_EQ(0, strcmp(kIdentifier, buffer));
}
class DownloadTest : public UITest {
protected:
DownloadTest() : UITest() {}
void CleanUpDownload(const std::wstring& client_filename,
const std::wstring& server_filename) {
// Find the path on the client.
std::wstring file_on_client(download_prefix_);
file_on_client.append(client_filename);
EXPECT_TRUE(file_util::PathExists(file_on_client));
// Find the path on the server.
std::wstring file_on_server;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA,
&file_on_server));
file_on_server.append(L"\\");
file_on_server.append(server_filename);
ASSERT_TRUE(file_util::PathExists(file_on_server));
// Check that we downloaded the file correctly.
EXPECT_TRUE(file_util::ContentsEqual(file_on_server,
file_on_client));
// Check if the Zone Identifier is correclty set.
if (VolumeSupportsADS(file_on_client))
CheckZoneIdentifier(file_on_client);
// Delete the client copy of the file.
EXPECT_TRUE(file_util::Delete(file_on_client, false));
}
void CleanUpDownload(const std::wstring& file) {
CleanUpDownload(file, file);
}
virtual void SetUp() {
UITest::SetUp();
download_prefix_ = GetDownloadDirectory();
download_prefix_ += FilePath::kSeparators[0];
}
protected:
void RunSizeTest(const wstring& url,
const wstring& expected_title_in_progress,
const wstring& expected_title_finished) {
{
EXPECT_EQ(1, GetTabCount());
NavigateToURL(GURL(url));
// Downloads appear in the shelf
WaitUntilTabCount(1);
// TODO(tc): check download status text
// Complete sending the request. We do this by loading a second URL in a
// separate tab.
scoped_ptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
EXPECT_TRUE(window->AppendTab(GURL(
URLRequestSlowDownloadJob::kFinishDownloadUrl)));
EXPECT_EQ(2, GetTabCount());
// TODO(tc): check download status text
// Make sure the download shelf is showing.
scoped_ptr<TabProxy> dl_tab(window->GetTab(0));
ASSERT_TRUE(dl_tab.get());
EXPECT_TRUE(WaitForDownloadShelfVisible(dl_tab.get()));
}
std::wstring filename = file_util::GetFilenameFromPath(url);
EXPECT_TRUE(file_util::PathExists(download_prefix_ + filename));
// Delete the file we just downloaded.
for (int i = 0; i < 10; ++i) {
if (file_util::Delete(download_prefix_ + filename, false))
break;
PlatformThread::Sleep(action_max_timeout_ms() / 10);
}
EXPECT_FALSE(file_util::PathExists(download_prefix_ + filename));
}
wstring download_prefix_;
};
} // namespace
// Download a file with non-viewable content, verify that the
// download tab opened and the file exists.
TEST_F(DownloadTest, DownloadMimeType) {
wstring file = L"download-test1.lib";
wstring expected_title = L"100% - " + file;
EXPECT_EQ(1, GetTabCount());
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file));
// No new tabs created, downloads appear in the current tab's download shelf.
WaitUntilTabCount(1);
// Wait until the file is downloaded.
PlatformThread::Sleep(action_timeout_ms());
CleanUpDownload(file);
scoped_ptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
EXPECT_TRUE(WaitForDownloadShelfVisible(tab_proxy.get()));
}
// Access a file with a viewable mime-type, verify that a download
// did not initiate.
TEST_F(DownloadTest, NoDownload) {
wstring file = L"download-test2.html";
wstring file_path = download_prefix_;
file_util::AppendToPath(&file_path, file);
if (file_util::PathExists(file_path))
ASSERT_TRUE(file_util::Delete(file_path, false));
EXPECT_EQ(1, GetTabCount());
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file));
WaitUntilTabCount(1);
// Wait to see if the file will be downloaded.
PlatformThread::Sleep(action_timeout_ms());
EXPECT_FALSE(file_util::PathExists(file_path));
if (file_util::PathExists(file_path))
ASSERT_TRUE(file_util::Delete(file_path, false));
scoped_ptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
EXPECT_FALSE(WaitForDownloadShelfVisible(tab_proxy.get()));
}
// Download a 0-size file with a content-disposition header, verify that the
// download tab opened and the file exists as the filename specified in the
// header. This also ensures we properly handle empty file downloads.
TEST_F(DownloadTest, ContentDisposition) {
wstring file = L"download-test3.gif";
wstring download_file = L"download-test3-attachment.gif";
wstring expected_title = L"100% - " + download_file;
EXPECT_EQ(1, GetTabCount());
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file));
WaitUntilTabCount(1);
// Wait until the file is downloaded.
PlatformThread::Sleep(action_timeout_ms());
CleanUpDownload(download_file, file);
// Ensure the download shelf is visible on the current tab.
scoped_ptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
EXPECT_TRUE(WaitForDownloadShelfVisible(tab_proxy.get()));
}
// UnknownSize and KnownSize are tests which depend on
// URLRequestSlowDownloadJob to serve content in a certain way. Data will be
// sent in two chunks where the first chunk is 35K and the second chunk is 10K.
// The test will first attempt to download a file; but the server will "pause"
// in the middle until the server receives a second request for
// "download-finish. At that time, the download will finish.
// TODO(paul): Reenable, http://code.google.com/p/chromium/issues/detail?id=7191
TEST_F(DownloadTest, DISABLED_UnknownSize) {
std::wstring url(URLRequestSlowDownloadJob::kUnknownSizeUrl);
std::wstring filename = file_util::GetFilenameFromPath(url);
RunSizeTest(url, L"32.0 KB - " + filename, L"100% - " + filename);
}
// http://b/1158253
TEST_F(DownloadTest, DISABLED_KnownSize) {
std::wstring url(URLRequestSlowDownloadJob::kKnownSizeUrl);
std::wstring filename = file_util::GetFilenameFromPath(url);
RunSizeTest(url, L"71% - " + filename, L"100% - " + filename);
}
<|endoftext|> |
<commit_before>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
#include "host/desktop_session_ipc.h"
#include "base/logging.h"
#include "codec/video_util.h"
#include "common/message_serialization.h"
#include "desktop/mouse_cursor.h"
#include "desktop/shared_memory_desktop_frame.h"
#include "ipc/ipc_channel.h"
#include "ipc/shared_memory.h"
namespace host {
class DesktopSessionIpc::SharedBuffer : public ipc::SharedMemoryBase
{
public:
~SharedBuffer() = default;
static std::unique_ptr<SharedBuffer> wrap(std::unique_ptr<ipc::SharedMemory> shared_memory)
{
std::shared_ptr<ipc::SharedMemory> shared_frame(shared_memory.release());
return std::unique_ptr<SharedBuffer>(new SharedBuffer(shared_frame));
}
std::unique_ptr<SharedBuffer> share()
{
return std::unique_ptr<SharedBuffer>(new SharedBuffer(shared_memory_));
}
void* data() override
{
return shared_memory_->data();
}
Handle handle() const override
{
return shared_memory_->handle();
}
int id() const override
{
return shared_memory_->id();
}
private:
explicit SharedBuffer(std::shared_ptr<ipc::SharedMemory>& shared_memory)
: shared_memory_(shared_memory)
{
// Nothing
}
std::shared_ptr<ipc::SharedMemory> shared_memory_;
DISALLOW_COPY_AND_ASSIGN(SharedBuffer);
};
DesktopSessionIpc::DesktopSessionIpc(std::unique_ptr<ipc::Channel> channel, Delegate* delegate)
: channel_(std::move(channel)),
delegate_(delegate)
{
DCHECK(channel_);
DCHECK(delegate_);
}
DesktopSessionIpc::~DesktopSessionIpc() = default;
void DesktopSessionIpc::start()
{
channel_->setListener(this);
channel_->resume();
delegate_->onDesktopSessionStarted();
}
void DesktopSessionIpc::enableSession(bool enable)
{
outgoing_message_.Clear();
outgoing_message_.mutable_enable_session()->set_enable(enable);
channel_->send(common::serializeMessage(outgoing_message_));
}
void DesktopSessionIpc::selectScreen(const proto::Screen& screen)
{
outgoing_message_.Clear();
outgoing_message_.mutable_select_source()->mutable_screen()->CopyFrom(screen);
channel_->send(common::serializeMessage(outgoing_message_));
}
void DesktopSessionIpc::enableFeatures(const proto::internal::EnableFeatures& features)
{
outgoing_message_.Clear();
outgoing_message_.mutable_enable_features()->CopyFrom(features);
channel_->send(common::serializeMessage(outgoing_message_));
}
void DesktopSessionIpc::injectKeyEvent(const proto::KeyEvent& event)
{
outgoing_message_.Clear();
outgoing_message_.mutable_key_event()->CopyFrom(event);
channel_->send(common::serializeMessage(outgoing_message_));
}
void DesktopSessionIpc::injectPointerEvent(const proto::PointerEvent& event)
{
outgoing_message_.Clear();
outgoing_message_.mutable_pointer_event()->CopyFrom(event);
channel_->send(common::serializeMessage(outgoing_message_));
}
void DesktopSessionIpc::injectClipboardEvent(const proto::ClipboardEvent& event)
{
outgoing_message_.Clear();
outgoing_message_.mutable_clipboard_event()->CopyFrom(event);
channel_->send(common::serializeMessage(outgoing_message_));
}
void DesktopSessionIpc::userSessionControl(proto::internal::UserSessionControl::Action action)
{
outgoing_message_.Clear();
outgoing_message_.mutable_user_session_control()->set_action(action);
channel_->send(common::serializeMessage(outgoing_message_));
}
void DesktopSessionIpc::onDisconnected()
{
delegate_->onDesktopSessionStopped();
}
void DesktopSessionIpc::onMessageReceived(const base::ByteArray& buffer)
{
incoming_message_.Clear();
if (!common::parseMessage(buffer, &incoming_message_))
{
LOG(LS_ERROR) << "Invalid message from desktop";
return;
}
if (incoming_message_.has_encode_frame())
{
onEncodeFrame(incoming_message_.encode_frame());
}
else if (incoming_message_.has_screen_list())
{
delegate_->onScreenListChanged(incoming_message_.screen_list());
}
else if (incoming_message_.has_shared_buffer())
{
switch (incoming_message_.shared_buffer().type())
{
case proto::internal::SharedBuffer::CREATE:
onCreateSharedBuffer(incoming_message_.shared_buffer().shared_buffer_id());
break;
case proto::internal::SharedBuffer::RELEASE:
onReleaseSharedBuffer(incoming_message_.shared_buffer().shared_buffer_id());
break;
default:
NOTREACHED();
break;
}
}
else if (incoming_message_.has_clipboard_event())
{
delegate_->onClipboardEvent(incoming_message_.clipboard_event());
}
else
{
LOG(LS_ERROR) << "Unhandled message from desktop";
return;
}
}
void DesktopSessionIpc::onEncodeFrame(const proto::internal::EncodeFrame& encode_frame)
{
if (encode_frame.has_frame())
{
const proto::internal::SerializedDesktopFrame& serialized_frame = encode_frame.frame();
std::unique_ptr<SharedBuffer> shared_buffer = sharedBuffer(serialized_frame.shared_buffer_id());
if (!shared_buffer)
return;
const proto::Rect& frame_rect = serialized_frame.desktop_rect();
std::unique_ptr<desktop::Frame> frame = desktop::SharedMemoryFrame::attach(
desktop::Size(frame_rect.width(), frame_rect.height()),
codec::parsePixelFormat(serialized_frame.pixel_format()),
std::move(shared_buffer));
frame->setTopLeft(desktop::Point(frame_rect.x(), frame_rect.y()));
for (int i = 0; i < serialized_frame.dirty_rect_size(); ++i)
frame->updatedRegion()->addRect(codec::parseRect(serialized_frame.dirty_rect(i)));
delegate_->onScreenCaptured(*frame);
}
if (encode_frame.has_mouse_cursor())
{
const proto::internal::SerializedMouseCursor& serialized_mouse_cursor =
encode_frame.mouse_cursor();
desktop::Size size = desktop::Size(
serialized_mouse_cursor.width(), serialized_mouse_cursor.height());
desktop::Point hotspot = desktop::Point(
serialized_mouse_cursor.hotspot_x(), serialized_mouse_cursor.hotspot_y());
std::unique_ptr<uint8_t[]> data =
std::make_unique<uint8_t[]>(serialized_mouse_cursor.data().size());
memcpy(data.get(),
serialized_mouse_cursor.data().data(),
serialized_mouse_cursor.data().size());
delegate_->onCursorCaptured(
std::make_shared<desktop::MouseCursor>(std::move(data), size, hotspot));
}
outgoing_message_.Clear();
outgoing_message_.mutable_encode_frame_result()->set_dummy(1);
channel_->send(common::serializeMessage(outgoing_message_));
}
void DesktopSessionIpc::onCreateSharedBuffer(int shared_buffer_id)
{
std::unique_ptr<ipc::SharedMemory> shared_memory =
ipc::SharedMemory::open(ipc::SharedMemory::Mode::READ_ONLY, shared_buffer_id);
if (!shared_memory)
{
LOG(LS_ERROR) << "Failed to create the shared buffer " << shared_buffer_id;
return;
}
shared_buffers_.emplace(shared_buffer_id, SharedBuffer::wrap(std::move(shared_memory)));
}
void DesktopSessionIpc::onReleaseSharedBuffer(int shared_buffer_id)
{
shared_buffers_.erase(shared_buffer_id);
}
std::unique_ptr<DesktopSessionIpc::SharedBuffer> DesktopSessionIpc::sharedBuffer(
int shared_buffer_id)
{
auto result = shared_buffers_.find(shared_buffer_id);
if (result == shared_buffers_.end())
{
LOG(LS_ERROR) << "Failed to find the shared buffer " << shared_buffer_id;
return nullptr;
}
return result->second->share();
}
} // namespace host
<commit_msg>- Fix V807 warning (found by PVS-Studio).<commit_after>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
#include "host/desktop_session_ipc.h"
#include "base/logging.h"
#include "codec/video_util.h"
#include "common/message_serialization.h"
#include "desktop/mouse_cursor.h"
#include "desktop/shared_memory_desktop_frame.h"
#include "ipc/ipc_channel.h"
#include "ipc/shared_memory.h"
namespace host {
class DesktopSessionIpc::SharedBuffer : public ipc::SharedMemoryBase
{
public:
~SharedBuffer() = default;
static std::unique_ptr<SharedBuffer> wrap(std::unique_ptr<ipc::SharedMemory> shared_memory)
{
std::shared_ptr<ipc::SharedMemory> shared_frame(shared_memory.release());
return std::unique_ptr<SharedBuffer>(new SharedBuffer(shared_frame));
}
std::unique_ptr<SharedBuffer> share()
{
return std::unique_ptr<SharedBuffer>(new SharedBuffer(shared_memory_));
}
void* data() override
{
return shared_memory_->data();
}
Handle handle() const override
{
return shared_memory_->handle();
}
int id() const override
{
return shared_memory_->id();
}
private:
explicit SharedBuffer(std::shared_ptr<ipc::SharedMemory>& shared_memory)
: shared_memory_(shared_memory)
{
// Nothing
}
std::shared_ptr<ipc::SharedMemory> shared_memory_;
DISALLOW_COPY_AND_ASSIGN(SharedBuffer);
};
DesktopSessionIpc::DesktopSessionIpc(std::unique_ptr<ipc::Channel> channel, Delegate* delegate)
: channel_(std::move(channel)),
delegate_(delegate)
{
DCHECK(channel_);
DCHECK(delegate_);
}
DesktopSessionIpc::~DesktopSessionIpc() = default;
void DesktopSessionIpc::start()
{
channel_->setListener(this);
channel_->resume();
delegate_->onDesktopSessionStarted();
}
void DesktopSessionIpc::enableSession(bool enable)
{
outgoing_message_.Clear();
outgoing_message_.mutable_enable_session()->set_enable(enable);
channel_->send(common::serializeMessage(outgoing_message_));
}
void DesktopSessionIpc::selectScreen(const proto::Screen& screen)
{
outgoing_message_.Clear();
outgoing_message_.mutable_select_source()->mutable_screen()->CopyFrom(screen);
channel_->send(common::serializeMessage(outgoing_message_));
}
void DesktopSessionIpc::enableFeatures(const proto::internal::EnableFeatures& features)
{
outgoing_message_.Clear();
outgoing_message_.mutable_enable_features()->CopyFrom(features);
channel_->send(common::serializeMessage(outgoing_message_));
}
void DesktopSessionIpc::injectKeyEvent(const proto::KeyEvent& event)
{
outgoing_message_.Clear();
outgoing_message_.mutable_key_event()->CopyFrom(event);
channel_->send(common::serializeMessage(outgoing_message_));
}
void DesktopSessionIpc::injectPointerEvent(const proto::PointerEvent& event)
{
outgoing_message_.Clear();
outgoing_message_.mutable_pointer_event()->CopyFrom(event);
channel_->send(common::serializeMessage(outgoing_message_));
}
void DesktopSessionIpc::injectClipboardEvent(const proto::ClipboardEvent& event)
{
outgoing_message_.Clear();
outgoing_message_.mutable_clipboard_event()->CopyFrom(event);
channel_->send(common::serializeMessage(outgoing_message_));
}
void DesktopSessionIpc::userSessionControl(proto::internal::UserSessionControl::Action action)
{
outgoing_message_.Clear();
outgoing_message_.mutable_user_session_control()->set_action(action);
channel_->send(common::serializeMessage(outgoing_message_));
}
void DesktopSessionIpc::onDisconnected()
{
delegate_->onDesktopSessionStopped();
}
void DesktopSessionIpc::onMessageReceived(const base::ByteArray& buffer)
{
incoming_message_.Clear();
if (!common::parseMessage(buffer, &incoming_message_))
{
LOG(LS_ERROR) << "Invalid message from desktop";
return;
}
if (incoming_message_.has_encode_frame())
{
onEncodeFrame(incoming_message_.encode_frame());
}
else if (incoming_message_.has_screen_list())
{
delegate_->onScreenListChanged(incoming_message_.screen_list());
}
else if (incoming_message_.has_shared_buffer())
{
switch (incoming_message_.shared_buffer().type())
{
case proto::internal::SharedBuffer::CREATE:
onCreateSharedBuffer(incoming_message_.shared_buffer().shared_buffer_id());
break;
case proto::internal::SharedBuffer::RELEASE:
onReleaseSharedBuffer(incoming_message_.shared_buffer().shared_buffer_id());
break;
default:
NOTREACHED();
break;
}
}
else if (incoming_message_.has_clipboard_event())
{
delegate_->onClipboardEvent(incoming_message_.clipboard_event());
}
else
{
LOG(LS_ERROR) << "Unhandled message from desktop";
return;
}
}
void DesktopSessionIpc::onEncodeFrame(const proto::internal::EncodeFrame& encode_frame)
{
if (encode_frame.has_frame())
{
const proto::internal::SerializedDesktopFrame& serialized_frame = encode_frame.frame();
std::unique_ptr<SharedBuffer> shared_buffer = sharedBuffer(serialized_frame.shared_buffer_id());
if (!shared_buffer)
return;
const proto::Rect& frame_rect = serialized_frame.desktop_rect();
std::unique_ptr<desktop::Frame> frame = desktop::SharedMemoryFrame::attach(
desktop::Size(frame_rect.width(), frame_rect.height()),
codec::parsePixelFormat(serialized_frame.pixel_format()),
std::move(shared_buffer));
frame->setTopLeft(desktop::Point(frame_rect.x(), frame_rect.y()));
for (int i = 0; i < serialized_frame.dirty_rect_size(); ++i)
frame->updatedRegion()->addRect(codec::parseRect(serialized_frame.dirty_rect(i)));
delegate_->onScreenCaptured(*frame);
}
if (encode_frame.has_mouse_cursor())
{
const proto::internal::SerializedMouseCursor& serialized_mouse_cursor =
encode_frame.mouse_cursor();
const std::string& serialized_data = serialized_mouse_cursor.data();
desktop::Size size = desktop::Size(
serialized_mouse_cursor.width(), serialized_mouse_cursor.height());
desktop::Point hotspot = desktop::Point(
serialized_mouse_cursor.hotspot_x(), serialized_mouse_cursor.hotspot_y());
std::unique_ptr<uint8_t[]> data =
std::make_unique<uint8_t[]>(serialized_data.size());
memcpy(data.get(), serialized_data.data(), serialized_data.size());
delegate_->onCursorCaptured(
std::make_shared<desktop::MouseCursor>(std::move(data), size, hotspot));
}
outgoing_message_.Clear();
outgoing_message_.mutable_encode_frame_result()->set_dummy(1);
channel_->send(common::serializeMessage(outgoing_message_));
}
void DesktopSessionIpc::onCreateSharedBuffer(int shared_buffer_id)
{
std::unique_ptr<ipc::SharedMemory> shared_memory =
ipc::SharedMemory::open(ipc::SharedMemory::Mode::READ_ONLY, shared_buffer_id);
if (!shared_memory)
{
LOG(LS_ERROR) << "Failed to create the shared buffer " << shared_buffer_id;
return;
}
shared_buffers_.emplace(shared_buffer_id, SharedBuffer::wrap(std::move(shared_memory)));
}
void DesktopSessionIpc::onReleaseSharedBuffer(int shared_buffer_id)
{
shared_buffers_.erase(shared_buffer_id);
}
std::unique_ptr<DesktopSessionIpc::SharedBuffer> DesktopSessionIpc::sharedBuffer(
int shared_buffer_id)
{
auto result = shared_buffers_.find(shared_buffer_id);
if (result == shared_buffers_.end())
{
LOG(LS_ERROR) << "Failed to find the shared buffer " << shared_buffer_id;
return nullptr;
}
return result->second->share();
}
} // namespace host
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/history/history_database.h"
#include <algorithm>
#include <set>
#include <string>
#include "app/sql/transaction.h"
#include "base/command_line.h"
#include "base/file_util.h"
#if defined(OS_MACOSX)
#include "base/mac_util.h"
#endif
#include "base/histogram.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "chrome/browser/diagnostics/sqlite_diagnostics.h"
#include "chrome/common/chrome_switches.h"
namespace history {
namespace {
// Current version number. We write databases at the "current" version number,
// but any previous version that can read the "compatible" one can make do with
// or database without *too* many bad effects.
static const int kCurrentVersionNumber = 18;
static const int kCompatibleVersionNumber = 16;
static const char kEarlyExpirationThresholdKey[] = "early_expiration_threshold";
void ComputeDatabaseMetrics(const FilePath& history_name,
sql::Connection& db) {
if (base::RandInt(1, 100) != 50)
return; // Only do this computation sometimes since it can be expensive.
int64 file_size = 0;
if (!file_util::GetFileSize(history_name, &file_size))
return;
int file_mb = static_cast<int>(file_size / (1024 * 1024));
UMA_HISTOGRAM_MEMORY_MB("History.DatabaseFileMB", file_mb);
sql::Statement url_count(db.GetUniqueStatement("SELECT count(*) FROM urls"));
if (!url_count || !url_count.Step())
return;
UMA_HISTOGRAM_COUNTS("History.URLTableCount", url_count.ColumnInt(0));
sql::Statement visit_count(db.GetUniqueStatement(
"SELECT count(*) FROM visits"));
if (!visit_count || !visit_count.Step())
return;
UMA_HISTOGRAM_COUNTS("History.VisitTableCount", visit_count.ColumnInt(0));
}
} // namespace
HistoryDatabase::HistoryDatabase()
: needs_version_17_migration_(false),
needs_version_18_migration_(false) {
}
HistoryDatabase::~HistoryDatabase() {
}
sql::InitStatus HistoryDatabase::Init(const FilePath& history_name,
const FilePath& bookmarks_path) {
// Set the exceptional sqlite error handler.
db_.set_error_delegate(GetErrorHandlerForHistoryDb());
// Set the database page size to something a little larger to give us
// better performance (we're typically seek rather than bandwidth limited).
// This only has an effect before any tables have been created, otherwise
// this is a NOP. Must be a power of 2 and a max of 8192.
db_.set_page_size(4096);
// Increase the cache size. The page size, plus a little extra, times this
// value, tells us how much memory the cache will use maximum.
// 6000 * 4MB = 24MB
// TODO(brettw) scale this value to the amount of available memory.
db_.set_cache_size(6000);
// Note that we don't set exclusive locking here. That's done by
// BeginExclusiveMode below which is called later (we have to be in shared
// mode to start out for the in-memory backend to read the data).
if (!db_.Open(history_name))
return sql::INIT_FAILURE;
// Wrap the rest of init in a tranaction. This will prevent the database from
// getting corrupted if we crash in the middle of initialization or migration.
sql::Transaction committer(&db_);
if (!committer.Begin())
return sql::INIT_FAILURE;
#if defined(OS_MACOSX)
// Exclude the history file and its journal from backups.
mac_util::SetFileBackupExclusion(history_name, true);
FilePath::StringType history_name_string(history_name.value());
history_name_string += "-journal";
FilePath history_journal_name(history_name_string);
mac_util::SetFileBackupExclusion(history_journal_name, true);
#endif
// Prime the cache.
db_.Preload();
// Create the tables and indices.
// NOTE: If you add something here, also add it to
// RecreateAllButStarAndURLTables.
if (!meta_table_.Init(&db_, GetCurrentVersion(), kCompatibleVersionNumber))
return sql::INIT_FAILURE;
if (!CreateURLTable(false) || !InitVisitTable() ||
!InitKeywordSearchTermsTable() || !InitDownloadTable() ||
!InitSegmentTables())
return sql::INIT_FAILURE;
CreateMainURLIndex();
CreateSupplimentaryURLIndices();
// Version check.
sql::InitStatus version_status = EnsureCurrentVersion(bookmarks_path);
if (version_status != sql::INIT_OK)
return version_status;
ComputeDatabaseMetrics(history_name, db_);
return committer.Commit() ? sql::INIT_OK : sql::INIT_FAILURE;
}
void HistoryDatabase::BeginExclusiveMode() {
// We can't use set_exclusive_locking() since that only has an effect before
// the DB is opened.
db_.Execute("PRAGMA locking_mode=EXCLUSIVE");
}
// static
int HistoryDatabase::GetCurrentVersion() {
// Temporary solution while TopSites is behind a flag. If there is
// no flag, we are still using the Thumbnails file, i.e. we are at
// version 17.
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kTopSites)) {
return kCurrentVersionNumber;
} else {
return kCurrentVersionNumber - 1;
}
}
void HistoryDatabase::BeginTransaction() {
db_.BeginTransaction();
}
void HistoryDatabase::CommitTransaction() {
db_.CommitTransaction();
}
bool HistoryDatabase::RecreateAllTablesButURL() {
if (!DropVisitTable())
return false;
if (!InitVisitTable())
return false;
if (!DropKeywordSearchTermsTable())
return false;
if (!InitKeywordSearchTermsTable())
return false;
if (!DropSegmentTables())
return false;
if (!InitSegmentTables())
return false;
// We also add the supplementary URL indices at this point. This index is
// over parts of the URL table that weren't automatically created when the
// temporary URL table was
CreateSupplimentaryURLIndices();
return true;
}
void HistoryDatabase::Vacuum() {
DCHECK_EQ(0, db_.transaction_nesting()) <<
"Can not have a transaction when vacuuming.";
db_.Execute("VACUUM");
}
bool HistoryDatabase::SetSegmentID(VisitID visit_id, SegmentID segment_id) {
sql::Statement s(db_.GetCachedStatement(SQL_FROM_HERE,
"UPDATE visits SET segment_id = ? WHERE id = ?"));
if (!s) {
NOTREACHED() << db_.GetErrorMessage();
return false;
}
s.BindInt64(0, segment_id);
s.BindInt64(1, visit_id);
DCHECK(db_.GetLastChangeCount() == 1);
return s.Run();
}
SegmentID HistoryDatabase::GetSegmentID(VisitID visit_id) {
sql::Statement s(db_.GetCachedStatement(SQL_FROM_HERE,
"SELECT segment_id FROM visits WHERE id = ?"));
if (!s) {
NOTREACHED() << db_.GetErrorMessage();
return 0;
}
s.BindInt64(0, visit_id);
if (s.Step()) {
if (s.ColumnType(0) == sql::COLUMN_TYPE_NULL)
return 0;
else
return s.ColumnInt64(0);
}
return 0;
}
base::Time HistoryDatabase::GetEarlyExpirationThreshold() {
if (!cached_early_expiration_threshold_.is_null())
return cached_early_expiration_threshold_;
int64 threshold;
if (!meta_table_.GetValue(kEarlyExpirationThresholdKey, &threshold)) {
// Set to a very early non-zero time, so it's before all history, but not
// zero to avoid re-retrieval.
threshold = 1L;
}
cached_early_expiration_threshold_ = base::Time::FromInternalValue(threshold);
return cached_early_expiration_threshold_;
}
void HistoryDatabase::UpdateEarlyExpirationThreshold(base::Time threshold) {
meta_table_.SetValue(kEarlyExpirationThresholdKey,
threshold.ToInternalValue());
cached_early_expiration_threshold_ = threshold;
}
sql::Connection& HistoryDatabase::GetDB() {
return db_;
}
// Migration -------------------------------------------------------------------
sql::InitStatus HistoryDatabase::EnsureCurrentVersion(
const FilePath& tmp_bookmarks_path) {
// We can't read databases newer than we were designed for.
if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) {
LOG(WARNING) << "History database is too new.";
return sql::INIT_TOO_NEW;
}
// NOTICE: If you are changing structures for things shared with the archived
// history file like URLs, visits, or downloads, that will need migration as
// well. Instead of putting such migration code in this class, it should be
// in the corresponding file (url_database.cc, etc.) and called from here and
// from the archived_database.cc.
int cur_version = meta_table_.GetVersionNumber();
// Put migration code here
if (cur_version == 15) {
if (!MigrateBookmarksToFile(tmp_bookmarks_path) ||
!DropStarredIDFromURLs()) {
LOG(WARNING) << "Unable to update history database to version 16.";
return sql::INIT_FAILURE;
}
++cur_version;
meta_table_.SetVersionNumber(cur_version);
meta_table_.SetCompatibleVersionNumber(
std::min(cur_version, kCompatibleVersionNumber));
}
if (cur_version == 16) {
#if !defined(OS_WIN)
// In this version we bring the time format on Mac & Linux in sync with the
// Windows version so that profiles can be moved between computers.
MigrateTimeEpoch();
#endif
// On all platforms we bump the version number, so on Windows this
// migration is a NOP. We keep the compatible version at 16 since things
// will basically still work, just history will be in the future if an
// old version reads it.
++cur_version;
meta_table_.SetVersionNumber(cur_version);
}
if (cur_version == 17)
needs_version_18_migration_ = true;
// When the version is too old, we just try to continue anyway, there should
// not be a released product that makes a database too old for us to handle.
LOG_IF(WARNING, cur_version < GetCurrentVersion()) <<
"History database version " << cur_version << " is too old to handle.";
return sql::INIT_OK;
}
#if !defined(OS_WIN)
void HistoryDatabase::MigrateTimeEpoch() {
// Update all the times in the URLs and visits table in the main database.
// For visits, clear the indexed flag since we'll delete the FTS databases in
// the next step.
db_.Execute(
"UPDATE urls "
"SET last_visit_time = last_visit_time + 11644473600000000 "
"WHERE id IN (SELECT id FROM urls WHERE last_visit_time > 0);");
db_.Execute(
"UPDATE visits "
"SET visit_time = visit_time + 11644473600000000, is_indexed = 0 "
"WHERE id IN (SELECT id FROM visits WHERE visit_time > 0);");
db_.Execute(
"UPDATE segment_usage "
"SET time_slot = time_slot + 11644473600000000 "
"WHERE id IN (SELECT id FROM segment_usage WHERE time_slot > 0);");
// Erase all the full text index files. These will take a while to update and
// are less important, so we just blow them away. Same with the archived
// database.
needs_version_17_migration_ = true;
}
#endif
void HistoryDatabase::MigrationToTopSitesDone() {
// We should be migrating from 17 to 18.
DCHECK_EQ(17, meta_table_.GetVersionNumber());
meta_table_.SetVersionNumber(18);
needs_version_18_migration_ = false;
}
} // namespace history
<commit_msg>Remove the warning during conversion to TopSites. Set version back to non-top sites when running without the --top-sites flag.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/history/history_database.h"
#include <algorithm>
#include <set>
#include <string>
#include "app/sql/transaction.h"
#include "base/command_line.h"
#include "base/file_util.h"
#if defined(OS_MACOSX)
#include "base/mac_util.h"
#endif
#include "base/histogram.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "chrome/browser/diagnostics/sqlite_diagnostics.h"
#include "chrome/common/chrome_switches.h"
namespace history {
namespace {
// Current version number. We write databases at the "current" version number,
// but any previous version that can read the "compatible" one can make do with
// or database without *too* many bad effects.
static const int kCurrentVersionNumber = 18;
static const int kCompatibleVersionNumber = 16;
static const char kEarlyExpirationThresholdKey[] = "early_expiration_threshold";
void ComputeDatabaseMetrics(const FilePath& history_name,
sql::Connection& db) {
if (base::RandInt(1, 100) != 50)
return; // Only do this computation sometimes since it can be expensive.
int64 file_size = 0;
if (!file_util::GetFileSize(history_name, &file_size))
return;
int file_mb = static_cast<int>(file_size / (1024 * 1024));
UMA_HISTOGRAM_MEMORY_MB("History.DatabaseFileMB", file_mb);
sql::Statement url_count(db.GetUniqueStatement("SELECT count(*) FROM urls"));
if (!url_count || !url_count.Step())
return;
UMA_HISTOGRAM_COUNTS("History.URLTableCount", url_count.ColumnInt(0));
sql::Statement visit_count(db.GetUniqueStatement(
"SELECT count(*) FROM visits"));
if (!visit_count || !visit_count.Step())
return;
UMA_HISTOGRAM_COUNTS("History.VisitTableCount", visit_count.ColumnInt(0));
}
} // namespace
HistoryDatabase::HistoryDatabase()
: needs_version_17_migration_(false),
needs_version_18_migration_(false) {
}
HistoryDatabase::~HistoryDatabase() {
}
sql::InitStatus HistoryDatabase::Init(const FilePath& history_name,
const FilePath& bookmarks_path) {
// Set the exceptional sqlite error handler.
db_.set_error_delegate(GetErrorHandlerForHistoryDb());
// Set the database page size to something a little larger to give us
// better performance (we're typically seek rather than bandwidth limited).
// This only has an effect before any tables have been created, otherwise
// this is a NOP. Must be a power of 2 and a max of 8192.
db_.set_page_size(4096);
// Increase the cache size. The page size, plus a little extra, times this
// value, tells us how much memory the cache will use maximum.
// 6000 * 4MB = 24MB
// TODO(brettw) scale this value to the amount of available memory.
db_.set_cache_size(6000);
// Note that we don't set exclusive locking here. That's done by
// BeginExclusiveMode below which is called later (we have to be in shared
// mode to start out for the in-memory backend to read the data).
if (!db_.Open(history_name))
return sql::INIT_FAILURE;
// Wrap the rest of init in a tranaction. This will prevent the database from
// getting corrupted if we crash in the middle of initialization or migration.
sql::Transaction committer(&db_);
if (!committer.Begin())
return sql::INIT_FAILURE;
#if defined(OS_MACOSX)
// Exclude the history file and its journal from backups.
mac_util::SetFileBackupExclusion(history_name, true);
FilePath::StringType history_name_string(history_name.value());
history_name_string += "-journal";
FilePath history_journal_name(history_name_string);
mac_util::SetFileBackupExclusion(history_journal_name, true);
#endif
// Prime the cache.
db_.Preload();
// Create the tables and indices.
// NOTE: If you add something here, also add it to
// RecreateAllButStarAndURLTables.
if (!meta_table_.Init(&db_, GetCurrentVersion(), kCompatibleVersionNumber))
return sql::INIT_FAILURE;
if (!CreateURLTable(false) || !InitVisitTable() ||
!InitKeywordSearchTermsTable() || !InitDownloadTable() ||
!InitSegmentTables())
return sql::INIT_FAILURE;
CreateMainURLIndex();
CreateSupplimentaryURLIndices();
// Version check.
sql::InitStatus version_status = EnsureCurrentVersion(bookmarks_path);
if (version_status != sql::INIT_OK)
return version_status;
ComputeDatabaseMetrics(history_name, db_);
return committer.Commit() ? sql::INIT_OK : sql::INIT_FAILURE;
}
void HistoryDatabase::BeginExclusiveMode() {
// We can't use set_exclusive_locking() since that only has an effect before
// the DB is opened.
db_.Execute("PRAGMA locking_mode=EXCLUSIVE");
}
// static
int HistoryDatabase::GetCurrentVersion() {
// Temporary solution while TopSites is behind a flag. If there is
// no flag, we are still using the Thumbnails file, i.e. we are at
// version 17.
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kTopSites)) {
return kCurrentVersionNumber;
} else {
return kCurrentVersionNumber - 1;
}
}
void HistoryDatabase::BeginTransaction() {
db_.BeginTransaction();
}
void HistoryDatabase::CommitTransaction() {
db_.CommitTransaction();
}
bool HistoryDatabase::RecreateAllTablesButURL() {
if (!DropVisitTable())
return false;
if (!InitVisitTable())
return false;
if (!DropKeywordSearchTermsTable())
return false;
if (!InitKeywordSearchTermsTable())
return false;
if (!DropSegmentTables())
return false;
if (!InitSegmentTables())
return false;
// We also add the supplementary URL indices at this point. This index is
// over parts of the URL table that weren't automatically created when the
// temporary URL table was
CreateSupplimentaryURLIndices();
return true;
}
void HistoryDatabase::Vacuum() {
DCHECK_EQ(0, db_.transaction_nesting()) <<
"Can not have a transaction when vacuuming.";
db_.Execute("VACUUM");
}
bool HistoryDatabase::SetSegmentID(VisitID visit_id, SegmentID segment_id) {
sql::Statement s(db_.GetCachedStatement(SQL_FROM_HERE,
"UPDATE visits SET segment_id = ? WHERE id = ?"));
if (!s) {
NOTREACHED() << db_.GetErrorMessage();
return false;
}
s.BindInt64(0, segment_id);
s.BindInt64(1, visit_id);
DCHECK(db_.GetLastChangeCount() == 1);
return s.Run();
}
SegmentID HistoryDatabase::GetSegmentID(VisitID visit_id) {
sql::Statement s(db_.GetCachedStatement(SQL_FROM_HERE,
"SELECT segment_id FROM visits WHERE id = ?"));
if (!s) {
NOTREACHED() << db_.GetErrorMessage();
return 0;
}
s.BindInt64(0, visit_id);
if (s.Step()) {
if (s.ColumnType(0) == sql::COLUMN_TYPE_NULL)
return 0;
else
return s.ColumnInt64(0);
}
return 0;
}
base::Time HistoryDatabase::GetEarlyExpirationThreshold() {
if (!cached_early_expiration_threshold_.is_null())
return cached_early_expiration_threshold_;
int64 threshold;
if (!meta_table_.GetValue(kEarlyExpirationThresholdKey, &threshold)) {
// Set to a very early non-zero time, so it's before all history, but not
// zero to avoid re-retrieval.
threshold = 1L;
}
cached_early_expiration_threshold_ = base::Time::FromInternalValue(threshold);
return cached_early_expiration_threshold_;
}
void HistoryDatabase::UpdateEarlyExpirationThreshold(base::Time threshold) {
meta_table_.SetValue(kEarlyExpirationThresholdKey,
threshold.ToInternalValue());
cached_early_expiration_threshold_ = threshold;
}
sql::Connection& HistoryDatabase::GetDB() {
return db_;
}
// Migration -------------------------------------------------------------------
sql::InitStatus HistoryDatabase::EnsureCurrentVersion(
const FilePath& tmp_bookmarks_path) {
// We can't read databases newer than we were designed for.
if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) {
LOG(WARNING) << "History database is too new.";
return sql::INIT_TOO_NEW;
}
// NOTICE: If you are changing structures for things shared with the archived
// history file like URLs, visits, or downloads, that will need migration as
// well. Instead of putting such migration code in this class, it should be
// in the corresponding file (url_database.cc, etc.) and called from here and
// from the archived_database.cc.
int cur_version = meta_table_.GetVersionNumber();
// Put migration code here
if (cur_version == 15) {
if (!MigrateBookmarksToFile(tmp_bookmarks_path) ||
!DropStarredIDFromURLs()) {
LOG(WARNING) << "Unable to update history database to version 16.";
return sql::INIT_FAILURE;
}
++cur_version;
meta_table_.SetVersionNumber(cur_version);
meta_table_.SetCompatibleVersionNumber(
std::min(cur_version, kCompatibleVersionNumber));
}
if (cur_version == 16) {
#if !defined(OS_WIN)
// In this version we bring the time format on Mac & Linux in sync with the
// Windows version so that profiles can be moved between computers.
MigrateTimeEpoch();
#endif
// On all platforms we bump the version number, so on Windows this
// migration is a NOP. We keep the compatible version at 16 since things
// will basically still work, just history will be in the future if an
// old version reads it.
++cur_version;
meta_table_.SetVersionNumber(cur_version);
}
if (cur_version == 17)
needs_version_18_migration_ = true;
if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kTopSites) &&
cur_version == 18) {
// Set DB version back to pre-top sites.
cur_version = 17;
meta_table_.SetVersionNumber(cur_version);
}
// When the version is too old, we just try to continue anyway, there should
// not be a released product that makes a database too old for us to handle.
LOG_IF(WARNING, (cur_version < GetCurrentVersion() &&
!needs_version_18_migration_)) <<
"History database version " << cur_version << " is too old to handle.";
return sql::INIT_OK;
}
#if !defined(OS_WIN)
void HistoryDatabase::MigrateTimeEpoch() {
// Update all the times in the URLs and visits table in the main database.
// For visits, clear the indexed flag since we'll delete the FTS databases in
// the next step.
db_.Execute(
"UPDATE urls "
"SET last_visit_time = last_visit_time + 11644473600000000 "
"WHERE id IN (SELECT id FROM urls WHERE last_visit_time > 0);");
db_.Execute(
"UPDATE visits "
"SET visit_time = visit_time + 11644473600000000, is_indexed = 0 "
"WHERE id IN (SELECT id FROM visits WHERE visit_time > 0);");
db_.Execute(
"UPDATE segment_usage "
"SET time_slot = time_slot + 11644473600000000 "
"WHERE id IN (SELECT id FROM segment_usage WHERE time_slot > 0);");
// Erase all the full text index files. These will take a while to update and
// are less important, so we just blow them away. Same with the archived
// database.
needs_version_17_migration_ = true;
}
#endif
void HistoryDatabase::MigrationToTopSitesDone() {
// We should be migrating from 17 to 18.
DCHECK_EQ(17, meta_table_.GetVersionNumber());
meta_table_.SetVersionNumber(18);
needs_version_18_migration_ = false;
}
} // namespace history
<|endoftext|> |
<commit_before>#ifndef HOG_READER_HPP_GUARD
#define HOG_READER_HPP_GUARD
//===----------------------------------------------------------------------===//
//
// The Descent map loader
//
// NAME : HogReader
// PURPOSE : Providing a decoder and wrapper for the Descent .HOG format.
// COPYRIGHT : (c) 2011 Sean Donnellan. All Rights Reserved.
// AUTHORS : Sean Donnellan (darkdonno@gmail.com)
// DESCRIPTION : A decoder for the HOG file format that is used by Parallax
// Software in the computer game, Descent.
//
// The file format is as follows:
//
// - Magic number which is 3 bytes and corresponding to the
// string "DHF"
// - A series of files which are preceded by a short header,
// which describes the name of the file and the numer of bytes.
//
// | "DHF" - 3 bytes
// |---------------- Start of the first file
// | filename - 13 bytes
// | size - 4 bytes
// | data - the size of this part is by the size before it.
// |---------------- The next header/file comes straight after.
// | filename - 13 bytes
// | size - 4 bytes
// | data - the size of this part is by the size before it.
//
//===----------------------------------------------------------------------===//
#include <memory>
#include <vector>
#include <stdint.h>
class HogReaderIterator;
struct HogFileHeader
{
char name[13]; // Padded to 13 bytes with \0.
uint32_t size; // The filesize as N bytes.
};
// Warning: The above structure is padded on x86 so you can not just read in the
// whole thing.
class HogReader
{
public:
typedef HogReaderIterator iterator;
HogReader(const char* filename);
~HogReader();
bool IsValid() const;
// Returns true if the file was succesfully opened and the magic header is
// correct.
bool NextFile();
std::vector<uint8_t> CurrentFile();
// Returns a copy of the data for the current file after reading it.
const char* CurrentFileName() const;
unsigned int CurrentFileSize() const;
iterator begin();
iterator end();
private:
FILE* myFile;
uint8_t myHeader[3];
HogFileHeader myChildFile;
bool hasReadFile;
};
#endif<commit_msg>Re-ordered a class member to avoid padding on x64.<commit_after>#ifndef HOG_READER_HPP_GUARD
#define HOG_READER_HPP_GUARD
//===----------------------------------------------------------------------===//
//
// The Descent map loader
//
// NAME : HogReader
// PURPOSE : Providing a decoder and wrapper for the Descent .HOG format.
// COPYRIGHT : (c) 2011 Sean Donnellan. All Rights Reserved.
// AUTHORS : Sean Donnellan (darkdonno@gmail.com)
// DESCRIPTION : A decoder for the HOG file format that is used by Parallax
// Software in the computer game, Descent.
//
// The file format is as follows:
//
// - Magic number which is 3 bytes and corresponding to the
// string "DHF"
// - A series of files which are preceded by a short header,
// which describes the name of the file and the numer of bytes.
//
// | "DHF" - 3 bytes
// |---------------- Start of the first file
// | filename - 13 bytes
// | size - 4 bytes
// | data - the size of this part is by the size before it.
// |---------------- The next header/file comes straight after.
// | filename - 13 bytes
// | size - 4 bytes
// | data - the size of this part is by the size before it.
//
//===----------------------------------------------------------------------===//
#include <memory>
#include <vector>
#include <stdint.h>
class HogReaderIterator;
struct HogFileHeader
{
char name[13]; // Padded to 13 bytes with \0.
uint32_t size; // The filesize as N bytes.
};
// Warning: The above structure is padded on x86 so you can not just read in the
// whole thing.
class HogReader
{
public:
typedef HogReaderIterator iterator;
HogReader(const char* filename);
~HogReader();
bool IsValid() const;
// Returns true if the file was succesfully opened and the magic header is
// correct.
bool NextFile();
std::vector<uint8_t> CurrentFile();
// Returns a copy of the data for the current file after reading it.
const char* CurrentFileName() const;
unsigned int CurrentFileSize() const;
iterator begin();
iterator end();
private:
FILE* myFile;
uint8_t myHeader[3];
bool hasReadFile;
HogFileHeader myChildFile;
};
#endif<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "app/system_monitor.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
#include "testing/gtest/include/gtest/gtest.h"
class ProfileManagerTest : public testing::Test {
protected:
ProfileManagerTest() : ui_thread_(ChromeThread::UI, &message_loop_) {
}
virtual void SetUp() {
// Name a subdirectory of the temp directory.
ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &test_dir_));
test_dir_ = test_dir_.Append(FILE_PATH_LITERAL("ProfileManagerTest"));
// Create a fresh, empty copy of this directory.
file_util::Delete(test_dir_, true);
file_util::CreateDirectory(test_dir_);
}
virtual void TearDown() {
// Clean up test directory
ASSERT_TRUE(file_util::Delete(test_dir_, true));
ASSERT_FALSE(file_util::PathExists(test_dir_));
}
MessageLoopForUI message_loop_;
ChromeThread ui_thread_;
// the path to temporary directory used to contain the test operations
FilePath test_dir_;
};
TEST_F(ProfileManagerTest, CreateProfile) {
FilePath source_path;
PathService::Get(chrome::DIR_TEST_DATA, &source_path);
source_path = source_path.Append(FILE_PATH_LITERAL("profiles"));
source_path = source_path.Append(FILE_PATH_LITERAL("sample"));
FilePath dest_path = test_dir_;
dest_path = dest_path.Append(FILE_PATH_LITERAL("New Profile"));
scoped_ptr<Profile> profile;
// Successfully create a profile.
profile.reset(ProfileManager::CreateProfile(dest_path));
ASSERT_TRUE(profile.get());
profile.reset();
#ifdef NDEBUG
// In Release mode, we always try to always return a profile. In debug,
// these cases would trigger DCHECKs.
// The profile already exists when we call CreateProfile. Just load it.
profile.reset(ProfileManager::CreateProfile(dest_path));
ASSERT_TRUE(profile.get());
#endif
}
TEST_F(ProfileManagerTest, DefaultProfileDir) {
CommandLine *cl = CommandLine::ForCurrentProcess();
SystemMonitor dummy;
ProfileManager profile_manager;
std::string profile_dir("my_user");
cl->AppendSwitch(switches::kTestType);
FilePath expected_default =
FilePath::FromWStringHack(chrome::kNotSignedInProfile);
EXPECT_EQ(expected_default.value(),
profile_manager.GetCurrentProfileDir().value());
}
#if defined(OS_CHROMEOS)
// This functionality only exists on Chrome OS.
TEST_F(ProfileManagerTest, LoggedInProfileDir) {
CommandLine *cl = CommandLine::ForCurrentProcess();
SystemMonitor dummy;
ProfileManager profile_manager;
std::string profile_dir("my_user");
cl->AppendSwitchWithValue(switches::kLoginProfile, profile_dir);
cl->AppendSwitch(switches::kTestType);
FilePath expected_default =
FilePath::FromWStringHack(chrome::kNotSignedInProfile);
EXPECT_EQ(expected_default.value(),
profile_manager.GetCurrentProfileDir().value());
profile_manager.Observe(NotificationType::LOGIN_USER_CHANGED,
NotificationService::AllSources(),
NotificationService::NoDetails());
FilePath expected_logged_in(profile_dir);
EXPECT_EQ(expected_logged_in.value(),
profile_manager.GetCurrentProfileDir().value());
LOG(INFO) << test_dir_.Append(profile_manager.GetCurrentProfileDir()).value();
}
#endif
// TODO(timsteele): This is disabled while I try to track down a purify
// regression (http://crbug.com/10553).
TEST_F(ProfileManagerTest, DISABLED_CreateAndUseTwoProfiles) {
FilePath source_path;
PathService::Get(chrome::DIR_TEST_DATA, &source_path);
source_path = source_path.Append(FILE_PATH_LITERAL("profiles"));
source_path = source_path.Append(FILE_PATH_LITERAL("sample"));
FilePath dest_path1 = test_dir_;
dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("New Profile 1"));
FilePath dest_path2 = test_dir_;
dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("New Profile 2"));
scoped_ptr<Profile> profile1;
scoped_ptr<Profile> profile2;
// Successfully create the profiles.
profile1.reset(ProfileManager::CreateProfile(dest_path1));
ASSERT_TRUE(profile1.get());
profile2.reset(ProfileManager::CreateProfile(dest_path2));
ASSERT_TRUE(profile2.get());
// Force lazy-init of some profile services to simulate use.
EXPECT_TRUE(profile1->GetHistoryService(Profile::EXPLICIT_ACCESS));
EXPECT_TRUE(profile1->GetBookmarkModel());
EXPECT_TRUE(profile2->GetBookmarkModel());
EXPECT_TRUE(profile2->GetHistoryService(Profile::EXPLICIT_ACCESS));
profile1.reset();
profile2.reset();
}
<commit_msg>Re-enable ProfileManagerTest.CreateAndUseTwoProfiles which was disabled due to a Purify error (which we no longer use).<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "app/system_monitor.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
#include "testing/gtest/include/gtest/gtest.h"
class ProfileManagerTest : public testing::Test {
protected:
ProfileManagerTest() : ui_thread_(ChromeThread::UI, &message_loop_) {
}
virtual void SetUp() {
// Name a subdirectory of the temp directory.
ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &test_dir_));
test_dir_ = test_dir_.Append(FILE_PATH_LITERAL("ProfileManagerTest"));
// Create a fresh, empty copy of this directory.
file_util::Delete(test_dir_, true);
file_util::CreateDirectory(test_dir_);
}
virtual void TearDown() {
// Clean up test directory
ASSERT_TRUE(file_util::Delete(test_dir_, true));
ASSERT_FALSE(file_util::PathExists(test_dir_));
}
MessageLoopForUI message_loop_;
ChromeThread ui_thread_;
// the path to temporary directory used to contain the test operations
FilePath test_dir_;
};
TEST_F(ProfileManagerTest, CreateProfile) {
FilePath source_path;
PathService::Get(chrome::DIR_TEST_DATA, &source_path);
source_path = source_path.Append(FILE_PATH_LITERAL("profiles"));
source_path = source_path.Append(FILE_PATH_LITERAL("sample"));
FilePath dest_path = test_dir_;
dest_path = dest_path.Append(FILE_PATH_LITERAL("New Profile"));
scoped_ptr<Profile> profile;
// Successfully create a profile.
profile.reset(ProfileManager::CreateProfile(dest_path));
ASSERT_TRUE(profile.get());
profile.reset();
#ifdef NDEBUG
// In Release mode, we always try to always return a profile. In debug,
// these cases would trigger DCHECKs.
// The profile already exists when we call CreateProfile. Just load it.
profile.reset(ProfileManager::CreateProfile(dest_path));
ASSERT_TRUE(profile.get());
#endif
}
TEST_F(ProfileManagerTest, DefaultProfileDir) {
CommandLine *cl = CommandLine::ForCurrentProcess();
SystemMonitor dummy;
ProfileManager profile_manager;
std::string profile_dir("my_user");
cl->AppendSwitch(switches::kTestType);
FilePath expected_default =
FilePath::FromWStringHack(chrome::kNotSignedInProfile);
EXPECT_EQ(expected_default.value(),
profile_manager.GetCurrentProfileDir().value());
}
#if defined(OS_CHROMEOS)
// This functionality only exists on Chrome OS.
TEST_F(ProfileManagerTest, LoggedInProfileDir) {
CommandLine *cl = CommandLine::ForCurrentProcess();
SystemMonitor dummy;
ProfileManager profile_manager;
std::string profile_dir("my_user");
cl->AppendSwitchWithValue(switches::kLoginProfile, profile_dir);
cl->AppendSwitch(switches::kTestType);
FilePath expected_default =
FilePath::FromWStringHack(chrome::kNotSignedInProfile);
EXPECT_EQ(expected_default.value(),
profile_manager.GetCurrentProfileDir().value());
profile_manager.Observe(NotificationType::LOGIN_USER_CHANGED,
NotificationService::AllSources(),
NotificationService::NoDetails());
FilePath expected_logged_in(profile_dir);
EXPECT_EQ(expected_logged_in.value(),
profile_manager.GetCurrentProfileDir().value());
LOG(INFO) << test_dir_.Append(profile_manager.GetCurrentProfileDir()).value();
}
#endif
TEST_F(ProfileManagerTest, CreateAndUseTwoProfiles) {
FilePath source_path;
PathService::Get(chrome::DIR_TEST_DATA, &source_path);
source_path = source_path.Append(FILE_PATH_LITERAL("profiles"));
source_path = source_path.Append(FILE_PATH_LITERAL("sample"));
FilePath dest_path1 = test_dir_;
dest_path1 = dest_path1.Append(FILE_PATH_LITERAL("New Profile 1"));
FilePath dest_path2 = test_dir_;
dest_path2 = dest_path2.Append(FILE_PATH_LITERAL("New Profile 2"));
scoped_ptr<Profile> profile1;
scoped_ptr<Profile> profile2;
// Successfully create the profiles.
profile1.reset(ProfileManager::CreateProfile(dest_path1));
ASSERT_TRUE(profile1.get());
profile2.reset(ProfileManager::CreateProfile(dest_path2));
ASSERT_TRUE(profile2.get());
// Force lazy-init of some profile services to simulate use.
EXPECT_TRUE(profile1->GetHistoryService(Profile::EXPLICIT_ACCESS));
EXPECT_TRUE(profile1->GetBookmarkModel());
EXPECT_TRUE(profile2->GetBookmarkModel());
EXPECT_TRUE(profile2->GetHistoryService(Profile::EXPLICIT_ACCESS));
profile1.reset();
profile2.reset();
}
<|endoftext|> |
<commit_before>#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/io/octree_pointcloud_compression.h>
#include <stdio.h>
#include <sstream>
#include <stdlib.h>
using namespace std;
using namespace pcl;
using namespace pcl::octree;
#ifdef WIN32
# define sleep(x) Sleep((x)*1000)
#endif
class SimpleOpenNIViewer
{
public:
SimpleOpenNIViewer () :
viewer (" Point Cloud Compression Example")
{
}
void
cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
{
if (!viewer.wasStopped ())
{
// stringstream to store compressed point cloud
std::stringstream compressedData;
// output pointcloud
PointCloud<PointXYZRGB>::Ptr cloudOut (new PointCloud<PointXYZRGB> ());
// compress point cloud
PointCloudEncoder->encodePointCloud (cloud, compressedData);
// decompress point cloud
PointCloudDecoder->decodePointCloud (compressedData, cloudOut);
// show decompressed point cloud
viewer.showCloud (cloudOut);
}
}
void
run ()
{
bool showStatistics = true;
// for a full list of profiles see: /io/include/pcl/compression/compression_profiles.h
compression_Profiles_e compressionProfile = pcl::octree::MED_RES_ONLINE_COMPRESSION_WITH_COLOR;
// instantiate point cloud compression for encoding and decoding
PointCloudEncoder = new PointCloudCompression<PointXYZRGB> (compressionProfile, showStatistics);
PointCloudDecoder = new PointCloudCompression<PointXYZRGB> ();
// create a new grabber for OpenNI devices
pcl::Grabber* interface = new pcl::OpenNIGrabber ();
// make callback function from member function
boost::function<void
(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)> f = boost::bind (&SimpleOpenNIViewer::cloud_cb_, this, _1);
// connect callback function for desired signal. In this case its a point cloud with color values
boost::signals2::connection c = interface->registerCallback (f);
// start receiving point clouds
interface->start ();
while (!viewer.wasStopped ())
{
sleep (1);
}
interface->stop ();
// delete point cloud compression instances
delete (PointCloudEncoder);
delete (PointCloudDecoder);
}
pcl::visualization::CloudViewer viewer;
PointCloudCompression<PointXYZRGB>* PointCloudEncoder;
PointCloudCompression<PointXYZRGB>* PointCloudDecoder;
};
int
main (int argc, char **argv)
{
SimpleOpenNIViewer v;
v.run ();
return 0;
}
<commit_msg>reverting r1201, better fix is in r1168, thanks Mourad<commit_after>#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/compression/octree_pointcloud_compression.h>
#include <stdio.h>
#include <sstream>
#include <stdlib.h>
using namespace std;
using namespace pcl;
using namespace pcl::octree;
#ifdef WIN32
# define sleep(x) Sleep((x)*1000)
#endif
class SimpleOpenNIViewer
{
public:
SimpleOpenNIViewer () :
viewer (" Point Cloud Compression Example")
{
}
void
cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
{
if (!viewer.wasStopped ())
{
// stringstream to store compressed point cloud
std::stringstream compressedData;
// output pointcloud
PointCloud<PointXYZRGB>::Ptr cloudOut (new PointCloud<PointXYZRGB> ());
// compress point cloud
PointCloudEncoder->encodePointCloud (cloud, compressedData);
// decompress point cloud
PointCloudDecoder->decodePointCloud (compressedData, cloudOut);
// show decompressed point cloud
viewer.showCloud (cloudOut);
}
}
void
run ()
{
bool showStatistics = true;
// for a full list of profiles see: /io/include/pcl/compression/compression_profiles.h
compression_Profiles_e compressionProfile = pcl::octree::MED_RES_ONLINE_COMPRESSION_WITH_COLOR;
// instantiate point cloud compression for encoding and decoding
PointCloudEncoder = new PointCloudCompression<PointXYZRGB> (compressionProfile, showStatistics);
PointCloudDecoder = new PointCloudCompression<PointXYZRGB> ();
// create a new grabber for OpenNI devices
pcl::Grabber* interface = new pcl::OpenNIGrabber ();
// make callback function from member function
boost::function<void
(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)> f = boost::bind (&SimpleOpenNIViewer::cloud_cb_, this, _1);
// connect callback function for desired signal. In this case its a point cloud with color values
boost::signals2::connection c = interface->registerCallback (f);
// start receiving point clouds
interface->start ();
while (!viewer.wasStopped ())
{
sleep (1);
}
interface->stop ();
// delete point cloud compression instances
delete (PointCloudEncoder);
delete (PointCloudDecoder);
}
pcl::visualization::CloudViewer viewer;
PointCloudCompression<PointXYZRGB>* PointCloudEncoder;
PointCloudCompression<PointXYZRGB>* PointCloudDecoder;
};
int
main (int argc, char **argv)
{
SimpleOpenNIViewer v;
v.run ();
return 0;
}
<|endoftext|> |
<commit_before>#include "vulkan.hpp"
#include "vulkan_symbol_wrapper.h"
#include <stdexcept>
#include <vector>
#include "vulkan_events.hpp"
#ifdef HAVE_GLFW
#include <GLFW/glfw3.h>
#endif
#ifdef HAVE_DYLIB
#include <dlfcn.h>
#endif
using namespace std;
#undef VULKAN_DEBUG
namespace Vulkan
{
Context::Context(const char **instance_ext, uint32_t instance_ext_count, const char **device_ext,
uint32_t device_ext_count)
: owned_instance(true)
, owned_device(true)
{
if (!create_instance(instance_ext, instance_ext_count))
{
destroy();
throw runtime_error("Failed to create Vulkan instance.");
}
VkPhysicalDeviceFeatures features = {};
if (!create_device(VK_NULL_HANDLE, VK_NULL_HANDLE, device_ext, device_ext_count, nullptr, 0, &features))
{
destroy();
throw runtime_error("Failed to create Vulkan device.");
}
}
bool Context::init_loader(PFN_vkGetInstanceProcAddr addr)
{
if (!addr)
{
#ifdef HAVE_DYLIB
static void *module;
if (!module)
{
module = dlopen("libvulkan.so", RTLD_LOCAL | RTLD_LAZY);
if (!module)
return false;
}
addr = reinterpret_cast<PFN_vkGetInstanceProcAddr>(dlsym(module, "vkGetInstanceProcAddr"));
if (!addr)
return false;
#else
return false;
#endif
}
vulkan_symbol_wrapper_init(addr);
return vulkan_symbol_wrapper_load_global_symbols();
}
Context::Context(VkInstance instance, VkPhysicalDevice gpu, VkDevice device, VkQueue queue, uint32_t queue_family)
: device(device)
, instance(instance)
, gpu(gpu)
, queue(queue)
, queue_family(queue_family)
, owned_instance(false)
, owned_device(false)
{
vulkan_symbol_wrapper_load_core_instance_symbols(instance);
vulkan_symbol_wrapper_load_core_device_symbols(device);
vkGetPhysicalDeviceProperties(gpu, &gpu_props);
vkGetPhysicalDeviceMemoryProperties(gpu, &mem_props);
}
Context::Context(VkInstance instance, VkPhysicalDevice gpu, VkSurfaceKHR surface,
const char **required_device_extensions, unsigned num_required_device_extensions,
const char **required_device_layers, unsigned num_required_device_layers,
const VkPhysicalDeviceFeatures *required_features)
: instance(instance)
, owned_instance(false)
, owned_device(true)
{
vulkan_symbol_wrapper_load_core_instance_symbols(instance);
if (!create_device(gpu, surface, required_device_extensions, num_required_device_extensions, required_device_layers,
num_required_device_layers, required_features))
{
destroy();
throw runtime_error("Failed to create Vulkan device.");
}
}
void Context::destroy()
{
if (device != VK_NULL_HANDLE)
vkDeviceWaitIdle(device);
#ifdef VULKAN_DEBUG
if (debug_callback)
vkDestroyDebugReportCallbackEXT(instance, debug_callback, nullptr);
#endif
if (owned_device && device != VK_NULL_HANDLE)
vkDestroyDevice(device, nullptr);
if (owned_instance && instance != VK_NULL_HANDLE)
vkDestroyInstance(instance, nullptr);
}
Context::~Context()
{
destroy();
}
const VkApplicationInfo &Context::get_application_info()
{
static const VkApplicationInfo info = {
VK_STRUCTURE_TYPE_APPLICATION_INFO, nullptr, "paraLLEl PSX", 0, "paraLLEl PSX", 0, VK_MAKE_VERSION(1, 0, 18),
};
return info;
}
#ifdef VULKAN_DEBUG
static VKAPI_ATTR VkBool32 VKAPI_CALL vulkan_debug_cb(VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT objectType, uint64_t object,
size_t location, int32_t messageCode, const char *pLayerPrefix,
const char *pMessage, void *pUserData)
{
(void)objectType;
(void)object;
(void)location;
(void)messageCode;
(void)pUserData;
if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)
{
fprintf(stderr, "[Vulkan]: Error: %s: %s\n", pLayerPrefix, pMessage);
}
else if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT)
{
fprintf(stderr, "[Vulkan]: Warning: %s: %s\n", pLayerPrefix, pMessage);
}
else if (flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT)
{
//fprintf(stderr, "[Vulkan]: Performance warning: %s: %s\n", pLayerPrefix, pMessage);
}
else
{
fprintf(stderr, "[Vulkan]: Information: %s: %s\n", pLayerPrefix, pMessage);
}
return VK_FALSE;
}
#endif
bool Context::create_instance(const char **instance_ext, uint32_t instance_ext_count)
{
VkInstanceCreateInfo info = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO };
info.pApplicationInfo = &get_application_info();
vector<const char *> instance_exts;
vector<const char *> instance_layers;
for (uint32_t i = 0; i < instance_ext_count; i++)
instance_exts.push_back(instance_ext[i]);
#ifdef VULKAN_DEBUG
instance_exts.push_back("VK_EXT_debug_report");
instance_layers.push_back("VK_LAYER_LUNARG_standard_validation");
#endif
info.enabledExtensionCount = instance_exts.size();
info.ppEnabledExtensionNames = instance_exts.empty() ? nullptr : instance_exts.data();
info.enabledLayerCount = instance_layers.size();
info.ppEnabledLayerNames = instance_layers.empty() ? nullptr : instance_layers.data();
if (vkCreateInstance(&info, nullptr, &instance) != VK_SUCCESS)
return false;
vulkan_symbol_wrapper_load_core_instance_symbols(instance);
#ifdef VULKAN_DEBUG
VULKAN_SYMBOL_WRAPPER_LOAD_INSTANCE_EXTENSION_SYMBOL(instance, vkCreateDebugReportCallbackEXT);
VULKAN_SYMBOL_WRAPPER_LOAD_INSTANCE_EXTENSION_SYMBOL(instance, vkDebugReportMessageEXT);
VULKAN_SYMBOL_WRAPPER_LOAD_INSTANCE_EXTENSION_SYMBOL(instance, vkDestroyDebugReportCallbackEXT);
{
VkDebugReportCallbackCreateInfoEXT info = { VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT };
info.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT |
VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;
info.pfnCallback = vulkan_debug_cb;
vkCreateDebugReportCallbackEXT(instance, &info, NULL, &debug_callback);
}
#endif
return true;
}
bool Context::create_device(VkPhysicalDevice gpu, VkSurfaceKHR surface, const char **required_device_extensions,
unsigned num_required_device_extensions, const char **required_device_layers,
unsigned num_required_device_layers, const VkPhysicalDeviceFeatures *required_features)
{
if (gpu == VK_NULL_HANDLE)
{
uint32_t gpu_count = 0;
V(vkEnumeratePhysicalDevices(instance, &gpu_count, nullptr));
vector<VkPhysicalDevice> gpus(gpu_count);
V(vkEnumeratePhysicalDevices(instance, &gpu_count, gpus.data()));
gpu = gpus.front();
}
this->gpu = gpu;
vkGetPhysicalDeviceProperties(gpu, &gpu_props);
vkGetPhysicalDeviceMemoryProperties(gpu, &mem_props);
LOGI("Vulkan GPU: %s\n", gpu_props.deviceName);
uint32_t queue_count;
vkGetPhysicalDeviceQueueFamilyProperties(gpu, &queue_count, nullptr);
vector<VkQueueFamilyProperties> queue_props(queue_count);
vkGetPhysicalDeviceQueueFamilyProperties(gpu, &queue_count, queue_props.data());
if (surface != VK_NULL_HANDLE)
{
VULKAN_SYMBOL_WRAPPER_LOAD_INSTANCE_EXTENSION_SYMBOL(instance, vkGetPhysicalDeviceSurfaceSupportKHR);
}
bool found_queue = false;
for (unsigned i = 0; i < queue_count; i++)
{
VkBool32 supported = surface == VK_NULL_HANDLE;
#ifdef HAVE_GLFW
supported = glfwGetPhysicalDevicePresentationSupport(instance, gpu, i);
#else
if (surface != VK_NULL_HANDLE)
vkGetPhysicalDeviceSurfaceSupportKHR(gpu, i, surface, &supported);
#endif
VkQueueFlags required = VK_QUEUE_COMPUTE_BIT | VK_QUEUE_GRAPHICS_BIT;
if (supported && ((queue_props[i].queueFlags & required) == required))
{
found_queue = true;
queue_family = i;
break;
}
}
if (!found_queue)
return false;
static const float prio = 1.0f;
VkDeviceQueueCreateInfo queue_info = { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO };
VkDeviceCreateInfo device_info = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO };
device_info.pQueueCreateInfos = &queue_info;
queue_info.queueFamilyIndex = queue_family;
queue_info.queueCount = 1;
queue_info.pQueuePriorities = &prio;
device_info.queueCreateInfoCount = 1;
// Should query for these, but no big deal for now.
device_info.ppEnabledExtensionNames = required_device_extensions;
device_info.enabledExtensionCount = num_required_device_extensions;
device_info.ppEnabledLayerNames = required_device_layers;
device_info.enabledLayerCount = num_required_device_layers;
VkPhysicalDeviceFeatures enabled_features = *required_features;
{
VkPhysicalDeviceFeatures features;
vkGetPhysicalDeviceFeatures(gpu, &features);
if (features.textureCompressionETC2)
enabled_features.textureCompressionETC2 = VK_TRUE;
if (features.textureCompressionBC)
enabled_features.textureCompressionBC = VK_TRUE;
if (features.textureCompressionASTC_LDR)
enabled_features.textureCompressionASTC_LDR = VK_TRUE;
if (features.fullDrawIndexUint32)
enabled_features.fullDrawIndexUint32 = VK_TRUE;
if (features.imageCubeArray)
enabled_features.imageCubeArray = VK_TRUE;
}
device_info.pEnabledFeatures = &enabled_features;
#ifdef VULKAN_DEBUG
static const char *device_layers[] = { "VK_LAYER_LUNARG_standard_validation" };
device_info.enabledLayerCount = 1;
device_info.ppEnabledLayerNames = device_layers;
#endif
if (vkCreateDevice(gpu, &device_info, nullptr, &device) != VK_SUCCESS)
return false;
vulkan_symbol_wrapper_load_core_device_symbols(device);
vkGetDeviceQueue(device, queue_family, 0, &queue);
return true;
}
}
<commit_msg>Log which GPUs are found.<commit_after>#include "vulkan.hpp"
#include "vulkan_symbol_wrapper.h"
#include <stdexcept>
#include <vector>
#include "vulkan_events.hpp"
#ifdef HAVE_GLFW
#include <GLFW/glfw3.h>
#endif
#ifdef HAVE_DYLIB
#include <dlfcn.h>
#endif
using namespace std;
#undef VULKAN_DEBUG
namespace Vulkan
{
Context::Context(const char **instance_ext, uint32_t instance_ext_count, const char **device_ext,
uint32_t device_ext_count)
: owned_instance(true)
, owned_device(true)
{
if (!create_instance(instance_ext, instance_ext_count))
{
destroy();
throw runtime_error("Failed to create Vulkan instance.");
}
VkPhysicalDeviceFeatures features = {};
if (!create_device(VK_NULL_HANDLE, VK_NULL_HANDLE, device_ext, device_ext_count, nullptr, 0, &features))
{
destroy();
throw runtime_error("Failed to create Vulkan device.");
}
}
bool Context::init_loader(PFN_vkGetInstanceProcAddr addr)
{
if (!addr)
{
#ifdef HAVE_DYLIB
static void *module;
if (!module)
{
module = dlopen("libvulkan.so", RTLD_LOCAL | RTLD_LAZY);
if (!module)
return false;
}
addr = reinterpret_cast<PFN_vkGetInstanceProcAddr>(dlsym(module, "vkGetInstanceProcAddr"));
if (!addr)
return false;
#else
return false;
#endif
}
vulkan_symbol_wrapper_init(addr);
return vulkan_symbol_wrapper_load_global_symbols();
}
Context::Context(VkInstance instance, VkPhysicalDevice gpu, VkDevice device, VkQueue queue, uint32_t queue_family)
: device(device)
, instance(instance)
, gpu(gpu)
, queue(queue)
, queue_family(queue_family)
, owned_instance(false)
, owned_device(false)
{
vulkan_symbol_wrapper_load_core_instance_symbols(instance);
vulkan_symbol_wrapper_load_core_device_symbols(device);
vkGetPhysicalDeviceProperties(gpu, &gpu_props);
vkGetPhysicalDeviceMemoryProperties(gpu, &mem_props);
}
Context::Context(VkInstance instance, VkPhysicalDevice gpu, VkSurfaceKHR surface,
const char **required_device_extensions, unsigned num_required_device_extensions,
const char **required_device_layers, unsigned num_required_device_layers,
const VkPhysicalDeviceFeatures *required_features)
: instance(instance)
, owned_instance(false)
, owned_device(true)
{
vulkan_symbol_wrapper_load_core_instance_symbols(instance);
if (!create_device(gpu, surface, required_device_extensions, num_required_device_extensions, required_device_layers,
num_required_device_layers, required_features))
{
destroy();
throw runtime_error("Failed to create Vulkan device.");
}
}
void Context::destroy()
{
if (device != VK_NULL_HANDLE)
vkDeviceWaitIdle(device);
#ifdef VULKAN_DEBUG
if (debug_callback)
vkDestroyDebugReportCallbackEXT(instance, debug_callback, nullptr);
#endif
if (owned_device && device != VK_NULL_HANDLE)
vkDestroyDevice(device, nullptr);
if (owned_instance && instance != VK_NULL_HANDLE)
vkDestroyInstance(instance, nullptr);
}
Context::~Context()
{
destroy();
}
const VkApplicationInfo &Context::get_application_info()
{
static const VkApplicationInfo info = {
VK_STRUCTURE_TYPE_APPLICATION_INFO, nullptr, "paraLLEl PSX", 0, "paraLLEl PSX", 0, VK_MAKE_VERSION(1, 0, 18),
};
return info;
}
#ifdef VULKAN_DEBUG
static VKAPI_ATTR VkBool32 VKAPI_CALL vulkan_debug_cb(VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT objectType, uint64_t object,
size_t location, int32_t messageCode, const char *pLayerPrefix,
const char *pMessage, void *pUserData)
{
(void)objectType;
(void)object;
(void)location;
(void)messageCode;
(void)pUserData;
if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)
{
fprintf(stderr, "[Vulkan]: Error: %s: %s\n", pLayerPrefix, pMessage);
}
else if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT)
{
fprintf(stderr, "[Vulkan]: Warning: %s: %s\n", pLayerPrefix, pMessage);
}
else if (flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT)
{
//fprintf(stderr, "[Vulkan]: Performance warning: %s: %s\n", pLayerPrefix, pMessage);
}
else
{
fprintf(stderr, "[Vulkan]: Information: %s: %s\n", pLayerPrefix, pMessage);
}
return VK_FALSE;
}
#endif
bool Context::create_instance(const char **instance_ext, uint32_t instance_ext_count)
{
VkInstanceCreateInfo info = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO };
info.pApplicationInfo = &get_application_info();
vector<const char *> instance_exts;
vector<const char *> instance_layers;
for (uint32_t i = 0; i < instance_ext_count; i++)
instance_exts.push_back(instance_ext[i]);
#ifdef VULKAN_DEBUG
instance_exts.push_back("VK_EXT_debug_report");
instance_layers.push_back("VK_LAYER_LUNARG_standard_validation");
#endif
info.enabledExtensionCount = instance_exts.size();
info.ppEnabledExtensionNames = instance_exts.empty() ? nullptr : instance_exts.data();
info.enabledLayerCount = instance_layers.size();
info.ppEnabledLayerNames = instance_layers.empty() ? nullptr : instance_layers.data();
if (vkCreateInstance(&info, nullptr, &instance) != VK_SUCCESS)
return false;
vulkan_symbol_wrapper_load_core_instance_symbols(instance);
#ifdef VULKAN_DEBUG
VULKAN_SYMBOL_WRAPPER_LOAD_INSTANCE_EXTENSION_SYMBOL(instance, vkCreateDebugReportCallbackEXT);
VULKAN_SYMBOL_WRAPPER_LOAD_INSTANCE_EXTENSION_SYMBOL(instance, vkDebugReportMessageEXT);
VULKAN_SYMBOL_WRAPPER_LOAD_INSTANCE_EXTENSION_SYMBOL(instance, vkDestroyDebugReportCallbackEXT);
{
VkDebugReportCallbackCreateInfoEXT info = { VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT };
info.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT |
VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;
info.pfnCallback = vulkan_debug_cb;
vkCreateDebugReportCallbackEXT(instance, &info, NULL, &debug_callback);
}
#endif
return true;
}
bool Context::create_device(VkPhysicalDevice gpu, VkSurfaceKHR surface, const char **required_device_extensions,
unsigned num_required_device_extensions, const char **required_device_layers,
unsigned num_required_device_layers, const VkPhysicalDeviceFeatures *required_features)
{
if (gpu == VK_NULL_HANDLE)
{
uint32_t gpu_count = 0;
V(vkEnumeratePhysicalDevices(instance, &gpu_count, nullptr));
vector<VkPhysicalDevice> gpus(gpu_count);
V(vkEnumeratePhysicalDevices(instance, &gpu_count, gpus.data()));
for (auto &gpu : gpus)
{
VkPhysicalDeviceProperties props;
vkGetPhysicalDeviceProperties(gpu, &props);
LOGI("Found Vulkan GPU: %s\n", props.deviceName);
}
gpu = gpus.front();
}
this->gpu = gpu;
vkGetPhysicalDeviceProperties(gpu, &gpu_props);
vkGetPhysicalDeviceMemoryProperties(gpu, &mem_props);
LOGI("Selected Vulkan GPU: %s\n", gpu_props.deviceName);
uint32_t queue_count;
vkGetPhysicalDeviceQueueFamilyProperties(gpu, &queue_count, nullptr);
vector<VkQueueFamilyProperties> queue_props(queue_count);
vkGetPhysicalDeviceQueueFamilyProperties(gpu, &queue_count, queue_props.data());
if (surface != VK_NULL_HANDLE)
{
VULKAN_SYMBOL_WRAPPER_LOAD_INSTANCE_EXTENSION_SYMBOL(instance, vkGetPhysicalDeviceSurfaceSupportKHR);
}
bool found_queue = false;
for (unsigned i = 0; i < queue_count; i++)
{
VkBool32 supported = surface == VK_NULL_HANDLE;
#ifdef HAVE_GLFW
supported = glfwGetPhysicalDevicePresentationSupport(instance, gpu, i);
#else
if (surface != VK_NULL_HANDLE)
vkGetPhysicalDeviceSurfaceSupportKHR(gpu, i, surface, &supported);
#endif
VkQueueFlags required = VK_QUEUE_COMPUTE_BIT | VK_QUEUE_GRAPHICS_BIT;
if (supported && ((queue_props[i].queueFlags & required) == required))
{
found_queue = true;
queue_family = i;
break;
}
}
if (!found_queue)
return false;
static const float prio = 1.0f;
VkDeviceQueueCreateInfo queue_info = { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO };
VkDeviceCreateInfo device_info = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO };
device_info.pQueueCreateInfos = &queue_info;
queue_info.queueFamilyIndex = queue_family;
queue_info.queueCount = 1;
queue_info.pQueuePriorities = &prio;
device_info.queueCreateInfoCount = 1;
// Should query for these, but no big deal for now.
device_info.ppEnabledExtensionNames = required_device_extensions;
device_info.enabledExtensionCount = num_required_device_extensions;
device_info.ppEnabledLayerNames = required_device_layers;
device_info.enabledLayerCount = num_required_device_layers;
VkPhysicalDeviceFeatures enabled_features = *required_features;
{
VkPhysicalDeviceFeatures features;
vkGetPhysicalDeviceFeatures(gpu, &features);
if (features.textureCompressionETC2)
enabled_features.textureCompressionETC2 = VK_TRUE;
if (features.textureCompressionBC)
enabled_features.textureCompressionBC = VK_TRUE;
if (features.textureCompressionASTC_LDR)
enabled_features.textureCompressionASTC_LDR = VK_TRUE;
if (features.fullDrawIndexUint32)
enabled_features.fullDrawIndexUint32 = VK_TRUE;
if (features.imageCubeArray)
enabled_features.imageCubeArray = VK_TRUE;
}
device_info.pEnabledFeatures = &enabled_features;
#ifdef VULKAN_DEBUG
static const char *device_layers[] = { "VK_LAYER_LUNARG_standard_validation" };
device_info.enabledLayerCount = 1;
device_info.ppEnabledLayerNames = device_layers;
#endif
if (vkCreateDevice(gpu, &device_info, nullptr, &device) != VK_SUCCESS)
return false;
vulkan_symbol_wrapper_load_core_device_symbols(device);
vkGetDeviceQueue(device, queue_family, 0, &queue);
return true;
}
}
<|endoftext|> |
<commit_before>#pragma once
using namespace std;
#include <vector>
#include <regex>
#include "IEventHandler.hpp"
#include "ICommand.hpp"
#include "Line.hpp"
#include "Utility.hpp"
namespace OCScript
{
// OCScript̃RANXłB
class Core
{
private:
vector<ICommand*> _Commands;
vector<Line> _ScriptStorage;
unsigned int _CurrentLineIndex;
public:
// R}hlj܂B
// : ICommandExecutableR}h̃NX
void AddCommand(ICommand *command)
{
_Commands.push_back(command);
}
// ɎssύX܂B
// : s0n܂CfbNX
void SetCurrentLineIndex(unsigned int lineIndex)
{
_CurrentLineIndex = lineIndex;
}
// XNvg ScriptStorage Ɉꊇǂݍ݂܂B
// : s蕶̃xN^
// O\̂郁\bhł
void LoadScript(const vector<string> scriptLines)
{
vector<Line> lines;
int lineIndex = 1;
for (auto scriptLine : scriptLines)
{
smatch m1, m2;
// słȂ
if (!regex_match(scriptLine, regex("^[ \t]*$")))
{
m1 = smatch();
// \Ƀ}b`
if (regex_match(scriptLine, m1, regex("^[ \t]*([a-zA-Z0-9._-]+)[ \t]*\\((.+)\\)[ \t]*;[ \t]*$")))
{
string commandName = m1[1];
string paramsStr = m1[2];
vector<string> paramsSourceVec = Utility::StrSplit(paramsStr, ',');
vector<string> paramsDestVec;
int paramIndex = 1;
for (auto paramToken : paramsSourceVec)
{
string content;
m1 = smatch();
m2 = smatch();
// NH[gẗł
if (regex_match(paramToken, m1, regex("^[ \t]*\"(.*)\"[ \t]*$")) || regex_match(paramToken, m2, regex("^[ \t]*\'(.*)\'[ \t]*$")))
{
if (!m1.empty())
content = m1[1];
else if (!m2.empty())
content = m2[1];
else
throw exception(("VXeG[܂B}b`ʂĂ܂B(s: " + to_string(lineIndex) + ")").c_str());
}
else
{
m1 = smatch();
if (!regex_match(paramToken, m1, regex("^[ \t]*([^ \t]*)[ \t]*$")))
throw exception(("͎̉ɃG[܂B(s: " + to_string(lineIndex) + ", ԍ: " + to_string(paramIndex) + ")").c_str());
content = m1[1];
}
paramsDestVec.push_back(content);
paramIndex++;
}
lines.push_back(Line(commandName, paramsDestVec));
}
else
throw exception(("\G[܂B(s: " + to_string(lineIndex) + ")").c_str());
}
lineIndex++;
}
_ScriptStorage = vector<Line>(lines);
}
// XNvg ScriptStorage Ɉꊇǂݍ݂܂B
// : XNvg̕
// O\̂郁\bhł
void LoadScript(const string scriptText)
{
vector<string> scriptLines = Utility::StrSplit(scriptText, '\n');
LoadScript(scriptLines);
}
// s̑ΏۂƂȂĂXNvgs܂B
// O\̂郁\bhł
void ExecuteCurrentLine()
{
if (_ScriptStorage.empty())
throw("ScriptStorage̒głB");
if (_CurrentLineIndex > _ScriptStorage.size() - 1)
throw("XNvg͍Ō܂ŎsĂ܂B");
auto line = _ScriptStorage[_CurrentLineIndex];
for (auto command : _Commands)
if (line.GetCommandName() == command->GetCommandName())
{
AccessEventArgs accessEventArgs;
command->Access(&accessEventArgs, line.GetParams());
if (!accessEventArgs.GetIsCancelNextCommand())
_CurrentLineIndex++;
}
if (_CurrentLineIndex >= _ScriptStorage.size() - 1)
{
}
}
};
}
<commit_msg>Add TODO<commit_after>#pragma once
using namespace std;
#include <vector>
#include <regex>
#include "IEventHandler.hpp"
#include "ICommand.hpp"
#include "Line.hpp"
#include "Utility.hpp"
namespace OCScript
{
// OCScript̃RANXłB
class Core
{
private:
vector<ICommand*> _Commands;
vector<Line> _ScriptStorage;
unsigned int _CurrentLineIndex;
public:
// R}hlj܂B
// : ICommandExecutableR}h̃NX
void AddCommand(ICommand *command)
{
_Commands.push_back(command);
}
// ɎssύX܂B
// : s0n܂CfbNX
void SetCurrentLineIndex(unsigned int lineIndex)
{
_CurrentLineIndex = lineIndex;
}
// XNvg ScriptStorage Ɉꊇǂݍ݂܂B
// : s蕶̃xN^
// O\̂郁\bhł
void LoadScript(const vector<string> scriptLines)
{
vector<Line> lines;
int lineIndex = 1;
for (auto scriptLine : scriptLines)
{
smatch m1, m2;
// słȂ
if (!regex_match(scriptLine, regex("^[ \t]*$")))
{
m1 = smatch();
// \Ƀ}b`
if (regex_match(scriptLine, m1, regex("^[ \t]*([a-zA-Z0-9._-]+)[ \t]*\\((.+)\\)[ \t]*;[ \t]*$")))
{
string commandName = m1[1];
string paramsStr = m1[2];
vector<string> paramsSourceVec = Utility::StrSplit(paramsStr, ',');
vector<string> paramsDestVec;
int paramIndex = 1;
for (auto paramToken : paramsSourceVec)
{
string content;
m1 = smatch();
m2 = smatch();
// NH[gẗł
if (regex_match(paramToken, m1, regex("^[ \t]*\"(.*)\"[ \t]*$")) || regex_match(paramToken, m2, regex("^[ \t]*\'(.*)\'[ \t]*$")))
{
if (!m1.empty())
content = m1[1];
else if (!m2.empty())
content = m2[1];
else
throw exception(("VXeG[܂B}b`ʂĂ܂B(s: " + to_string(lineIndex) + ")").c_str());
}
else
{
m1 = smatch();
if (!regex_match(paramToken, m1, regex("^[ \t]*([^ \t]*)[ \t]*$")))
throw exception(("͎̉ɃG[܂B(s: " + to_string(lineIndex) + ", ԍ: " + to_string(paramIndex) + ")").c_str());
content = m1[1];
}
paramsDestVec.push_back(content);
paramIndex++;
}
lines.push_back(Line(commandName, paramsDestVec));
}
else
throw exception(("\G[܂B(s: " + to_string(lineIndex) + ")").c_str());
}
lineIndex++;
}
_ScriptStorage = vector<Line>(lines);
}
// XNvg ScriptStorage Ɉꊇǂݍ݂܂B
// : XNvg̕
// O\̂郁\bhł
void LoadScript(const string scriptText)
{
vector<string> scriptLines = Utility::StrSplit(scriptText, '\n');
LoadScript(scriptLines);
}
// s̑ΏۂƂȂĂXNvgs܂B
// O\̂郁\bhł
void ExecuteCurrentLine()
{
if (_ScriptStorage.empty())
throw("ScriptStorage̒głB");
if (_CurrentLineIndex > _ScriptStorage.size() - 1)
throw("XNvg͍Ō܂ŎsĂ܂B");
auto line = _ScriptStorage[_CurrentLineIndex];
for (auto command : _Commands)
if (line.GetCommandName() == command->GetCommandName())
{
AccessEventArgs accessEventArgs;
command->Access(&accessEventArgs, line.GetParams());
if (!accessEventArgs.GetIsCancelNextCommand())
_CurrentLineIndex++;
}
if (_CurrentLineIndex >= _ScriptStorage.size() - 1)
{
// TODO: Ō܂ŎsꂽƂCxg
}
}
};
}
<|endoftext|> |
<commit_before>#include "RedBlackTree.h"
#include <algorithm>
#include <cassert>
#include <iostream>
#include <string>
#include <utility>
#define RED 'R'
#define BLACK 'B'
RbNode RBNIL = {BLACK, -1, &RBNIL, &RBNIL, &RBNIL};
static RbNode *Next(RbNode *e) {
RbNode *p = e->right;
while (not_nil(p->left)) {
p = p->left;
}
return p;
}
static RbNode *Uncle(RbNode *e) {
if (e->father->father->left == e->father)
return e->father->father->right;
if (e->father->father->right == e->father)
return e->father->father->left;
assert(false);
}
static bool IsLeft(RbNode *e) { return e->father->left == e; }
static bool IsRight(RbNode *e) { return e->father->right == e; }
static RbNode *Brother(RbNode *e) {
if (IsLeft(e)) {
return e->father->right;
}
if (IsRight(e)) {
return e->father->left;
}
assert(false);
}
static std::string DumpColor(const RbNode *e) {
return (is_nil(e) ? "B" : (e->color == BLACK ? "B" : "R"));
}
static void DumpNode(RbNode *e) {
if (is_nil(e)) {
std::cout << " [nil B] RBNIL[" << DumpColor(&RBNIL) << "]" << std::endl;
} else {
std::cout << " [" << e->value << " " << DumpColor(e) << " left:"
<< (is_nil(e->left) ? "nil" : std::to_string(e->left->value))
<< " right:"
<< (is_nil(e->right) ? "nil" : std::to_string(e->right->value))
<< " father:"
<< (is_nil(e->father) ? "nil" : std::to_string(e->father->value))
<< "] RBNIL[" << DumpColor(&RBNIL) << "]" << std::endl;
if (not_nil(e->left)) {
DumpNode(e->left);
}
if (not_nil(e->right)) {
DumpNode(e->right);
}
}
}
static void DumpTree(RbNode *root, const std::string &msg) {
assert(root);
std::cout << std::endl << std::endl << msg << std::endl;
DumpNode(root);
}
static void DumpTree(RedBlackTree *t, const std::string &msg) {
assert(t);
DumpTree(t->root, msg);
}
static void Free(RbNode *e) {
if (e == NULL || is_nil(e))
return;
Free(e->left);
Free(e->right);
delete e;
}
static void LeftRotate(RedBlackTree *t, RbNode *e) {
DumpTree(t, "before left rotate e:" + std::to_string(e->value));
RbNode *p = e->right;
e->right = p->left;
if (not_nil(p->left)) {
p->left->father = e;
}
if (not_nil(p)) {
p->father = e->father;
}
if (not_nil(e->father)) {
if (e == e->father->left) {
e->father->left = p;
} else {
e->father->right = p;
}
} else {
t->root = p;
}
p->left = e;
if (not_nil(e)) {
e->father = p;
}
DumpTree(t, "after left rotate e:" + std::to_string(e->value));
}
static void RightRotate(RedBlackTree *t, RbNode *e) {
DumpTree(t, "before right rotate e:" + std::to_string(e->value));
RbNode *p = e->left;
e->left = p->right;
if (not_nil(p->right)) {
p->right->father = e;
}
if (not_nil(p)) {
p->father = e->father;
}
if (not_nil(e->father)) {
if (e == e->father->right) {
e->father->right = p;
} else {
e->father->left = p;
}
} else {
t->root = p;
}
p->right = e;
if (not_nil(e)) {
e->father = p;
}
DumpTree(t, "after right rotate e:" + std::to_string(e->value));
}
void FixInsert(RedBlackTree *t, RbNode *e) {
assert(RBNIL.color == BLACK);
while ((e != t->root) && (e->father->color == RED)) {
// case A: e.father is e.grand_father's left child
if (IsLeft(e->father)) {
RbNode *e_uncle = Uncle(e);
// case 1: Red Uncle, e.uncle is red
if (e_uncle->color == RED) {
e->father->color = BLACK;
e_uncle->color = BLACK;
e->father->father->color = RED;
e = e->father->father; // next loop from e.grand_father
} else {
// case 2: Black Uncle, left-right-case
if (IsRight(e)) {
e = e->father;
LeftRotate(t, e);
}
// case 3: Black Uncle, left-left-case
e->father->color = BLACK;
e->father->father->color = RED;
RightRotate(t, e->father->father);
}
}
// case B: e.father is e.grand_father's right child
else {
RbNode *e_uncle = Uncle(e);
// case 1: Red Uncle
if (e_uncle->color == RED) {
e->father->color = BLACK;
e_uncle->color = BLACK;
e->father->father->color = RED;
e = e->father->father; // next loop from e.grand_father
} else {
// case 4: Black Uncle, left-right-case
if (IsLeft(e)) {
e = e->father;
RightRotate(t, e);
}
// case 5: Black Uncle, right-right-case
e->father->color = BLACK;
e->father->father->color = RED;
LeftRotate(t, e->father->father);
}
}
} // while
t->root->color = BLACK;
}
static void FixErase(RedBlackTree *t, RbNode *e) {
assert(RBNIL.color == BLACK);
while ((e != t->root) && (e->color == BLACK)) {
DumpTree(t, "fix erase");
// case A: e is left child
if (IsLeft(e)) {
RbNode *e_brother = Brother(e);
if (e_brother->color == RED) {
e_brother->color = BLACK;
e->father->color = RED;
LeftRotate(t, e->father);
e_brother = e->father->right;
}
if (e_brother->left->color == BLACK && e_brother->right->color == BLACK) {
e_brother->color = RED;
e = e->father;
} else {
if (e_brother->right->color == BLACK) {
e_brother->left->color = BLACK;
e_brother->color = RED;
RightRotate(t, e_brother);
e_brother = e->father->right;
}
e_brother->color = e->father->color;
e->father->color = BLACK;
e_brother->right->color = BLACK;
LeftRotate(t, e->father);
e = t->root; // break loop
}
}
// case B: e is right child
else {
RbNode *e_brother = Brother(e);
if (e_brother->color == RED) {
e_brother->color = BLACK;
e->father->color = RED;
LeftRotate(t, e->father);
e_brother = e->father->left;
}
if (e_brother->right->color == BLACK && e_brother->left->color == BLACK) {
e_brother->color = RED;
e = e->father;
} else {
if (e_brother->left->color == BLACK) {
e_brother->right->color = BLACK;
e_brother->color = RED;
LeftRotate(t, e_brother);
e_brother = e->father->left;
}
e_brother->color = e->father->color;
e->father->color = BLACK;
e_brother->left->color = BLACK;
RightRotate(t, e->father);
e = t->root; // break loop
}
}
}
e->color = BLACK;
}
static void Erase(RedBlackTree *t, RbNode *e) {
assert(RBNIL.color == BLACK);
RbNode *p, *q;
if (is_nil(e)) {
return;
}
if (is_nil(e->left) || is_nil(e->right)) {
p = e;
} else {
p = Next(e);
}
if (not_nil(p->left)) {
q = p->left;
} else {
q = p->right;
}
if (not_nil(q)) {
q->father = p->father;
}
if (not_nil(p->father)) {
if (IsLeft(p)) {
p->father->left = q;
} else {
p->father->right = q;
}
} else {
t->root = q;
}
if (p != e) {
e->value = p->value;
}
if (p->color == BLACK) {
FixErase(t, q);
}
delete p;
}
static RbNode *Find(RbNode *e, int value) {
assert(RBNIL.color == BLACK);
if (is_nil(e)) {
return &RBNIL;
}
//二分查找
if (e->value == value) {
return e;
} else if (e->value > value) {
return Find(e->left, value);
} else {
return Find(e->right, value);
}
}
static RbNode *Insert(RbNode *father, RbNode *e) {
assert(RBNIL.color == BLACK);
assert(e);
if (is_nil(father)) {
return e;
}
//利用二分查找找到适合value插入的位置e
if (father->value > e->value) {
father->left = Insert(father->left, e);
father->left->father = father;
} else if (father->value < e->value) {
father->right = Insert(father->right, e);
father->right->father = father;
} else {
assert(father->value != e->value);
}
return father;
}
RedBlackTree *RedBlackTreeNew() {
RedBlackTree *t = new RedBlackTree();
if (!t)
return NULL;
set_nil(t->root);
return t;
}
void RedBlackTreeFree(RedBlackTree *t) {
assert(t);
Free(t->root);
delete t;
}
void RedBlackTreeInsert(RedBlackTree *t, int value) {
assert(t);
assert(value >= 0);
RbNode *e = new RbNode();
set_nil(e->left);
set_nil(e->right);
set_nil(e->father);
e->color = RED; // new node is red
e->value = value;
t->root = Insert(t->root, e);
FixInsert(t, e);
assert(RBNIL.color == BLACK);
}
RbNode *RedBlackTreeFind(RedBlackTree *t, int value) {
return Find(t->root, value);
}
void RedBlackTreeErase(RedBlackTree *t, int value) {
RbNode *e = Find(t->root, value);
Erase(t, e);
DumpTree(t, "erase");
assert(RBNIL.color == BLACK);
}
<commit_msg>use return instead of red black tree ptr<commit_after>#include "RedBlackTree.h"
#include <algorithm>
#include <cassert>
#include <iostream>
#include <string>
#include <utility>
#define RED 'R'
#define BLACK 'B'
RbNode RBNIL = {BLACK, -1, &RBNIL, &RBNIL, &RBNIL};
static RbNode *Next(RbNode *e) {
RbNode *p = e->right;
while (not_nil(p->left)) {
p = p->left;
}
return p;
}
static RbNode *Uncle(RbNode *e) {
if (e->father->father->left == e->father)
return e->father->father->right;
if (e->father->father->right == e->father)
return e->father->father->left;
assert(false);
}
static bool IsLeft(RbNode *e) { return e->father->left == e; }
static bool IsRight(RbNode *e) { return e->father->right == e; }
static RbNode *Brother(RbNode *e) {
if (IsLeft(e)) {
return e->father->right;
}
if (IsRight(e)) {
return e->father->left;
}
assert(false);
}
static std::string DumpColor(const RbNode *e) {
return (is_nil(e) ? "B" : (e->color == BLACK ? "B" : "R"));
}
static void DumpNode(RbNode *e) {
if (is_nil(e)) {
std::cout << " [nil B] RBNIL[" << DumpColor(&RBNIL) << "]" << std::endl;
} else {
std::cout << " [" << e->value << " " << DumpColor(e) << " left:"
<< (is_nil(e->left) ? "nil" : std::to_string(e->left->value))
<< " right:"
<< (is_nil(e->right) ? "nil" : std::to_string(e->right->value))
<< " father:"
<< (is_nil(e->father) ? "nil" : std::to_string(e->father->value))
<< "] RBNIL[" << DumpColor(&RBNIL) << "]" << std::endl;
if (not_nil(e->left)) {
DumpNode(e->left);
}
if (not_nil(e->right)) {
DumpNode(e->right);
}
}
}
static void DumpTree(RbNode *root, const std::string &msg) {
assert(root);
std::cout << std::endl << std::endl << msg << std::endl;
DumpNode(root);
}
static void DumpTree(RedBlackTree *t, const std::string &msg) {
assert(t);
DumpTree(t->root, msg);
}
static void Free(RbNode *e) {
if (e == NULL || is_nil(e))
return;
Free(e->left);
Free(e->right);
delete e;
}
static RbNode *LeftRotate(RbNode *root, RbNode *e) {
DumpTree(root, "before left rotate e:" + std::to_string(e->value));
RbNode *p = e->right;
e->right = p->left;
if (not_nil(p->left)) {
p->left->father = e;
}
if (not_nil(p)) {
p->father = e->father;
}
if (not_nil(e->father)) {
if (e == e->father->left) {
e->father->left = p;
} else {
e->father->right = p;
}
} else {
root = p;
}
p->left = e;
if (not_nil(e)) {
e->father = p;
}
DumpTree(root, "after left rotate e:" + std::to_string(e->value));
return root;
}
static RbNode *RightRotate(RbNode *root, RbNode *e) {
DumpTree(root, "before right rotate e:" + std::to_string(e->value));
RbNode *p = e->left;
e->left = p->right;
if (not_nil(p->right)) {
p->right->father = e;
}
if (not_nil(p)) {
p->father = e->father;
}
if (not_nil(e->father)) {
if (e == e->father->right) {
e->father->right = p;
} else {
e->father->left = p;
}
} else {
root = p;
}
p->right = e;
if (not_nil(e)) {
e->father = p;
}
DumpTree(root, "after right rotate e:" + std::to_string(e->value));
return root;
}
static RbNode *FixInsert(RbNode *root, RbNode *e) {
assert(RBNIL.color == BLACK);
while ((e != root) && (e->father->color == RED)) {
// case A: e.father is e.grand_father's left child
if (IsLeft(e->father)) {
RbNode *e_uncle = Uncle(e);
// case 1: Red Uncle, e.uncle is red
if (e_uncle->color == RED) {
e->father->color = BLACK;
e_uncle->color = BLACK;
e->father->father->color = RED;
e = e->father->father; // next loop from e.grand_father
} else {
// case 2: Black Uncle, left-right-case
if (IsRight(e)) {
e = e->father;
root = LeftRotate(root, e);
}
// case 3: Black Uncle, left-left-case
e->father->color = BLACK;
e->father->father->color = RED;
root = RightRotate(root, e->father->father);
}
}
// case B: e.father is e.grand_father's right child
else {
RbNode *e_uncle = Uncle(e);
// case 1: Red Uncle
if (e_uncle->color == RED) {
e->father->color = BLACK;
e_uncle->color = BLACK;
e->father->father->color = RED;
e = e->father->father; // next loop from e.grand_father
} else {
// case 4: Black Uncle, left-right-case
if (IsLeft(e)) {
e = e->father;
root = RightRotate(root, e);
}
// case 5: Black Uncle, right-right-case
e->father->color = BLACK;
e->father->father->color = RED;
root = LeftRotate(root, e->father->father);
}
}
} // while
root->color = BLACK;
return root;
}
static RbNode *FixErase(RbNode *root, RbNode *e) {
assert(RBNIL.color == BLACK);
while ((e != root) && (e->color == BLACK)) {
DumpTree(root, "fix erase");
// case A: e is left child
if (IsLeft(e)) {
RbNode *e_brother = Brother(e);
if (e_brother->color == RED) {
e_brother->color = BLACK;
e->father->color = RED;
root = LeftRotate(root, e->father);
e_brother = e->father->right;
}
if (e_brother->left->color == BLACK && e_brother->right->color == BLACK) {
e_brother->color = RED;
e = e->father;
} else {
if (e_brother->right->color == BLACK) {
e_brother->left->color = BLACK;
e_brother->color = RED;
root = RightRotate(root, e_brother);
e_brother = e->father->right;
}
e_brother->color = e->father->color;
e->father->color = BLACK;
e_brother->right->color = BLACK;
root = LeftRotate(root, e->father);
e = root; // break loop
}
}
// case B: e is right child
else {
RbNode *e_brother = Brother(e);
if (e_brother->color == RED) {
e_brother->color = BLACK;
e->father->color = RED;
root = LeftRotate(root, e->father);
e_brother = e->father->left;
}
if (e_brother->right->color == BLACK && e_brother->left->color == BLACK) {
e_brother->color = RED;
e = e->father;
} else {
if (e_brother->left->color == BLACK) {
e_brother->right->color = BLACK;
e_brother->color = RED;
root = LeftRotate(root, e_brother);
e_brother = e->father->left;
}
e_brother->color = e->father->color;
e->father->color = BLACK;
e_brother->left->color = BLACK;
root = RightRotate(root, e->father);
e = root; // break loop
}
}
}
e->color = BLACK;
return root;
}
static RbNode *Erase(RbNode *root, RbNode *e) {
assert(RBNIL.color == BLACK);
RbNode *p, *q;
if (is_nil(e)) {
return root;
}
if (is_nil(e->left) || is_nil(e->right)) {
p = e;
} else {
p = Next(e);
}
if (not_nil(p->left)) {
q = p->left;
} else {
q = p->right;
}
if (not_nil(q)) {
q->father = p->father;
}
if (not_nil(p->father)) {
if (IsLeft(p)) {
p->father->left = q;
} else {
p->father->right = q;
}
} else {
root = q;
}
if (p != e) {
e->value = p->value;
}
if (p->color == BLACK) {
root = FixErase(root, q);
}
delete p;
return root;
}
static RbNode *Find(RbNode *e, int value) {
assert(RBNIL.color == BLACK);
if (is_nil(e)) {
return &RBNIL;
}
//二分查找
if (e->value == value) {
return e;
} else if (e->value > value) {
return Find(e->left, value);
} else {
return Find(e->right, value);
}
}
static RbNode *Insert(RbNode *father, RbNode *e) {
assert(RBNIL.color == BLACK);
assert(e);
if (is_nil(father)) {
return e;
}
//利用二分查找找到适合value插入的位置e
if (father->value > e->value) {
father->left = Insert(father->left, e);
father->left->father = father;
} else if (father->value < e->value) {
father->right = Insert(father->right, e);
father->right->father = father;
} else {
assert(father->value != e->value);
}
return father;
}
RedBlackTree *RedBlackTreeNew() {
RedBlackTree *t = new RedBlackTree();
if (!t)
return NULL;
set_nil(t->root);
return t;
}
void RedBlackTreeFree(RedBlackTree *t) {
assert(t);
Free(t->root);
delete t;
}
void RedBlackTreeInsert(RedBlackTree *t, int value) {
assert(t);
assert(value >= 0);
RbNode *e = new RbNode();
set_nil(e->left);
set_nil(e->right);
set_nil(e->father);
e->color = RED; // new node is red
e->value = value;
t->root = Insert(t->root, e);
t->root = FixInsert(t->root, e);
assert(RBNIL.color == BLACK);
}
RbNode *RedBlackTreeFind(RedBlackTree *t, int value) {
return Find(t->root, value);
}
void RedBlackTreeErase(RedBlackTree *t, int value) {
RbNode *e = Find(t->root, value);
Erase(t, e);
DumpTree(t, "erase");
assert(RBNIL.color == BLACK);
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include "Communicator.h"
#include "Message.h"
#include "GenException.h"
#include <string>
#include <map>
using namespace std;
class TrackerMessage : public Message {
public:
TrackerMessage(MessageDir dir, Communicator* originator) :
Message(dir, originator) { }
vector<string> dest_list_;
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class TestCommunicator : public Communicator {
public:
TestCommunicator(string name) {
msg_ = new TrackerMessage(UP_MSG, this);
name_ = name;
stop_at_return_ = true;
flip_at_receive_ = false;
flip_down_to_up_ = false;
forget_set_dest_ = false;
down_up_count_ = 0;
}
~TestCommunicator() {
delete msg_;
}
Communicator* parent_;
TrackerMessage* msg_;
string name_;
bool stop_at_return_, flip_at_receive_, forget_set_dest_;
bool flip_down_to_up_;
int down_up_count_;
void startMessage() {
msg_->dest_list_.push_back(name_);
msg_->setNextDest(parent_);
msg_->sendOn();
}
private:
void receiveMessage(Message* msg) {
(dynamic_cast<TrackerMessage*>(msg))->dest_list_.push_back(name_);
if (stop_at_return_ && this == msg->getSender()) {
return;
} else if (flip_at_receive_) {
msg->setDir(DOWN_MSG);
} else if (flip_down_to_up_) {
int max_num_flips = 2;
if (msg->getDir() == DOWN_MSG && down_up_count_ < max_num_flips) {
msg->setDir(UP_MSG);
down_up_count_++;
}
}
if ( !forget_set_dest_ ) {
msg->setNextDest(parent_);
}
msg->sendOn();
}
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class MessageTest : public ::testing::Test {
protected:
TestCommunicator* comm1;
TestCommunicator* comm2;
TestCommunicator* comm3;
TestCommunicator* comm4;
virtual void SetUp(){
comm1 = new TestCommunicator("comm1");
comm2 = new TestCommunicator("comm2");
comm3 = new TestCommunicator("comm3");
comm4 = new TestCommunicator("comm4");
comm1->parent_ = comm2;
comm2->parent_ = comm3;
comm3->parent_ = comm4;
comm4->flip_at_receive_ = true;
};
virtual void TearDown() {
delete comm1;
delete comm2;
delete comm3;
delete comm4;
}
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessageTest, CleanThrough) {
bool threw_exception = false;
try {
comm1->startMessage();
} catch (GenException error) {
threw_exception = true;
}
vector<string> stops = comm1->msg_->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 7;
EXPECT_FALSE(threw_exception);
EXPECT_TRUE(num_stops == expected_num_stops);
if (num_stops == expected_num_stops) {
EXPECT_TRUE(stops[0] == "comm1");
EXPECT_TRUE(stops[1] == "comm2");
EXPECT_TRUE(stops[2] == "comm3");
EXPECT_TRUE(stops[3] == "comm4");
EXPECT_TRUE(stops[4] == "comm3");
EXPECT_TRUE(stops[5] == "comm2");
EXPECT_TRUE(stops[6] == "comm1");
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessageTest, PassBeyondOrigin) {
bool threw_exception = false;
comm1->stop_at_return_ = false;
try {
comm1->startMessage();
} catch (GenException error) {
threw_exception = true;
}
vector<string> stops = comm1->msg_->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 7;
EXPECT_TRUE(threw_exception);
EXPECT_TRUE(num_stops == expected_num_stops);
if (num_stops == expected_num_stops) {
EXPECT_TRUE(stops[0] == "comm1");
EXPECT_TRUE(stops[1] == "comm2");
EXPECT_TRUE(stops[2] == "comm3");
EXPECT_TRUE(stops[3] == "comm4");
EXPECT_TRUE(stops[4] == "comm3");
EXPECT_TRUE(stops[5] == "comm2");
EXPECT_TRUE(stops[6] == "comm1");
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessageTest, ForgetToSetDest) {
bool threw_exception = false;
comm3->forget_set_dest_ = true;
try {
comm1->startMessage();
} catch (GenException error) {
threw_exception = true;
}
vector<string> stops = comm1->msg_->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 3;
EXPECT_TRUE(threw_exception);
EXPECT_TRUE(num_stops == expected_num_stops);
if (num_stops == expected_num_stops) {
EXPECT_TRUE(stops[0] == "comm1");
EXPECT_TRUE(stops[1] == "comm2");
EXPECT_TRUE(stops[2] == "comm3");
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessageTest, SendToSelf) {
bool threw_exception = false;
comm3->parent_ = comm3;
try {
comm1->startMessage();
} catch (GenException error) {
threw_exception = true;
}
vector<string> stops = comm1->msg_->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 3;
EXPECT_TRUE(threw_exception);
EXPECT_TRUE(num_stops == expected_num_stops);
if (num_stops == expected_num_stops) {
EXPECT_TRUE(stops[0] == "comm1");
EXPECT_TRUE(stops[1] == "comm2");
EXPECT_TRUE(stops[2] == "comm3");
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessageTest, YoYo) {
bool threw_exception = false;
comm2->flip_down_to_up_ = true;
try {
comm1->startMessage();
} catch (GenException error) {
threw_exception = true;
}
vector<string> stops = comm1->msg_->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 15;
EXPECT_FALSE(threw_exception);
EXPECT_TRUE(num_stops == expected_num_stops);
if (num_stops == expected_num_stops) {
EXPECT_TRUE(stops[0] == "comm1");
EXPECT_TRUE(stops[1] == "comm2");
EXPECT_TRUE(stops[2] == "comm3");
EXPECT_TRUE(stops[3] == "comm4");
EXPECT_TRUE(stops[4] == "comm3");
EXPECT_TRUE(stops[5] == "comm2");
EXPECT_TRUE(stops[6] == "comm3");
EXPECT_TRUE(stops[7] == "comm4");
EXPECT_TRUE(stops[8] == "comm3");
EXPECT_TRUE(stops[9] == "comm2");
EXPECT_TRUE(stops[10] == "comm3");
EXPECT_TRUE(stops[11] == "comm4");
EXPECT_TRUE(stops[12] == "comm3");
EXPECT_TRUE(stops[13] == "comm2");
EXPECT_TRUE(stops[14] == "comm1");
}
}
<commit_msg>improved tests by using more features of googletest (primarily better assertion selection).<commit_after>#include <gtest/gtest.h>
#include "Communicator.h"
#include "Message.h"
#include "GenException.h"
#include <string>
#include <map>
using namespace std;
class TrackerMessage : public Message {
public:
TrackerMessage(MessageDir dir, Communicator* originator) :
Message(dir, originator) { }
vector<string> dest_list_;
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class TestCommunicator : public Communicator {
public:
TestCommunicator(string name) {
msg_ = new TrackerMessage(UP_MSG, this);
name_ = name;
stop_at_return_ = true;
flip_at_receive_ = false;
flip_down_to_up_ = false;
forget_set_dest_ = false;
down_up_count_ = 0;
}
~TestCommunicator() {
delete msg_;
}
Communicator* parent_;
TrackerMessage* msg_;
string name_;
bool stop_at_return_, flip_at_receive_, forget_set_dest_;
bool flip_down_to_up_;
int down_up_count_;
void startMessage() {
msg_->dest_list_.push_back(name_);
msg_->setNextDest(parent_);
msg_->sendOn();
}
private:
void receiveMessage(Message* msg) {
(dynamic_cast<TrackerMessage*>(msg))->dest_list_.push_back(name_);
if (stop_at_return_ && this == msg->getSender()) {
return;
} else if (flip_at_receive_) {
msg->setDir(DOWN_MSG);
} else if (flip_down_to_up_) {
int max_num_flips = 2;
if (msg->getDir() == DOWN_MSG && down_up_count_ < max_num_flips) {
msg->setDir(UP_MSG);
down_up_count_++;
}
}
if ( !forget_set_dest_ ) {
msg->setNextDest(parent_);
}
msg->sendOn();
}
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class MessageTest : public ::testing::Test {
protected:
TestCommunicator* comm1;
TestCommunicator* comm2;
TestCommunicator* comm3;
TestCommunicator* comm4;
virtual void SetUp(){
comm1 = new TestCommunicator("comm1");
comm2 = new TestCommunicator("comm2");
comm3 = new TestCommunicator("comm3");
comm4 = new TestCommunicator("comm4");
comm1->parent_ = comm2;
comm2->parent_ = comm3;
comm3->parent_ = comm4;
comm4->flip_at_receive_ = true;
};
virtual void TearDown() {
delete comm1;
delete comm2;
delete comm3;
delete comm4;
}
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessageTest, CleanThrough) {
ASSERT_NO_THROW(comm1->startMessage());
vector<string> stops = comm1->msg_->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 7;
ASSERT_EQ(num_stops, expected_num_stops);
EXPECT_EQ(stops[0], "comm1");
EXPECT_EQ(stops[1], "comm2");
EXPECT_EQ(stops[2], "comm3");
EXPECT_EQ(stops[3], "comm4");
EXPECT_EQ(stops[4], "comm3");
EXPECT_EQ(stops[5], "comm2");
EXPECT_EQ(stops[6], "comm1");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessageTest, PassBeyondOrigin) {
comm1->stop_at_return_ = false;
ASSERT_THROW(comm1->startMessage(), GenException);
vector<string> stops = comm1->msg_->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 7;
ASSERT_EQ(num_stops, expected_num_stops);
EXPECT_EQ(stops[0], "comm1");
EXPECT_EQ(stops[1], "comm2");
EXPECT_EQ(stops[2], "comm3");
EXPECT_EQ(stops[3], "comm4");
EXPECT_EQ(stops[4], "comm3");
EXPECT_EQ(stops[5], "comm2");
EXPECT_EQ(stops[6], "comm1");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessageTest, ForgetToSetDest) {
comm3->forget_set_dest_ = true;
ASSERT_THROW(comm1->startMessage(), GenException);
vector<string> stops = comm1->msg_->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 3;
ASSERT_EQ(num_stops, expected_num_stops);
EXPECT_EQ(stops[0], "comm1");
EXPECT_EQ(stops[1], "comm2");
EXPECT_EQ(stops[2], "comm3");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessageTest, SendToSelf) {
comm3->parent_ = comm3;
ASSERT_THROW(comm1->startMessage(), GenException);
vector<string> stops = comm1->msg_->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 3;
ASSERT_EQ(num_stops, expected_num_stops);
EXPECT_EQ(stops[0], "comm1");
EXPECT_EQ(stops[1], "comm2");
EXPECT_EQ(stops[2], "comm3");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessageTest, YoYo) {
comm2->flip_down_to_up_ = true;
ASSERT_NO_THROW(comm1->startMessage());
vector<string> stops = comm1->msg_->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 15;
ASSERT_EQ(num_stops, expected_num_stops);
EXPECT_EQ(stops[0], "comm1");
EXPECT_EQ(stops[1], "comm2");
EXPECT_EQ(stops[2], "comm3");
EXPECT_EQ(stops[3], "comm4");
EXPECT_EQ(stops[4], "comm3");
EXPECT_EQ(stops[5], "comm2");
EXPECT_EQ(stops[6], "comm3");
EXPECT_EQ(stops[7], "comm4");
EXPECT_EQ(stops[8], "comm3");
EXPECT_EQ(stops[9], "comm2");
EXPECT_EQ(stops[10], "comm3");
EXPECT_EQ(stops[11], "comm4");
EXPECT_EQ(stops[12], "comm3");
EXPECT_EQ(stops[13], "comm2");
EXPECT_EQ(stops[14], "comm1");
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2015-2016 CNRS
//
// This file is part of Pinocchio
// Pinocchio 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
// 3 of the License, or (at your option) any later version.
//
// Pinocchio is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.
#ifndef __se3_kinematics_hpp__
#define __se3_kinematics_hpp__
#include "pinocchio/multibody/model.hpp"
namespace se3
{
///
/// \brief Browse through the model tree structure with an empty step
///
/// \param[in] model The model structure of the rigid body system.
/// \param[in] data The data structure of the rigid body system.
///
inline void emptyForwardPass(const Model & model,
Data & data);
inline void forwardKinematics(const Model & model,
Data & data,
const Eigen::VectorXd & q);
inline void forwardKinematics(const Model & model,
Data & data,
const Eigen::VectorXd & q,
const Eigen::VectorXd & v);
inline void forwardKinematics(const Model & model,
Data & data,
const Eigen::VectorXd & q,
const Eigen::VectorXd & v,
const Eigen::VectorXd & a);
} // namespace se3
/* --- Details -------------------------------------------------------------------- */
/* --- Details -------------------------------------------------------------------- */
/* --- Details -------------------------------------------------------------------- */
#include "pinocchio/algorithm/kinematics.hxx"
#endif // ifndef __se3_kinematics_hpp__
<commit_msg>[Doc] Specify documentation for kinematics algo<commit_after>//
// Copyright (c) 2015-2016 CNRS
//
// This file is part of Pinocchio
// Pinocchio 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
// 3 of the License, or (at your option) any later version.
//
// Pinocchio is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.
#ifndef __se3_kinematics_hpp__
#define __se3_kinematics_hpp__
#include "pinocchio/multibody/model.hpp"
namespace se3
{
///
/// \brief Browse through the kinematic structure with a void step.
///
/// \note This void step allows to quantify the time spent in the rollout.
///
/// \param[in] model The model structure of the rigid body system.
/// \param[in] data The data structure of the rigid body system.
///
inline void emptyForwardPass(const Model & model,
Data & data);
///
/// \brief Update the joint placement according to the current joint configuration.
///
/// \param[in] model The model structure of the rigid body system.
/// \param[in] data The data structure of the rigid body system.
/// \param[in] q The joint configuration (vector dim model.nq).
///
inline void forwardKinematics(const Model & model,
Data & data,
const Eigen::VectorXd & q);
///
/// \brief Update the joint placement according to the current joint configuration and velocity.
///
/// \param[in] model The model structure of the rigid body system.
/// \param[in] data The data structure of the rigid body system.
/// \param[in] q The joint configuration (vector dim model.nq).
/// \param[in] v The joint velocity (vector dim model.nv).
///
inline void forwardKinematics(const Model & model,
Data & data,
const Eigen::VectorXd & q,
const Eigen::VectorXd & v);
///
/// \brief Update the joint placement according to the current joint configuration, velocity and acceleration.
///
/// \param[in] model The model structure of the rigid body system.
/// \param[in] data The data structure of the rigid body system.
/// \param[in] q The joint configuration (vector dim model.nq).
/// \param[in] v The joint velocity (vector dim model.nv).
/// \param[in] a The joint acceleration (vector dim model.nv).
///
inline void forwardKinematics(const Model & model,
Data & data,
const Eigen::VectorXd & q,
const Eigen::VectorXd & v,
const Eigen::VectorXd & a);
} // namespace se3
/* --- Details -------------------------------------------------------------------- */
/* --- Details -------------------------------------------------------------------- */
/* --- Details -------------------------------------------------------------------- */
#include "pinocchio/algorithm/kinematics.hxx"
#endif // ifndef __se3_kinematics_hpp__
<|endoftext|> |
<commit_before>// 8 april 2015
#include "uipriv_windows.hpp"
struct uiEntry {
uiWindowsControl c;
HWND hwnd;
void (*onChanged)(uiEntry *, void *);
void *onChangedData;
BOOL inhibitChanged;
};
static BOOL onWM_COMMAND(uiControl *c, HWND hwnd, WORD code, LRESULT *lResult)
{
uiEntry *e = uiEntry(c);
if (code != EN_CHANGE)
return FALSE;
if (e->inhibitChanged)
return FALSE;
(*(e->onChanged))(e, e->onChangedData);
*lResult = 0;
return TRUE;
}
static void uiEntryDestroy(uiControl *c)
{
uiEntry *e = uiEntry(c);
uiWindowsUnregisterWM_COMMANDHandler(e->hwnd);
uiWindowsEnsureDestroyWindow(e->hwnd);
uiFreeControl(uiControl(e));
}
uiWindowsControlAllDefaultsExceptDestroy(uiEntry)
// from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing
#define entryWidth 107 /* this is actually the shorter progress bar width, but Microsoft only indicates as wide as necessary */
#define entryHeight 14
static void uiEntryMinimumSize(uiWindowsControl *c, intmax_t *width, intmax_t *height)
{
uiEntry *e = uiEntry(c);
uiWindowsSizing sizing;
int x, y;
x = entryWidth;
y = entryHeight;
uiWindowsGetSizing(e->hwnd, &sizing);
uiWindowsSizingDlgUnitsToPixels(&sizing, &x, &y);
*width = x;
*height = y;
}
static void defaultOnChanged(uiEntry *e, void *data)
{
// do nothing
}
char *uiEntryText(uiEntry *e)
{
return uiWindowsWindowText(e->hwnd);
}
void uiEntrySetText(uiEntry *e, const char *text)
{
// doing this raises an EN_CHANGED
e->inhibitChanged = TRUE;
uiWindowsSetWindowText(e->hwnd, text);
e->inhibitChanged = FALSE;
// don't queue the control for resize; entry sizes are independent of their contents
}
void uiEntryOnChanged(uiEntry *e, void (*f)(uiEntry *, void *), void *data)
{
e->onChanged = f;
e->onChangedData = data;
}
int uiEntryReadOnly(uiEntry *e)
{
return (getStyle(e->hwnd) & ES_READONLY) != 0;
}
void uiEntrySetReadOnly(uiEntry *e, int readonly)
{
WPARAM ro;
ro = (WPARAM) FALSE;
if (readonly)
ro = (WPARAM) TRUE;
if (SendMessage(e->hwnd, EM_SETREADONLY, ro, 0) == 0)
logLastError(L"error making uiEntry read-only");
}
static uiEntry *finishNewEntry(DWORD style)
{
uiEntry *e;
uiWindowsNewControl(uiEntry, e);
e->hwnd = uiWindowsEnsureCreateControlHWND(WS_EX_CLIENTEDGE,
L"edit", L"",
style | ES_AUTOHSCROLL | ES_LEFT | ES_NOHIDESEL | WS_TABSTOP,
hInstance, NULL,
TRUE);
uiWindowsRegisterWM_COMMANDHandler(e->hwnd, onWM_COMMAND, uiControl(e));
uiEntryOnChanged(e, defaultOnChanged, NULL);
return e;
}
uiEntry *uiNewEntry(void)
{
return finishNewEntry(0);
}
uiEntry *uiNewPasswordEntry(void)
{
return finishNewEntry(ES_PASSWORD);
}
uiEntry *uiNewSearchEntry(void)
{
// TODO
return finishNewEntry(0);
}
<commit_msg>Improved the appearance of uiSearchEntry on Windows somewhat.<commit_after>// 8 april 2015
#include "uipriv_windows.hpp"
struct uiEntry {
uiWindowsControl c;
HWND hwnd;
void (*onChanged)(uiEntry *, void *);
void *onChangedData;
BOOL inhibitChanged;
};
static BOOL onWM_COMMAND(uiControl *c, HWND hwnd, WORD code, LRESULT *lResult)
{
uiEntry *e = uiEntry(c);
if (code != EN_CHANGE)
return FALSE;
if (e->inhibitChanged)
return FALSE;
(*(e->onChanged))(e, e->onChangedData);
*lResult = 0;
return TRUE;
}
static void uiEntryDestroy(uiControl *c)
{
uiEntry *e = uiEntry(c);
uiWindowsUnregisterWM_COMMANDHandler(e->hwnd);
uiWindowsEnsureDestroyWindow(e->hwnd);
uiFreeControl(uiControl(e));
}
uiWindowsControlAllDefaultsExceptDestroy(uiEntry)
// from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing
#define entryWidth 107 /* this is actually the shorter progress bar width, but Microsoft only indicates as wide as necessary */
#define entryHeight 14
static void uiEntryMinimumSize(uiWindowsControl *c, intmax_t *width, intmax_t *height)
{
uiEntry *e = uiEntry(c);
uiWindowsSizing sizing;
int x, y;
x = entryWidth;
y = entryHeight;
uiWindowsGetSizing(e->hwnd, &sizing);
uiWindowsSizingDlgUnitsToPixels(&sizing, &x, &y);
*width = x;
*height = y;
}
static void defaultOnChanged(uiEntry *e, void *data)
{
// do nothing
}
char *uiEntryText(uiEntry *e)
{
return uiWindowsWindowText(e->hwnd);
}
void uiEntrySetText(uiEntry *e, const char *text)
{
// doing this raises an EN_CHANGED
e->inhibitChanged = TRUE;
uiWindowsSetWindowText(e->hwnd, text);
e->inhibitChanged = FALSE;
// don't queue the control for resize; entry sizes are independent of their contents
}
void uiEntryOnChanged(uiEntry *e, void (*f)(uiEntry *, void *), void *data)
{
e->onChanged = f;
e->onChangedData = data;
}
int uiEntryReadOnly(uiEntry *e)
{
return (getStyle(e->hwnd) & ES_READONLY) != 0;
}
void uiEntrySetReadOnly(uiEntry *e, int readonly)
{
WPARAM ro;
ro = (WPARAM) FALSE;
if (readonly)
ro = (WPARAM) TRUE;
if (SendMessage(e->hwnd, EM_SETREADONLY, ro, 0) == 0)
logLastError(L"error making uiEntry read-only");
}
static uiEntry *finishNewEntry(DWORD style)
{
uiEntry *e;
uiWindowsNewControl(uiEntry, e);
e->hwnd = uiWindowsEnsureCreateControlHWND(WS_EX_CLIENTEDGE,
L"edit", L"",
style | ES_AUTOHSCROLL | ES_LEFT | ES_NOHIDESEL | WS_TABSTOP,
hInstance, NULL,
TRUE);
uiWindowsRegisterWM_COMMANDHandler(e->hwnd, onWM_COMMAND, uiControl(e));
uiEntryOnChanged(e, defaultOnChanged, NULL);
return e;
}
uiEntry *uiNewEntry(void)
{
return finishNewEntry(0);
}
uiEntry *uiNewPasswordEntry(void)
{
return finishNewEntry(ES_PASSWORD);
}
uiEntry *uiNewSearchEntry(void)
{
uiEntry *e;
HRESULT hr;
e = finishNewEntry(0);
// TODO this is from ThemeExplorer; is it documented anywhere?
// TODO SearchBoxEditComposited has no border
hr = SetWindowTheme(e->hwnd, L"SearchBoxEdit", NULL);
// TODO will hr be S_OK if themes are disabled?
return e;
}
<|endoftext|> |
<commit_before>/*
* settings_container.hpp
*
* Created on: Mar 31, 2016
* Author: jschwan
*/
#ifndef SRC_UTIL_SETTINGS_CONTAINER_HPP_
#define SRC_UTIL_SETTINGS_CONTAINER_HPP_
#include <flexcore/utils/generic_container.hpp>
#include <flexcore/utils/settings/settings.hpp>
namespace fc
{
/**
* \brief Container Handling Ownership of Settings.
*
* Allows adding new settings which are then connected to backend.
* Has non-owning reference to settingsbackend.
*/
template <class backend_t>
class settings_container
{
public:
explicit settings_container(backend_t& backend) :
backend_access(backend)
{
}
template <class data_t>
fc::setting<data_t>& add(setting_id name, data_t init_value)
{
return container.add<fc::setting<data_t>>(
std::move(name),
backend_access,
std::move(init_value));
}
private:
generic_container container;
backend_t& backend_access;
};
}
#endif /* SRC_UTIL_SETTINGS_CONTAINER_HPP_ */
<commit_msg>settings_container add can now be called with constraint<commit_after>/*
* settings_container.hpp
*
* Created on: Mar 31, 2016
* Author: jschwan
*/
#ifndef SRC_UTIL_SETTINGS_CONTAINER_HPP_
#define SRC_UTIL_SETTINGS_CONTAINER_HPP_
#include <flexcore/utils/generic_container.hpp>
#include <flexcore/utils/settings/settings.hpp>
namespace fc
{
/**
* \brief Container Handling Ownership of Settings.
*
* Allows adding new settings which are then connected to backend.
* Has non-owning reference to settingsbackend.
*/
template <class backend_t>
class settings_container
{
public:
explicit settings_container(backend_t& backend) :
backend_access(backend)
{
}
template <class data_t>
fc::setting<data_t>& add(setting_id name, data_t init_value)
{
return container.add<fc::setting<data_t>>(
std::move(name),
backend_access,
std::move(init_value));
}
template <class data_t, class constraint_t>
fc::setting<data_t>& add(setting_id name, data_t init_value, constraint_t constr)
{
return container.add<fc::setting<data_t>>(
std::move(name),
backend_access,
std::move(init_value),
std::move(constr));
}
private:
generic_container container;
backend_t& backend_access;
};
}
#endif /* SRC_UTIL_SETTINGS_CONTAINER_HPP_ */
<|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: registerservices.cxx,v $
* $Revision: 1.42 $
*
* 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_framework.hxx"
//_________________________________________________________________________________________________________________
// includes of my own project
//_________________________________________________________________________________________________________________
#include <macros/registration.hxx>
/*=================================================================================================================
Add new include and new register info to for new services.
Example:
#ifndef __YOUR_SERVICE_1_HXX_
#include <service1.hxx>
#endif
#ifndef __YOUR_SERVICE_2_HXX_
#include <service2.hxx>
#endif
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( Service1 )
COMPONENTINFO( Service2 )
)
COMPONENTGETFACTORY ( IFFACTORIE( Service1 )
else
IFFACTORIE( Service2 )
)
=================================================================================================================*/
#include <services/urltransformer.hxx>
#include <services/desktop.hxx>
#include <services/frame.hxx>
#include <services/modulemanager.hxx>
#include <jobs/jobexecutor.hxx>
#include <recording/dispatchrecordersupplier.hxx>
#include <recording/dispatchrecorder.hxx>
#include <dispatch/mailtodispatcher.hxx>
#include <dispatch/servicehandler.hxx>
#include <jobs/jobdispatch.hxx>
#include <services/backingcomp.hxx>
#include <services/dispatchhelper.hxx>
#include <services/layoutmanager.hxx>
#include <services/license.hxx>
#include <uifactory/uielementfactorymanager.hxx>
#include <uifactory/popupmenucontrollerfactory.hxx>
#include <uielement/fontmenucontroller.hxx>
#include <uielement/fontsizemenucontroller.hxx>
#include <uielement/objectmenucontroller.hxx>
#include <uielement/headermenucontroller.hxx>
#include <uielement/footermenucontroller.hxx>
#include <uielement/controlmenucontroller.hxx>
#include <uielement/macrosmenucontroller.hxx>
#ifndef __FRAMEWORK_UIELEMENT_UICOMMANDDESCRIPTION_HXX_
#include <uielement/uicommanddescription.hxx>
#endif
#include <uiconfiguration/uiconfigurationmanager.hxx>
#include <uiconfiguration/moduleuicfgsupplier.hxx>
#include <uiconfiguration/moduleuiconfigurationmanager.hxx>
#include <uifactory/menubarfactory.hxx>
#include <accelerators/globalacceleratorconfiguration.hxx>
#include <accelerators/moduleacceleratorconfiguration.hxx>
#include <accelerators/documentacceleratorconfiguration.hxx>
#include <uifactory/toolboxfactory.hxx>
#include <uifactory/addonstoolboxfactory.hxx>
#include "uiconfiguration/windowstateconfiguration.hxx"
#include <uielement/toolbarsmenucontroller.hxx>
#include "uifactory/toolbarcontrollerfactory.hxx"
#include "uifactory/statusbarcontrollerfactory.hxx"
#include <uielement/toolbarsmenucontroller.hxx>
#include <services/autorecovery.hxx>
#include <helper/statusindicatorfactory.hxx>
#include <uielement/recentfilesmenucontroller.hxx>
#include <uifactory/statusbarfactory.hxx>
#ifndef __FRAMEWORK_UIELEMENT_UICATEGORYDESCRPTION_HXX_
#include <uiconfiguration/uicategorydescription.hxx>
#endif
#include <services/sessionlistener.hxx>
#include <uielement/logoimagestatusbarcontroller.hxx>
#include <uielement/logotextstatusbarcontroller.hxx>
#include <uielement/newmenucontroller.hxx>
#include <services/taskcreatorsrv.hxx>
#include <uielement/simpletextstatusbarcontroller.hxx>
#include <services/uriabbreviation.hxx>
#include <dispatch/popupmenudispatcher.hxx>
#include <uielement/langselectionstatusbarcontroller.hxx>
#include <uielement/langselectionmenucontroller.hxx>
#include <uiconfiguration/imagemanager.hxx>
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( ::framework::URLTransformer )
COMPONENTINFO( ::framework::Desktop )
COMPONENTINFO( ::framework::Frame )
COMPONENTINFO( ::framework::JobExecutor )
COMPONENTINFO( ::framework::DispatchRecorderSupplier )
COMPONENTINFO( ::framework::DispatchRecorder )
COMPONENTINFO( ::framework::MailToDispatcher )
COMPONENTINFO( ::framework::ServiceHandler )
COMPONENTINFO( ::framework::JobDispatch )
COMPONENTINFO( ::framework::BackingComp )
COMPONENTINFO( ::framework::DispatchHelper )
COMPONENTINFO( ::framework::LayoutManager )
COMPONENTINFO( ::framework::License )
COMPONENTINFO( ::framework::UIElementFactoryManager )
COMPONENTINFO( ::framework::PopupMenuControllerFactory )
COMPONENTINFO( ::framework::FontMenuController )
COMPONENTINFO( ::framework::FontSizeMenuController )
COMPONENTINFO( ::framework::ObjectMenuController )
COMPONENTINFO( ::framework::HeaderMenuController )
COMPONENTINFO( ::framework::FooterMenuController )
COMPONENTINFO( ::framework::ControlMenuController )
COMPONENTINFO( ::framework::MacrosMenuController )
COMPONENTINFO( ::framework::UICommandDescription )
COMPONENTINFO( ::framework::ModuleManager )
COMPONENTINFO( ::framework::UIConfigurationManager )
COMPONENTINFO( ::framework::ModuleUIConfigurationManagerSupplier )
COMPONENTINFO( ::framework::ModuleUIConfigurationManager )
COMPONENTINFO( ::framework::MenuBarFactory )
COMPONENTINFO( ::framework::GlobalAcceleratorConfiguration )
COMPONENTINFO( ::framework::ModuleAcceleratorConfiguration )
COMPONENTINFO( ::framework::DocumentAcceleratorConfiguration )
COMPONENTINFO( ::framework::ToolBoxFactory )
COMPONENTINFO( ::framework::AddonsToolBoxFactory )
COMPONENTINFO( ::framework::WindowStateConfiguration )
COMPONENTINFO( ::framework::ToolbarControllerFactory )
COMPONENTINFO( ::framework::ToolbarsMenuController )
COMPONENTINFO( ::framework::AutoRecovery )
COMPONENTINFO( ::framework::StatusIndicatorFactory )
COMPONENTINFO( ::framework::RecentFilesMenuController )
COMPONENTINFO( ::framework::StatusBarFactory )
COMPONENTINFO( ::framework::UICategoryDescription )
COMPONENTINFO( ::framework::StatusbarControllerFactory )
COMPONENTINFO( ::framework::SessionListener )
COMPONENTINFO( ::framework::LogoImageStatusbarController )
COMPONENTINFO( ::framework::LogoTextStatusbarController )
COMPONENTINFO( ::framework::NewMenuController )
COMPONENTINFO( ::framework::TaskCreatorService )
COMPONENTINFO( ::framework::SimpleTextStatusbarController )
COMPONENTINFO( ::framework::UriAbbreviation )
COMPONENTINFO( ::framework::PopupMenuDispatcher )
COMPONENTINFO( ::framework::ImageManager )
COMPONENTINFO( ::framework::LangSelectionStatusbarController )
COMPONENTINFO( ::framework::LanguageSelectionMenuController )
)
COMPONENTGETFACTORY ( IFFACTORY( ::framework::URLTransformer ) else
IFFACTORY( ::framework::Desktop ) else
IFFACTORY( ::framework::Frame ) else
IFFACTORY( ::framework::JobExecutor ) else
IFFACTORY( ::framework::DispatchRecorderSupplier ) else
IFFACTORY( ::framework::DispatchRecorder ) else
IFFACTORY( ::framework::MailToDispatcher ) else
IFFACTORY( ::framework::ServiceHandler ) else
IFFACTORY( ::framework::JobDispatch ) else
IFFACTORY( ::framework::BackingComp ) else
IFFACTORY( ::framework::DispatchHelper ) else
IFFACTORY( ::framework::LayoutManager ) else
IFFACTORY( ::framework::License ) else
IFFACTORY( ::framework::UIElementFactoryManager ) else
IFFACTORY( ::framework::PopupMenuControllerFactory ) else
IFFACTORY( ::framework::FontMenuController ) else
IFFACTORY( ::framework::FontSizeMenuController ) else
IFFACTORY( ::framework::ObjectMenuController ) else
IFFACTORY( ::framework::HeaderMenuController ) else
IFFACTORY( ::framework::FooterMenuController ) else
IFFACTORY( ::framework::ControlMenuController ) else
IFFACTORY( ::framework::MacrosMenuController ) else
IFFACTORY( ::framework::UICommandDescription ) else
IFFACTORY( ::framework::ModuleManager ) else
IFFACTORY( ::framework::UIConfigurationManager ) else
IFFACTORY( ::framework::ModuleUIConfigurationManagerSupplier ) else
IFFACTORY( ::framework::ModuleUIConfigurationManager ) else
IFFACTORY( ::framework::MenuBarFactory ) else
IFFACTORY( ::framework::GlobalAcceleratorConfiguration ) else
IFFACTORY( ::framework::ModuleAcceleratorConfiguration ) else
IFFACTORY( ::framework::DocumentAcceleratorConfiguration ) else
IFFACTORY( ::framework::ToolBoxFactory ) else
IFFACTORY( ::framework::AddonsToolBoxFactory ) else
IFFACTORY( ::framework::WindowStateConfiguration ) else
IFFACTORY( ::framework::ToolbarControllerFactory ) else
IFFACTORY( ::framework::ToolbarsMenuController ) else
IFFACTORY( ::framework::AutoRecovery ) else
IFFACTORY( ::framework::StatusIndicatorFactory ) else
IFFACTORY( ::framework::RecentFilesMenuController ) else
IFFACTORY( ::framework::StatusBarFactory ) else
IFFACTORY( ::framework::UICategoryDescription ) else
IFFACTORY( ::framework::SessionListener ) else
IFFACTORY( ::framework::StatusbarControllerFactory ) else
IFFACTORY( ::framework::SessionListener ) else
IFFACTORY( ::framework::LogoImageStatusbarController ) else
IFFACTORY( ::framework::LogoTextStatusbarController ) else
IFFACTORY( ::framework::TaskCreatorService ) else
IFFACTORY( ::framework::NewMenuController ) else
IFFACTORY( ::framework::SimpleTextStatusbarController ) else
IFFACTORY( ::framework::UriAbbreviation ) else
IFFACTORY( ::framework::PopupMenuDispatcher ) else
IFFACTORY( ::framework::ImageManager )
IFFACTORY( ::framework::PopupMenuDispatcher ) else
IFFACTORY( ::framework::LangSelectionStatusbarController ) else
IFFACTORY( ::framework::LanguageSelectionMenuController )
)
<commit_msg>INTEGRATION: CWS oxtsysint01 (1.41.24); FILE MERGED 2008/04/15 13:26:34 dv 1.41.24.2: RESYNC: (1.41-1.42); FILE MERGED 2008/04/10 09:41:20 dv 1.41.24.1: #i85856# Office should handle '.oxt' files<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: registerservices.cxx,v $
* $Revision: 1.43 $
*
* 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_framework.hxx"
//_________________________________________________________________________________________________________________
// includes of my own project
//_________________________________________________________________________________________________________________
#include <macros/registration.hxx>
/*=================================================================================================================
Add new include and new register info to for new services.
Example:
#ifndef __YOUR_SERVICE_1_HXX_
#include <service1.hxx>
#endif
#ifndef __YOUR_SERVICE_2_HXX_
#include <service2.hxx>
#endif
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( Service1 )
COMPONENTINFO( Service2 )
)
COMPONENTGETFACTORY ( IFFACTORIE( Service1 )
else
IFFACTORIE( Service2 )
)
=================================================================================================================*/
#include <services/urltransformer.hxx>
#include <services/desktop.hxx>
#include <services/frame.hxx>
#include <services/modulemanager.hxx>
#include <dispatch/oxt_handler.hxx>
#include <jobs/jobexecutor.hxx>
#include <recording/dispatchrecordersupplier.hxx>
#include <recording/dispatchrecorder.hxx>
#include <dispatch/mailtodispatcher.hxx>
#include <dispatch/servicehandler.hxx>
#include <jobs/jobdispatch.hxx>
#include <services/backingcomp.hxx>
#include <services/dispatchhelper.hxx>
#include <services/layoutmanager.hxx>
#include <services/license.hxx>
#include <uifactory/uielementfactorymanager.hxx>
#include <uifactory/popupmenucontrollerfactory.hxx>
#include <uielement/fontmenucontroller.hxx>
#include <uielement/fontsizemenucontroller.hxx>
#include <uielement/objectmenucontroller.hxx>
#include <uielement/headermenucontroller.hxx>
#include <uielement/footermenucontroller.hxx>
#include <uielement/controlmenucontroller.hxx>
#include <uielement/macrosmenucontroller.hxx>
#ifndef __FRAMEWORK_UIELEMENT_UICOMMANDDESCRIPTION_HXX_
#include <uielement/uicommanddescription.hxx>
#endif
#include <uiconfiguration/uiconfigurationmanager.hxx>
#include <uiconfiguration/moduleuicfgsupplier.hxx>
#include <uiconfiguration/moduleuiconfigurationmanager.hxx>
#include <uifactory/menubarfactory.hxx>
#include <accelerators/globalacceleratorconfiguration.hxx>
#include <accelerators/moduleacceleratorconfiguration.hxx>
#include <accelerators/documentacceleratorconfiguration.hxx>
#include <uifactory/toolboxfactory.hxx>
#include <uifactory/addonstoolboxfactory.hxx>
#include "uiconfiguration/windowstateconfiguration.hxx"
#include <uielement/toolbarsmenucontroller.hxx>
#include "uifactory/toolbarcontrollerfactory.hxx"
#include "uifactory/statusbarcontrollerfactory.hxx"
#include <uielement/toolbarsmenucontroller.hxx>
#include <services/autorecovery.hxx>
#include <helper/statusindicatorfactory.hxx>
#include <uielement/recentfilesmenucontroller.hxx>
#include <uifactory/statusbarfactory.hxx>
#ifndef __FRAMEWORK_UIELEMENT_UICATEGORYDESCRPTION_HXX_
#include <uiconfiguration/uicategorydescription.hxx>
#endif
#include <services/sessionlistener.hxx>
#include <uielement/logoimagestatusbarcontroller.hxx>
#include <uielement/logotextstatusbarcontroller.hxx>
#include <uielement/newmenucontroller.hxx>
#include <services/taskcreatorsrv.hxx>
#include <uielement/simpletextstatusbarcontroller.hxx>
#include <services/uriabbreviation.hxx>
#include <dispatch/popupmenudispatcher.hxx>
#include <uielement/langselectionstatusbarcontroller.hxx>
#include <uielement/langselectionmenucontroller.hxx>
#include <uiconfiguration/imagemanager.hxx>
COMPONENTGETIMPLEMENTATIONENVIRONMENT
COMPONENTWRITEINFO ( COMPONENTINFO( ::framework::URLTransformer )
COMPONENTINFO( ::framework::Desktop )
COMPONENTINFO( ::framework::Frame )
COMPONENTINFO( ::framework::Oxt_Handler )
COMPONENTINFO( ::framework::JobExecutor )
COMPONENTINFO( ::framework::DispatchRecorderSupplier )
COMPONENTINFO( ::framework::DispatchRecorder )
COMPONENTINFO( ::framework::MailToDispatcher )
COMPONENTINFO( ::framework::ServiceHandler )
COMPONENTINFO( ::framework::JobDispatch )
COMPONENTINFO( ::framework::BackingComp )
COMPONENTINFO( ::framework::DispatchHelper )
COMPONENTINFO( ::framework::LayoutManager )
COMPONENTINFO( ::framework::License )
COMPONENTINFO( ::framework::UIElementFactoryManager )
COMPONENTINFO( ::framework::PopupMenuControllerFactory )
COMPONENTINFO( ::framework::FontMenuController )
COMPONENTINFO( ::framework::FontSizeMenuController )
COMPONENTINFO( ::framework::ObjectMenuController )
COMPONENTINFO( ::framework::HeaderMenuController )
COMPONENTINFO( ::framework::FooterMenuController )
COMPONENTINFO( ::framework::ControlMenuController )
COMPONENTINFO( ::framework::MacrosMenuController )
COMPONENTINFO( ::framework::UICommandDescription )
COMPONENTINFO( ::framework::ModuleManager )
COMPONENTINFO( ::framework::UIConfigurationManager )
COMPONENTINFO( ::framework::ModuleUIConfigurationManagerSupplier )
COMPONENTINFO( ::framework::ModuleUIConfigurationManager )
COMPONENTINFO( ::framework::MenuBarFactory )
COMPONENTINFO( ::framework::GlobalAcceleratorConfiguration )
COMPONENTINFO( ::framework::ModuleAcceleratorConfiguration )
COMPONENTINFO( ::framework::DocumentAcceleratorConfiguration )
COMPONENTINFO( ::framework::ToolBoxFactory )
COMPONENTINFO( ::framework::AddonsToolBoxFactory )
COMPONENTINFO( ::framework::WindowStateConfiguration )
COMPONENTINFO( ::framework::ToolbarControllerFactory )
COMPONENTINFO( ::framework::ToolbarsMenuController )
COMPONENTINFO( ::framework::AutoRecovery )
COMPONENTINFO( ::framework::StatusIndicatorFactory )
COMPONENTINFO( ::framework::RecentFilesMenuController )
COMPONENTINFO( ::framework::StatusBarFactory )
COMPONENTINFO( ::framework::UICategoryDescription )
COMPONENTINFO( ::framework::StatusbarControllerFactory )
COMPONENTINFO( ::framework::SessionListener )
COMPONENTINFO( ::framework::LogoImageStatusbarController )
COMPONENTINFO( ::framework::LogoTextStatusbarController )
COMPONENTINFO( ::framework::NewMenuController )
COMPONENTINFO( ::framework::TaskCreatorService )
COMPONENTINFO( ::framework::SimpleTextStatusbarController )
COMPONENTINFO( ::framework::UriAbbreviation )
COMPONENTINFO( ::framework::PopupMenuDispatcher )
COMPONENTINFO( ::framework::ImageManager )
COMPONENTINFO( ::framework::LangSelectionStatusbarController )
COMPONENTINFO( ::framework::LanguageSelectionMenuController )
)
COMPONENTGETFACTORY ( IFFACTORY( ::framework::URLTransformer ) else
IFFACTORY( ::framework::Desktop ) else
IFFACTORY( ::framework::Frame ) else
IFFACTORY( ::framework::Oxt_Handler ) else
IFFACTORY( ::framework::JobExecutor ) else
IFFACTORY( ::framework::DispatchRecorderSupplier ) else
IFFACTORY( ::framework::DispatchRecorder ) else
IFFACTORY( ::framework::MailToDispatcher ) else
IFFACTORY( ::framework::ServiceHandler ) else
IFFACTORY( ::framework::JobDispatch ) else
IFFACTORY( ::framework::BackingComp ) else
IFFACTORY( ::framework::DispatchHelper ) else
IFFACTORY( ::framework::LayoutManager ) else
IFFACTORY( ::framework::License ) else
IFFACTORY( ::framework::UIElementFactoryManager ) else
IFFACTORY( ::framework::PopupMenuControllerFactory ) else
IFFACTORY( ::framework::FontMenuController ) else
IFFACTORY( ::framework::FontSizeMenuController ) else
IFFACTORY( ::framework::ObjectMenuController ) else
IFFACTORY( ::framework::HeaderMenuController ) else
IFFACTORY( ::framework::FooterMenuController ) else
IFFACTORY( ::framework::ControlMenuController ) else
IFFACTORY( ::framework::MacrosMenuController ) else
IFFACTORY( ::framework::UICommandDescription ) else
IFFACTORY( ::framework::ModuleManager ) else
IFFACTORY( ::framework::UIConfigurationManager ) else
IFFACTORY( ::framework::ModuleUIConfigurationManagerSupplier ) else
IFFACTORY( ::framework::ModuleUIConfigurationManager ) else
IFFACTORY( ::framework::MenuBarFactory ) else
IFFACTORY( ::framework::GlobalAcceleratorConfiguration ) else
IFFACTORY( ::framework::ModuleAcceleratorConfiguration ) else
IFFACTORY( ::framework::DocumentAcceleratorConfiguration ) else
IFFACTORY( ::framework::ToolBoxFactory ) else
IFFACTORY( ::framework::AddonsToolBoxFactory ) else
IFFACTORY( ::framework::WindowStateConfiguration ) else
IFFACTORY( ::framework::ToolbarControllerFactory ) else
IFFACTORY( ::framework::ToolbarsMenuController ) else
IFFACTORY( ::framework::AutoRecovery ) else
IFFACTORY( ::framework::StatusIndicatorFactory ) else
IFFACTORY( ::framework::RecentFilesMenuController ) else
IFFACTORY( ::framework::StatusBarFactory ) else
IFFACTORY( ::framework::UICategoryDescription ) else
IFFACTORY( ::framework::SessionListener ) else
IFFACTORY( ::framework::StatusbarControllerFactory ) else
IFFACTORY( ::framework::SessionListener ) else
IFFACTORY( ::framework::LogoImageStatusbarController ) else
IFFACTORY( ::framework::LogoTextStatusbarController ) else
IFFACTORY( ::framework::TaskCreatorService ) else
IFFACTORY( ::framework::NewMenuController ) else
IFFACTORY( ::framework::SimpleTextStatusbarController ) else
IFFACTORY( ::framework::UriAbbreviation ) else
IFFACTORY( ::framework::PopupMenuDispatcher ) else
IFFACTORY( ::framework::ImageManager ) else
IFFACTORY( ::framework::PopupMenuDispatcher ) else
IFFACTORY( ::framework::LangSelectionStatusbarController ) else
IFFACTORY( ::framework::LanguageSelectionMenuController )
)
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkImageFileWriter.h"
#include "itkImageFileReader.h"
#include "itkVTKImageIO.h"
#include "itkGenerateImageSource.h"
#include <fstream>
#include <iostream>
#include <algorithm>
namespace itk
{
/** \class ConstantImageSource
* Image Source that generates an image with constant pixel value.
*/
template< class TOutputImage >
class ConstantImageSource:public GenerateImageSource< TOutputImage >
{
public:
/** Standard class typedefs. */
typedef ConstantImageSource Self;
typedef ConstantImageSource< TOutputImage > Superclass;
typedef SmartPointer< Self > Pointer;
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Run-time type information (and related methods). */
itkTypeMacro(ConstantImageSource, GenerateImageSource);
/** Set the value to fill the image. */
itkSetMacro(Value, typename TOutputImage::PixelType);
protected:
ConstantImageSource(){}
~ConstantImageSource(){}
/** Does the real work. */
virtual void GenerateData();
private:
ConstantImageSource(const Self &); //purposely not implemented
void operator=(const Self &); //purposely not implemented
typename TOutputImage::PixelType m_Value;
};
template< class TOutputImage >
void ConstantImageSource< TOutputImage >
::GenerateData()
{
TOutputImage* out = this->GetOutput();
out->SetBufferedRegion(out->GetRequestedRegion());
out->Allocate();
out->FillBuffer( m_Value );
}
}// end namespace
/**
* Compares two image regions.
* Assumes that the region is valid and buffered in both images.
*/
template<class TImage>
bool ImagesEqual(const TImage* img1, const TImage* img2,
const typename TImage::RegionType& region)
{
if( !img1->GetBufferedRegion().IsInside(region) ) return false;
if( !img2->GetBufferedRegion().IsInside(region) ) return false;
itk::ImageRegionConstIterator<TImage> it1(img1, region);
itk::ImageRegionConstIterator<TImage> it2(img2, region);
for(it1.GoToBegin(), it2.GoToBegin(); !it1.IsAtEnd(); ++it1, ++it2)
{
if(it1.Get() != it2.Get())
{
return false;
}
}
return true;
}
template<class TImage>
bool ImagesEqual(const TImage* img1, const TImage* img2)
{
return ImagesEqual(img1, img2, img1->GetLargestPossibleRegion());
}
/**
* Generates an image with constant pixel value 23 (binary pattern 0..010111,
* little endian) and saves it with streamed writing, reads it non-streamed and
* compares the original image with the read image.
*/
template<class TScalar, unsigned int TDimension>
int TestStreamWrite(char *file1, unsigned int numberOfStreams = 0)
{
typedef itk::Image<TScalar,TDimension> ImageType;
// Create a source object (in this case a constant image).
typename ImageType::SizeValueType size[TDimension];
for (unsigned int i = 0; i < TDimension; i++)
{
size[i] = 2 << (i + 1);
}
typename itk::ConstantImageSource<ImageType>::Pointer constValueImageSource;
constValueImageSource = itk::ConstantImageSource<ImageType>::New();
constValueImageSource->SetValue(static_cast<TScalar>(23));
constValueImageSource->SetSize(size);
typename ImageType::SpacingValueType spacing[3] = {5.0f, 10.0f, 15.0f};
typename ImageType::PointValueType origin[3] = {-5.0f, -10.0f, -15.0f};
constValueImageSource->SetSpacing(spacing);
constValueImageSource->SetOrigin(origin);
ImageType* consValueImage = constValueImageSource->GetOutput();
// Create a mapper (in this case a writer). A mapper
// is templated on the input type.
itk::VTKImageIO::Pointer vtkIO;
vtkIO = itk::VTKImageIO::New();
vtkIO->SetFileTypeToBinary();
// Write out the image
typename itk::ImageFileWriter<ImageType>::Pointer writer;
writer = itk::ImageFileWriter<ImageType>::New();
writer->SetInput(consValueImage);
writer->SetFileName(file1);
if ( numberOfStreams > 0 )
{
writer->SetNumberOfStreamDivisions( numberOfStreams );
}
writer->Write();
// Check if written file is correct
typename itk::ImageFileReader<ImageType>::Pointer reader;
reader = itk::ImageFileReader<ImageType>::New();
reader->SetImageIO(vtkIO);
reader->SetFileName(file1);
consValueImage->SetRequestedRegion(consValueImage->GetLargestPossibleRegion());
consValueImage->Update();
reader->Update();
bool imagesEqual = ImagesEqual(consValueImage, reader->GetOutput());
std::string componentType = itk::ImageIOBase::GetComponentTypeAsString( vtkIO->GetComponentType() );
if ( !imagesEqual )
{
std::cout << "[FAILED] writing (" << componentType << ", dim = " << TDimension
<< ", numberOfStreams = " << numberOfStreams << ")" << std::endl;
return EXIT_FAILURE;
}
std::cout << "[PASSED] writing (" << componentType << ", dim = " << TDimension
<< ", numberOfStreams = " << numberOfStreams << ")" << std::endl;
return EXIT_SUCCESS;
}
/**
* Generates an image with constant pixel value 23 (binary pattern 0..010111,
* little endian) and saves it with non-streamed writing, reads it streamed and
* compares the original image with the read image.
*/
template<class TScalar, unsigned int TDimension>
int TestStreamRead(char *file1, unsigned int numberOfStreams = 0)
{
typedef itk::Image<TScalar,TDimension> ImageType;
// Create a source object (in this case a constant image).
typename ImageType::SizeValueType size[TDimension];
for (unsigned int i = 0; i < TDimension; i++)
{
size[i] = 2 << (i + 1);
}
typename itk::ConstantImageSource<ImageType>::Pointer constValueImageSource;
constValueImageSource = itk::ConstantImageSource<ImageType>::New();
constValueImageSource->SetValue(static_cast<TScalar>(23));
constValueImageSource->SetSize(size);
typename ImageType::SpacingValueType spacing[3] = {5.0f, 10.0f, 15.0f};
typename ImageType::PointValueType origin[3] = {-5.0f, -10.0f, -15.0f};
constValueImageSource->SetSpacing(spacing);
constValueImageSource->SetOrigin(origin);
ImageType* consValueImage = constValueImageSource->GetOutput();
// Create a mapper (in this case a writer). A mapper
// is templated on the input type.
itk::VTKImageIO::Pointer vtkIO;
vtkIO = itk::VTKImageIO::New();
vtkIO->SetFileTypeToBinary();
// Write out the image non-streamed
typename itk::ImageFileWriter<ImageType>::Pointer writer;
writer = itk::ImageFileWriter<ImageType>::New();
writer->SetInput(consValueImage);
writer->SetFileName(file1);
writer->SetNumberOfStreamDivisions( 1 );
writer->Write();
// Check if written file is correct
typename itk::ImageFileReader<ImageType>::Pointer reader;
reader = itk::ImageFileReader<ImageType>::New();
reader->SetImageIO(vtkIO);
reader->SetFileName(file1);
if (numberOfStreams > 0)
{
reader->UseStreamingOn();
}
// Simulate streaming and compares regions
numberOfStreams = std::max(1u, std::min(static_cast<unsigned int>(size[TDimension-1]), numberOfStreams));
typename ImageType::SizeValueType width = (size[TDimension-1]+numberOfStreams-1) / numberOfStreams;
typename ImageType::RegionType totalRegion = consValueImage->GetLargestPossibleRegion();
ImageType* readImage = reader->GetOutput();
consValueImage->SetRequestedRegion(totalRegion);
consValueImage->Update();
bool imagesEqual = true;
for (unsigned int i = 0; i < numberOfStreams; ++i)
{
typename ImageType::RegionType region(totalRegion);
region.SetIndex(TDimension-1, region.GetIndex(TDimension-1) + i * width);
region.SetSize(TDimension-1, width);
region.Crop(totalRegion);
readImage->SetRequestedRegion(region);
readImage->Update();
if(!ImagesEqual(readImage, consValueImage, region))
{
imagesEqual = false;
break;
}
}
std::string componentType = itk::ImageIOBase::GetComponentTypeAsString( vtkIO->GetComponentType() );
if ( !imagesEqual )
{
std::cout << "[FAILED] reading (" << componentType << ", dim = " << TDimension
<< ", numberOfStreams = " << numberOfStreams << ")" << std::endl;
return EXIT_FAILURE;
}
std::cout << "[PASSED] reading (" << componentType << ", dim = " << TDimension
<< ", numberOfStreams = " << numberOfStreams << ")" << std::endl;
return EXIT_SUCCESS;
}
int itkVTKImageIOStreamTest(int argc, char* argv[] )
{
if( argc < 2 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " output" << std::endl;
return EXIT_FAILURE;
}
unsigned int numberOfStreams = 2;
int status = 0;
#define ReadWriteTestMACRO(scalarType) \
status += TestStreamWrite<scalarType,2>(argv[1], 0); \
status += TestStreamWrite<scalarType,2>(argv[1], numberOfStreams); \
status += TestStreamWrite<scalarType,3>(argv[1], 0); \
status += TestStreamWrite<scalarType,3>(argv[1], numberOfStreams); \
status += TestStreamRead<scalarType,2>(argv[1], 0); \
status += TestStreamRead<scalarType,2>(argv[1], numberOfStreams); \
status += TestStreamRead<scalarType,3>(argv[1], 0); \
status += TestStreamRead<scalarType,3>(argv[1], numberOfStreams);
ReadWriteTestMACRO(float)
ReadWriteTestMACRO(double)
ReadWriteTestMACRO(unsigned char)
ReadWriteTestMACRO(char)
ReadWriteTestMACRO(unsigned short)
ReadWriteTestMACRO(short)
ReadWriteTestMACRO(unsigned int)
ReadWriteTestMACRO(int)
ReadWriteTestMACRO(unsigned long)
ReadWriteTestMACRO(long)
return status;
}
<commit_msg>BUG: Uninitialized value in VTKImageIOStreamTest<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkImageFileWriter.h"
#include "itkImageFileReader.h"
#include "itkVTKImageIO.h"
#include "itkGenerateImageSource.h"
#include <fstream>
#include <iostream>
#include <algorithm>
namespace itk
{
/** \class ConstantImageSource
* Image Source that generates an image with constant pixel value.
*/
template< class TOutputImage >
class ConstantImageSource:public GenerateImageSource< TOutputImage >
{
public:
/** Standard class typedefs. */
typedef ConstantImageSource Self;
typedef ConstantImageSource< TOutputImage > Superclass;
typedef SmartPointer< Self > Pointer;
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Run-time type information (and related methods). */
itkTypeMacro(ConstantImageSource, GenerateImageSource);
/** Set the value to fill the image. */
itkSetMacro(Value, typename TOutputImage::PixelType);
protected:
ConstantImageSource()
{
m_Value = NumericTraits< typename TOutputImage::PixelType >::Zero;
}
~ConstantImageSource(){}
/** Does the real work. */
virtual void GenerateData();
private:
ConstantImageSource(const Self &); //purposely not implemented
void operator=(const Self &); //purposely not implemented
typename TOutputImage::PixelType m_Value;
};
template< class TOutputImage >
void ConstantImageSource< TOutputImage >
::GenerateData()
{
TOutputImage* out = this->GetOutput();
out->SetBufferedRegion(out->GetRequestedRegion());
out->Allocate();
out->FillBuffer( m_Value );
}
}// end namespace
/**
* Compares two image regions.
* Assumes that the region is valid and buffered in both images.
*/
template<class TImage>
bool ImagesEqual(const TImage* img1, const TImage* img2,
const typename TImage::RegionType& region)
{
if( !img1->GetBufferedRegion().IsInside(region) ) return false;
if( !img2->GetBufferedRegion().IsInside(region) ) return false;
itk::ImageRegionConstIterator<TImage> it1(img1, region);
itk::ImageRegionConstIterator<TImage> it2(img2, region);
for(it1.GoToBegin(), it2.GoToBegin(); !it1.IsAtEnd(); ++it1, ++it2)
{
if(it1.Get() != it2.Get())
{
return false;
}
}
return true;
}
template<class TImage>
bool ImagesEqual(const TImage* img1, const TImage* img2)
{
return ImagesEqual(img1, img2, img1->GetLargestPossibleRegion());
}
/**
* Generates an image with constant pixel value 23 (binary pattern 0..010111,
* little endian) and saves it with streamed writing, reads it non-streamed and
* compares the original image with the read image.
*/
template<class TScalar, unsigned int TDimension>
int TestStreamWrite(char *file1, unsigned int numberOfStreams = 0)
{
typedef itk::Image<TScalar,TDimension> ImageType;
// Create a source object (in this case a constant image).
typename ImageType::SizeValueType size[TDimension];
for (unsigned int i = 0; i < TDimension; i++)
{
size[i] = 2 << (i + 1);
}
typename itk::ConstantImageSource<ImageType>::Pointer constValueImageSource;
constValueImageSource = itk::ConstantImageSource<ImageType>::New();
constValueImageSource->SetValue(static_cast<TScalar>(23));
constValueImageSource->SetSize(size);
typename ImageType::SpacingValueType spacing[3] = {5.0f, 10.0f, 15.0f};
typename ImageType::PointValueType origin[3] = {-5.0f, -10.0f, -15.0f};
constValueImageSource->SetSpacing(spacing);
constValueImageSource->SetOrigin(origin);
ImageType* consValueImage = constValueImageSource->GetOutput();
// Create a mapper (in this case a writer). A mapper
// is templated on the input type.
itk::VTKImageIO::Pointer vtkIO;
vtkIO = itk::VTKImageIO::New();
vtkIO->SetFileTypeToBinary();
// Write out the image
typename itk::ImageFileWriter<ImageType>::Pointer writer;
writer = itk::ImageFileWriter<ImageType>::New();
writer->SetInput(consValueImage);
writer->SetFileName(file1);
if ( numberOfStreams > 0 )
{
writer->SetNumberOfStreamDivisions( numberOfStreams );
}
writer->Write();
// Check if written file is correct
typename itk::ImageFileReader<ImageType>::Pointer reader;
reader = itk::ImageFileReader<ImageType>::New();
reader->SetImageIO(vtkIO);
reader->SetFileName(file1);
consValueImage->SetRequestedRegion(consValueImage->GetLargestPossibleRegion());
consValueImage->Update();
reader->Update();
bool imagesEqual = ImagesEqual(consValueImage, reader->GetOutput());
std::string componentType = itk::ImageIOBase::GetComponentTypeAsString( vtkIO->GetComponentType() );
if ( !imagesEqual )
{
std::cout << "[FAILED] writing (" << componentType << ", dim = " << TDimension
<< ", numberOfStreams = " << numberOfStreams << ")" << std::endl;
return EXIT_FAILURE;
}
std::cout << "[PASSED] writing (" << componentType << ", dim = " << TDimension
<< ", numberOfStreams = " << numberOfStreams << ")" << std::endl;
return EXIT_SUCCESS;
}
/**
* Generates an image with constant pixel value 23 (binary pattern 0..010111,
* little endian) and saves it with non-streamed writing, reads it streamed and
* compares the original image with the read image.
*/
template<class TScalar, unsigned int TDimension>
int TestStreamRead(char *file1, unsigned int numberOfStreams = 0)
{
typedef itk::Image<TScalar,TDimension> ImageType;
// Create a source object (in this case a constant image).
typename ImageType::SizeValueType size[TDimension];
for (unsigned int i = 0; i < TDimension; i++)
{
size[i] = 2 << (i + 1);
}
typename itk::ConstantImageSource<ImageType>::Pointer constValueImageSource;
constValueImageSource = itk::ConstantImageSource<ImageType>::New();
constValueImageSource->SetValue(static_cast<TScalar>(23));
constValueImageSource->SetSize(size);
typename ImageType::SpacingValueType spacing[3] = {5.0f, 10.0f, 15.0f};
typename ImageType::PointValueType origin[3] = {-5.0f, -10.0f, -15.0f};
constValueImageSource->SetSpacing(spacing);
constValueImageSource->SetOrigin(origin);
ImageType* consValueImage = constValueImageSource->GetOutput();
// Create a mapper (in this case a writer). A mapper
// is templated on the input type.
itk::VTKImageIO::Pointer vtkIO;
vtkIO = itk::VTKImageIO::New();
vtkIO->SetFileTypeToBinary();
// Write out the image non-streamed
typename itk::ImageFileWriter<ImageType>::Pointer writer;
writer = itk::ImageFileWriter<ImageType>::New();
writer->SetInput(consValueImage);
writer->SetFileName(file1);
writer->SetNumberOfStreamDivisions( 1 );
writer->Write();
// Check if written file is correct
typename itk::ImageFileReader<ImageType>::Pointer reader;
reader = itk::ImageFileReader<ImageType>::New();
reader->SetImageIO(vtkIO);
reader->SetFileName(file1);
if (numberOfStreams > 0)
{
reader->UseStreamingOn();
}
// Simulate streaming and compares regions
numberOfStreams = std::max(1u, std::min(static_cast<unsigned int>(size[TDimension-1]), numberOfStreams));
typename ImageType::SizeValueType width = (size[TDimension-1]+numberOfStreams-1) / numberOfStreams;
typename ImageType::RegionType totalRegion = consValueImage->GetLargestPossibleRegion();
ImageType* readImage = reader->GetOutput();
consValueImage->SetRequestedRegion(totalRegion);
consValueImage->Update();
bool imagesEqual = true;
for (unsigned int i = 0; i < numberOfStreams; ++i)
{
typename ImageType::RegionType region(totalRegion);
region.SetIndex(TDimension-1, region.GetIndex(TDimension-1) + i * width);
region.SetSize(TDimension-1, width);
region.Crop(totalRegion);
readImage->SetRequestedRegion(region);
readImage->Update();
if(!ImagesEqual(readImage, consValueImage, region))
{
imagesEqual = false;
break;
}
}
std::string componentType = itk::ImageIOBase::GetComponentTypeAsString( vtkIO->GetComponentType() );
if ( !imagesEqual )
{
std::cout << "[FAILED] reading (" << componentType << ", dim = " << TDimension
<< ", numberOfStreams = " << numberOfStreams << ")" << std::endl;
return EXIT_FAILURE;
}
std::cout << "[PASSED] reading (" << componentType << ", dim = " << TDimension
<< ", numberOfStreams = " << numberOfStreams << ")" << std::endl;
return EXIT_SUCCESS;
}
int itkVTKImageIOStreamTest(int argc, char* argv[] )
{
if( argc < 2 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " output" << std::endl;
return EXIT_FAILURE;
}
unsigned int numberOfStreams = 2;
int status = 0;
#define ReadWriteTestMACRO(scalarType) \
status += TestStreamWrite<scalarType,2>(argv[1], 0); \
status += TestStreamWrite<scalarType,2>(argv[1], numberOfStreams); \
status += TestStreamWrite<scalarType,3>(argv[1], 0); \
status += TestStreamWrite<scalarType,3>(argv[1], numberOfStreams); \
status += TestStreamRead<scalarType,2>(argv[1], 0); \
status += TestStreamRead<scalarType,2>(argv[1], numberOfStreams); \
status += TestStreamRead<scalarType,3>(argv[1], 0); \
status += TestStreamRead<scalarType,3>(argv[1], numberOfStreams);
ReadWriteTestMACRO(float)
ReadWriteTestMACRO(double)
ReadWriteTestMACRO(unsigned char)
ReadWriteTestMACRO(char)
ReadWriteTestMACRO(unsigned short)
ReadWriteTestMACRO(short)
ReadWriteTestMACRO(unsigned int)
ReadWriteTestMACRO(int)
ReadWriteTestMACRO(unsigned long)
ReadWriteTestMACRO(long)
return status;
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: Constraint.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2016 Stanford University and the Authors *
* Author(s): Frank C. Anderson, Ajay Seth *
* *
* 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. *
* -------------------------------------------------------------------------- */
//=============================================================================
// INCLUDES
//=============================================================================
#include "Constraint.h"
#include <OpenSim/Simulation/Model/Model.h>
#include "simbody/internal/Constraint.h"
//=============================================================================
// STATICS
//=============================================================================
using namespace std;
//using namespace SimTK;
using namespace OpenSim;
//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
//_____________________________________________________________________________
/**
* Default constructor.
*/
Constraint::Constraint()
{
setNull();
constructProperties();
}
//_____________________________________________________________________________
/**
* Destructor.
*/
Constraint::~Constraint()
{
}
//_____________________________________________________________________________
/**
* Set the data members of this Constraint to their null values.
*/
void Constraint::setNull(void)
{
setAuthors("Frank Anderson, Ajay Seth");
}
//_____________________________________________________________________________
/**
* Connect properties to local pointers.
*/
void Constraint::constructProperties(void)
{
constructProperty_isEnforced(true);
}
void Constraint::updateFromXMLNode(SimTK::Xml::Element& node,
int versionNumber) {
if(versionNumber < XMLDocument::getLatestVersion()) {
if(versionNumber < 30508) {
// Rename property 'isDisabled' to 'isEnforced' and
// negate the contained value.
std::string oldName{"isDisabled"};
std::string newName{"isEnforced"};
if(node.hasElement(oldName)) {
auto elem = node.getRequiredElement(oldName);
elem.setElementTag(newName);
if(elem.getValue().find("true") != std::string::npos)
elem.setValue("false");
else if(elem.getValue().find("false") != std::string::npos)
elem.setValue("true");
}
}
}
Super::updateFromXMLNode(node, versionNumber);
}
//_____________________________________________________________________________
/**
* Perform some set up functions that happen after the
* object has been deserialized or copied.
*
* @param aModel OpenSim model containing this Constraint.
*/
void Constraint::extendConnectToModel(Model& aModel)
{
Super::extendConnectToModel(aModel);
}
void Constraint::extendInitStateFromProperties(SimTK::State& s) const
{
Super::extendInitStateFromProperties(s);
SimTK::Constraint& simConstraint =
_model->updMatterSubsystem().updConstraint(_index);
// Otherwise we have to change the status of the constraint
if(get_isEnforced())
simConstraint.enable(s);
else
simConstraint.disable(s);
}
void Constraint::extendSetPropertiesFromState(const SimTK::State& state)
{
Super::extendSetPropertiesFromState(state);
set_isEnforced(isEnforced(state));
}
//=============================================================================
// UTILITY
//=============================================================================
//_____________________________________________________________________________
/**
* Update an existing Constraint with parameter values from a
* new one, but only for the parameters that were explicitly
* specified in the XML node.
*
* @param aConstraint Constraint to update from
*/
void Constraint::updateFromConstraint(SimTK::State& s,
const Constraint &aConstraint)
{
setIsEnforced(s, aConstraint.isEnforced(s));
}
//=============================================================================
// GET AND SET
//=============================================================================
//-----------------------------------------------------------------------------
// DISABLE
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Get whether or not this Constraint is enforced.
* Simbody multibody system instance is realized every time the isEnforced
* changes, BUT multiple sets to the same value have no cost.
*/
bool Constraint::isEnforced(const SimTK::State& s) const
{
return !_model->updMatterSubsystem().updConstraint(_index).isDisabled(s);
}
//_____________________________________________________________________________
/**
* Set whether or not this Constraint is enforced.
* Simbody multibody system instance is realized every time the isEnforced
* changes, BUT multiple sets to the same value have no cost.
*
* @param isEnforced If true the constraint is enabled (active).
* If false the constraint is disabled (in-active).
*/
bool Constraint::setIsEnforced(SimTK::State& s, bool isEnforced)
{
SimTK::Constraint& simConstraint =
_model->updMatterSubsystem().updConstraint(_index);
bool modelConstraintIsEnforced = !simConstraint.isDisabled(s);
// Check if we already have the correct enabling of the constraint then
// do nothing
if(isEnforced == modelConstraintIsEnforced)
return true;
// Otherwise we have to change the status of the constraint
if(isEnforced)
simConstraint.enable(s);
else
simConstraint.disable(s);
_model->updateAssemblyConditions(s);
set_isEnforced(isEnforced);
return true;
}
//-----------------------------------------------------------------------------
// FORCES
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Ask the constraint for the forces it is imposing on the system
* Simbody multibody system must be realized to at least position
* Returns: the bodyForces on those bodies being constrained (constrainedBodies)
* a SpatialVec (6 components) describing resulting torque and force
* mobilityForces acting along constrained mobilities
*
* @param state State of model
* @param bodyForcesInAncestor is a Vector of SpatialVecs contain constraint
forces
* @param mobilityForces is a Vector of forces that act along the constrained
* mobilities associated with this constraint
*/
void Constraint::
calcConstraintForces(const SimTK::State& s,
SimTK::Vector_<SimTK::SpatialVec>& bodyForcesInAncestor,
SimTK::Vector& mobilityForces) const {
SimTK::Constraint& simConstraint =
_model->updMatterSubsystem().updConstraint(_index);
if(!simConstraint.isDisabled(s)){
SimTK::Vector multipliers = simConstraint.getMultipliersAsVector(s);
simConstraint.calcConstraintForcesFromMultipliers(s, multipliers,
bodyForcesInAncestor,
mobilityForces);
}
}
/**
* Methods to query a Constraint forces for the value actually applied during simulation
* The names of the quantities (column labels) is returned by this first function
* getRecordLabels()
*/
Array<std::string> Constraint::getRecordLabels() const
{
SimTK::Constraint& simConstraint = _model->updMatterSubsystem().updConstraint(_index);
const SimTK::State &ds = _model->getWorkingState();
// number of bodies being directly constrained
int ncb = simConstraint.getNumConstrainedBodies();
// number of mobilities being directly constrained
int ncm = simConstraint.getNumConstrainedU(ds);
const BodySet &bodies = _model->getBodySet();
Array<std::string> labels("");
for(int i=0; i<ncb; ++i){
const SimTK::MobilizedBody &b = simConstraint.getMobilizedBodyFromConstrainedBody(SimTK::ConstrainedBodyIndex(i));
const SimTK::MobilizedBodyIndex &bx = b.getMobilizedBodyIndex();
Body *bod = NULL;
for(int j=0; j<bodies.getSize(); ++j ){
if(bodies[j].getMobilizedBodyIndex() == bx){
bod = &bodies[j];
break;
}
}
if(bod == NULL){
throw Exception("Constraint "+getName()+" does not have an identifiable body index.");
}
string prefix = getName()+"_"+bod->getName();
labels.append(prefix+"_Fx");
labels.append(prefix+"_Fy");
labels.append(prefix+"_Fz");
labels.append(prefix+"_Mx");
labels.append(prefix+"_My");
labels.append(prefix+"_Mz");
}
char c[2] = "";
for(int i=0; i<ncm; ++i){
sprintf(c, "%d", i);
labels.append(getName()+"_mobility_F"+c);
}
return labels;
}
/**
* Given SimTK::State object extract all the values necessary to report constraint forces, application
* location frame, etc. used in conjunction with getRecordLabels and should return same size Array
*/
Array<double> Constraint::getRecordValues(const SimTK::State& state) const
{
// EOMs are solved for accelerations (udots) and constraint multipliers (lambdas)
// simultaneously, so system must be realized to acceleration
_model->getMultibodySystem().realize(state, SimTK::Stage::Acceleration);
SimTK::Constraint& simConstraint = _model->updMatterSubsystem().updConstraint(_index);
// number of bodies being directly constrained
int ncb = simConstraint.getNumConstrainedBodies();
// number of mobilities being directly constrained
int ncm = simConstraint.getNumConstrainedU(state);
SimTK::Vector_<SimTK::SpatialVec> bodyForcesInAncestor(ncb);
bodyForcesInAncestor.setToZero();
SimTK::Vector mobilityForces(ncm, 0.0);
Array<double> values(0.0,6*ncb+ncm);
calcConstraintForces(state, bodyForcesInAncestor, mobilityForces);
for(int i=0; i<ncb; ++i){
for(int j=0; j<3; ++j){
// Simbody constraints have reaction moments first and OpenSim reports forces first
// so swap them here
values[i*6+j] = (bodyForcesInAncestor(i)[1])[j]; // moments on constrained body i
values[i*6+3+j] = (bodyForcesInAncestor(i)[0])[j]; // forces on constrained body i
}
}
for(int i=0; i<ncm; ++i){
values[6*ncb+i] = mobilityForces[i];
}
return values;
};
<commit_msg>Make updateFromXMLNode more robust by accepting multiple variations of string expressions for bool value.<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: Constraint.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2016 Stanford University and the Authors *
* Author(s): Frank C. Anderson, Ajay Seth *
* *
* 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. *
* -------------------------------------------------------------------------- */
//=============================================================================
// INCLUDES
//=============================================================================
#include "Constraint.h"
#include <OpenSim/Simulation/Model/Model.h>
#include "simbody/internal/Constraint.h"
//=============================================================================
// STATICS
//=============================================================================
using namespace std;
//using namespace SimTK;
using namespace OpenSim;
//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
//_____________________________________________________________________________
/**
* Default constructor.
*/
Constraint::Constraint()
{
setNull();
constructProperties();
}
//_____________________________________________________________________________
/**
* Destructor.
*/
Constraint::~Constraint()
{
}
//_____________________________________________________________________________
/**
* Set the data members of this Constraint to their null values.
*/
void Constraint::setNull(void)
{
setAuthors("Frank Anderson, Ajay Seth");
}
//_____________________________________________________________________________
/**
* Connect properties to local pointers.
*/
void Constraint::constructProperties(void)
{
constructProperty_isEnforced(true);
}
void Constraint::updateFromXMLNode(SimTK::Xml::Element& node,
int versionNumber) {
if (versionNumber < XMLDocument::getLatestVersion()) {
if (versionNumber < 30509) {
// Rename property 'isDisabled' to 'isEnforced' and
// negate the contained value.
std::string oldName{ "isDisabled" };
std::string newName{ "isEnforced" };
if (node.hasElement(oldName)) {
auto elem = node.getRequiredElement(oldName);
bool isDisabled = false;
elem.getValue().tryConvertToBool(isDisabled);
// now update tag name to 'isEnforced'
elem.setElementTag(newName);
// update its value to be the opposite of 'isDisabled'
elem.setValue(SimTK::String(!isDisabled));
}
}
}
Super::updateFromXMLNode(node, versionNumber);
}
//_____________________________________________________________________________
/**
* Perform some set up functions that happen after the
* object has been deserialized or copied.
*
* @param aModel OpenSim model containing this Constraint.
*/
void Constraint::extendConnectToModel(Model& aModel)
{
Super::extendConnectToModel(aModel);
}
void Constraint::extendInitStateFromProperties(SimTK::State& s) const
{
Super::extendInitStateFromProperties(s);
SimTK::Constraint& simConstraint =
_model->updMatterSubsystem().updConstraint(_index);
// Otherwise we have to change the status of the constraint
if(get_isEnforced())
simConstraint.enable(s);
else
simConstraint.disable(s);
}
void Constraint::extendSetPropertiesFromState(const SimTK::State& state)
{
Super::extendSetPropertiesFromState(state);
set_isEnforced(isEnforced(state));
}
//=============================================================================
// UTILITY
//=============================================================================
//_____________________________________________________________________________
/**
* Update an existing Constraint with parameter values from a
* new one, but only for the parameters that were explicitly
* specified in the XML node.
*
* @param aConstraint Constraint to update from
*/
void Constraint::updateFromConstraint(SimTK::State& s,
const Constraint &aConstraint)
{
setIsEnforced(s, aConstraint.isEnforced(s));
}
//=============================================================================
// GET AND SET
//=============================================================================
//-----------------------------------------------------------------------------
// DISABLE
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Get whether or not this Constraint is enforced.
* Simbody multibody system instance is realized every time the isEnforced
* changes, BUT multiple sets to the same value have no cost.
*/
bool Constraint::isEnforced(const SimTK::State& s) const
{
return !_model->updMatterSubsystem().updConstraint(_index).isDisabled(s);
}
//_____________________________________________________________________________
/**
* Set whether or not this Constraint is enforced.
* Simbody multibody system instance is realized every time the isEnforced
* changes, BUT multiple sets to the same value have no cost.
*
* @param isEnforced If true the constraint is enabled (active).
* If false the constraint is disabled (in-active).
*/
bool Constraint::setIsEnforced(SimTK::State& s, bool isEnforced)
{
SimTK::Constraint& simConstraint =
_model->updMatterSubsystem().updConstraint(_index);
bool modelConstraintIsEnforced = !simConstraint.isDisabled(s);
// Check if we already have the correct enabling of the constraint then
// do nothing
if(isEnforced == modelConstraintIsEnforced)
return true;
// Otherwise we have to change the status of the constraint
if(isEnforced)
simConstraint.enable(s);
else
simConstraint.disable(s);
_model->updateAssemblyConditions(s);
set_isEnforced(isEnforced);
return true;
}
//-----------------------------------------------------------------------------
// FORCES
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Ask the constraint for the forces it is imposing on the system
* Simbody multibody system must be realized to at least position
* Returns: the bodyForces on those bodies being constrained (constrainedBodies)
* a SpatialVec (6 components) describing resulting torque and force
* mobilityForces acting along constrained mobilities
*
* @param state State of model
* @param bodyForcesInAncestor is a Vector of SpatialVecs contain constraint
forces
* @param mobilityForces is a Vector of forces that act along the constrained
* mobilities associated with this constraint
*/
void Constraint::
calcConstraintForces(const SimTK::State& s,
SimTK::Vector_<SimTK::SpatialVec>& bodyForcesInAncestor,
SimTK::Vector& mobilityForces) const {
SimTK::Constraint& simConstraint =
_model->updMatterSubsystem().updConstraint(_index);
if(!simConstraint.isDisabled(s)){
SimTK::Vector multipliers = simConstraint.getMultipliersAsVector(s);
simConstraint.calcConstraintForcesFromMultipliers(s, multipliers,
bodyForcesInAncestor,
mobilityForces);
}
}
/**
* Methods to query a Constraint forces for the value actually applied during simulation
* The names of the quantities (column labels) is returned by this first function
* getRecordLabels()
*/
Array<std::string> Constraint::getRecordLabels() const
{
SimTK::Constraint& simConstraint = _model->updMatterSubsystem().updConstraint(_index);
const SimTK::State &ds = _model->getWorkingState();
// number of bodies being directly constrained
int ncb = simConstraint.getNumConstrainedBodies();
// number of mobilities being directly constrained
int ncm = simConstraint.getNumConstrainedU(ds);
const BodySet &bodies = _model->getBodySet();
Array<std::string> labels("");
for(int i=0; i<ncb; ++i){
const SimTK::MobilizedBody &b = simConstraint.getMobilizedBodyFromConstrainedBody(SimTK::ConstrainedBodyIndex(i));
const SimTK::MobilizedBodyIndex &bx = b.getMobilizedBodyIndex();
Body *bod = NULL;
for(int j=0; j<bodies.getSize(); ++j ){
if(bodies[j].getMobilizedBodyIndex() == bx){
bod = &bodies[j];
break;
}
}
if(bod == NULL){
throw Exception("Constraint "+getName()+" does not have an identifiable body index.");
}
string prefix = getName()+"_"+bod->getName();
labels.append(prefix+"_Fx");
labels.append(prefix+"_Fy");
labels.append(prefix+"_Fz");
labels.append(prefix+"_Mx");
labels.append(prefix+"_My");
labels.append(prefix+"_Mz");
}
char c[2] = "";
for(int i=0; i<ncm; ++i){
sprintf(c, "%d", i);
labels.append(getName()+"_mobility_F"+c);
}
return labels;
}
/**
* Given SimTK::State object extract all the values necessary to report constraint forces, application
* location frame, etc. used in conjunction with getRecordLabels and should return same size Array
*/
Array<double> Constraint::getRecordValues(const SimTK::State& state) const
{
// EOMs are solved for accelerations (udots) and constraint multipliers (lambdas)
// simultaneously, so system must be realized to acceleration
_model->getMultibodySystem().realize(state, SimTK::Stage::Acceleration);
SimTK::Constraint& simConstraint = _model->updMatterSubsystem().updConstraint(_index);
// number of bodies being directly constrained
int ncb = simConstraint.getNumConstrainedBodies();
// number of mobilities being directly constrained
int ncm = simConstraint.getNumConstrainedU(state);
SimTK::Vector_<SimTK::SpatialVec> bodyForcesInAncestor(ncb);
bodyForcesInAncestor.setToZero();
SimTK::Vector mobilityForces(ncm, 0.0);
Array<double> values(0.0,6*ncb+ncm);
calcConstraintForces(state, bodyForcesInAncestor, mobilityForces);
for(int i=0; i<ncb; ++i){
for(int j=0; j<3; ++j){
// Simbody constraints have reaction moments first and OpenSim reports forces first
// so swap them here
values[i*6+j] = (bodyForcesInAncestor(i)[1])[j]; // moments on constrained body i
values[i*6+3+j] = (bodyForcesInAncestor(i)[0])[j]; // forces on constrained body i
}
}
for(int i=0; i<ncm; ++i){
values[6*ncb+i] = mobilityForces[i];
}
return values;
};
<|endoftext|> |
<commit_before>
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//---- ANALYSIS system ----
#include "AliCaloTrackAODReader.h"
#include "AliAODInputHandler.h"
#include "AliMultiEventInputHandler.h"
#include "AliAnalysisManager.h"
#include "AliMixedEvent.h"
#include "AliAODEvent.h"
#include "AliGenEventHeader.h"
#include "AliLog.h"
#include "AliAnalysisTaskEmcalEmbeddingHelper.h"
/// \cond CLASSIMP
ClassImp(AliCaloTrackAODReader) ;
/// \endcond
//______________________________________________
/// Default constructor. Initialize parameters
//______________________________________________
AliCaloTrackAODReader::AliCaloTrackAODReader() :
AliCaloTrackReader(), fOrgInputEvent(0x0),
fSelectHybridTracks(0), fSelectPrimaryTracks(0),
fTrackFilterMask(0), fTrackFilterMaskComplementary(0),
fSelectFractionTPCSharedClusters(0), fCutTPCSharedClustersFraction(0)
{
fDataType = kAOD;
//fTrackFilterMask = 128;
//fTrackFilterMaskComplementary = 0; // in case of hybrid tracks, without using the standard method
//fSelectFractionTPCSharedClusters = kTRUE;
fCutTPCSharedClustersFraction = 0.4;
}
//_________________________________________________________
/// Check if the vertex was well reconstructed.
/// Copy method of PCM group.
//_________________________________________________________
Bool_t AliCaloTrackAODReader::CheckForPrimaryVertex() const
{
AliAODEvent * aodevent = NULL;
// In case of analysis of pure MC event used in embedding
// get bkg PbPb event since cuts for embedded event are based on
// data vertex and not on pp simu vertex
if ( fEmbeddedEvent[1] ) // Input event is MC
aodevent = dynamic_cast<AliAODEvent*>(((AliAnalysisManager::GetAnalysisManager())->GetInputEventHandler())->GetEvent());
else
aodevent = dynamic_cast<AliAODEvent*>(fInputEvent);
if ( !aodevent ) return kFALSE;
if ( aodevent->GetPrimaryVertex() != NULL )
{
if ( aodevent->GetPrimaryVertex()->GetNContributors() > 0 )
{
return kTRUE;
}
}
if ( aodevent->GetPrimaryVertexSPD() != NULL )
{
if ( aodevent->GetPrimaryVertexSPD()->GetNContributors() > 0 )
{
return kTRUE;
}
else
{
AliDebug(1,Form("Null number of contributors from bad vertex type:: %s",
aodevent->GetPrimaryVertex()->GetName()));
return kFALSE;
}
}
return kFALSE;
}
//___________________________________________________
/// Fill the output list of initialized control histograms.
/// Cluster or track spectra histograms, depending on different selection cuts.
/// First fill the histograms of the mother class, that are independent on ESD/AOD.
/// Then add the AOD specific ones.
//___________________________________________________
TList * AliCaloTrackAODReader::GetCreateControlHistograms()
{
AliCaloTrackReader::GetCreateControlHistograms();
if(fFillCTS)
{
for(Int_t i = 0; i < 6; i++)
{
TString names[] = {"FilterBit_Hybrid", "SPDHit", "NclustersITS", "Chi2ITS", "SharedCluster", "Primary"};
fhCTSAODTrackCutsPt[i] = new TH1F(Form("hCTSReaderAODClusterCuts_%d_%s",i,names[i].Data()),
Form("AOD CTS Cut %d, %s",i,names[i].Data()),
fEnergyHistogramNbins, fEnergyHistogramLimit[0], fEnergyHistogramLimit[1]) ;
fhCTSAODTrackCutsPt[i]->SetYTitle("# tracks");
fhCTSAODTrackCutsPt[i]->SetXTitle("#it{p}_{T} (GeV)");
fOutputContainer->Add(fhCTSAODTrackCutsPt[i]);
}
}
return fOutputContainer ;
}
//________________________________________________________
/// Save parameters used for analysis in a string.
//________________________________________________________
TObjString * AliCaloTrackAODReader::GetListOfParameters()
{
// Recover the string from the mother class
TString parList = (AliCaloTrackReader::GetListOfParameters())->GetString();
const Int_t buffersize = 255;
char onePar[buffersize] ;
snprintf(onePar,buffersize,"AOD Track: Hybrid %d, Filter bit %d, Complementary bit %d, Primary %d; ",
fSelectHybridTracks, (Int_t)fTrackFilterMask, (Int_t)fTrackFilterMaskComplementary, fSelectPrimaryTracks) ;
parList+=onePar ;
if ( fSelectFractionTPCSharedClusters )
{
snprintf(onePar,buffersize,"Fraction of TPC shared clusters ON: %2.2f ", fCutTPCSharedClustersFraction) ;
parList+=onePar ;
}
return new TObjString(parList) ;
}
//____________________________________________________________
/// \return list of MC particles in AOD. Do it for the corresponding input event.
//____________________________________________________________
TClonesArray* AliCaloTrackAODReader::GetAODMCParticles() const
{
TClonesArray * particles = NULL ;
AliAODEvent * aod = dynamic_cast<AliAODEvent*> (fInputEvent) ;
if(aod) particles = (TClonesArray*) aod->FindListObject("mcparticles");
return particles ;
}
//___________________________________________________________
/// \return MC header in AOD. Do it for the corresponding input event.
//___________________________________________________________
AliAODMCHeader* AliCaloTrackAODReader::GetAODMCHeader() const
{
AliAODMCHeader *mch = NULL;
AliAODEvent * aod = NULL;
if ( fEmbeddedEvent[0] && !fEmbeddedEvent[1] )
aod = dynamic_cast<AliAODEvent*> (AliAnalysisTaskEmcalEmbeddingHelper::GetInstance()->GetExternalEvent());
else
aod = dynamic_cast<AliAODEvent*> (fInputEvent);
if(aod) mch = dynamic_cast<AliAODMCHeader*>(aod->FindListObject("mcHeader"));
return mch;
}
//______________________________________________________________
/// \return pointer to Generated event header (AliGenEventHeader)
//______________________________________________________________
AliGenEventHeader* AliCaloTrackAODReader::GetGenEventHeader() const
{
if ( !GetAODMCHeader() ) return 0x0;
if ( fGenEventHeader ) return fGenEventHeader;
Int_t nGenerators = GetAODMCHeader()->GetNCocktailHeaders();
if ( nGenerators <= 0 ) return 0x0;
if ( fMCGenerEventHeaderToAccept=="" )
return GetAODMCHeader()->GetCocktailHeader(0);
//if(nGenerators < 1) printf("No generators %d\n",nGenerators);
for(Int_t igen = 0; igen < nGenerators; igen++)
{
AliGenEventHeader * eventHeader = GetAODMCHeader()->GetCocktailHeader(igen) ;
TString name = eventHeader->GetName();
AliDebug(2,Form("AOD Event header %d name %s event header class %s: Select if contains <%s>",
igen,name.Data(),eventHeader->ClassName(),fMCGenerEventHeaderToAccept.Data()));
// if(nGenerators < 2)
// printf("AOD Event header %d name %s event header class %s: Select if contains <%s>\n",
// igen,name.Data(),eventHeader->ClassName(),fMCGenerEventHeaderToAccept.Data());
if(name.Contains(fMCGenerEventHeaderToAccept,TString::kIgnoreCase))
return eventHeader ;
}
return 0x0;
}
//_____________________________
///
/// Return track ID, different for ESD and AODs.
/// In AODs a track can correspond to several definitions.
/// If negative (hybrid constrained to vertex), it corresponds to global track
/// with ID positive plus one.
///
/// See AliCaloTrackReader for ESD correspondent.
///
/// \return track ID
/// \param track: pointer to track
//_____________________________
Int_t AliCaloTrackAODReader::GetTrackID(AliVTrack* track)
{
Int_t id = track->GetID();
if( id < 0 ) id = TMath::Abs(id) - 1;
return id;
}
//________________________________________________________
/// Save parameters used for analysis in a string.
//________________________________________________________
void AliCaloTrackAODReader::Print(const Option_t * opt) const
{
if(! opt)
return;
AliCaloTrackReader::Print(opt);
printf("AOD Track: Hybrid %d, Filter bit %d, Complementary bit %d, Primary %d; \n",
fSelectHybridTracks, (Int_t)fTrackFilterMask, (Int_t)fTrackFilterMaskComplementary, fSelectPrimaryTracks) ;
if ( fSelectFractionTPCSharedClusters )
{
printf("Fraction of TPC shared clusters ON: %2.2f ", fCutTPCSharedClustersFraction) ;
}
}
//_____________________________________________________________________________
/// Select AOD track using the AOD filter bits or predefined selection methods.
//_____________________________________________________________________________
Bool_t AliCaloTrackAODReader::SelectTrack(AliVTrack* track, Double_t pTrack[3])
{
AliAODTrack *aodtrack = dynamic_cast <AliAODTrack*>(track);
if(!aodtrack) return kFALSE;
track->GetPxPyPz(pTrack) ;
AliDebug(2,Form("AOD track type: %d (primary %d), hybrid? %d",
aodtrack->GetType(),AliAODTrack::kPrimary,
aodtrack->IsHybridGlobalConstrainedGlobal()));
// Hybrid?
if ( fSelectHybridTracks && fTrackFilterMaskComplementary == 0 )
{
if ( !aodtrack->IsHybridGlobalConstrainedGlobal() ) return kFALSE ;
}
else if ( fTrackFilterMask > 0 || fTrackFilterMaskComplementary > 0 ) // Filter Bit?
{
Bool_t accept = aodtrack->TestFilterBit(fTrackFilterMask);
if ( !fSelectHybridTracks && !accept ) return kFALSE ;
if ( fSelectHybridTracks ) // Second filter bit for hybrids?
{
Bool_t acceptcomplement = aodtrack->TestFilterBit(fTrackFilterMaskComplementary);
if ( !accept && !acceptcomplement ) return kFALSE ;
}
}
fhCTSAODTrackCutsPt[0]->Fill(aodtrack->Pt());
//
// ITS related cuts
// Not much sense to use with TPC only or Hybrid tracks
//
// printf("SPD %d (%d,%d) - n clus %d >= %d - chi2 %f max chi2 %f\n",
// fSelectSPDHitTracks, aodtrack->HasPointOnITSLayer(0),!aodtrack->HasPointOnITSLayer(1),
// aodtrack->GetITSNcls(),fSelectMinITSclusters,
// aodtrack->GetITSchi2(),fSelectMaxChi2PerITScluster);
if ( fSelectSPDHitTracks )
{
if ( !aodtrack->HasPointOnITSLayer(0) && !aodtrack->HasPointOnITSLayer(1) )
return kFALSE ;
AliDebug(2,"Pass SPD layer cut");
}
fhCTSAODTrackCutsPt[1]->Fill(aodtrack->Pt());
Int_t nITScls = aodtrack->GetITSNcls();
if ( fSelectMinITSclusters > 0 && nITScls < fSelectMinITSclusters )
{
return kFALSE;
AliDebug(2,"Pass n ITS cluster cut");
}
fhCTSAODTrackCutsPt[2]->Fill(aodtrack->Pt());
Float_t chi2PerITScluster = 0.;
if ( nITScls > 0 ) chi2PerITScluster = aodtrack->GetITSchi2()/nITScls;
if ( chi2PerITScluster > fSelectMaxChi2PerITScluster )
{
return kFALSE;
AliDebug(2,"Pass ITS chi2/ncls cut");
}
fhCTSAODTrackCutsPt[3]->Fill(aodtrack->Pt());
//
if ( fSelectFractionTPCSharedClusters )
{
Double_t frac = 0;
Float_t ncls = Float_t(aodtrack->GetTPCncls ());
Float_t nclsS = Float_t(aodtrack->GetTPCnclsS());
if ( ncls> 0 ) frac = nclsS / ncls ;
if ( frac > fCutTPCSharedClustersFraction )
{
AliDebug(2,Form("\t Reject track, shared cluster fraction %f > %f",frac, fCutTPCSharedClustersFraction));
return kFALSE ;
}
}
fhCTSAODTrackCutsPt[4]->Fill(aodtrack->Pt());
//
if ( fSelectPrimaryTracks )
{
if ( aodtrack->GetType()!= AliAODTrack::kPrimary )
{
AliDebug(2,"\t Remove not primary track");
return kFALSE ;
}
}
AliDebug(2,"\t accepted track!");
fhCTSAODTrackCutsPt[5]->Fill(aodtrack->Pt());
return kTRUE;
}
//_________________________________________________________________
/// Connect the data pointers
/// If input is AOD, do analysis with input, if not, do analysis with the output aod.
//_________________________________________________________________
void AliCaloTrackAODReader::SetInputOutputMCEvent(AliVEvent* input,
AliAODEvent* aod,
AliMCEvent* mc)
{
//printf("AODInputHandler %p, MergeEvents %d \n",aodIH, aodIH->GetMergeEvents());
Bool_t tesd = kFALSE ;
Bool_t taod = kTRUE ;
if ( strcmp(input->GetName(), "AliMixedEvent") == 0 )
{
AliMultiEventInputHandler* multiEH = dynamic_cast<AliMultiEventInputHandler*>((AliAnalysisManager::GetAnalysisManager())->GetInputEventHandler());
if(multiEH){
if (multiEH->GetFormat() == 0 )
{
tesd = kTRUE ;
} else if (multiEH->GetFormat() == 1)
{
taod = kTRUE ;
}
}
else
{
AliFatal("MultiEventHandler is NULL");
return;
}
}
if (strcmp(input->GetName(),"AliESDEvent") == 0)
{
tesd = kTRUE ;
} else if (strcmp(input->GetName(),"AliAODEvent") == 0)
{
taod = kTRUE ;
}
if(tesd)
{
SetInputEvent(aod);
SetOutputEvent(aod);
fOrgInputEvent = input;
}
else if(taod)
{
AliAODInputHandler* aodIH = dynamic_cast<AliAODInputHandler*>((AliAnalysisManager::GetAnalysisManager())->GetInputEventHandler());
if (aodIH && aodIH->GetMergeEvents())
{
//Merged events, use output AOD.
SetInputEvent(aod);
SetOutputEvent(aod);
fOrgInputEvent = input;
}
else
{
SetInputEvent(input);
SetOutputEvent(aod);
}
}
else
{
AliFatal(Form("STOP : Wrong data format: %s",input->GetName()));
}
SetMC(mc);
}
<commit_msg>fix method comment<commit_after>
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//---- ANALYSIS system ----
#include "AliCaloTrackAODReader.h"
#include "AliAODInputHandler.h"
#include "AliMultiEventInputHandler.h"
#include "AliAnalysisManager.h"
#include "AliMixedEvent.h"
#include "AliAODEvent.h"
#include "AliGenEventHeader.h"
#include "AliLog.h"
#include "AliAnalysisTaskEmcalEmbeddingHelper.h"
/// \cond CLASSIMP
ClassImp(AliCaloTrackAODReader) ;
/// \endcond
//______________________________________________
/// Default constructor. Initialize parameters
//______________________________________________
AliCaloTrackAODReader::AliCaloTrackAODReader() :
AliCaloTrackReader(), fOrgInputEvent(0x0),
fSelectHybridTracks(0), fSelectPrimaryTracks(0),
fTrackFilterMask(0), fTrackFilterMaskComplementary(0),
fSelectFractionTPCSharedClusters(0), fCutTPCSharedClustersFraction(0)
{
fDataType = kAOD;
//fTrackFilterMask = 128;
//fTrackFilterMaskComplementary = 0; // in case of hybrid tracks, without using the standard method
//fSelectFractionTPCSharedClusters = kTRUE;
fCutTPCSharedClustersFraction = 0.4;
}
//_________________________________________________________
/// Check if the vertex was well reconstructed.
/// Copy method of PCM group.
//_________________________________________________________
Bool_t AliCaloTrackAODReader::CheckForPrimaryVertex() const
{
AliAODEvent * aodevent = NULL;
// In case of analysis of pure MC event used in embedding
// get bkg PbPb event since cuts for embedded event are based on
// data vertex and not on pp simu vertex
if ( fEmbeddedEvent[1] ) // Input event is MC
aodevent = dynamic_cast<AliAODEvent*>(((AliAnalysisManager::GetAnalysisManager())->GetInputEventHandler())->GetEvent());
else
aodevent = dynamic_cast<AliAODEvent*>(fInputEvent);
if ( !aodevent ) return kFALSE;
if ( aodevent->GetPrimaryVertex() != NULL )
{
if ( aodevent->GetPrimaryVertex()->GetNContributors() > 0 )
{
return kTRUE;
}
}
if ( aodevent->GetPrimaryVertexSPD() != NULL )
{
if ( aodevent->GetPrimaryVertexSPD()->GetNContributors() > 0 )
{
return kTRUE;
}
else
{
AliDebug(1,Form("Null number of contributors from bad vertex type:: %s",
aodevent->GetPrimaryVertex()->GetName()));
return kFALSE;
}
}
return kFALSE;
}
//___________________________________________________
/// Fill the output list of initialized control histograms.
/// Cluster or track spectra histograms, depending on different selection cuts.
/// First fill the histograms of the mother class, that are independent on ESD/AOD.
/// Then add the AOD specific ones.
//___________________________________________________
TList * AliCaloTrackAODReader::GetCreateControlHistograms()
{
AliCaloTrackReader::GetCreateControlHistograms();
if(fFillCTS)
{
for(Int_t i = 0; i < 6; i++)
{
TString names[] = {"FilterBit_Hybrid", "SPDHit", "NclustersITS", "Chi2ITS", "SharedCluster", "Primary"};
fhCTSAODTrackCutsPt[i] = new TH1F(Form("hCTSReaderAODClusterCuts_%d_%s",i,names[i].Data()),
Form("AOD CTS Cut %d, %s",i,names[i].Data()),
fEnergyHistogramNbins, fEnergyHistogramLimit[0], fEnergyHistogramLimit[1]) ;
fhCTSAODTrackCutsPt[i]->SetYTitle("# tracks");
fhCTSAODTrackCutsPt[i]->SetXTitle("#it{p}_{T} (GeV)");
fOutputContainer->Add(fhCTSAODTrackCutsPt[i]);
}
}
return fOutputContainer ;
}
//________________________________________________________
/// Save parameters used for analysis in a string.
//________________________________________________________
TObjString * AliCaloTrackAODReader::GetListOfParameters()
{
// Recover the string from the mother class
TString parList = (AliCaloTrackReader::GetListOfParameters())->GetString();
const Int_t buffersize = 255;
char onePar[buffersize] ;
snprintf(onePar,buffersize,"AOD Track: Hybrid %d, Filter bit %d, Complementary bit %d, Primary %d; ",
fSelectHybridTracks, (Int_t)fTrackFilterMask, (Int_t)fTrackFilterMaskComplementary, fSelectPrimaryTracks) ;
parList+=onePar ;
if ( fSelectFractionTPCSharedClusters )
{
snprintf(onePar,buffersize,"Fraction of TPC shared clusters ON: %2.2f ", fCutTPCSharedClustersFraction) ;
parList+=onePar ;
}
return new TObjString(parList) ;
}
//____________________________________________________________
/// \return list of MC particles in AOD. Do it for the corresponding input event.
//____________________________________________________________
TClonesArray* AliCaloTrackAODReader::GetAODMCParticles() const
{
TClonesArray * particles = NULL ;
AliAODEvent * aod = dynamic_cast<AliAODEvent*> (fInputEvent) ;
if(aod) particles = (TClonesArray*) aod->FindListObject("mcparticles");
return particles ;
}
//___________________________________________________________
/// \return MC header in AOD. Do it for the corresponding input event.
//___________________________________________________________
AliAODMCHeader* AliCaloTrackAODReader::GetAODMCHeader() const
{
AliAODMCHeader *mch = NULL;
AliAODEvent * aod = NULL;
if ( fEmbeddedEvent[0] && !fEmbeddedEvent[1] )
aod = dynamic_cast<AliAODEvent*> (AliAnalysisTaskEmcalEmbeddingHelper::GetInstance()->GetExternalEvent());
else
aod = dynamic_cast<AliAODEvent*> (fInputEvent);
if(aod) mch = dynamic_cast<AliAODMCHeader*>(aod->FindListObject("mcHeader"));
return mch;
}
//______________________________________________________________
/// \return pointer to Generated event header (AliGenEventHeader)
//______________________________________________________________
AliGenEventHeader* AliCaloTrackAODReader::GetGenEventHeader() const
{
if ( !GetAODMCHeader() ) return 0x0;
if ( fGenEventHeader ) return fGenEventHeader;
Int_t nGenerators = GetAODMCHeader()->GetNCocktailHeaders();
if ( nGenerators <= 0 ) return 0x0;
if ( fMCGenerEventHeaderToAccept=="" )
return GetAODMCHeader()->GetCocktailHeader(0);
//if(nGenerators < 1) printf("No generators %d\n",nGenerators);
for(Int_t igen = 0; igen < nGenerators; igen++)
{
AliGenEventHeader * eventHeader = GetAODMCHeader()->GetCocktailHeader(igen) ;
TString name = eventHeader->GetName();
AliDebug(2,Form("AOD Event header %d name %s event header class %s: Select if contains <%s>",
igen,name.Data(),eventHeader->ClassName(),fMCGenerEventHeaderToAccept.Data()));
// if(nGenerators < 2)
// printf("AOD Event header %d name %s event header class %s: Select if contains <%s>\n",
// igen,name.Data(),eventHeader->ClassName(),fMCGenerEventHeaderToAccept.Data());
if(name.Contains(fMCGenerEventHeaderToAccept,TString::kIgnoreCase))
return eventHeader ;
}
return 0x0;
}
//_____________________________
///
/// Return track ID, different for ESD and AODs.
/// In AODs a track can correspond to several definitions.
/// If negative (hybrid constrained to vertex), it corresponds to global track
/// with ID positive plus one.
///
/// See AliCaloTrackReader for ESD correspondent.
///
/// \return track ID
/// \param track: pointer to track
//_____________________________
Int_t AliCaloTrackAODReader::GetTrackID(AliVTrack* track)
{
Int_t id = track->GetID();
if( id < 0 ) id = TMath::Abs(id) - 1;
return id;
}
//________________________________________________________
/// Print parameters
//________________________________________________________
void AliCaloTrackAODReader::Print(const Option_t * opt) const
{
if(! opt)
return;
AliCaloTrackReader::Print(opt);
printf("AOD Track: Hybrid %d, Filter bit %d, Complementary bit %d, Primary %d; \n",
fSelectHybridTracks, (Int_t)fTrackFilterMask, (Int_t)fTrackFilterMaskComplementary, fSelectPrimaryTracks) ;
if ( fSelectFractionTPCSharedClusters )
{
printf("Fraction of TPC shared clusters ON: %2.2f ", fCutTPCSharedClustersFraction) ;
}
}
//_____________________________________________________________________________
/// Select AOD track using the AOD filter bits or predefined selection methods.
//_____________________________________________________________________________
Bool_t AliCaloTrackAODReader::SelectTrack(AliVTrack* track, Double_t pTrack[3])
{
AliAODTrack *aodtrack = dynamic_cast <AliAODTrack*>(track);
if(!aodtrack) return kFALSE;
track->GetPxPyPz(pTrack) ;
AliDebug(2,Form("AOD track type: %d (primary %d), hybrid? %d",
aodtrack->GetType(),AliAODTrack::kPrimary,
aodtrack->IsHybridGlobalConstrainedGlobal()));
// Hybrid?
if ( fSelectHybridTracks && fTrackFilterMaskComplementary == 0 )
{
if ( !aodtrack->IsHybridGlobalConstrainedGlobal() ) return kFALSE ;
}
else if ( fTrackFilterMask > 0 || fTrackFilterMaskComplementary > 0 ) // Filter Bit?
{
Bool_t accept = aodtrack->TestFilterBit(fTrackFilterMask);
if ( !fSelectHybridTracks && !accept ) return kFALSE ;
if ( fSelectHybridTracks ) // Second filter bit for hybrids?
{
Bool_t acceptcomplement = aodtrack->TestFilterBit(fTrackFilterMaskComplementary);
if ( !accept && !acceptcomplement ) return kFALSE ;
}
}
fhCTSAODTrackCutsPt[0]->Fill(aodtrack->Pt());
//
// ITS related cuts
// Not much sense to use with TPC only or Hybrid tracks
//
// printf("SPD %d (%d,%d) - n clus %d >= %d - chi2 %f max chi2 %f\n",
// fSelectSPDHitTracks, aodtrack->HasPointOnITSLayer(0),!aodtrack->HasPointOnITSLayer(1),
// aodtrack->GetITSNcls(),fSelectMinITSclusters,
// aodtrack->GetITSchi2(),fSelectMaxChi2PerITScluster);
if ( fSelectSPDHitTracks )
{
if ( !aodtrack->HasPointOnITSLayer(0) && !aodtrack->HasPointOnITSLayer(1) )
return kFALSE ;
AliDebug(2,"Pass SPD layer cut");
}
fhCTSAODTrackCutsPt[1]->Fill(aodtrack->Pt());
Int_t nITScls = aodtrack->GetITSNcls();
if ( fSelectMinITSclusters > 0 && nITScls < fSelectMinITSclusters )
{
return kFALSE;
AliDebug(2,"Pass n ITS cluster cut");
}
fhCTSAODTrackCutsPt[2]->Fill(aodtrack->Pt());
Float_t chi2PerITScluster = 0.;
if ( nITScls > 0 ) chi2PerITScluster = aodtrack->GetITSchi2()/nITScls;
if ( chi2PerITScluster > fSelectMaxChi2PerITScluster )
{
return kFALSE;
AliDebug(2,"Pass ITS chi2/ncls cut");
}
fhCTSAODTrackCutsPt[3]->Fill(aodtrack->Pt());
//
if ( fSelectFractionTPCSharedClusters )
{
Double_t frac = 0;
Float_t ncls = Float_t(aodtrack->GetTPCncls ());
Float_t nclsS = Float_t(aodtrack->GetTPCnclsS());
if ( ncls> 0 ) frac = nclsS / ncls ;
if ( frac > fCutTPCSharedClustersFraction )
{
AliDebug(2,Form("\t Reject track, shared cluster fraction %f > %f",frac, fCutTPCSharedClustersFraction));
return kFALSE ;
}
}
fhCTSAODTrackCutsPt[4]->Fill(aodtrack->Pt());
//
if ( fSelectPrimaryTracks )
{
if ( aodtrack->GetType()!= AliAODTrack::kPrimary )
{
AliDebug(2,"\t Remove not primary track");
return kFALSE ;
}
}
AliDebug(2,"\t accepted track!");
fhCTSAODTrackCutsPt[5]->Fill(aodtrack->Pt());
return kTRUE;
}
//_________________________________________________________________
/// Connect the data pointers
/// If input is AOD, do analysis with input, if not, do analysis with the output aod.
//_________________________________________________________________
void AliCaloTrackAODReader::SetInputOutputMCEvent(AliVEvent* input,
AliAODEvent* aod,
AliMCEvent* mc)
{
//printf("AODInputHandler %p, MergeEvents %d \n",aodIH, aodIH->GetMergeEvents());
Bool_t tesd = kFALSE ;
Bool_t taod = kTRUE ;
if ( strcmp(input->GetName(), "AliMixedEvent") == 0 )
{
AliMultiEventInputHandler* multiEH = dynamic_cast<AliMultiEventInputHandler*>((AliAnalysisManager::GetAnalysisManager())->GetInputEventHandler());
if(multiEH){
if (multiEH->GetFormat() == 0 )
{
tesd = kTRUE ;
} else if (multiEH->GetFormat() == 1)
{
taod = kTRUE ;
}
}
else
{
AliFatal("MultiEventHandler is NULL");
return;
}
}
if (strcmp(input->GetName(),"AliESDEvent") == 0)
{
tesd = kTRUE ;
} else if (strcmp(input->GetName(),"AliAODEvent") == 0)
{
taod = kTRUE ;
}
if(tesd)
{
SetInputEvent(aod);
SetOutputEvent(aod);
fOrgInputEvent = input;
}
else if(taod)
{
AliAODInputHandler* aodIH = dynamic_cast<AliAODInputHandler*>((AliAnalysisManager::GetAnalysisManager())->GetInputEventHandler());
if (aodIH && aodIH->GetMergeEvents())
{
//Merged events, use output AOD.
SetInputEvent(aod);
SetOutputEvent(aod);
fOrgInputEvent = input;
}
else
{
SetInputEvent(input);
SetOutputEvent(aod);
}
}
else
{
AliFatal(Form("STOP : Wrong data format: %s",input->GetName()));
}
SetMC(mc);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/test/trace_event_analyzer.h"
#include "base/version.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/tracing.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/gpu/gpu_blacklist.h"
#include "content/browser/gpu/gpu_data_manager.h"
#include "net/base/net_util.h"
namespace {
class GpuFeatureTest : public InProcessBrowserTest {
public:
GpuFeatureTest() {}
virtual void SetUpCommandLine(CommandLine* command_line) {
// This enables DOM automation for tab contents.
EnableDOMAutomation();
}
void SetupBlacklist(const std::string& json_blacklist) {
scoped_ptr<Version> os_version(Version::GetVersionFromString("1.0"));
GpuBlacklist* blacklist = new GpuBlacklist("1.0");
ASSERT_TRUE(blacklist->LoadGpuBlacklist(
json_blacklist, GpuBlacklist::kAllOs));
GpuDataManager::GetInstance()->SetBuiltInGpuBlacklist(blacklist);
}
void RunTest(const FilePath& url, bool expect_gpu_process) {
using namespace trace_analyzer;
FilePath test_path;
PathService::Get(chrome::DIR_TEST_DATA, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("gpu"));
test_path = test_path.Append(url);
ASSERT_TRUE(file_util::PathExists(test_path))
<< "Missing test file: " << test_path.value();
ASSERT_TRUE(tracing::BeginTracing("test_gpu"));
ui_test_utils::DOMMessageQueue message_queue;
// Have to use a new tab for the blacklist to work.
ui_test_utils::NavigateToURLWithDisposition(
browser(), net::FilePathToFileURL(test_path), NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_NONE);
// Wait for message indicating the test has finished running.
ASSERT_TRUE(message_queue.WaitForMessage(NULL));
std::string json_events;
ASSERT_TRUE(tracing::EndTracing(&json_events));
scoped_ptr<TraceAnalyzer> analyzer(TraceAnalyzer::Create(json_events));
EXPECT_EQ(expect_gpu_process, analyzer->FindOneEvent(
Query(EVENT_NAME) == Query::String("GpuProcessLaunched")) != NULL);
}
};
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingAllowed) {
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(flags.flags(), 0u);
const bool expect_gpu_process = true;
const FilePath url(FILE_PATH_LITERAL("feature_compositing.html"));
RunTest(url, expect_gpu_process);
}
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingBlocked) {
const std::string json_blacklist =
"{\n"
" \"name\": \"gpu blacklist\",\n"
" \"version\": \"1.0\",\n"
" \"entries\": [\n"
" {\n"
" \"id\": 1,\n"
" \"blacklist\": [\n"
" \"accelerated_compositing\"\n"
" ]\n"
" }\n"
" ]\n"
"}";
SetupBlacklist(json_blacklist);
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(
flags.flags(),
static_cast<uint32>(GpuFeatureFlags::kGpuFeatureAcceleratedCompositing));
const bool expect_gpu_process = false;
const FilePath url(FILE_PATH_LITERAL("feature_compositing.html"));
RunTest(url, expect_gpu_process);
}
#if defined(OS_LINUX)
// http://crbug.com/104142
#define WebGLAllowed FLAKY_WebGLAllowed
#endif
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLAllowed) {
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(flags.flags(), 0u);
const bool expect_gpu_process = true;
const FilePath url(FILE_PATH_LITERAL("feature_webgl.html"));
RunTest(url, expect_gpu_process);
}
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLBlocked) {
const std::string json_blacklist =
"{\n"
" \"name\": \"gpu blacklist\",\n"
" \"version\": \"1.0\",\n"
" \"entries\": [\n"
" {\n"
" \"id\": 1,\n"
" \"blacklist\": [\n"
" \"webgl\"\n"
" ]\n"
" }\n"
" ]\n"
"}";
SetupBlacklist(json_blacklist);
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(
flags.flags(),
static_cast<uint32>(GpuFeatureFlags::kGpuFeatureWebgl));
const bool expect_gpu_process = false;
const FilePath url(FILE_PATH_LITERAL("feature_webgl.html"));
RunTest(url, expect_gpu_process);
}
#if defined(OS_LINUX)
// http://crbug.com/104142
#define Canvas2DAllowed FLAKY_Canvas2DAllowed
#endif
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, Canvas2DAllowed) {
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(flags.flags(), 0u);
#if defined(OS_MACOSX)
// TODO(zmo): enabling Mac when skia backend is enabled.
const bool expect_gpu_process = false;
#else
const bool expect_gpu_process = true;
#endif
const FilePath url(FILE_PATH_LITERAL("feature_canvas2d.html"));
RunTest(url, expect_gpu_process);
}
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, Canvas2DBlocked) {
const std::string json_blacklist =
"{\n"
" \"name\": \"gpu blacklist\",\n"
" \"version\": \"1.0\",\n"
" \"entries\": [\n"
" {\n"
" \"id\": 1,\n"
" \"blacklist\": [\n"
" \"accelerated_2d_canvas\"\n"
" ]\n"
" }\n"
" ]\n"
"}";
SetupBlacklist(json_blacklist);
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(
flags.flags(),
static_cast<uint32>(GpuFeatureFlags::kGpuFeatureAccelerated2dCanvas));
const bool expect_gpu_process = false;
const FilePath url(FILE_PATH_LITERAL("feature_canvas2d.html"));
RunTest(url, expect_gpu_process);
}
} // namespace anonymous
<commit_msg>Mark GpuFeatureTest.WebGLAlloweda as DISABLED_ on Linux, as it crashes/times out<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/test/trace_event_analyzer.h"
#include "base/version.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/tracing.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/gpu/gpu_blacklist.h"
#include "content/browser/gpu/gpu_data_manager.h"
#include "net/base/net_util.h"
namespace {
class GpuFeatureTest : public InProcessBrowserTest {
public:
GpuFeatureTest() {}
virtual void SetUpCommandLine(CommandLine* command_line) {
// This enables DOM automation for tab contents.
EnableDOMAutomation();
}
void SetupBlacklist(const std::string& json_blacklist) {
scoped_ptr<Version> os_version(Version::GetVersionFromString("1.0"));
GpuBlacklist* blacklist = new GpuBlacklist("1.0");
ASSERT_TRUE(blacklist->LoadGpuBlacklist(
json_blacklist, GpuBlacklist::kAllOs));
GpuDataManager::GetInstance()->SetBuiltInGpuBlacklist(blacklist);
}
void RunTest(const FilePath& url, bool expect_gpu_process) {
using namespace trace_analyzer;
FilePath test_path;
PathService::Get(chrome::DIR_TEST_DATA, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("gpu"));
test_path = test_path.Append(url);
ASSERT_TRUE(file_util::PathExists(test_path))
<< "Missing test file: " << test_path.value();
ASSERT_TRUE(tracing::BeginTracing("test_gpu"));
ui_test_utils::DOMMessageQueue message_queue;
// Have to use a new tab for the blacklist to work.
ui_test_utils::NavigateToURLWithDisposition(
browser(), net::FilePathToFileURL(test_path), NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_NONE);
// Wait for message indicating the test has finished running.
ASSERT_TRUE(message_queue.WaitForMessage(NULL));
std::string json_events;
ASSERT_TRUE(tracing::EndTracing(&json_events));
scoped_ptr<TraceAnalyzer> analyzer(TraceAnalyzer::Create(json_events));
EXPECT_EQ(expect_gpu_process, analyzer->FindOneEvent(
Query(EVENT_NAME) == Query::String("GpuProcessLaunched")) != NULL);
}
};
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingAllowed) {
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(flags.flags(), 0u);
const bool expect_gpu_process = true;
const FilePath url(FILE_PATH_LITERAL("feature_compositing.html"));
RunTest(url, expect_gpu_process);
}
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingBlocked) {
const std::string json_blacklist =
"{\n"
" \"name\": \"gpu blacklist\",\n"
" \"version\": \"1.0\",\n"
" \"entries\": [\n"
" {\n"
" \"id\": 1,\n"
" \"blacklist\": [\n"
" \"accelerated_compositing\"\n"
" ]\n"
" }\n"
" ]\n"
"}";
SetupBlacklist(json_blacklist);
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(
flags.flags(),
static_cast<uint32>(GpuFeatureFlags::kGpuFeatureAcceleratedCompositing));
const bool expect_gpu_process = false;
const FilePath url(FILE_PATH_LITERAL("feature_compositing.html"));
RunTest(url, expect_gpu_process);
}
#if defined(OS_LINUX)
// http://crbug.com/104142
#define MAYBE_WebGLAllowed DISABLED_WebGLAllowed
#else
#define MAYBE_WebGLAllowed WebGLAllowed
#endif
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, MAYBE_WebGLAllowed) {
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(flags.flags(), 0u);
const bool expect_gpu_process = true;
const FilePath url(FILE_PATH_LITERAL("feature_webgl.html"));
RunTest(url, expect_gpu_process);
}
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLBlocked) {
const std::string json_blacklist =
"{\n"
" \"name\": \"gpu blacklist\",\n"
" \"version\": \"1.0\",\n"
" \"entries\": [\n"
" {\n"
" \"id\": 1,\n"
" \"blacklist\": [\n"
" \"webgl\"\n"
" ]\n"
" }\n"
" ]\n"
"}";
SetupBlacklist(json_blacklist);
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(
flags.flags(),
static_cast<uint32>(GpuFeatureFlags::kGpuFeatureWebgl));
const bool expect_gpu_process = false;
const FilePath url(FILE_PATH_LITERAL("feature_webgl.html"));
RunTest(url, expect_gpu_process);
}
#if defined(OS_LINUX)
// http://crbug.com/104142
#define Canvas2DAllowed FLAKY_Canvas2DAllowed
#endif
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, Canvas2DAllowed) {
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(flags.flags(), 0u);
#if defined(OS_MACOSX)
// TODO(zmo): enabling Mac when skia backend is enabled.
const bool expect_gpu_process = false;
#else
const bool expect_gpu_process = true;
#endif
const FilePath url(FILE_PATH_LITERAL("feature_canvas2d.html"));
RunTest(url, expect_gpu_process);
}
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, Canvas2DBlocked) {
const std::string json_blacklist =
"{\n"
" \"name\": \"gpu blacklist\",\n"
" \"version\": \"1.0\",\n"
" \"entries\": [\n"
" {\n"
" \"id\": 1,\n"
" \"blacklist\": [\n"
" \"accelerated_2d_canvas\"\n"
" ]\n"
" }\n"
" ]\n"
"}";
SetupBlacklist(json_blacklist);
GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
EXPECT_EQ(
flags.flags(),
static_cast<uint32>(GpuFeatureFlags::kGpuFeatureAccelerated2dCanvas));
const bool expect_gpu_process = false;
const FilePath url(FILE_PATH_LITERAL("feature_canvas2d.html"));
RunTest(url, expect_gpu_process);
}
} // namespace anonymous
<|endoftext|> |
<commit_before>#ifndef BEATWAVE_EMPTYCIRCLE_HPP_
#define BEATWAVE_EMPTYCIRCLE_HPP_
#include <core/animatedgroup.hpp>
class EmptyCircle: public AnimatedGroup<float, sf::Vector2f, sf::Color>
{
public:
enum Property
{
Radius = 0,
Position,
Color
};
using AnimatedGroup::AnimatedGroup;
void render(sf::RenderTarget *renderTarget) const
{
auto radius = value<Radius>();
sf::CircleShape circle(radius);
circle.setOutlineColor(value<Color>());
circle.setOutlineThickness(1.0f);
circle.setFillColor(sf::Color::Transparent);
circle.setPosition(value<Position>() - sf::Vector2f(radius, radius));
renderTarget->draw(circle);
}
};
#endif // BEATWAVE_EMPTYCIRCLE_HPP_
<commit_msg>Add thickness to EmptyCirce (#126)<commit_after>#ifndef BEATWAVE_EMPTYCIRCLE_HPP_
#define BEATWAVE_EMPTYCIRCLE_HPP_
#include <core/animatedgroup.hpp>
class EmptyCircle: public AnimatedGroup<float, sf::Vector2f, sf::Color, float>
{
public:
enum Property
{
Radius = 0,
Position,
Color,
Thickness
};
using AnimatedGroup::AnimatedGroup;
void render(sf::RenderTarget *renderTarget) const
{
auto radius = value<Radius>();
sf::CircleShape circle(radius);
circle.setOutlineColor(value<Color>());
circle.setOutlineThickness(value<Thickness>());
circle.setFillColor(sf::Color::Transparent);
circle.setPosition(value<Position>() - sf::Vector2f(radius, radius));
renderTarget->draw(circle);
}
};
#endif // BEATWAVE_EMPTYCIRCLE_HPP_
<|endoftext|> |
<commit_before>// Copyright (c) 2012-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <interfaces/chain.h>
#include <node/context.h>
#include <optional.h>
#include <test/util/mining.h>
#include <test/util/setup_common.h>
#include <test/util/wallet.h>
#include <validationinterface.h>
#include <wallet/wallet.h>
static void WalletBalance(benchmark::State& state, const bool set_dirty, const bool add_watchonly, const bool add_mine)
{
const auto& ADDRESS_WATCHONLY = ADDRESS_BCRT1_UNSPENDABLE;
NodeContext node;
std::unique_ptr<interfaces::Chain> chain = interfaces::MakeChain(node);
CWallet wallet{chain.get(), WalletLocation(), WalletDatabase::CreateMock()};
{
wallet.SetupLegacyScriptPubKeyMan();
bool first_run;
if (wallet.LoadWallet(first_run) != DBErrors::LOAD_OK) assert(false);
}
auto handler = chain->handleNotifications({ &wallet, [](CWallet*) {} });
const Optional<std::string> address_mine{add_mine ? Optional<std::string>{getnewaddress(wallet)} : nullopt};
if (add_watchonly) importaddress(wallet, ADDRESS_WATCHONLY);
for (int i = 0; i < 600; ++i) {
generatetoaddress(g_testing_setup->m_node, address_mine.get_value_or(ADDRESS_WATCHONLY));
generatetoaddress(g_testing_setup->m_node, ADDRESS_WATCHONLY);
}
SyncWithValidationInterfaceQueue();
auto bal = wallet.GetBalance(); // Cache
while (state.KeepRunning()) {
if (set_dirty) wallet.MarkDirty();
bal = wallet.GetBalance();
if (add_mine) assert(bal.m_mine_trusted > 0);
if (add_watchonly) assert(bal.m_watchonly_trusted > 0);
}
}
static void WalletBalanceDirty(benchmark::State& state) { WalletBalance(state, /* set_dirty */ true, /* add_watchonly */ true, /* add_mine */ true); }
static void WalletBalanceClean(benchmark::State& state) { WalletBalance(state, /* set_dirty */ false, /* add_watchonly */ true, /* add_mine */ true); }
static void WalletBalanceMine(benchmark::State& state) { WalletBalance(state, /* set_dirty */ false, /* add_watchonly */ false, /* add_mine */ true); }
static void WalletBalanceWatch(benchmark::State& state) { WalletBalance(state, /* set_dirty */ false, /* add_watchonly */ true, /* add_mine */ false); }
BENCHMARK(WalletBalanceDirty, 2500);
BENCHMARK(WalletBalanceClean, 8000);
BENCHMARK(WalletBalanceMine, 16000);
BENCHMARK(WalletBalanceWatch, 8000);
<commit_msg>Fix bench balance test<commit_after>// Copyright (c) 2012-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <interfaces/chain.h>
#include <node/context.h>
#include <optional.h>
#include <test/util/mining.h>
#include <test/util/setup_common.h>
#include <test/util/wallet.h>
#include <validationinterface.h>
#include <wallet/wallet.h>
static void WalletBalance(benchmark::State& state, const bool set_dirty, const bool add_watchonly, const bool add_mine)
{
const auto& ADDRESS_WATCHONLY = ADDRESS_BCRT1_UNSPENDABLE;
NodeContext node;
std::unique_ptr<interfaces::Chain> chain = interfaces::MakeChain(node);
CWallet wallet{chain.get(), WalletLocation(), WalletDatabase::CreateMock()};
{
wallet.SetupLegacyScriptPubKeyMan();
bool first_run;
if (wallet.LoadWallet(first_run) != DBErrors::LOAD_OK) assert(false);
}
auto handler = chain->handleNotifications({ &wallet, [](CWallet*) {} });
const Optional<std::string> address_mine{add_mine ? Optional<std::string>{getnewaddress(wallet)} : nullopt};
if (add_watchonly) importaddress(wallet, ADDRESS_WATCHONLY);
int blockCount = Params().GetConsensus().CoinbaseMaturity(0) + 100;
for (int i = 0; i < blockCount; ++i) {
generatetoaddress(g_testing_setup->m_node, address_mine.get_value_or(ADDRESS_WATCHONLY));
generatetoaddress(g_testing_setup->m_node, ADDRESS_WATCHONLY);
}
SyncWithValidationInterfaceQueue();
auto bal = wallet.GetBalance(); // Cache
while (state.KeepRunning()) {
if (set_dirty) wallet.MarkDirty();
bal = wallet.GetBalance();
if (add_mine) assert(bal.m_mine_trusted > 0);
if (add_watchonly) assert(bal.m_watchonly_trusted > 0);
}
}
static void WalletBalanceDirty(benchmark::State& state) { WalletBalance(state, /* set_dirty */ true, /* add_watchonly */ true, /* add_mine */ true); }
static void WalletBalanceClean(benchmark::State& state) { WalletBalance(state, /* set_dirty */ false, /* add_watchonly */ true, /* add_mine */ true); }
static void WalletBalanceMine(benchmark::State& state) { WalletBalance(state, /* set_dirty */ false, /* add_watchonly */ false, /* add_mine */ true); }
static void WalletBalanceWatch(benchmark::State& state) { WalletBalance(state, /* set_dirty */ false, /* add_watchonly */ true, /* add_mine */ false); }
BENCHMARK(WalletBalanceDirty, 2500);
BENCHMARK(WalletBalanceClean, 8000);
BENCHMARK(WalletBalanceMine, 16000);
BENCHMARK(WalletBalanceWatch, 8000);
<|endoftext|> |
<commit_before>// Copyright (c) 2022 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <interfaces/chain.h>
#include <node/context.h>
#include <test/util/mining.h>
#include <test/util/setup_common.h>
#include <test/util/wallet.h>
#include <util/translation.h>
#include <validationinterface.h>
#include <wallet/context.h>
#include <wallet/receive.h>
#include <wallet/wallet.h>
#include <optional>
using wallet::CWallet;
using wallet::DatabaseOptions;
using wallet::DatabaseStatus;
using wallet::ISMINE_SPENDABLE;
using wallet::MakeWalletDatabase;
using wallet::WALLET_FLAG_DESCRIPTORS;
using wallet::WalletContext;
static const std::shared_ptr<CWallet> BenchLoadWallet(WalletContext& context, DatabaseOptions& options)
{
DatabaseStatus status;
bilingual_str error;
std::vector<bilingual_str> warnings;
auto database = MakeWalletDatabase("", options, status, error);
assert(database);
auto wallet = CWallet::Create(context, "", std::move(database), options.create_flags, error, warnings);
NotifyWalletLoaded(context, wallet);
if (context.chain) {
wallet->postInitProcess();
}
return wallet;
}
static void BenchUnloadWallet(std::shared_ptr<CWallet>&& wallet)
{
SyncWithValidationInterfaceQueue();
wallet->m_chain_notifications_handler.reset();
UnloadWallet(std::move(wallet));
}
static void WalletLoading(benchmark::Bench& bench, bool legacy_wallet)
{
const auto test_setup = MakeNoLogFileContext<TestingSetup>();
WalletContext context;
context.args = &test_setup->m_args;
context.chain = test_setup->m_node.chain.get();
// Setup the wallet
// Loading the wallet will also create it
DatabaseOptions options;
if (!legacy_wallet) options.create_flags = WALLET_FLAG_DESCRIPTORS;
auto wallet = BenchLoadWallet(context, options);
// Generate a bunch of transactions and addresses to put into the wallet
for (int i = 0; i < 5000; ++i) {
generatetoaddress(test_setup->m_node, getnewaddress(*wallet));
}
// reload the wallet for the actual benchmark
BenchUnloadWallet(std::move(wallet));
bench.run([&] {
wallet = BenchLoadWallet(context, options);
// Cleanup
BenchUnloadWallet(std::move(wallet));
});
}
static void WalletLoadingLegacy(benchmark::Bench& bench) { WalletLoading(bench, /*legacy_wallet=*/true); }
static void WalletLoadingDescriptors(benchmark::Bench& bench) { WalletLoading(bench, /*legacy_wallet=*/false); }
BENCHMARK(WalletLoadingLegacy);
BENCHMARK(WalletLoadingDescriptors);
<commit_msg>bench: use unsafesqlitesync in wallet loading benchmark<commit_after>// Copyright (c) 2022 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <interfaces/chain.h>
#include <node/context.h>
#include <test/util/mining.h>
#include <test/util/setup_common.h>
#include <test/util/wallet.h>
#include <util/translation.h>
#include <validationinterface.h>
#include <wallet/context.h>
#include <wallet/receive.h>
#include <wallet/wallet.h>
#include <optional>
using wallet::CWallet;
using wallet::DatabaseOptions;
using wallet::DatabaseStatus;
using wallet::ISMINE_SPENDABLE;
using wallet::MakeWalletDatabase;
using wallet::WALLET_FLAG_DESCRIPTORS;
using wallet::WalletContext;
static const std::shared_ptr<CWallet> BenchLoadWallet(WalletContext& context, DatabaseOptions& options)
{
DatabaseStatus status;
bilingual_str error;
std::vector<bilingual_str> warnings;
auto database = MakeWalletDatabase("", options, status, error);
assert(database);
auto wallet = CWallet::Create(context, "", std::move(database), options.create_flags, error, warnings);
NotifyWalletLoaded(context, wallet);
if (context.chain) {
wallet->postInitProcess();
}
return wallet;
}
static void BenchUnloadWallet(std::shared_ptr<CWallet>&& wallet)
{
SyncWithValidationInterfaceQueue();
wallet->m_chain_notifications_handler.reset();
UnloadWallet(std::move(wallet));
}
static void WalletLoading(benchmark::Bench& bench, bool legacy_wallet)
{
const auto test_setup = MakeNoLogFileContext<TestingSetup>();
test_setup->m_args.ForceSetArg("-unsafesqlitesync", "1");
WalletContext context;
context.args = &test_setup->m_args;
context.chain = test_setup->m_node.chain.get();
// Setup the wallet
// Loading the wallet will also create it
DatabaseOptions options;
if (!legacy_wallet) options.create_flags = WALLET_FLAG_DESCRIPTORS;
auto wallet = BenchLoadWallet(context, options);
// Generate a bunch of transactions and addresses to put into the wallet
for (int i = 0; i < 5000; ++i) {
generatetoaddress(test_setup->m_node, getnewaddress(*wallet));
}
// reload the wallet for the actual benchmark
BenchUnloadWallet(std::move(wallet));
bench.run([&] {
wallet = BenchLoadWallet(context, options);
// Cleanup
BenchUnloadWallet(std::move(wallet));
});
}
static void WalletLoadingLegacy(benchmark::Bench& bench) { WalletLoading(bench, /*legacy_wallet=*/true); }
static void WalletLoadingDescriptors(benchmark::Bench& bench) { WalletLoading(bench, /*legacy_wallet=*/false); }
BENCHMARK(WalletLoadingLegacy);
BENCHMARK(WalletLoadingDescriptors);
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "msvcinfo.h"
#include <tools/error.h>
#include <tools/profile.h>
#include <tools/stringconstants.h>
#include <QtCore/qbytearray.h>
#include <QtCore/qdir.h>
#include <QtCore/qprocess.h>
#include <QtCore/qstringlist.h>
#include <QtCore/qtemporaryfile.h>
#ifdef Q_OS_WIN
#include <QtCore/qt_windows.h>
#endif
#include <algorithm>
#include <mutex>
using namespace qbs;
using namespace qbs::Internal;
static std::recursive_mutex envMutex;
static QString mkStr(const char *s) { return QString::fromLocal8Bit(s); }
static QString mkStr(const QByteArray &ba) { return mkStr(ba.constData()); }
class TemporaryEnvChanger
{
public:
TemporaryEnvChanger(const QProcessEnvironment &envChanges) : m_locker(envMutex)
{
QProcessEnvironment currentEnv = QProcessEnvironment::systemEnvironment();
const auto keys = envChanges.keys();
for (const QString &key : keys) {
m_changesToRestore.insert(key, currentEnv.value(key));
qputenv(qPrintable(key), qPrintable(envChanges.value(key)));
}
}
~TemporaryEnvChanger()
{
const auto keys = m_changesToRestore.keys();
for (const QString &key : keys)
qputenv(qPrintable(key), qPrintable(m_changesToRestore.value(key)));
}
private:
QProcessEnvironment m_changesToRestore;
std::lock_guard<std::recursive_mutex> m_locker;
};
static QByteArray runProcess(const QString &exeFilePath, const QStringList &args,
const QProcessEnvironment &env = QProcessEnvironment(),
bool allowFailure = false,
const QByteArray &pipeData = QByteArray())
{
TemporaryEnvChanger envChanger(env);
QProcess process;
process.start(exeFilePath, args);
if (!process.waitForStarted())
throw ErrorInfo(mkStr("Could not start %1 (%2)").arg(exeFilePath, process.errorString()));
if (!pipeData.isEmpty()) {
process.write(pipeData);
process.closeWriteChannel();
}
if (!process.waitForFinished(-1) || process.exitStatus() != QProcess::NormalExit)
throw ErrorInfo(mkStr("Could not run %1 (%2)").arg(exeFilePath, process.errorString()));
if (process.exitCode() != 0 && !allowFailure) {
ErrorInfo e(mkStr("Process '%1' failed with exit code %2.")
.arg(exeFilePath).arg(process.exitCode()));
const QByteArray stdErr = process.readAllStandardError();
if (!stdErr.isEmpty())
e.append(mkStr("stderr was: %1").arg(mkStr(stdErr)));
const QByteArray stdOut = process.readAllStandardOutput();
if (!stdOut.isEmpty())
e.append(mkStr("stdout was: %1").arg(mkStr(stdOut)));
throw e;
}
return process.readAllStandardOutput().trimmed();
}
class DummyFile {
public:
DummyFile(QString fp) : filePath(std::move(fp)) { }
~DummyFile() { QFile::remove(filePath); }
const QString filePath;
};
#ifdef Q_OS_WIN
static QStringList parseCommandLine(const QString &commandLine)
{
QStringList list;
const auto buf = new wchar_t[commandLine.size() + 1];
buf[commandLine.toWCharArray(buf)] = 0;
int argCount = 0;
LPWSTR *args = CommandLineToArgvW(buf, &argCount);
if (!args)
throw ErrorInfo(mkStr("Could not parse command line arguments: ") + commandLine);
for (int i = 0; i < argCount; ++i)
list.push_back(QString::fromWCharArray(args[i]));
delete[] buf;
return list;
}
#endif
static QVariantMap getMsvcDefines(const QString &compilerFilePath,
const QProcessEnvironment &compilerEnv,
MSVC::CompilerLanguage language)
{
#ifdef Q_OS_WIN
QString backendSwitch, languageSwitch;
switch (language) {
case MSVC::CLanguage:
backendSwitch = QStringLiteral("/B1");
languageSwitch = QStringLiteral("/TC");
break;
case MSVC::CPlusPlusLanguage:
backendSwitch = QStringLiteral("/Bx");
languageSwitch = QStringLiteral("/TP");
break;
}
const QByteArray commands("set MSC_CMD_FLAGS\n");
QStringList out = QString::fromLocal8Bit(runProcess(compilerFilePath, QStringList()
<< QStringLiteral("/nologo")
<< backendSwitch
<< qEnvironmentVariable("COMSPEC")
<< QStringLiteral("/c")
<< languageSwitch
<< QStringLiteral("NUL"),
compilerEnv, true, commands)).split(QLatin1Char('\n'));
auto findResult = std::find_if(out.cbegin(), out.cend(), [] (const QString &line) {
return line.startsWith(QLatin1String("MSC_CMD_FLAGS="));
});
if (findResult == out.cend()) {
throw ErrorInfo(QStringLiteral("Unexpected compiler frontend output: ")
+ out.join(QLatin1Char('\n')));
}
QVariantMap map;
const QStringList args = parseCommandLine(findResult->trimmed());
for (const QString &arg : args) {
if (!arg.startsWith(QStringLiteral("-D")))
continue;
int idx = arg.indexOf(QLatin1Char('='), 2);
if (idx > 2)
map.insert(arg.mid(2, idx - 2), arg.mid(idx + 1));
else
map.insert(arg.mid(2), QVariant());
}
return map;
#else
Q_UNUSED(compilerFilePath);
Q_UNUSED(compilerEnv);
Q_UNUSED(language);
return {};
#endif
}
/*!
\internal
clang-cl does not support gcc and msvc ways to dump a macros, so we have to use original
clang.exe directly
*/
static QVariantMap getClangClDefines(
const QString &compilerFilePath,
const QProcessEnvironment &compilerEnv,
MSVC::CompilerLanguage language)
{
#ifdef Q_OS_WIN
QFileInfo clInfo(compilerFilePath);
QFileInfo clangInfo(clInfo.absolutePath() + QLatin1String("/clang.exe"));
if (!clangInfo.exists())
throw ErrorInfo(QStringLiteral("%1 does not exist").arg(clangInfo.absoluteFilePath()));
QString languageSwitch;
switch (language) {
case MSVC::CLanguage:
languageSwitch = QStringLiteral("c");
break;
case MSVC::CPlusPlusLanguage:
languageSwitch = QStringLiteral("c++");
break;
}
QStringList args = {
QStringLiteral("-dM"),
QStringLiteral("-E"),
QStringLiteral("-x"),
languageSwitch,
QStringLiteral("NUL"),
};
const auto lines = QString::fromLocal8Bit(
runProcess(
clangInfo.absoluteFilePath(),
args,
compilerEnv,
true)).split(QLatin1Char('\n'));
QVariantMap result;
for (const auto &line: lines) {
static const auto defineString = QLatin1String("#define ");
if (!line.startsWith(defineString)) {
throw ErrorInfo(QStringLiteral("Unexpected compiler frontend output: ")
+ lines.join(QLatin1Char('\n')));
}
QStringView view(line.data() + defineString.size());
const auto it = std::find(view.begin(), view.end(), QLatin1Char(' '));
if (it == view.end()) {
throw ErrorInfo(QStringLiteral("Unexpected compiler frontend output: ")
+ lines.join(QLatin1Char('\n')));
}
QStringView key(view.begin(), it);
QStringView value(it + 1, view.end());
result.insert(key.toString(), value.isEmpty() ? QVariant() : QVariant(value.toString()));
}
return result;
#else
Q_UNUSED(compilerFilePath);
Q_UNUSED(compilerEnv);
Q_UNUSED(language);
return {};
#endif
}
void MSVC::init()
{
determineCompilerVersion();
}
/*!
\internal
Returns the architecture detected from the compiler path.
*/
QString MSVC::architectureFromClPath(const QString &clPath)
{
const auto parentDir = QFileInfo(clPath).absolutePath();
const auto parentDirName = QFileInfo(parentDir).fileName().toLower();
if (parentDirName == QLatin1String("bin"))
return QStringLiteral("x86");
return parentDirName;
}
QString MSVC::binPathForArchitecture(const QString &arch) const
{
QString archSubDir;
if (arch != StringConstants::x86Arch())
archSubDir = arch;
return QDir::cleanPath(vcInstallPath + QLatin1Char('/') + pathPrefix + QLatin1Char('/')
+ archSubDir);
}
static QString clExeSuffix() { return QStringLiteral("/cl.exe"); }
QString MSVC::clPathForArchitecture(const QString &arch) const
{
return binPathForArchitecture(arch) + clExeSuffix();
}
QVariantMap MSVC::compilerDefines(const QString &compilerFilePath,
MSVC::CompilerLanguage language) const
{
const auto compilerName = QFileInfo(compilerFilePath).fileName().toLower();
if (compilerName == QLatin1String("clang-cl.exe"))
return getClangClDefines(compilerFilePath, environment, language);
return getMsvcDefines(compilerFilePath, environment, language);
}
void MSVC::determineCompilerVersion()
{
QString cppFilePath;
{
QTemporaryFile cppFile(QDir::tempPath() + QLatin1String("/qbsXXXXXX.cpp"));
cppFile.setAutoRemove(false);
if (!cppFile.open()) {
throw ErrorInfo(mkStr("Could not create temporary file (%1)")
.arg(cppFile.errorString()));
}
cppFilePath = cppFile.fileName();
cppFile.write("_MSC_FULL_VER");
cppFile.close();
}
DummyFile fileDeleter(cppFilePath);
std::lock_guard<std::recursive_mutex> locker(envMutex);
const QByteArray origPath = qgetenv("PATH");
qputenv("PATH", environment.value(StringConstants::pathEnvVar()).toLatin1() + ';' + origPath);
QByteArray versionStr = runProcess(
binPath + clExeSuffix(),
QStringList() << QStringLiteral("/nologo") << QStringLiteral("/EP")
<< QDir::toNativeSeparators(cppFilePath));
qputenv("PATH", origPath);
compilerVersion = Version(versionStr.mid(0, 2).toInt(), versionStr.mid(2, 2).toInt(),
versionStr.mid(4).toInt());
}
<commit_msg>Fix parseCommandLine() function<commit_after>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "msvcinfo.h"
#include <tools/error.h>
#include <tools/profile.h>
#include <tools/stringconstants.h>
#include <QtCore/qbytearray.h>
#include <QtCore/qdir.h>
#include <QtCore/qprocess.h>
#include <QtCore/qstringlist.h>
#include <QtCore/qtemporaryfile.h>
#ifdef Q_OS_WIN
#include <QtCore/qt_windows.h>
#endif
#include <algorithm>
#include <memory>
#include <mutex>
using namespace qbs;
using namespace qbs::Internal;
static std::recursive_mutex envMutex;
static QString mkStr(const char *s) { return QString::fromLocal8Bit(s); }
static QString mkStr(const QByteArray &ba) { return mkStr(ba.constData()); }
class TemporaryEnvChanger
{
public:
TemporaryEnvChanger(const QProcessEnvironment &envChanges) : m_locker(envMutex)
{
QProcessEnvironment currentEnv = QProcessEnvironment::systemEnvironment();
const auto keys = envChanges.keys();
for (const QString &key : keys) {
m_changesToRestore.insert(key, currentEnv.value(key));
qputenv(qPrintable(key), qPrintable(envChanges.value(key)));
}
}
~TemporaryEnvChanger()
{
const auto keys = m_changesToRestore.keys();
for (const QString &key : keys)
qputenv(qPrintable(key), qPrintable(m_changesToRestore.value(key)));
}
private:
QProcessEnvironment m_changesToRestore;
std::lock_guard<std::recursive_mutex> m_locker;
};
static QByteArray runProcess(const QString &exeFilePath, const QStringList &args,
const QProcessEnvironment &env = QProcessEnvironment(),
bool allowFailure = false,
const QByteArray &pipeData = QByteArray())
{
TemporaryEnvChanger envChanger(env);
QProcess process;
process.start(exeFilePath, args);
if (!process.waitForStarted())
throw ErrorInfo(mkStr("Could not start %1 (%2)").arg(exeFilePath, process.errorString()));
if (!pipeData.isEmpty()) {
process.write(pipeData);
process.closeWriteChannel();
}
if (!process.waitForFinished(-1) || process.exitStatus() != QProcess::NormalExit)
throw ErrorInfo(mkStr("Could not run %1 (%2)").arg(exeFilePath, process.errorString()));
if (process.exitCode() != 0 && !allowFailure) {
ErrorInfo e(mkStr("Process '%1' failed with exit code %2.")
.arg(exeFilePath).arg(process.exitCode()));
const QByteArray stdErr = process.readAllStandardError();
if (!stdErr.isEmpty())
e.append(mkStr("stderr was: %1").arg(mkStr(stdErr)));
const QByteArray stdOut = process.readAllStandardOutput();
if (!stdOut.isEmpty())
e.append(mkStr("stdout was: %1").arg(mkStr(stdOut)));
throw e;
}
return process.readAllStandardOutput().trimmed();
}
class DummyFile {
public:
DummyFile(QString fp) : filePath(std::move(fp)) { }
~DummyFile() { QFile::remove(filePath); }
const QString filePath;
};
#ifdef Q_OS_WIN
static QStringList parseCommandLine(const QString &commandLine)
{
const auto buf = std::make_unique<wchar_t[]>(size_t(commandLine.size()) + 1);
buf[size_t(commandLine.toWCharArray(buf.get()))] = 0;
int argCount = 0;
const auto argsDeleter = [](LPWSTR *p){ LocalFree(p); };
const auto args = std::unique_ptr<LPWSTR[], decltype(argsDeleter)>(
CommandLineToArgvW(buf.get(), &argCount), argsDeleter);
if (!args)
throw ErrorInfo(mkStr("Could not parse command line arguments: ") + commandLine);
QStringList list;
list.reserve(argCount);
for (int i = 0; i < argCount; ++i)
list.push_back(QString::fromWCharArray(args[size_t(i)]));
return list;
}
#endif
static QVariantMap getMsvcDefines(const QString &compilerFilePath,
const QProcessEnvironment &compilerEnv,
MSVC::CompilerLanguage language)
{
#ifdef Q_OS_WIN
QString backendSwitch, languageSwitch;
switch (language) {
case MSVC::CLanguage:
backendSwitch = QStringLiteral("/B1");
languageSwitch = QStringLiteral("/TC");
break;
case MSVC::CPlusPlusLanguage:
backendSwitch = QStringLiteral("/Bx");
languageSwitch = QStringLiteral("/TP");
break;
}
const QByteArray commands("set MSC_CMD_FLAGS\n");
QStringList out = QString::fromLocal8Bit(runProcess(compilerFilePath, QStringList()
<< QStringLiteral("/nologo")
<< backendSwitch
<< qEnvironmentVariable("COMSPEC")
<< QStringLiteral("/c")
<< languageSwitch
<< QStringLiteral("NUL"),
compilerEnv, true, commands)).split(QLatin1Char('\n'));
auto findResult = std::find_if(out.cbegin(), out.cend(), [] (const QString &line) {
return line.startsWith(QLatin1String("MSC_CMD_FLAGS="));
});
if (findResult == out.cend()) {
throw ErrorInfo(QStringLiteral("Unexpected compiler frontend output: ")
+ out.join(QLatin1Char('\n')));
}
QVariantMap map;
const QStringList args = parseCommandLine(findResult->trimmed());
for (const QString &arg : args) {
if (!arg.startsWith(QStringLiteral("-D")))
continue;
int idx = arg.indexOf(QLatin1Char('='), 2);
if (idx > 2)
map.insert(arg.mid(2, idx - 2), arg.mid(idx + 1));
else
map.insert(arg.mid(2), QVariant());
}
return map;
#else
Q_UNUSED(compilerFilePath);
Q_UNUSED(compilerEnv);
Q_UNUSED(language);
return {};
#endif
}
/*!
\internal
clang-cl does not support gcc and msvc ways to dump a macros, so we have to use original
clang.exe directly
*/
static QVariantMap getClangClDefines(
const QString &compilerFilePath,
const QProcessEnvironment &compilerEnv,
MSVC::CompilerLanguage language)
{
#ifdef Q_OS_WIN
QFileInfo clInfo(compilerFilePath);
QFileInfo clangInfo(clInfo.absolutePath() + QLatin1String("/clang.exe"));
if (!clangInfo.exists())
throw ErrorInfo(QStringLiteral("%1 does not exist").arg(clangInfo.absoluteFilePath()));
QString languageSwitch;
switch (language) {
case MSVC::CLanguage:
languageSwitch = QStringLiteral("c");
break;
case MSVC::CPlusPlusLanguage:
languageSwitch = QStringLiteral("c++");
break;
}
QStringList args = {
QStringLiteral("-dM"),
QStringLiteral("-E"),
QStringLiteral("-x"),
languageSwitch,
QStringLiteral("NUL"),
};
const auto lines = QString::fromLocal8Bit(
runProcess(
clangInfo.absoluteFilePath(),
args,
compilerEnv,
true)).split(QLatin1Char('\n'));
QVariantMap result;
for (const auto &line: lines) {
static const auto defineString = QLatin1String("#define ");
if (!line.startsWith(defineString)) {
throw ErrorInfo(QStringLiteral("Unexpected compiler frontend output: ")
+ lines.join(QLatin1Char('\n')));
}
QStringView view(line.data() + defineString.size());
const auto it = std::find(view.begin(), view.end(), QLatin1Char(' '));
if (it == view.end()) {
throw ErrorInfo(QStringLiteral("Unexpected compiler frontend output: ")
+ lines.join(QLatin1Char('\n')));
}
QStringView key(view.begin(), it);
QStringView value(it + 1, view.end());
result.insert(key.toString(), value.isEmpty() ? QVariant() : QVariant(value.toString()));
}
return result;
#else
Q_UNUSED(compilerFilePath);
Q_UNUSED(compilerEnv);
Q_UNUSED(language);
return {};
#endif
}
void MSVC::init()
{
determineCompilerVersion();
}
/*!
\internal
Returns the architecture detected from the compiler path.
*/
QString MSVC::architectureFromClPath(const QString &clPath)
{
const auto parentDir = QFileInfo(clPath).absolutePath();
const auto parentDirName = QFileInfo(parentDir).fileName().toLower();
if (parentDirName == QLatin1String("bin"))
return QStringLiteral("x86");
return parentDirName;
}
QString MSVC::binPathForArchitecture(const QString &arch) const
{
QString archSubDir;
if (arch != StringConstants::x86Arch())
archSubDir = arch;
return QDir::cleanPath(vcInstallPath + QLatin1Char('/') + pathPrefix + QLatin1Char('/')
+ archSubDir);
}
static QString clExeSuffix() { return QStringLiteral("/cl.exe"); }
QString MSVC::clPathForArchitecture(const QString &arch) const
{
return binPathForArchitecture(arch) + clExeSuffix();
}
QVariantMap MSVC::compilerDefines(const QString &compilerFilePath,
MSVC::CompilerLanguage language) const
{
const auto compilerName = QFileInfo(compilerFilePath).fileName().toLower();
if (compilerName == QLatin1String("clang-cl.exe"))
return getClangClDefines(compilerFilePath, environment, language);
return getMsvcDefines(compilerFilePath, environment, language);
}
void MSVC::determineCompilerVersion()
{
QString cppFilePath;
{
QTemporaryFile cppFile(QDir::tempPath() + QLatin1String("/qbsXXXXXX.cpp"));
cppFile.setAutoRemove(false);
if (!cppFile.open()) {
throw ErrorInfo(mkStr("Could not create temporary file (%1)")
.arg(cppFile.errorString()));
}
cppFilePath = cppFile.fileName();
cppFile.write("_MSC_FULL_VER");
cppFile.close();
}
DummyFile fileDeleter(cppFilePath);
std::lock_guard<std::recursive_mutex> locker(envMutex);
const QByteArray origPath = qgetenv("PATH");
qputenv("PATH", environment.value(StringConstants::pathEnvVar()).toLatin1() + ';' + origPath);
QByteArray versionStr = runProcess(
binPath + clExeSuffix(),
QStringList() << QStringLiteral("/nologo") << QStringLiteral("/EP")
<< QDir::toNativeSeparators(cppFilePath));
qputenv("PATH", origPath);
compilerVersion = Version(versionStr.mid(0, 2).toInt(), versionStr.mid(2, 2).toInt(),
versionStr.mid(4).toInt());
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2010 Apple 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:
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/accessibility/AXMenuListPopup.h"
#include "core/accessibility/AXMenuListOption.h"
#include "core/accessibility/AXObjectCache.h"
#include "core/html/HTMLSelectElement.h"
namespace WebCore {
using namespace HTMLNames;
AXMenuListPopup::AXMenuListPopup()
{
}
bool AXMenuListPopup::isVisible() const
{
return false;
}
bool AXMenuListPopup::isOffScreen() const
{
if (!m_parent)
return true;
return m_parent->isCollapsed();
}
bool AXMenuListPopup::isEnabled() const
{
if (!m_parent)
return false;
return m_parent->isEnabled();
}
bool AXMenuListPopup::computeAccessibilityIsIgnored() const
{
return accessibilityIsIgnoredByDefault();
}
AXMenuListOption* AXMenuListPopup::menuListOptionAXObject(HTMLElement* element) const
{
ASSERT(element);
if (!isHTMLOptionElement(*element))
return 0;
AXObject* object = document()->axObjectCache()->getOrCreate(MenuListOptionRole);
ASSERT_WITH_SECURITY_IMPLICATION(object->isMenuListOption());
AXMenuListOption* option = toAXMenuListOption(object);
option->setElement(element);
return option;
}
bool AXMenuListPopup::press() const
{
if (!m_parent)
return false;
m_parent->press();
return true;
}
void AXMenuListPopup::addChildren()
{
if (!m_parent)
return;
Node* selectNode = m_parent->node();
if (!selectNode)
return;
m_haveChildren = true;
const WillBeHeapVector<RawPtrWillBeMember<HTMLElement> >& listItems = toHTMLSelectElement(selectNode)->listItems();
unsigned length = listItems.size();
for (unsigned i = 0; i < length; i++) {
AXMenuListOption* option = menuListOptionAXObject(listItems[i]);
if (option) {
option->setParent(this);
m_children.append(option);
}
}
}
void AXMenuListPopup::childrenChanged()
{
AXObjectCache* cache = axObjectCache();
for (size_t i = m_children.size(); i > 0 ; --i) {
AXObject* child = m_children[i - 1].get();
// FIXME: How could children end up in here that have no actionElement(), the check
// in menuListOptionAXObject would seem to prevent that.
if (child->actionElement()) {
child->detachFromParent();
cache->remove(child->axObjectID());
}
}
m_children.clear();
m_haveChildren = false;
}
void AXMenuListPopup::didUpdateActiveOption(int optionIndex)
{
// We defer creation of the children until updating the active option so that we don't
// create AXObjects for <option> elements while they're in the middle of removal.
if (!m_haveChildren)
addChildren();
ASSERT_ARG(optionIndex, optionIndex >= 0);
ASSERT_ARG(optionIndex, optionIndex < static_cast<int>(m_children.size()));
AXObjectCache* cache = axObjectCache();
RefPtr<AXObject> child = m_children[optionIndex].get();
cache->postNotification(child.get(), document(), AXObjectCache::AXFocusedUIElementChanged, true, PostSynchronously);
cache->postNotification(child.get(), document(), AXObjectCache::AXMenuListItemSelected, true, PostSynchronously);
}
} // namespace WebCore
<commit_msg>axObjectCache() can return null.<commit_after>/*
* Copyright (C) 2010 Apple 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:
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/accessibility/AXMenuListPopup.h"
#include "core/accessibility/AXMenuListOption.h"
#include "core/accessibility/AXObjectCache.h"
#include "core/html/HTMLSelectElement.h"
namespace WebCore {
using namespace HTMLNames;
AXMenuListPopup::AXMenuListPopup()
{
}
bool AXMenuListPopup::isVisible() const
{
return false;
}
bool AXMenuListPopup::isOffScreen() const
{
if (!m_parent)
return true;
return m_parent->isCollapsed();
}
bool AXMenuListPopup::isEnabled() const
{
if (!m_parent)
return false;
return m_parent->isEnabled();
}
bool AXMenuListPopup::computeAccessibilityIsIgnored() const
{
return accessibilityIsIgnoredByDefault();
}
AXMenuListOption* AXMenuListPopup::menuListOptionAXObject(HTMLElement* element) const
{
ASSERT(element);
if (!isHTMLOptionElement(*element))
return 0;
AXObject* object = document()->axObjectCache()->getOrCreate(MenuListOptionRole);
ASSERT_WITH_SECURITY_IMPLICATION(object->isMenuListOption());
AXMenuListOption* option = toAXMenuListOption(object);
option->setElement(element);
return option;
}
bool AXMenuListPopup::press() const
{
if (!m_parent)
return false;
m_parent->press();
return true;
}
void AXMenuListPopup::addChildren()
{
if (!m_parent)
return;
Node* selectNode = m_parent->node();
if (!selectNode)
return;
m_haveChildren = true;
const WillBeHeapVector<RawPtrWillBeMember<HTMLElement> >& listItems = toHTMLSelectElement(selectNode)->listItems();
unsigned length = listItems.size();
for (unsigned i = 0; i < length; i++) {
AXMenuListOption* option = menuListOptionAXObject(listItems[i]);
if (option) {
option->setParent(this);
m_children.append(option);
}
}
}
void AXMenuListPopup::childrenChanged()
{
AXObjectCache* cache = axObjectCache();
if (!cache)
return;
for (size_t i = m_children.size(); i > 0 ; --i) {
AXObject* child = m_children[i - 1].get();
// FIXME: How could children end up in here that have no actionElement(), the check
// in menuListOptionAXObject would seem to prevent that.
if (child->actionElement()) {
child->detachFromParent();
cache->remove(child->axObjectID());
}
}
m_children.clear();
m_haveChildren = false;
}
void AXMenuListPopup::didUpdateActiveOption(int optionIndex)
{
// We defer creation of the children until updating the active option so that we don't
// create AXObjects for <option> elements while they're in the middle of removal.
if (!m_haveChildren)
addChildren();
ASSERT_ARG(optionIndex, optionIndex >= 0);
ASSERT_ARG(optionIndex, optionIndex < static_cast<int>(m_children.size()));
AXObjectCache* cache = axObjectCache();
RefPtr<AXObject> child = m_children[optionIndex].get();
cache->postNotification(child.get(), document(), AXObjectCache::AXFocusedUIElementChanged, true, PostSynchronously);
cache->postNotification(child.get(), document(), AXObjectCache::AXMenuListItemSelected, true, PostSynchronously);
}
} // namespace WebCore
<|endoftext|> |
<commit_before>#include "ovkCLogManager.h"
#include <iostream>
using namespace OpenViBE;
using namespace OpenViBE::Kernel;
using namespace std;
CLogManager::CLogManager(const IKernelContext& rKernelContext)
:TKernelObject<ILogManager>(rKernelContext)
,m_eCurrentLogLevel(LogLevel_Info)
{
}
boolean CLogManager::isActive(ELogLevel eLogLevel)
{
map<ELogLevel, boolean>::iterator itLogLevel=m_vActiveLevel.find(eLogLevel);
if(itLogLevel==m_vActiveLevel.end())
{
return true;
}
return itLogLevel->second;
}
boolean CLogManager::activate(ELogLevel eLogLevel, boolean bActive)
{
m_vActiveLevel[eLogLevel]=bActive;
return true;
}
boolean CLogManager::activate(ELogLevel eStartLogLevel, ELogLevel eEndLogLevel, boolean bActive)
{
for(int i=eStartLogLevel; i<=eEndLogLevel; i++)
{
m_vActiveLevel[ELogLevel(i)]=bActive;
}
return true;
}
boolean CLogManager::activate(boolean bActive)
{
return activate(LogLevel_First, LogLevel_Last, bActive);
}
void CLogManager::log(const uint64 ui64Value)
{
logForEach<const uint64>(ui64Value);
}
void CLogManager::log(const uint32 ui32Value)
{
logForEach<const uint32>(ui32Value);
}
void CLogManager::log(const uint16 ui16Value)
{
logForEach<const uint16>(ui16Value);
}
void CLogManager::log(const uint8 ui8Value)
{
logForEach<const uint8>(ui8Value);
}
void CLogManager::log(const int64 i64Value)
{
logForEach<const int64>(i64Value);
}
void CLogManager::log(const int32 i32Value)
{
logForEach<const int32>(i32Value);
}
void CLogManager::log(const int16 i16Value)
{
logForEach<const int16>(i16Value);
}
void CLogManager::log(const int8 i8Value)
{
logForEach<const int8>(i8Value);
}
void CLogManager::log(const float64 f64Value)
{
logForEach<const float64>(f64Value);
}
void CLogManager::log(const float32 f32Value)
{
logForEach<const float32>(f32Value);
}
void CLogManager::log(const boolean bValue)
{
logForEach<const boolean>(bValue);
}
void CLogManager::log(const CIdentifier& rValue)
{
logForEach<const CIdentifier&>(rValue);
}
void CLogManager::log(const CString& rValue)
{
logForEach<const CString&>(rValue);
}
void CLogManager::log(const char* rValue)
{
logForEach<const char*>(rValue);
}
void CLogManager::log(const ELogLevel eLogLevel)
{
m_eCurrentLogLevel=eLogLevel;
logForEach<ELogLevel>(eLogLevel);
}
void CLogManager::log(const ELogColor eLogColor)
{
logForEach<ELogColor>(eLogColor);
}
boolean CLogManager::addListener(ILogListener* pListener)
{
if(pListener==NULL)
{
return false;
}
vector<ILogListener*>::iterator itLogListener=m_vListener.begin();
while(itLogListener!=m_vListener.end())
{
if((*itLogListener)==pListener)
{
return false;
}
itLogListener++;
}
m_vListener.push_back(pListener);
return true;
}
boolean CLogManager::removeListener(ILogListener* pListener)
{
boolean l_bResult=false;
vector<ILogListener*>::iterator itLogListener=m_vListener.begin();
while(itLogListener!=m_vListener.end())
{
if((*itLogListener)==pListener)
{
itLogListener=m_vListener.erase(itLogListener);
l_bResult=true;
}
}
return l_bResult;
}
<commit_msg>openvibe-kernel : * corrected bug on log manager with infinite loop when removing a log listener<commit_after>#include "ovkCLogManager.h"
#include <iostream>
using namespace OpenViBE;
using namespace OpenViBE::Kernel;
using namespace std;
CLogManager::CLogManager(const IKernelContext& rKernelContext)
:TKernelObject<ILogManager>(rKernelContext)
,m_eCurrentLogLevel(LogLevel_Info)
{
}
boolean CLogManager::isActive(ELogLevel eLogLevel)
{
map<ELogLevel, boolean>::iterator itLogLevel=m_vActiveLevel.find(eLogLevel);
if(itLogLevel==m_vActiveLevel.end())
{
return true;
}
return itLogLevel->second;
}
boolean CLogManager::activate(ELogLevel eLogLevel, boolean bActive)
{
m_vActiveLevel[eLogLevel]=bActive;
return true;
}
boolean CLogManager::activate(ELogLevel eStartLogLevel, ELogLevel eEndLogLevel, boolean bActive)
{
for(int i=eStartLogLevel; i<=eEndLogLevel; i++)
{
m_vActiveLevel[ELogLevel(i)]=bActive;
}
return true;
}
boolean CLogManager::activate(boolean bActive)
{
return activate(LogLevel_First, LogLevel_Last, bActive);
}
void CLogManager::log(const uint64 ui64Value)
{
logForEach<const uint64>(ui64Value);
}
void CLogManager::log(const uint32 ui32Value)
{
logForEach<const uint32>(ui32Value);
}
void CLogManager::log(const uint16 ui16Value)
{
logForEach<const uint16>(ui16Value);
}
void CLogManager::log(const uint8 ui8Value)
{
logForEach<const uint8>(ui8Value);
}
void CLogManager::log(const int64 i64Value)
{
logForEach<const int64>(i64Value);
}
void CLogManager::log(const int32 i32Value)
{
logForEach<const int32>(i32Value);
}
void CLogManager::log(const int16 i16Value)
{
logForEach<const int16>(i16Value);
}
void CLogManager::log(const int8 i8Value)
{
logForEach<const int8>(i8Value);
}
void CLogManager::log(const float64 f64Value)
{
logForEach<const float64>(f64Value);
}
void CLogManager::log(const float32 f32Value)
{
logForEach<const float32>(f32Value);
}
void CLogManager::log(const boolean bValue)
{
logForEach<const boolean>(bValue);
}
void CLogManager::log(const CIdentifier& rValue)
{
logForEach<const CIdentifier&>(rValue);
}
void CLogManager::log(const CString& rValue)
{
logForEach<const CString&>(rValue);
}
void CLogManager::log(const char* rValue)
{
logForEach<const char*>(rValue);
}
void CLogManager::log(const ELogLevel eLogLevel)
{
m_eCurrentLogLevel=eLogLevel;
logForEach<ELogLevel>(eLogLevel);
}
void CLogManager::log(const ELogColor eLogColor)
{
logForEach<ELogColor>(eLogColor);
}
boolean CLogManager::addListener(ILogListener* pListener)
{
if(pListener==NULL)
{
return false;
}
vector<ILogListener*>::iterator itLogListener=m_vListener.begin();
while(itLogListener!=m_vListener.end())
{
if((*itLogListener)==pListener)
{
return false;
}
itLogListener++;
}
m_vListener.push_back(pListener);
return true;
}
boolean CLogManager::removeListener(ILogListener* pListener)
{
boolean l_bResult=false;
vector<ILogListener*>::iterator itLogListener=m_vListener.begin();
while(itLogListener!=m_vListener.end())
{
if((*itLogListener)==pListener)
{
itLogListener=m_vListener.erase(itLogListener);
l_bResult=true;
}
itLogListener++;
}
return l_bResult;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: VIndexColumn.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2006-06-20 02:10:46 $
*
* 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_SDBCX_INDEXCOLUMN_HXX_
#include "connectivity/sdbcx/VIndexColumn.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
using namespace connectivity;
using namespace connectivity::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OIndexColumn::getImplementationName( ) throw (::com::sun::star::uno::RuntimeException)
{
if(isNew())
return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VIndexColumnDescription");
return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VIndex");
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OIndexColumn::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException)
{
::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);
if(isNew())
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.IndexDescription");
else
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Index");
return aSupported;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL OIndexColumn::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)
{
Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
const ::rtl::OUString* pSupported = aSupported.getConstArray();
const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
;
return pSupported != pEnd;
}
// -----------------------------------------------------------------------------
OIndexColumn::OIndexColumn(sal_Bool _bCase) : OColumn(_bCase), m_IsAscending(sal_True)
{
construct();
}
// -------------------------------------------------------------------------
OIndexColumn::OIndexColumn( sal_Bool _IsAscending,
const ::rtl::OUString& _Name,
const ::rtl::OUString& _TypeName,
const ::rtl::OUString& _DefaultValue,
sal_Int32 _IsNullable,
sal_Int32 _Precision,
sal_Int32 _Scale,
sal_Int32 _Type,
sal_Bool _IsAutoIncrement,
sal_Bool _IsRowVersion,
sal_Bool _IsCurrency,
sal_Bool _bCase
) : OColumn(_Name,
_TypeName,
_DefaultValue,
_IsNullable,
_Precision,
_Scale,
_Type,
_IsAutoIncrement,
_IsRowVersion,
_IsCurrency,
_bCase)
, m_IsAscending(_IsAscending)
{
construct();
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OIndexColumn::createArrayHelper( sal_Int32 /*_nId*/ ) const
{
return doCreateArrayHelper();
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& SAL_CALL OIndexColumn::getInfoHelper()
{
return *OIndexColumn_PROP::getArrayHelper(isNew() ? 1 : 0);
}
// -------------------------------------------------------------------------
void OIndexColumn::construct()
{
sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISASCENDING), PROPERTY_ID_ISASCENDING, nAttrib,&m_IsAscending, ::getBooleanCppuType());
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS pchfix02 (1.10.60); FILE MERGED 2006/09/01 17:22:37 kaib 1.10.60.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: VIndexColumn.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: obo $ $Date: 2006-09-17 03:11: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_connectivity.hxx"
#ifndef _CONNECTIVITY_SDBCX_INDEXCOLUMN_HXX_
#include "connectivity/sdbcx/VIndexColumn.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
using namespace connectivity;
using namespace connectivity::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::uno;
// -----------------------------------------------------------------------------
::rtl::OUString SAL_CALL OIndexColumn::getImplementationName( ) throw (::com::sun::star::uno::RuntimeException)
{
if(isNew())
return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VIndexColumnDescription");
return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VIndex");
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OIndexColumn::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException)
{
::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);
if(isNew())
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.IndexDescription");
else
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Index");
return aSupported;
}
// -----------------------------------------------------------------------------
sal_Bool SAL_CALL OIndexColumn::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)
{
Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
const ::rtl::OUString* pSupported = aSupported.getConstArray();
const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
;
return pSupported != pEnd;
}
// -----------------------------------------------------------------------------
OIndexColumn::OIndexColumn(sal_Bool _bCase) : OColumn(_bCase), m_IsAscending(sal_True)
{
construct();
}
// -------------------------------------------------------------------------
OIndexColumn::OIndexColumn( sal_Bool _IsAscending,
const ::rtl::OUString& _Name,
const ::rtl::OUString& _TypeName,
const ::rtl::OUString& _DefaultValue,
sal_Int32 _IsNullable,
sal_Int32 _Precision,
sal_Int32 _Scale,
sal_Int32 _Type,
sal_Bool _IsAutoIncrement,
sal_Bool _IsRowVersion,
sal_Bool _IsCurrency,
sal_Bool _bCase
) : OColumn(_Name,
_TypeName,
_DefaultValue,
_IsNullable,
_Precision,
_Scale,
_Type,
_IsAutoIncrement,
_IsRowVersion,
_IsCurrency,
_bCase)
, m_IsAscending(_IsAscending)
{
construct();
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OIndexColumn::createArrayHelper( sal_Int32 /*_nId*/ ) const
{
return doCreateArrayHelper();
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& SAL_CALL OIndexColumn::getInfoHelper()
{
return *OIndexColumn_PROP::getArrayHelper(isNew() ? 1 : 0);
}
// -------------------------------------------------------------------------
void OIndexColumn::construct()
{
sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;
registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISASCENDING), PROPERTY_ID_ISASCENDING, nAttrib,&m_IsAscending, ::getBooleanCppuType());
}
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/gpu/gpu_surface_tracker.h"
#include "base/logging.h"
GpuSurfaceTracker::GpuSurfaceTracker()
: next_surface_id_(1) {
}
GpuSurfaceTracker::~GpuSurfaceTracker() {
}
GpuSurfaceTracker* GpuSurfaceTracker::GetInstance() {
return Singleton<GpuSurfaceTracker>::get();
}
int GpuSurfaceTracker::AddSurfaceForRenderer(int renderer_id,
int render_widget_id) {
base::AutoLock lock(lock_);
SurfaceInfo info = {
renderer_id,
render_widget_id,
gfx::kNullAcceleratedWidget
};
int surface_id = next_surface_id_++;
surface_map_[surface_id] = info;
return surface_id;
}
int GpuSurfaceTracker::LookupSurfaceForRenderer(int renderer_id,
int render_widget_id) {
base::AutoLock lock(lock_);
for (SurfaceMap::iterator it = surface_map_.begin(); it != surface_map_.end();
++it) {
const SurfaceInfo& info = it->second;
if (info.renderer_id == renderer_id &&
info.render_widget_id == render_widget_id) {
return it->first;
}
}
return 0;
}
int GpuSurfaceTracker::AddSurfaceForNativeWidget(
gfx::AcceleratedWidget widget) {
base::AutoLock lock(lock_);
SurfaceInfo info = { 0, 0, widget };
int surface_id = next_surface_id_++;
surface_map_[surface_id] = info;
return surface_id;
}
void GpuSurfaceTracker::RemoveSurface(int surface_id) {
base::AutoLock lock(lock_);
DCHECK(surface_map_.find(surface_id) != surface_map_.end());
surface_map_.erase(surface_id);
}
bool GpuSurfaceTracker::GetRenderWidgetIDForSurface(int surface_id,
int* renderer_id,
int* render_widget_id) {
base::AutoLock lock(lock_);
SurfaceMap::iterator it = surface_map_.find(surface_id);
if (it == surface_map_.end())
return false;
const SurfaceInfo& info = it->second;
*renderer_id = info.renderer_id;
*render_widget_id = info.render_widget_id;
return true;
}
void GpuSurfaceTracker::SetSurfaceHandle(int surface_id,
const gfx::GLSurfaceHandle& handle) {
base::AutoLock lock(lock_);
DCHECK(surface_map_.find(surface_id) != surface_map_.end());
SurfaceInfo& info = surface_map_[surface_id];
info.handle = handle;
}
gfx::GLSurfaceHandle GpuSurfaceTracker::GetSurfaceHandle(int surface_id) {
base::AutoLock lock(lock_);
DCHECK(surface_map_.find(surface_id) != surface_map_.end());
return surface_map_[surface_id].handle;
}
gfx::PluginWindowHandle GpuSurfaceTracker::GetSurfaceWindowHandle(
int surface_id) {
base::AutoLock lock(lock_);
SurfaceMap::iterator it = surface_map_.find(surface_id);
if (it == surface_map_.end())
return gfx::kNullPluginWindow;
return it->second.handle.handle;
}<commit_msg>Fix mac_clang build. Review URL: https://chromiumcodereview.appspot.com/9768005<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/gpu/gpu_surface_tracker.h"
#include "base/logging.h"
GpuSurfaceTracker::GpuSurfaceTracker()
: next_surface_id_(1) {
}
GpuSurfaceTracker::~GpuSurfaceTracker() {
}
GpuSurfaceTracker* GpuSurfaceTracker::GetInstance() {
return Singleton<GpuSurfaceTracker>::get();
}
int GpuSurfaceTracker::AddSurfaceForRenderer(int renderer_id,
int render_widget_id) {
base::AutoLock lock(lock_);
SurfaceInfo info = {
renderer_id,
render_widget_id,
gfx::kNullAcceleratedWidget
};
int surface_id = next_surface_id_++;
surface_map_[surface_id] = info;
return surface_id;
}
int GpuSurfaceTracker::LookupSurfaceForRenderer(int renderer_id,
int render_widget_id) {
base::AutoLock lock(lock_);
for (SurfaceMap::iterator it = surface_map_.begin(); it != surface_map_.end();
++it) {
const SurfaceInfo& info = it->second;
if (info.renderer_id == renderer_id &&
info.render_widget_id == render_widget_id) {
return it->first;
}
}
return 0;
}
int GpuSurfaceTracker::AddSurfaceForNativeWidget(
gfx::AcceleratedWidget widget) {
base::AutoLock lock(lock_);
SurfaceInfo info = { 0, 0, widget };
int surface_id = next_surface_id_++;
surface_map_[surface_id] = info;
return surface_id;
}
void GpuSurfaceTracker::RemoveSurface(int surface_id) {
base::AutoLock lock(lock_);
DCHECK(surface_map_.find(surface_id) != surface_map_.end());
surface_map_.erase(surface_id);
}
bool GpuSurfaceTracker::GetRenderWidgetIDForSurface(int surface_id,
int* renderer_id,
int* render_widget_id) {
base::AutoLock lock(lock_);
SurfaceMap::iterator it = surface_map_.find(surface_id);
if (it == surface_map_.end())
return false;
const SurfaceInfo& info = it->second;
*renderer_id = info.renderer_id;
*render_widget_id = info.render_widget_id;
return true;
}
void GpuSurfaceTracker::SetSurfaceHandle(int surface_id,
const gfx::GLSurfaceHandle& handle) {
base::AutoLock lock(lock_);
DCHECK(surface_map_.find(surface_id) != surface_map_.end());
SurfaceInfo& info = surface_map_[surface_id];
info.handle = handle;
}
gfx::GLSurfaceHandle GpuSurfaceTracker::GetSurfaceHandle(int surface_id) {
base::AutoLock lock(lock_);
DCHECK(surface_map_.find(surface_id) != surface_map_.end());
return surface_map_[surface_id].handle;
}
gfx::PluginWindowHandle GpuSurfaceTracker::GetSurfaceWindowHandle(
int surface_id) {
base::AutoLock lock(lock_);
SurfaceMap::iterator it = surface_map_.find(surface_id);
if (it == surface_map_.end())
return gfx::kNullPluginWindow;
return it->second.handle.handle;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */
#include "dcpappletbuttons.h"
#include <Pages>
#include <DcpAppletDb>
#include <DcpBriefComponent>
#include <DcpAppletMetadata>
#include <DcpApplet>
#include <QCoreApplication>
#include <QtDebug>
#include <DuiSceneManager>
#include <DuiGridLayoutPolicy>
#include <DuiLinearLayoutPolicy>
#include "maintranslations.h"
#define DEBUG
#include "../../../lib/src/dcpdebug.h"
/*!
* \class DcpAppletButtons
* \brief A container which contains buttons that represents the applets.
*/
DcpAppletButtons::DcpAppletButtons (
const QString &logicalId,
const QString &categoryName,
const QString &title,
QGraphicsWidget *parent)
: DcpMainCategory (title, parent, logicalId),
m_CategoryName (categoryName),
m_LogicalId (logicalId),
m_CategoryInfo (0)
{
setCreateSeparators (true);
setMaxColumns (2);
createContents ();
setMattiID ("DcpAppletButtons::" + logicalId + "::" + categoryName);
}
DcpAppletButtons::DcpAppletButtons (
const DcpCategoryInfo *categoryInfo,
const QString &title,
QGraphicsWidget *parent)
: DcpMainCategory (title, parent, categoryInfo->titleId),
m_CategoryName (categoryInfo->appletCategory),
m_CategoryInfo (categoryInfo)
{
setCreateSeparators (true);
setMaxColumns (2);
createContents ();
setMattiID (
QString ("DcpAppletButtons::") +
categoryInfo->titleId + "::" +
categoryInfo->appletCategory);
}
void
DcpAppletButtons::createContents ()
{
DcpAppletMetadataList list;
DCP_DEBUG ("");
/*
* Getting the list of applet variants (metadata objects) that will go into
* this widget.
*/
if (logicalId() == DcpMain::mostRecentUsedTitleId) {
list = DcpAppletDb::instance()->listMostUsed ();
} else {
bool withUncategorized;
const char *names[3];
withUncategorized = m_CategoryInfo &&
m_CategoryInfo->subPageId == PageHandle::Applications;
if (m_CategoryInfo) {
names[0] = m_CategoryInfo->titleId;
names[1] = m_CategoryInfo->appletCategory;
} else {
names[0] = DCP_STR (m_LogicalId);
names[1] = DCP_STR (m_CategoryName);
}
names[2] = 0;
list = DcpAppletDb::instance()->listByCategory (names, 2,
withUncategorized ? dcp_category_name_enlisted : NULL);
}
/*
* If we have a category info that might contain static elements, like the
* 'accounts & applications' contain the 'service accounts' and
* 'applications' static elements.
*/
if (m_CategoryInfo && m_CategoryInfo->staticElements) {
const DcpCategoryInfo *element;
for (int cnt = 0; ; ++cnt) {
element = &m_CategoryInfo->staticElements[cnt];
if (element->titleId == 0)
break;
addComponent (
element->appletCategory,
"",
element->subPageId);
}
}
/*
* Adding the applet variants to the widget.
*/
foreach (DcpAppletMetadata *item, list) {
addComponent (item);
QCoreApplication::processEvents ();
}
m_PortraitLayout->setObjectName ("MostUsedItems");
m_LandscapeLayout->setObjectName ("MostUsedItems");
setVerticalSpacing (0);
}
void
DcpAppletButtons::addComponent (
DcpAppletMetadata *metadata)
{
DcpBriefComponent *component;
component = new DcpBriefComponent (metadata, this, logicalId());
component->setSubPage (PageHandle::APPLET, metadata->name());
appendWidget (component);
}
void
DcpAppletButtons::addComponent (
const QString &briefTitleText,
const QString &briefSecondaryText,
const PageHandle &pageHandle)
{
DcpBriefComponent *component;
component = new DcpBriefComponent (
briefTitleText,
briefSecondaryText,
this, logicalId());
component->setSubPage (pageHandle);
appendWidget (component);
}
void
DcpAppletButtons::reload ()
{
DCP_WARNING ("WARNING: Why do we need this function?!");
deleteItems ();
createContents ();
}
QString
DcpAppletButtons::mattiID ()
{
return m_mattiID;
}
void
DcpAppletButtons::setMattiID (
const QString &mattiID)
{
m_mattiID = mattiID;
}
<commit_msg>Object name fixed.<commit_after>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */
#include "dcpappletbuttons.h"
#include <Pages>
#include <DcpAppletDb>
#include <DcpBriefComponent>
#include <DcpAppletMetadata>
#include <DcpApplet>
#include <QCoreApplication>
#include <QtDebug>
#include <DuiSceneManager>
#include <DuiGridLayoutPolicy>
#include <DuiLinearLayoutPolicy>
#include "maintranslations.h"
#define DEBUG
#include "../../../lib/src/dcpdebug.h"
/*!
* \class DcpAppletButtons
* \brief A container which contains buttons that represents the applets.
*/
DcpAppletButtons::DcpAppletButtons (
const QString &logicalId,
const QString &categoryName,
const QString &title,
QGraphicsWidget *parent)
: DcpMainCategory (title, parent, logicalId),
m_CategoryName (categoryName),
m_LogicalId (logicalId),
m_CategoryInfo (0)
{
setCreateSeparators (true);
setMaxColumns (2);
createContents ();
setMattiID ("DcpAppletButtons::" + logicalId + "::" + categoryName);
}
DcpAppletButtons::DcpAppletButtons (
const DcpCategoryInfo *categoryInfo,
const QString &title,
QGraphicsWidget *parent)
: DcpMainCategory (title, parent, categoryInfo->titleId),
m_CategoryName (categoryInfo->appletCategory),
m_CategoryInfo (categoryInfo)
{
setCreateSeparators (true);
setMaxColumns (2);
createContents ();
setMattiID (
QString ("DcpAppletButtons::") +
categoryInfo->titleId + "::" +
categoryInfo->appletCategory);
}
void
DcpAppletButtons::createContents ()
{
DcpAppletMetadataList list;
DCP_DEBUG ("");
/*
* Getting the list of applet variants (metadata objects) that will go into
* this widget.
*/
if (logicalId() == DcpMain::mostRecentUsedTitleId) {
list = DcpAppletDb::instance()->listMostUsed ();
m_PortraitLayout->setObjectName ("MostUsedItems");
m_LandscapeLayout->setObjectName ("MostUsedItems");
} else {
bool withUncategorized;
const char *names[3];
withUncategorized = m_CategoryInfo &&
m_CategoryInfo->subPageId == PageHandle::Applications;
if (m_CategoryInfo) {
names[0] = m_CategoryInfo->titleId;
names[1] = m_CategoryInfo->appletCategory;
} else {
names[0] = DCP_STR (m_LogicalId);
names[1] = DCP_STR (m_CategoryName);
}
names[2] = 0;
list = DcpAppletDb::instance()->listByCategory (names, 2,
withUncategorized ? dcp_category_name_enlisted : NULL);
}
/*
* If we have a category info that might contain static elements, like the
* 'accounts & applications' contain the 'service accounts' and
* 'applications' static elements.
*/
if (m_CategoryInfo && m_CategoryInfo->staticElements) {
const DcpCategoryInfo *element;
for (int cnt = 0; ; ++cnt) {
element = &m_CategoryInfo->staticElements[cnt];
if (element->titleId == 0)
break;
addComponent (
element->appletCategory,
"",
element->subPageId);
}
}
/*
* Adding the applet variants to the widget.
*/
foreach (DcpAppletMetadata *item, list) {
addComponent (item);
QCoreApplication::processEvents ();
}
setVerticalSpacing (0);
}
void
DcpAppletButtons::addComponent (
DcpAppletMetadata *metadata)
{
DcpBriefComponent *component;
component = new DcpBriefComponent (metadata, this, logicalId());
component->setSubPage (PageHandle::APPLET, metadata->name());
appendWidget (component);
}
void
DcpAppletButtons::addComponent (
const QString &briefTitleText,
const QString &briefSecondaryText,
const PageHandle &pageHandle)
{
DcpBriefComponent *component;
component = new DcpBriefComponent (
briefTitleText,
briefSecondaryText,
this, logicalId());
component->setSubPage (pageHandle);
appendWidget (component);
}
void
DcpAppletButtons::reload ()
{
DCP_WARNING ("WARNING: Why do we need this function?!");
deleteItems ();
createContents ();
}
QString
DcpAppletButtons::mattiID ()
{
return m_mattiID;
}
void
DcpAppletButtons::setMattiID (
const QString &mattiID)
{
m_mattiID = mattiID;
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 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 "Xalan" 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/>.
*/
#if !defined(FORMATTERTOHTML_HEADER_GUARD_1357924680)
#define FORMATTERTOHTML_HEADER_GUARD_1357924680
/**
* $Id$
*
* $State$
*
* @author David N. Bertoni <david_n_bertoni@lotus.com>
*/
// Base include file. Must be first.
#include <XMLSupport/XMLSupportDefinitions.hpp>
#include <set>
#include <map>
#include <vector>
// Base class header file.
#include <XMLSupport/FormatterToXML.hpp>
#include <Include/XalanArrayKeyMap.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
/**
* FormatterToHTML formats SAX-style events into HTML.
*/
class XALAN_XMLSUPPORT_EXPORT FormatterToHTML : public FormatterToXML
{
public:
/**
* Perform static initialization. See class XMLSupportInit.
*/
static void
initialize();
/**
* Perform static shut down. See class XMLSupportInit.
*/
static void
terminate();
enum eDummy
{
eDefaultIndentAmount = 4
};
/**
* Constructor for customized encoding and doctype.
* @param writer The character output stream to use.
* @param encoding Java character encoding in use by <VAR>writer</VAR>.
* @param doctype String to be printed at the top of the document.
* @param indent Number of spaces to indent at each nesting level.
*/
FormatterToHTML(
Writer& writer,
const XalanDOMString& encoding = XalanDOMString(),
const XalanDOMString& mediaType = XalanDOMString(),
const XalanDOMString& doctypeSystem = XalanDOMString(),
const XalanDOMString& doctypePublic = XalanDOMString(),
bool doIndent = true,
int indent = eDefaultIndentAmount,
const XalanDOMString& version = XalanDOMString(),
const XalanDOMString& standalone = XalanDOMString(),
bool xmlDecl = false);
virtual
~FormatterToHTML();
// These methods are inherited from DocumentHandler ...
virtual void
startDocument();
virtual void
endDocument();
virtual void
startElement(
const XMLCh* const name,
AttributeList& attrs);
virtual void
endElement(const XMLCh* const name);
virtual void
characters(
const XMLCh* const chars,
const unsigned int length);
// These methods are inherited from FormatterListener ...
virtual void
entityReference(const XMLCh* const name);
virtual void
cdata(
const XMLCh* const ch,
const unsigned int length);
virtual void
processingInstruction(
const XMLCh* const target,
const XMLCh* const data);
class ElemDesc
{
public:
enum eFlags
{
EMPTY = (1 << 1),
FLOW = (1 << 2),
BLOCK = (1 << 3),
BLOCKFORM = (1 << 4),
BLOCKFORMFIELDSET = (1 << 5),
CDATA = (1 << 6),
PCDATA = (1 << 7),
RAW = (1 << 8),
INLINE = (1 << 9),
INLINEA = (1 << 10),
INLINELABEL = (1 << 11),
FONTSTYLE = (1 << 12),
PHRASE = (1 << 13),
FORMCTRL = (1 << 14),
SPECIAL = (1 << 15),
ASPECIAL = (1 << 16),
HEADMISC = (1 << 17),
HEAD = (1 << 18),
LIST = (1 << 19),
PREFORMATTED = (1 << 20),
WHITESPACESENSITIVE = (1 << 21),
ATTRURL = (1 << 1),
ATTREMPTY = (1 << 2)
};
ElemDesc(unsigned int flags = 0) :
m_flags(flags)
{
}
~ElemDesc()
{
}
bool
operator==(const ElemDesc& theRHS) const
{
return m_flags == theRHS.m_flags && m_attrs == theRHS.m_attrs;
}
bool
is(unsigned int flags) const
{
return m_flags & flags ? true : false;
}
void
setAttr(
const XalanDOMChar* name,
unsigned int flags)
{
m_attrs.insert(AttributeMapType::value_type(name, flags));
}
bool
isAttrFlagSet(
const XalanDOMChar* name,
unsigned int flags) const
{
const AttributeMapType::const_iterator i =
m_attrs.find(name);
if (i == m_attrs.end())
{
return false;
}
else
{
return (*i).second & flags ? true : false;
}
}
private:
typedef XalanArrayKeyMap<
XalanDOMChar,
unsigned int,
less_no_case_ascii_wide_string> AttributeMapType;
const unsigned int m_flags;
AttributeMapType m_attrs;
};
typedef XalanArrayKeyMap<
XalanDOMChar,
ElemDesc,
less_no_case_ascii_wide_string> ElementFlagsMapType;
protected:
// These methods are new ...
/**
* Write an attribute string.
* @param string The string to write.
* @param encoding The current encoding.
*/
virtual void
writeAttrString(
const XalanDOMChar* string,
const XalanDOMString& encoding);
private:
static const ElementFlagsMapType& s_elementFlags;
/**
* Dummy description for elements not found.
*/
static const ElemDesc s_dummyDesc;
/**
* The string "<!DOCTYPE HTML".
*/
static const XalanDOMCharVectorType& s_doctypeHeaderStartString;
/**
* The string " PUBLIC \"".
*/
static const XalanDOMCharVectorType& s_doctypeHeaderPublicString;
/**
* The string " SYSTEM".
*/
static const XalanDOMCharVectorType& s_doctypeHeaderSystemString;
/**
* The string "SCRIPT".
*/
static const XalanDOMCharVectorType& s_scriptString;
/**
* The string "STYLE".
*/
static const XalanDOMCharVectorType& s_styleString;
/**
* The string "lt".
*/
static const XalanDOMCharVectorType& s_ltString;
/**
* The string "gt".
*/
static const XalanDOMCharVectorType& s_gtString;
/**
* The string "amp.
*/
static const XalanDOMCharVectorType& s_ampString;
/**
* The string "fnof".
*/
static const XalanDOMCharVectorType& s_fnofString;
/**
* Set the attribute characters what will require special mapping.
*/
void
initAttrCharsMap();
/**
* Set the output characters what will require special mapping.
*/
void
initCharsMap();
void
copyEntityIntoBuffer(const XalanDOMChar* s);
void
copyEntityIntoBuffer(const XalanDOMString& s);
void
copyEntityIntoBuffer(const XalanDOMCharVectorType& s);
/**
* Get an ElemDesc instance for the specified name.
*
* @param name the name to search.
* @return a const reference to the ElemDesc instance.
*/
static const ElemDesc&
getElemDesc(const XalanDOMChar* name);
/**
* Initialize the map of element flags.
*
* @return map of element flags.
*/
static void
initializeElementFlagsMap(ElementFlagsMapType& );
/**
* Process an attribute.
* @param name The name of the attribute.
* @param value The value of the attribute.
*/
virtual void
processAttribute(
const XalanDOMChar* name,
const XalanDOMChar* value,
const ElemDesc& elemDesc);
/**
* Write the specified <var>string</var> after substituting non ASCII characters,
* with <CODE>%HH</CODE>, where HH is the hex of the byte value.
*
* @param string String to convert to XML format.
* @param specials Chracters, should be represeted in chracter referenfces.
* @param encoding CURRENTLY NOT IMPLEMENTED.
*/
void
writeAttrURI(
const XalanDOMChar* string,
const XalanDOMString encoding);
XalanDOMString m_currentElementName;
bool m_inBlockElem;
BoolStackType m_isRawStack;
bool m_isScriptOrStyleElem;
bool m_isFirstElem;
};
#endif // FORMATTERTOHTML_HEADER_GUARD_1357924680
<commit_msg>Changed default indent to 0.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 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 "Xalan" 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/>.
*/
#if !defined(FORMATTERTOHTML_HEADER_GUARD_1357924680)
#define FORMATTERTOHTML_HEADER_GUARD_1357924680
/**
* $Id$
*
* $State$
*
* @author David N. Bertoni <david_n_bertoni@lotus.com>
*/
// Base include file. Must be first.
#include <XMLSupport/XMLSupportDefinitions.hpp>
#include <set>
#include <map>
#include <vector>
// Base class header file.
#include <XMLSupport/FormatterToXML.hpp>
#include <Include/XalanArrayKeyMap.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
/**
* FormatterToHTML formats SAX-style events into HTML.
*/
class XALAN_XMLSUPPORT_EXPORT FormatterToHTML : public FormatterToXML
{
public:
/**
* Perform static initialization. See class XMLSupportInit.
*/
static void
initialize();
/**
* Perform static shut down. See class XMLSupportInit.
*/
static void
terminate();
enum eDummy
{
eDefaultIndentAmount = 0
};
/**
* Constructor for customized encoding and doctype.
* @param writer The character output stream to use.
* @param encoding Java character encoding in use by <VAR>writer</VAR>.
* @param doctype String to be printed at the top of the document.
* @param indent Number of spaces to indent at each nesting level.
*/
FormatterToHTML(
Writer& writer,
const XalanDOMString& encoding = XalanDOMString(),
const XalanDOMString& mediaType = XalanDOMString(),
const XalanDOMString& doctypeSystem = XalanDOMString(),
const XalanDOMString& doctypePublic = XalanDOMString(),
bool doIndent = true,
int indent = eDefaultIndentAmount,
const XalanDOMString& version = XalanDOMString(),
const XalanDOMString& standalone = XalanDOMString(),
bool xmlDecl = false);
virtual
~FormatterToHTML();
// These methods are inherited from DocumentHandler ...
virtual void
startDocument();
virtual void
endDocument();
virtual void
startElement(
const XMLCh* const name,
AttributeList& attrs);
virtual void
endElement(const XMLCh* const name);
virtual void
characters(
const XMLCh* const chars,
const unsigned int length);
// These methods are inherited from FormatterListener ...
virtual void
entityReference(const XMLCh* const name);
virtual void
cdata(
const XMLCh* const ch,
const unsigned int length);
virtual void
processingInstruction(
const XMLCh* const target,
const XMLCh* const data);
class ElemDesc
{
public:
enum eFlags
{
EMPTY = (1 << 1),
FLOW = (1 << 2),
BLOCK = (1 << 3),
BLOCKFORM = (1 << 4),
BLOCKFORMFIELDSET = (1 << 5),
CDATA = (1 << 6),
PCDATA = (1 << 7),
RAW = (1 << 8),
INLINE = (1 << 9),
INLINEA = (1 << 10),
INLINELABEL = (1 << 11),
FONTSTYLE = (1 << 12),
PHRASE = (1 << 13),
FORMCTRL = (1 << 14),
SPECIAL = (1 << 15),
ASPECIAL = (1 << 16),
HEADMISC = (1 << 17),
HEAD = (1 << 18),
LIST = (1 << 19),
PREFORMATTED = (1 << 20),
WHITESPACESENSITIVE = (1 << 21),
ATTRURL = (1 << 1),
ATTREMPTY = (1 << 2)
};
ElemDesc(unsigned int flags = 0) :
m_flags(flags)
{
}
~ElemDesc()
{
}
bool
operator==(const ElemDesc& theRHS) const
{
return m_flags == theRHS.m_flags && m_attrs == theRHS.m_attrs;
}
bool
is(unsigned int flags) const
{
return m_flags & flags ? true : false;
}
void
setAttr(
const XalanDOMChar* name,
unsigned int flags)
{
m_attrs.insert(AttributeMapType::value_type(name, flags));
}
bool
isAttrFlagSet(
const XalanDOMChar* name,
unsigned int flags) const
{
const AttributeMapType::const_iterator i =
m_attrs.find(name);
if (i == m_attrs.end())
{
return false;
}
else
{
return (*i).second & flags ? true : false;
}
}
private:
typedef XalanArrayKeyMap<
XalanDOMChar,
unsigned int,
less_no_case_ascii_wide_string> AttributeMapType;
const unsigned int m_flags;
AttributeMapType m_attrs;
};
typedef XalanArrayKeyMap<
XalanDOMChar,
ElemDesc,
less_no_case_ascii_wide_string> ElementFlagsMapType;
protected:
// These methods are new ...
/**
* Write an attribute string.
* @param string The string to write.
* @param encoding The current encoding.
*/
virtual void
writeAttrString(
const XalanDOMChar* string,
const XalanDOMString& encoding);
private:
static const ElementFlagsMapType& s_elementFlags;
/**
* Dummy description for elements not found.
*/
static const ElemDesc s_dummyDesc;
/**
* The string "<!DOCTYPE HTML".
*/
static const XalanDOMCharVectorType& s_doctypeHeaderStartString;
/**
* The string " PUBLIC \"".
*/
static const XalanDOMCharVectorType& s_doctypeHeaderPublicString;
/**
* The string " SYSTEM".
*/
static const XalanDOMCharVectorType& s_doctypeHeaderSystemString;
/**
* The string "SCRIPT".
*/
static const XalanDOMCharVectorType& s_scriptString;
/**
* The string "STYLE".
*/
static const XalanDOMCharVectorType& s_styleString;
/**
* The string "lt".
*/
static const XalanDOMCharVectorType& s_ltString;
/**
* The string "gt".
*/
static const XalanDOMCharVectorType& s_gtString;
/**
* The string "amp.
*/
static const XalanDOMCharVectorType& s_ampString;
/**
* The string "fnof".
*/
static const XalanDOMCharVectorType& s_fnofString;
/**
* Set the attribute characters what will require special mapping.
*/
void
initAttrCharsMap();
/**
* Set the output characters what will require special mapping.
*/
void
initCharsMap();
void
copyEntityIntoBuffer(const XalanDOMChar* s);
void
copyEntityIntoBuffer(const XalanDOMString& s);
void
copyEntityIntoBuffer(const XalanDOMCharVectorType& s);
/**
* Get an ElemDesc instance for the specified name.
*
* @param name the name to search.
* @return a const reference to the ElemDesc instance.
*/
static const ElemDesc&
getElemDesc(const XalanDOMChar* name);
/**
* Initialize the map of element flags.
*
* @return map of element flags.
*/
static void
initializeElementFlagsMap(ElementFlagsMapType& );
/**
* Process an attribute.
* @param name The name of the attribute.
* @param value The value of the attribute.
*/
virtual void
processAttribute(
const XalanDOMChar* name,
const XalanDOMChar* value,
const ElemDesc& elemDesc);
/**
* Write the specified <var>string</var> after substituting non ASCII characters,
* with <CODE>%HH</CODE>, where HH is the hex of the byte value.
*
* @param string String to convert to XML format.
* @param specials Chracters, should be represeted in chracter referenfces.
* @param encoding CURRENTLY NOT IMPLEMENTED.
*/
void
writeAttrURI(
const XalanDOMChar* string,
const XalanDOMString encoding);
XalanDOMString m_currentElementName;
bool m_inBlockElem;
BoolStackType m_isRawStack;
bool m_isScriptOrStyleElem;
bool m_isFirstElem;
};
#endif // FORMATTERTOHTML_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>#include "tests.h"
#include "coroutine_system.h"
using swoole::Coroutine;
using swoole::coroutine::System;
TEST(coroutine_gethostbyname, resolve_with_cache)
{
coro_test([](void *arg)
{
System::set_dns_cache_capacity(10);
std::string addr1 = System::gethostbyname("www.baidu.com", AF_INET);
ASSERT_NE(addr1, "");
int64_t start = swTimer_get_absolute_msec();
for (int i = 0; i < 100; ++i)
{
std::string addr2 = System::gethostbyname("www.baidu.com", AF_INET);
ASSERT_EQ(addr1, addr2);
}
ASSERT_LT(swTimer_get_absolute_msec() - start, 5);
});
}
TEST(coroutine_gethostbyname, resolve_without_cache)
{
coro_test([](void *arg)
{
System::set_dns_cache_capacity(0);
std::string addr1 = System::gethostbyname("www.baidu.com", AF_INET);
ASSERT_NE(addr1, "");
int64_t start = swTimer_get_absolute_msec();
for (int i = 0; i < 5; ++i)
{
std::string addr2 = System::gethostbyname("www.baidu.com", AF_INET);
ASSERT_NE(addr2, "");
}
ASSERT_GT(swTimer_get_absolute_msec() - start, 3);
});
}
TEST(coroutine_gethostbyname, resolve_cache_inet4_and_inet6)
{
coro_test([](void *arg)
{
System::set_dns_cache_capacity(10);
std::string addr1 = System::gethostbyname("ipv6.sjtu.edu.cn", AF_INET);
std::string addr2 = System::gethostbyname("ipv6.sjtu.edu.cn", AF_INET6);
ASSERT_NE(addr1, "");
ASSERT_NE(addr2, "");
ASSERT_EQ(addr1.find(":"), addr1.npos);
ASSERT_NE(addr2.find(":"), addr2.npos);
int64_t start = swTimer_get_absolute_msec();
for (int i = 0; i < 100; ++i)
{
std::string addr3 = System::gethostbyname("ipv6.sjtu.edu.cn", AF_INET);
std::string addr4 = System::gethostbyname("ipv6.sjtu.edu.cn", AF_INET6);
ASSERT_EQ(addr1, addr3);
ASSERT_EQ(addr2, addr4);
}
ASSERT_LT(swTimer_get_absolute_msec() - start, 5);
});
}
<commit_msg>Improve core test of gethostbyname<commit_after>#include "tests.h"
#include "coroutine_system.h"
using swoole::Coroutine;
using swoole::coroutine::System;
TEST(coroutine_gethostbyname, resolve_cache)
{
coro_test([](void *arg)
{
System::set_dns_cache_capacity(10);
std::string addr1 = System::gethostbyname("www.baidu.com", AF_INET);
ASSERT_NE(addr1, "");
int64_t with_cache = swTimer_get_absolute_msec();
for (int i = 0; i < 100; ++i)
{
std::string addr2 = System::gethostbyname("www.baidu.com", AF_INET);
ASSERT_EQ(addr1, addr2);
}
with_cache = swTimer_get_absolute_msec() - with_cache;
System::set_dns_cache_capacity(0);
int64_t without_cache = swTimer_get_absolute_msec();
for (int i = 0; i < 5; ++i)
{
std::string addr2 = System::gethostbyname("www.baidu.com", AF_INET);
ASSERT_NE(addr2, "");
}
without_cache = swTimer_get_absolute_msec() - without_cache;
ASSERT_GT(without_cache, with_cache);
});
}
TEST(coroutine_gethostbyname, resolve_cache_inet4_and_inet6)
{
coro_test([](void *arg)
{
System::set_dns_cache_capacity(10);
std::string addr1 = System::gethostbyname("ipv6.sjtu.edu.cn", AF_INET);
std::string addr2 = System::gethostbyname("ipv6.sjtu.edu.cn", AF_INET6);
ASSERT_NE(addr1, "");
ASSERT_NE(addr2, "");
ASSERT_EQ(addr1.find(":"), addr1.npos);
ASSERT_NE(addr2.find(":"), addr2.npos);
int64_t start = swTimer_get_absolute_msec();
for (int i = 0; i < 100; ++i)
{
std::string addr3 = System::gethostbyname("ipv6.sjtu.edu.cn", AF_INET);
std::string addr4 = System::gethostbyname("ipv6.sjtu.edu.cn", AF_INET6);
ASSERT_EQ(addr1, addr3);
ASSERT_EQ(addr2, addr4);
}
ASSERT_LT(swTimer_get_absolute_msec() - start, 5);
});
}
<|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <af/defines.h>
#include <string>
#include <stdlib.h>
#include <util.hpp>
#include <err_common.hpp>
#if defined(OS_WIN)
#include <Windows.h>
typedef HMODULE LibHandle;
#else
#include <dlfcn.h>
typedef void* LibHandle;
#endif
namespace unified
{
const int NUM_BACKENDS = 3;
const int NUM_ENV_VARS = 2;
#define UNIFIED_ERROR_LOAD_LIB() \
AF_RETURN_ERROR("Failed to load dynamic library. " \
"See http://www.arrayfire.com/docs/unifiedbackend.htm " \
"for instructions to set up environment for Unified backend.", \
AF_ERR_LOAD_LIB)
class AFSymbolManager {
public:
static AFSymbolManager& getInstance();
~AFSymbolManager();
unsigned getBackendCount();
int getAvailableBackends();
af_err setBackend(af::Backend bnkd);
af::Backend getActiveBackend() { return activeBackend; }
template<typename... CalleeArgs>
af_err call(const char* symbolName, CalleeArgs... args) {
if (!activeHandle) {
UNIFIED_ERROR_LOAD_LIB();
}
typedef af_err(*af_func)(CalleeArgs...);
af_func funcHandle;
#if defined(OS_WIN)
funcHandle = (af_func)GetProcAddress(activeHandle, symbolName);
#else
funcHandle = (af_func)dlsym(activeHandle, symbolName);
#endif
if (!funcHandle) {
std::string str = "Failed to load symbol: ";
str += symbolName;
AF_RETURN_ERROR(str.c_str(),
AF_ERR_LOAD_SYM);
}
return funcHandle(args...);
}
LibHandle getHandle() { return activeHandle; }
protected:
AFSymbolManager();
// Following two declarations are required to
// avoid copying accidental copy/assignment
// of instance returned by getInstance to other
// variables
AFSymbolManager(AFSymbolManager const&);
void operator=(AFSymbolManager const&);
private:
LibHandle bkndHandles[NUM_BACKENDS];
LibHandle activeHandle;
LibHandle defaultHandle;
unsigned numBackends;
int backendsAvailable;
af_backend activeBackend;
af_backend defaultBackend;
};
// Helper functions to ensure all the input arrays are on the active backend
bool checkArray(af_backend activeBackend, af_array a);
bool checkArrays(af_backend activeBackend);
template<typename T, typename... Args>
bool checkArrays(af_backend activeBackend, T a, Args... arg)
{
return checkArray(activeBackend, a) && checkArrays(activeBackend, arg...);
}
} // namespace unified
// Macro to check af_array as inputs. The arguments to this macro should be
// only input af_arrays. Not outputs or other types.
#define CHECK_ARRAYS(...) do { \
af_backend backendId = unified::AFSymbolManager::getInstance().getActiveBackend(); \
if(!unified::checkArrays(backendId, __VA_ARGS__)) \
AF_RETURN_ERROR("Input array does not belong to current backend", \
AF_ERR_ARR_BKND_MISMATCH); \
} while(0)
#if defined(OS_WIN)
#define CALL(...) unified::AFSymbolManager::getInstance().call(__FUNCTION__, __VA_ARGS__)
#define CALL_NO_PARAMS() unified::AFSymbolManager::getInstance().call(__FUNCTION__)
#else
#define CALL(...) unified::AFSymbolManager::getInstance().call(__func__, __VA_ARGS__)
#define CALL_NO_PARAMS() unified::AFSymbolManager::getInstance().call(__func__)
#endif
#if defined(OS_WIN)
#define LOAD_SYMBOL() GetProcAddress(unified::AFSymbolManager::getInstance().getHandle(), __FUNCTION__)
#else
#define LOAD_SYMBOL() dlsym(unified::AFSymbolManager::getInstance().getHandle(), __func__)
#endif
<commit_msg>Cache backend symbols in the unified backend<commit_after>/*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <af/defines.h>
#include <string>
#include <stdlib.h>
#include <util.hpp>
#include <err_common.hpp>
#if defined(OS_WIN)
#include <Windows.h>
typedef HMODULE LibHandle;
#else
#include <dlfcn.h>
typedef void* LibHandle;
#endif
#include <array>
#include <unordered_map>
namespace unified
{
const int NUM_BACKENDS = 3;
const int NUM_ENV_VARS = 2;
#define UNIFIED_ERROR_LOAD_LIB() \
AF_RETURN_ERROR("Failed to load dynamic library. " \
"See http://www.arrayfire.com/docs/unifiedbackend.htm " \
"for instructions to set up environment for Unified backend.", \
AF_ERR_LOAD_LIB)
static int backend_index(af::Backend be) {
switch (be) {
case AF_BACKEND_CPU: return 0;
case AF_BACKEND_CUDA: return 1;
case AF_BACKEND_OPENCL: return 2;
default: return -1;
}
}
class AFSymbolManager {
public:
static AFSymbolManager& getInstance();
~AFSymbolManager();
unsigned getBackendCount();
int getAvailableBackends();
af_err setBackend(af::Backend bnkd);
af::Backend getActiveBackend() { return activeBackend; }
template<typename... CalleeArgs>
af_err call(const char* symbolName, CalleeArgs... args) {
typedef af_err(*af_func)(CalleeArgs...);
if (!activeHandle) {
UNIFIED_ERROR_LOAD_LIB();
}
static std::array<std::unordered_map<const char*, af_func>, NUM_BACKENDS> funcHandles;
int index = backend_index(getActiveBackend());
af_func& funcHandle = funcHandles[index][symbolName];
if (!funcHandle) {
#if defined(OS_WIN)
funcHandle = (af_func)GetProcAddress(activeHandle, symbolName);
#else
funcHandle = (af_func)dlsym(activeHandle, symbolName);
#endif
}
if (!funcHandle) {
std::string str = "Failed to load symbol: ";
str += symbolName;
AF_RETURN_ERROR(str.c_str(),
AF_ERR_LOAD_SYM);
}
return funcHandle(args...);
}
LibHandle getHandle() { return activeHandle; }
protected:
AFSymbolManager();
// Following two declarations are required to
// avoid copying accidental copy/assignment
// of instance returned by getInstance to other
// variables
AFSymbolManager(AFSymbolManager const&);
void operator=(AFSymbolManager const&);
private:
LibHandle bkndHandles[NUM_BACKENDS];
LibHandle activeHandle;
LibHandle defaultHandle;
unsigned numBackends;
int backendsAvailable;
af_backend activeBackend;
af_backend defaultBackend;
};
// Helper functions to ensure all the input arrays are on the active backend
bool checkArray(af_backend activeBackend, af_array a);
bool checkArrays(af_backend activeBackend);
template<typename T, typename... Args>
bool checkArrays(af_backend activeBackend, T a, Args... arg)
{
return checkArray(activeBackend, a) && checkArrays(activeBackend, arg...);
}
} // namespace unified
// Macro to check af_array as inputs. The arguments to this macro should be
// only input af_arrays. Not outputs or other types.
#define CHECK_ARRAYS(...) do { \
af_backend backendId = unified::AFSymbolManager::getInstance().getActiveBackend(); \
if(!unified::checkArrays(backendId, __VA_ARGS__)) \
AF_RETURN_ERROR("Input array does not belong to current backend", \
AF_ERR_ARR_BKND_MISMATCH); \
} while(0)
#if defined(OS_WIN)
#define CALL(...) unified::AFSymbolManager::getInstance().call(__FUNCTION__, __VA_ARGS__)
#define CALL_NO_PARAMS() unified::AFSymbolManager::getInstance().call(__FUNCTION__)
#else
#define CALL(...) unified::AFSymbolManager::getInstance().call(__func__, __VA_ARGS__)
#define CALL_NO_PARAMS() unified::AFSymbolManager::getInstance().call(__func__)
#endif
#if defined(OS_WIN)
#define LOAD_SYMBOL() GetProcAddress(unified::AFSymbolManager::getInstance().getHandle(), __FUNCTION__)
#else
#define LOAD_SYMBOL() dlsym(unified::AFSymbolManager::getInstance().getHandle(), __func__)
#endif
<|endoftext|> |
<commit_before>#include <DO/Sara/Core/EigenExtension.hpp>
#include <DO/Sara/Core/Math/NewtonRaphson.hpp>
#include <DO/Sara/Core/Math/UnivariatePolynomial.hpp>
#include <complex>
#include <ctime>
#include <memory>
namespace DO { namespace Sara {
// Cauchy's method to calculate the polynomial lower bound.
auto compute_moduli_lower_bound(const UnivariatePolynomial<double>& P)
-> double
{
auto Q = P;
Q[0] = -std::abs(Q[0] / Q[Q.degree()]);
for (int i = 1; i <= Q.degree(); ++i)
Q[i] = std::abs(Q[i] / Q[Q.degree()]);
auto x = 1.;
auto newton_raphson = NewtonRaphson<double>{Q};
x = newton_raphson(x, 50);
return x;
}
// Sigma is a real polynomial. So (s1, s2) is a pair of identical real numbers
// or a conjugate complex pair.
auto sigma_generic_formula(const std::complex<double>& s1)
-> UnivariatePolynomial<double>
{
const auto a = std::real(s1);
const auto b = std::imag(s1);
return Z.pow<double>(2) - 2 * a * Z + (a * a + b * b);
}
// See formula (2.2) at page 547.
// Don't use because overflow and underflow problems would occur (page 563).
auto K1_generic_recurrence_formula(const UnivariatePolynomial<double>& K0,
const UnivariatePolynomial<double>& P,
const UnivariatePolynomial<double>& sigma,
const std::complex<double>& s1)
-> UnivariatePolynomial<double>
{
const auto s2 = std::conj(s1);
Matrix2cd a, b, c;
a << P(s1), P(s2), //
K0(s1), K0(s2);
b << K0(s1), K0(s2), //
s1 * P(s1), s2 * P(s2);
c << s1 * P(s1), s2 * P(s2), //
P(s1), P(s2);
const auto m = std::real(a.determinant() / c.determinant());
const auto n = std::real(b.determinant() / c.determinant());
return ((K0 + (m * Z + n)*P) / sigma).first;
}
// See formula (2.7) at page 548.
auto
sigma_formula_from_shift_polynomials(const UnivariatePolynomial<double>& K0,
const UnivariatePolynomial<double>& K1,
const UnivariatePolynomial<double>& K2,
const std::complex<double>& s1)
-> UnivariatePolynomial<double>
{
const auto s2 = std::conj(s1);
const auto a2 = std::real(K1(s1) * K2(s2) - K1(s2) * K2(s1));
const auto a1 = std::real(K0(s2) * K2(s1) - K0(s1) * K2(s2));
const auto a0 = std::real(K0(s1) * K1(s2) - K0(s2) * K1(s1));
// return (a2 * Z.pow(2) + a1 * Z + a0) / a2;
return Z.pow<double>(2) + (a1 / a2) * Z + (a0 / a2);
}
// See formula at "Stage 1: no-shift process" at page 556.
auto K1_no_shift_polynomial(const UnivariatePolynomial<double>& K0,
const UnivariatePolynomial<double>& P)
-> UnivariatePolynomial<double>
{
auto K1 = (K0 - (K0(0) / P(0)) * P) / Z;
return K1.first;
}
// This is the scaled recurrence formula (page 563).
auto K0_polynomial(const UnivariatePolynomial<double>& P)
-> UnivariatePolynomial<double>
{
return derivative(P) / P.degree();
}
// Fixed-shift process.
struct Stage2
{
enum ConvergenceType : std::uint8_t
{
NoConvergence = 0,
LinearFactor = 1,
QuadraticFactor = 2
};
//! @{
//! @brief parameters.
int M{5};
int L{20};
std::random_device rd;
std::mt19937 gen;
std::uniform_real_distribution<> dist{0, 94.0};
double beta;
//! @}
//! The polynomial of which we want to find the roots.
UnivariatePolynomial<double>& P;
//! P(s1) and P(s2).
std::complex<double>& P_s1;
std::complex<double>& P_s2;
//! Quadratic real polynomial divisor.
UnivariatePolynomial<double>& sigma;
//! The roots of sigma.
std::complex<double>& s1;
std::complex<double>& s2;
//! Stage 2: fixed-shift polynomial.
//! Stage 3: variable-shift polynomial.
UnivariatePolynomial<double> K0;
UnivariatePolynomial<double> K1;
//! K0(s1) and K0(s2)
std::complex<double>& K0_s1;
std::complex<double>& K0_s2;
//! Auxiliary variables.
double a, b, c, d;
double u, v;
UnivariatePolynomial<double> Q_P, P_r;
UnivariatePolynomial<double> Q_K0, K0_r;
//! Fixed-shift coefficients to update sigma.
MatrixXcd K1_{3, 2};
// 1. Determine moduli lower bound $\beta$.
auto determine_lower_bound() -> void
{
beta = compute_moduli_lower_bound(P);
}
// 2. Form polynomial sigma(z).
auto form_quadratic_divisor_sigma() -> void
{
constexpr auto i = std::complex<double>{0, 1};
const auto phase = dist(rd);
s1 = beta * std::exp(i * phase);
s2 = std::conj(s1);
sigma = Z.pow<double>(2) - 2 * std::real(s1) * Z + std::real(s1 * s2);
}
// 3.1 Evaluate the polynomial at divisor roots.
auto evaluate_polynomial_at_divisor_roots() -> void
{
P_s1 = P(s1);
P_s2 = P(s1);
}
// 3.2 Evaluate the fixed-shift polynomial at divisor roots.
auto evaluate_shift_polynomial_at_divisor_roots() -> void
{
K0_s1 = K0(s1);
K0_s2 = K0(s1);
}
// 3.3 Calculate coefficient of linear remainders (cf. formula 9.7).
auto calculate_coefficients_of_linear_remainders() -> void
{
// See stage 2 formula (9.7) (page 563).
Matrix4cd M;
Vector4cd y;
M <<
1, -s2, 0, 0,
0, 0, 1, -s2,
1, -s1, 0, 0,
0, 0, 1, -s1;
y << P_s1, P_s2, K0_s1, K0_s2;
Vector4cd x = M.colPivHouseholderQr().solve(y);
a = std::real(x[0]);
b = std::real(x[1]);
c = std::real(x[2]);
d = std::real(x[3]);
u = -std::real(s1 + s2);
v = std::real(s1 * s2);
}
// 3.4 Calculate the next fixed/variable-shift polynomial (cf. formula 9.8).
auto calculate_next_fixed_shit_polynomial() -> void
{
P_r = b * (Z + u) + a;
K0_r = c * (Z + u) + d;
Q_P = ((P - P_r) / sigma).first;
Q_K0 = ((K0 - K0_r) / sigma).first;
const auto c0 = b * c - a * d;
const auto c1 = (a * a + u * a * b + v * b * b) / c0;
const auto c2 = (a * c + u * a * d + v * b * d) / c0;
K1 = c1 * Q_K0 + (Z - c2) * Q_P + b;
}
// 3.5 Calculate the new quadratic polynomial sigma (cf. formula 6.7).
auto calculate_next_quadratic_divisor() -> void
{
K1_(0, 0) = K1(s1);
K1_(0, 1) = K1(s2);
K1_(1, 0) = (K1_(0, 0) - K1(0) / P(0) * P_s1) / s1;
K1_(1, 1) = (K1_(0, 1) - K1(0) / P(0) * P_s2) / s2;
K1_(2, 0) = (K1_(1, 0) - K1(0) / P(0) * P_s1) / s1;
K1_(2, 1) = (K1_(1, 1) - K1(0) / P(0) * P_s2) / s2;
}
auto check_convergence_linear_factor() -> void;
auto check_convergence_quadratic_factor() -> void;
};
} /* namespace Sara */
} /* namespace DO */
<commit_msg>WIP: add implementation of the update formula for sigma.<commit_after>#include <DO/Sara/Core/EigenExtension.hpp>
#include <DO/Sara/Core/Math/NewtonRaphson.hpp>
#include <DO/Sara/Core/Math/UnivariatePolynomial.hpp>
#include <complex>
#include <ctime>
#include <memory>
namespace DO { namespace Sara {
// Cauchy's method to calculate the polynomial lower bound.
auto compute_moduli_lower_bound(const UnivariatePolynomial<double>& P)
-> double
{
auto Q = P;
Q[0] = -std::abs(Q[0] / Q[Q.degree()]);
for (int i = 1; i <= Q.degree(); ++i)
Q[i] = std::abs(Q[i] / Q[Q.degree()]);
auto x = 1.;
auto newton_raphson = NewtonRaphson<double>{Q};
x = newton_raphson(x, 50);
return x;
}
// Sigma is a real polynomial. So (s1, s2) is a pair of identical real numbers
// or a conjugate complex pair.
auto sigma_generic_formula(const std::complex<double>& s1)
-> UnivariatePolynomial<double>
{
const auto a = std::real(s1);
const auto b = std::imag(s1);
return Z.pow<double>(2) - 2 * a * Z + (a * a + b * b);
}
// See formula (2.2) at page 547.
// Don't use because overflow and underflow problems would occur (page 563).
auto K1_generic_recurrence_formula(const UnivariatePolynomial<double>& K0,
const UnivariatePolynomial<double>& P,
const UnivariatePolynomial<double>& sigma,
const std::complex<double>& s1)
-> UnivariatePolynomial<double>
{
const auto s2 = std::conj(s1);
Matrix2cd a, b, c;
a << P(s1), P(s2), //
K0(s1), K0(s2);
b << K0(s1), K0(s2), //
s1 * P(s1), s2 * P(s2);
c << s1 * P(s1), s2 * P(s2), //
P(s1), P(s2);
const auto m = std::real(a.determinant() / c.determinant());
const auto n = std::real(b.determinant() / c.determinant());
return ((K0 + (m * Z + n)*P) / sigma).first;
}
// See formula (2.7) at page 548.
auto
sigma_formula_from_shift_polynomials(const UnivariatePolynomial<double>& K0,
const UnivariatePolynomial<double>& K1,
const UnivariatePolynomial<double>& K2,
const std::complex<double>& s1)
-> UnivariatePolynomial<double>
{
const auto s2 = std::conj(s1);
const auto a2 = std::real(K1(s1) * K2(s2) - K1(s2) * K2(s1));
const auto a1 = std::real(K0(s2) * K2(s1) - K0(s1) * K2(s2));
const auto a0 = std::real(K0(s1) * K1(s2) - K0(s2) * K1(s1));
// return (a2 * Z.pow(2) + a1 * Z + a0) / a2;
return Z.pow<double>(2) + (a1 / a2) * Z + (a0 / a2);
}
// See formula at "Stage 1: no-shift process" at page 556.
auto K1_no_shift_polynomial(const UnivariatePolynomial<double>& K0,
const UnivariatePolynomial<double>& P)
-> UnivariatePolynomial<double>
{
auto K1 = (K0 - (K0(0) / P(0)) * P) / Z;
return K1.first;
}
// This is the scaled recurrence formula (page 563).
auto K0_polynomial(const UnivariatePolynomial<double>& P)
-> UnivariatePolynomial<double>
{
return derivative(P) / P.degree();
}
// Fixed-shift process.
struct Stage2
{
enum ConvergenceType : std::uint8_t
{
NoConvergence = 0,
LinearFactor = 1,
QuadraticFactor = 2
};
//! @{
//! @brief parameters.
int M{5};
int L{20};
std::random_device rd;
std::mt19937 gen;
std::uniform_real_distribution<> dist{0, 94.0};
double beta;
//! @}
//! The polynomial of which we want to find the roots.
UnivariatePolynomial<double>& P;
//! P(s1) and P(s2).
std::complex<double>& P_s1;
std::complex<double>& P_s2;
//! Quadratic real polynomial divisor.
UnivariatePolynomial<double>& sigma;
//! The roots of sigma.
std::complex<double>& s1;
std::complex<double>& s2;
//! Stage 2: fixed-shift polynomial.
//! Stage 3: variable-shift polynomial.
UnivariatePolynomial<double> K0;
UnivariatePolynomial<double> K1;
//! K0(s1) and K0(s2)
std::complex<double>& K0_s1;
std::complex<double>& K0_s2;
//! Auxiliary variables.
double a, b, c, d;
double u, v;
UnivariatePolynomial<double> Q_P, P_r;
UnivariatePolynomial<double> Q_K0, K0_r;
//! Fixed-shift coefficients to update sigma.
MatrixXcd K1_{3, 2};
// 1. Determine moduli lower bound $\beta$.
auto determine_lower_bound() -> void
{
beta = compute_moduli_lower_bound(P);
}
// 2. Form polynomial sigma(z).
auto form_quadratic_divisor_sigma() -> void
{
constexpr auto i = std::complex<double>{0, 1};
const auto phase = dist(rd);
s1 = beta * std::exp(i * phase);
s2 = std::conj(s1);
sigma = Z.pow<double>(2) - 2 * std::real(s1) * Z + std::real(s1 * s2);
}
// 3.1 Evaluate the polynomial at divisor roots.
auto evaluate_polynomial_at_divisor_roots() -> void
{
P_s1 = P(s1);
P_s2 = P(s1);
}
// 3.2 Evaluate the fixed-shift polynomial at divisor roots.
auto evaluate_shift_polynomial_at_divisor_roots() -> void
{
K0_s1 = K0(s1);
K0_s2 = K0(s1);
}
// 3.3 Calculate coefficient of linear remainders (cf. formula 9.7).
auto calculate_coefficients_of_linear_remainders() -> void
{
// See stage 2 formula (9.7) (page 563).
Matrix4cd M;
Vector4cd y;
M <<
1, -s2, 0, 0,
0, 0, 1, -s2,
1, -s1, 0, 0,
0, 0, 1, -s1;
y << P_s1, P_s2, K0_s1, K0_s2;
Vector4cd x = M.colPivHouseholderQr().solve(y);
a = std::real(x[0]);
b = std::real(x[1]);
c = std::real(x[2]);
d = std::real(x[3]);
u = -std::real(s1 + s2);
v = std::real(s1 * s2);
}
// 3.4 Calculate the next fixed/variable-shift polynomial (cf. formula 9.8).
auto calculate_next_fixed_shit_polynomial() -> void
{
P_r = b * (Z + u) + a;
K0_r = c * (Z + u) + d;
Q_P = ((P - P_r) / sigma).first;
Q_K0 = ((K0 - K0_r) / sigma).first;
const auto c0 = b * c - a * d;
const auto c1 = (a * a + u * a * b + v * b * b) / c0;
const auto c2 = (a * c + u * a * d + v * b * d) / c0;
K1 = c1 * Q_K0 + (Z - c2) * Q_P + b;
}
// 3.5 Calculate the new quadratic polynomial sigma (cf. formula 6.7).
auto calculate_next_quadratic_divisor() -> void
{
const auto b1 = -K0[0] / P[0];
const auto b2 = K0[1] + b1 * P[1] / P[0];
const auto a1 = b * c - a * d;
const auto a2 = a * c + u * a * d + v * b * d;
const auto c2 = b1 * a2;
const auto c3 = b1 * b1 * (a * a + u * a * b + v * b * b);
const auto c4 = v * b2 * a1 - c2 - c3;
const auto c1 = c * c + u * c * d + v * d * d +
b1 * (a * c + u * b * c + v * b * d) - c4;
const auto delta_u = -(u * (c2 + c3) + v * (b1 * a1 + b2 * a2)) / c1;
const auto delta_v = v * c4 / c1;
sigma[0] = v + delta_v;
sigma[1] = u + delta_u;
sigma[2] = 1.0;
}
auto check_convergence_linear_factor() -> void;
auto check_convergence_quadratic_factor() -> void;
};
} /* namespace Sara */
} /* namespace DO */
<|endoftext|> |
<commit_before>#include <memory>
#include "celero/Celero.h"
#include <blackhole/log.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/sink/null.hpp>
#include <blackhole/repository.hpp>
using namespace blackhole;
enum level {
debug,
info,
warning,
error,
critical
};
const int N = 200000;
std::string map_timestamp(const timeval& tv) {
char str[64];
struct tm tm;
localtime_r((time_t *)&tv.tv_sec, &tm);
if (std::strftime(str, sizeof(str), "%F %T", &tm)) {
return str;
}
return "UNKNOWN";
}
std::string map_severity(const level& level) {
static const char* descriptions[] = {
"DEBUG",
"INFO",
"WARNING",
"ERROR",
"CRITICAL"
};
if (static_cast<std::size_t>(level) < sizeof(descriptions) / sizeof(*descriptions))
return descriptions[level];
return std::to_string(static_cast<int>(level));
}
void init_blackhole_log() {
repository_t<level>::instance().configure<
sink::null_t,
formatter::string_t
>();
mapping::value_t mapper;
mapper.add<timeval>("timestamp", &map_timestamp);
mapper.add<level>("severity", &map_severity);
formatter_config_t formatter("string", mapper);
formatter["pattern"] = "[%(timestamp)s] [%(severity)s]: %(message)s";
sink_config_t sink("null");
frontend_config_t frontend = { formatter, sink };
log_config_t config{ "root", { frontend } };
repository_t<level>::instance().add_config(config);
}
verbose_logger_t<level> *log_;
int main(int argc, char** argv) {
init_blackhole_log();
auto log = repository_t<level>::instance().root();
log_ = &log;
celero::Run(argc, argv);
return 0;
}
BASELINE(CeleroBenchTest, BoostLog, 0, N) {
BH_LOG((*log_), warning, "Something bad is going on but I can handle it");
}
<commit_msg>Benchmark specialization.<commit_after>#include <memory>
#include "celero/Celero.h"
#include <blackhole/log.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/sink/null.hpp>
#include <blackhole/repository.hpp>
using namespace blackhole;
enum level {
debug,
info,
warning,
error,
critical
};
const int N = 200000;
std::string map_timestamp(const timeval& tv) {
char str[64];
struct tm tm;
localtime_r((time_t *)&tv.tv_sec, &tm);
if (std::strftime(str, sizeof(str), "%F %T", &tm)) {
return str;
}
return "UNKNOWN";
}
std::string map_severity(const level& level) {
static const char* descriptions[] = {
"DEBUG",
"INFO",
"WARNING",
"ERROR",
"CRITICAL"
};
if (static_cast<std::size_t>(level) < sizeof(descriptions) / sizeof(*descriptions))
return descriptions[level];
return std::to_string(static_cast<int>(level));
}
formatter::string_t fmt("[%(timestamp)s] [%(severity)s]: %(message)s");
void init_blackhole_log() {
repository_t<level>::instance().configure<
sink::null_t,
formatter::string_t
>();
mapping::value_t mapper;
mapper.add<timeval>("timestamp", &map_timestamp);
mapper.add<level>("severity", &map_severity);
fmt.set_mapper(mapper);
formatter_config_t formatter("string", mapper);
formatter["pattern"] = "[%(timestamp)s] [%(severity)s]: %(message)s";
sink_config_t sink("null");
frontend_config_t frontend = { formatter, sink };
log_config_t config{ "root", { frontend } };
repository_t<level>::instance().add_config(config);
}
verbose_logger_t<level> *log_;
int main(int argc, char** argv) {
init_blackhole_log();
auto log = repository_t<level>::instance().root();
log_ = &log;
celero::Run(argc, argv);
return 0;
}
BASELINE(PureStringFormatter, Baseline, 0, N) {
log::record_t record;
record.attributes.insert(keyword::message() = "Something bad is going on but I can handle it");
timeval tv;
gettimeofday(&tv, nullptr);
record.attributes.insert(keyword::timestamp() = tv);
record.attributes.insert(keyword::severity<level>() = level::warning);
celero::DoNotOptimizeAway(fmt.format(record));
}
<|endoftext|> |
<commit_before>#include "mo/SmellFinder.h"
#include "mo/TraverseAST.h"
#include "mo/util/FileUtil.h"
#include "mo/exception/MessageBasedException.h"
#include <iostream>
SmellFinder::SmellFinder() {
_index = clang_createIndex(0, 0);
_translationUnit = 0;
}
SmellFinder::~SmellFinder() {
clang_disposeTranslationUnit(_translationUnit);
clang_disposeIndex(_index);
}
void SmellFinder::compileSourceFileToTranslationUnit(string src) {
if (FileUtil::isSrcExists(src)) {
_translationUnit = clang_parseTranslationUnit(_index, src.c_str(), 0, 0, 0, 0, CXTranslationUnit_None);
if (!_translationUnit) {
throw new MessageBasedException("Code compilation fails!");
}
}
else {
throw new MessageBasedException("File doesn't exist!");
}
}
bool SmellFinder::hasSmell(string src) {
compileSourceFileToTranslationUnit(src);
clang_visitChildren(clang_getTranslationUnitCursor(_translationUnit), traverseAST, 0);
return false;
}
<commit_msg>pass RuleViolation to ASTVisitor<commit_after>#include "mo/SmellFinder.h"
#include "mo/TraverseAST.h"
#include "mo/RuleViolation.h"
#include "mo/util/FileUtil.h"
#include "mo/exception/MessageBasedException.h"
#include <iostream>
SmellFinder::SmellFinder() {
_index = clang_createIndex(0, 0);
_translationUnit = 0;
}
SmellFinder::~SmellFinder() {
clang_disposeTranslationUnit(_translationUnit);
clang_disposeIndex(_index);
}
void SmellFinder::compileSourceFileToTranslationUnit(string src) {
if (FileUtil::isSrcExists(src)) {
_translationUnit = clang_parseTranslationUnit(_index, src.c_str(), 0, 0, 0, 0, CXTranslationUnit_None);
if (!_translationUnit) {
throw new MessageBasedException("Code compilation fails!");
}
}
else {
throw new MessageBasedException("File doesn't exist!");
}
}
bool SmellFinder::hasSmell(string src) {
compileSourceFileToTranslationUnit(src);
RuleViolation *violation = new RuleViolation();
clang_visitChildren(clang_getTranslationUnitCursor(_translationUnit), traverseAST, violation);
return violation->numberOfViolations();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkPictureShader.h"
#include "SkBitmap.h"
#include "SkBitmapProcShader.h"
#include "SkCanvas.h"
#include "SkImageGenerator.h"
#include "SkMatrixUtils.h"
#include "SkPicture.h"
#include "SkReadBuffer.h"
#include "SkResourceCache.h"
#if SK_SUPPORT_GPU
#include "GrContext.h"
#include "GrCaps.h"
#endif
namespace {
static unsigned gBitmapSkaderKeyNamespaceLabel;
struct BitmapShaderKey : public SkResourceCache::Key {
public:
BitmapShaderKey(uint32_t pictureID,
const SkRect& tile,
SkShader::TileMode tmx,
SkShader::TileMode tmy,
const SkSize& scale,
const SkMatrix& localMatrix)
: fPictureID(pictureID)
, fTile(tile)
, fTmx(tmx)
, fTmy(tmy)
, fScale(scale) {
for (int i = 0; i < 9; ++i) {
fLocalMatrixStorage[i] = localMatrix[i];
}
static const size_t keySize = sizeof(fPictureID) +
sizeof(fTile) +
sizeof(fTmx) + sizeof(fTmy) +
sizeof(fScale) +
sizeof(fLocalMatrixStorage);
// This better be packed.
SkASSERT(sizeof(uint32_t) * (&fEndOfStruct - &fPictureID) == keySize);
this->init(&gBitmapSkaderKeyNamespaceLabel, 0, keySize);
}
private:
uint32_t fPictureID;
SkRect fTile;
SkShader::TileMode fTmx, fTmy;
SkSize fScale;
SkScalar fLocalMatrixStorage[9];
SkDEBUGCODE(uint32_t fEndOfStruct;)
};
struct BitmapShaderRec : public SkResourceCache::Rec {
BitmapShaderRec(const BitmapShaderKey& key, SkShader* tileShader, size_t bitmapBytes)
: fKey(key)
, fShader(SkRef(tileShader))
, fBitmapBytes(bitmapBytes) {}
BitmapShaderKey fKey;
SkAutoTUnref<SkShader> fShader;
size_t fBitmapBytes;
const Key& getKey() const override { return fKey; }
size_t bytesUsed() const override {
return sizeof(fKey) + sizeof(SkShader) + fBitmapBytes;
}
const char* getCategory() const override { return "bitmap-shader"; }
SkDiscardableMemory* diagnostic_only_getDiscardable() const override { return nullptr; }
static bool Visitor(const SkResourceCache::Rec& baseRec, void* contextShader) {
const BitmapShaderRec& rec = static_cast<const BitmapShaderRec&>(baseRec);
SkAutoTUnref<SkShader>* result = reinterpret_cast<SkAutoTUnref<SkShader>*>(contextShader);
result->reset(SkRef(rec.fShader.get()));
// The bitmap shader is backed by an image generator, thus it can always re-generate its
// pixels if discarded.
return true;
}
};
} // namespace
SkPictureShader::SkPictureShader(const SkPicture* picture, TileMode tmx, TileMode tmy,
const SkMatrix* localMatrix, const SkRect* tile)
: INHERITED(localMatrix)
, fPicture(SkRef(picture))
, fTile(tile ? *tile : picture->cullRect())
, fTmx(tmx)
, fTmy(tmy) {
}
SkShader* SkPictureShader::Create(const SkPicture* picture, TileMode tmx, TileMode tmy,
const SkMatrix* localMatrix, const SkRect* tile) {
if (!picture || picture->cullRect().isEmpty() || (tile && tile->isEmpty())) {
return SkShader::CreateEmptyShader();
}
return new SkPictureShader(picture, tmx, tmy, localMatrix, tile);
}
SkFlattenable* SkPictureShader::CreateProc(SkReadBuffer& buffer) {
SkMatrix lm;
buffer.readMatrix(&lm);
TileMode mx = (TileMode)buffer.read32();
TileMode my = (TileMode)buffer.read32();
SkRect tile;
buffer.readRect(&tile);
SkAutoTUnref<SkPicture> picture;
if (buffer.isCrossProcess() && SkPicture::PictureIOSecurityPrecautionsEnabled()) {
if (buffer.isVersionLT(SkReadBuffer::kPictureShaderHasPictureBool_Version)) {
// Older code blindly serialized pictures. We don't trust them.
buffer.validate(false);
return nullptr;
}
// Newer code won't serialize pictures in disallow-cross-process-picture mode.
// Assert that they didn't serialize anything except a false here.
buffer.validate(!buffer.readBool());
} else {
// Old code always serialized the picture. New code writes a 'true' first if it did.
if (buffer.isVersionLT(SkReadBuffer::kPictureShaderHasPictureBool_Version) ||
buffer.readBool()) {
picture.reset(SkPicture::CreateFromBuffer(buffer));
}
}
return SkPictureShader::Create(picture, mx, my, &lm, &tile);
}
void SkPictureShader::flatten(SkWriteBuffer& buffer) const {
buffer.writeMatrix(this->getLocalMatrix());
buffer.write32(fTmx);
buffer.write32(fTmy);
buffer.writeRect(fTile);
// The deserialization code won't trust that our serialized picture is safe to deserialize.
// So write a 'false' telling it that we're not serializing a picture.
if (buffer.isCrossProcess() && SkPicture::PictureIOSecurityPrecautionsEnabled()) {
buffer.writeBool(false);
} else {
buffer.writeBool(true);
fPicture->flatten(buffer);
}
}
SkShader* SkPictureShader::refBitmapShader(const SkMatrix& viewMatrix, const SkMatrix* localM,
const int maxTextureSize) const {
SkASSERT(fPicture && !fPicture->cullRect().isEmpty());
SkMatrix m;
m.setConcat(viewMatrix, this->getLocalMatrix());
if (localM) {
m.preConcat(*localM);
}
// Use a rotation-invariant scale
SkPoint scale;
//
// TODO: replace this with decomposeScale() -- but beware LayoutTest rebaselines!
//
if (!SkDecomposeUpper2x2(m, nullptr, &scale, nullptr)) {
// Decomposition failed, use an approximation.
scale.set(SkScalarSqrt(m.getScaleX() * m.getScaleX() + m.getSkewX() * m.getSkewX()),
SkScalarSqrt(m.getScaleY() * m.getScaleY() + m.getSkewY() * m.getSkewY()));
}
SkSize scaledSize = SkSize::Make(SkScalarAbs(scale.x() * fTile.width()),
SkScalarAbs(scale.y() * fTile.height()));
// Clamp the tile size to about 4M pixels
static const SkScalar kMaxTileArea = 2048 * 2048;
SkScalar tileArea = SkScalarMul(scaledSize.width(), scaledSize.height());
if (tileArea > kMaxTileArea) {
SkScalar clampScale = SkScalarSqrt(kMaxTileArea / tileArea);
scaledSize.set(SkScalarMul(scaledSize.width(), clampScale),
SkScalarMul(scaledSize.height(), clampScale));
}
#if SK_SUPPORT_GPU
// Scale down the tile size if larger than maxTextureSize for GPU Path or it should fail on create texture
if (maxTextureSize) {
if (scaledSize.width() > maxTextureSize || scaledSize.height() > maxTextureSize) {
SkScalar downScale = maxTextureSize / SkMax32(scaledSize.width(), scaledSize.height());
scaledSize.set(SkScalarFloorToScalar(SkScalarMul(scaledSize.width(), downScale)),
SkScalarFloorToScalar(SkScalarMul(scaledSize.height(), downScale)));
}
}
#endif
SkISize tileSize = scaledSize.toRound();
if (tileSize.isEmpty()) {
return SkShader::CreateEmptyShader();
}
// The actual scale, compensating for rounding & clamping.
SkSize tileScale = SkSize::Make(SkIntToScalar(tileSize.width()) / fTile.width(),
SkIntToScalar(tileSize.height()) / fTile.height());
SkAutoTUnref<SkShader> tileShader;
BitmapShaderKey key(fPicture->uniqueID(),
fTile,
fTmx,
fTmy,
tileScale,
this->getLocalMatrix());
if (!SkResourceCache::Find(key, BitmapShaderRec::Visitor, &tileShader)) {
SkMatrix tileMatrix;
tileMatrix.setRectToRect(fTile, SkRect::MakeIWH(tileSize.width(), tileSize.height()),
SkMatrix::kFill_ScaleToFit);
SkBitmap bm;
if (!SkDEPRECATED_InstallDiscardablePixelRef(
SkImageGenerator::NewFromPicture(tileSize, fPicture, &tileMatrix, nullptr), &bm)) {
return nullptr;
}
SkMatrix shaderMatrix = this->getLocalMatrix();
shaderMatrix.preScale(1 / tileScale.width(), 1 / tileScale.height());
tileShader.reset(CreateBitmapShader(bm, fTmx, fTmy, &shaderMatrix));
SkResourceCache::Add(new BitmapShaderRec(key, tileShader.get(), bm.getSize()));
}
return tileShader.detach();
}
size_t SkPictureShader::contextSize() const {
return sizeof(PictureShaderContext);
}
SkShader::Context* SkPictureShader::onCreateContext(const ContextRec& rec, void* storage) const {
SkAutoTUnref<SkShader> bitmapShader(this->refBitmapShader(*rec.fMatrix, rec.fLocalMatrix));
if (nullptr == bitmapShader.get()) {
return nullptr;
}
return PictureShaderContext::Create(storage, *this, rec, bitmapShader);
}
/////////////////////////////////////////////////////////////////////////////////////////
SkShader::Context* SkPictureShader::PictureShaderContext::Create(void* storage,
const SkPictureShader& shader, const ContextRec& rec, SkShader* bitmapShader) {
PictureShaderContext* ctx = new (storage) PictureShaderContext(shader, rec, bitmapShader);
if (nullptr == ctx->fBitmapShaderContext) {
ctx->~PictureShaderContext();
ctx = nullptr;
}
return ctx;
}
SkPictureShader::PictureShaderContext::PictureShaderContext(
const SkPictureShader& shader, const ContextRec& rec, SkShader* bitmapShader)
: INHERITED(shader, rec)
, fBitmapShader(SkRef(bitmapShader))
{
fBitmapShaderContextStorage = sk_malloc_throw(bitmapShader->contextSize());
fBitmapShaderContext = bitmapShader->createContext(rec, fBitmapShaderContextStorage);
//if fBitmapShaderContext is null, we are invalid
}
SkPictureShader::PictureShaderContext::~PictureShaderContext() {
if (fBitmapShaderContext) {
fBitmapShaderContext->~Context();
}
sk_free(fBitmapShaderContextStorage);
}
uint32_t SkPictureShader::PictureShaderContext::getFlags() const {
SkASSERT(fBitmapShaderContext);
return fBitmapShaderContext->getFlags();
}
SkShader::Context::ShadeProc SkPictureShader::PictureShaderContext::asAShadeProc(void** ctx) {
SkASSERT(fBitmapShaderContext);
return fBitmapShaderContext->asAShadeProc(ctx);
}
void SkPictureShader::PictureShaderContext::shadeSpan(int x, int y, SkPMColor dstC[], int count) {
SkASSERT(fBitmapShaderContext);
fBitmapShaderContext->shadeSpan(x, y, dstC, count);
}
void SkPictureShader::PictureShaderContext::shadeSpan16(int x, int y, uint16_t dstC[], int count) {
SkASSERT(fBitmapShaderContext);
fBitmapShaderContext->shadeSpan16(x, y, dstC, count);
}
#ifndef SK_IGNORE_TO_STRING
void SkPictureShader::toString(SkString* str) const {
static const char* gTileModeName[SkShader::kTileModeCount] = {
"clamp", "repeat", "mirror"
};
str->appendf("PictureShader: [%f:%f:%f:%f] ",
fPicture->cullRect().fLeft,
fPicture->cullRect().fTop,
fPicture->cullRect().fRight,
fPicture->cullRect().fBottom);
str->appendf("(%s, %s)", gTileModeName[fTmx], gTileModeName[fTmy]);
this->INHERITED::toString(str);
}
#endif
#if SK_SUPPORT_GPU
const GrFragmentProcessor* SkPictureShader::asFragmentProcessor(
GrContext* context,
const SkMatrix& viewM,
const SkMatrix* localMatrix,
SkFilterQuality fq,
GrProcessorDataManager* procDataManager) const {
int maxTextureSize = 0;
if (context) {
maxTextureSize = context->caps()->maxTextureSize();
}
SkAutoTUnref<SkShader> bitmapShader(this->refBitmapShader(viewM, localMatrix, maxTextureSize));
if (!bitmapShader) {
return nullptr;
}
return bitmapShader->asFragmentProcessor(context, viewM, nullptr, fq, procDataManager);
}
#endif
<commit_msg>SkImage-backed SkPictureShader<commit_after>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkPictureShader.h"
#include "SkCanvas.h"
#include "SkImageCacherator.h"
#include "SkImageGenerator.h"
#include "SkImageShader.h"
#include "SkMatrixUtils.h"
#include "SkPicture.h"
#include "SkReadBuffer.h"
#include "SkResourceCache.h"
#if SK_SUPPORT_GPU
#include "GrContext.h"
#include "GrCaps.h"
#endif
namespace {
static unsigned gBitmapSkaderKeyNamespaceLabel;
struct BitmapShaderKey : public SkResourceCache::Key {
public:
BitmapShaderKey(uint32_t pictureID,
const SkRect& tile,
SkShader::TileMode tmx,
SkShader::TileMode tmy,
const SkSize& scale,
const SkMatrix& localMatrix)
: fPictureID(pictureID)
, fTile(tile)
, fTmx(tmx)
, fTmy(tmy)
, fScale(scale) {
for (int i = 0; i < 9; ++i) {
fLocalMatrixStorage[i] = localMatrix[i];
}
static const size_t keySize = sizeof(fPictureID) +
sizeof(fTile) +
sizeof(fTmx) + sizeof(fTmy) +
sizeof(fScale) +
sizeof(fLocalMatrixStorage);
// This better be packed.
SkASSERT(sizeof(uint32_t) * (&fEndOfStruct - &fPictureID) == keySize);
this->init(&gBitmapSkaderKeyNamespaceLabel, 0, keySize);
}
private:
uint32_t fPictureID;
SkRect fTile;
SkShader::TileMode fTmx, fTmy;
SkSize fScale;
SkScalar fLocalMatrixStorage[9];
SkDEBUGCODE(uint32_t fEndOfStruct;)
};
struct BitmapShaderRec : public SkResourceCache::Rec {
BitmapShaderRec(const BitmapShaderKey& key, SkShader* tileShader, size_t bitmapBytes)
: fKey(key)
, fShader(SkRef(tileShader))
, fBitmapBytes(bitmapBytes) {}
BitmapShaderKey fKey;
SkAutoTUnref<SkShader> fShader;
size_t fBitmapBytes;
const Key& getKey() const override { return fKey; }
size_t bytesUsed() const override {
return sizeof(fKey) + sizeof(SkShader) + fBitmapBytes;
}
const char* getCategory() const override { return "bitmap-shader"; }
SkDiscardableMemory* diagnostic_only_getDiscardable() const override { return nullptr; }
static bool Visitor(const SkResourceCache::Rec& baseRec, void* contextShader) {
const BitmapShaderRec& rec = static_cast<const BitmapShaderRec&>(baseRec);
SkAutoTUnref<SkShader>* result = reinterpret_cast<SkAutoTUnref<SkShader>*>(contextShader);
result->reset(SkRef(rec.fShader.get()));
// The bitmap shader is backed by an image generator, thus it can always re-generate its
// pixels if discarded.
return true;
}
};
} // namespace
SkPictureShader::SkPictureShader(const SkPicture* picture, TileMode tmx, TileMode tmy,
const SkMatrix* localMatrix, const SkRect* tile)
: INHERITED(localMatrix)
, fPicture(SkRef(picture))
, fTile(tile ? *tile : picture->cullRect())
, fTmx(tmx)
, fTmy(tmy) {
}
SkShader* SkPictureShader::Create(const SkPicture* picture, TileMode tmx, TileMode tmy,
const SkMatrix* localMatrix, const SkRect* tile) {
if (!picture || picture->cullRect().isEmpty() || (tile && tile->isEmpty())) {
return SkShader::CreateEmptyShader();
}
return new SkPictureShader(picture, tmx, tmy, localMatrix, tile);
}
SkFlattenable* SkPictureShader::CreateProc(SkReadBuffer& buffer) {
SkMatrix lm;
buffer.readMatrix(&lm);
TileMode mx = (TileMode)buffer.read32();
TileMode my = (TileMode)buffer.read32();
SkRect tile;
buffer.readRect(&tile);
SkAutoTUnref<SkPicture> picture;
if (buffer.isCrossProcess() && SkPicture::PictureIOSecurityPrecautionsEnabled()) {
if (buffer.isVersionLT(SkReadBuffer::kPictureShaderHasPictureBool_Version)) {
// Older code blindly serialized pictures. We don't trust them.
buffer.validate(false);
return nullptr;
}
// Newer code won't serialize pictures in disallow-cross-process-picture mode.
// Assert that they didn't serialize anything except a false here.
buffer.validate(!buffer.readBool());
} else {
// Old code always serialized the picture. New code writes a 'true' first if it did.
if (buffer.isVersionLT(SkReadBuffer::kPictureShaderHasPictureBool_Version) ||
buffer.readBool()) {
picture.reset(SkPicture::CreateFromBuffer(buffer));
}
}
return SkPictureShader::Create(picture, mx, my, &lm, &tile);
}
void SkPictureShader::flatten(SkWriteBuffer& buffer) const {
buffer.writeMatrix(this->getLocalMatrix());
buffer.write32(fTmx);
buffer.write32(fTmy);
buffer.writeRect(fTile);
// The deserialization code won't trust that our serialized picture is safe to deserialize.
// So write a 'false' telling it that we're not serializing a picture.
if (buffer.isCrossProcess() && SkPicture::PictureIOSecurityPrecautionsEnabled()) {
buffer.writeBool(false);
} else {
buffer.writeBool(true);
fPicture->flatten(buffer);
}
}
SkShader* SkPictureShader::refBitmapShader(const SkMatrix& viewMatrix, const SkMatrix* localM,
const int maxTextureSize) const {
SkASSERT(fPicture && !fPicture->cullRect().isEmpty());
SkMatrix m;
m.setConcat(viewMatrix, this->getLocalMatrix());
if (localM) {
m.preConcat(*localM);
}
// Use a rotation-invariant scale
SkPoint scale;
//
// TODO: replace this with decomposeScale() -- but beware LayoutTest rebaselines!
//
if (!SkDecomposeUpper2x2(m, nullptr, &scale, nullptr)) {
// Decomposition failed, use an approximation.
scale.set(SkScalarSqrt(m.getScaleX() * m.getScaleX() + m.getSkewX() * m.getSkewX()),
SkScalarSqrt(m.getScaleY() * m.getScaleY() + m.getSkewY() * m.getSkewY()));
}
SkSize scaledSize = SkSize::Make(SkScalarAbs(scale.x() * fTile.width()),
SkScalarAbs(scale.y() * fTile.height()));
// Clamp the tile size to about 4M pixels
static const SkScalar kMaxTileArea = 2048 * 2048;
SkScalar tileArea = SkScalarMul(scaledSize.width(), scaledSize.height());
if (tileArea > kMaxTileArea) {
SkScalar clampScale = SkScalarSqrt(kMaxTileArea / tileArea);
scaledSize.set(SkScalarMul(scaledSize.width(), clampScale),
SkScalarMul(scaledSize.height(), clampScale));
}
#if SK_SUPPORT_GPU
// Scale down the tile size if larger than maxTextureSize for GPU Path or it should fail on create texture
if (maxTextureSize) {
if (scaledSize.width() > maxTextureSize || scaledSize.height() > maxTextureSize) {
SkScalar downScale = maxTextureSize / SkMax32(scaledSize.width(), scaledSize.height());
scaledSize.set(SkScalarFloorToScalar(SkScalarMul(scaledSize.width(), downScale)),
SkScalarFloorToScalar(SkScalarMul(scaledSize.height(), downScale)));
}
}
#endif
SkISize tileSize = scaledSize.toRound();
if (tileSize.isEmpty()) {
return SkShader::CreateEmptyShader();
}
// The actual scale, compensating for rounding & clamping.
SkSize tileScale = SkSize::Make(SkIntToScalar(tileSize.width()) / fTile.width(),
SkIntToScalar(tileSize.height()) / fTile.height());
SkAutoTUnref<SkShader> tileShader;
BitmapShaderKey key(fPicture->uniqueID(),
fTile,
fTmx,
fTmy,
tileScale,
this->getLocalMatrix());
if (!SkResourceCache::Find(key, BitmapShaderRec::Visitor, &tileShader)) {
SkMatrix tileMatrix =
SkMatrix::MakeRectToRect(fTile, SkRect::MakeIWH(tileSize.width(), tileSize.height()),
SkMatrix::kFill_ScaleToFit);
SkAutoTUnref<SkImage> tileImage(
SkImage::NewFromPicture(fPicture, tileSize, &tileMatrix, nullptr));
if (!tileImage) {
return nullptr;
}
SkMatrix shaderMatrix = this->getLocalMatrix();
shaderMatrix.preScale(1 / tileScale.width(), 1 / tileScale.height());
tileShader.reset(tileImage->newShader(fTmx, fTmy, &shaderMatrix));
// The actual pixels are accounted for in the SkImage cacherator budget. Here we
// use a rough estimate for the related objects.
const size_t bytesUsed = sizeof(SkImageShader) +
sizeof(SkImage) +
sizeof(SkImageCacherator) +
sizeof(SkImageGenerator);
SkResourceCache::Add(new BitmapShaderRec(key, tileShader.get(), bytesUsed));
}
return tileShader.detach();
}
size_t SkPictureShader::contextSize() const {
return sizeof(PictureShaderContext);
}
SkShader::Context* SkPictureShader::onCreateContext(const ContextRec& rec, void* storage) const {
SkAutoTUnref<SkShader> bitmapShader(this->refBitmapShader(*rec.fMatrix, rec.fLocalMatrix));
if (nullptr == bitmapShader.get()) {
return nullptr;
}
return PictureShaderContext::Create(storage, *this, rec, bitmapShader);
}
/////////////////////////////////////////////////////////////////////////////////////////
SkShader::Context* SkPictureShader::PictureShaderContext::Create(void* storage,
const SkPictureShader& shader, const ContextRec& rec, SkShader* bitmapShader) {
PictureShaderContext* ctx = new (storage) PictureShaderContext(shader, rec, bitmapShader);
if (nullptr == ctx->fBitmapShaderContext) {
ctx->~PictureShaderContext();
ctx = nullptr;
}
return ctx;
}
SkPictureShader::PictureShaderContext::PictureShaderContext(
const SkPictureShader& shader, const ContextRec& rec, SkShader* bitmapShader)
: INHERITED(shader, rec)
, fBitmapShader(SkRef(bitmapShader))
{
fBitmapShaderContextStorage = sk_malloc_throw(bitmapShader->contextSize());
fBitmapShaderContext = bitmapShader->createContext(rec, fBitmapShaderContextStorage);
//if fBitmapShaderContext is null, we are invalid
}
SkPictureShader::PictureShaderContext::~PictureShaderContext() {
if (fBitmapShaderContext) {
fBitmapShaderContext->~Context();
}
sk_free(fBitmapShaderContextStorage);
}
uint32_t SkPictureShader::PictureShaderContext::getFlags() const {
SkASSERT(fBitmapShaderContext);
return fBitmapShaderContext->getFlags();
}
SkShader::Context::ShadeProc SkPictureShader::PictureShaderContext::asAShadeProc(void** ctx) {
SkASSERT(fBitmapShaderContext);
return fBitmapShaderContext->asAShadeProc(ctx);
}
void SkPictureShader::PictureShaderContext::shadeSpan(int x, int y, SkPMColor dstC[], int count) {
SkASSERT(fBitmapShaderContext);
fBitmapShaderContext->shadeSpan(x, y, dstC, count);
}
void SkPictureShader::PictureShaderContext::shadeSpan16(int x, int y, uint16_t dstC[], int count) {
SkASSERT(fBitmapShaderContext);
fBitmapShaderContext->shadeSpan16(x, y, dstC, count);
}
#ifndef SK_IGNORE_TO_STRING
void SkPictureShader::toString(SkString* str) const {
static const char* gTileModeName[SkShader::kTileModeCount] = {
"clamp", "repeat", "mirror"
};
str->appendf("PictureShader: [%f:%f:%f:%f] ",
fPicture->cullRect().fLeft,
fPicture->cullRect().fTop,
fPicture->cullRect().fRight,
fPicture->cullRect().fBottom);
str->appendf("(%s, %s)", gTileModeName[fTmx], gTileModeName[fTmy]);
this->INHERITED::toString(str);
}
#endif
#if SK_SUPPORT_GPU
const GrFragmentProcessor* SkPictureShader::asFragmentProcessor(
GrContext* context,
const SkMatrix& viewM,
const SkMatrix* localMatrix,
SkFilterQuality fq,
GrProcessorDataManager* procDataManager) const {
int maxTextureSize = 0;
if (context) {
maxTextureSize = context->caps()->maxTextureSize();
}
SkAutoTUnref<SkShader> bitmapShader(this->refBitmapShader(viewM, localMatrix, maxTextureSize));
if (!bitmapShader) {
return nullptr;
}
return bitmapShader->asFragmentProcessor(context, viewM, nullptr, fq, procDataManager);
}
#endif
<|endoftext|> |
<commit_before>//===------------------------- cxa_default_handlers.cpp -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//
// This file implements the default terminate_handler and unexpected_handler.
//===----------------------------------------------------------------------===//
#include <stdexcept>
#include <new>
#include <exception>
#include <cstdlib>
#include "abort_message.h"
#include "config.h" // For __sync_swap
#include "cxxabi.h"
#include "cxa_handlers.hpp"
#include "cxa_exception.hpp"
#include "private_typeinfo.h"
static const char* cause = "uncaught";
__attribute__((noreturn))
static void demangling_terminate_handler()
{
// If there might be an uncaught exception
using namespace __cxxabiv1;
__cxa_eh_globals* globals = __cxa_get_globals_fast();
if (globals)
{
__cxa_exception* exception_header = globals->caughtExceptions;
// If there is an uncaught exception
if (exception_header)
{
_Unwind_Exception* unwind_exception =
reinterpret_cast<_Unwind_Exception*>(exception_header + 1) - 1;
bool native_exception =
(unwind_exception->exception_class & get_vendor_and_language) ==
(kOurExceptionClass & get_vendor_and_language);
if (native_exception)
{
void* thrown_object =
unwind_exception->exception_class == kOurDependentExceptionClass ?
((__cxa_dependent_exception*)exception_header)->primaryException :
exception_header + 1;
const __shim_type_info* thrown_type =
static_cast<const __shim_type_info*>(exception_header->exceptionType);
// Try to get demangled name of thrown_type
int status;
char buf[1024];
size_t len = sizeof(buf);
const char* name = __cxa_demangle(thrown_type->name(), buf, &len, &status);
if (status != 0)
name = thrown_type->name();
// If the uncaught exception can be caught with std::exception&
const __shim_type_info* catch_type =
static_cast<const __shim_type_info*>(&typeid(std::exception));
if (catch_type->can_catch(thrown_type, thrown_object))
{
// Include the what() message from the exception
const std::exception* e = static_cast<const std::exception*>(thrown_object);
abort_message("terminating with %s exception of type %s: %s",
cause, name, e->what());
}
else
// Else just note that we're terminating with an exception
abort_message("terminating with %s exception of type %s",
cause, name);
}
else
// Else we're terminating with a foreign exception
abort_message("terminating with %s foreign exception", cause);
}
}
// Else just note that we're terminating
abort_message("terminating");
}
__attribute__((noreturn))
static void demangling_unexpected_handler()
{
cause = "unexpected";
std::terminate();
}
#if !LIBCXXABI_SILENT_TERMINATE
static std::terminate_handler default_terminate_handler = demangling_terminate_handler;
static std::terminate_handler default_unexpected_handler = demangling_unexpected_handler;
#else
static std::terminate_handler default_terminate_handler = std::abort;
static std::terminate_handler default_unexpected_handler = std::abort;
#endif
//
// Global variables that hold the pointers to the current handler
//
_LIBCXXABI_DATA_VIS
std::terminate_handler __cxa_terminate_handler = default_terminate_handler;
_LIBCXXABI_DATA_VIS
std::unexpected_handler __cxa_unexpected_handler = default_unexpected_handler;
// In the future these will become:
// std::atomic<std::terminate_handler> __cxa_terminate_handler(default_terminate_handler);
// std::atomic<std::unexpected_handler> __cxa_unexpected_handler(default_unexpected_handler);
namespace std
{
unexpected_handler
set_unexpected(unexpected_handler func) _NOEXCEPT
{
if (func == 0)
func = default_unexpected_handler;
return __atomic_exchange_n(&__cxa_unexpected_handler, func,
__ATOMIC_ACQ_REL);
// Using of C++11 atomics this should be rewritten
// return __cxa_unexpected_handler.exchange(func, memory_order_acq_rel);
}
terminate_handler
set_terminate(terminate_handler func) _NOEXCEPT
{
if (func == 0)
func = default_terminate_handler;
return __atomic_exchange_n(&__cxa_terminate_handler, func,
__ATOMIC_ACQ_REL);
// Using of C++11 atomics this should be rewritten
// return __cxa_terminate_handler.exchange(func, memory_order_acq_rel);
}
}
<commit_msg>Fix couple of test failures when using the LIBCXXABI_SILENT_TERMINATE mode.<commit_after>//===------------------------- cxa_default_handlers.cpp -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//
// This file implements the default terminate_handler and unexpected_handler.
//===----------------------------------------------------------------------===//
#include <stdexcept>
#include <new>
#include <exception>
#include <cstdlib>
#include "abort_message.h"
#include "config.h" // For __sync_swap
#include "cxxabi.h"
#include "cxa_handlers.hpp"
#include "cxa_exception.hpp"
#include "private_typeinfo.h"
static const char* cause = "uncaught";
__attribute__((noreturn))
static void demangling_terminate_handler()
{
// If there might be an uncaught exception
using namespace __cxxabiv1;
__cxa_eh_globals* globals = __cxa_get_globals_fast();
if (globals)
{
__cxa_exception* exception_header = globals->caughtExceptions;
// If there is an uncaught exception
if (exception_header)
{
_Unwind_Exception* unwind_exception =
reinterpret_cast<_Unwind_Exception*>(exception_header + 1) - 1;
bool native_exception =
(unwind_exception->exception_class & get_vendor_and_language) ==
(kOurExceptionClass & get_vendor_and_language);
if (native_exception)
{
void* thrown_object =
unwind_exception->exception_class == kOurDependentExceptionClass ?
((__cxa_dependent_exception*)exception_header)->primaryException :
exception_header + 1;
const __shim_type_info* thrown_type =
static_cast<const __shim_type_info*>(exception_header->exceptionType);
// Try to get demangled name of thrown_type
int status;
char buf[1024];
size_t len = sizeof(buf);
const char* name = __cxa_demangle(thrown_type->name(), buf, &len, &status);
if (status != 0)
name = thrown_type->name();
// If the uncaught exception can be caught with std::exception&
const __shim_type_info* catch_type =
static_cast<const __shim_type_info*>(&typeid(std::exception));
if (catch_type->can_catch(thrown_type, thrown_object))
{
// Include the what() message from the exception
const std::exception* e = static_cast<const std::exception*>(thrown_object);
abort_message("terminating with %s exception of type %s: %s",
cause, name, e->what());
}
else
// Else just note that we're terminating with an exception
abort_message("terminating with %s exception of type %s",
cause, name);
}
else
// Else we're terminating with a foreign exception
abort_message("terminating with %s foreign exception", cause);
}
}
// Else just note that we're terminating
abort_message("terminating");
}
__attribute__((noreturn))
static void demangling_unexpected_handler()
{
cause = "unexpected";
std::terminate();
}
#if !LIBCXXABI_SILENT_TERMINATE
static std::terminate_handler default_terminate_handler = demangling_terminate_handler;
static std::terminate_handler default_unexpected_handler = demangling_unexpected_handler;
#else
static std::terminate_handler default_terminate_handler = std::abort;
static std::terminate_handler default_unexpected_handler = std::terminate;
#endif
//
// Global variables that hold the pointers to the current handler
//
_LIBCXXABI_DATA_VIS
std::terminate_handler __cxa_terminate_handler = default_terminate_handler;
_LIBCXXABI_DATA_VIS
std::unexpected_handler __cxa_unexpected_handler = default_unexpected_handler;
// In the future these will become:
// std::atomic<std::terminate_handler> __cxa_terminate_handler(default_terminate_handler);
// std::atomic<std::unexpected_handler> __cxa_unexpected_handler(default_unexpected_handler);
namespace std
{
unexpected_handler
set_unexpected(unexpected_handler func) _NOEXCEPT
{
if (func == 0)
func = default_unexpected_handler;
return __atomic_exchange_n(&__cxa_unexpected_handler, func,
__ATOMIC_ACQ_REL);
// Using of C++11 atomics this should be rewritten
// return __cxa_unexpected_handler.exchange(func, memory_order_acq_rel);
}
terminate_handler
set_terminate(terminate_handler func) _NOEXCEPT
{
if (func == 0)
func = default_terminate_handler;
return __atomic_exchange_n(&__cxa_terminate_handler, func,
__ATOMIC_ACQ_REL);
// Using of C++11 atomics this should be rewritten
// return __cxa_terminate_handler.exchange(func, memory_order_acq_rel);
}
}
<|endoftext|> |
<commit_before>//
// Created by max on 23/03/17.
//
#include <fstream>
#include "SettingsManager.h"
SettingsManager * SettingsManager::instance = nullptr;
SettingsManager::SettingsManager()
{
QString const userHome = []() -> QString {
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
return QString(homedir) + "/";
}();
QString const configFolder = userHome + ".config/finances-manager/";
mDatabaseLocation = QString(configFolder) + "finances.db";
mDefaultPlotType = PlotType::CUMULATIVE_WITH_MINMAX;
// TODO
// load rc file
mConfigFilePath = configFolder + "config";
loadConfig(mConfigFilePath);
atexit(deallocateSettingsManagerAtExit);
}
SettingsManager::~SettingsManager()
{
std::ofstream config (mConfigFilePath.toStdString());
config << "defaultPlotType " << static_cast<int>(mDefaultPlotType) << std::endl;
config << "databaseLocation " << mDatabaseLocation.toStdString() << std::endl;
config.close();
}
SettingsManager *
SettingsManager::getInstance()
{
if (instance == nullptr)
{
instance = new SettingsManager;
}
return instance;
}
QString const&
SettingsManager::databaseLocation()
{
return mDatabaseLocation;
}
void
SettingsManager::setDatabaseLocation(QString const& dbLocation)
{
mDatabaseLocation = dbLocation;
emit databaseLocationChanged(dbLocation);
}
PlotType const&
SettingsManager::defaultPlottype()
{
return mDefaultPlotType;
}
void
SettingsManager::setDefaultPlotType(PlotType const& pt)
{
mDefaultPlotType = pt;
emit defaultPlottypeChanged(pt);
}
void
SettingsManager::loadConfig(QString const& filename)
{
std::ifstream configFile;
configFile.open(filename.toStdString().c_str());
std::string token;
while (configFile)
{
configFile >> token;
if (token == "defaultPlotType")
{
int i;
configFile >> i;
mDefaultPlotType = static_cast<PlotType>(i);
}
else if (token == "databaseLocation")
{
configFile >> token;
mDatabaseLocation = QString(token.c_str());
}
}
configFile.close();
}
void
deallocateSettingsManagerAtExit()
{
if (SettingsManager::instance != nullptr) delete SettingsManager::instance;
}
<commit_msg>Removed fixed TODO<commit_after>//
// Created by max on 23/03/17.
//
#include <fstream>
#include "SettingsManager.h"
SettingsManager * SettingsManager::instance = nullptr;
SettingsManager::SettingsManager()
{
QString const userHome = []() -> QString {
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
return QString(homedir) + "/";
}();
QString const configFolder = userHome + ".config/finances-manager/";
mDatabaseLocation = QString(configFolder) + "finances.db";
mDefaultPlotType = PlotType::CUMULATIVE_WITH_MINMAX;
// load rc file
mConfigFilePath = configFolder + "config";
loadConfig(mConfigFilePath);
atexit(deallocateSettingsManagerAtExit);
}
SettingsManager::~SettingsManager()
{
std::ofstream config (mConfigFilePath.toStdString());
config << "defaultPlotType " << static_cast<int>(mDefaultPlotType) << std::endl;
config << "databaseLocation " << mDatabaseLocation.toStdString() << std::endl;
config.close();
}
SettingsManager *
SettingsManager::getInstance()
{
if (instance == nullptr)
{
instance = new SettingsManager;
}
return instance;
}
QString const&
SettingsManager::databaseLocation()
{
return mDatabaseLocation;
}
void
SettingsManager::setDatabaseLocation(QString const& dbLocation)
{
mDatabaseLocation = dbLocation;
emit databaseLocationChanged(dbLocation);
}
PlotType const&
SettingsManager::defaultPlottype()
{
return mDefaultPlotType;
}
void
SettingsManager::setDefaultPlotType(PlotType const& pt)
{
mDefaultPlotType = pt;
emit defaultPlottypeChanged(pt);
}
void
SettingsManager::loadConfig(QString const& filename)
{
std::ifstream configFile;
configFile.open(filename.toStdString().c_str());
std::string token;
while (configFile)
{
configFile >> token;
if (token == "defaultPlotType")
{
int i;
configFile >> i;
mDefaultPlotType = static_cast<PlotType>(i);
}
else if (token == "databaseLocation")
{
configFile >> token;
mDatabaseLocation = QString(token.c_str());
}
}
configFile.close();
}
void
deallocateSettingsManagerAtExit()
{
if (SettingsManager::instance != nullptr) delete SettingsManager::instance;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) <2013-2014>, <BenHJ>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*/
// an implementation of XTEA
#include "teasafe/detail/DetailTeaSafe.hpp"
#include "cipher/scrypt/crypto_scrypt.hpp"
#include "cipher/XTEAByteTransformer.hpp"
#include <boost/make_shared.hpp>
#include <vector>
namespace teasafe { namespace cipher
{
namespace detail
{
// the xtea encipher algorithm as found on wikipedia. Use this to encrypt
// a sequence of numbers. The original plain-text is then xor-ed with this
// sequence
void encipher(unsigned int num_rounds, uint32_t v[2], uint32_t const key[4])
{
unsigned int i;
uint32_t v0=v[0], v1=v[1], sum=0, delta=0x9E3779B9;
for (i=0; i < num_rounds; i++) {
v0 += ((v1 << 4 ^ v1 >> 5) + v1) ^(sum + key[sum & 3]);
sum += delta;
v1 += ((v0 << 4 ^ v0 >> 5) + v0) ^(sum + key[(sum>>11) & 3]);
}
v[0]=v0; v[1]=v1;
}
// helper code found here:
// http://codereview.stackexchange.com/questions/2050/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data
// Question posted by Alan Davis on Sep 6 `08.
void convertBytesAndEncipher(unsigned int num_rounds, unsigned char * buffer, uint32_t const key[4])
{
// convert the input buffer to 2 64bit integers
uint32_t datablock[2];
datablock[0] = (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | (buffer[3]);
datablock[1] = (buffer[4] << 24) | (buffer[5] << 16) | (buffer[6] << 8) | (buffer[7]);
// encrypt the 128 bit number
encipher(num_rounds, datablock, key);
// convert the two 64 bit numbers, now encrypted, to an 8-byte buffer again
buffer[0] = static_cast<unsigned char>((datablock[0] >> 24) & 0xFF);
buffer[1] = static_cast<unsigned char>((datablock[0] >> 16) & 0xFF);
buffer[2] = static_cast<unsigned char>((datablock[0] >> 8) & 0xFF);
buffer[3] = static_cast<unsigned char>((datablock[0]) & 0xFF);
buffer[4] = static_cast<unsigned char>((datablock[1] >> 24) & 0xFF);
buffer[5] = static_cast<unsigned char>((datablock[1] >> 16) & 0xFF);
buffer[6] = static_cast<unsigned char>((datablock[1] >> 8) & 0xFF);
buffer[7] = static_cast<unsigned char>((datablock[1]) & 0xFF);
}
}
// used for holding the hash-generated key
static uint32_t g_key[4];
// used to optimize crypto process. This will store
// the first 256MB of cipher stream
static std::vector<char> g_bigCipherBuffer;
XTEAByteTransformer::XTEAByteTransformer(std::string const &password,
uint64_t const iv,
unsigned int const rounds)
: IByteTransformer()
, m_password(password)
, m_iv(iv)
, m_rounds(rounds) // note, the suggested xtea rounds is 64 in the literature
{
}
void
XTEAByteTransformer::init()
{
//
// The following key generation algorithm uses scrypt, with N = 2^20; r = 8; p = 1
//
if (!IByteTransformer::m_init) {
unsigned char temp[16];
broadcastEvent(EventType::KeyGenBegin);
uint8_t salt[8];
teasafe::detail::convertUInt64ToInt8Array(m_iv, salt);
::crypto_scrypt((uint8_t*)m_password.c_str(), m_password.size(), salt, 8,
1048576, 8, 1, temp, 16);
broadcastEvent(EventType::KeyGenEnd);
int c = 0;
for (int i = 0; i < 16; i += 4) {
unsigned char buf[4];
buf[0] = temp[i];
buf[1] = temp[i + 1];
buf[2] = temp[i + 2];
buf[3] = temp[i + 3];
g_key[c] = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | (buf[3]);
++c;
}
buildBigCipherBuffer();
IByteTransformer::m_init = true;
}
}
XTEAByteTransformer::~XTEAByteTransformer()
{
}
void
XTEAByteTransformer::buildBigCipherBuffer()
{
broadcastEvent(EventType::BigCipherBuildBegin);
std::vector<char>().swap(g_bigCipherBuffer);
std::vector<char> in;
in.resize(teasafe::detail::CIPHER_BUFFER_SIZE);
g_bigCipherBuffer.resize(teasafe::detail::CIPHER_BUFFER_SIZE);
uint64_t div = teasafe::detail::CIPHER_BUFFER_SIZE / 100000;
for(uint64_t i = 0;i<div;++i) {
doTransform((&in.front()) + (i * 100000), (&g_bigCipherBuffer.front()) + (i*100000), 0, 100000);
broadcastEvent(EventType::CipherBuildUpdate);
}
broadcastEvent(EventType::BigCipherBuildEnd);
}
void
XTEAByteTransformer::doTransform(char *in, char *out, std::ios_base::streamoff startPosition, long length) const
{
// big cipher buffer has been initialized
if (IByteTransformer::m_init) {
// prefer to use cipher buffer
if ((startPosition + length) < teasafe::detail::CIPHER_BUFFER_SIZE) {
for (long j = 0; j < length; ++j) {
out[j] = in[j] ^ g_bigCipherBuffer[j + startPosition];
}
return;
}
}
// how many blocks required? defaults to 1, if length greater
// than 8 bytes then more blocks are needed
long blocksRequired = 0;
std::ios_base::streamoff const startPositionOffset = startPosition % 8;
// the counter used to determine where we start in the cipher stream
uint64_t startRD = (startPosition - startPositionOffset);
uint64_t ctr = (startRD / 8) + m_iv;
// encipher the initial 64 bit counter.
UIntVector buf;
buf.resize(8);
cypherBytes(ctr, buf);
// c is a counter used to store which byte is currently being encrypted
long c = 0;
// if the length is > 8, we need to encrypt in multiples of 8
if (length > 8) {
// compute how many blocks of size 8 bytes will be encrypted
long remainder = length % 8;
long roundedDown = length - remainder;
blocksRequired += (roundedDown / 8);
// encrypt blocksRequired times 8 byte blocks of data
doSubTransformations(in, // input buffer
out, // output buffer
startPosition, // seeked-to position
startPositionOffset, // 8-byte block offset
blocksRequired, // number of iterations
c, // stream position
ctr, // the CTR counter
buf); // the cipher text buffer
// encrypt the final block which is of length remainder bytes
if (remainder > 0) {
doSubTransformations(in, out, startPosition, startPositionOffset, 1, c, ctr, buf, remainder);
}
return;
}
// else the length < 8 so just encrypt length bytes
doSubTransformations(in, out, startPosition, startPositionOffset, 1, c, ctr, buf, length);
}
void
XTEAByteTransformer::doXOR(char *in,
char *out,
std::ios_base::streamoff const startPositionOffset,
long &c,
uint64_t &ctr,
int const bytesToEncrypt,
UIntVector &buf) const
{
// now xor plain with key stream
int k = 0;
for (int j = startPositionOffset; j < bytesToEncrypt + startPositionOffset; ++j) {
if (j >= 8) {
// iterate cipher counter and update cipher buffer
if(j == 8) { cypherBytes(ctr, buf); }
out[c] = in[c] ^ buf[k];
++k;
} else { out[c] = in[c] ^ buf[j]; }
++c;
}
}
void
XTEAByteTransformer::cypherBytes(uint64_t &ctr, UIntVector &buf) const
{
teasafe::detail::convertUInt64ToInt8Array(ctr, &buf.front());
detail::convertBytesAndEncipher(m_rounds, &buf.front(), g_key);
++ctr;
}
void
XTEAByteTransformer::doSubTransformations(char *in,
char *out,
std::ios_base::streamoff const startPosition,
std::ios_base::streamoff const startPositionOffset,
long const blocksOfSize8BeingTransformed,
long &c,
uint64_t &ctr,
UIntVector &buf,
int const bytesToEncrypt) const
{
// transform blocks
for (long i = 0; i < blocksOfSize8BeingTransformed; ++i) {
// now XOR plain with key stream.
this->doXOR(in, out, startPositionOffset, c, ctr, bytesToEncrypt, buf);
// cipher buffer needs updating if the start position is 0 in which
// case it won't have been updated by the XOR loop
if(startPositionOffset == 0) { cypherBytes(ctr, buf); }
}
}
}
}
<commit_msg>Fixed xtea cipher comment<commit_after>/*
Copyright (c) <2013-2014>, <BenHJ>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*/
// an implementation of XTEA
#include "teasafe/detail/DetailTeaSafe.hpp"
#include "cipher/scrypt/crypto_scrypt.hpp"
#include "cipher/XTEAByteTransformer.hpp"
#include <boost/make_shared.hpp>
#include <vector>
namespace teasafe { namespace cipher
{
namespace detail
{
// the xtea encipher algorithm as found on wikipedia. Use this to encrypt
// a sequence of numbers. The original plain-text is then xor-ed with this
// sequence
void encipher(unsigned int num_rounds, uint32_t v[2], uint32_t const key[4])
{
unsigned int i;
uint32_t v0=v[0], v1=v[1], sum=0, delta=0x9E3779B9;
for (i=0; i < num_rounds; i++) {
v0 += ((v1 << 4 ^ v1 >> 5) + v1) ^(sum + key[sum & 3]);
sum += delta;
v1 += ((v0 << 4 ^ v0 >> 5) + v0) ^(sum + key[(sum>>11) & 3]);
}
v[0]=v0; v[1]=v1;
}
// helper code found here:
// http://codereview.stackexchange.com/questions/2050/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data
// Question posted by Alan Davis on Sep 6 `08.
void convertBytesAndEncipher(unsigned int num_rounds, unsigned char * buffer, uint32_t const key[4])
{
// convert the input buffer to 2 32bit integers
uint32_t datablock[2];
datablock[0] = (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | (buffer[3]);
datablock[1] = (buffer[4] << 24) | (buffer[5] << 16) | (buffer[6] << 8) | (buffer[7]);
// encrypt the 64 bit number
encipher(num_rounds, datablock, key);
// convert the two 32 bit numbers, now encrypted, to an 8-byte buffer again
buffer[0] = static_cast<unsigned char>((datablock[0] >> 24) & 0xFF);
buffer[1] = static_cast<unsigned char>((datablock[0] >> 16) & 0xFF);
buffer[2] = static_cast<unsigned char>((datablock[0] >> 8) & 0xFF);
buffer[3] = static_cast<unsigned char>((datablock[0]) & 0xFF);
buffer[4] = static_cast<unsigned char>((datablock[1] >> 24) & 0xFF);
buffer[5] = static_cast<unsigned char>((datablock[1] >> 16) & 0xFF);
buffer[6] = static_cast<unsigned char>((datablock[1] >> 8) & 0xFF);
buffer[7] = static_cast<unsigned char>((datablock[1]) & 0xFF);
}
}
// used for holding the hash-generated key
static uint32_t g_key[4];
// used to optimize crypto process. This will store
// the first 256MB of cipher stream
static std::vector<char> g_bigCipherBuffer;
XTEAByteTransformer::XTEAByteTransformer(std::string const &password,
uint64_t const iv,
unsigned int const rounds)
: IByteTransformer()
, m_password(password)
, m_iv(iv)
, m_rounds(rounds) // note, the suggested xtea rounds is 64 in the literature
{
}
void
XTEAByteTransformer::init()
{
//
// The following key generation algorithm uses scrypt, with N = 2^20; r = 8; p = 1
//
if (!IByteTransformer::m_init) {
unsigned char temp[16];
broadcastEvent(EventType::KeyGenBegin);
uint8_t salt[8];
teasafe::detail::convertUInt64ToInt8Array(m_iv, salt);
::crypto_scrypt((uint8_t*)m_password.c_str(), m_password.size(), salt, 8,
1048576, 8, 1, temp, 16);
broadcastEvent(EventType::KeyGenEnd);
int c = 0;
for (int i = 0; i < 16; i += 4) {
unsigned char buf[4];
buf[0] = temp[i];
buf[1] = temp[i + 1];
buf[2] = temp[i + 2];
buf[3] = temp[i + 3];
g_key[c] = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | (buf[3]);
++c;
}
buildBigCipherBuffer();
IByteTransformer::m_init = true;
}
}
XTEAByteTransformer::~XTEAByteTransformer()
{
}
void
XTEAByteTransformer::buildBigCipherBuffer()
{
broadcastEvent(EventType::BigCipherBuildBegin);
std::vector<char>().swap(g_bigCipherBuffer);
std::vector<char> in;
in.resize(teasafe::detail::CIPHER_BUFFER_SIZE);
g_bigCipherBuffer.resize(teasafe::detail::CIPHER_BUFFER_SIZE);
uint64_t div = teasafe::detail::CIPHER_BUFFER_SIZE / 100000;
for(uint64_t i = 0;i<div;++i) {
doTransform((&in.front()) + (i * 100000), (&g_bigCipherBuffer.front()) + (i*100000), 0, 100000);
broadcastEvent(EventType::CipherBuildUpdate);
}
broadcastEvent(EventType::BigCipherBuildEnd);
}
void
XTEAByteTransformer::doTransform(char *in, char *out, std::ios_base::streamoff startPosition, long length) const
{
// big cipher buffer has been initialized
if (IByteTransformer::m_init) {
// prefer to use cipher buffer
if ((startPosition + length) < teasafe::detail::CIPHER_BUFFER_SIZE) {
for (long j = 0; j < length; ++j) {
out[j] = in[j] ^ g_bigCipherBuffer[j + startPosition];
}
return;
}
}
// how many blocks required? defaults to 1, if length greater
// than 8 bytes then more blocks are needed
long blocksRequired = 0;
std::ios_base::streamoff const startPositionOffset = startPosition % 8;
// the counter used to determine where we start in the cipher stream
uint64_t startRD = (startPosition - startPositionOffset);
uint64_t ctr = (startRD / 8) + m_iv;
// encipher the initial 64 bit counter.
UIntVector buf;
buf.resize(8);
cypherBytes(ctr, buf);
// c is a counter used to store which byte is currently being encrypted
long c = 0;
// if the length is > 8, we need to encrypt in multiples of 8
if (length > 8) {
// compute how many blocks of size 8 bytes will be encrypted
long remainder = length % 8;
long roundedDown = length - remainder;
blocksRequired += (roundedDown / 8);
// encrypt blocksRequired times 8 byte blocks of data
doSubTransformations(in, // input buffer
out, // output buffer
startPosition, // seeked-to position
startPositionOffset, // 8-byte block offset
blocksRequired, // number of iterations
c, // stream position
ctr, // the CTR counter
buf); // the cipher text buffer
// encrypt the final block which is of length remainder bytes
if (remainder > 0) {
doSubTransformations(in, out, startPosition, startPositionOffset, 1, c, ctr, buf, remainder);
}
return;
}
// else the length < 8 so just encrypt length bytes
doSubTransformations(in, out, startPosition, startPositionOffset, 1, c, ctr, buf, length);
}
void
XTEAByteTransformer::doXOR(char *in,
char *out,
std::ios_base::streamoff const startPositionOffset,
long &c,
uint64_t &ctr,
int const bytesToEncrypt,
UIntVector &buf) const
{
// now xor plain with key stream
int k = 0;
for (int j = startPositionOffset; j < bytesToEncrypt + startPositionOffset; ++j) {
if (j >= 8) {
// iterate cipher counter and update cipher buffer
if(j == 8) { cypherBytes(ctr, buf); }
out[c] = in[c] ^ buf[k];
++k;
} else { out[c] = in[c] ^ buf[j]; }
++c;
}
}
void
XTEAByteTransformer::cypherBytes(uint64_t &ctr, UIntVector &buf) const
{
teasafe::detail::convertUInt64ToInt8Array(ctr, &buf.front());
detail::convertBytesAndEncipher(m_rounds, &buf.front(), g_key);
++ctr;
}
void
XTEAByteTransformer::doSubTransformations(char *in,
char *out,
std::ios_base::streamoff const startPosition,
std::ios_base::streamoff const startPositionOffset,
long const blocksOfSize8BeingTransformed,
long &c,
uint64_t &ctr,
UIntVector &buf,
int const bytesToEncrypt) const
{
// transform blocks
for (long i = 0; i < blocksOfSize8BeingTransformed; ++i) {
// now XOR plain with key stream.
this->doXOR(in, out, startPositionOffset, c, ctr, bytesToEncrypt, buf);
// cipher buffer needs updating if the start position is 0 in which
// case it won't have been updated by the XOR loop
if(startPositionOffset == 0) { cypherBytes(ctr, buf); }
}
}
}
}
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <service>
#include <info>
__attribute__((weak))
extern "C" int main(int, const char*[]);
__attribute__((weak))
void Service::start(const std::string& cmd)
{
std::string st(cmd); // mangled copy
int argc = 0;
const char* argv[64];
// Populate argv
char* begin = (char*) st.data();
char* end = begin + st.size();
for (char* ptr = begin; ptr < end; ptr++)
if (std::isspace(*ptr)) {
argv[argc++] = begin;
*ptr = 0; // zero terminate
begin = ptr+1; // next arg
}
int exit_status = main(argc, argv);
INFO("main","returned with status %d", exit_status);
//exit(exit_status);
}
<commit_msg>main: Add out of bounds checking<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <service>
#include <info>
#define ARGS_MAX 64
__attribute__((weak))
extern "C" int main(int, const char*[]);
__attribute__((weak))
void Service::start(const std::string& cmd)
{
std::string st(cmd); // mangled copy
int argc = 0;
const char* argv[ARGS_MAX];
// Populate argv
char* begin = (char*) st.data();
char* end = begin + st.size();
for (char* ptr = begin; ptr < end; ptr++)
if (std::isspace(*ptr)) {
argv[argc++] = begin;
*ptr = 0; // zero terminate
begin = ptr+1; // next arg
if (argc >= ARGS_MAX) break;
}
int exit_status = main(argc, argv);
INFO("main","returned with status %d", exit_status);
//exit(exit_status);
}
<|endoftext|> |
<commit_before>#include <os>
#include <kprint>
#include <util/crc32.hpp>
#define SOFT_RESET_MAGIC 0xFEE1DEAD
#define SOFT_RESET_LOCATION 0x7000
namespace hw {
extern uint32_t apic_timer_get_ticks() noexcept;
extern void apic_timer_set_ticks(uint32_t) noexcept;
}
struct softreset_t
{
uint32_t checksum;
MHz cpu_freq;
uint32_t apic_ticks;
};
bool OS::is_softreset_magic(uintptr_t value)
{
return value == SOFT_RESET_MAGIC;
}
void OS::resume_softreset(intptr_t addr)
{
auto* data = (softreset_t*) addr;
/// validate soft-reset data
const uint32_t csum_copy = data->checksum;
data->checksum = 0;
uint32_t crc = crc32(data, sizeof(softreset_t));
if (crc != csum_copy) {
kprintf("[!] Failed to verify CRC of softreset data: %08x vs %08x\n",
crc, csum_copy);
return;
}
data->checksum = csum_copy;
kprint("[!] Soft resetting OS\n");
/// restore known values
OS::cpu_mhz_ = data->cpu_freq;
hw::apic_timer_set_ticks(data->apic_ticks);
}
extern "C"
void* __os_store_soft_reset()
{
// store softreset data in low memory
auto* data = (softreset_t*) SOFT_RESET_LOCATION;
data->checksum = 0;
data->cpu_freq = OS::cpu_freq();
data->apic_ticks = hw::apic_timer_get_ticks();
uint32_t csum = crc32(data, sizeof(softreset_t));
data->checksum = csum;
return data;
}
<commit_msg>kernel: Silence soft-reset<commit_after>#include <os>
#include <kprint>
#include <util/crc32.hpp>
#define SOFT_RESET_MAGIC 0xFEE1DEAD
#define SOFT_RESET_LOCATION 0x7000
namespace hw {
extern uint32_t apic_timer_get_ticks() noexcept;
extern void apic_timer_set_ticks(uint32_t) noexcept;
}
struct softreset_t
{
uint32_t checksum;
MHz cpu_freq;
uint32_t apic_ticks;
};
bool OS::is_softreset_magic(uintptr_t value)
{
return value == SOFT_RESET_MAGIC;
}
void OS::resume_softreset(intptr_t addr)
{
auto* data = (softreset_t*) addr;
/// validate soft-reset data
const uint32_t csum_copy = data->checksum;
data->checksum = 0;
uint32_t crc = crc32(data, sizeof(softreset_t));
if (crc != csum_copy) {
kprintf("[!] Failed to verify CRC of softreset data: %08x vs %08x\n",
crc, csum_copy);
return;
}
data->checksum = csum_copy;
/// restore known values
OS::cpu_mhz_ = data->cpu_freq;
hw::apic_timer_set_ticks(data->apic_ticks);
}
extern "C"
void* __os_store_soft_reset()
{
// store softreset data in low memory
auto* data = (softreset_t*) SOFT_RESET_LOCATION;
data->checksum = 0;
data->cpu_freq = OS::cpu_freq();
data->apic_ticks = hw::apic_timer_get_ticks();
uint32_t csum = crc32(data, sizeof(softreset_t));
data->checksum = csum;
return data;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* libvisio
* Version: MPL 1.1 / GPLv2+ / LGPLv2+
*
* 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 or as specified alternatively below. 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.
*
* Major Contributor(s):
* Copyright (C) 2011 Fridrich Strba <fridrich.strba@bluewin.ch>
* Copyright (C) 2011 Eilidh McAdam <tibbylickle@gmail.com>
*
*
* All Rights Reserved.
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPLv2+"), or
* the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"),
* in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable
* instead of those above.
*/
#include <time.h>
#include "VSDCollector.h"
#include "VSDFieldList.h"
void libvisio::VSDTextField::handle(VSDCollector *collector) const
{
collector->collectTextField(m_id, m_level, m_nameId, m_formatStringId);
}
libvisio::VSDFieldListElement *libvisio::VSDTextField::clone()
{
return new VSDTextField(m_id, m_level, m_nameId, m_formatStringId);
}
WPXString libvisio::VSDTextField::getString(const std::map<unsigned, WPXString> &strVec)
{
std::map<unsigned, WPXString>::const_iterator iter = strVec.find(m_nameId);
if (iter != strVec.end())
return iter->second;
else
return WPXString();
}
void libvisio::VSDTextField::setNameId(int nameId)
{
m_nameId = nameId;
}
void libvisio::VSDNumericField::handle(VSDCollector *collector) const
{
collector->collectNumericField(m_id, m_level, m_format, m_number, m_formatStringId);
}
libvisio::VSDFieldListElement *libvisio::VSDNumericField::clone()
{
return new VSDNumericField(m_id, m_level, m_format, m_number, m_formatStringId);
}
#define MAX_BUFFER 1024
WPXString libvisio::VSDNumericField::datetimeToString(const char *format, double datetime)
{
WPXString result;
char buffer[MAX_BUFFER];
time_t timer = (time_t)(86400 * datetime - 2209161600.0);
strftime(&buffer[0], MAX_BUFFER-1, format, gmtime(&timer));
result.append(&buffer[0]);
return result;
}
WPXString libvisio::VSDNumericField::getString(const std::map<unsigned, WPXString> &)
{
if (m_format == 0xffff)
return WPXString();
switch (m_format)
{
case VSD_FIELD_FORMAT_DateMDYY:
case VSD_FIELD_FORMAT_DateMMDDYY:
case VSD_FIELD_FORMAT_DateMmmDYYYY:
case VSD_FIELD_FORMAT_DateMmmmDYYYY:
case VSD_FIELD_FORMAT_DateDMYY:
case VSD_FIELD_FORMAT_DateDDMMYY:
case VSD_FIELD_FORMAT_DateDMMMYYYY:
case VSD_FIELD_FORMAT_DateDMMMMYYYY:
case VSD_FIELD_FORMAT_Dateyyyymd:
case VSD_FIELD_FORMAT_Dateyymmdd:
case VSD_FIELD_FORMAT_DateTWNfYYYYMMDDD_C:
case VSD_FIELD_FORMAT_DateTWNsYYYYMMDDD_C:
case VSD_FIELD_FORMAT_DateTWNfyyyymmddww_C:
case VSD_FIELD_FORMAT_DateTWNfyyyymmdd_C:
case VSD_FIELD_FORMAT_Dategggemdww_J:
case VSD_FIELD_FORMAT_Dateyyyymdww_J:
case VSD_FIELD_FORMAT_Dategggemd_J:
case VSD_FIELD_FORMAT_Dateyyyymd_J:
case VSD_FIELD_FORMAT_DateYYYYMMMDDDWWW_C:
case VSD_FIELD_FORMAT_DateYYYYMMMDDD_C:
case VSD_FIELD_FORMAT_DategeMMMMddddww_K:
case VSD_FIELD_FORMAT_Dateyyyymdww_K:
case VSD_FIELD_FORMAT_DategeMMMMddd_K:
case VSD_FIELD_FORMAT_Dateyyyymd_K:
case VSD_FIELD_FORMAT_Dateyyyy_m_d:
case VSD_FIELD_FORMAT_Dateyy_mm_dd:
case VSD_FIELD_FORMAT_Dateyyyymd_S:
case VSD_FIELD_FORMAT_Dateyyyymmdd_S:
case VSD_FIELD_FORMAT_Datewwyyyymmdd_S:
case VSD_FIELD_FORMAT_Datewwyyyymd_S:
case VSD_FIELD_FORMAT_MsoDateShort:
case VSD_FIELD_FORMAT_MsoDateLongDay:
case VSD_FIELD_FORMAT_MsoDateLong:
case VSD_FIELD_FORMAT_MsoDateShortAlt:
case VSD_FIELD_FORMAT_MsoDateISO:
case VSD_FIELD_FORMAT_MsoDateShortMon:
case VSD_FIELD_FORMAT_MsoDateShortSlash:
case VSD_FIELD_FORMAT_MsoDateShortAbb:
case VSD_FIELD_FORMAT_MsoDateEnglish:
case VSD_FIELD_FORMAT_MsoDateMonthYr:
case VSD_FIELD_FORMAT_MsoDateMon_Yr:
return datetimeToString("%x", m_number);
case VSD_FIELD_FORMAT_TimeGen:
case VSD_FIELD_FORMAT_TimeHMM:
case VSD_FIELD_FORMAT_TimeHHMM:
case VSD_FIELD_FORMAT_TimeHMM24:
case VSD_FIELD_FORMAT_TimeHHMM24:
case VSD_FIELD_FORMAT_TimeHMMAMPM:
case VSD_FIELD_FORMAT_TimeHHMMAMPM:
case VSD_FIELD_FORMAT_TimeAMPMhmm_J:
case VSD_FIELD_FORMAT_TimeAMPMhmm_C:
case VSD_FIELD_FORMAT_TimeAMPMhmm_K:
case VSD_FIELD_FORMAT_TimeAMPM_hmm_J:
case VSD_FIELD_FORMAT_Timehmm_J:
case VSD_FIELD_FORMAT_TimeAMPM_hmm_C:
case VSD_FIELD_FORMAT_Timehmm_C:
case VSD_FIELD_FORMAT_TimeAMPM_hmm_K:
case VSD_FIELD_FORMAT_Timehmm_K:
case VSD_FIELD_FORMAT_TimeHMMAMPM_E:
case VSD_FIELD_FORMAT_TimeHHMMAMPM_E:
case VSD_FIELD_FORMAT_TimeAMPMhmm_S:
case VSD_FIELD_FORMAT_TimeAMPMhhmm_S:
case VSD_FIELD_FORMAT_MsoTimePM:
case VSD_FIELD_FORMAT_MsoTimeSecPM:
case VSD_FIELD_FORMAT_MsoTime24:
case VSD_FIELD_FORMAT_MsoTimeSec24:
return datetimeToString("%X", m_number);
case VSD_FIELD_FORMAT_MsoTimeDatePM:
case VSD_FIELD_FORMAT_MsoTimeDateSecPM:
return datetimeToString("%x %X", m_number);
default:
{
WPXString result;
WPXProperty *pProp = WPXPropertyFactory::newDoubleProp(m_number);
if (pProp)
{
result = pProp->getStr();
delete pProp;
}
return result;
}
}
}
void libvisio::VSDNumericField::setFormat(unsigned short format)
{
m_format = format;
}
void libvisio::VSDNumericField::setValue(double number)
{
m_number = number;
}
libvisio::VSDFieldList::VSDFieldList() :
m_elements(),
m_elementsOrder(),
m_id(0),
m_level(0)
{
}
libvisio::VSDFieldList::VSDFieldList(const libvisio::VSDFieldList &fieldList) :
m_elements(),
m_elementsOrder(fieldList.m_elementsOrder),
m_id(fieldList.m_id),
m_level(fieldList.m_level)
{
std::map<unsigned, VSDFieldListElement *>::const_iterator iter = fieldList.m_elements.begin();
for (; iter != fieldList.m_elements.end(); ++iter)
m_elements[iter->first] = iter->second->clone();
}
libvisio::VSDFieldList &libvisio::VSDFieldList::operator=(const libvisio::VSDFieldList &fieldList)
{
if (this != &fieldList)
{
clear();
std::map<unsigned, VSDFieldListElement *>::const_iterator iter = fieldList.m_elements.begin();
for (; iter != fieldList.m_elements.end(); ++iter)
m_elements[iter->first] = iter->second->clone();
m_elementsOrder = fieldList.m_elementsOrder;
m_id = fieldList.m_id;
m_level = fieldList.m_level;
}
return *this;
}
libvisio::VSDFieldList::~VSDFieldList()
{
clear();
}
void libvisio::VSDFieldList::setElementsOrder(const std::vector<unsigned> &elementsOrder)
{
m_elementsOrder.clear();
for (unsigned i = 0; i<elementsOrder.size(); i++)
m_elementsOrder.push_back(elementsOrder[i]);
}
void libvisio::VSDFieldList::addFieldList(unsigned id, unsigned level)
{
m_id = id;
m_level = level;
}
void libvisio::VSDFieldList::addTextField(unsigned id, unsigned level, int nameId, int formatStringId)
{
m_elements[id] = new VSDTextField(id, level, nameId, formatStringId);
}
void libvisio::VSDFieldList::addNumericField(unsigned id, unsigned level, unsigned short format, double number, int formatStringId)
{
m_elements[id] = new VSDNumericField(id, level, format, number, formatStringId);
}
void libvisio::VSDFieldList::handle(VSDCollector *collector) const
{
if (empty())
return;
collector->collectFieldList(m_id, m_level);
std::map<unsigned, VSDFieldListElement *>::const_iterator iter;
if (!m_elementsOrder.empty())
{
for (unsigned i = 0; i < m_elementsOrder.size(); i++)
{
iter = m_elements.find(m_elementsOrder[i]);
if (iter != m_elements.end())
iter->second->handle(collector);
}
}
else
{
for (iter = m_elements.begin(); iter != m_elements.end(); ++iter)
iter->second->handle(collector);
}
}
void libvisio::VSDFieldList::clear()
{
for (std::map<unsigned, VSDFieldListElement *>::iterator iter = m_elements.begin(); iter != m_elements.end(); ++iter)
delete iter->second;
m_elements.clear();
m_elementsOrder.clear();
}
libvisio::VSDFieldListElement *libvisio::VSDFieldList::getElement(unsigned index)
{
if (m_elementsOrder.size() > index)
index = m_elementsOrder[index];
std::map<unsigned, VSDFieldListElement *>::const_iterator iter = m_elements.find(index);
if (iter != m_elements.end())
return iter->second;
else
return 0;
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>coverity: gmtime can return NULL<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* libvisio
* Version: MPL 1.1 / GPLv2+ / LGPLv2+
*
* 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 or as specified alternatively below. 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.
*
* Major Contributor(s):
* Copyright (C) 2011 Fridrich Strba <fridrich.strba@bluewin.ch>
* Copyright (C) 2011 Eilidh McAdam <tibbylickle@gmail.com>
*
*
* All Rights Reserved.
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPLv2+"), or
* the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"),
* in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable
* instead of those above.
*/
#include <time.h>
#include "VSDCollector.h"
#include "VSDFieldList.h"
void libvisio::VSDTextField::handle(VSDCollector *collector) const
{
collector->collectTextField(m_id, m_level, m_nameId, m_formatStringId);
}
libvisio::VSDFieldListElement *libvisio::VSDTextField::clone()
{
return new VSDTextField(m_id, m_level, m_nameId, m_formatStringId);
}
WPXString libvisio::VSDTextField::getString(const std::map<unsigned, WPXString> &strVec)
{
std::map<unsigned, WPXString>::const_iterator iter = strVec.find(m_nameId);
if (iter != strVec.end())
return iter->second;
else
return WPXString();
}
void libvisio::VSDTextField::setNameId(int nameId)
{
m_nameId = nameId;
}
void libvisio::VSDNumericField::handle(VSDCollector *collector) const
{
collector->collectNumericField(m_id, m_level, m_format, m_number, m_formatStringId);
}
libvisio::VSDFieldListElement *libvisio::VSDNumericField::clone()
{
return new VSDNumericField(m_id, m_level, m_format, m_number, m_formatStringId);
}
#define MAX_BUFFER 1024
WPXString libvisio::VSDNumericField::datetimeToString(const char *format, double datetime)
{
WPXString result;
char buffer[MAX_BUFFER];
time_t timer = (time_t)(86400 * datetime - 2209161600.0);
const struct tm *const time = gmtime(&timer);
if (time)
{
strftime(&buffer[0], MAX_BUFFER-1, format, time);
result.append(&buffer[0]);
}
return result;
}
WPXString libvisio::VSDNumericField::getString(const std::map<unsigned, WPXString> &)
{
if (m_format == 0xffff)
return WPXString();
switch (m_format)
{
case VSD_FIELD_FORMAT_DateMDYY:
case VSD_FIELD_FORMAT_DateMMDDYY:
case VSD_FIELD_FORMAT_DateMmmDYYYY:
case VSD_FIELD_FORMAT_DateMmmmDYYYY:
case VSD_FIELD_FORMAT_DateDMYY:
case VSD_FIELD_FORMAT_DateDDMMYY:
case VSD_FIELD_FORMAT_DateDMMMYYYY:
case VSD_FIELD_FORMAT_DateDMMMMYYYY:
case VSD_FIELD_FORMAT_Dateyyyymd:
case VSD_FIELD_FORMAT_Dateyymmdd:
case VSD_FIELD_FORMAT_DateTWNfYYYYMMDDD_C:
case VSD_FIELD_FORMAT_DateTWNsYYYYMMDDD_C:
case VSD_FIELD_FORMAT_DateTWNfyyyymmddww_C:
case VSD_FIELD_FORMAT_DateTWNfyyyymmdd_C:
case VSD_FIELD_FORMAT_Dategggemdww_J:
case VSD_FIELD_FORMAT_Dateyyyymdww_J:
case VSD_FIELD_FORMAT_Dategggemd_J:
case VSD_FIELD_FORMAT_Dateyyyymd_J:
case VSD_FIELD_FORMAT_DateYYYYMMMDDDWWW_C:
case VSD_FIELD_FORMAT_DateYYYYMMMDDD_C:
case VSD_FIELD_FORMAT_DategeMMMMddddww_K:
case VSD_FIELD_FORMAT_Dateyyyymdww_K:
case VSD_FIELD_FORMAT_DategeMMMMddd_K:
case VSD_FIELD_FORMAT_Dateyyyymd_K:
case VSD_FIELD_FORMAT_Dateyyyy_m_d:
case VSD_FIELD_FORMAT_Dateyy_mm_dd:
case VSD_FIELD_FORMAT_Dateyyyymd_S:
case VSD_FIELD_FORMAT_Dateyyyymmdd_S:
case VSD_FIELD_FORMAT_Datewwyyyymmdd_S:
case VSD_FIELD_FORMAT_Datewwyyyymd_S:
case VSD_FIELD_FORMAT_MsoDateShort:
case VSD_FIELD_FORMAT_MsoDateLongDay:
case VSD_FIELD_FORMAT_MsoDateLong:
case VSD_FIELD_FORMAT_MsoDateShortAlt:
case VSD_FIELD_FORMAT_MsoDateISO:
case VSD_FIELD_FORMAT_MsoDateShortMon:
case VSD_FIELD_FORMAT_MsoDateShortSlash:
case VSD_FIELD_FORMAT_MsoDateShortAbb:
case VSD_FIELD_FORMAT_MsoDateEnglish:
case VSD_FIELD_FORMAT_MsoDateMonthYr:
case VSD_FIELD_FORMAT_MsoDateMon_Yr:
return datetimeToString("%x", m_number);
case VSD_FIELD_FORMAT_TimeGen:
case VSD_FIELD_FORMAT_TimeHMM:
case VSD_FIELD_FORMAT_TimeHHMM:
case VSD_FIELD_FORMAT_TimeHMM24:
case VSD_FIELD_FORMAT_TimeHHMM24:
case VSD_FIELD_FORMAT_TimeHMMAMPM:
case VSD_FIELD_FORMAT_TimeHHMMAMPM:
case VSD_FIELD_FORMAT_TimeAMPMhmm_J:
case VSD_FIELD_FORMAT_TimeAMPMhmm_C:
case VSD_FIELD_FORMAT_TimeAMPMhmm_K:
case VSD_FIELD_FORMAT_TimeAMPM_hmm_J:
case VSD_FIELD_FORMAT_Timehmm_J:
case VSD_FIELD_FORMAT_TimeAMPM_hmm_C:
case VSD_FIELD_FORMAT_Timehmm_C:
case VSD_FIELD_FORMAT_TimeAMPM_hmm_K:
case VSD_FIELD_FORMAT_Timehmm_K:
case VSD_FIELD_FORMAT_TimeHMMAMPM_E:
case VSD_FIELD_FORMAT_TimeHHMMAMPM_E:
case VSD_FIELD_FORMAT_TimeAMPMhmm_S:
case VSD_FIELD_FORMAT_TimeAMPMhhmm_S:
case VSD_FIELD_FORMAT_MsoTimePM:
case VSD_FIELD_FORMAT_MsoTimeSecPM:
case VSD_FIELD_FORMAT_MsoTime24:
case VSD_FIELD_FORMAT_MsoTimeSec24:
return datetimeToString("%X", m_number);
case VSD_FIELD_FORMAT_MsoTimeDatePM:
case VSD_FIELD_FORMAT_MsoTimeDateSecPM:
return datetimeToString("%x %X", m_number);
default:
{
WPXString result;
WPXProperty *pProp = WPXPropertyFactory::newDoubleProp(m_number);
if (pProp)
{
result = pProp->getStr();
delete pProp;
}
return result;
}
}
}
void libvisio::VSDNumericField::setFormat(unsigned short format)
{
m_format = format;
}
void libvisio::VSDNumericField::setValue(double number)
{
m_number = number;
}
libvisio::VSDFieldList::VSDFieldList() :
m_elements(),
m_elementsOrder(),
m_id(0),
m_level(0)
{
}
libvisio::VSDFieldList::VSDFieldList(const libvisio::VSDFieldList &fieldList) :
m_elements(),
m_elementsOrder(fieldList.m_elementsOrder),
m_id(fieldList.m_id),
m_level(fieldList.m_level)
{
std::map<unsigned, VSDFieldListElement *>::const_iterator iter = fieldList.m_elements.begin();
for (; iter != fieldList.m_elements.end(); ++iter)
m_elements[iter->first] = iter->second->clone();
}
libvisio::VSDFieldList &libvisio::VSDFieldList::operator=(const libvisio::VSDFieldList &fieldList)
{
if (this != &fieldList)
{
clear();
std::map<unsigned, VSDFieldListElement *>::const_iterator iter = fieldList.m_elements.begin();
for (; iter != fieldList.m_elements.end(); ++iter)
m_elements[iter->first] = iter->second->clone();
m_elementsOrder = fieldList.m_elementsOrder;
m_id = fieldList.m_id;
m_level = fieldList.m_level;
}
return *this;
}
libvisio::VSDFieldList::~VSDFieldList()
{
clear();
}
void libvisio::VSDFieldList::setElementsOrder(const std::vector<unsigned> &elementsOrder)
{
m_elementsOrder.clear();
for (unsigned i = 0; i<elementsOrder.size(); i++)
m_elementsOrder.push_back(elementsOrder[i]);
}
void libvisio::VSDFieldList::addFieldList(unsigned id, unsigned level)
{
m_id = id;
m_level = level;
}
void libvisio::VSDFieldList::addTextField(unsigned id, unsigned level, int nameId, int formatStringId)
{
m_elements[id] = new VSDTextField(id, level, nameId, formatStringId);
}
void libvisio::VSDFieldList::addNumericField(unsigned id, unsigned level, unsigned short format, double number, int formatStringId)
{
m_elements[id] = new VSDNumericField(id, level, format, number, formatStringId);
}
void libvisio::VSDFieldList::handle(VSDCollector *collector) const
{
if (empty())
return;
collector->collectFieldList(m_id, m_level);
std::map<unsigned, VSDFieldListElement *>::const_iterator iter;
if (!m_elementsOrder.empty())
{
for (unsigned i = 0; i < m_elementsOrder.size(); i++)
{
iter = m_elements.find(m_elementsOrder[i]);
if (iter != m_elements.end())
iter->second->handle(collector);
}
}
else
{
for (iter = m_elements.begin(); iter != m_elements.end(); ++iter)
iter->second->handle(collector);
}
}
void libvisio::VSDFieldList::clear()
{
for (std::map<unsigned, VSDFieldListElement *>::iterator iter = m_elements.begin(); iter != m_elements.end(); ++iter)
delete iter->second;
m_elements.clear();
m_elementsOrder.clear();
}
libvisio::VSDFieldListElement *libvisio::VSDFieldList::getElement(unsigned index)
{
if (m_elementsOrder.size() > index)
index = m_elementsOrder[index];
std::map<unsigned, VSDFieldListElement *>::const_iterator iter = m_elements.find(index);
if (iter != m_elements.end())
return iter->second;
else
return 0;
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|> |
<commit_before>/*
This file is part of the Ofi Labs X2 project.
Copyright (C) 2010 Ariya Hidayat <ariya.hidayat@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "kineticmodel.h"
#include <QtCore/QTimer>
#include <QtCore/QDateTime>
static const int KineticModelDefaultUpdateInterval = 15; // ms
class KineticModelPrivate
{
public:
QTimer ticker;
bool released;
int duration;
QPointF position;
QPointF velocity;
QPointF deacceleration;
QTime timestamp;
QPointF lastPosition;
KineticModelPrivate();
};
KineticModelPrivate::KineticModelPrivate()
: released(false)
, duration(1403)
, position(0, 0)
, velocity(0, 0)
, deacceleration(0, 0)
, lastPosition(0, 0)
{
}
KineticModel::KineticModel(QObject *parent)
: QObject(parent)
, d_ptr(new KineticModelPrivate)
{
connect(&d_ptr->ticker, SIGNAL(timeout()), SLOT(update()));
d_ptr->ticker.setInterval(KineticModelDefaultUpdateInterval);
}
KineticModel::~KineticModel()
{
}
int KineticModel::duration() const
{
return d_ptr->duration;
}
void KineticModel::setDuration(int ms)
{
d_ptr->duration = ms;
}
QPointF KineticModel::position() const
{
return d_ptr->position;
}
void KineticModel::setPosition(QPointF position)
{
setPosition( position.x(), position.y() );
}
void KineticModel::setPosition(qreal posX, qreal posY)
{
d_ptr->released = false;
d_ptr->position.setX( posX );
d_ptr->position.setY( posY );
update();
}
int KineticModel::updateInterval() const
{
return d_ptr->ticker.interval();
}
void KineticModel::setUpdateInterval(int ms)
{
d_ptr->ticker.setInterval(ms);
}
void KineticModel::resetSpeed()
{
Q_D(KineticModel);
d->released = false;
d->ticker.stop();
d->lastPosition = d->position;
d->timestamp.start();
d->velocity = QPointF(0, 0);
}
void KineticModel::release()
{
Q_D(KineticModel);
d->released = true;
d->deacceleration = d->velocity * 1000 / ( 1 + d_ptr->duration );
if (d->deacceleration.x() < 0) {
d->deacceleration.setX( -d->deacceleration.x() );
}
if (d->deacceleration.y() < 0) {
d->deacceleration.setY( -d->deacceleration.y() );
}
if (d->deacceleration.x() > 0.0005 || d->deacceleration.y() > 0.0005) {
if (!d->ticker.isActive())
d->ticker.start();
update();
} else {
d->ticker.stop();
emit finished();
}
}
void KineticModel::update()
{
Q_D(KineticModel);
int elapsed = d->timestamp.elapsed();
// too fast gives less accuracy
if (elapsed < d->ticker.interval() / 2) {
return;
}
qreal delta = static_cast<qreal>(elapsed) / 1000.0;
if (d->released) {
d->position += d->velocity * delta;
QPointF vstep = d->deacceleration * delta;
if (d->velocity.x() < vstep.x() && d->velocity.x() >= -vstep.x()) {
d->velocity.setX( 0 );
d->ticker.stop();
} else {
if (d->velocity.x() > 0)
d->velocity.setX( d->velocity.x() - vstep.x() );
else
d->velocity.setX( d->velocity.x() + vstep.x() );
}
if (d->velocity.y() < vstep.y() && d->velocity.y() >= -vstep.y()) {
d->velocity.setY( 0 );
} else {
if (d->velocity.y() > 0)
d->velocity.setY( d->velocity.y() - vstep.y() );
else
d->velocity.setY( d->velocity.y() + vstep.y() );
}
emit positionChanged();
if (d->velocity.isNull()) {
emit finished();
d->ticker.stop();
}
} else {
QPointF lastSpeed = d->velocity;
QPointF currentSpeed = ( d->position - d->lastPosition ) / delta;
d->velocity = .2 * lastSpeed + .8 * currentSpeed;
d->lastPosition = d->position;
}
d->timestamp.start();
}
#include "kineticmodel.moc"
<commit_msg>only stop kinetic spinning if velocity of both dimensions reaches zero<commit_after>/*
This file is part of the Ofi Labs X2 project.
Copyright (C) 2010 Ariya Hidayat <ariya.hidayat@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "kineticmodel.h"
#include <QtCore/QTimer>
#include <QtCore/QDateTime>
static const int KineticModelDefaultUpdateInterval = 15; // ms
class KineticModelPrivate
{
public:
QTimer ticker;
bool released;
int duration;
QPointF position;
QPointF velocity;
QPointF deacceleration;
QTime timestamp;
QPointF lastPosition;
KineticModelPrivate();
};
KineticModelPrivate::KineticModelPrivate()
: released(false)
, duration(1403)
, position(0, 0)
, velocity(0, 0)
, deacceleration(0, 0)
, lastPosition(0, 0)
{
}
KineticModel::KineticModel(QObject *parent)
: QObject(parent)
, d_ptr(new KineticModelPrivate)
{
connect(&d_ptr->ticker, SIGNAL(timeout()), SLOT(update()));
d_ptr->ticker.setInterval(KineticModelDefaultUpdateInterval);
}
KineticModel::~KineticModel()
{
}
int KineticModel::duration() const
{
return d_ptr->duration;
}
void KineticModel::setDuration(int ms)
{
d_ptr->duration = ms;
}
QPointF KineticModel::position() const
{
return d_ptr->position;
}
void KineticModel::setPosition(QPointF position)
{
setPosition( position.x(), position.y() );
}
void KineticModel::setPosition(qreal posX, qreal posY)
{
d_ptr->released = false;
d_ptr->position.setX( posX );
d_ptr->position.setY( posY );
update();
}
int KineticModel::updateInterval() const
{
return d_ptr->ticker.interval();
}
void KineticModel::setUpdateInterval(int ms)
{
d_ptr->ticker.setInterval(ms);
}
void KineticModel::resetSpeed()
{
Q_D(KineticModel);
d->released = false;
d->ticker.stop();
d->lastPosition = d->position;
d->timestamp.start();
d->velocity = QPointF(0, 0);
}
void KineticModel::release()
{
Q_D(KineticModel);
d->released = true;
d->deacceleration = d->velocity * 1000 / ( 1 + d_ptr->duration );
if (d->deacceleration.x() < 0) {
d->deacceleration.setX( -d->deacceleration.x() );
}
if (d->deacceleration.y() < 0) {
d->deacceleration.setY( -d->deacceleration.y() );
}
if (d->deacceleration.x() > 0.0005 || d->deacceleration.y() > 0.0005) {
if (!d->ticker.isActive())
d->ticker.start();
update();
} else {
d->ticker.stop();
emit finished();
}
}
void KineticModel::update()
{
Q_D(KineticModel);
int elapsed = d->timestamp.elapsed();
// too fast gives less accuracy
if (elapsed < d->ticker.interval() / 2) {
return;
}
qreal delta = static_cast<qreal>(elapsed) / 1000.0;
if (d->released) {
d->position += d->velocity * delta;
QPointF vstep = d->deacceleration * delta;
if (d->velocity.x() < vstep.x() && d->velocity.x() >= -vstep.x()) {
d->velocity.setX( 0 );
} else {
if (d->velocity.x() > 0)
d->velocity.setX( d->velocity.x() - vstep.x() );
else
d->velocity.setX( d->velocity.x() + vstep.x() );
}
if (d->velocity.y() < vstep.y() && d->velocity.y() >= -vstep.y()) {
d->velocity.setY( 0 );
} else {
if (d->velocity.y() > 0)
d->velocity.setY( d->velocity.y() - vstep.y() );
else
d->velocity.setY( d->velocity.y() + vstep.y() );
}
emit positionChanged();
if (d->velocity.isNull()) {
emit finished();
d->ticker.stop();
}
} else {
QPointF lastSpeed = d->velocity;
QPointF currentSpeed = ( d->position - d->lastPosition ) / delta;
d->velocity = .2 * lastSpeed + .8 * currentSpeed;
d->lastPosition = d->position;
}
d->timestamp.start();
}
#include "kineticmodel.moc"
<|endoftext|> |
<commit_before>#include "client.h"
#include "controller/controlcontroller.h"
#include "controller/reportcontroller.h"
#include "controller/logincontroller.h"
#include "controller/registrationcontroller.h"
#include "controller/configcontroller.h"
#include "network/networkmanager.h"
#include "task/taskexecutor.h"
#include "scheduler/schedulerstorage.h"
#include "report/reportstorage.h"
#include "scheduler/scheduler.h"
#include "settings.h"
#include "log/logger.h"
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QDebug>
#ifdef Q_OS_UNIX
#include <QSocketNotifier>
#include <sys/socket.h>
#include <signal.h>
#include <unistd.h>
#endif // Q_OS_UNIX
// TEST INCLUDES
#include "timing/immediatetiming.h"
#include "task/task.h"
#include "measurement/btc/btc_definition.h"
#include "measurement/ping/ping_definition.h"
LOGGER(Client);
class Client::Private : public QObject
{
Q_OBJECT
public:
Private(Client* q)
: q(q)
, status(Client::Unregistered)
, networkAccessManager(new QNetworkAccessManager(q))
, schedulerStorage(&scheduler)
, reportStorage(&reportScheduler)
{
executor.setNetworkManager(&networkManager);
scheduler.setExecutor(&executor);
connect(&executor, SIGNAL(finished(TestDefinitionPtr,ResultPtr)), this, SLOT(taskFinished(TestDefinitionPtr,ResultPtr)));
}
Client* q;
// Properties
Client::Status status;
QNetworkAccessManager* networkAccessManager;
TaskExecutor executor;
Scheduler scheduler;
SchedulerStorage schedulerStorage;
ReportScheduler reportScheduler;
ReportStorage reportStorage;
Settings settings;
NetworkManager networkManager;
ControlController controlController;
ReportController reportController;
RegistrationController registrationController;
LoginController loginController;
ConfigController configController;
#ifdef Q_OS_UNIX
static int sigintFd[2];
static int sighupFd[2];
static int sigtermFd[2];
QSocketNotifier* snInt;
QSocketNotifier* snHup;
QSocketNotifier* snTerm;
// Unix signal handlers.
static void intSignalHandler(int unused);
static void hupSignalHandler(int unused);
static void termSignalHandler(int unused);
#endif // Q_OS_UNIX
// Functions
void setupUnixSignalHandlers();
public slots:
#ifdef Q_OS_UNIX
void handleSigInt();
void handleSigHup();
void handleSigTerm();
#endif // Q_OS_UNIX
void taskFinished(const TestDefinitionPtr& test, const ResultPtr& result);
};
#ifdef Q_OS_UNIX
int Client::Private::sigintFd[2];
int Client::Private::sighupFd[2];
int Client::Private::sigtermFd[2];
void Client::Private::intSignalHandler(int)
{
char a = 1;
::write(sigintFd[0], &a, sizeof(a));
}
void Client::Private::hupSignalHandler(int)
{
char a = 1;
::write(sighupFd[0], &a, sizeof(a));
}
void Client::Private::termSignalHandler(int)
{
char a = 1;
::write(sigtermFd[0], &a, sizeof(a));
}
#endif // Q_OS_UNIX
void Client::Private::setupUnixSignalHandlers()
{
#ifdef Q_OS_UNIX
struct sigaction Int, hup, term;
Int.sa_handler = Client::Private::intSignalHandler;
sigemptyset(&Int.sa_mask);
Int.sa_flags = 0;
Int.sa_flags |= SA_RESTART;
if (sigaction(SIGINT, &Int, 0) > 0)
return;
hup.sa_handler = Client::Private::hupSignalHandler;
sigemptyset(&hup.sa_mask);
hup.sa_flags = 0;
hup.sa_flags |= SA_RESTART;
if (sigaction(SIGHUP, &hup, 0) > 0)
return;
term.sa_handler = Client::Private::termSignalHandler;
sigemptyset(&term.sa_mask);
term.sa_flags = 0;
term.sa_flags |= SA_RESTART;
if (sigaction(SIGTERM, &term, 0) > 0)
return;
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigintFd))
qFatal("Couldn't create INT socketpair");
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sighupFd))
qFatal("Couldn't create HUP socketpair");
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigtermFd))
qFatal("Couldn't create TERM socketpair");
snInt = new QSocketNotifier(sigintFd[1], QSocketNotifier::Read, this);
connect(snInt, SIGNAL(activated(int)), this, SLOT(handleSigInt()));
snHup = new QSocketNotifier(sighupFd[1], QSocketNotifier::Read, this);
connect(snHup, SIGNAL(activated(int)), this, SLOT(handleSigHup()));
snTerm = new QSocketNotifier(sigtermFd[1], QSocketNotifier::Read, this);
connect(snTerm, SIGNAL(activated(int)), this, SLOT(handleSigTerm()));
#endif // Q_OS_UNIX
}
#ifdef Q_OS_UNIX
void Client::Private::handleSigInt()
{
snInt->setEnabled(false);
char tmp;
::read(sigintFd[1], &tmp, sizeof(tmp));
LOG_INFO("Interrupt requested, quitting.");
qApp->quit();
snInt->setEnabled(true);
}
void Client::Private::handleSigTerm()
{
snTerm->setEnabled(false);
char tmp;
::read(sigtermFd[1], &tmp, sizeof(tmp));
LOG_INFO("Termination requested, quitting.");
qApp->quit();
snTerm->setEnabled(true);
}
void Client::Private::handleSigHup()
{
snHup->setEnabled(false);
char tmp;
::read(sighupFd[1], &tmp, sizeof(tmp));
LOG_INFO("Hangup detected, quitting.");
qApp->quit();
snHup->setEnabled(true);
}
#endif // Q_OS_UNIX
void Client::Private::taskFinished(const TestDefinitionPtr &test, const ResultPtr &result)
{
ReportPtr oldReport = reportScheduler.reportByTaskId(test->id());
ResultList results = oldReport.isNull() ? ResultList() : oldReport->results();
results.append(result);
ReportPtr report(new Report(test->id(), QDateTime::currentDateTime(), results));
reportScheduler.addReport(report);
}
Client::Client(QObject *parent)
: QObject(parent)
, d(new Private(this))
{
}
Client::~Client()
{
d->schedulerStorage.storeData();
d->reportStorage.storeData();
delete d;
}
Client *Client::instance()
{
static Client* ins = NULL;
if ( !ins )
ins = new Client();
return ins;
}
bool Client::init()
{
qRegisterMetaType<TestDefinitionPtr>();
qRegisterMetaType<ResultPtr>();
d->setupUnixSignalHandlers();
d->settings.init();
// Initialize storages
d->schedulerStorage.loadData();
d->reportStorage.loadData();
// Initialize controllers
d->networkManager.init(&d->scheduler, &d->settings);
d->configController.init(&d->networkManager, &d->settings);
d->controlController.init(&d->networkManager, &d->scheduler, &d->settings);
d->reportController.init(&d->reportScheduler, &d->settings);
d->loginController.init(&d->networkManager, &d->settings);
d->registrationController.init(&d->networkManager, &d->settings);
return true;
}
void Client::btc()
{
BulkTransportCapacityDefinition btcDef("141.82.49.80", 3365, 1024*50);
TimingPtr timing(new ImmediateTiming());
TestDefinitionPtr testDefinition(new TestDefinition(QUuid::createUuid(), "btc_ma", timing, btcDef.toVariant()));
d->scheduler.enqueue(testDefinition);
}
void Client::upnp()
{
TimingPtr timing(new ImmediateTiming());
TestDefinitionPtr testDefinition(new TestDefinition("{3702e527-f84f-4542-8df6-4e3d2a0ec977}", "upnp", timing, QVariant()));
d->scheduler.enqueue(testDefinition);
}
void Client::ping()
{
PingDefinition pingDef("141.82.49.80", 4, 2);
TimingPtr timing(new ImmediateTiming());
TestDefinitionPtr testDefinition(new TestDefinition(QUuid::createUuid(), "ping", timing, pingDef.toVariant()));
d->scheduler.enqueue(testDefinition);
}
void Client::setStatus(Client::Status status)
{
if ( d->status == status )
return;
d->status = status;
emit statusChanged();
}
Client::Status Client::status() const
{
return d->status;
}
QNetworkAccessManager *Client::networkAccessManager() const
{
return d->networkAccessManager;
}
Scheduler *Client::scheduler() const
{
return &d->scheduler;
}
ReportScheduler *Client::reportScheduler() const
{
return &d->reportScheduler;
}
NetworkManager *Client::networkManager() const
{
return &d->networkManager;
}
TaskExecutor *Client::taskExecutor() const
{
return &d->executor;
}
ConfigController *Client::configController() const
{
return &d->configController;
}
RegistrationController *Client::registrationController() const
{
return &d->registrationController;
}
LoginController *Client::loginController() const
{
return &d->loginController;
}
ReportController *Client::reportController() const
{
return &d->reportController;
}
Settings *Client::settings() const
{
return &d->settings;
}
#include "client.moc"
<commit_msg>Ctrl-C handler for Windows.<commit_after>#include "client.h"
#include "controller/controlcontroller.h"
#include "controller/reportcontroller.h"
#include "controller/logincontroller.h"
#include "controller/registrationcontroller.h"
#include "controller/configcontroller.h"
#include "network/networkmanager.h"
#include "task/taskexecutor.h"
#include "scheduler/schedulerstorage.h"
#include "report/reportstorage.h"
#include "scheduler/scheduler.h"
#include "settings.h"
#include "log/logger.h"
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QDebug>
#ifdef Q_OS_UNIX
#include <QSocketNotifier>
#include <sys/socket.h>
#include <signal.h>
#include <unistd.h>
#endif // Q_OS_UNIX
#ifdef Q_OS_WIN
#include <Windows.h>
#include <stdio.h>
#endif // Q_OS_WIN
// TEST INCLUDES
#include "timing/immediatetiming.h"
#include "task/task.h"
#include "measurement/btc/btc_definition.h"
#include "measurement/ping/ping_definition.h"
LOGGER(Client);
class Client::Private : public QObject
{
Q_OBJECT
public:
Private(Client* q)
: q(q)
, status(Client::Unregistered)
, networkAccessManager(new QNetworkAccessManager(q))
, schedulerStorage(&scheduler)
, reportStorage(&reportScheduler)
{
executor.setNetworkManager(&networkManager);
scheduler.setExecutor(&executor);
connect(&executor, SIGNAL(finished(TestDefinitionPtr,ResultPtr)), this, SLOT(taskFinished(TestDefinitionPtr,ResultPtr)));
}
Client* q;
// Properties
Client::Status status;
QNetworkAccessManager* networkAccessManager;
TaskExecutor executor;
Scheduler scheduler;
SchedulerStorage schedulerStorage;
ReportScheduler reportScheduler;
ReportStorage reportStorage;
Settings settings;
NetworkManager networkManager;
ControlController controlController;
ReportController reportController;
RegistrationController registrationController;
LoginController loginController;
ConfigController configController;
#ifdef Q_OS_UNIX
static int sigintFd[2];
static int sighupFd[2];
static int sigtermFd[2];
QSocketNotifier* snInt;
QSocketNotifier* snHup;
QSocketNotifier* snTerm;
// Unix signal handlers.
static void intSignalHandler(int unused);
static void hupSignalHandler(int unused);
static void termSignalHandler(int unused);
#endif // Q_OS_UNIX
// Functions
void setupUnixSignalHandlers();
#ifdef Q_OS_WIN
static BOOL CtrlHandler(DWORD ctrlType);
#endif // Q_OS_WIN
public slots:
#ifdef Q_OS_UNIX
void handleSigInt();
void handleSigHup();
void handleSigTerm();
#endif // Q_OS_UNIX
void taskFinished(const TestDefinitionPtr& test, const ResultPtr& result);
};
#ifdef Q_OS_UNIX
int Client::Private::sigintFd[2];
int Client::Private::sighupFd[2];
int Client::Private::sigtermFd[2];
void Client::Private::intSignalHandler(int)
{
char a = 1;
::write(sigintFd[0], &a, sizeof(a));
}
void Client::Private::hupSignalHandler(int)
{
char a = 1;
::write(sighupFd[0], &a, sizeof(a));
}
void Client::Private::termSignalHandler(int)
{
char a = 1;
::write(sigtermFd[0], &a, sizeof(a));
}
#endif // Q_OS_UNIX
void Client::Private::setupUnixSignalHandlers()
{
#ifdef Q_OS_UNIX
struct sigaction Int, hup, term;
Int.sa_handler = Client::Private::intSignalHandler;
sigemptyset(&Int.sa_mask);
Int.sa_flags = 0;
Int.sa_flags |= SA_RESTART;
if (sigaction(SIGINT, &Int, 0) > 0)
return;
hup.sa_handler = Client::Private::hupSignalHandler;
sigemptyset(&hup.sa_mask);
hup.sa_flags = 0;
hup.sa_flags |= SA_RESTART;
if (sigaction(SIGHUP, &hup, 0) > 0)
return;
term.sa_handler = Client::Private::termSignalHandler;
sigemptyset(&term.sa_mask);
term.sa_flags = 0;
term.sa_flags |= SA_RESTART;
if (sigaction(SIGTERM, &term, 0) > 0)
return;
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigintFd))
qFatal("Couldn't create INT socketpair");
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sighupFd))
qFatal("Couldn't create HUP socketpair");
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigtermFd))
qFatal("Couldn't create TERM socketpair");
snInt = new QSocketNotifier(sigintFd[1], QSocketNotifier::Read, this);
connect(snInt, SIGNAL(activated(int)), this, SLOT(handleSigInt()));
snHup = new QSocketNotifier(sighupFd[1], QSocketNotifier::Read, this);
connect(snHup, SIGNAL(activated(int)), this, SLOT(handleSigHup()));
snTerm = new QSocketNotifier(sigtermFd[1], QSocketNotifier::Read, this);
connect(snTerm, SIGNAL(activated(int)), this, SLOT(handleSigTerm()));
#elif defined(Q_OS_WIN)
SetConsoleCtrlHandler((PHANDLER_ROUTINE)Private::CtrlHandler, TRUE);
#endif
}
BOOL Client::Private::CtrlHandler(DWORD ctrlType)
{
switch(ctrlType) {
case CTRL_C_EVENT:
case CTRL_CLOSE_EVENT:
LOG_INFO("Close requested, quitting.");
qApp->quit();
return TRUE;
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
LOG_INFO("System shutdown or user logout, quitting.");
qApp->quit();
return FALSE;
default:
return FALSE;
}
}
#ifdef Q_OS_UNIX
void Client::Private::handleSigInt()
{
snInt->setEnabled(false);
char tmp;
::read(sigintFd[1], &tmp, sizeof(tmp));
LOG_INFO("Interrupt requested, quitting.");
qApp->quit();
snInt->setEnabled(true);
}
void Client::Private::handleSigTerm()
{
snTerm->setEnabled(false);
char tmp;
::read(sigtermFd[1], &tmp, sizeof(tmp));
LOG_INFO("Termination requested, quitting.");
qApp->quit();
snTerm->setEnabled(true);
}
void Client::Private::handleSigHup()
{
snHup->setEnabled(false);
char tmp;
::read(sighupFd[1], &tmp, sizeof(tmp));
LOG_INFO("Hangup detected, quitting.");
qApp->quit();
snHup->setEnabled(true);
}
#endif // Q_OS_UNIX
void Client::Private::taskFinished(const TestDefinitionPtr &test, const ResultPtr &result)
{
ReportPtr oldReport = reportScheduler.reportByTaskId(test->id());
ResultList results = oldReport.isNull() ? ResultList() : oldReport->results();
results.append(result);
ReportPtr report(new Report(test->id(), QDateTime::currentDateTime(), results));
reportScheduler.addReport(report);
}
Client::Client(QObject *parent)
: QObject(parent)
, d(new Private(this))
{
}
Client::~Client()
{
d->schedulerStorage.storeData();
d->reportStorage.storeData();
delete d;
}
Client *Client::instance()
{
static Client* ins = NULL;
if ( !ins )
ins = new Client();
return ins;
}
bool Client::init()
{
qRegisterMetaType<TestDefinitionPtr>();
qRegisterMetaType<ResultPtr>();
d->setupUnixSignalHandlers();
d->settings.init();
// Initialize storages
d->schedulerStorage.loadData();
d->reportStorage.loadData();
// Initialize controllers
d->networkManager.init(&d->scheduler, &d->settings);
d->configController.init(&d->networkManager, &d->settings);
d->controlController.init(&d->networkManager, &d->scheduler, &d->settings);
d->reportController.init(&d->reportScheduler, &d->settings);
d->loginController.init(&d->networkManager, &d->settings);
d->registrationController.init(&d->networkManager, &d->settings);
return true;
}
void Client::btc()
{
BulkTransportCapacityDefinition btcDef("141.82.49.80", 3365, 1024*50);
TimingPtr timing(new ImmediateTiming());
TestDefinitionPtr testDefinition(new TestDefinition(QUuid::createUuid(), "btc_ma", timing, btcDef.toVariant()));
d->scheduler.enqueue(testDefinition);
}
void Client::upnp()
{
TimingPtr timing(new ImmediateTiming());
TestDefinitionPtr testDefinition(new TestDefinition("{3702e527-f84f-4542-8df6-4e3d2a0ec977}", "upnp", timing, QVariant()));
d->scheduler.enqueue(testDefinition);
}
void Client::ping()
{
PingDefinition pingDef("141.82.49.80", 4, 2);
TimingPtr timing(new ImmediateTiming());
TestDefinitionPtr testDefinition(new TestDefinition(QUuid::createUuid(), "ping", timing, pingDef.toVariant()));
d->scheduler.enqueue(testDefinition);
}
void Client::setStatus(Client::Status status)
{
if ( d->status == status )
return;
d->status = status;
emit statusChanged();
}
Client::Status Client::status() const
{
return d->status;
}
QNetworkAccessManager *Client::networkAccessManager() const
{
return d->networkAccessManager;
}
Scheduler *Client::scheduler() const
{
return &d->scheduler;
}
ReportScheduler *Client::reportScheduler() const
{
return &d->reportScheduler;
}
NetworkManager *Client::networkManager() const
{
return &d->networkManager;
}
TaskExecutor *Client::taskExecutor() const
{
return &d->executor;
}
ConfigController *Client::configController() const
{
return &d->configController;
}
RegistrationController *Client::registrationController() const
{
return &d->registrationController;
}
LoginController *Client::loginController() const
{
return &d->loginController;
}
ReportController *Client::reportController() const
{
return &d->reportController;
}
Settings *Client::settings() const
{
return &d->settings;
}
#include "client.moc"
<|endoftext|> |
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014 Pedro Côrte-Real
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "tiff/CiffEntry.h"
#include "common/Common.h" // for uchar8, uint32, ushort16
#include "io/Endianness.h" // for getU32LE, getU16LE
#include "parsers/CiffParserException.h" // for ThrowCPE
#include <cstdio> // for sprintf
#include <cstring> // for memcpy, strlen
#include <string> // for string, allocator
#include <vector> // for vector
using namespace std;
namespace RawSpeed {
CiffEntry::CiffEntry(FileMap* f, uint32 value_data, uint32 offset) {
own_data = nullptr;
ushort16 p = getU16LE(f->getData(offset, 2));
tag = (CiffTag) (p & 0x3fff);
ushort16 datalocation = (p & 0xc000);
type = (CiffDataType) (p & 0x3800);
if (datalocation == 0x0000) { // Data is offset in value_data
bytesize = getU32LE(f->getData(offset + 2, 4));
data_offset = getU32LE(f->getData(offset + 6, 4)) + value_data;
data = f->getDataWrt(data_offset, bytesize);
} else if (datalocation == 0x4000) { // Data is stored directly in entry
data_offset = offset + 2;
bytesize = 8; // Maximum of 8 bytes of data (the size and offset fields)
data = f->getDataWrt(data_offset, bytesize);
} else
ThrowCPE("Don't understand data location 0x%x\n", datalocation);
// Set the number of items using the shift
count = bytesize >> getElementShift();
}
CiffEntry::~CiffEntry() {
if (own_data)
delete[] own_data;
}
uint32 __attribute__((pure)) CiffEntry::getElementShift() {
switch (type) {
case CIFF_BYTE:
case CIFF_ASCII:
return 0;
case CIFF_SHORT:
return 1;
case CIFF_LONG:
case CIFF_MIX:
case CIFF_SUB1:
case CIFF_SUB2:
return 2;
}
return 0;
}
uint32 __attribute__((pure)) CiffEntry::getElementSize() {
switch (type) {
case CIFF_BYTE:
case CIFF_ASCII:
return 1;
case CIFF_SHORT:
return 2;
case CIFF_LONG:
case CIFF_MIX:
case CIFF_SUB1:
case CIFF_SUB2:
return 4;
}
return 0;
}
bool __attribute__((pure)) CiffEntry::isInt() {
return (type == CIFF_LONG || type == CIFF_SHORT || type == CIFF_BYTE);
}
uint32 CiffEntry::getU32(uint32 num) {
if (!isInt()) {
ThrowCPE(
"Wrong type 0x%x encountered. Expected Long, Short or Byte at 0x%x",
type, tag);
}
if (type == CIFF_BYTE)
return getByte(num);
if (type == CIFF_SHORT)
return getU16(num);
if (num*4+3 >= bytesize)
ThrowCPE("Trying to read out of bounds");
return getU32LE(data + num * 4);
}
ushort16 CiffEntry::getU16(uint32 num) {
if (type != CIFF_SHORT && type != CIFF_BYTE)
ThrowCPE("Wrong type 0x%x encountered. Expected Short at 0x%x", type, tag);
if (num*2+1 >= bytesize)
ThrowCPE("Trying to read out of bounds");
return getU16LE(data + num * 2);
}
uchar8 CiffEntry::getByte(uint32 num) {
if (type != CIFF_BYTE)
ThrowCPE("Wrong type 0x%x encountered. Expected Byte at 0x%x", type, tag);
if (num >= bytesize)
ThrowCPE("Trying to read out of bounds");
return data[num];
}
string CiffEntry::getString() {
if (type != CIFF_ASCII)
ThrowCPE("Wrong type 0x%x encountered. Expected Ascii", type);
if (!own_data) {
own_data = new uchar8[count];
memcpy(own_data, data, count);
own_data[count-1] = 0; // Ensure string is not larger than count defines
}
return string((const char*)&own_data[0]);
}
vector<string> CiffEntry::getStrings() {
vector<string> strs;
if (type != CIFF_ASCII)
ThrowCPE("Wrong type 0x%x encountered. Expected Ascii", type);
if (!own_data) {
own_data = new uchar8[count];
memcpy(own_data, data, count);
own_data[count-1] = 0; // Ensure string is not larger than count defines
}
uint32 start = 0;
for (uint32 i=0; i< count; i++) {
if (own_data[i] == 0) {
strs.emplace_back((const char *)&own_data[start]);
start = i+1;
}
}
return strs;
}
bool __attribute__((pure)) CiffEntry::isString() {
return (type == CIFF_ASCII);
}
void CiffEntry::setData( const void *in_data, uint32 byte_count )
{
if (byte_count > bytesize)
ThrowCPE("data set larger than entry size given");
if (!own_data) {
own_data = new uchar8[bytesize];
memcpy(own_data, data, bytesize);
}
memcpy(own_data, in_data, byte_count);
}
uchar8* CiffEntry::getDataWrt()
{
if (!own_data) {
own_data = new uchar8[bytesize];
memcpy(own_data, data, bytesize);
}
return own_data;
}
#ifdef _MSC_VER
#pragma warning(disable: 4996) // this function or variable may be unsafe
#endif
std::string CiffEntry::getValueAsString()
{
if (type == CIFF_ASCII)
return string((const char*)&data[0]);
auto *temp_string = new char[4096];
if (count == 1) {
switch (type) {
case CIFF_LONG:
sprintf(temp_string, "Long: %u (0x%x)", getU32(), getU32());
break;
case CIFF_SHORT:
sprintf(temp_string, "Short: %u (0x%x)", getU32(), getU32());
break;
case CIFF_BYTE:
sprintf(temp_string, "Byte: %u (0x%x)", getU32(), getU32());
break;
default:
sprintf(temp_string, "Type: %x: ", type);
for (uint32 i = 0; i < getElementSize(); i++) {
sprintf(&temp_string[strlen(temp_string-1)], "%x", data[i]);
}
}
}
string ret(temp_string);
delete [] temp_string;
return ret;
}
} // namespace RawSpeed
<commit_msg>CiffEntry::CiffEntry(): use plain getData<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014 Pedro Côrte-Real
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "tiff/CiffEntry.h"
#include "common/Common.h" // for uchar8, uint32, ushort16
#include "io/Endianness.h" // for getU32LE, getU16LE
#include "parsers/CiffParserException.h" // for ThrowCPE
#include <cstdio> // for sprintf
#include <cstring> // for memcpy, strlen
#include <string> // for string, allocator
#include <vector> // for vector
using namespace std;
namespace RawSpeed {
CiffEntry::CiffEntry(FileMap* f, uint32 value_data, uint32 offset) {
own_data = nullptr;
ushort16 p = getU16LE(f->getData(offset, 2));
tag = (CiffTag) (p & 0x3fff);
ushort16 datalocation = (p & 0xc000);
type = (CiffDataType) (p & 0x3800);
if (datalocation == 0x0000) { // Data is offset in value_data
bytesize = getU32LE(f->getData(offset + 2, 4));
data_offset = getU32LE(f->getData(offset + 6, 4)) + value_data;
data = f->getData(data_offset, bytesize);
} else if (datalocation == 0x4000) { // Data is stored directly in entry
data_offset = offset + 2;
bytesize = 8; // Maximum of 8 bytes of data (the size and offset fields)
data = f->getData(data_offset, bytesize);
} else
ThrowCPE("Don't understand data location 0x%x\n", datalocation);
// Set the number of items using the shift
count = bytesize >> getElementShift();
}
CiffEntry::~CiffEntry() {
if (own_data)
delete[] own_data;
}
uint32 __attribute__((pure)) CiffEntry::getElementShift() {
switch (type) {
case CIFF_BYTE:
case CIFF_ASCII:
return 0;
case CIFF_SHORT:
return 1;
case CIFF_LONG:
case CIFF_MIX:
case CIFF_SUB1:
case CIFF_SUB2:
return 2;
}
return 0;
}
uint32 __attribute__((pure)) CiffEntry::getElementSize() {
switch (type) {
case CIFF_BYTE:
case CIFF_ASCII:
return 1;
case CIFF_SHORT:
return 2;
case CIFF_LONG:
case CIFF_MIX:
case CIFF_SUB1:
case CIFF_SUB2:
return 4;
}
return 0;
}
bool __attribute__((pure)) CiffEntry::isInt() {
return (type == CIFF_LONG || type == CIFF_SHORT || type == CIFF_BYTE);
}
uint32 CiffEntry::getU32(uint32 num) {
if (!isInt()) {
ThrowCPE(
"Wrong type 0x%x encountered. Expected Long, Short or Byte at 0x%x",
type, tag);
}
if (type == CIFF_BYTE)
return getByte(num);
if (type == CIFF_SHORT)
return getU16(num);
if (num*4+3 >= bytesize)
ThrowCPE("Trying to read out of bounds");
return getU32LE(data + num * 4);
}
ushort16 CiffEntry::getU16(uint32 num) {
if (type != CIFF_SHORT && type != CIFF_BYTE)
ThrowCPE("Wrong type 0x%x encountered. Expected Short at 0x%x", type, tag);
if (num*2+1 >= bytesize)
ThrowCPE("Trying to read out of bounds");
return getU16LE(data + num * 2);
}
uchar8 CiffEntry::getByte(uint32 num) {
if (type != CIFF_BYTE)
ThrowCPE("Wrong type 0x%x encountered. Expected Byte at 0x%x", type, tag);
if (num >= bytesize)
ThrowCPE("Trying to read out of bounds");
return data[num];
}
string CiffEntry::getString() {
if (type != CIFF_ASCII)
ThrowCPE("Wrong type 0x%x encountered. Expected Ascii", type);
if (!own_data) {
own_data = new uchar8[count];
memcpy(own_data, data, count);
own_data[count-1] = 0; // Ensure string is not larger than count defines
}
return string((const char*)&own_data[0]);
}
vector<string> CiffEntry::getStrings() {
vector<string> strs;
if (type != CIFF_ASCII)
ThrowCPE("Wrong type 0x%x encountered. Expected Ascii", type);
if (!own_data) {
own_data = new uchar8[count];
memcpy(own_data, data, count);
own_data[count-1] = 0; // Ensure string is not larger than count defines
}
uint32 start = 0;
for (uint32 i=0; i< count; i++) {
if (own_data[i] == 0) {
strs.emplace_back((const char *)&own_data[start]);
start = i+1;
}
}
return strs;
}
bool __attribute__((pure)) CiffEntry::isString() {
return (type == CIFF_ASCII);
}
void CiffEntry::setData( const void *in_data, uint32 byte_count )
{
if (byte_count > bytesize)
ThrowCPE("data set larger than entry size given");
if (!own_data) {
own_data = new uchar8[bytesize];
memcpy(own_data, data, bytesize);
}
memcpy(own_data, in_data, byte_count);
}
uchar8* CiffEntry::getDataWrt()
{
if (!own_data) {
own_data = new uchar8[bytesize];
memcpy(own_data, data, bytesize);
}
return own_data;
}
#ifdef _MSC_VER
#pragma warning(disable: 4996) // this function or variable may be unsafe
#endif
std::string CiffEntry::getValueAsString()
{
if (type == CIFF_ASCII)
return string((const char*)&data[0]);
auto *temp_string = new char[4096];
if (count == 1) {
switch (type) {
case CIFF_LONG:
sprintf(temp_string, "Long: %u (0x%x)", getU32(), getU32());
break;
case CIFF_SHORT:
sprintf(temp_string, "Short: %u (0x%x)", getU32(), getU32());
break;
case CIFF_BYTE:
sprintf(temp_string, "Byte: %u (0x%x)", getU32(), getU32());
break;
default:
sprintf(temp_string, "Type: %x: ", type);
for (uint32 i = 0; i < getElementSize(); i++) {
sprintf(&temp_string[strlen(temp_string-1)], "%x", data[i]);
}
}
}
string ret(temp_string);
delete [] temp_string;
return ret;
}
} // namespace RawSpeed
<|endoftext|> |
<commit_before><commit_msg>Use RecursiveMutex for CLAP UI events<commit_after><|endoftext|> |
<commit_before>/*
Copyright (c) 2015-2017 by the parties listed in the AUTHORS file.
All rights reserved. Use of this source code is governed by
a BSD-style license that can be found in the LICENSE file.
*/
#ifndef TOAST_MEMORY_HPP
#define TOAST_MEMORY_HPP
namespace toast { namespace mem {
// Byte alignment for SIMD. This should work for all modern systems,
// including MIC
static size_t const SIMD_ALIGN = 64;
void * aligned_alloc ( size_t size, size_t align );
void aligned_free ( void * ptr );
template < typename T >
class simd_allocator {
public :
// type definitions
typedef T value_type;
typedef T * pointer;
typedef T const * const_pointer;
typedef T & reference;
typedef T const & const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
// rebind allocator to type U
template < typename U >
struct rebind {
typedef simd_allocator < U > other;
};
// return address of values
pointer address ( reference value ) const {
return &value;
}
const_pointer address ( const_reference value ) const {
return &value;
}
simd_allocator ( ) throw() { }
simd_allocator ( simd_allocator const & ) throw() { }
template < typename U >
simd_allocator ( simd_allocator < U > const & ) throw() { }
~simd_allocator ( ) throw() { }
// return maximum number of elements that can be allocated
size_type max_size() const throw() {
return std::numeric_limits < std::size_t > :: max() / sizeof(T);
}
// allocate but don't initialize num elements of type T
pointer allocate ( size_type const num, const void *hint=0 ) {
pointer align_ptr = static_cast < pointer > ( aligned_alloc ( num * sizeof(T), SIMD_ALIGN ) );
return align_ptr;
}
// initialize elements of allocated storage p with value value
void construct ( pointer p, T const & value ) {
// initialize memory with placement new
new ( static_cast < void * > (p) ) T(value);
}
// destroy elements of initialized storage p
void destroy ( pointer p ) {
// destroy objects by calling their destructor
p->~T();
}
// deallocate storage p of deleted elements
void deallocate ( pointer p, size_type num ) {
aligned_free ( static_cast < void * > (p) );
}
};
// return that all specializations of this allocator are interchangeable
template < typename T1, class T2 >
bool operator == ( simd_allocator < T1 > const &, simd_allocator < T2 > const & ) throw() {
return true;
}
template < typename T1, class T2 >
bool operator != ( simd_allocator < T1 > const &, simd_allocator < T2 > const & ) throw() {
return false;
}
//========================================================================//
// cleaner version of:
// double* var = static_cast<double*>(toast::mem::aligned_alloc(
// n * sizeof(double), toast::mem::SIMD_ALIGN ) );
template <typename _Tp>
_Tp* simd_alloc(size_t n)
{
return static_cast<_Tp*>(toast::mem::aligned_alloc(n * sizeof(_Tp),
toast::mem::SIMD_ALIGN));
}
//========================================================================//
// template class for memory-aligned c-style array with internal
// allocation and deallocation
template <typename _Tp>
class simd_array
{
public:
typedef std::size_t size_type;
public:
simd_array()
: m_data(nullptr)
{ }
simd_array(size_type _n)
: m_data(toast::mem::simd_alloc<_Tp>(_n))
{ }
simd_array(size_type _n, const _Tp& _init)
: m_data(toast::mem::simd_alloc<_Tp>(_n))
{
for(size_type i = 0; i < _n; ++i)
m_data[i] = _init;
}
~simd_array()
{
toast::mem::aligned_free(m_data);
}
// conversion function to const _Tp*
operator const _Tp*() const
__attribute__((assume_aligned(64)))
{ return m_data; }
// conversion function to _Tp*
operator _Tp*()
__attribute__((assume_aligned(64)))
{ return m_data; }
_Tp& operator [](const size_type& i) { return m_data[i]; }
const _Tp& operator [](const size_type& i) const { return m_data[i]; }
simd_array& operator=(const simd_array& rhs)
{
if(this != &rhs)
{
if(m_data)
toast::mem::aligned_free(m_data);
m_data = static_cast<_Tp*>(rhs.m_data);
// otherwise will be deleted
const_cast<simd_array&>(rhs).m_data = nullptr;
}
return *this;
}
private:
_Tp* m_data __attribute__((bnd_variable_size));
} __attribute__((aligned (64)));
//========================================================================//
} }
#endif
<commit_msg>Fix compilation with Intel compilers.<commit_after>/*
Copyright (c) 2015-2017 by the parties listed in the AUTHORS file.
All rights reserved. Use of this source code is governed by
a BSD-style license that can be found in the LICENSE file.
*/
#ifndef TOAST_MEMORY_HPP
#define TOAST_MEMORY_HPP
namespace toast { namespace mem {
// Byte alignment for SIMD. This should work for all modern systems,
// including MIC
static size_t const SIMD_ALIGN = 64;
void * aligned_alloc ( size_t size, size_t align );
void aligned_free ( void * ptr );
template < typename T >
class simd_allocator {
public :
// type definitions
typedef T value_type;
typedef T * pointer;
typedef T const * const_pointer;
typedef T & reference;
typedef T const & const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
// rebind allocator to type U
template < typename U >
struct rebind {
typedef simd_allocator < U > other;
};
// return address of values
pointer address ( reference value ) const {
return &value;
}
const_pointer address ( const_reference value ) const {
return &value;
}
simd_allocator ( ) throw() { }
simd_allocator ( simd_allocator const & ) throw() { }
template < typename U >
simd_allocator ( simd_allocator < U > const & ) throw() { }
~simd_allocator ( ) throw() { }
// return maximum number of elements that can be allocated
size_type max_size() const throw() {
return std::numeric_limits < std::size_t > :: max() / sizeof(T);
}
// allocate but don't initialize num elements of type T
pointer allocate ( size_type const num, const void *hint=0 ) {
pointer align_ptr = static_cast < pointer > ( aligned_alloc ( num * sizeof(T), SIMD_ALIGN ) );
return align_ptr;
}
// initialize elements of allocated storage p with value value
void construct ( pointer p, T const & value ) {
// initialize memory with placement new
new ( static_cast < void * > (p) ) T(value);
}
// destroy elements of initialized storage p
void destroy ( pointer p ) {
// destroy objects by calling their destructor
p->~T();
}
// deallocate storage p of deleted elements
void deallocate ( pointer p, size_type num ) {
aligned_free ( static_cast < void * > (p) );
}
};
// return that all specializations of this allocator are interchangeable
template < typename T1, class T2 >
bool operator == ( simd_allocator < T1 > const &, simd_allocator < T2 > const & ) throw() {
return true;
}
template < typename T1, class T2 >
bool operator != ( simd_allocator < T1 > const &, simd_allocator < T2 > const & ) throw() {
return false;
}
//========================================================================//
// cleaner version of:
// double* var = static_cast<double*>(toast::mem::aligned_alloc(
// n * sizeof(double), toast::mem::SIMD_ALIGN ) );
template <typename _Tp>
_Tp* simd_alloc(size_t n)
{
return static_cast<_Tp*>(toast::mem::aligned_alloc(n * sizeof(_Tp),
toast::mem::SIMD_ALIGN));
}
//========================================================================//
// template class for memory-aligned c-style array with internal
// allocation and deallocation
template <typename _Tp>
class simd_array
{
public:
typedef std::size_t size_type;
public:
simd_array()
: m_data(nullptr)
{ }
simd_array(size_type _n)
: m_data(toast::mem::simd_alloc<_Tp>(_n))
{ }
simd_array(size_type _n, const _Tp& _init)
: m_data(toast::mem::simd_alloc<_Tp>(_n))
{
for(size_type i = 0; i < _n; ++i)
m_data[i] = _init;
}
~simd_array()
{
toast::mem::aligned_free(m_data);
}
// conversion function to const _Tp*
operator const _Tp*() const
__attribute__((assume_aligned(64)))
{ return m_data; }
// conversion function to _Tp*
operator _Tp*()
__attribute__((assume_aligned(64)))
{ return m_data; }
//_Tp& operator [](const size_type& i) { return m_data[i]; }
//const _Tp& operator [](const size_type& i) const { return m_data[i]; }
simd_array& operator=(const simd_array& rhs)
{
if(this != &rhs)
{
if(m_data)
toast::mem::aligned_free(m_data);
m_data = static_cast<_Tp*>(rhs.m_data);
// otherwise will be deleted
const_cast<simd_array&>(rhs).m_data = nullptr;
}
return *this;
}
private:
_Tp* m_data __attribute__((bnd_variable_size));
} __attribute__((aligned (64)));
//========================================================================//
} }
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkScaleTransformTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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 <iostream>
#include "itkScaleTransform.h"
#include "vnl/vnl_vector_fixed.h"
#include "itkVector.h"
int itkScaleTransformTest(int ,char * [] )
{
typedef itk::ScaleTransform<double> TransformType;
const double epsilon = 1e-10;
const unsigned int N = 3;
bool Ok = true;
/* Create a 3D identity transformation and show its parameters */
{
TransformType::Pointer identityTransform = TransformType::New();
TransformType::ScaleType scale = identityTransform->GetScale();
std::cout << "Scale from instantiating an identity transform: ";
for(unsigned int j=0; j<N; j++)
{
std::cout << scale[j] << " ";
}
std::cout << std::endl;
for(unsigned int i=0; i<N; i++)
{
if( fabs( scale[i] - 1.0 ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Identity doesn't have a unit scale " << std::endl;
return EXIT_FAILURE;
}
}
/* Create a Scale transform */
{
TransformType::Pointer scaleTransform = TransformType::New();
TransformType::ScaleType::ValueType iscaleInit[3] = {1,4,9};
TransformType::ScaleType iscale = iscaleInit;
scaleTransform->SetScale( iscale );
TransformType::ScaleType scale = scaleTransform->GetScale();
std::cout << "scale initialization test: ";
for(unsigned int j=0; j<N; j++)
{
std::cout << scale[j] << " ";
}
std::cout << std::endl;
for(unsigned int i=0; i<N; i++)
{
if( fabs( scale[i] - iscale[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "GetScale differs from SetScale value " << std::endl;
return EXIT_FAILURE;
}
{
// scale an itk::Point
TransformType::InputPointType::ValueType pInit[3] = {10,10,10};
TransformType::InputPointType p = pInit;
TransformType::InputPointType q;
for(unsigned int j=0; j<N; j++)
{
q[j] = p[j] * iscale[j];
}
TransformType::OutputPointType r;
r = scaleTransform->TransformPoint( p );
for(unsigned int i=0; i<N; i++)
{
if( fabs( q[i] - r[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Error scaling point : " << p << std::endl;
std::cerr << "Result should be : " << q << std::endl;
std::cerr << "Reported Result is : " << r << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Ok scaling an itk::Point " << std::endl;
}
}
{
// Scale an itk::Vector
TransformType::InputVectorType::ValueType pInit[3] = {10,10,10};
TransformType::InputVectorType p = pInit;
TransformType::OutputVectorType q;
for(unsigned int j=0; j<N; j++)
{
q[j] = p[j] * iscale[j];
}
TransformType::OutputVectorType r;
r = scaleTransform->TransformVector( p );
for(unsigned int i=0; i<N; i++)
{
if( fabs( q[i]- r[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Error scaling vector: " << p << std::endl;
std::cerr << "Reported Result is : " << q << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Ok scaling an itk::Vector " << std::endl;
}
}
{
// Scale an itk::CovariantVector
TransformType::InputCovariantVectorType::ValueType pInit[3] = {10,10,10};
TransformType::InputCovariantVectorType p = pInit;
TransformType::OutputCovariantVectorType q;
for(unsigned int j=0; j<N; j++)
{
q[j] = p[j] / iscale[j];
}
TransformType::OutputCovariantVectorType r;
r = scaleTransform->TransformCovariantVector( p );
for(unsigned int i=0; i<N; i++)
{
if( fabs( q[i]- r[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Error scaling covariant vector: " << p << std::endl;
std::cerr << "Reported Result is : " << q << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Ok scaling an itk::CovariantVector " << std::endl;
}
}
{
// Scale a vnl_vector
TransformType::InputVnlVectorType p;
p[0] = 11;
p[1] = 7;
p[2] = 15;
TransformType::OutputVnlVectorType q;
for(unsigned int j=0; j<N; j++)
{
q[j] = p[j] * iscale[j];
}
TransformType::OutputVnlVectorType r;
r = scaleTransform->TransformVector( p );
for(unsigned int i=0; i<N; i++)
{
if( fabs( q[i] - r[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Error scaling vnl_vector: " << p << std::endl;
std::cerr << "Reported Result is : " << q << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Ok scaling an vnl_Vector " << std::endl;
}
}
}
return EXIT_SUCCESS;
}
<commit_msg>ENH: new methods SetCenter() / GetCenter() methods exercised.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkScaleTransformTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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 <iostream>
#include "itkScaleTransform.h"
#include "vnl/vnl_vector_fixed.h"
#include "itkVector.h"
int itkScaleTransformTest(int ,char * [] )
{
typedef itk::ScaleTransform<double> TransformType;
const double epsilon = 1e-10;
const unsigned int N = 3;
bool Ok = true;
/* Create a 3D identity transformation and show its parameters */
{
TransformType::Pointer identityTransform = TransformType::New();
TransformType::ScaleType scale = identityTransform->GetScale();
std::cout << "Scale from instantiating an identity transform: ";
for(unsigned int j=0; j<N; j++)
{
std::cout << scale[j] << " ";
}
std::cout << std::endl;
for(unsigned int i=0; i<N; i++)
{
if( fabs( scale[i] - 1.0 ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Identity doesn't have a unit scale " << std::endl;
return EXIT_FAILURE;
}
}
/* Create a Scale transform */
{
TransformType::Pointer scaleTransform = TransformType::New();
TransformType::ScaleType::ValueType iscaleInit[3] = {1,4,9};
TransformType::ScaleType iscale = iscaleInit;
scaleTransform->SetScale( iscale );
TransformType::ScaleType scale = scaleTransform->GetScale();
std::cout << "scale initialization test: ";
for(unsigned int j=0; j<N; j++)
{
std::cout << scale[j] << " ";
}
std::cout << std::endl;
for(unsigned int i=0; i<N; i++)
{
if( fabs( scale[i] - iscale[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "GetScale differs from SetScale value " << std::endl;
return EXIT_FAILURE;
}
{
// scale an itk::Point
TransformType::InputPointType::ValueType pInit[3] = {10,10,10};
TransformType::InputPointType p = pInit;
TransformType::InputPointType q;
for(unsigned int j=0; j<N; j++)
{
q[j] = p[j] * iscale[j];
}
TransformType::OutputPointType r;
r = scaleTransform->TransformPoint( p );
for(unsigned int i=0; i<N; i++)
{
if( fabs( q[i] - r[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Error scaling point : " << p << std::endl;
std::cerr << "Result should be : " << q << std::endl;
std::cerr << "Reported Result is : " << r << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Ok scaling an itk::Point " << std::endl;
}
}
{
// Scale an itk::Vector
TransformType::InputVectorType::ValueType pInit[3] = {10,10,10};
TransformType::InputVectorType p = pInit;
TransformType::OutputVectorType q;
for(unsigned int j=0; j<N; j++)
{
q[j] = p[j] * iscale[j];
}
TransformType::OutputVectorType r;
r = scaleTransform->TransformVector( p );
for(unsigned int i=0; i<N; i++)
{
if( fabs( q[i]- r[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Error scaling vector: " << p << std::endl;
std::cerr << "Reported Result is : " << q << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Ok scaling an itk::Vector " << std::endl;
}
}
{
// Scale an itk::CovariantVector
TransformType::InputCovariantVectorType::ValueType pInit[3] = {10,10,10};
TransformType::InputCovariantVectorType p = pInit;
TransformType::OutputCovariantVectorType q;
for(unsigned int j=0; j<N; j++)
{
q[j] = p[j] / iscale[j];
}
TransformType::OutputCovariantVectorType r;
r = scaleTransform->TransformCovariantVector( p );
for(unsigned int i=0; i<N; i++)
{
if( fabs( q[i]- r[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Error scaling covariant vector: " << p << std::endl;
std::cerr << "Reported Result is : " << q << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Ok scaling an itk::CovariantVector " << std::endl;
}
}
{
// Scale a vnl_vector
TransformType::InputVnlVectorType p;
p[0] = 11;
p[1] = 7;
p[2] = 15;
TransformType::OutputVnlVectorType q;
for(unsigned int j=0; j<N; j++)
{
q[j] = p[j] * iscale[j];
}
TransformType::OutputVnlVectorType r;
r = scaleTransform->TransformVector( p );
for(unsigned int i=0; i<N; i++)
{
if( fabs( q[i] - r[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Error scaling vnl_vector: " << p << std::endl;
std::cerr << "Reported Result is : " << q << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Ok scaling an vnl_Vector " << std::endl;
}
}
// Exercise Set/Get Center methods
{
typedef TransformType::InputPointType CenterType;
CenterType center;
center[0] = 5;
center[1] = 6;
center[2] = 7;
scaleTransform->SetCenter( center );
CenterType c2 = scaleTransform->GetCenter();
if( c2.EuclideanDistanceTo( center ) > 1e-5 )
{
std::cerr << "Error in Set/Get center." << std::endl;
std::cerr << "It was SetCenter() to : " << center << std::endl;
std::cerr << "but GetCenter() returned : " << c2 << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Ok SetCenter() / GetCenter() " << std::endl;
}
}
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "TerrainTests.h"
#include "OgreTerrain.h"
#include "OgreConfigFile.h"
#include "OgreResourceGroupManager.h"
#include "OgreLogManager.h"
//--------------------------------------------------------------------------
void TerrainTests::SetUp()
{
mFSLayer = OGRE_NEW_T(Ogre::FileSystemLayer, Ogre::MEMCATEGORY_GENERAL)(OGRE_VERSION_NAME);
#ifdef OGRE_STATIC_LIB
mRoot = OGRE_NEW Root(BLANKSTRING);
mStaticPluginLoader.load();
#else
String pluginsPath = mFSLayer->getConfigFilePath("plugins.cfg");
mRoot = OGRE_NEW Root(pluginsPath);
Ogre::LogManager::getSingletonPtr()->getDefaultLog()->setDebugOutputEnabled(false);
#endif
mTerrainOpts = OGRE_NEW TerrainGlobalOptions();
// Load resource paths from config file
ConfigFile cf;
String resourcesPath = mFSLayer->getConfigFilePath("resources.cfg");
cf.load(resourcesPath);
// Go through all sections & settings in the file
String secName, typeName, archName;
ConfigFile::SettingsBySection_::const_iterator seci;
for(seci = cf.getSettingsBySection().begin(); seci != cf.getSettingsBySection().end(); ++seci) {
secName = seci->first;
const ConfigFile::SettingsMultiMap& settings = seci->second;
ConfigFile::SettingsMultiMap::const_iterator i;
for (i = settings.begin(); i != settings.end(); ++i)
{
typeName = i->first;
archName = i->second;
ResourceGroupManager::getSingleton().addResourceLocation(
archName, typeName, secName);
}
}
mSceneMgr = mRoot->createSceneManager();
}
//--------------------------------------------------------------------------
void TerrainTests::TearDown()
{
OGRE_DELETE mTerrainOpts;
OGRE_DELETE mRoot;
OGRE_DELETE_T(mFSLayer, FileSystemLayer, Ogre::MEMCATEGORY_GENERAL);
}
//--------------------------------------------------------------------------
TEST_F(TerrainTests, create)
{
Terrain* t = OGRE_NEW Terrain(mSceneMgr);
Image img;
img.load("terrain.png", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
Terrain::ImportData imp;
imp.inputImage = &img;
imp.terrainSize = 513;
imp.worldSize = 1000;
imp.minBatchSize = 33;
imp.maxBatchSize = 65;
t->prepare(imp);
// Note: Do not load as this would require GPU access!
//t->load();
OGRE_DELETE t;
ASSERT_TRUE(1);
}
//--------------------------------------------------------------------------
<commit_msg>Tests: Terrain - actually test something<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "TerrainTests.h"
#include "OgreTerrain.h"
#include "OgreConfigFile.h"
#include "OgreResourceGroupManager.h"
#include "OgreLogManager.h"
//--------------------------------------------------------------------------
void TerrainTests::SetUp()
{
mFSLayer = OGRE_NEW_T(Ogre::FileSystemLayer, Ogre::MEMCATEGORY_GENERAL)(OGRE_VERSION_NAME);
#ifdef OGRE_STATIC_LIB
mRoot = OGRE_NEW Root(BLANKSTRING);
mStaticPluginLoader.load();
#else
String pluginsPath = mFSLayer->getConfigFilePath("plugins.cfg");
mRoot = OGRE_NEW Root(pluginsPath);
Ogre::LogManager::getSingletonPtr()->getDefaultLog()->setDebugOutputEnabled(false);
#endif
mTerrainOpts = OGRE_NEW TerrainGlobalOptions();
// Load resource paths from config file
ConfigFile cf;
String resourcesPath = mFSLayer->getConfigFilePath("resources.cfg");
cf.load(resourcesPath);
// Go through all sections & settings in the file
String secName, typeName, archName;
ConfigFile::SettingsBySection_::const_iterator seci;
for(seci = cf.getSettingsBySection().begin(); seci != cf.getSettingsBySection().end(); ++seci) {
secName = seci->first;
const ConfigFile::SettingsMultiMap& settings = seci->second;
ConfigFile::SettingsMultiMap::const_iterator i;
for (i = settings.begin(); i != settings.end(); ++i)
{
typeName = i->first;
archName = i->second;
ResourceGroupManager::getSingleton().addResourceLocation(
archName, typeName, secName);
}
}
mSceneMgr = mRoot->createSceneManager();
}
//--------------------------------------------------------------------------
void TerrainTests::TearDown()
{
OGRE_DELETE mTerrainOpts;
OGRE_DELETE mRoot;
OGRE_DELETE_T(mFSLayer, FileSystemLayer, Ogre::MEMCATEGORY_GENERAL);
}
//--------------------------------------------------------------------------
TEST_F(TerrainTests, create)
{
Terrain* t = OGRE_NEW Terrain(mSceneMgr);
Image img;
img.load("terrain.png", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
Terrain::ImportData imp;
imp.inputImage = &img;
imp.terrainSize = 513;
imp.worldSize = 1000;
imp.minBatchSize = 33;
imp.maxBatchSize = 65;
ASSERT_TRUE(t->prepare(imp));
// Note: Do not load as this would require GPU access!
//t->load();
OGRE_DELETE t;
}
//--------------------------------------------------------------------------
<|endoftext|> |
<commit_before><commit_msg>fix some MSVC warnings<commit_after><|endoftext|> |
<commit_before>// Copyright 2015 The Bazel Authors. 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 <errno.h> // errno, ENAMETOOLONG
#include <limits.h>
#include <pwd.h>
#include <signal.h>
#include <string.h> // strerror
#include <sys/mount.h>
#include <sys/param.h>
#include <sys/queue.h>
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
#include <libprocstat.h> // must be included after <sys/...> headers
#include "src/main/cpp/blaze_util.h"
#include "src/main/cpp/blaze_util_platform.h"
#include "src/main/cpp/util/errors.h"
#include "src/main/cpp/util/exit_code.h"
#include "src/main/cpp/util/file.h"
#include "src/main/cpp/util/logging.h"
#include "src/main/cpp/util/port.h"
#include "src/main/cpp/util/strings.h"
namespace blaze {
using blaze_util::GetLastErrorString;
using std::string;
string GetOutputRoot() {
char buf[2048];
struct passwd pwbuf;
struct passwd *pw = NULL;
int uid = getuid();
int r = getpwuid_r(uid, &pwbuf, buf, 2048, &pw);
if (r != -1 && pw != NULL) {
return blaze_util::JoinPath(pw->pw_dir, ".cache/bazel");
} else {
return "/tmp";
}
}
void WarnFilesystemType(const string &output_base) {
struct statfs buf = {};
if (statfs(output_base.c_str(), &buf) < 0) {
BAZEL_LOG(WARNING) << "couldn't get file system type information for '"
<< output_base << "': " << strerror(errno);
return;
}
if (strcmp(buf.f_fstypename, "nfs") == 0) {
BAZEL_LOG(WARNING) << "Output base '" << output_base
<< "' is on NFS. This may lead to surprising failures "
"and undetermined behavior.";
}
}
string GetSelfPath() {
char buffer[PATH_MAX] = {};
auto pid = getpid();
if (kill(pid, 0) < 0) return "";
auto procstat = procstat_open_sysctl();
unsigned int n;
auto p = procstat_getprocs(procstat, KERN_PROC_PID, pid, &n);
if (p) {
if (n != 1) {
BAZEL_DIE(blaze_exit_code::INTERNAL_ERROR)
<< "expected exactly one process from procstat_getprocs, got " << n
<< ": " << GetLastErrorString();
}
auto r = procstat_getpathname(procstat, p, buffer, PATH_MAX);
if (r != 0) {
BAZEL_DIE(blaze_exit_code::INTERNAL_ERROR)
<< "procstat_getpathname failed: " << GetLastErrorString();
}
procstat_freeprocs(procstat, p);
}
procstat_close(procstat);
return string(buffer);
}
uint64_t GetMillisecondsMonotonic() {
struct timespec ts = {};
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec * 1000LL + (ts.tv_nsec / 1000000LL);
}
uint64_t GetMillisecondsSinceProcessStart() {
struct timespec ts = {};
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
return ts.tv_sec * 1000LL + (ts.tv_nsec / 1000000LL);
}
void SetScheduling(bool batch_cpu_scheduling, int io_nice_level) {
// Stubbed out so we can compile for FreeBSD.
}
string GetProcessCWD(int pid) {
if (kill(pid, 0) < 0) return "";
auto procstat = procstat_open_sysctl();
unsigned int n;
auto p = procstat_getprocs(procstat, KERN_PROC_PID, pid, &n);
string cwd;
if (p) {
if (n != 1) {
BAZEL_DIE(blaze_exit_code::INTERNAL_ERROR)
<< "expected exactly one process from procstat_getprocs, got " << n
<< ": " << GetLastErrorString();
}
auto files = procstat_getfiles(procstat, p, false);
filestat *entry;
STAILQ_FOREACH(entry, files, next) {
if (entry->fs_uflags & PS_FST_UFLAG_CDIR) {
if (entry->fs_path) {
cwd = entry->fs_path;
} else {
cwd = "";
}
}
}
procstat_freefiles(procstat, files);
procstat_freeprocs(procstat, p);
}
procstat_close(procstat);
return cwd;
}
bool IsSharedLibrary(const string &filename) {
return blaze_util::ends_with(filename, ".so");
}
string GetSystemJavabase() {
// if JAVA_HOME is defined, then use it as default.
string javahome = GetEnv("JAVA_HOME");
return !javahome.empty() ? javahome : "/usr/local/openjdk8";
}
void WriteSystemSpecificProcessIdentifier(
const string& server_dir, pid_t server_pid) {
}
bool VerifyServerProcess(int pid, const string &output_base) {
// TODO(lberki): This only checks for the process's existence, not whether
// its start time matches. Therefore this might accidentally kill an
// unrelated process if the server died and the PID got reused.
return killpg(pid, 0) == 0;
}
// Not supported.
void ExcludePathFromBackup(const string &path) {
}
int32_t GetExplicitSystemLimit(const int resource) {
return -1;
}
} // namespace blaze
<commit_msg>blaze_util_freebsd.cc: include path.h explicitly<commit_after>// Copyright 2015 The Bazel Authors. 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 <errno.h> // errno, ENAMETOOLONG
#include <limits.h>
#include <pwd.h>
#include <signal.h>
#include <string.h> // strerror
#include <sys/mount.h>
#include <sys/param.h>
#include <sys/queue.h>
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
#include <libprocstat.h> // must be included after <sys/...> headers
#include "src/main/cpp/blaze_util.h"
#include "src/main/cpp/blaze_util_platform.h"
#include "src/main/cpp/util/errors.h"
#include "src/main/cpp/util/exit_code.h"
#include "src/main/cpp/util/file.h"
#include "src/main/cpp/util/logging.h"
#include "src/main/cpp/util/path.h"
#include "src/main/cpp/util/port.h"
#include "src/main/cpp/util/strings.h"
namespace blaze {
using blaze_util::GetLastErrorString;
using std::string;
string GetOutputRoot() {
char buf[2048];
struct passwd pwbuf;
struct passwd *pw = NULL;
int uid = getuid();
int r = getpwuid_r(uid, &pwbuf, buf, 2048, &pw);
if (r != -1 && pw != NULL) {
return blaze_util::JoinPath(pw->pw_dir, ".cache/bazel");
} else {
return "/tmp";
}
}
void WarnFilesystemType(const string &output_base) {
struct statfs buf = {};
if (statfs(output_base.c_str(), &buf) < 0) {
BAZEL_LOG(WARNING) << "couldn't get file system type information for '"
<< output_base << "': " << strerror(errno);
return;
}
if (strcmp(buf.f_fstypename, "nfs") == 0) {
BAZEL_LOG(WARNING) << "Output base '" << output_base
<< "' is on NFS. This may lead to surprising failures "
"and undetermined behavior.";
}
}
string GetSelfPath() {
char buffer[PATH_MAX] = {};
auto pid = getpid();
if (kill(pid, 0) < 0) return "";
auto procstat = procstat_open_sysctl();
unsigned int n;
auto p = procstat_getprocs(procstat, KERN_PROC_PID, pid, &n);
if (p) {
if (n != 1) {
BAZEL_DIE(blaze_exit_code::INTERNAL_ERROR)
<< "expected exactly one process from procstat_getprocs, got " << n
<< ": " << GetLastErrorString();
}
auto r = procstat_getpathname(procstat, p, buffer, PATH_MAX);
if (r != 0) {
BAZEL_DIE(blaze_exit_code::INTERNAL_ERROR)
<< "procstat_getpathname failed: " << GetLastErrorString();
}
procstat_freeprocs(procstat, p);
}
procstat_close(procstat);
return string(buffer);
}
uint64_t GetMillisecondsMonotonic() {
struct timespec ts = {};
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec * 1000LL + (ts.tv_nsec / 1000000LL);
}
uint64_t GetMillisecondsSinceProcessStart() {
struct timespec ts = {};
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
return ts.tv_sec * 1000LL + (ts.tv_nsec / 1000000LL);
}
void SetScheduling(bool batch_cpu_scheduling, int io_nice_level) {
// Stubbed out so we can compile for FreeBSD.
}
string GetProcessCWD(int pid) {
if (kill(pid, 0) < 0) return "";
auto procstat = procstat_open_sysctl();
unsigned int n;
auto p = procstat_getprocs(procstat, KERN_PROC_PID, pid, &n);
string cwd;
if (p) {
if (n != 1) {
BAZEL_DIE(blaze_exit_code::INTERNAL_ERROR)
<< "expected exactly one process from procstat_getprocs, got " << n
<< ": " << GetLastErrorString();
}
auto files = procstat_getfiles(procstat, p, false);
filestat *entry;
STAILQ_FOREACH(entry, files, next) {
if (entry->fs_uflags & PS_FST_UFLAG_CDIR) {
if (entry->fs_path) {
cwd = entry->fs_path;
} else {
cwd = "";
}
}
}
procstat_freefiles(procstat, files);
procstat_freeprocs(procstat, p);
}
procstat_close(procstat);
return cwd;
}
bool IsSharedLibrary(const string &filename) {
return blaze_util::ends_with(filename, ".so");
}
string GetSystemJavabase() {
// if JAVA_HOME is defined, then use it as default.
string javahome = GetEnv("JAVA_HOME");
return !javahome.empty() ? javahome : "/usr/local/openjdk8";
}
void WriteSystemSpecificProcessIdentifier(
const string& server_dir, pid_t server_pid) {
}
bool VerifyServerProcess(int pid, const string &output_base) {
// TODO(lberki): This only checks for the process's existence, not whether
// its start time matches. Therefore this might accidentally kill an
// unrelated process if the server died and the PID got reused.
return killpg(pid, 0) == 0;
}
// Not supported.
void ExcludePathFromBackup(const string &path) {
}
int32_t GetExplicitSystemLimit(const int resource) {
return -1;
}
} // namespace blaze
<|endoftext|> |
<commit_before><commit_msg>Shifting code a bit to make it more readable<commit_after><|endoftext|> |
<commit_before><commit_msg>EXP-1577 FOLLOWUP Making default My Profile window size the same as size of other residents' profile floaters.<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: QueryDesignView.hxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: vg $ $Date: 2005-02-16 16:01:23 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DBAUI_QUERYDESIGNVIEW_HXX
#define DBAUI_QUERYDESIGNVIEW_HXX
#ifndef DBAUI_QUERYVIEW_HXX
#include "queryview.hxx"
#endif
#ifndef _SV_SPLIT_HXX
#include <vcl/split.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef DBAUI_ENUMTYPES_HXX
#include "QEnumTypes.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef DBAUI_QUERYCONTROLLER_HXX
#include "querycontroller.hxx"
#endif
#ifndef DBAUI_CONNECTIONLINEDATA_HXX
#include "ConnectionLineData.hxx"
#endif
namespace connectivity
{
class OSQLParseNode;
}
class ComboBox;
namespace dbaui
{
enum SqlParseError
{
eIllegalJoin,
eStatementTooLong,
eNoConnection,
eNoSelectStatement,
eStatementTooComplex,
eColumnInLikeNotFound,
eNoColumnInLike,
eColumnNotFound,
eNativeMode,
eTooManyTables,
eTooManyConditions,
eTooManyColumns,
eIllegalJoinCondition,
eOk
};
class OQueryViewSwitch;
class OAddTableDlg;
class OQueryTableWindow;
class OSelectionBrowseBox;
class OTableConnection;
class OQueryTableConnectionData;
class OQueryContainerWindow;
class OQueryDesignView : public OQueryView
{
enum ChildFocusState
{
SELECTION,
TABLEVIEW,
NONE
};
Splitter m_aSplitter;
::com::sun::star::lang::Locale m_aLocale;
::rtl::OUString m_sDecimalSep;
OSelectionBrowseBox* m_pSelectionBox; // presents the lower window
ChildFocusState m_eChildFocus;
sal_Bool m_bInKeyEvent;
sal_Bool m_bInSplitHandler;
public:
OQueryDesignView(OQueryContainerWindow* pParent, OQueryController* _pController,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& );
virtual ~OQueryDesignView();
virtual sal_Bool isCutAllowed();
virtual sal_Bool isPasteAllowed();
virtual sal_Bool isCopyAllowed();
virtual void copy();
virtual void cut();
virtual void paste();
// clears the whole query
virtual void clear();
// set the view readonly or not
virtual void setReadOnly(sal_Bool _bReadOnly);
// check if the statement is correct when not returning false
virtual sal_Bool checkStatement();
// set the statement for representation
virtual void setStatement(const ::rtl::OUString& _rsStatement);
// returns the current sql statement
virtual ::rtl::OUString getStatement();
/// late construction
virtual void Construct();
virtual void initialize();
// window overloads
virtual long PreNotify( NotifyEvent& rNEvt );
virtual void GetFocus();
BOOL IsAddAllowed();
sal_Bool isSlotEnabled(sal_Int32 _nSlotId);
void setSlotEnabled(sal_Int32 _nSlotId,sal_Bool _bEnable);
void setNoneVisbleRow(sal_Int32 _nRows);
::com::sun::star::lang::Locale getLocale() const { return m_aLocale;}
::rtl::OUString getDecimalSeparator() const { return m_sDecimalSep;}
sal_Bool HasTable() const;
SqlParseError InsertField( const OTableFieldDescRef& rInfo, sal_Bool bVis=sal_True, sal_Bool bActivate = sal_True);
// save the position of the table window and the pos of the splitters
void SaveTabWinUIConfig(OQueryTableWindow* pWin);
// called when fields are deleted
void DeleteFields( const ::rtl::OUString& rAliasName );
// called when a table from tabeview was deleted
void TableDeleted(const ::rtl::OUString& rAliasName);
BOOL getColWidth( const ::rtl::OUString& rAliasName, const ::rtl::OUString& rFieldName, sal_uInt32& nWidth );
void fillValidFields(const ::rtl::OUString& strTableName, ComboBox* pFieldList);
void zoomTableView(const Fraction& _rFraction);
void SaveUIConfig();
void stopTimer();
void startTimer();
void reset();
sal_Bool InitFromParseNode();
::connectivity::OSQLParseNode* getPredicateTreeFromEntry( OTableFieldDescRef pEntry,
const String& _sCriteria,
::rtl::OUString& _rsErrorMessage,
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxColumn);
protected:
// return the Rectangle where I can paint myself
virtual void resizeDocumentView(Rectangle& rRect);
DECL_LINK( SplitHdl, void* );
};
}
#endif // DBAUI_QUERYDESIGNVIEW_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.18.114); FILE MERGED 2005/09/05 17:34:22 rt 1.18.114.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: QueryDesignView.hxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: rt $ $Date: 2005-09-08 15:30: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
*
************************************************************************/
#ifndef DBAUI_QUERYDESIGNVIEW_HXX
#define DBAUI_QUERYDESIGNVIEW_HXX
#ifndef DBAUI_QUERYVIEW_HXX
#include "queryview.hxx"
#endif
#ifndef _SV_SPLIT_HXX
#include <vcl/split.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef DBAUI_ENUMTYPES_HXX
#include "QEnumTypes.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef DBAUI_QUERYCONTROLLER_HXX
#include "querycontroller.hxx"
#endif
#ifndef DBAUI_CONNECTIONLINEDATA_HXX
#include "ConnectionLineData.hxx"
#endif
namespace connectivity
{
class OSQLParseNode;
}
class ComboBox;
namespace dbaui
{
enum SqlParseError
{
eIllegalJoin,
eStatementTooLong,
eNoConnection,
eNoSelectStatement,
eStatementTooComplex,
eColumnInLikeNotFound,
eNoColumnInLike,
eColumnNotFound,
eNativeMode,
eTooManyTables,
eTooManyConditions,
eTooManyColumns,
eIllegalJoinCondition,
eOk
};
class OQueryViewSwitch;
class OAddTableDlg;
class OQueryTableWindow;
class OSelectionBrowseBox;
class OTableConnection;
class OQueryTableConnectionData;
class OQueryContainerWindow;
class OQueryDesignView : public OQueryView
{
enum ChildFocusState
{
SELECTION,
TABLEVIEW,
NONE
};
Splitter m_aSplitter;
::com::sun::star::lang::Locale m_aLocale;
::rtl::OUString m_sDecimalSep;
OSelectionBrowseBox* m_pSelectionBox; // presents the lower window
ChildFocusState m_eChildFocus;
sal_Bool m_bInKeyEvent;
sal_Bool m_bInSplitHandler;
public:
OQueryDesignView(OQueryContainerWindow* pParent, OQueryController* _pController,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& );
virtual ~OQueryDesignView();
virtual sal_Bool isCutAllowed();
virtual sal_Bool isPasteAllowed();
virtual sal_Bool isCopyAllowed();
virtual void copy();
virtual void cut();
virtual void paste();
// clears the whole query
virtual void clear();
// set the view readonly or not
virtual void setReadOnly(sal_Bool _bReadOnly);
// check if the statement is correct when not returning false
virtual sal_Bool checkStatement();
// set the statement for representation
virtual void setStatement(const ::rtl::OUString& _rsStatement);
// returns the current sql statement
virtual ::rtl::OUString getStatement();
/// late construction
virtual void Construct();
virtual void initialize();
// window overloads
virtual long PreNotify( NotifyEvent& rNEvt );
virtual void GetFocus();
BOOL IsAddAllowed();
sal_Bool isSlotEnabled(sal_Int32 _nSlotId);
void setSlotEnabled(sal_Int32 _nSlotId,sal_Bool _bEnable);
void setNoneVisbleRow(sal_Int32 _nRows);
::com::sun::star::lang::Locale getLocale() const { return m_aLocale;}
::rtl::OUString getDecimalSeparator() const { return m_sDecimalSep;}
sal_Bool HasTable() const;
SqlParseError InsertField( const OTableFieldDescRef& rInfo, sal_Bool bVis=sal_True, sal_Bool bActivate = sal_True);
// save the position of the table window and the pos of the splitters
void SaveTabWinUIConfig(OQueryTableWindow* pWin);
// called when fields are deleted
void DeleteFields( const ::rtl::OUString& rAliasName );
// called when a table from tabeview was deleted
void TableDeleted(const ::rtl::OUString& rAliasName);
BOOL getColWidth( const ::rtl::OUString& rAliasName, const ::rtl::OUString& rFieldName, sal_uInt32& nWidth );
void fillValidFields(const ::rtl::OUString& strTableName, ComboBox* pFieldList);
void zoomTableView(const Fraction& _rFraction);
void SaveUIConfig();
void stopTimer();
void startTimer();
void reset();
sal_Bool InitFromParseNode();
::connectivity::OSQLParseNode* getPredicateTreeFromEntry( OTableFieldDescRef pEntry,
const String& _sCriteria,
::rtl::OUString& _rsErrorMessage,
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxColumn);
protected:
// return the Rectangle where I can paint myself
virtual void resizeDocumentView(Rectangle& rRect);
DECL_LINK( SplitHdl, void* );
};
}
#endif // DBAUI_QUERYDESIGNVIEW_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: querycontroller.hxx,v $
*
* $Revision: 1.29 $
*
* last change: $Author: pjunck $ $Date: 2004-10-22 12:06:52 $
*
* 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 DBAUI_QUERYCONTROLLER_HXX
#define DBAUI_QUERYCONTROLLER_HXX
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSER_HPP_
#include <com/sun/star/sdb/XSQLQueryComposer.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef DBAUI_QUERYVIEW_HXX
#include "queryview.hxx"
#endif
#ifndef _UNDO_HXX
#include <svtools/undo.hxx>
#endif
#ifndef _CONNECTIVITY_PARSE_SQLITERATOR_HXX_
#include <connectivity/sqliterator.hxx>
#endif
#ifndef _CONNECTIVITY_SQLPARSE_HXX
#include <connectivity/sqlparse.hxx>
#endif
#ifndef _CONNECTIVITY_SQLNODE_HXX
#include <connectivity/sqlnode.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XOBJECTOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XObjectOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOBJECTINPUTSTREAM_HPP_
#include <com/sun/star/io/XObjectInputStream.hpp>
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef SVX_QUERYDESIGNCONTEXT_HXX
#include "svx/ParseContext.hxx"
#endif
#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX
#include "querycontainerwindow.hxx"
#endif
#ifndef DBAUI_TABLEFIELDDESC_HXX
#include "TableFieldDescription.hxx"
#endif
class VCLXWindow;
namespace dbaui
{
class OQueryView;
class OQueryContainerWindow;
class OTableConnectionData;
class OTableWindowData;
class OAddTableDlg;
class OTableFieldDesc;
class OQueryTableWindow;
class OQueryController : public OJoinController
{
OTableFields m_vTableFieldDesc;
OTableFields m_vUnUsedFieldsDesc; // contains fields which aren't visible and don't have any criteria
::svxform::OSystemParseContext* m_pParseContext;
::connectivity::OSQLParser* m_pSqlParser; // to parse sql statements
::connectivity::OSQLParseTreeIterator* m_pSqlIterator; // to iterate through them
::std::vector<sal_uInt32> m_vColumnWidth;
::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSQLQueryComposer > m_xComposer;
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xFormatter; // a number formatter working with the connection's NumberFormatsSupplier
::rtl::OUString m_sStatement; // contains the sql statement
::rtl::OUString m_sUpdateCatalogName; // catalog for update data
::rtl::OUString m_sUpdateSchemaName; // schema for update data
::rtl::OUString m_sUpdateTableName; // table for update data
::rtl::OUString m_sName; // name of the query
sal_Int32 m_nVisibleRows; // which rows the selection browse should show
sal_Int32 m_nSplitPos; // the position of the splitter
sal_Bool m_bDesign; // if design is true then we show the complete design otherwise only the text format
sal_Bool m_bDistinct; // true when you want "select distinct" otherwise false
sal_Bool m_bViewAlias; // show the alias row in the design view
sal_Bool m_bViewTable; // show the table row in the design view
sal_Bool m_bViewFunction; // show the function row in the design view
sal_Bool m_bEsacpeProcessing;// is true when we shouldn't parse the statement
sal_Bool m_bCreateView; // set to true when we should create a view otherwise we create a normal query
sal_Bool m_bIndependent; // are we creating an "independent" SQL command (which does *not* belong to a data source)?
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> getElements() const;
sal_Bool askForNewName( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess>& _xElements,
sal_Bool _bSaveAs);
// creates the querycomposer
void setQueryComposer();
void deleteIterator();
void executeQuery();
void doSaveAsDoc(sal_Bool _bSaveAs);
void saveViewSettings(::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _rViewProps);
void loadViewSettings(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _rViewProps);
::rtl::OUString translateStatement( bool _bFireStatementChange = true );
protected:
// all the features which should be handled by this class
virtual void AddSupportedFeatures();
// state of a feature. 'feature' may be the handle of a ::com::sun::star::util::URL somebody requested a dispatch interface for OR a toolbar slot.
virtual FeatureState GetState(sal_uInt16 nId) const;
// execute a feature
virtual void Execute(sal_uInt16 nId, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& aArgs);
virtual void reconnect( sal_Bool _bUI );
virtual void updateTitle( );
OQueryContainerWindow* getContainer() const { return static_cast< OQueryContainerWindow* >( getView() ); }
public:
OQueryController(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM);
~OQueryController();
OTableFields& getTableFieldDesc() { return m_vTableFieldDesc; }
OTableFields& getUnUsedFields() { return m_vUnUsedFieldsDesc; }
void clearFields();
virtual void setModified(sal_Bool _bModified=sal_True);
// should the statement be parsed by our own sql parser
sal_Bool isEsacpeProcessing() const { return m_bEsacpeProcessing; }
sal_Bool isDesignMode() const { return m_bDesign; }
sal_Bool isDistinct() const { return m_bDistinct; }
::rtl::OUString getStatement() const { return m_sStatement; }
sal_Int32 getSplitPos() const { return m_nSplitPos;}
sal_Int32 getVisibleRows() const { return m_nVisibleRows; }
void setDistinct(sal_Bool _bDistinct) { m_bDistinct = _bDistinct;}
void setSplitPos(sal_Int32 _nSplitPos) { m_nSplitPos = _nSplitPos;}
void setVisibleRows(sal_Int32 _nVisibleRows) { m_nVisibleRows = _nVisibleRows;}
::connectivity::OSQLParser* getParser() { return m_pSqlParser; }
::connectivity::OSQLParseTreeIterator& getParseIterator() { return *m_pSqlIterator; }
sal_uInt32 getColWidth(sal_uInt16 _nPos) const
{
return m_vColumnWidth.size() < _nPos ? m_vColumnWidth[_nPos] : sal_uInt32(0);
}
virtual sal_Bool Construct(Window* pParent);
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > getNumberFormatter()const { return m_xFormatter; }
// XEventListener
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::lang::XComponent
virtual void SAL_CALL disposing();
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
// need by registration
static ::rtl::OUString getImplementationName_Static() throw( ::com::sun::star::uno::RuntimeException );
static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
SAL_CALL Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);
protected:
virtual void onLoadedMenu(const ::com::sun::star::uno::Reference< drafts::com::sun::star::frame::XLayoutManager >& _xLayoutManager);
virtual OTableWindowData* createTableWindowData();
virtual OJoinDesignView* getJoinView();
// ask the user if the design should be saved when it is modified
virtual short saveModified();
virtual void reset();
virtual void impl_initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments );
void resetImpl();
/// sets m_sStatement, and notifies our respective property change listeners
void setStatement_fireEvent( const ::rtl::OUString& _rNewStatement, bool _bFireStatementChange = true );
private:
DECL_LINK( OnExecuteAddTable, void* );
};
}
#endif // DBAUI_QUERYCONTROLLER_HXX
<commit_msg>INTEGRATION: CWS docking4 (1.28.8); FILE MERGED 2004/11/02 15:27:26 ssa 1.28.8.2: RESYNC: (1.28-1.29); FILE MERGED 2004/09/30 11:04:50 fs 1.28.8.1: #i33338# AddSupportedFeatures -> describeSupportedFeatures<commit_after>/*************************************************************************
*
* $RCSfile: querycontroller.hxx,v $
*
* $Revision: 1.30 $
*
* last change: $Author: obo $ $Date: 2004-11-16 14:32:12 $
*
* 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 DBAUI_QUERYCONTROLLER_HXX
#define DBAUI_QUERYCONTROLLER_HXX
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSER_HPP_
#include <com/sun/star/sdb/XSQLQueryComposer.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef DBAUI_QUERYVIEW_HXX
#include "queryview.hxx"
#endif
#ifndef _UNDO_HXX
#include <svtools/undo.hxx>
#endif
#ifndef _CONNECTIVITY_PARSE_SQLITERATOR_HXX_
#include <connectivity/sqliterator.hxx>
#endif
#ifndef _CONNECTIVITY_SQLPARSE_HXX
#include <connectivity/sqlparse.hxx>
#endif
#ifndef _CONNECTIVITY_SQLNODE_HXX
#include <connectivity/sqlnode.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XOBJECTOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XObjectOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOBJECTINPUTSTREAM_HPP_
#include <com/sun/star/io/XObjectInputStream.hpp>
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef SVX_QUERYDESIGNCONTEXT_HXX
#include "svx/ParseContext.hxx"
#endif
#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX
#include "querycontainerwindow.hxx"
#endif
#ifndef DBAUI_TABLEFIELDDESC_HXX
#include "TableFieldDescription.hxx"
#endif
class VCLXWindow;
namespace dbaui
{
class OQueryView;
class OQueryContainerWindow;
class OTableConnectionData;
class OTableWindowData;
class OAddTableDlg;
class OTableFieldDesc;
class OQueryTableWindow;
class OQueryController : public OJoinController
{
OTableFields m_vTableFieldDesc;
OTableFields m_vUnUsedFieldsDesc; // contains fields which aren't visible and don't have any criteria
::svxform::OSystemParseContext* m_pParseContext;
::connectivity::OSQLParser* m_pSqlParser; // to parse sql statements
::connectivity::OSQLParseTreeIterator* m_pSqlIterator; // to iterate through them
::std::vector<sal_uInt32> m_vColumnWidth;
::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSQLQueryComposer > m_xComposer;
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > m_xFormatter; // a number formatter working with the connection's NumberFormatsSupplier
::rtl::OUString m_sStatement; // contains the sql statement
::rtl::OUString m_sUpdateCatalogName; // catalog for update data
::rtl::OUString m_sUpdateSchemaName; // schema for update data
::rtl::OUString m_sUpdateTableName; // table for update data
::rtl::OUString m_sName; // name of the query
sal_Int32 m_nVisibleRows; // which rows the selection browse should show
sal_Int32 m_nSplitPos; // the position of the splitter
sal_Bool m_bDesign; // if design is true then we show the complete design otherwise only the text format
sal_Bool m_bDistinct; // true when you want "select distinct" otherwise false
sal_Bool m_bViewAlias; // show the alias row in the design view
sal_Bool m_bViewTable; // show the table row in the design view
sal_Bool m_bViewFunction; // show the function row in the design view
sal_Bool m_bEsacpeProcessing;// is true when we shouldn't parse the statement
sal_Bool m_bCreateView; // set to true when we should create a view otherwise we create a normal query
sal_Bool m_bIndependent; // are we creating an "independent" SQL command (which does *not* belong to a data source)?
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> getElements() const;
sal_Bool askForNewName( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess>& _xElements,
sal_Bool _bSaveAs);
// creates the querycomposer
void setQueryComposer();
void deleteIterator();
void executeQuery();
void doSaveAsDoc(sal_Bool _bSaveAs);
void saveViewSettings(::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _rViewProps);
void loadViewSettings(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _rViewProps);
::rtl::OUString translateStatement( bool _bFireStatementChange = true );
protected:
// all the features which should be handled by this class
virtual void describeSupportedFeatures();
// state of a feature. 'feature' may be the handle of a ::com::sun::star::util::URL somebody requested a dispatch interface for OR a toolbar slot.
virtual FeatureState GetState(sal_uInt16 nId) const;
// execute a feature
virtual void Execute(sal_uInt16 nId, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& aArgs);
virtual void reconnect( sal_Bool _bUI );
virtual void updateTitle( );
OQueryContainerWindow* getContainer() const { return static_cast< OQueryContainerWindow* >( getView() ); }
public:
OQueryController(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM);
~OQueryController();
OTableFields& getTableFieldDesc() { return m_vTableFieldDesc; }
OTableFields& getUnUsedFields() { return m_vUnUsedFieldsDesc; }
void clearFields();
virtual void setModified(sal_Bool _bModified=sal_True);
// should the statement be parsed by our own sql parser
sal_Bool isEsacpeProcessing() const { return m_bEsacpeProcessing; }
sal_Bool isDesignMode() const { return m_bDesign; }
sal_Bool isDistinct() const { return m_bDistinct; }
::rtl::OUString getStatement() const { return m_sStatement; }
sal_Int32 getSplitPos() const { return m_nSplitPos;}
sal_Int32 getVisibleRows() const { return m_nVisibleRows; }
void setDistinct(sal_Bool _bDistinct) { m_bDistinct = _bDistinct;}
void setSplitPos(sal_Int32 _nSplitPos) { m_nSplitPos = _nSplitPos;}
void setVisibleRows(sal_Int32 _nVisibleRows) { m_nVisibleRows = _nVisibleRows;}
::connectivity::OSQLParser* getParser() { return m_pSqlParser; }
::connectivity::OSQLParseTreeIterator& getParseIterator() { return *m_pSqlIterator; }
sal_uInt32 getColWidth(sal_uInt16 _nPos) const
{
return m_vColumnWidth.size() < _nPos ? m_vColumnWidth[_nPos] : sal_uInt32(0);
}
virtual sal_Bool Construct(Window* pParent);
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > getNumberFormatter()const { return m_xFormatter; }
// XEventListener
virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::lang::XComponent
virtual void SAL_CALL disposing();
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
// need by registration
static ::rtl::OUString getImplementationName_Static() throw( ::com::sun::star::uno::RuntimeException );
static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
SAL_CALL Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);
protected:
virtual void onLoadedMenu(const ::com::sun::star::uno::Reference< drafts::com::sun::star::frame::XLayoutManager >& _xLayoutManager);
virtual OTableWindowData* createTableWindowData();
virtual OJoinDesignView* getJoinView();
// ask the user if the design should be saved when it is modified
virtual short saveModified();
virtual void reset();
virtual void impl_initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments );
void resetImpl();
/// sets m_sStatement, and notifies our respective property change listeners
void setStatement_fireEvent( const ::rtl::OUString& _rNewStatement, bool _bFireStatementChange = true );
private:
DECL_LINK( OnExecuteAddTable, void* );
};
}
#endif // DBAUI_QUERYCONTROLLER_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: UserSettingsDlg.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2005-03-18 10:11:54 $
*
* 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 EXPRESS 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 _DBU_REGHELPER_HXX_
#include "dbu_reghelper.hxx"
#endif
#ifndef _DBAUI_USERSETTINGSDLG_HXX
#include "UserSettingsDlg.hxx"
#endif
#ifndef DBAUI_USERADMINDLG_HXX
#include "UserAdminDlg.hxx"
#endif
using namespace dbaui;
extern "C" void SAL_CALL createRegistryInfo_OUserSettingsDialog()
{
static OMultiInstanceAutoRegistration< OUserSettingsDialog > aAutoRegistration;
}
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
//=========================================================================
//-------------------------------------------------------------------------
OUserSettingsDialog::OUserSettingsDialog(const Reference< XMultiServiceFactory >& _rxORB)
:ODatabaseAdministrationDialog(_rxORB)
{
}
//-------------------------------------------------------------------------
Sequence<sal_Int8> SAL_CALL OUserSettingsDialog::getImplementationId( ) throw(RuntimeException)
{
static ::cppu::OImplementationId aId;
return aId.getImplementationId();
}
//-------------------------------------------------------------------------
Reference< XInterface > SAL_CALL OUserSettingsDialog::Create(const Reference< XMultiServiceFactory >& _rxFactory)
{
return *(new OUserSettingsDialog(_rxFactory));
}
//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL OUserSettingsDialog::getImplementationName() throw(RuntimeException)
{
return getImplementationName_Static();
}
//-------------------------------------------------------------------------
::rtl::OUString OUserSettingsDialog::getImplementationName_Static() throw(RuntimeException)
{
return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.comp.dbu.OUserSettingsDialog"));
}
//-------------------------------------------------------------------------
::comphelper::StringSequence SAL_CALL OUserSettingsDialog::getSupportedServiceNames() throw(RuntimeException)
{
return getSupportedServiceNames_Static();
}
//-------------------------------------------------------------------------
::comphelper::StringSequence OUserSettingsDialog::getSupportedServiceNames_Static() throw(RuntimeException)
{
::comphelper::StringSequence aSupported(1);
aSupported.getArray()[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.UserAdministrationDialog"));
return aSupported;
}
//-------------------------------------------------------------------------
Reference<XPropertySetInfo> SAL_CALL OUserSettingsDialog::getPropertySetInfo() throw(RuntimeException)
{
Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) );
return xInfo;
}
//-------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& OUserSettingsDialog::getInfoHelper()
{
return *const_cast<OUserSettingsDialog*>(this)->getArrayHelper();
}
//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OUserSettingsDialog::createArrayHelper( ) const
{
Sequence< Property > aProps;
describeProperties(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
//------------------------------------------------------------------------------
Dialog* OUserSettingsDialog::createDialog(Window* _pParent)
{
OUserAdminDlg* pDlg = new OUserAdminDlg(_pParent, m_pDatasourceItems, m_xORB,m_aInitialSelection,m_xActiveConnection);
return pDlg;
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.98); FILE MERGED 2005/09/05 17:35:57 rt 1.3.98.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: UserSettingsDlg.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:49:30 $
*
* 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 _DBU_REGHELPER_HXX_
#include "dbu_reghelper.hxx"
#endif
#ifndef _DBAUI_USERSETTINGSDLG_HXX
#include "UserSettingsDlg.hxx"
#endif
#ifndef DBAUI_USERADMINDLG_HXX
#include "UserAdminDlg.hxx"
#endif
using namespace dbaui;
extern "C" void SAL_CALL createRegistryInfo_OUserSettingsDialog()
{
static OMultiInstanceAutoRegistration< OUserSettingsDialog > aAutoRegistration;
}
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
//=========================================================================
//-------------------------------------------------------------------------
OUserSettingsDialog::OUserSettingsDialog(const Reference< XMultiServiceFactory >& _rxORB)
:ODatabaseAdministrationDialog(_rxORB)
{
}
//-------------------------------------------------------------------------
Sequence<sal_Int8> SAL_CALL OUserSettingsDialog::getImplementationId( ) throw(RuntimeException)
{
static ::cppu::OImplementationId aId;
return aId.getImplementationId();
}
//-------------------------------------------------------------------------
Reference< XInterface > SAL_CALL OUserSettingsDialog::Create(const Reference< XMultiServiceFactory >& _rxFactory)
{
return *(new OUserSettingsDialog(_rxFactory));
}
//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL OUserSettingsDialog::getImplementationName() throw(RuntimeException)
{
return getImplementationName_Static();
}
//-------------------------------------------------------------------------
::rtl::OUString OUserSettingsDialog::getImplementationName_Static() throw(RuntimeException)
{
return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.comp.dbu.OUserSettingsDialog"));
}
//-------------------------------------------------------------------------
::comphelper::StringSequence SAL_CALL OUserSettingsDialog::getSupportedServiceNames() throw(RuntimeException)
{
return getSupportedServiceNames_Static();
}
//-------------------------------------------------------------------------
::comphelper::StringSequence OUserSettingsDialog::getSupportedServiceNames_Static() throw(RuntimeException)
{
::comphelper::StringSequence aSupported(1);
aSupported.getArray()[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.UserAdministrationDialog"));
return aSupported;
}
//-------------------------------------------------------------------------
Reference<XPropertySetInfo> SAL_CALL OUserSettingsDialog::getPropertySetInfo() throw(RuntimeException)
{
Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) );
return xInfo;
}
//-------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& OUserSettingsDialog::getInfoHelper()
{
return *const_cast<OUserSettingsDialog*>(this)->getArrayHelper();
}
//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OUserSettingsDialog::createArrayHelper( ) const
{
Sequence< Property > aProps;
describeProperties(aProps);
return new ::cppu::OPropertyArrayHelper(aProps);
}
//------------------------------------------------------------------------------
Dialog* OUserSettingsDialog::createDialog(Window* _pParent)
{
OUserAdminDlg* pDlg = new OUserAdminDlg(_pParent, m_pDatasourceItems, m_xORB,m_aInitialSelection,m_xActiveConnection);
return pDlg;
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<|endoftext|> |
<commit_before>#define BOOST_TEST_MODULE
#include <boost/test/included/unit_test.hpp>
#include <bluetoe/sm/security_manager.hpp>
#include "test_sm.hpp"
/**
* using the example data from Core (V5), Vol 3, Part H, 2.2.3 Confirm value generation function c1 for LE Legacy Pairing
* p1 is 0x05000800000302070710000001010001
* p2 is 0x00000000A1A2A3A4A5A6B1B2B3B4B5B6
* 128-bit k is 0x00000000000000000000000000000000
* 128-bit value r is 0x5783D52156AD6F0E6388274EC6702EE0
* 128-bit output from the c1 function is 0x1e1e3fef878988ead2a74dc5bef13b86
*/
BOOST_FIXTURE_TEST_CASE( c1_test, test::security_functions )
{
const bluetoe::details::uint128_t p1{{
0x01, 0x00, 0x01, 0x01,
0x00, 0x00, 0x10, 0x07,
0x07, 0x02, 0x03, 0x00,
0x00, 0x08, 0x00, 0x05
}};
const bluetoe::details::uint128_t p2{{
0xB6, 0xB5, 0xB4, 0xB3,
0xB2, 0xB1, 0xA6, 0xA5,
0xA4, 0xA3, 0xA2, 0xA1,
0x00, 0x00, 0x00, 0x00
}};
const bluetoe::details::uint128_t k{{
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
}};
const bluetoe::details::uint128_t r{{
0xE0, 0x2E, 0x70, 0xC6,
0x4E, 0x27, 0x88, 0x63,
0x0E, 0x6F, 0xAD, 0x56,
0x21, 0xD5, 0x83, 0x57
}};
const bluetoe::details::uint128_t expected{{
0x86, 0x3b, 0xf1, 0xbe,
0xc5, 0x4d, 0xa7, 0xd2,
0xea, 0x88, 0x89, 0x87,
0xef, 0x3f, 0x1e, 0x1e
}};
const bluetoe::details::uint128_t confirm = c1( k, r, p1, p2 );
BOOST_CHECK_EQUAL_COLLECTIONS(
confirm.begin(), confirm.end(), expected.begin(), expected.end() );
}
BOOST_FIXTURE_TEST_CASE( aes_test, test::security_functions )
{
const bluetoe::details::uint128_t key{{
0x0f, 0x0e, 0x0d, 0x0c,
0x0b, 0x0a, 0x09, 0x08,
0x07, 0x06, 0x05, 0x04,
0x03, 0x02, 0x01, 0x00
}};
const bluetoe::details::uint128_t input{{
0xff, 0xee, 0xdd, 0xcc,
0xbb, 0xaa, 0x99, 0x88,
0x77, 0x66, 0x55, 0x44,
0x33, 0x22, 0x11, 0x00
}};
const bluetoe::details::uint128_t expected{{
0x5a, 0xc5, 0xb4, 0x70,
0x80, 0xb7, 0xcd, 0xd8,
0x30, 0x04, 0x7b, 0x6a,
0xd8, 0xe0, 0xc4, 0x69
}};
const bluetoe::details::uint128_t output = aes( key, input );
BOOST_CHECK_EQUAL_COLLECTIONS(
output.begin(), output.end(), expected.begin(), expected.end() );
}
BOOST_FIXTURE_TEST_CASE( xor_test, test::security_functions )
{
const bluetoe::details::uint128_t p1{{
0x01, 0x00, 0x01, 0x01,
0x00, 0x00, 0x10, 0x07,
0x07, 0x02, 0x03, 0x00,
0x00, 0x08, 0x00, 0x05
}};
const bluetoe::details::uint128_t r{{
0xE0, 0x2E, 0x70, 0xC6,
0x4E, 0x27, 0x88, 0x63,
0x0E, 0x6F, 0xAD, 0x56,
0x21, 0xD5, 0x83, 0x57
}};
const bluetoe::details::uint128_t expected{{
0xe1, 0x2e, 0x71, 0xc7,
0x4e, 0x27, 0x98, 0x64,
0x09, 0x6d, 0xae, 0x56,
0x21, 0xdd, 0x83, 0x52
}};
const bluetoe::details::uint128_t output = xor_( p1, r );
BOOST_CHECK_EQUAL_COLLECTIONS(
output.begin(), output.end(), expected.begin(), expected.end() );
}
<commit_msg>testing s1()<commit_after>#define BOOST_TEST_MODULE
#include <boost/test/included/unit_test.hpp>
#include <bluetoe/sm/security_manager.hpp>
#include "test_sm.hpp"
/**
* using the example data from Core (V5), Vol 3, Part H, 2.2.3 Confirm value generation function c1 for LE Legacy Pairing
* p1 is 0x05000800000302070710000001010001
* p2 is 0x00000000A1A2A3A4A5A6B1B2B3B4B5B6
* 128-bit k is 0x00000000000000000000000000000000
* 128-bit value r is 0x5783D52156AD6F0E6388274EC6702EE0
* 128-bit output from the c1 function is 0x1e1e3fef878988ead2a74dc5bef13b86
*/
BOOST_FIXTURE_TEST_CASE( c1_test, test::security_functions )
{
const bluetoe::details::uint128_t p1{{
0x01, 0x00, 0x01, 0x01,
0x00, 0x00, 0x10, 0x07,
0x07, 0x02, 0x03, 0x00,
0x00, 0x08, 0x00, 0x05
}};
const bluetoe::details::uint128_t p2{{
0xB6, 0xB5, 0xB4, 0xB3,
0xB2, 0xB1, 0xA6, 0xA5,
0xA4, 0xA3, 0xA2, 0xA1,
0x00, 0x00, 0x00, 0x00
}};
const bluetoe::details::uint128_t k{{
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
}};
const bluetoe::details::uint128_t r{{
0xE0, 0x2E, 0x70, 0xC6,
0x4E, 0x27, 0x88, 0x63,
0x0E, 0x6F, 0xAD, 0x56,
0x21, 0xD5, 0x83, 0x57
}};
const bluetoe::details::uint128_t expected{{
0x86, 0x3b, 0xf1, 0xbe,
0xc5, 0x4d, 0xa7, 0xd2,
0xea, 0x88, 0x89, 0x87,
0xef, 0x3f, 0x1e, 0x1e
}};
const bluetoe::details::uint128_t confirm = c1( k, r, p1, p2 );
BOOST_CHECK_EQUAL_COLLECTIONS(
confirm.begin(), confirm.end(), expected.begin(), expected.end() );
}
// For example if the 128-bit value r1 is 0x000F0E0D0C0B0A091122334455667788 then r1’ is 0x1122334455667788.
// If the 128-bit value r2 is 0x010203040506070899AABBCCDDEEFF00 then r2’ is 0x99AABBCCDDEEFF00.
// For example, if the 64-bit value r1’ is 0x1122334455667788 and r2’ is 0x99AABBCCDDEEFF00 then
// r’ is 0x112233445566778899AABBCCDDEEFF00.
// For example if the 128-bit value k is 0x00000000000000000000000000000000
// and the 128-bit value r' is 0x112233445566778899AABBCCDDEEFF00
// then the output from the key generation function s1 is 0x9a1fe1f0e8b0f49b5b4216ae796da062.
BOOST_FIXTURE_TEST_CASE( s1_test, test::security_functions )
{
static const bluetoe::details::uint128_t k = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
// r1 = 0x000F0E0D0C0B0A091122334455667788
static const bluetoe::details::uint128_t r1 = {
0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11,
0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00
};
// r2 = 0x010203040506070899AABBCCDDEEFF00
static const bluetoe::details::uint128_t r2 = {
0x00, 0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99,
0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01
};
// 0x9a1fe1f0e8b0f49b5b4216ae796da062
static const bluetoe::details::uint128_t expected = {
0x62, 0xa0, 0x6d, 0x79, 0xae, 0x16, 0x42, 0x5b,
0x9b, 0xf4, 0xb0, 0xe8, 0xf0, 0xe1, 0x1f, 0x9a
};
const bluetoe::details::uint128_t key = s1( k, r1, r2 );
BOOST_CHECK_EQUAL_COLLECTIONS(
key.begin(), key.end(), expected.begin(), expected.end() );
}
BOOST_FIXTURE_TEST_CASE( aes_test, test::security_functions )
{
const bluetoe::details::uint128_t key{{
0x0f, 0x0e, 0x0d, 0x0c,
0x0b, 0x0a, 0x09, 0x08,
0x07, 0x06, 0x05, 0x04,
0x03, 0x02, 0x01, 0x00
}};
const bluetoe::details::uint128_t input{{
0xff, 0xee, 0xdd, 0xcc,
0xbb, 0xaa, 0x99, 0x88,
0x77, 0x66, 0x55, 0x44,
0x33, 0x22, 0x11, 0x00
}};
const bluetoe::details::uint128_t expected{{
0x5a, 0xc5, 0xb4, 0x70,
0x80, 0xb7, 0xcd, 0xd8,
0x30, 0x04, 0x7b, 0x6a,
0xd8, 0xe0, 0xc4, 0x69
}};
const bluetoe::details::uint128_t output = aes( key, input );
BOOST_CHECK_EQUAL_COLLECTIONS(
output.begin(), output.end(), expected.begin(), expected.end() );
}
BOOST_FIXTURE_TEST_CASE( xor_test, test::security_functions )
{
const bluetoe::details::uint128_t p1{{
0x01, 0x00, 0x01, 0x01,
0x00, 0x00, 0x10, 0x07,
0x07, 0x02, 0x03, 0x00,
0x00, 0x08, 0x00, 0x05
}};
const bluetoe::details::uint128_t r{{
0xE0, 0x2E, 0x70, 0xC6,
0x4E, 0x27, 0x88, 0x63,
0x0E, 0x6F, 0xAD, 0x56,
0x21, 0xD5, 0x83, 0x57
}};
const bluetoe::details::uint128_t expected{{
0xe1, 0x2e, 0x71, 0xc7,
0x4e, 0x27, 0x98, 0x64,
0x09, 0x6d, 0xae, 0x56,
0x21, 0xdd, 0x83, 0x52
}};
const bluetoe::details::uint128_t output = xor_( p1, r );
BOOST_CHECK_EQUAL_COLLECTIONS(
output.begin(), output.end(), expected.begin(), expected.end() );
}
<|endoftext|> |
<commit_before>//---------------------------- sparse_decomposition.cc ---------------------------
// Copyright (C) 1998, 1999, 2000, 2001, 2002
// by the deal.II authors and Stephen "Cheffo" Kolaroff
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- sparse_decomposition.h ---------------------------
#include <lac/sparse_decomposition.templates.h>
template class SparseLUDecomposition<double>;
template void SparseLUDecomposition<double>::decompose<double> (const SparseMatrix<double> &,
const double);
template void SparseLUDecomposition<double>::decompose<float> (const SparseMatrix<float> &,
const double);
template class SparseLUDecomposition<float>;
template void SparseLUDecomposition<float>::decompose<double> (const SparseMatrix<double> &,
const double);
template void SparseLUDecomposition<float>::decompose<float> (const SparseMatrix<float> &,
const double);
<commit_msg>Add some missing explicit instantiations.<commit_after>//---------------------------- sparse_decomposition.cc ---------------------------
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
// by the deal.II authors and Stephen "Cheffo" Kolaroff
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------- sparse_decomposition.h ---------------------------
#include <lac/sparse_decomposition.templates.h>
template class SparseLUDecomposition<double>;
template void SparseLUDecomposition<double>::decompose<double> (const SparseMatrix<double> &,
const double);
template void SparseLUDecomposition<double>::decompose<float> (const SparseMatrix<float> &,
const double);
template void SparseLUDecomposition<double>::copy_from<double> (const SparseMatrix<double> &);
template void SparseLUDecomposition<double>::copy_from<float> (const SparseMatrix<float> &);
template class SparseLUDecomposition<float>;
template void SparseLUDecomposition<float>::decompose<double> (const SparseMatrix<double> &,
const double);
template void SparseLUDecomposition<float>::decompose<float> (const SparseMatrix<float> &,
const double);
template void SparseLUDecomposition<float>::copy_from<double> (const SparseMatrix<double> &);
template void SparseLUDecomposition<float>::copy_from<float> (const SparseMatrix<float> &);
<|endoftext|> |
<commit_before>#ifndef COFFEE_MILL_DCD_CONVERT
#define COFFEE_MILL_DCD_CONVERT
#include <mill/dcd/DCDReader.hpp>
#include <mill/pdb/PDBReader.hpp>
#include <mill/pdb/PDBWriter.hpp>
#include <mill/util/file_extension.hpp>
#include <toml/toml.hpp>
#include <string_view>
#include <deque>
namespace mill
{
inline const char* dcd_convert_usage() noexcept
{
return "usage: mill dcd convert <format> <dcdfile> [reference(optional)]\n"
" $ mill dcd convert pdb traj.dcd [model.pdb(optional)]\n"
" convert traj.dcd to pdb format.\n"
" without pdb file, it consider all the particles as CA.\n"
" the pdb file must have the same number of particles with snapshot in dcd.\n";
}
// argv := arrayof{ "convert", "pdb", "filename", [pdb] }
inline int mode_dcd_convert(std::deque<std::string_view> args)
{
using vector_type = DCDReader::vector_type;
if(args.size() < 2)
{
log::error("mill dcd convert: too few arguments");
log::error(dcd_convert_usage());
return 1;
}
const auto format = args.at(1);
if(format == "help")
{
log::info(dcd_convert_usage());
return 0;
}
else if(format != "pdb")
{
log::error("mill dcd convert: unknown format: ", format);
log::error(dcd_convert_usage());
return 1;
}
if(args.size() < 3)
{
log::error("mill dcd convert: too few arguments");
log::error(dcd_convert_usage());
return 1;
}
const auto fname = args.at(2);
if(extension_of(fname) == ".dcd")
{
std::optional<std::string> pdbname;
if(args.size() >= 4)
{
pdbname = std::string(args.at(3));
}
const std::string outname = std::string(base_name_of(fname)) + "_converted.pdb";
std::ofstream ofs(outname);
if(not ofs.good())
{
log::error("mill dcd convert: file open error: ", outname);
log::error(dcd_convert_usage());
return 1;
}
DCDReader reader(fname);
PDBWriter<vector_type> writer;
const auto header = reader.read_header();
const std::size_t num_particles = header.at("nparticle").as_integer();
std::vector<PDBAtom<vector_type>> atoms(num_particles);
if(pdbname) // reference pdb exists.
{
log::fatal("PDB reference option is currently unavailable");
// PDBReader<vector_type> pdbreader;
// std::ifstream pdbfile(*pdbname);
// if(not pdbfile.good())
// {
// log::error("mill dcd convert: file open error: ", *pdbname);
// log::error(dcd_convert_usage());
// return 1;
// }
// atoms = pdbreader.read(*pdbname);
// if(atoms.size() != static_cast<std::size_t>(num_particles))
// {
// log::error("mill dcd convert: file open error: "
// "pdb file may have different structure: ",
// "num particle in dcd = ", num_particles,
// "num particle in pdb = ", atoms.size());
// log::error(dcd_convert_usage());
// return 1;
// }
}
else
{
std::size_t idx = 1;
for(auto& atom : atoms)
{
atom = make_default_atom(static_cast<int>(idx), vector_type(0,0,0));
++idx;
}
}
std::size_t model = 0;
for(const auto& frame : reader)
{
++model;
ofs << "MODEL " << std::setw(4) << model << '\n';
std::size_t idx = 0;
for(const auto& p : frame)
{
atoms.at(idx).position = p.position();
++idx;
}
writer.write(ofs, atoms);
ofs << "ENDMDL\n";
}
ofs << std::flush;
ofs.close();
return 0;
}
else
{
log::error("error: mill dcd convert: unknown file extension: ", fname);
log::error(dcd_convert_usage());
return 1;
}
}
} // mill
#endif// COFFEE_MILL_DCD_CONVERT
<commit_msg>:recycle: use new PDBReader in dcd convert<commit_after>#ifndef COFFEE_MILL_DCD_CONVERT
#define COFFEE_MILL_DCD_CONVERT
#include <mill/util/file_extension.hpp>
#include <mill/traj.hpp>
#include <toml/toml.hpp>
#include <string_view>
#include <deque>
namespace mill
{
inline const char* dcd_convert_usage() noexcept
{
return "usage: mill dcd convert <format> <dcdfile> [reference(optional)]\n"
" $ mill dcd convert pdb traj.dcd [model.pdb(optional)]\n"
" convert traj.dcd to pdb format.\n"
" without pdb file, it consider all the particles as CA.\n"
" the pdb file must have the same number of particles with snapshot in dcd.\n";
}
// argv := arrayof{ "convert", "pdb", "filename", [pdb] }
inline int mode_dcd_convert(std::deque<std::string_view> args)
{
if(args.size() < 2)
{
log::error("mill dcd convert: too few arguments");
log::error(dcd_convert_usage());
return 1;
}
const auto format = args.at(1);
if(format == "help")
{
log::info(dcd_convert_usage());
return 0;
}
else if(format != "pdb")
{
log::error("mill dcd convert: unknown format: ", format);
log::error(dcd_convert_usage());
return 1;
}
if(args.size() < 3)
{
log::error("mill dcd convert: too few arguments");
log::error(dcd_convert_usage());
return 1;
}
const auto filename = args.at(2);
if(extension_of(filename) == ".dcd")
{
std::optional<Snapshot> ref_frame = std::nullopt;
if(4 <= args.size() && extension_of(args.at(3)) == ".pdb")
{
PDBReader reader(std::string(args.at(3)));
std::ignore = reader.read_header();
ref_frame = reader.read_frame(); // read 1st frame
}
auto reader = read(filename);
auto traj = reader.read();
if(ref_frame)
{
for(auto& frame : traj)
{
Snapshot pdbinfo(ref_frame.value());
frame.merge_attributes(pdbinfo);
}
}
PDBWriter writer(std::string(base_name_of(filename)) + "_converted.pdb");
writer.write(traj);
return 0;
}
else
{
log::error("error: mill dcd convert: unknown file extension: ", filename);
log::error(dcd_convert_usage());
return 1;
}
}
} // mill
#endif// COFFEE_MILL_DCD_CONVERT
<|endoftext|> |
<commit_before>/*******************************************************************************
* Copyright 2017-2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include "ngraph/builder/tensor_mask.hpp"
#include "ngraph/op/broadcast.hpp"
#include "ngraph/op/constant.hpp"
#include "ngraph/op/convert.hpp"
#include "ngraph/op/less.hpp"
#include "ngraph/op/reshape.hpp"
using namespace ngraph;
std::shared_ptr<Node> ngraph::builder::tensor_mask(const std::shared_ptr<Node>& sequence_lengths,
size_t sequence_axis,
size_t batch_axis,
Shape mask_shape)
{
if (sequence_axis >= mask_shape.size())
{
throw ngraph_error("Sequence axis must be in range 0..mask_shape rank");
}
if (batch_axis >= mask_shape.size())
{
throw ngraph_error("Sequence axis must be in range 0..mask_shape rank");
}
// all axes except the sequence axis
AxisSet non_sequence_axes;
// all axes except the batch axis
AxisSet non_batch_axes;
for (auto axis = 0; axis < mask_shape.size(); ++axis)
{
if (axis != sequence_axis)
{
non_sequence_axes.insert(axis);
}
if (axis != batch_axis)
{
non_batch_axes.insert(axis);
}
}
// broadcast sequence lengths to mask shape along all non-batch axes
auto broadcast_sequence_lengths =
std::make_shared<op::Broadcast>(sequence_lengths, mask_shape, non_batch_axes);
// create sequence data [0, ..., max_sequence_length]
auto max_sequence_length = mask_shape[sequence_axis];
std::vector<uint32_t> sequence_data(max_sequence_length);
std::iota(sequence_data.begin(), sequence_data.end(), 0);
// create sequence constant
auto sequence =
std::make_shared<op::Constant>(element::u32, Shape{max_sequence_length}, sequence_data);
// convert sequence to input type
auto convert_sequence =
std::make_shared<op::Convert>(sequence, sequence_lengths->get_element_type());
// broadcast sequence to mask shape along all non-sequence axes
auto broadcast_sequence =
std::make_shared<op::Broadcast>(convert_sequence, mask_shape, non_sequence_axes);
// mask = sequence_length < sequence
return std::make_shared<op::Less>(broadcast_sequence, broadcast_sequence_lengths);
}
<commit_msg>Missing header (#770)<commit_after>/*******************************************************************************
* Copyright 2017-2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include <numeric>
#include "ngraph/builder/tensor_mask.hpp"
#include "ngraph/op/broadcast.hpp"
#include "ngraph/op/constant.hpp"
#include "ngraph/op/convert.hpp"
#include "ngraph/op/less.hpp"
#include "ngraph/op/reshape.hpp"
using namespace ngraph;
std::shared_ptr<Node> ngraph::builder::tensor_mask(const std::shared_ptr<Node>& sequence_lengths,
size_t sequence_axis,
size_t batch_axis,
Shape mask_shape)
{
if (sequence_axis >= mask_shape.size())
{
throw ngraph_error("Sequence axis must be in range 0..mask_shape rank");
}
if (batch_axis >= mask_shape.size())
{
throw ngraph_error("Sequence axis must be in range 0..mask_shape rank");
}
// all axes except the sequence axis
AxisSet non_sequence_axes;
// all axes except the batch axis
AxisSet non_batch_axes;
for (auto axis = 0; axis < mask_shape.size(); ++axis)
{
if (axis != sequence_axis)
{
non_sequence_axes.insert(axis);
}
if (axis != batch_axis)
{
non_batch_axes.insert(axis);
}
}
// broadcast sequence lengths to mask shape along all non-batch axes
auto broadcast_sequence_lengths =
std::make_shared<op::Broadcast>(sequence_lengths, mask_shape, non_batch_axes);
// create sequence data [0, ..., max_sequence_length]
auto max_sequence_length = mask_shape[sequence_axis];
std::vector<uint32_t> sequence_data(max_sequence_length);
std::iota(sequence_data.begin(), sequence_data.end(), 0);
// create sequence constant
auto sequence =
std::make_shared<op::Constant>(element::u32, Shape{max_sequence_length}, sequence_data);
// convert sequence to input type
auto convert_sequence =
std::make_shared<op::Convert>(sequence, sequence_lengths->get_element_type());
// broadcast sequence to mask shape along all non-sequence axes
auto broadcast_sequence =
std::make_shared<op::Broadcast>(convert_sequence, mask_shape, non_sequence_axes);
// mask = sequence_length < sequence
return std::make_shared<op::Less>(broadcast_sequence, broadcast_sequence_lengths);
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// simple_optimizer.cpp
//
// Identification: /peloton/src/optimizer/simple_optimizer.cpp
//
// Copyright (c) 2016, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "optimizer/simple_optimizer.h"
#include "parser/peloton/abstract_parse.h"
#include "common/logger.h"
namespace peloton {
namespace optimizer {
SimpleOptimizer::SimpleOptimizer() {
}
;
SimpleOptimizer::~SimpleOptimizer() {
}
;
std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree(
const std::unique_ptr<parser::AbstractParse>& parse_tree) {
std::shared_ptr<planner::AbstractPlan> plan_tree;
if (parse_tree.get() == nullptr)
return plan_tree;
std::unique_ptr<planner::AbstractPlan> child_plan;
// TODO: Transform the parse tree
// One to one Mapping
auto parse_item_node_type = parse_tree->GetParseNodeType();
switch(parse_item_node_type){
case PLAN_NODE_TYPE_DROP:
child_plan = new planner::DropPlan();
break;
case PLAN_NODE_TYPE_SEQSCAN:
child_plan = new planner::SeqScanPlan();
break;
default:
LOG_INFO("Unsupported Parse Node Type");
}
// Need to recurse and give base case. for every child in parse tree.
if (child_plan != nullptr) {
if (plan_tree != nullptr)
plan_tree->AddChild(std::move(child_plan));
else
plan_tree = child_plan;
}
auto child_parse = parse_tree->children_;
for(auto child : child_parse){
BuildPlanTree(child);
}
return plan_tree;
}
} // namespace optimizer
} // namespace peloton
<commit_msg>Fix Simple mistakes - still don't build<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// simple_optimizer.cpp
//
// Identification: /peloton/src/optimizer/simple_optimizer.cpp
//
// Copyright (c) 2016, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "optimizer/simple_optimizer.h"
#include "parser/peloton/abstract_parse.h"
#include "common/logger.h"
namespace peloton {
namespace optimizer {
SimpleOptimizer::SimpleOptimizer() {
}
;
SimpleOptimizer::~SimpleOptimizer() {
}
;
std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree(
const std::unique_ptr<parser::AbstractParse>& parse_tree) {
std::shared_ptr<planner::AbstractPlan> plan_tree;
if (parse_tree.get() == nullptr)
return plan_tree;
std::unique_ptr<planner::AbstractPlan> child_plan;
// TODO: Transform the parse tree
// One to one Mapping
auto parse_item_node_type = parse_tree->GetParseNodeType();
switch(parse_item_node_type){
case PARSE_NODE_TYPE_DROP:
child_plan = new planner::DropPlan();
break;
case PARSE_NODE_TYPE_SCAN:
child_plan = new planner::SeqScanPlan();
break;
default:
LOG_INFO("Unsupported Parse Node Type");
}
// Need to recurse and give base case. for every child in parse tree.
if (child_plan != nullptr) {
if (plan_tree != nullptr)
plan_tree->AddChild(std::move(child_plan));
else
plan_tree = child_plan;
}
auto child_parse = parse_tree->GetChildren();
for(auto child : child_parse){
BuildPlanTree(child);
}
return plan_tree;
}
} // namespace optimizer
} // namespace peloton
<|endoftext|> |
<commit_before>#include "osg/LightSource"
#include "osgDB/Registry"
#include "osgDB/Input"
#include "osgDB/Output"
using namespace osg;
using namespace osgDB;
// forward declare functions to use later.
bool LightSource_readLocalData(Object& obj, Input& fr);
bool LightSource_writeLocalData(const Object& obj, Output& fw);
// register the read and write functions with the osgDB::Registry.
RegisterDotOsgWrapperProxy g_LightSourceProxy
(
new osg::LightSource,
"LightSource",
"Object Node LightSource Group",
&LightSource_readLocalData,
&LightSource_writeLocalData
);
bool LightSource_readLocalData(Object& obj, Input& fr)
{
bool iteratorAdvanced = false;
LightSource& lightsource = static_cast<LightSource&>(obj);
if (fr[0].matchWord("referenceFrame"))
{
if (fr[1].matchWord("RELATIVE_TO_ABSOLUTE") || fr[1].matchWord("ABSOLUTE"))
{
lightsource.setReferenceFrame(LightSource::ABSOLUTE_RF);
fr += 2;
iteratorAdvanced = true;
}
if (fr[1].matchWord("RELATIVE_TO_PARENTS") || fr[1].matchWord("RELATIVE"))
{
lightsource.setReferenceFrame(LightSource::RELATIVE_RF);
fr += 2;
iteratorAdvanced = true;
}
}
osg::ref_ptr<StateAttribute> sa=fr.readStateAttribute();
osg::Light* light = dynamic_cast<Light*>(sa.get());
if (light)
{
lightsource.setLight(light);
iteratorAdvanced = true;
}
return iteratorAdvanced;
}
bool LightSource_writeLocalData(const Object& obj, Output& fw)
{
const LightSource& lightsource = static_cast<const LightSource&>(obj);
fw.indent() << "referenceFrame ";
switch (lightsource.getReferenceFrame())
{
case LightSource::ABSOLUTE_RF:
fw << "ABSOLUTE\n";
break;
case LightSource::RELATIVE_RF:
default:
fw << "RELATIVE\n";
};
if (lightsource.getLight()) fw.writeObject(*lightsource.getLight());
return true;
}
<commit_msg>Changed the LightSource::setReferenceFrame() read code so that it doesn't enable the culling active flag if its was already set to false.<commit_after>#include "osg/LightSource"
#include "osgDB/Registry"
#include "osgDB/Input"
#include "osgDB/Output"
using namespace osg;
using namespace osgDB;
// forward declare functions to use later.
bool LightSource_readLocalData(Object& obj, Input& fr);
bool LightSource_writeLocalData(const Object& obj, Output& fw);
// register the read and write functions with the osgDB::Registry.
RegisterDotOsgWrapperProxy g_LightSourceProxy
(
new osg::LightSource,
"LightSource",
"Object Node LightSource Group",
&LightSource_readLocalData,
&LightSource_writeLocalData
);
bool LightSource_readLocalData(Object& obj, Input& fr)
{
bool iteratorAdvanced = false;
LightSource& lightsource = static_cast<LightSource&>(obj);
if (fr[0].matchWord("referenceFrame"))
{
bool cullingActiveBefore = lightsource.getCullingActive();
if (fr[1].matchWord("RELATIVE_TO_ABSOLUTE") || fr[1].matchWord("ABSOLUTE"))
{
lightsource.setReferenceFrame(LightSource::ABSOLUTE_RF);
fr += 2;
iteratorAdvanced = true;
}
if (fr[1].matchWord("RELATIVE_TO_PARENTS") || fr[1].matchWord("RELATIVE"))
{
lightsource.setReferenceFrame(LightSource::RELATIVE_RF);
fr += 2;
iteratorAdvanced = true;
}
// if culling wasn't before reset it to off.
if (!cullingActiveBefore && lightsource.getCullingActive())
{
lightsource.setCullingActive(cullingActiveBefore);
}
}
osg::ref_ptr<StateAttribute> sa=fr.readStateAttribute();
osg::Light* light = dynamic_cast<Light*>(sa.get());
if (light)
{
lightsource.setLight(light);
iteratorAdvanced = true;
}
return iteratorAdvanced;
}
bool LightSource_writeLocalData(const Object& obj, Output& fw)
{
const LightSource& lightsource = static_cast<const LightSource&>(obj);
fw.indent() << "referenceFrame ";
switch (lightsource.getReferenceFrame())
{
case LightSource::ABSOLUTE_RF:
fw << "ABSOLUTE\n";
break;
case LightSource::RELATIVE_RF:
default:
fw << "RELATIVE\n";
};
if (lightsource.getLight()) fw.writeObject(*lightsource.getLight());
return true;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013, David C Horton
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.
*/
namespace drachtio {
class SipDialogController ;
}
#include <boost/bind.hpp>
#include "pending-request-controller.hpp"
#include "controller.hpp"
#include "cdr.hpp"
#define CLIENT_TIMEOUT (4000)
namespace drachtio {
PendingRequest_t::PendingRequest_t(msg_t* msg, sip_t* sip, tport_t* tp ) : m_msg( msg ), m_tp(tp), m_callId(sip->sip_call_id->i_id) {
DR_LOG(log_debug) << "PendingRequest_t::PendingRequest_t" ;
generateUuid( m_transactionId ) ;
msg_ref_create( m_msg ) ;
}
PendingRequest_t::~PendingRequest_t() {
msg_destroy( m_msg ) ;
DR_LOG(log_debug) << "PendingRequest_t::~PendingRequest_t - unref'ed msg" ;
}
msg_t* PendingRequest_t::getMsg() { return m_msg ; }
sip_t* PendingRequest_t::getSipObject() { return sip_object(m_msg); }
const string& PendingRequest_t::getCallId() { return m_callId; }
const string& PendingRequest_t::getTransactionId() { return m_transactionId; }
tport_t* PendingRequest_t::getTport() { return m_tp; }
PendingRequestController::PendingRequestController( DrachtioController* pController) : m_pController(pController),
m_agent(pController->getAgent()), m_pClientController(pController->getClientController()), m_timerQueue(pController->getRoot() ) {
assert(m_agent) ;
}
PendingRequestController::~PendingRequestController() {
}
int PendingRequestController::processNewRequest( msg_t* msg, sip_t* sip, string& transactionId ) {
assert(sip->sip_request->rq_method != sip_method_invite || NULL == sip->sip_to->a_tag ) ; //new INVITEs only
client_ptr client = m_pClientController->selectClientForRequestOutsideDialog( sip->sip_request->rq_method_name ) ;
if( !client ) {
DR_LOG(log_error) << "processNewRequest - No providers available for " << sip->sip_request->rq_method_name ;
generateUuid( transactionId ) ;
return 503 ;
}
boost::shared_ptr<PendingRequest_t> p = add( msg, sip ) ;
msg_destroy( msg ) ; //our PendingRequest_t is now the holder of the message
string encodedMessage ;
EncodeStackMessage( sip, encodedMessage ) ;
SipMsgData_t meta( msg ) ;
m_pClientController->addNetTransaction( client, p->getTransactionId() ) ;
m_pClientController->getIOService().post( boost::bind(&Client::sendSipMessageToClient, client, p->getTransactionId(),
encodedMessage, meta ) ) ;
transactionId = p->getTransactionId() ;
return 0 ;
}
boost::shared_ptr<PendingRequest_t> PendingRequestController::add( msg_t* msg, sip_t* sip ) {
tport_t *tp = nta_incoming_transport(m_pController->getAgent(), NULL, msg);
tport_unref(tp) ; //because the above increments the refcount and we don't need to
boost::shared_ptr<PendingRequest_t> p = boost::make_shared<PendingRequest_t>( msg, sip, tp ) ;
DR_LOG(log_debug) << "PendingRequestController::add - tport: " << std::hex << (void*) tp <<
", Call-ID: " << p->getCallId() << ", transactionId " << p->getTransactionId() ;
// give client 4 seconds to respond before clearing state
TimerEventHandle handle = m_timerQueue.add( boost::bind(&PendingRequestController::timeout, shared_from_this(), p->getTransactionId()), NULL, CLIENT_TIMEOUT ) ;
p->setTimerHandle( handle ) ;
boost::lock_guard<boost::mutex> lock(m_mutex) ;
m_mapCallId2Invite.insert( mapCallId2Invite::value_type(p->getCallId(), p) ) ;
m_mapTxnId2Invite.insert( mapTxnId2Invite::value_type(p->getTransactionId(), p) ) ;
return p ;
}
boost::shared_ptr<PendingRequest_t> PendingRequestController::findAndRemove( const string& transactionId, bool timeout ) {
boost::shared_ptr<PendingRequest_t> p ;
boost::lock_guard<boost::mutex> lock(m_mutex) ;
mapTxnId2Invite::iterator it = m_mapTxnId2Invite.find( transactionId ) ;
if( it != m_mapTxnId2Invite.end() ) {
p = it->second ;
m_mapTxnId2Invite.erase( it ) ;
mapCallId2Invite::iterator it2 = m_mapCallId2Invite.find( p->getCallId() ) ;
assert( it2 != m_mapCallId2Invite.end()) ;
m_mapCallId2Invite.erase( it2 ) ;
if( !timeout ) {
m_timerQueue.remove( p->getTimerHandle() ) ;
}
}
return p ;
}
void PendingRequestController::timeout(const string& transactionId) {
DR_LOG(log_debug) << "PendingRequestController::timeout: giving up on transactionId " << transactionId ;
this->findAndRemove( transactionId, true ) ;
}
void PendingRequestController::logStorageCount(void) {
boost::lock_guard<boost::mutex> lock(m_mutex) ;
DR_LOG(log_debug) << "PendingRequestController storage counts" ;
DR_LOG(log_debug) << "----------------------------------" ;
DR_LOG(log_debug) << "m_mapCallId2Invite size: " << m_mapCallId2Invite.size() ;
DR_LOG(log_debug) << "m_mapTxnId2Invite size: " << m_mapTxnId2Invite.size() ;
}
} ;
<commit_msg>remove client controller net transaction when timing out a pending request<commit_after>/*
Copyright (c) 2013, David C Horton
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.
*/
namespace drachtio {
class SipDialogController ;
}
#include <boost/bind.hpp>
#include "pending-request-controller.hpp"
#include "controller.hpp"
#include "cdr.hpp"
#define CLIENT_TIMEOUT (4000)
namespace drachtio {
PendingRequest_t::PendingRequest_t(msg_t* msg, sip_t* sip, tport_t* tp ) : m_msg( msg ), m_tp(tp), m_callId(sip->sip_call_id->i_id) {
DR_LOG(log_debug) << "PendingRequest_t::PendingRequest_t" ;
generateUuid( m_transactionId ) ;
msg_ref_create( m_msg ) ;
}
PendingRequest_t::~PendingRequest_t() {
msg_destroy( m_msg ) ;
DR_LOG(log_debug) << "PendingRequest_t::~PendingRequest_t - unref'ed msg" ;
}
msg_t* PendingRequest_t::getMsg() { return m_msg ; }
sip_t* PendingRequest_t::getSipObject() { return sip_object(m_msg); }
const string& PendingRequest_t::getCallId() { return m_callId; }
const string& PendingRequest_t::getTransactionId() { return m_transactionId; }
tport_t* PendingRequest_t::getTport() { return m_tp; }
PendingRequestController::PendingRequestController( DrachtioController* pController) : m_pController(pController),
m_agent(pController->getAgent()), m_pClientController(pController->getClientController()), m_timerQueue(pController->getRoot() ) {
assert(m_agent) ;
}
PendingRequestController::~PendingRequestController() {
}
int PendingRequestController::processNewRequest( msg_t* msg, sip_t* sip, string& transactionId ) {
assert(sip->sip_request->rq_method != sip_method_invite || NULL == sip->sip_to->a_tag ) ; //new INVITEs only
client_ptr client = m_pClientController->selectClientForRequestOutsideDialog( sip->sip_request->rq_method_name ) ;
if( !client ) {
DR_LOG(log_error) << "processNewRequest - No providers available for " << sip->sip_request->rq_method_name ;
generateUuid( transactionId ) ;
return 503 ;
}
boost::shared_ptr<PendingRequest_t> p = add( msg, sip ) ;
msg_destroy( msg ) ; //our PendingRequest_t is now the holder of the message
string encodedMessage ;
EncodeStackMessage( sip, encodedMessage ) ;
SipMsgData_t meta( msg ) ;
m_pClientController->addNetTransaction( client, p->getTransactionId() ) ;
m_pClientController->getIOService().post( boost::bind(&Client::sendSipMessageToClient, client, p->getTransactionId(),
encodedMessage, meta ) ) ;
transactionId = p->getTransactionId() ;
return 0 ;
}
boost::shared_ptr<PendingRequest_t> PendingRequestController::add( msg_t* msg, sip_t* sip ) {
tport_t *tp = nta_incoming_transport(m_pController->getAgent(), NULL, msg);
tport_unref(tp) ; //because the above increments the refcount and we don't need to
boost::shared_ptr<PendingRequest_t> p = boost::make_shared<PendingRequest_t>( msg, sip, tp ) ;
DR_LOG(log_debug) << "PendingRequestController::add - tport: " << std::hex << (void*) tp <<
", Call-ID: " << p->getCallId() << ", transactionId " << p->getTransactionId() ;
// give client 4 seconds to respond before clearing state
TimerEventHandle handle = m_timerQueue.add( boost::bind(&PendingRequestController::timeout, shared_from_this(), p->getTransactionId()), NULL, CLIENT_TIMEOUT ) ;
p->setTimerHandle( handle ) ;
boost::lock_guard<boost::mutex> lock(m_mutex) ;
m_mapCallId2Invite.insert( mapCallId2Invite::value_type(p->getCallId(), p) ) ;
m_mapTxnId2Invite.insert( mapTxnId2Invite::value_type(p->getTransactionId(), p) ) ;
return p ;
}
boost::shared_ptr<PendingRequest_t> PendingRequestController::findAndRemove( const string& transactionId, bool timeout ) {
boost::shared_ptr<PendingRequest_t> p ;
boost::lock_guard<boost::mutex> lock(m_mutex) ;
mapTxnId2Invite::iterator it = m_mapTxnId2Invite.find( transactionId ) ;
if( it != m_mapTxnId2Invite.end() ) {
p = it->second ;
m_mapTxnId2Invite.erase( it ) ;
mapCallId2Invite::iterator it2 = m_mapCallId2Invite.find( p->getCallId() ) ;
assert( it2 != m_mapCallId2Invite.end()) ;
m_mapCallId2Invite.erase( it2 ) ;
if( !timeout ) {
m_timerQueue.remove( p->getTimerHandle() ) ;
}
}
return p ;
}
void PendingRequestController::timeout(const string& transactionId) {
DR_LOG(log_debug) << "PendingRequestController::timeout: giving up on transactionId " << transactionId ;
this->findAndRemove( transactionId, true ) ;
m_pClientController->removeNetTransaction( transactionId ) ;
}
void PendingRequestController::logStorageCount(void) {
boost::lock_guard<boost::mutex> lock(m_mutex) ;
DR_LOG(log_debug) << "PendingRequestController storage counts" ;
DR_LOG(log_debug) << "----------------------------------" ;
DR_LOG(log_debug) << "m_mapCallId2Invite size: " << m_mapCallId2Invite.size() ;
DR_LOG(log_debug) << "m_mapTxnId2Invite size: " << m_mapTxnId2Invite.size() ;
}
} ;
<|endoftext|> |
<commit_before>/*
* Listener on a TCP port.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "ServerSocket.hxx"
#include "SocketDescriptor.hxx"
#include "SocketAddress.hxx"
#include "StaticSocketAddress.hxx"
#include "fd_util.h"
#include "pool.hxx"
#include "util/Error.hxx"
#include <socket/util.h>
#include <socket/address.h>
#include <assert.h>
#include <stddef.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
static bool
IsTCP(SocketAddress address)
{
return address.GetFamily() == AF_INET || address.GetFamily() == AF_INET6;
}
inline void
ServerSocket::Callback()
{
StaticSocketAddress remote_address;
Error error;
auto remote_fd = fd.Accept(remote_address, error);
if (!remote_fd.IsDefined()) {
if (!error.IsDomain(errno_domain) ||
(error.GetCode() != EAGAIN && error.GetCode() != EWOULDBLOCK))
OnAcceptError(std::move(error));
return;
}
if (IsTCP(remote_address) &&
!socket_set_nodelay(remote_fd.Get(), true)) {
error.SetErrno("setsockopt(TCP_NODELAY) failed");
OnAcceptError(std::move(error));
return;
}
OnAccept(std::move(remote_fd), remote_address);
}
void
ServerSocket::Callback(gcc_unused int fd, gcc_unused short event, void *ctx)
{
ServerSocket &ss = *(ServerSocket *)ctx;
ss.Callback();
pool_commit();
}
bool
ServerSocket::Listen(int family, int socktype, int protocol,
SocketAddress address,
Error &error)
{
if (address.GetFamily() == AF_UNIX) {
const struct sockaddr_un *sun = (const struct sockaddr_un *)address.GetAddress();
if (sun->sun_path[0] != '\0')
/* delete non-abstract socket files before reusing them */
unlink(sun->sun_path);
}
if (!fd.CreateListen(family, socktype, protocol, address, error))
return nullptr;
event_set(&event, fd.Get(), EV_READ|EV_PERSIST, Callback, this);
AddEvent();
return true;
}
bool
ServerSocket::ListenTCP(unsigned port, Error &error)
{
assert(port > 0);
struct sockaddr_in6 sa6;
struct sockaddr_in sa4;
memset(&sa6, 0, sizeof(sa6));
sa6.sin6_family = AF_INET6;
sa6.sin6_addr = in6addr_any;
sa6.sin6_port = htons(port);
memset(&sa4, 0, sizeof(sa4));
sa4.sin_family = AF_INET;
sa4.sin_addr.s_addr = INADDR_ANY;
sa4.sin_port = htons(port);
return Listen(PF_INET6, SOCK_STREAM, 0,
SocketAddress((const struct sockaddr *)&sa6, sizeof(sa6)),
IgnoreError()) ||
Listen(PF_INET, SOCK_STREAM, 0,
SocketAddress((const struct sockaddr *)&sa4, sizeof(sa4)),
error);
}
bool
ServerSocket::ListenPath(const char *path, Error &error)
{
StaticSocketAddress address;
address.SetLocal(path);
return Listen(AF_LOCAL, SOCK_STREAM, 0, address, error);
}
ServerSocket::~ServerSocket()
{
event_del(&event);
}
<commit_msg>net/ServerSocket: fix bool return value<commit_after>/*
* Listener on a TCP port.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "ServerSocket.hxx"
#include "SocketDescriptor.hxx"
#include "SocketAddress.hxx"
#include "StaticSocketAddress.hxx"
#include "fd_util.h"
#include "pool.hxx"
#include "util/Error.hxx"
#include <socket/util.h>
#include <socket/address.h>
#include <assert.h>
#include <stddef.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
static bool
IsTCP(SocketAddress address)
{
return address.GetFamily() == AF_INET || address.GetFamily() == AF_INET6;
}
inline void
ServerSocket::Callback()
{
StaticSocketAddress remote_address;
Error error;
auto remote_fd = fd.Accept(remote_address, error);
if (!remote_fd.IsDefined()) {
if (!error.IsDomain(errno_domain) ||
(error.GetCode() != EAGAIN && error.GetCode() != EWOULDBLOCK))
OnAcceptError(std::move(error));
return;
}
if (IsTCP(remote_address) &&
!socket_set_nodelay(remote_fd.Get(), true)) {
error.SetErrno("setsockopt(TCP_NODELAY) failed");
OnAcceptError(std::move(error));
return;
}
OnAccept(std::move(remote_fd), remote_address);
}
void
ServerSocket::Callback(gcc_unused int fd, gcc_unused short event, void *ctx)
{
ServerSocket &ss = *(ServerSocket *)ctx;
ss.Callback();
pool_commit();
}
bool
ServerSocket::Listen(int family, int socktype, int protocol,
SocketAddress address,
Error &error)
{
if (address.GetFamily() == AF_UNIX) {
const struct sockaddr_un *sun = (const struct sockaddr_un *)address.GetAddress();
if (sun->sun_path[0] != '\0')
/* delete non-abstract socket files before reusing them */
unlink(sun->sun_path);
}
if (!fd.CreateListen(family, socktype, protocol, address, error))
return false;
event_set(&event, fd.Get(), EV_READ|EV_PERSIST, Callback, this);
AddEvent();
return true;
}
bool
ServerSocket::ListenTCP(unsigned port, Error &error)
{
assert(port > 0);
struct sockaddr_in6 sa6;
struct sockaddr_in sa4;
memset(&sa6, 0, sizeof(sa6));
sa6.sin6_family = AF_INET6;
sa6.sin6_addr = in6addr_any;
sa6.sin6_port = htons(port);
memset(&sa4, 0, sizeof(sa4));
sa4.sin_family = AF_INET;
sa4.sin_addr.s_addr = INADDR_ANY;
sa4.sin_port = htons(port);
return Listen(PF_INET6, SOCK_STREAM, 0,
SocketAddress((const struct sockaddr *)&sa6, sizeof(sa6)),
IgnoreError()) ||
Listen(PF_INET, SOCK_STREAM, 0,
SocketAddress((const struct sockaddr *)&sa4, sizeof(sa4)),
error);
}
bool
ServerSocket::ListenPath(const char *path, Error &error)
{
StaticSocketAddress address;
address.SetLocal(path);
return Listen(AF_LOCAL, SOCK_STREAM, 0, address, error);
}
ServerSocket::~ServerSocket()
{
event_del(&event);
}
<|endoftext|> |
<commit_before>
#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <node_object_wrap.h>
#include "speex/speex_jitter.h"
#include "common.h"
#include <nan.h>
#include <string.h>
using namespace node;
using namespace v8;
class NodeJitterBuffer : public ObjectWrap {
private:
JitterBuffer* jitterBuffer;
protected:
public:
NodeJitterBuffer( int step_size ) {
jitterBuffer = jitter_buffer_init( step_size );
}
~NodeJitterBuffer() {
fprintf( stderr, "\nDestroyer\n\n" );
if( jitterBuffer != NULL ) {
jitter_buffer_destroy( jitterBuffer );
jitterBuffer = NULL;
}
}
static NAN_METHOD(Put) {
REQ_OBJ_ARG( 0, packet );
Local<Object> data = Local<Object>::Cast(
packet->Get( Nan::New( "data" ).ToLocalChecked() ) );
int timestamp = packet->Get( Nan::New( "timestamp" ).ToLocalChecked() )->Int32Value();
int span = packet->Get( Nan::New( "span" ).ToLocalChecked() )->Int32Value();
int sequence = packet->Get( Nan::New( "sequence" ).ToLocalChecked() )->Int32Value();
// Userdata is optional.
int userData = 0;
Handle<Value> userDataHandle = packet->Get( Nan::New( "userData" ).ToLocalChecked() );
if( !userDataHandle.IsEmpty() ) {
userData = userDataHandle->Int32Value();
}
JitterBufferPacket speexPacket;
speexPacket.data = Buffer::Data( data );
speexPacket.len = Buffer::Length( data );
speexPacket.timestamp = timestamp;
speexPacket.span = span;
speexPacket.sequence = sequence;
speexPacket.user_data = userData;
// Put copies the data so it's okay to pass a reference to a local variable.
NodeJitterBuffer* self = ObjectWrap::Unwrap<NodeJitterBuffer>( info.This() );
jitter_buffer_put( self->jitterBuffer, &speexPacket );
}
static NAN_METHOD(Get) {
REQ_INT_ARG( 0, desiredSpan );
char data[4096];
JitterBufferPacket jitterPacket;
jitterPacket.data = data;
jitterPacket.len = 4096;
spx_int32_t start_offset = 0;
NodeJitterBuffer* self = ObjectWrap::Unwrap<NodeJitterBuffer>( info.This() );
int returnValue = jitter_buffer_get( self->jitterBuffer, &jitterPacket, desiredSpan, &start_offset );
if( returnValue == JITTER_BUFFER_OK ) {
CREATE_BUFFER( data, jitterPacket.data, jitterPacket.len );
Local<Object> packet = Nan::New<Object>();
packet->Set( Nan::New( "data" ).ToLocalChecked(), data );
packet->Set( Nan::New( "timestamp" ).ToLocalChecked(), Nan::New<Number>( jitterPacket.timestamp ) );
packet->Set( Nan::New( "span" ).ToLocalChecked(), Nan::New<Number>( jitterPacket.span ) );
packet->Set( Nan::New( "sequence" ).ToLocalChecked(), Nan::New<Number>( jitterPacket.sequence ) );
packet->Set( Nan::New( "userData" ).ToLocalChecked(), Nan::New<Number>( jitterPacket.user_data ) );
info.GetReturnValue().Set( packet );
} else {
info.GetReturnValue().Set( Nan::New<Number>( returnValue ) );
}
}
static NAN_METHOD(Tick) {
NodeJitterBuffer* self = ObjectWrap::Unwrap<NodeJitterBuffer>( info.This() );
jitter_buffer_tick( self->jitterBuffer );
}
static NAN_METHOD(GetMargin) {
NodeJitterBuffer* self = ObjectWrap::Unwrap<NodeJitterBuffer>( info.This() );
int margin;
jitter_buffer_ctl( self->jitterBuffer, JITTER_BUFFER_GET_MARGIN, &margin );
info.GetReturnValue().Set( Nan::New<Number>( margin ) );
}
static NAN_METHOD(SetMargin) {
REQ_INT_ARG( 0, margin );
NodeJitterBuffer* self = ObjectWrap::Unwrap<NodeJitterBuffer>( info.This() );
jitter_buffer_ctl( self->jitterBuffer, JITTER_BUFFER_SET_MARGIN, &margin );
info.GetReturnValue().Set( Nan::New<Number>( margin ) );
}
static NAN_METHOD(New) {
if( !info.IsConstructCall()) {
return Nan::ThrowTypeError("Use the new operator to construct the NodeJitterBuffer.");
}
OPT_INT_ARG(0, stepSize, 10);
NodeJitterBuffer* encoder = new NodeJitterBuffer( stepSize );
encoder->Wrap( info.This() );
info.GetReturnValue().Set( info.This() );
}
static void Init(Handle<Object> exports) {
Nan::HandleScope scope;
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
tpl->SetClassName(Nan::New("JitterBuffer").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod( tpl, "put", Put );
Nan::SetPrototypeMethod( tpl, "get", Get );
Nan::SetPrototypeMethod( tpl, "tick", Tick );
Nan::SetPrototypeMethod( tpl, "setMargin", SetMargin );
Nan::SetPrototypeMethod( tpl, "getMargin", GetMargin );
exports->Set(
Nan::New("JitterBuffer").ToLocalChecked(),
tpl->GetFunction());
}
};
void NodeInit(Handle<Object> exports) {
NodeJitterBuffer::Init( exports );
}
NODE_MODULE(node_jitterbuffer, NodeInit)
<commit_msg>Remove debug output from destructor<commit_after>
#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <node_object_wrap.h>
#include "speex/speex_jitter.h"
#include "common.h"
#include <nan.h>
#include <string.h>
using namespace node;
using namespace v8;
class NodeJitterBuffer : public ObjectWrap {
private:
JitterBuffer* jitterBuffer;
protected:
public:
NodeJitterBuffer( int step_size ) {
jitterBuffer = jitter_buffer_init( step_size );
}
~NodeJitterBuffer() {
if( jitterBuffer != NULL ) {
jitter_buffer_destroy( jitterBuffer );
jitterBuffer = NULL;
}
}
static NAN_METHOD(Put) {
REQ_OBJ_ARG( 0, packet );
Local<Object> data = Local<Object>::Cast(
packet->Get( Nan::New( "data" ).ToLocalChecked() ) );
int timestamp = packet->Get( Nan::New( "timestamp" ).ToLocalChecked() )->Int32Value();
int span = packet->Get( Nan::New( "span" ).ToLocalChecked() )->Int32Value();
int sequence = packet->Get( Nan::New( "sequence" ).ToLocalChecked() )->Int32Value();
// Userdata is optional.
int userData = 0;
Handle<Value> userDataHandle = packet->Get( Nan::New( "userData" ).ToLocalChecked() );
if( !userDataHandle.IsEmpty() ) {
userData = userDataHandle->Int32Value();
}
JitterBufferPacket speexPacket;
speexPacket.data = Buffer::Data( data );
speexPacket.len = Buffer::Length( data );
speexPacket.timestamp = timestamp;
speexPacket.span = span;
speexPacket.sequence = sequence;
speexPacket.user_data = userData;
// Put copies the data so it's okay to pass a reference to a local variable.
NodeJitterBuffer* self = ObjectWrap::Unwrap<NodeJitterBuffer>( info.This() );
jitter_buffer_put( self->jitterBuffer, &speexPacket );
}
static NAN_METHOD(Get) {
REQ_INT_ARG( 0, desiredSpan );
char data[4096];
JitterBufferPacket jitterPacket;
jitterPacket.data = data;
jitterPacket.len = 4096;
spx_int32_t start_offset = 0;
NodeJitterBuffer* self = ObjectWrap::Unwrap<NodeJitterBuffer>( info.This() );
int returnValue = jitter_buffer_get( self->jitterBuffer, &jitterPacket, desiredSpan, &start_offset );
if( returnValue == JITTER_BUFFER_OK ) {
CREATE_BUFFER( data, jitterPacket.data, jitterPacket.len );
Local<Object> packet = Nan::New<Object>();
packet->Set( Nan::New( "data" ).ToLocalChecked(), data );
packet->Set( Nan::New( "timestamp" ).ToLocalChecked(), Nan::New<Number>( jitterPacket.timestamp ) );
packet->Set( Nan::New( "span" ).ToLocalChecked(), Nan::New<Number>( jitterPacket.span ) );
packet->Set( Nan::New( "sequence" ).ToLocalChecked(), Nan::New<Number>( jitterPacket.sequence ) );
packet->Set( Nan::New( "userData" ).ToLocalChecked(), Nan::New<Number>( jitterPacket.user_data ) );
info.GetReturnValue().Set( packet );
} else {
info.GetReturnValue().Set( Nan::New<Number>( returnValue ) );
}
}
static NAN_METHOD(Tick) {
NodeJitterBuffer* self = ObjectWrap::Unwrap<NodeJitterBuffer>( info.This() );
jitter_buffer_tick( self->jitterBuffer );
}
static NAN_METHOD(GetMargin) {
NodeJitterBuffer* self = ObjectWrap::Unwrap<NodeJitterBuffer>( info.This() );
int margin;
jitter_buffer_ctl( self->jitterBuffer, JITTER_BUFFER_GET_MARGIN, &margin );
info.GetReturnValue().Set( Nan::New<Number>( margin ) );
}
static NAN_METHOD(SetMargin) {
REQ_INT_ARG( 0, margin );
NodeJitterBuffer* self = ObjectWrap::Unwrap<NodeJitterBuffer>( info.This() );
jitter_buffer_ctl( self->jitterBuffer, JITTER_BUFFER_SET_MARGIN, &margin );
info.GetReturnValue().Set( Nan::New<Number>( margin ) );
}
static NAN_METHOD(New) {
if( !info.IsConstructCall()) {
return Nan::ThrowTypeError("Use the new operator to construct the NodeJitterBuffer.");
}
OPT_INT_ARG(0, stepSize, 10);
NodeJitterBuffer* encoder = new NodeJitterBuffer( stepSize );
encoder->Wrap( info.This() );
info.GetReturnValue().Set( info.This() );
}
static void Init(Handle<Object> exports) {
Nan::HandleScope scope;
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
tpl->SetClassName(Nan::New("JitterBuffer").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod( tpl, "put", Put );
Nan::SetPrototypeMethod( tpl, "get", Get );
Nan::SetPrototypeMethod( tpl, "tick", Tick );
Nan::SetPrototypeMethod( tpl, "setMargin", SetMargin );
Nan::SetPrototypeMethod( tpl, "getMargin", GetMargin );
exports->Set(
Nan::New("JitterBuffer").ToLocalChecked(),
tpl->GetFunction());
}
};
void NodeInit(Handle<Object> exports) {
NodeJitterBuffer::Init( exports );
}
NODE_MODULE(node_jitterbuffer, NodeInit)
<|endoftext|> |
<commit_before>/**
** \file object/call-class.cc
** \brief Creation of the URBI object call.
*/
#include <boost/numeric/conversion/converter.hpp>
#include <libport/foreach.hh>
#include <libport/ufloat.hh>
#include "object/call-class.hh"
#include "object/alien.hh"
#include "object/atom.hh"
#include "object/object.hh"
#include "runner/runner.hh"
namespace object
{
rObject call_class;
/*------------------.
| Call primitives. |
`------------------*/
static const ast::exps_type&
args_get (const rObject& self)
{
const rObject& alien_args = self->slot_get (libport::Symbol ("args"));
return unbox (const ast::exps_type&, alien_args);
}
static rObject
context_get (const rObject& self)
{
return self->slot_get (libport::Symbol ("context"));
}
static rObject
call_class_evalArgAt (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (2);
FETCH_ARG (1, Float);
const rObject& scope = context_get (args[0]);
const ast::exps_type& func_args = args_get (args[0]);
int n;
try {
n = libport::ufloat_to_int (arg1->value_get ());
}
catch (boost::numeric::bad_numeric_cast& e)
{
throw BadInteger (arg1->value_get (), __PRETTY_FUNCTION__);
}
if (n < 0 || n >= static_cast<int>(func_args.size ()))
throw PrimitiveError (__PRETTY_FUNCTION__,
(boost::format ("bad argument %1%") % n) .str ());
ast::exps_type::const_iterator i = func_args.begin();
advance (i, n);
return r.eval_in_scope (scope, **i);
}
static rObject
call_class_evalArgs (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (1);
const rObject& scope = context_get (args[0]);
const ast::exps_type& func_args = args_get (args[0]);
std::list<rObject> res;
foreach (ast::Exp* exp, func_args)
res.push_back (r.eval_in_scope (scope, *exp));
return new List (res);
}
static rObject
call_class_argsCount (runner::Runner&, objects_type args)
{
CHECK_ARG_COUNT (1);
return new Float (args_get (args[0]) .size ());
}
void
call_class_initialize ()
{
#define DECLARE(Name) \
call_class->slot_set (#Name, \
new Primitive(call_class_ ## Name));
DECLARE (evalArgAt);
DECLARE (evalArgs);
DECLARE (argsCount);
#undef DECLARE
}
}; // namespace object
<commit_msg>Do not try to evaluate self as it is not an expression<commit_after>/**
** \file object/call-class.cc
** \brief Creation of the URBI object call.
*/
#include <boost/numeric/conversion/converter.hpp>
#include <libport/foreach.hh>
#include <libport/ufloat.hh>
#include "object/call-class.hh"
#include "object/alien.hh"
#include "object/atom.hh"
#include "object/object.hh"
#include "runner/runner.hh"
namespace object
{
rObject call_class;
/*------------------.
| Call primitives. |
`------------------*/
static const ast::exps_type&
args_get (const rObject& self)
{
const rObject& alien_args = self->slot_get (libport::Symbol ("args"));
return unbox (const ast::exps_type&, alien_args);
}
static rObject
context_get (const rObject& self)
{
return self->slot_get (libport::Symbol ("context"));
}
static rObject
call_class_evalArgAt (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (2);
FETCH_ARG (1, Float);
const rObject& scope = context_get (args[0]);
const ast::exps_type& func_args = args_get (args[0]);
int n;
try {
n = libport::ufloat_to_int (arg1->value_get ());
}
catch (boost::numeric::bad_numeric_cast& e)
{
throw BadInteger (arg1->value_get (), __PRETTY_FUNCTION__);
}
if (n < 0 || n >= static_cast<int>(func_args.size ()))
throw PrimitiveError (__PRETTY_FUNCTION__,
(boost::format ("bad argument %1%") % n) .str ());
ast::exps_type::const_iterator i = func_args.begin();
advance (i, n);
return r.eval_in_scope (scope, **i);
}
static rObject
call_class_evalArgs (runner::Runner& r, objects_type args)
{
CHECK_ARG_COUNT (1);
const rObject& scope = context_get (args[0]);
const ast::exps_type& func_args = args_get (args[0]);
std::list<rObject> res;
ast::exps_type::const_iterator i = func_args.begin();
++i;
ast::exps_type::const_iterator i_end = func_args.end();
for (; i != i_end; ++i)
res.push_back (r.eval_in_scope (scope, **i));
return new List (res);
}
static rObject
call_class_argsCount (runner::Runner&, objects_type args)
{
CHECK_ARG_COUNT (1);
return new Float (args_get (args[0]) .size ());
}
void
call_class_initialize ()
{
#define DECLARE(Name) \
call_class->slot_set (#Name, \
new Primitive(call_class_ ## Name));
DECLARE (evalArgAt);
DECLARE (evalArgs);
DECLARE (argsCount);
#undef DECLARE
}
}; // namespace object
<|endoftext|> |
<commit_before>/**
* @file
* @brief Implementation of object with digitized pixel hit
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "PixelHit.hpp"
#include <set>
#include "DepositedCharge.hpp"
#include "PropagatedCharge.hpp"
#include "exceptions.h"
using namespace allpix;
PixelHit::PixelHit(Pixel pixel, double time, double signal, const PixelCharge* pixel_charge)
: pixel_(std::move(pixel)), time_(time), signal_(signal) {
pixel_charge_ = const_cast<PixelCharge*>(pixel_charge); // NOLINT
// Get the unique set of MC particles
std::set<const MCParticle*> unique_particles;
for(auto mc_particle : pixel_charge->getMCParticles()) {
unique_particles.insert(mc_particle);
}
// Store the MC particle references
for(auto mc_particle : unique_particles) {
mc_particles_.push_back(const_cast<MCParticle*>(mc_particle)); // NOLINT
}
}
const Pixel& PixelHit::getPixel() const {
return pixel_;
}
Pixel::Index PixelHit::getIndex() const {
return getPixel().getIndex();
}
/**
* @throws MissingReferenceException If the pointed object is not in scope
*
* Object is stored as TRef and can only be accessed if pointed object is in scope
*/
const PixelCharge* PixelHit::getPixelCharge() const {
auto pixel_charge = dynamic_cast<PixelCharge*>(pixel_charge_.GetObject());
if(pixel_charge == nullptr) {
throw MissingReferenceException(typeid(*this), typeid(PixelCharge));
}
return pixel_charge;
}
/**
* @throws MissingReferenceException If the pointed object is not in scope
*
* MCParticles can only be fetched if the full history of objects are in scope and stored
*/
std::vector<const MCParticle*> PixelHit::getMCParticles() const {
std::vector<const MCParticle*> mc_particles;
for(auto mc_particle : mc_particles_) {
if(mc_particle == nullptr) {
throw MissingReferenceException(typeid(*this), typeid(MCParticle));
}
mc_particles.emplace_back(dynamic_cast<MCParticle*>(mc_particle.GetObject()));
}
// Return as a vector of mc particles
return mc_particles;
}
ClassImp(PixelHit)
<commit_msg>change auto iterator ref<commit_after>/**
* @file
* @brief Implementation of object with digitized pixel hit
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "PixelHit.hpp"
#include <set>
#include "DepositedCharge.hpp"
#include "PropagatedCharge.hpp"
#include "exceptions.h"
using namespace allpix;
PixelHit::PixelHit(Pixel pixel, double time, double signal, const PixelCharge* pixel_charge)
: pixel_(std::move(pixel)), time_(time), signal_(signal) {
pixel_charge_ = const_cast<PixelCharge*>(pixel_charge); // NOLINT
// Get the unique set of MC particles
std::set<const MCParticle*> unique_particles;
for(auto mc_particle : pixel_charge->getMCParticles()) {
unique_particles.insert(mc_particle);
}
// Store the MC particle references
for(auto mc_particle : unique_particles) {
mc_particles_.push_back(const_cast<MCParticle*>(mc_particle)); // NOLINT
}
}
const Pixel& PixelHit::getPixel() const {
return pixel_;
}
Pixel::Index PixelHit::getIndex() const {
return getPixel().getIndex();
}
/**
* @throws MissingReferenceException If the pointed object is not in scope
*
* Object is stored as TRef and can only be accessed if pointed object is in scope
*/
const PixelCharge* PixelHit::getPixelCharge() const {
auto pixel_charge = dynamic_cast<PixelCharge*>(pixel_charge_.GetObject());
if(pixel_charge == nullptr) {
throw MissingReferenceException(typeid(*this), typeid(PixelCharge));
}
return pixel_charge;
}
/**
* @throws MissingReferenceException If the pointed object is not in scope
*
* MCParticles can only be fetched if the full history of objects are in scope and stored
*/
std::vector<const MCParticle*> PixelHit::getMCParticles() const {
std::vector<const MCParticle*> mc_particles;
for(auto& mc_particle : mc_particles_) {
if(mc_particle == nullptr) {
throw MissingReferenceException(typeid(*this), typeid(MCParticle));
}
mc_particles.emplace_back(dynamic_cast<MCParticle*>(mc_particle.GetObject()));
}
// Return as a vector of mc particles
return mc_particles;
}
ClassImp(PixelHit)
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 New Designs Unlimited, LLC
* Opensource Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenAlpr.
*
* OpenAlpr is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "utility.h"
Rect expandRect(Rect original, int expandXPixels, int expandYPixels, int maxX, int maxY)
{
Rect expandedRegion = Rect(original);
float halfX = round((float) expandXPixels / 2.0);
float halfY = round((float) expandYPixels / 2.0);
expandedRegion.x = expandedRegion.x - halfX;
expandedRegion.width = expandedRegion.width + expandXPixels;
expandedRegion.y = expandedRegion.y - halfY;
expandedRegion.height = expandedRegion.height + expandYPixels;
if (expandedRegion.x < 0)
expandedRegion.x = 0;
if (expandedRegion.y < 0)
expandedRegion.y = 0;
if (expandedRegion.x + expandedRegion.width > maxX)
expandedRegion.width = maxX - expandedRegion.x;
if (expandedRegion.y + expandedRegion.height > maxY)
expandedRegion.height = maxY - expandedRegion.y;
return expandedRegion;
}
Mat drawImageDashboard(vector<Mat> images, int imageType, int numColumns)
{
int numRows = ceil((float) images.size() / (float) numColumns);
Mat dashboard(Size(images[0].cols * numColumns, images[0].rows * numRows), imageType);
for (int i = 0; i < numColumns * numRows; i++)
{
if (i < images.size())
images[i].copyTo(dashboard(Rect((i%numColumns) * images[i].cols, floor((float) i/numColumns) * images[i].rows, images[i].cols, images[i].rows)));
else
{
Mat black = Mat::zeros(images[0].size(), imageType);
black.copyTo(dashboard(Rect((i%numColumns) * images[0].cols, floor((float) i/numColumns) * images[0].rows, images[0].cols, images[0].rows)));
}
}
return dashboard;
}
Mat addLabel(Mat input, string label)
{
const int border_size = 1;
const Scalar border_color(0,0,255);
const int extraHeight = 20;
const Scalar bg(222,222,222);
const Scalar fg(0,0,0);
Rect destinationRect(border_size, extraHeight, input.cols, input.rows);
Mat newImage(Size(input.cols + (border_size), input.rows + extraHeight + (border_size )), input.type());
input.copyTo(newImage(destinationRect));
cout << " Adding label " << label << endl;
if (input.type() == CV_8U)
cvtColor(newImage, newImage, CV_GRAY2BGR);
rectangle(newImage, Point(0,0), Point(input.cols, extraHeight), bg, CV_FILLED);
putText(newImage, label, Point(5, extraHeight - 5), CV_FONT_HERSHEY_PLAIN , 0.7, fg);
rectangle(newImage, Point(0,0), Point(newImage.cols - 1, newImage.rows -1), border_color, border_size);
return newImage;
}
void drawAndWait(cv::Mat* frame)
{
cv::imshow("Temp Window", *frame);
while (cv::waitKey(50) == -1)
{
// loop
}
cv::destroyWindow("Temp Window");
}
void displayImage(Config* config, string windowName, cv::Mat frame)
{
if (config->debugShowImages)
imshow(windowName, frame);
}
vector<Mat> produceThresholds(const Mat img_gray, Config* config)
{
const int THRESHOLD_COUNT = 4;
//Mat img_equalized = equalizeBrightness(img_gray);
timespec startTime;
getTime(&startTime);
vector<Mat> thresholds;
for (int i = 0; i < THRESHOLD_COUNT; i++)
thresholds.push_back(Mat(img_gray.size(), CV_8U));
int i = 0;
// Adaptive
//adaptiveThreshold(img_gray, thresholds[i++], 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY_INV , 7, 3);
//adaptiveThreshold(img_gray, thresholds[i++], 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY_INV , 13, 3);
//adaptiveThreshold(img_gray, thresholds[i++], 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY_INV , 17, 3);
// Wolf
int k = 0, win=18;
//NiblackSauvolaWolfJolion (img_gray, thresholds[i++], WOLFJOLION, win, win, 0.05 + (k * 0.35));
//bitwise_not(thresholds[i-1], thresholds[i-1]);
NiblackSauvolaWolfJolion (img_gray, thresholds[i++], WOLFJOLION, win, win, 0.05 + (k * 0.35));
bitwise_not(thresholds[i-1], thresholds[i-1]);
k = 1; win = 22;
NiblackSauvolaWolfJolion (img_gray, thresholds[i++], WOLFJOLION, win, win, 0.05 + (k * 0.35));
bitwise_not(thresholds[i-1], thresholds[i-1]);
//NiblackSauvolaWolfJolion (img_gray, thresholds[i++], WOLFJOLION, win, win, 0.05 + (k * 0.35));
//bitwise_not(thresholds[i-1], thresholds[i-1]);
// Sauvola
k = 1;
NiblackSauvolaWolfJolion (img_gray, thresholds[i++], SAUVOLA, 12, 12, 0.18 * k);
bitwise_not(thresholds[i-1], thresholds[i-1]);
k=2;
NiblackSauvolaWolfJolion (img_gray, thresholds[i++], SAUVOLA, 12, 12, 0.18 * k);
bitwise_not(thresholds[i-1], thresholds[i-1]);
if (config->debugTiming)
{
timespec endTime;
getTime(&endTime);
cout << " -- Produce Threshold Time: " << diffclock(startTime, endTime) << "ms." << endl;
}
return thresholds;
//threshold(img_equalized, img_threshold, 100, 255, THRESH_BINARY);
}
double median(int array[], int arraySize)
{
if (arraySize == 0)
{
//std::cerr << "Median calculation requested on empty array" << endl;
return 0;
}
std::sort(&array[0], &array[arraySize]);
return arraySize % 2 ? array[arraySize / 2] : (array[max(0, arraySize / 2 - 1)] + array[arraySize / 2]) / 2;
}
Mat equalizeBrightness(Mat img)
{
// Divide the image by its morphologically closed counterpart
Mat kernel = getStructuringElement(MORPH_ELLIPSE, Size(19,19));
Mat closed;
morphologyEx(img, closed, MORPH_CLOSE, kernel);
img.convertTo(img, CV_32FC1); // divide requires floating-point
divide(img, closed, img, 1, CV_32FC1);
normalize(img, img, 0, 255, NORM_MINMAX);
img.convertTo(img, CV_8U); // convert back to unsigned int
return img;
}
void drawRotatedRect(Mat* img, RotatedRect rect, Scalar color, int thickness)
{
Point2f rect_points[4];
rect.points( rect_points );
for( int j = 0; j < 4; j++ )
line( *img, rect_points[j], rect_points[(j+1)%4], color, thickness, 8 );
}
void fillMask(Mat img, const Mat mask, Scalar color)
{
for (int row = 0; row < img.rows; row++)
{
for (int col = 0; col < img.cols; col++)
{
int m = (int) mask.at<uchar>(row, col);
if (m)
{
for (int z = 0; z < 3; z++)
{
int prevVal = img.at<Vec3b>(row, col)[z];
img.at<Vec3b>(row, col)[z] = ((int) color[z]) | prevVal;
}
}
}
}
}
void drawX(Mat img, Rect rect, Scalar color, int thickness)
{
Point tl(rect.x, rect.y);
Point tr(rect.x + rect.width, rect.y);
Point bl(rect.x, rect.y + rect.height);
Point br(rect.x + rect.width, rect.y + rect.height);
line(img, tl, br, color, thickness);
line(img, bl, tr, color, thickness);
}
double distanceBetweenPoints(Point p1, Point p2)
{
float asquared = (p2.x - p1.x)*(p2.x - p1.x);
float bsquared = (p2.y - p1.y)*(p2.y - p1.y);
return sqrt(asquared + bsquared);
}
float angleBetweenPoints(Point p1, Point p2)
{
int deltaY = p2.y - p1.y;
int deltaX = p2.x - p1.x;
return atan2((float) deltaY, (float) deltaX) * (180 / CV_PI);
}
Size getSizeMaintainingAspect(Mat inputImg, int maxWidth, int maxHeight)
{
float aspect = ((float) inputImg.cols) / ((float) inputImg.rows);
if (maxWidth / aspect > maxHeight)
{
return Size(maxHeight * aspect, maxHeight);
}
else
{
return Size(maxWidth, maxWidth / aspect);
}
}
LineSegment::LineSegment()
{
init(0, 0, 0, 0);
}
LineSegment::LineSegment(Point p1, Point p2)
{
init(p1.x, p1.y, p2.x, p2.y);
}
LineSegment::LineSegment(int x1, int y1, int x2, int y2)
{
init(x1, y1, x2, y2);
}
void LineSegment::init(int x1, int y1, int x2, int y2)
{
this->p1 = Point(x1, y1);
this->p2 = Point(x2, y2);
if (p2.x - p1.x == 0)
this->slope = 0.00000000001;
else
this->slope = (float) (p2.y - p1.y) / (float) (p2.x - p1.x);
this->length = distanceBetweenPoints(p1, p2);
this->angle = angleBetweenPoints(p1, p2);
}
bool LineSegment::isPointBelowLine( Point tp ){
return ((p2.x - p1.x)*(tp.y - p1.y) - (p2.y - p1.y)*(tp.x - p1.x)) > 0;
}
float LineSegment::getPointAt(float x)
{
return slope * (x - p2.x) + p2.y;
}
Point LineSegment::closestPointOnSegmentTo(Point p)
{
float top = (p.x - p1.x) * (p2.x - p1.x) + (p.y - p1.y)*(p2.y - p1.y);
float bottom = distanceBetweenPoints(p2, p1);
bottom = bottom * bottom;
float u = top / bottom;
float x = p1.x + u * (p2.x - p1.x);
float y = p1.y + u * (p2.y - p1.y);
return Point(x, y);
}
Point LineSegment::intersection(LineSegment line)
{
float c1, c2;
float intersection_X = -1, intersection_Y= -1;
c1 = p1.y - slope * p1.x; // which is same as y2 - slope * x2
c2 = line.p2.y - line.slope * line.p2.x; // which is same as y2 - slope * x2
if( (slope - line.slope) == 0)
{
//std::cout << "No Intersection between the lines" << endl;
}
else if (p1.x == p2.x)
{
// Line1 is vertical
return Point(p1.x, line.getPointAt(p1.x));
}
else if (line.p1.x == line.p2.x)
{
// Line2 is vertical
return Point(line.p1.x, getPointAt(line.p1.x));
}
else
{
intersection_X = (c2 - c1) / (slope - line.slope);
intersection_Y = slope * intersection_X + c1;
}
return Point(intersection_X, intersection_Y);
}
Point LineSegment::midpoint()
{
// Handle the case where the line is vertical
if (p1.x == p2.x)
{
float ydiff = p2.y-p1.y;
float y = p1.y + (ydiff/2);
return Point(p1.x, y);
}
float diff = p2.x - p1.x;
float midX = ((float) p1.x) + (diff / 2);
int midY = getPointAt(midX);
return Point(midX, midY);
}
LineSegment LineSegment::getParallelLine(float distance)
{
float diff_x = p2.x - p1.x;
float diff_y = p2.y - p1.y;
float angle = atan2( diff_x, diff_y);
float dist_x = distance * cos(angle);
float dist_y = -distance * sin(angle);
int offsetX = (int)round(dist_x);
int offsetY = (int)round(dist_y);
LineSegment result(p1.x + offsetX, p1.y + offsetY,
p2.x + offsetX, p2.y + offsetY);
return result;
}
<commit_msg>Reversed segfault fix as it was already fixed<commit_after>/*
* Copyright (c) 2013 New Designs Unlimited, LLC
* Opensource Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenAlpr.
*
* OpenAlpr is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "utility.h"
Rect expandRect(Rect original, int expandXPixels, int expandYPixels, int maxX, int maxY)
{
Rect expandedRegion = Rect(original);
float halfX = round((float) expandXPixels / 2.0);
float halfY = round((float) expandYPixels / 2.0);
expandedRegion.x = expandedRegion.x - halfX;
expandedRegion.width = expandedRegion.width + expandXPixels;
expandedRegion.y = expandedRegion.y - halfY;
expandedRegion.height = expandedRegion.height + expandYPixels;
if (expandedRegion.x < 0)
expandedRegion.x = 0;
if (expandedRegion.y < 0)
expandedRegion.y = 0;
if (expandedRegion.x + expandedRegion.width > maxX)
expandedRegion.width = maxX - expandedRegion.x;
if (expandedRegion.y + expandedRegion.height > maxY)
expandedRegion.height = maxY - expandedRegion.y;
return expandedRegion;
}
Mat drawImageDashboard(vector<Mat> images, int imageType, int numColumns)
{
int numRows = ceil((float) images.size() / (float) numColumns);
Mat dashboard(Size(images[0].cols * numColumns, images[0].rows * numRows), imageType);
for (int i = 0; i < numColumns * numRows; i++)
{
if (i < images.size())
images[i].copyTo(dashboard(Rect((i%numColumns) * images[i].cols, floor((float) i/numColumns) * images[i].rows, images[i].cols, images[i].rows)));
else
{
Mat black = Mat::zeros(images[0].size(), imageType);
black.copyTo(dashboard(Rect((i%numColumns) * images[0].cols, floor((float) i/numColumns) * images[0].rows, images[0].cols, images[0].rows)));
}
}
return dashboard;
}
Mat addLabel(Mat input, string label)
{
const int border_size = 1;
const Scalar border_color(0,0,255);
const int extraHeight = 20;
const Scalar bg(222,222,222);
const Scalar fg(0,0,0);
Rect destinationRect(border_size, extraHeight, input.cols, input.rows);
Mat newImage(Size(input.cols + (border_size), input.rows + extraHeight + (border_size )), input.type());
input.copyTo(newImage(destinationRect));
cout << " Adding label " << label << endl;
if (input.type() == CV_8U)
cvtColor(newImage, newImage, CV_GRAY2BGR);
rectangle(newImage, Point(0,0), Point(input.cols, extraHeight), bg, CV_FILLED);
putText(newImage, label, Point(5, extraHeight - 5), CV_FONT_HERSHEY_PLAIN , 0.7, fg);
rectangle(newImage, Point(0,0), Point(newImage.cols - 1, newImage.rows -1), border_color, border_size);
return newImage;
}
void drawAndWait(cv::Mat* frame)
{
cv::imshow("Temp Window", *frame);
while (cv::waitKey(50) == -1)
{
// loop
}
cv::destroyWindow("Temp Window");
}
void displayImage(Config* config, string windowName, cv::Mat frame)
{
if (config->debugShowImages)
imshow(windowName, frame);
}
vector<Mat> produceThresholds(const Mat img_gray, Config* config)
{
const int THRESHOLD_COUNT = 4;
//Mat img_equalized = equalizeBrightness(img_gray);
timespec startTime;
getTime(&startTime);
vector<Mat> thresholds;
for (int i = 0; i < THRESHOLD_COUNT; i++)
thresholds.push_back(Mat(img_gray.size(), CV_8U));
int i = 0;
// Adaptive
//adaptiveThreshold(img_gray, thresholds[i++], 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY_INV , 7, 3);
//adaptiveThreshold(img_gray, thresholds[i++], 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY_INV , 13, 3);
//adaptiveThreshold(img_gray, thresholds[i++], 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY_INV , 17, 3);
// Wolf
int k = 0, win=18;
//NiblackSauvolaWolfJolion (img_gray, thresholds[i++], WOLFJOLION, win, win, 0.05 + (k * 0.35));
//bitwise_not(thresholds[i-1], thresholds[i-1]);
NiblackSauvolaWolfJolion (img_gray, thresholds[i++], WOLFJOLION, win, win, 0.05 + (k * 0.35));
bitwise_not(thresholds[i-1], thresholds[i-1]);
k = 1; win = 22;
NiblackSauvolaWolfJolion (img_gray, thresholds[i++], WOLFJOLION, win, win, 0.05 + (k * 0.35));
bitwise_not(thresholds[i-1], thresholds[i-1]);
//NiblackSauvolaWolfJolion (img_gray, thresholds[i++], WOLFJOLION, win, win, 0.05 + (k * 0.35));
//bitwise_not(thresholds[i-1], thresholds[i-1]);
// Sauvola
k = 1;
NiblackSauvolaWolfJolion (img_gray, thresholds[i++], SAUVOLA, 12, 12, 0.18 * k);
bitwise_not(thresholds[i-1], thresholds[i-1]);
k=2;
NiblackSauvolaWolfJolion (img_gray, thresholds[i++], SAUVOLA, 12, 12, 0.18 * k);
bitwise_not(thresholds[i-1], thresholds[i-1]);
if (config->debugTiming)
{
timespec endTime;
getTime(&endTime);
cout << " -- Produce Threshold Time: " << diffclock(startTime, endTime) << "ms." << endl;
}
return thresholds;
//threshold(img_equalized, img_threshold, 100, 255, THRESH_BINARY);
}
double median(int array[], int arraySize)
{
if (arraySize == 0)
{
//std::cerr << "Median calculation requested on empty array" << endl;
return 0;
}
std::sort(&array[0], &array[arraySize]);
return arraySize % 2 ? array[arraySize / 2] : (array[arraySize / 2 - 1] + array[arraySize / 2]) / 2;
}
Mat equalizeBrightness(Mat img)
{
// Divide the image by its morphologically closed counterpart
Mat kernel = getStructuringElement(MORPH_ELLIPSE, Size(19,19));
Mat closed;
morphologyEx(img, closed, MORPH_CLOSE, kernel);
img.convertTo(img, CV_32FC1); // divide requires floating-point
divide(img, closed, img, 1, CV_32FC1);
normalize(img, img, 0, 255, NORM_MINMAX);
img.convertTo(img, CV_8U); // convert back to unsigned int
return img;
}
void drawRotatedRect(Mat* img, RotatedRect rect, Scalar color, int thickness)
{
Point2f rect_points[4];
rect.points( rect_points );
for( int j = 0; j < 4; j++ )
line( *img, rect_points[j], rect_points[(j+1)%4], color, thickness, 8 );
}
void fillMask(Mat img, const Mat mask, Scalar color)
{
for (int row = 0; row < img.rows; row++)
{
for (int col = 0; col < img.cols; col++)
{
int m = (int) mask.at<uchar>(row, col);
if (m)
{
for (int z = 0; z < 3; z++)
{
int prevVal = img.at<Vec3b>(row, col)[z];
img.at<Vec3b>(row, col)[z] = ((int) color[z]) | prevVal;
}
}
}
}
}
void drawX(Mat img, Rect rect, Scalar color, int thickness)
{
Point tl(rect.x, rect.y);
Point tr(rect.x + rect.width, rect.y);
Point bl(rect.x, rect.y + rect.height);
Point br(rect.x + rect.width, rect.y + rect.height);
line(img, tl, br, color, thickness);
line(img, bl, tr, color, thickness);
}
double distanceBetweenPoints(Point p1, Point p2)
{
float asquared = (p2.x - p1.x)*(p2.x - p1.x);
float bsquared = (p2.y - p1.y)*(p2.y - p1.y);
return sqrt(asquared + bsquared);
}
float angleBetweenPoints(Point p1, Point p2)
{
int deltaY = p2.y - p1.y;
int deltaX = p2.x - p1.x;
return atan2((float) deltaY, (float) deltaX) * (180 / CV_PI);
}
Size getSizeMaintainingAspect(Mat inputImg, int maxWidth, int maxHeight)
{
float aspect = ((float) inputImg.cols) / ((float) inputImg.rows);
if (maxWidth / aspect > maxHeight)
{
return Size(maxHeight * aspect, maxHeight);
}
else
{
return Size(maxWidth, maxWidth / aspect);
}
}
LineSegment::LineSegment()
{
init(0, 0, 0, 0);
}
LineSegment::LineSegment(Point p1, Point p2)
{
init(p1.x, p1.y, p2.x, p2.y);
}
LineSegment::LineSegment(int x1, int y1, int x2, int y2)
{
init(x1, y1, x2, y2);
}
void LineSegment::init(int x1, int y1, int x2, int y2)
{
this->p1 = Point(x1, y1);
this->p2 = Point(x2, y2);
if (p2.x - p1.x == 0)
this->slope = 0.00000000001;
else
this->slope = (float) (p2.y - p1.y) / (float) (p2.x - p1.x);
this->length = distanceBetweenPoints(p1, p2);
this->angle = angleBetweenPoints(p1, p2);
}
bool LineSegment::isPointBelowLine( Point tp ){
return ((p2.x - p1.x)*(tp.y - p1.y) - (p2.y - p1.y)*(tp.x - p1.x)) > 0;
}
float LineSegment::getPointAt(float x)
{
return slope * (x - p2.x) + p2.y;
}
Point LineSegment::closestPointOnSegmentTo(Point p)
{
float top = (p.x - p1.x) * (p2.x - p1.x) + (p.y - p1.y)*(p2.y - p1.y);
float bottom = distanceBetweenPoints(p2, p1);
bottom = bottom * bottom;
float u = top / bottom;
float x = p1.x + u * (p2.x - p1.x);
float y = p1.y + u * (p2.y - p1.y);
return Point(x, y);
}
Point LineSegment::intersection(LineSegment line)
{
float c1, c2;
float intersection_X = -1, intersection_Y= -1;
c1 = p1.y - slope * p1.x; // which is same as y2 - slope * x2
c2 = line.p2.y - line.slope * line.p2.x; // which is same as y2 - slope * x2
if( (slope - line.slope) == 0)
{
//std::cout << "No Intersection between the lines" << endl;
}
else if (p1.x == p2.x)
{
// Line1 is vertical
return Point(p1.x, line.getPointAt(p1.x));
}
else if (line.p1.x == line.p2.x)
{
// Line2 is vertical
return Point(line.p1.x, getPointAt(line.p1.x));
}
else
{
intersection_X = (c2 - c1) / (slope - line.slope);
intersection_Y = slope * intersection_X + c1;
}
return Point(intersection_X, intersection_Y);
}
Point LineSegment::midpoint()
{
// Handle the case where the line is vertical
if (p1.x == p2.x)
{
float ydiff = p2.y-p1.y;
float y = p1.y + (ydiff/2);
return Point(p1.x, y);
}
float diff = p2.x - p1.x;
float midX = ((float) p1.x) + (diff / 2);
int midY = getPointAt(midX);
return Point(midX, midY);
}
LineSegment LineSegment::getParallelLine(float distance)
{
float diff_x = p2.x - p1.x;
float diff_y = p2.y - p1.y;
float angle = atan2( diff_x, diff_y);
float dist_x = distance * cos(angle);
float dist_y = -distance * sin(angle);
int offsetX = (int)round(dist_x);
int offsetY = (int)round(dist_y);
LineSegment result(p1.x + offsetX, p1.y + offsetY,
p2.x + offsetX, p2.y + offsetY);
return result;
}
<|endoftext|> |
<commit_before>#pragma once
/*
* Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the COPYING file.
*/
/**
* \file
* \brief Various macros for qi. (deprecated, export API, disallow copy, ..)
* \includename{qi/macro.hpp}
* \verbatim
* This header file contains various macros for qi.
*
* - import/export symbol (:cpp:macro:`QI_IMPORT_API`,
* :cpp:macro:`QI_EXPORT_API`)
* - mark function and header as deprecated (:cpp:macro:`QI_DEPRECATED_HEADER`,
* :cpp:macro:`QI_API_DEPRECATED`)
* - generate compiler warning (:cpp:macro:`QI_COMPILER_WARNING`)
* - disallow copy and assign (:cpp:macro:`QI_DISALLOW_COPY_AND_ASSIGN`)
* \endverbatim
*/
#ifndef _QI_MACRO_HPP_
# define _QI_MACRO_HPP_
# include <qi/preproc.hpp>
/**
* \def QI_API_DEPRECATED(x)
* \brief Compiler flags to mark a function as deprecated. It will generate a
* compiler warning.
*/
#if defined(__GNUC__) && !defined(QI_NO_API_DEPRECATED)
# define QI_API_DEPRECATED __attribute__((deprecated))
#elif defined(_MSC_VER) && !defined(QI_NO_API_DEPRECATED)
# define QI_API_DEPRECATED __declspec(deprecated)
#else
# define QI_API_DEPRECATED
#endif
/**
* \def QI_NORETURN
* \brief Portable noreturn attribute, used to declare that a function does not return
*/
#if defined(__GNUC__)
# define QI_NORETURN __attribute__((noreturn))
#elif defined(_MSC_VER)
/// Portable noreturn attribute, used to declare that a function does not return
# define QI_NORETURN __declspec(noreturn)
#else
# define QI_NORETURN
#endif
/**
* \def QI_HAS_VARIABLE_LENGTH_ARRAY
* \brief Mark compilers supporting variable length array (VLA)
*/
#if defined(__GNUC__) && !defined(__clang__)
# define QI_HAS_VARIABLE_LENGTH_ARRAY 1
#else
# define QI_HAS_VARIABLE_LENGTH_ARRAY 0
#endif
// For shared library
/**
* \return the proper type specification for import/export
* \param libname the name of your library.
* This macro will use two preprocessor defines:
* libname_EXPORTS (cmake convention) and libname_STATIC_BUILD.
* Those macro can be unset or set to 0 to mean false, or set to empty or 1 to
* mean true.
* The first one must be true if the current compilation unit is within the library.
* The second must be true if the library was built as a static archive.
* The proper way to use this macro is to:
* - Have your buildsystem set mylib_EXPORTS when building MYLIB
* - Have your buildsystem produce a config.h file that
* \#define mylib_STATIC_BUILD to 1 or empty if it is a static build, and
* not define mylib_STATIC_BUILD or define it to 0 otherwise
* In one header, write
* \#include <mylib/config.h>
* \#define MYLIB_API QI_LIB_API(mylib)
*/
#define QI_LIB_API(libname) _QI_LIB_API(BOOST_PP_CAT(libname, _EXPORTS), BOOST_PP_CAT(libname, _STATIC_BUILD))
#define _QI_LIB_API(IS_BUILDING_LIB, IS_LIB_STATIC_BUILD) \
QI_LIB_API_NORMALIZED(_QI_IS_ONE_OR_EMPTY(BOOST_PP_CAT(_ , IS_BUILDING_LIB)), _QI_IS_ONE_OR_EMPTY(BOOST_PP_CAT(_, IS_LIB_STATIC_BUILD)))
/**
* \def QI_IMPORT_API
* \brief Compiler flags to import a function or a class.
*/
/**
* \def QI_EXPORT_API
* \brief Compiler flags to export a function or a class.
*/
/**
* \def QI_LIB_API_NORMALIZED(a, b)
* \brief Each platform must provide a QI_LIB_API_NORMALIZED(isBuilding, isStatic)
*/
#if defined _WIN32 || defined __CYGWIN__
# define QI_EXPORT_API __declspec(dllexport)
# define QI_IMPORT_API __declspec(dllimport)
# define QI_LIB_API_NORMALIZED(exporting, isstatic) BOOST_PP_CAT(BOOST_PP_CAT(_QI_LIB_API_NORMALIZED_, exporting), isstatic)
# define _QI_LIB_API_NORMALIZED_00 QI_IMPORT_API
# define _QI_LIB_API_NORMALIZED_10 QI_EXPORT_API
# define _QI_LIB_API_NORMALIZED_11
# define _QI_LIB_API_NORMALIZED_01
#elif __GNUC__ >= 4
# define QI_EXPORT_API __attribute__ ((visibility("default")))
# define QI_IMPORT_API QI_EXPORT_API
# define QI_LIB_API_NORMALIZED(a, b) QI_EXPORT_API
#else
# define QI_IMPORT_API
# define QI_EXPORT_API
# define QI_LIB_API_NORMALIZED(a, b)
#endif
//! \cond internal
// Macros adapted from opencv2.2
#if defined(_MSC_VER)
#define QI_DO_PRAGMA(x) __pragma(x)
#define __ALSTR2__(x) #x
#define __ALSTR1__(x) __ALSTR2__(x)
#define _ALMSVCLOC_ __FILE__ "("__ALSTR1__(__LINE__)") : "
#define QI_MSG_PRAGMA(_msg) QI_DO_PRAGMA(message (_ALMSVCLOC_ _msg))
#elif defined(__GNUC__)
#define QI_DO_PRAGMA(x) _Pragma (#x)
#define QI_MSG_PRAGMA(_msg) QI_DO_PRAGMA(message (_msg))
#else
#define QI_DO_PRAGMA(x)
#define QI_MSG_PRAGMA(_msg)
#endif
//! \endcond
/**
* \def QI_COMPILER_WARNING(x)
* \brief Generate a compiler warning.
* \param x The string displayed as the warning.
*/
#if defined(QI_NO_COMPILER_WARNING)
# define QI_COMPILER_WARNING(x)
#else
# define QI_COMPILER_WARNING(x) QI_MSG_PRAGMA("Warning: " #x)
#endif
/**
* \def QI_DEPRECATED_HEADER(x)
* \brief Generate a compiler warning stating a header is deprecated.
* add a message to explain what user should do
*/
#if !defined(WITH_DEPRECATED) || defined(QI_NO_DEPRECATED_HEADER)
# define QI_DEPRECATED_HEADER(x)
#else
# define QI_DEPRECATED_HEADER(x) QI_MSG_PRAGMA("\
This file includes at least one deprecated or antiquated ALDEBARAN header \
which may be removed without further notice in the next version. \
Please consult the changelog for details. " #x)
#endif
#ifdef __cplusplus
namespace qi {
template <typename T>
struct IsClonable;
};
#endif
/**
* \brief A macro used to deprecate another macro. Generate a compiler warning
* when the given macro is used.
* \param name The name of the macro.
* \verbatim
* Example:
*
* .. code-block:: cpp
*
* #define MAX(x,y)(QI_DEPRECATE_MACRO(MAX), x > y ? x : y)
* \endverbatim
*/
#define QI_DEPRECATE_MACRO(name) \
QI_COMPILER_WARNING(name macro is deprecated.)
/**
* \deprecated Use boost::noncopyable instead.
*
* \verbatim
* Example:
*
* .. code-block:: cpp
*
* class Foo : private boost::nonpyable
* {};
* \endverbatim
*
* \brief A macro to disallow copy constructor and operator=
* \param type The class name of which we want to forbid copy.
*
* \verbatim
* .. note::
* This macro should always be in the private (or protected) section of a
* class.
*
* Example:
*
* .. code-block:: cpp
*
* class Foo {
* Foo();
* private:
* QI_DISALLOW_COPY_AND_ASSIGN(Foo);
* };
* \endverbatim
*/
#define QI_DISALLOW_COPY_AND_ASSIGN(type) \
QI_DEPRECATE_MACRO(QI_DISALLOW_COPY_AND_ASSIGN) \
type(type const &); \
void operator=(type const &); \
using _qi_not_clonable = int; \
template<typename U> friend struct ::qi::IsClonable
/**
* \def QI_WARN_UNUSED_RESULT
* \brief This macro tags a result as unused.
*/
#if defined(__GNUC__)
# define QI_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#else
# define QI_WARN_UNUSED_RESULT
#endif
/**
* \def QI_ATTR_UNUSED
* \brief This macro tags a attribute as unused.
*/
#if defined(__GNUC__)
# define QI_ATTR_UNUSED __attribute__((unused))
#else
# define QI_ATTR_UNUSED
#endif
/**
* \brief This macro tags a parameter as unused.
*
* \verbatim
* Example:
*
* .. code-block:: cpp
*
* int zero(int QI_UNUSED(x))
* {
* return 0;
* }
* \endverbatim
*/
#define QI_UNUSED(x)
/**
* \def QI_UNIQ_DEF(A)
* \brief A macro to append the line number of the parent macro usage, to define a
* function in or a variable and avoid name collision.
*/
#define _QI_UNIQ_DEF_LEVEL2(A, B) A ## __uniq__ ## B
#define _QI_UNIQ_DEF_LEVEL1(A, B) _QI_UNIQ_DEF_LEVEL2(A, B)
#define QI_UNIQ_DEF(A) _QI_UNIQ_DEF_LEVEL1(A, __LINE__)
#if (!defined(__GNUC__) || defined(__clang__) || \
(__GNUC__ >= 4 && __GNUC_MINOR__ >= 7)) && __cplusplus >= 201103L
/**
* \def QI_CXX11_ENABLED
* \brief GCC < 4.7 is not standard compliant about __cplusplus
* clang 3.3 defines the same macros as GCC 4.2 but it is compliant
*/
# define QI_CXX11_ENABLED 1
#endif
/**
* \def QI_NOEXCEPT(cond)
* \brief Specify that a function may throw or not
*/
#ifdef QI_CXX11_ENABLED
# define QI_NOEXCEPT(cond) noexcept(cond)
#else
# define QI_NOEXCEPT(cond)
#endif
#endif // _QI_MACRO_HPP_
<commit_msg>Added a deprecation macro which accepts a message displayed on trigger.<commit_after>#pragma once
/*
* Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the COPYING file.
*/
/**
* \file
* \brief Various macros for qi. (deprecated, export API, disallow copy, ..)
* \includename{qi/macro.hpp}
* \verbatim
* This header file contains various macros for qi.
*
* - import/export symbol (:cpp:macro:`QI_IMPORT_API`,
* :cpp:macro:`QI_EXPORT_API`)
* - mark function and header as deprecated (:cpp:macro:`QI_DEPRECATED_HEADER`,
* :cpp:macro:`QI_API_DEPRECATED`)
* - generate compiler warning (:cpp:macro:`QI_COMPILER_WARNING`)
* - disallow copy and assign (:cpp:macro:`QI_DISALLOW_COPY_AND_ASSIGN`)
* \endverbatim
*/
#ifndef _QI_MACRO_HPP_
# define _QI_MACRO_HPP_
# include <qi/preproc.hpp>
/**
* \def QI_API_DEPRECATED
* \brief Compiler flags to mark a function as deprecated. It will generate a
* compiler warning.
*/
#if defined(__GNUC__) && !defined(QI_NO_API_DEPRECATED)
# define QI_API_DEPRECATED __attribute__((deprecated))
#elif defined(_MSC_VER) && !defined(QI_NO_API_DEPRECATED)
# define QI_API_DEPRECATED __declspec(deprecated)
#else
# define QI_API_DEPRECATED
#endif
/**
* \def QI_API_DEPRECATED_MSG(msg__)
* \brief Compiler flags to mark a function as deprecated. It will generate a
* compiler warning.
* \param msg__ A message providing a workaround.
*/
#if defined(__GNUC__) && !defined(QI_NO_API_DEPRECATED)
# define QI_API_DEPRECATED_MSG(msg__) __attribute__((deprecated(#msg__)))
#elif defined(_MSC_VER) && !defined(QI_NO_API_DEPRECATED)
# define QI_API_DEPRECATED_MSG(msg__) __declspec(deprecated(#msg__))
#else
# define QI_API_DEPRECATED_MSG(msg__)
#endif
/**
* \def QI_NORETURN
* \brief Portable noreturn attribute, used to declare that a function does not return
*/
#if defined(__GNUC__)
# define QI_NORETURN __attribute__((noreturn))
#elif defined(_MSC_VER)
/// Portable noreturn attribute, used to declare that a function does not return
# define QI_NORETURN __declspec(noreturn)
#else
# define QI_NORETURN
#endif
/**
* \def QI_HAS_VARIABLE_LENGTH_ARRAY
* \brief Mark compilers supporting variable length array (VLA)
*/
#if defined(__GNUC__) && !defined(__clang__)
# define QI_HAS_VARIABLE_LENGTH_ARRAY 1
#else
# define QI_HAS_VARIABLE_LENGTH_ARRAY 0
#endif
// For shared library
/**
* \return the proper type specification for import/export
* \param libname the name of your library.
* This macro will use two preprocessor defines:
* libname_EXPORTS (cmake convention) and libname_STATIC_BUILD.
* Those macro can be unset or set to 0 to mean false, or set to empty or 1 to
* mean true.
* The first one must be true if the current compilation unit is within the library.
* The second must be true if the library was built as a static archive.
* The proper way to use this macro is to:
* - Have your buildsystem set mylib_EXPORTS when building MYLIB
* - Have your buildsystem produce a config.h file that
* \#define mylib_STATIC_BUILD to 1 or empty if it is a static build, and
* not define mylib_STATIC_BUILD or define it to 0 otherwise
* In one header, write
* \#include <mylib/config.h>
* \#define MYLIB_API QI_LIB_API(mylib)
*/
#define QI_LIB_API(libname) _QI_LIB_API(BOOST_PP_CAT(libname, _EXPORTS), BOOST_PP_CAT(libname, _STATIC_BUILD))
#define _QI_LIB_API(IS_BUILDING_LIB, IS_LIB_STATIC_BUILD) \
QI_LIB_API_NORMALIZED(_QI_IS_ONE_OR_EMPTY(BOOST_PP_CAT(_ , IS_BUILDING_LIB)), _QI_IS_ONE_OR_EMPTY(BOOST_PP_CAT(_, IS_LIB_STATIC_BUILD)))
/**
* \def QI_IMPORT_API
* \brief Compiler flags to import a function or a class.
*/
/**
* \def QI_EXPORT_API
* \brief Compiler flags to export a function or a class.
*/
/**
* \def QI_LIB_API_NORMALIZED(a, b)
* \brief Each platform must provide a QI_LIB_API_NORMALIZED(isBuilding, isStatic)
*/
#if defined _WIN32 || defined __CYGWIN__
# define QI_EXPORT_API __declspec(dllexport)
# define QI_IMPORT_API __declspec(dllimport)
# define QI_LIB_API_NORMALIZED(exporting, isstatic) BOOST_PP_CAT(BOOST_PP_CAT(_QI_LIB_API_NORMALIZED_, exporting), isstatic)
# define _QI_LIB_API_NORMALIZED_00 QI_IMPORT_API
# define _QI_LIB_API_NORMALIZED_10 QI_EXPORT_API
# define _QI_LIB_API_NORMALIZED_11
# define _QI_LIB_API_NORMALIZED_01
#elif __GNUC__ >= 4
# define QI_EXPORT_API __attribute__ ((visibility("default")))
# define QI_IMPORT_API QI_EXPORT_API
# define QI_LIB_API_NORMALIZED(a, b) QI_EXPORT_API
#else
# define QI_IMPORT_API
# define QI_EXPORT_API
# define QI_LIB_API_NORMALIZED(a, b)
#endif
//! \cond internal
// Macros adapted from opencv2.2
#if defined(_MSC_VER)
#define QI_DO_PRAGMA(x) __pragma(x)
#define __ALSTR2__(x) #x
#define __ALSTR1__(x) __ALSTR2__(x)
#define _ALMSVCLOC_ __FILE__ "("__ALSTR1__(__LINE__)") : "
#define QI_MSG_PRAGMA(_msg) QI_DO_PRAGMA(message (_ALMSVCLOC_ _msg))
#elif defined(__GNUC__)
#define QI_DO_PRAGMA(x) _Pragma (#x)
#define QI_MSG_PRAGMA(_msg) QI_DO_PRAGMA(message (_msg))
#else
#define QI_DO_PRAGMA(x)
#define QI_MSG_PRAGMA(_msg)
#endif
//! \endcond
/**
* \def QI_COMPILER_WARNING(x)
* \brief Generate a compiler warning.
* \param x The string displayed as the warning.
*/
#if defined(QI_NO_COMPILER_WARNING)
# define QI_COMPILER_WARNING(x)
#else
# define QI_COMPILER_WARNING(x) QI_MSG_PRAGMA("Warning: " #x)
#endif
/**
* \def QI_DEPRECATED_HEADER(x)
* \brief Generate a compiler warning stating a header is deprecated.
* add a message to explain what user should do
*/
#if !defined(WITH_DEPRECATED) || defined(QI_NO_DEPRECATED_HEADER)
# define QI_DEPRECATED_HEADER(x)
#else
# define QI_DEPRECATED_HEADER(x) QI_MSG_PRAGMA("\
This file includes at least one deprecated or antiquated ALDEBARAN header \
which may be removed without further notice in the next version. \
Please consult the changelog for details. " #x)
#endif
#ifdef __cplusplus
namespace qi {
template <typename T>
struct IsClonable;
};
#endif
/**
* \brief A macro used to deprecate another macro. Generate a compiler warning
* when the given macro is used.
* \param name The name of the macro.
* \verbatim
* Example:
*
* .. code-block:: cpp
*
* #define MAX(x,y)(QI_DEPRECATE_MACRO(MAX), x > y ? x : y)
* \endverbatim
*/
#define QI_DEPRECATE_MACRO(name) \
QI_COMPILER_WARNING(name macro is deprecated.)
/**
* \deprecated Use boost::noncopyable instead.
*
* \verbatim
* Example:
*
* .. code-block:: cpp
*
* class Foo : private boost::nonpyable
* {};
* \endverbatim
*
* \brief A macro to disallow copy constructor and operator=
* \param type The class name of which we want to forbid copy.
*
* \verbatim
* .. note::
* This macro should always be in the private (or protected) section of a
* class.
*
* Example:
*
* .. code-block:: cpp
*
* class Foo {
* Foo();
* private:
* QI_DISALLOW_COPY_AND_ASSIGN(Foo);
* };
* \endverbatim
*/
#define QI_DISALLOW_COPY_AND_ASSIGN(type) \
QI_DEPRECATE_MACRO(QI_DISALLOW_COPY_AND_ASSIGN) \
type(type const &); \
void operator=(type const &); \
using _qi_not_clonable = int; \
template<typename U> friend struct ::qi::IsClonable
/**
* \def QI_WARN_UNUSED_RESULT
* \brief This macro tags a result as unused.
*/
#if defined(__GNUC__)
# define QI_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#else
# define QI_WARN_UNUSED_RESULT
#endif
/**
* \def QI_ATTR_UNUSED
* \brief This macro tags a attribute as unused.
*/
#if defined(__GNUC__)
# define QI_ATTR_UNUSED __attribute__((unused))
#else
# define QI_ATTR_UNUSED
#endif
/**
* \brief This macro tags a parameter as unused.
*
* \verbatim
* Example:
*
* .. code-block:: cpp
*
* int zero(int QI_UNUSED(x))
* {
* return 0;
* }
* \endverbatim
*/
#define QI_UNUSED(x)
/**
* \def QI_UNIQ_DEF(A)
* \brief A macro to append the line number of the parent macro usage, to define a
* function in or a variable and avoid name collision.
*/
#define _QI_UNIQ_DEF_LEVEL2(A, B) A ## __uniq__ ## B
#define _QI_UNIQ_DEF_LEVEL1(A, B) _QI_UNIQ_DEF_LEVEL2(A, B)
#define QI_UNIQ_DEF(A) _QI_UNIQ_DEF_LEVEL1(A, __LINE__)
#if (!defined(__GNUC__) || defined(__clang__) || \
(__GNUC__ >= 4 && __GNUC_MINOR__ >= 7)) && __cplusplus >= 201103L
/**
* \def QI_CXX11_ENABLED
* \brief GCC < 4.7 is not standard compliant about __cplusplus
* clang 3.3 defines the same macros as GCC 4.2 but it is compliant
*/
# define QI_CXX11_ENABLED 1
#endif
/**
* \def QI_NOEXCEPT(cond)
* \brief Specify that a function may throw or not
*/
#ifdef QI_CXX11_ENABLED
# define QI_NOEXCEPT(cond) noexcept(cond)
#else
# define QI_NOEXCEPT(cond)
#endif
#endif // _QI_MACRO_HPP_
<|endoftext|> |
<commit_before>/* This is free and unencumbered software released into the public domain. */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "rdf++/reader/trix.h"
#include "rdf++/quad.h"
#include "rdf++/term.h"
#include "rdf++/triple.h"
#include "xml_reader.h"
#include <memory> /* for std::unique_ptr */
#include <cstring> /* for std::strcmp() */
namespace {
enum class trix_element {
unknown = 0,
TriX,
graph,
triple,
id,
uri,
plain_literal,
typed_literal,
};
enum class trix_state {start, document, graph, triple, eof, abort};
struct trix_context {
trix_state state = trix_state::start;
trix_element element = trix_element::unknown;
unsigned int term_pos = 0;
std::unique_ptr<rdf::term> terms[3] = {nullptr, nullptr, nullptr};
std::unique_ptr<rdf::term> graph = nullptr;
std::function<void (rdf::triple*)> triple_callback = nullptr;
std::function<void (rdf::quad*)> quad_callback = nullptr;
};
struct implementation : public rdf::reader::implementation {
implementation(FILE* stream,
const char* content_type,
const char* charset,
const char* base_uri);
virtual ~implementation() noexcept override;
virtual void read_triples(std::function<void (rdf::triple*)> callback) override;
virtual void read_quads(std::function<void (rdf::quad*)> callback) override;
virtual void abort() override;
protected:
void read_with_context(trix_context& context);
void ensure_state(trix_state state, trix_context& context);
void assert_state(trix_state state, trix_context& context);
void enter_state(trix_state state, trix_context& context);
void leave_state(trix_state state, trix_context& context);
void change_state(trix_state state, trix_context& context);
void ensure_depth(unsigned int depth);
void ensure_depth(unsigned int depth_from, unsigned int depth_to);
void record_term(trix_context& context);
void begin_element(trix_context& context);
void finish_element(trix_context& context);
rdf::term* construct_term(trix_context& context);
private:
xml_reader _reader;
};
}
rdf::reader::implementation*
rdf_reader_for_trix(FILE* const stream,
const char* const content_type,
const char* const charset,
const char* const base_uri) {
return new implementation(stream, content_type, charset, base_uri);
}
implementation::implementation(FILE* const stream,
const char* const content_type,
const char* const charset,
const char* const base_uri)
: _reader(stream, base_uri, charset) {
assert(stream != nullptr);
(void)content_type;
}
implementation::~implementation() noexcept = default;
static trix_element
intern_trix_element(const char* const element_name) {
switch (*element_name) {
case 'T':
if (std::strcmp(element_name, "TriX") == 0) {
return trix_element::TriX;
}
break;
case 'g':
if (std::strcmp(element_name, "graph") == 0) {
return trix_element::graph;
}
break;
case 't':
if (std::strcmp(element_name, "triple") == 0) {
return trix_element::triple;
}
if (std::strcmp(element_name, "typedLiteral") == 0) {
return trix_element::typed_literal;
}
break;
case 'i':
if (std::strcmp(element_name, "id") == 0) {
return trix_element::id;
}
break;
case 'u':
if (std::strcmp(element_name, "uri") == 0) {
return trix_element::uri;
}
break;
case 'p':
if (std::strcmp(element_name, "plainLiteral") == 0) {
return trix_element::plain_literal;
}
break;
default:
break;
}
return trix_element::unknown;
}
static void
parse_error(const char* what = "TriX parse error") {
throw rdf::reader_error(what); // TODO
}
void
implementation::read_triples(std::function<void (rdf::triple*)> callback) {
trix_context context;
context.triple_callback = callback;
read_with_context(context);
}
void
implementation::read_quads(std::function<void (rdf::quad*)> callback) {
trix_context context;
context.quad_callback = callback;
read_with_context(context);
}
void
implementation::abort() {
// TODO
}
void
implementation::read_with_context(trix_context& context) {
while (_reader.read()) {
switch (_reader.node_type()) {
case xml_node_type::element:
begin_element(context);
break;
case xml_node_type::end_element:
finish_element(context);
break;
default: /* ignored */
break;
}
}
}
void
implementation::ensure_state(const trix_state state, trix_context& context) {
if (context.state != state) {
parse_error("ensure_state");
}
}
void
implementation::assert_state(const trix_state state, trix_context& context) {
(void)state, (void)context;
assert(context.state == state);
}
void
implementation::enter_state(const trix_state state, trix_context& context) {
switch (state) {
case trix_state::triple:
context.term_pos = 0;
break;
default:
break;
}
}
void
implementation::leave_state(const trix_state state, trix_context& context) {
switch (state) {
case trix_state::graph:
context.graph.reset();
break;
case trix_state::triple:
if (context.quad_callback) {
auto quad = new rdf::quad(
context.terms[0].get(),
context.terms[1].get(),
context.terms[2].get(),
context.graph ? (context.graph)->clone() : nullptr);
context.quad_callback(quad);
}
else if (context.triple_callback) {
auto triple = new rdf::triple(
context.terms[0].get(),
context.terms[1].get(),
context.terms[2].get());
context.triple_callback(triple);
}
for (auto i = 0U; i < 3; i++) {
if (context.quad_callback || context.triple_callback) {
/* The callback took ownership of the terms: */
context.terms[i].release();
}
else {
context.terms[i].reset();
}
}
context.term_pos = 0;
break;
default:
break;
}
}
void
implementation::change_state(const trix_state state, trix_context& context) {
leave_state(context.state, context);
context.state = state;
enter_state(context.state, context);
}
void
implementation::ensure_depth(const unsigned int depth) {
if (_reader.depth() != depth) {
parse_error("ensure_depth");
}
}
void
implementation::record_term(trix_context& context) {
if (context.term_pos >= 3) {
parse_error("record_term");
}
context.terms[context.term_pos].reset(construct_term(context));
context.term_pos++;
}
void
implementation::begin_element(trix_context& context) {
context.element = intern_trix_element(_reader.name());
switch (context.element) {
case trix_element::TriX:
ensure_state(trix_state::start, context);
ensure_depth(0);
change_state(trix_state::document, context);
break;
case trix_element::graph:
ensure_state(trix_state::document, context);
ensure_depth(1);
change_state(trix_state::graph, context);
break;
case trix_element::triple:
ensure_state(trix_state::graph, context);
ensure_depth(2);
change_state(trix_state::triple, context);
break;
case trix_element::uri:
if (context.state == trix_state::graph) {
ensure_depth(2);
//assert(context.graph.get() == nullptr); // FIXME
context.graph.reset(construct_term(context));
break;
}
ensure_state(trix_state::triple, context);
ensure_depth(3);
record_term(context);
break;
case trix_element::id:
case trix_element::plain_literal:
case trix_element::typed_literal:
ensure_state(trix_state::triple, context);
ensure_depth(3);
record_term(context);
break;
default:
parse_error("begin_element"); // TODO
}
}
void
implementation::finish_element(trix_context& context) {
context.element = intern_trix_element(_reader.name());
switch (context.element) {
case trix_element::TriX:
assert_state(trix_state::document, context);
change_state(trix_state::eof, context);
break;
case trix_element::graph:
assert_state(trix_state::graph, context);
change_state(trix_state::document, context);
break;
case trix_element::triple:
assert_state(trix_state::triple, context);
change_state(trix_state::graph, context);
break;
case trix_element::uri:
//assert_state(trix_state::triple, context); // FIXME
break;
case trix_element::id:
case trix_element::plain_literal:
case trix_element::typed_literal:
assert_state(trix_state::triple, context);
break;
default:
parse_error("finish_element"); // TODO
}
}
rdf::term*
implementation::construct_term(trix_context& context) {
rdf::term* term = nullptr;
const auto text = _reader.read_string();
switch (context.element) {
case trix_element::id: {
term = new rdf::blank_node(text);
break;
}
case trix_element::uri: {
term = new rdf::uri_reference(text);
break;
}
case trix_element::plain_literal: {
term = new rdf::plain_literal(text, _reader.xml_lang());
break;
}
case trix_element::typed_literal: {
const auto datatype_uri = _reader.get_attribute("datatype");
if (!datatype_uri) {
parse_error();
}
term = new rdf::typed_literal(text, datatype_uri);
break;
}
default: abort(); /* never reached */
}
return term;
}
<commit_msg>Improved error reporting and handling in the TriX reader.<commit_after>/* This is free and unencumbered software released into the public domain. */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "rdf++/reader/trix.h"
#include "rdf++/quad.h"
#include "rdf++/term.h"
#include "rdf++/triple.h"
#include "xml_reader.h"
#include <memory> /* for std::unique_ptr */
#include <cstring> /* for std::strcmp() */
namespace {
enum class trix_element {
unknown = 0,
TriX,
graph,
triple,
id,
uri,
plain_literal,
typed_literal,
};
enum class trix_state {start, document, graph, triple, eof, abort};
struct trix_context {
trix_state state = trix_state::start;
trix_element element = trix_element::unknown;
unsigned int term_pos = 0;
std::unique_ptr<rdf::term> terms[3] = {nullptr, nullptr, nullptr};
std::unique_ptr<rdf::term> graph = nullptr;
std::function<void (rdf::triple*)> triple_callback = nullptr;
std::function<void (rdf::quad*)> quad_callback = nullptr;
};
struct implementation : public rdf::reader::implementation {
implementation(FILE* stream,
const char* content_type,
const char* charset,
const char* base_uri);
virtual ~implementation() noexcept override;
virtual void read_triples(std::function<void (rdf::triple*)> callback) override;
virtual void read_quads(std::function<void (rdf::quad*)> callback) override;
virtual void abort() override;
protected:
void read_with_context(trix_context& context);
void ensure_state(trix_context& context, trix_state state);
void assert_state(trix_context& context, trix_state state);
void enter_state(trix_context& context, trix_state state);
void leave_state(trix_context& context, trix_state state);
void change_state(trix_context& context, trix_state state);
void ensure_depth(trix_context& context, unsigned int depth);
void record_term(trix_context& context);
void begin_element(trix_context& context);
void finish_element(trix_context& context);
rdf::term* construct_term(trix_context& context);
void throw_error(trix_context& context, const char* what);
private:
xml_reader _reader;
};
}
rdf::reader::implementation*
rdf_reader_for_trix(FILE* const stream,
const char* const content_type,
const char* const charset,
const char* const base_uri) {
return new implementation(stream, content_type, charset, base_uri);
}
implementation::implementation(FILE* const stream,
const char* const content_type,
const char* const charset,
const char* const base_uri)
: _reader(stream, base_uri, charset) {
assert(stream != nullptr);
(void)content_type;
}
implementation::~implementation() noexcept = default;
static trix_element
intern_trix_element(const char* const element_name) {
switch (*element_name) {
case 'T':
if (std::strcmp(element_name, "TriX") == 0) {
return trix_element::TriX;
}
break;
case 'g':
if (std::strcmp(element_name, "graph") == 0) {
return trix_element::graph;
}
break;
case 't':
if (std::strcmp(element_name, "triple") == 0) {
return trix_element::triple;
}
if (std::strcmp(element_name, "typedLiteral") == 0) {
return trix_element::typed_literal;
}
break;
case 'i':
if (std::strcmp(element_name, "id") == 0) {
return trix_element::id;
}
break;
case 'u':
if (std::strcmp(element_name, "uri") == 0) {
return trix_element::uri;
}
break;
case 'p':
if (std::strcmp(element_name, "plainLiteral") == 0) {
return trix_element::plain_literal;
}
break;
default:
break;
}
return trix_element::unknown;
}
void
implementation::read_triples(std::function<void (rdf::triple*)> callback) {
trix_context context;
context.triple_callback = callback;
read_with_context(context);
}
void
implementation::read_quads(std::function<void (rdf::quad*)> callback) {
trix_context context;
context.quad_callback = callback;
read_with_context(context);
}
void
implementation::abort() {
// TODO
}
void
implementation::read_with_context(trix_context& context) {
while (_reader.read()) {
switch (_reader.node_type()) {
case xml_node_type::element:
begin_element(context);
break;
case xml_node_type::end_element:
finish_element(context);
break;
default: /* ignored */
break;
}
}
}
void
implementation::ensure_state(trix_context& context, const trix_state state) {
if (context.state != state) {
throw_error(context, "mismatched nesting of elements in TriX input");
}
}
void
implementation::assert_state(trix_context& context, const trix_state state) {
(void)state, (void)context;
assert(context.state == state);
}
void
implementation::enter_state(trix_context& context, const trix_state state) {
switch (state) {
case trix_state::triple:
context.term_pos = 0;
break;
default:
break;
}
}
void
implementation::leave_state(trix_context& context, const trix_state state) {
switch (state) {
case trix_state::graph:
context.graph.reset();
break;
case trix_state::triple:
if (context.quad_callback) {
auto quad = new rdf::quad(
context.terms[0].get(),
context.terms[1].get(),
context.terms[2].get(),
context.graph ? (context.graph)->clone() : nullptr);
context.quad_callback(quad);
}
else if (context.triple_callback) {
auto triple = new rdf::triple(
context.terms[0].get(),
context.terms[1].get(),
context.terms[2].get());
context.triple_callback(triple);
}
for (auto i = 0U; i < 3; i++) {
if (context.quad_callback || context.triple_callback) {
/* The callback took ownership of the terms: */
context.terms[i].release();
}
else {
context.terms[i].reset();
}
}
context.term_pos = 0;
break;
default:
break;
}
}
void
implementation::change_state(trix_context& context, const trix_state state) {
leave_state(context, context.state);
context.state = state;
enter_state(context, context.state);
}
void
implementation::ensure_depth(trix_context& context, const unsigned int depth) {
if (_reader.depth() != depth) {
throw_error(context, "incorrect nesting of elements in TriX input");
}
}
void
implementation::record_term(trix_context& context) {
if (context.term_pos >= 3) {
throw_error(context, "too many elements inside <triple> element");
}
context.terms[context.term_pos].reset(construct_term(context));
context.term_pos++;
}
void
implementation::begin_element(trix_context& context) {
context.element = intern_trix_element(_reader.name());
switch (context.element) {
case trix_element::TriX:
ensure_state(context, trix_state::start);
ensure_depth(context, 0);
change_state(context, trix_state::document);
break;
case trix_element::graph:
ensure_state(context, trix_state::document);
ensure_depth(context, 1);
change_state(context, trix_state::graph);
break;
case trix_element::triple:
ensure_state(context, trix_state::graph);
ensure_depth(context, 2);
change_state(context, trix_state::triple);
break;
case trix_element::uri:
if (context.state == trix_state::graph) {
ensure_depth(context, 2);
if (context.graph) {
throw_error(context, "repeated <uri> element inside <graph> element");
}
context.graph.reset(construct_term(context));
break;
}
ensure_state(context, trix_state::triple);
ensure_depth(context, 3);
record_term(context);
break;
case trix_element::id:
case trix_element::plain_literal:
case trix_element::typed_literal:
ensure_state(context, trix_state::triple);
ensure_depth(context, 3);
record_term(context);
break;
default:
throw_error(context, "unknown XML element in TriX input");
}
}
void
implementation::finish_element(trix_context& context) {
context.element = intern_trix_element(_reader.name());
switch (context.element) {
case trix_element::TriX:
assert_state(context, trix_state::document);
change_state(context, trix_state::eof);
break;
case trix_element::graph:
assert_state(context, trix_state::graph);
change_state(context, trix_state::document);
break;
case trix_element::triple:
assert_state(context, trix_state::triple);
change_state(context, trix_state::graph);
break;
case trix_element::uri:
//assert_state(trix_state::triple, context); // FIXME: triple | graph
break;
case trix_element::id:
case trix_element::plain_literal:
case trix_element::typed_literal:
assert_state(context, trix_state::triple);
break;
default: abort(); /* never reached */
}
}
rdf::term*
implementation::construct_term(trix_context& context) {
rdf::term* term = nullptr;
const auto text = _reader.read_string();
switch (context.element) {
case trix_element::id: {
term = new rdf::blank_node(text);
break;
}
case trix_element::uri: {
term = new rdf::uri_reference(text);
break;
}
case trix_element::plain_literal: {
term = new rdf::plain_literal(text, _reader.xml_lang());
break;
}
case trix_element::typed_literal: {
const auto datatype_uri = _reader.get_attribute("datatype");
if (!datatype_uri) {
throw_error(context, "missing 'datatype' attribute for <typedLiteral> element");
}
term = new rdf::typed_literal(text, datatype_uri);
break;
}
default: abort(); /* never reached */
}
return term;
}
void
implementation::throw_error(trix_context& context,
const char* const what) {
(void)context;
throw rdf::reader_error(what, _reader.line_number(), _reader.column_number());
}
<|endoftext|> |
<commit_before>#include "inc/relabel_to_front.h"
using namespace std;
RelabelToFront::RelabelToFront(const ResidualNetwork &A) : E(ResidualNetwork(A))
{
this->Source = E.getSource();
this->Sink = E.getSink();
this->VertexCount = E.getCount();
this->PushCount = 0;
this->RelabelCount = 0;
this->DischargeCount = 0;
this->V = vector<Vertex>(VertexCount);
for (int i = 0; i < VertexCount; ++i)
{
V[i].NCurrent = E.getOutgoingEdges(i).begin();
}
this->HeightCount = vector<int>(2 * VertexCount, 0);
this->HeightCount[VertexCount] = 1;
this->HeightCount[0] = VertexCount - 1;
V[Source].Height = VertexCount;
}
RelabelToFront::~RelabelToFront()
{
}
void RelabelToFront::Run()
{
SetInitialLabels();
for (auto &edge : E.getOutgoingEdges(Source))
{
if (edge.weight > 0)
{
V[Source].ExcessFlow += edge.weight;
Push(edge);
}
}
do
{
int i = ActiveQueue.front();
ActiveQueue.pop();
Discharge(i);
} while (!ActiveQueue.empty());
}
void RelabelToFront::Discharge(const int i)
{
this->DischargeCount++;
auto begin = E.getOutgoingEdges(i).begin();
auto end = E.getOutgoingEdges(i).end();
auto current = V[i].NCurrent;
while (V[i].ExcessFlow > 0)
{
if (current == end)
{
int oldHeight = V[i].Height;
Relabel(i);
// We have a gap
if (HeightCount[oldHeight] == 0)
{
Gap(oldHeight);
}
current = begin;
continue;
}
else if (CanPush(*current))
{
Push(*current);
}
current++;
}
V[i].NCurrent = current;
}
void RelabelToFront::Push(ResidualEdge &edge)
{
this->PushCount++;
if (V[edge.to].ExcessFlow == 0 && edge.to != Source && edge.to != Sink)
{
ActiveQueue.push(edge.to);
}
int min = std::min(V[edge.from].ExcessFlow, edge.weight);
edge.weight -= min;
E.E[edge.to][edge.index].weight += min;
V[edge.from].ExcessFlow -= min;
V[edge.to].ExcessFlow += min;
}
void RelabelToFront::Relabel(const int i)
{
this->RelabelCount++;
this->V[i].RelabelCount++;
auto minHeight = 2 * VertexCount;
for (const auto &edge : E.getOutgoingEdges(i))
{
if (edge.weight > 0)
{
minHeight = min(minHeight, V[edge.to].Height);
}
}
HeightCount[V[i].Height]--;
V[i].Height = minHeight + 1;
HeightCount[V[i].Height]++;
}
void RelabelToFront::Gap(const int k)
{
for (int i = 0; i < VertexCount; i++)
{
if (i != Source && i != Sink && V[i].Height >= k)
{
HeightCount[V[i].Height]--;
V[i].Height = std::max(V[i].Height, VertexCount + 1);
HeightCount[V[i].Height]++;
}
}
}
bool RelabelToFront::CanPush(const ResidualEdge &edge)
{
// 1) Must be overflowing
if (!IsOverflowing(edge.from))
{
return false;
}
// 2) There must exist an edge in the residual network
if (edge.weight == 0)
{
return false;
}
// 4) i.h = j.h +1
if (V[edge.from].Height != V[edge.to].Height + 1)
{
return false;
}
return true;
}
bool RelabelToFront::CanRelabel(const int i)
{
// 1) Must be overflowing
if (!IsOverflowing(i))
{
return false;
}
// 2) All neigbors must be highter
for (auto edge : E.getOutgoingEdges(i))
{
if (edge.weight > 0)
{
if (V[edge.from].Height > V[edge.to].Height)
{
return false;
}
}
}
return true;
}
bool RelabelToFront::IsOverflowing(const int i)
{
return V[i].ExcessFlow > 0 && i != Source && i != Sink;
}
void RelabelToFront::SetInitialLabels()
{
queue<int> q;
vector<bool> A = vector<bool>(VertexCount, false);
q.push(Sink);
A[Sink] = true;
A[Source] = true;
while (!q.empty())
{
const int u = q.front();
q.pop();
const int dist = V[u].Height + 1;
for (const auto &edge : E.getOutgoingEdges(u))
{
if (E.E[edge.to][edge.index].weight > 0 && A[edge.to] == false)
{
q.push(edge.to);
A[edge.to] = true;
HeightCount[V[edge.to].Height]--;
V[edge.to].Height = dist;
HeightCount[V[edge.to].Height]++;
}
}
}
}
<commit_msg>Added more comments<commit_after>#include "inc/relabel_to_front.h"
using namespace std;
RelabelToFront::RelabelToFront(const ResidualNetwork &A) : E(ResidualNetwork(A))
{
this->Source = E.getSource();
this->Sink = E.getSink();
this->VertexCount = E.getCount();
this->PushCount = 0;
this->RelabelCount = 0;
this->DischargeCount = 0;
// Инициализация на списъка от върховете
this->V = vector<Vertex>(VertexCount);
for (int i = 0; i < VertexCount; ++i)
{
// Инициализация на указател към текущо ребро
V[i].NCurrent = E.getOutgoingEdges(i).begin();
}
// Масив, в които се запазва броя на върховете на всяка от височините
this->HeightCount = vector<int>(2 * VertexCount, 0);
// Източника и шахтата имат статична височина
this->HeightCount[VertexCount] = 1;
this->HeightCount[0] = VertexCount - 1;
V[Source].Height = VertexCount;
}
RelabelToFront::~RelabelToFront()
{
}
void RelabelToFront::Run()
{
// Изпълнението на евристиката Global Relabeling Heuristic
SetInitialLabels();
// Избутване на поток равен на разреза ({s}, V\{s})
for (auto &edge : E.getOutgoingEdges(Source))
{
if (edge.weight > 0)
{
V[Source].ExcessFlow += edge.weight;
Push(edge);
}
}
// Основно действие на алгоритъма
do
{
int i = ActiveQueue.front();
ActiveQueue.pop();
Discharge(i);
} while (!ActiveQueue.empty());
}
void RelabelToFront::Discharge(const int i)
{
this->DischargeCount++;
auto begin = E.getOutgoingEdges(i).begin();
auto end = E.getOutgoingEdges(i).end();
auto current = V[i].NCurrent;
while (V[i].ExcessFlow > 0)
{
if (current == end)
{
int oldHeight = V[i].Height;
Relabel(i);
// Изпълнение на евристиката Gap Heuristic, ако е намерена празна височина
if (HeightCount[oldHeight] == 0)
{
Gap(oldHeight);
}
current = begin;
continue;
}
else if (CanPush(*current))
{
Push(*current);
}
current++;
}
V[i].NCurrent = current;
}
void RelabelToFront::Push(ResidualEdge &edge)
{
this->PushCount++;
// Ако избутваме поток към неактивен връх, се добавя към опашката
if (V[edge.to].ExcessFlow == 0 && edge.to != Source && edge.to != Sink)
{
ActiveQueue.push(edge.to);
}
int min = std::min(V[edge.from].ExcessFlow, edge.weight);
edge.weight -= min;
E.E[edge.to][edge.index].weight += min;
V[edge.from].ExcessFlow -= min;
V[edge.to].ExcessFlow += min;
}
void RelabelToFront::Relabel(const int i)
{
this->RelabelCount++;
this->V[i].RelabelCount++;
auto minHeight = 2 * VertexCount;
for (const auto &edge : E.getOutgoingEdges(i))
{
if (edge.weight > 0)
{
minHeight = min(minHeight, V[edge.to].Height);
}
}
HeightCount[V[i].Height]--;
V[i].Height = minHeight + 1;
HeightCount[V[i].Height]++;
}
void RelabelToFront::Gap(const int k)
{
// Промяна на височините на всички върхове ако е намерена дупка във височините
for (int i = 0; i < VertexCount; i++)
{
if (i != Source && i != Sink && V[i].Height >= k)
{
HeightCount[V[i].Height]--;
V[i].Height = std::max(V[i].Height, VertexCount + 1);
HeightCount[V[i].Height]++;
}
}
}
bool RelabelToFront::CanPush(const ResidualEdge &edge)
{
// 1) Must be overflowing
if (!IsOverflowing(edge.from))
{
return false;
}
// 2) There must exist an edge in the residual network
if (edge.weight == 0)
{
return false;
}
// 4) i.h = j.h +1
if (V[edge.from].Height != V[edge.to].Height + 1)
{
return false;
}
return true;
}
bool RelabelToFront::CanRelabel(const int i)
{
// 1) Must be overflowing
if (!IsOverflowing(i))
{
return false;
}
// 2) All neigbors must be highter
for (auto edge : E.getOutgoingEdges(i))
{
if (edge.weight > 0)
{
if (V[edge.from].Height > V[edge.to].Height)
{
return false;
}
}
}
return true;
}
bool RelabelToFront::IsOverflowing(const int i)
{
return V[i].ExcessFlow > 0 && i != Source && i != Sink;
}
// Изпълнява обратно търсене в дълбочина
void RelabelToFront::SetInitialLabels()
{
queue<int> q;
vector<bool> A = vector<bool>(VertexCount, false);
q.push(Sink);
A[Sink] = true;
A[Source] = true;
while (!q.empty())
{
const int u = q.front();
q.pop();
const int dist = V[u].Height + 1;
for (const auto &edge : E.getOutgoingEdges(u))
{
if (E.E[edge.to][edge.index].weight > 0 && A[edge.to] == false)
{
q.push(edge.to);
A[edge.to] = true;
HeightCount[V[edge.to].Height]--;
V[edge.to].Height = dist;
HeightCount[V[edge.to].Height]++;
}
}
}
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2009, Markus Rickert
// 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 <algorithm>
#include <stack>
#include <boost/graph/graphviz.hpp>
#include <rl/math/Quaternion.h>
#include <rl/math/Rotation.h>
#include <rl/math/Spatial.h>
#include <rl/math/Unit.h>
#include "Exception.h"
#include "Kinematic.h"
#include "Prismatic.h"
#include "Revolute.h"
namespace rl
{
namespace mdl
{
Kinematic::Kinematic() :
Metric(),
invJ(),
J(),
Jdqd()
{
}
Kinematic::~Kinematic()
{
}
void
Kinematic::calculateJacobian(const bool& inWorldFrame)
{
this->calculateJacobian(this->J, inWorldFrame);
}
void
Kinematic::calculateJacobian(::rl::math::Matrix& J, const bool& inWorldFrame)
{
assert(J.rows() == this->getOperationalDof() * 6);
assert(J.cols() == this->getDof());
::rl::math::Vector tmp(this->getDof());
for (::std::size_t i = 0; i < this->getDof(); ++i)
{
for (::std::size_t j = 0; j < this->getDof(); ++j)
{
tmp(j) = i == j ? 1 : 0;
}
this->setVelocity(tmp);
this->forwardVelocity();
for (::std::size_t j = 0; j < this->getOperationalDof(); ++j)
{
if (inWorldFrame)
{
J.block(j * 6, i, 3, 1) = this->getOperationalPosition(j).linear() * this->getOperationalVelocity(j).linear();
J.block(j * 6 + 3, i, 3, 1) = this->getOperationalPosition(j).linear() * this->getOperationalVelocity(j).angular();
}
else
{
J.block(j * 6, i, 3, 1) = this->getOperationalVelocity(j).linear();
J.block(j * 6 + 3, i, 3, 1) = this->getOperationalVelocity(j).angular();
}
}
}
}
void
Kinematic::calculateJacobianDerivative(const bool& inWorldFrame)
{
this->calculateJacobianDerivative(this->Jdqd, inWorldFrame);
}
void
Kinematic::calculateJacobianDerivative(::rl::math::Vector& Jdqd, const bool& inWorldFrame)
{
::rl::math::Vector tmp = ::rl::math::Vector::Zero(this->getDof());
this->setAcceleration(tmp);
this->forwardVelocity();
this->forwardAcceleration();
for (::std::size_t j = 0; j < this->getOperationalDof(); ++j)
{
if (inWorldFrame)
{
Jdqd.segment(j * 6, 3) = this->getOperationalPosition(j).linear() * this->getOperationalAcceleration(j).linear();
Jdqd.segment(j * 6 + 3, 3) = this->getOperationalPosition(j).linear() * this->getOperationalAcceleration(j).angular();
}
else
{
Jdqd.segment(j * 6, 3) = this->getOperationalAcceleration(j).linear();
Jdqd.segment(j * 6 + 3, 3) = this->getOperationalAcceleration(j).angular();
}
}
}
void
Kinematic::calculateJacobianInverse(const ::rl::math::Real& lambda, const bool& doSvd)
{
this->calculateJacobianInverse(this->J, this->invJ, lambda, doSvd);
}
void
Kinematic::calculateJacobianInverse(const ::rl::math::Matrix& J, ::rl::math::Matrix& invJ, const ::rl::math::Real& lambda, const bool& doSvd) const
{
if (doSvd)
{
invJ.setZero();
::Eigen::JacobiSVD< ::rl::math::Matrix> svd(J, ::Eigen::ComputeFullU | ::Eigen::ComputeFullV);
::rl::math::Real wMin = svd.singularValues().minCoeff();
::rl::math::Real lambdaSqr = wMin < static_cast< ::rl::math::Real>(1.0e-9) ? (1 - ::std::pow((wMin / static_cast< ::rl::math::Real>(1.0e-9)), 2)) * ::std::pow(lambda, 2) : 0;
for (::std::ptrdiff_t i = 0; i < svd.nonzeroSingularValues(); ++i)
{
invJ.noalias() += (
svd.singularValues()(i) / (::std::pow(svd.singularValues()(i), 2) + lambdaSqr) *
svd.matrixV().col(i) * svd.matrixU().col(i).transpose()
);
}
}
else
{
invJ = J.transpose() * (
J * J.transpose() + ::std::pow(lambda, 2) *
::rl::math::Matrix::Identity(this->getOperationalDof() * 6, this->getOperationalDof() * 6)
).inverse();
}
}
::rl::math::Real
Kinematic::calculateManipulabilityMeasure() const
{
return calculateManipulabilityMeasure(this->J);
}
::rl::math::Real
Kinematic::calculateManipulabilityMeasure(const ::rl::math::Matrix& J) const
{
return ::std::sqrt((J * J.transpose()).determinant());
}
void
Kinematic::forwardAcceleration()
{
for (::std::vector<Element*>::iterator i = this->elements.begin(); i != this->elements.end(); ++i)
{
(*i)->forwardAcceleration();
}
}
void
Kinematic::forwardPosition()
{
for (::std::vector<Element*>::iterator i = this->elements.begin(); i != this->elements.end(); ++i)
{
(*i)->forwardPosition();
}
}
void
Kinematic::forwardVelocity()
{
for (::std::vector<Element*>::iterator i = this->elements.begin(); i != this->elements.end(); ++i)
{
(*i)->forwardVelocity();
}
}
const ::rl::math::Matrix&
Kinematic::getJacobian() const
{
return this->J;
}
const ::rl::math::Vector&
Kinematic::getJacobianDerivative() const
{
return this->Jdqd;
}
const ::rl::math::Matrix&
Kinematic::getJacobianInverse() const
{
return this->invJ;
}
bool
Kinematic::isSingular() const
{
return this->isSingular(this->J);
}
bool
Kinematic::isSingular(const ::rl::math::Matrix& J) const
{
::Eigen::JacobiSVD< ::rl::math::Matrix> svd(J);
return (::std::abs(svd.singularValues()(svd.singularValues().size() - 1)) > ::std::numeric_limits< ::rl::math::Real>::epsilon()) ? false : true;
}
void
Kinematic::update()
{
Metric::update();
this->invJ = ::rl::math::Matrix::Identity(this->getDof(), 6 * this->getOperationalDof());
this->J = ::rl::math::Matrix::Identity(6 * this->getOperationalDof(), this->getDof());
this->Jdqd = ::rl::math::Vector::Zero(6 * this->getOperationalDof());
}
}
}
<commit_msg>Fix Jacobian derivative world frame transformation<commit_after>//
// Copyright (c) 2009, Markus Rickert
// 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 <algorithm>
#include <stack>
#include <boost/graph/graphviz.hpp>
#include <rl/math/Quaternion.h>
#include <rl/math/Rotation.h>
#include <rl/math/Spatial.h>
#include <rl/math/Unit.h>
#include "Exception.h"
#include "Kinematic.h"
#include "Prismatic.h"
#include "Revolute.h"
namespace rl
{
namespace mdl
{
Kinematic::Kinematic() :
Metric(),
invJ(),
J(),
Jdqd()
{
}
Kinematic::~Kinematic()
{
}
void
Kinematic::calculateJacobian(const bool& inWorldFrame)
{
this->calculateJacobian(this->J, inWorldFrame);
}
void
Kinematic::calculateJacobian(::rl::math::Matrix& J, const bool& inWorldFrame)
{
assert(J.rows() == this->getOperationalDof() * 6);
assert(J.cols() == this->getDof());
::rl::math::Vector tmp(this->getDof());
for (::std::size_t i = 0; i < this->getDof(); ++i)
{
for (::std::size_t j = 0; j < this->getDof(); ++j)
{
tmp(j) = i == j ? 1 : 0;
}
this->setVelocity(tmp);
this->forwardVelocity();
for (::std::size_t j = 0; j < this->getOperationalDof(); ++j)
{
if (inWorldFrame)
{
J.block(j * 6, i, 3, 1) = this->getOperationalPosition(j).linear() * this->getOperationalVelocity(j).linear();
J.block(j * 6 + 3, i, 3, 1) = this->getOperationalPosition(j).linear() * this->getOperationalVelocity(j).angular();
}
else
{
J.block(j * 6, i, 3, 1) = this->getOperationalVelocity(j).linear();
J.block(j * 6 + 3, i, 3, 1) = this->getOperationalVelocity(j).angular();
}
}
}
}
void
Kinematic::calculateJacobianDerivative(const bool& inWorldFrame)
{
this->calculateJacobianDerivative(this->Jdqd, inWorldFrame);
}
void
Kinematic::calculateJacobianDerivative(::rl::math::Vector& Jdqd, const bool& inWorldFrame)
{
::rl::math::Vector tmp = ::rl::math::Vector::Zero(this->getDof());
this->setAcceleration(tmp);
this->forwardVelocity();
this->forwardAcceleration();
for (::std::size_t j = 0; j < this->getOperationalDof(); ++j)
{
if (inWorldFrame)
{
rl::math::Matrix33 wR = this->getOperationalVelocity(j).angular().cross33() * this->getOperationalPosition(j).linear();
Jdqd.segment(j * 6, 3) = this->getOperationalPosition(j).linear() * this->getOperationalAcceleration(j).linear() + wR * this->getOperationalVelocity(j).linear();
Jdqd.segment(j * 6 + 3, 3) = this->getOperationalPosition(j).linear() * this->getOperationalAcceleration(j).angular() + wR * this->getOperationalVelocity(j).angular();
}
else
{
Jdqd.segment(j * 6, 3) = this->getOperationalAcceleration(j).linear();
Jdqd.segment(j * 6 + 3, 3) = this->getOperationalAcceleration(j).angular();
}
}
}
void
Kinematic::calculateJacobianInverse(const ::rl::math::Real& lambda, const bool& doSvd)
{
this->calculateJacobianInverse(this->J, this->invJ, lambda, doSvd);
}
void
Kinematic::calculateJacobianInverse(const ::rl::math::Matrix& J, ::rl::math::Matrix& invJ, const ::rl::math::Real& lambda, const bool& doSvd) const
{
if (doSvd)
{
invJ.setZero();
::Eigen::JacobiSVD< ::rl::math::Matrix> svd(J, ::Eigen::ComputeFullU | ::Eigen::ComputeFullV);
::rl::math::Real wMin = svd.singularValues().minCoeff();
::rl::math::Real lambdaSqr = wMin < static_cast< ::rl::math::Real>(1.0e-9) ? (1 - ::std::pow((wMin / static_cast< ::rl::math::Real>(1.0e-9)), 2)) * ::std::pow(lambda, 2) : 0;
for (::std::ptrdiff_t i = 0; i < svd.nonzeroSingularValues(); ++i)
{
invJ.noalias() += (
svd.singularValues()(i) / (::std::pow(svd.singularValues()(i), 2) + lambdaSqr) *
svd.matrixV().col(i) * svd.matrixU().col(i).transpose()
);
}
}
else
{
invJ = J.transpose() * (
J * J.transpose() + ::std::pow(lambda, 2) *
::rl::math::Matrix::Identity(this->getOperationalDof() * 6, this->getOperationalDof() * 6)
).inverse();
}
}
::rl::math::Real
Kinematic::calculateManipulabilityMeasure() const
{
return calculateManipulabilityMeasure(this->J);
}
::rl::math::Real
Kinematic::calculateManipulabilityMeasure(const ::rl::math::Matrix& J) const
{
return ::std::sqrt((J * J.transpose()).determinant());
}
void
Kinematic::forwardAcceleration()
{
for (::std::vector<Element*>::iterator i = this->elements.begin(); i != this->elements.end(); ++i)
{
(*i)->forwardAcceleration();
}
}
void
Kinematic::forwardPosition()
{
for (::std::vector<Element*>::iterator i = this->elements.begin(); i != this->elements.end(); ++i)
{
(*i)->forwardPosition();
}
}
void
Kinematic::forwardVelocity()
{
for (::std::vector<Element*>::iterator i = this->elements.begin(); i != this->elements.end(); ++i)
{
(*i)->forwardVelocity();
}
}
const ::rl::math::Matrix&
Kinematic::getJacobian() const
{
return this->J;
}
const ::rl::math::Vector&
Kinematic::getJacobianDerivative() const
{
return this->Jdqd;
}
const ::rl::math::Matrix&
Kinematic::getJacobianInverse() const
{
return this->invJ;
}
bool
Kinematic::isSingular() const
{
return this->isSingular(this->J);
}
bool
Kinematic::isSingular(const ::rl::math::Matrix& J) const
{
::Eigen::JacobiSVD< ::rl::math::Matrix> svd(J);
return (::std::abs(svd.singularValues()(svd.singularValues().size() - 1)) > ::std::numeric_limits< ::rl::math::Real>::epsilon()) ? false : true;
}
void
Kinematic::update()
{
Metric::update();
this->invJ = ::rl::math::Matrix::Identity(this->getDof(), 6 * this->getOperationalDof());
this->J = ::rl::math::Matrix::Identity(6 * this->getOperationalDof(), this->getDof());
this->Jdqd = ::rl::math::Vector::Zero(6 * this->getOperationalDof());
}
}
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2008, Distributed Systems Architecture Group, Universidad */
/* Complutense de Madrid (dsa-research.org) */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#include "RequestManager.h"
#include "Nebula.h"
#include <cerrno>
#include <sys/signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
extern "C" void * rm_action_loop(void *arg)
{
RequestManager * rm;
if ( arg == 0 )
{
return 0;
}
Nebula::log("ReM",Log::INFO,"Request Manager started.");
rm = static_cast<RequestManager *>(arg);
rm->am.loop(0,0);
Nebula::log("ReM",Log::INFO,"Request Manager stopped.");
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
extern "C" void * rm_xml_server_loop(void *arg)
{
RequestManager * rm;
if ( arg == 0 )
{
return 0;
}
rm = static_cast<RequestManager *>(arg);
// Set cancel state for the thread
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,0);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,0);
//Start the server
rm->AbyssServer = new xmlrpc_c::serverAbyss(xmlrpc_c::serverAbyss::constrOpt()
.registryP(&rm->RequestManagerRegistry)
.logFileName(rm->xml_log_file)
.socketFd(rm->socket_fd));
rm->AbyssServer->run();
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int RequestManager::setup_socket()
{
int rc;
int yes = 1;
struct sockaddr_in rm_addr;
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if ( socket_fd == -1 )
{
ostringstream oss;
oss << "Can not open server socket: " << strerror(errno);
Nebula::log("ReM",Log::ERROR,oss);
return -1;
}
rc = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
if ( rc == -1 )
{
ostringstream oss;
oss << "Can not set socket options: " << strerror(errno);
Nebula::log("ReM",Log::ERROR,oss);
close(socket_fd);
return -1;
}
fcntl(socket_fd,F_SETFD,FD_CLOEXEC); // Close socket in MADs
rm_addr.sin_family = AF_INET;
rm_addr.sin_port = htons(port);
rm_addr.sin_addr.s_addr = INADDR_ANY;
rc = bind(socket_fd,(struct sockaddr *) &(rm_addr),sizeof(struct sockaddr));
if ( rc == -1)
{
ostringstream oss;
oss << "Can not bind to port " << port << " : " << strerror(errno);
Nebula::log("ReM",Log::ERROR,oss);
close(socket_fd);
return -1;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int RequestManager::start()
{
pthread_attr_t pattr;
ostringstream oss;
Nebula::log("ReM",Log::INFO,"Starting Request Manager...");
int rc = setup_socket();
if ( rc != 0 )
{
return -1;
}
register_xml_methods();
pthread_attr_init (&pattr);
pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);
pthread_create(&rm_thread,&pattr,rm_action_loop,(void *)this);
pthread_attr_init (&pattr);
pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);
oss << "Starting XML-RPC server, port " << port << " ...";
Nebula::log("ReM",Log::INFO,oss);
pthread_create(&rm_xml_server_thread,&pattr,rm_xml_server_loop,(void *)this);
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void RequestManager::do_action(
const string & action,
void * arg)
{
if (action == ACTION_FINALIZE)
{
Nebula::log("ReM",Log::INFO,"Stopping Request Manager...");
pthread_cancel(rm_xml_server_thread);
pthread_join(rm_xml_server_thread,0);
Nebula::log("ReM",Log::INFO,"XML-RPC server stopped.");
delete AbyssServer;
if ( socket_fd != -1 )
{
close(socket_fd);
}
}
else
{
ostringstream oss;
oss << "Unknown action name: " << action;
Nebula::log("ReM", Log::ERROR, oss);
}
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void RequestManager::register_xml_methods()
{
xmlrpc_c::methodPtr vm_allocate(new
RequestManager::VirtualMachineAllocate);
xmlrpc_c::methodPtr vm_deploy(new
RequestManager::VirtualMachineDeploy(vmpool,hpool));
xmlrpc_c::methodPtr vm_migrate(new
RequestManager::VirtualMachineMigrate(vmpool,hpool));
xmlrpc_c::methodPtr vm_action(new
RequestManager::VirtualMachineAction);
xmlrpc_c::methodPtr vm_info(new
RequestManager::VirtualMachineInfo(vmpool));
xmlrpc_c::methodPtr host_allocate(new
RequestManager::HostAllocate(hpool));
xmlrpc_c::methodPtr host_info(new
RequestManager::HostInfo(hpool));
xmlrpc_c::methodPtr host_delete(new
RequestManager::HostDelete(hpool));
xmlrpc_c::methodPtr host_enable(new
RequestManager::HostEnable(hpool));
xmlrpc_c::methodPtr vn_allocate(new
RequestManager::VirtualNetworkAllocate(vnpool));
xmlrpc_c::methodPtr vn_info(new
RequestManager::VirtualNetworkInfo(vnpool));
xmlrpc_c::methodPtr vn_delete(new
RequestManager::VirtualNetworkDelete(vnpool));
/* VM related methods */
RequestManagerRegistry.addMethod("one.vmallocate", vm_allocate);
RequestManagerRegistry.addMethod("one.vmdeploy", vm_deploy);
RequestManagerRegistry.addMethod("one.vmaction", vm_action);
RequestManagerRegistry.addMethod("one.vmmigrate", vm_migrate);
RequestManagerRegistry.addMethod("one.vmget_info", vm_info);
/* Host related methods*/
RequestManagerRegistry.addMethod("one.hostallocate", host_allocate);
RequestManagerRegistry.addMethod("one.hostinfo", host_info);
RequestManagerRegistry.addMethod("one.hostdelete", host_delete);
RequestManagerRegistry.addMethod("one.hostenable", host_enable);
/* Network related methods*/
RequestManagerRegistry.addMethod("one.vnallocate", vn_allocate);
RequestManagerRegistry.addMethod("one.vninfo", vn_info);
RequestManagerRegistry.addMethod("one.vndelete", vn_delete);
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
<commit_msg>Address #50 for OpenSuse 11<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2008, Distributed Systems Architecture Group, Universidad */
/* Complutense de Madrid (dsa-research.org) */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#include "RequestManager.h"
#include "Nebula.h"
#include <cerrno>
#include <sys/signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <cstring>
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
extern "C" void * rm_action_loop(void *arg)
{
RequestManager * rm;
if ( arg == 0 )
{
return 0;
}
Nebula::log("ReM",Log::INFO,"Request Manager started.");
rm = static_cast<RequestManager *>(arg);
rm->am.loop(0,0);
Nebula::log("ReM",Log::INFO,"Request Manager stopped.");
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
extern "C" void * rm_xml_server_loop(void *arg)
{
RequestManager * rm;
if ( arg == 0 )
{
return 0;
}
rm = static_cast<RequestManager *>(arg);
// Set cancel state for the thread
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,0);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,0);
//Start the server
rm->AbyssServer = new xmlrpc_c::serverAbyss(xmlrpc_c::serverAbyss::constrOpt()
.registryP(&rm->RequestManagerRegistry)
.logFileName(rm->xml_log_file)
.socketFd(rm->socket_fd));
rm->AbyssServer->run();
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int RequestManager::setup_socket()
{
int rc;
int yes = 1;
struct sockaddr_in rm_addr;
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if ( socket_fd == -1 )
{
ostringstream oss;
oss << "Can not open server socket: " << strerror(errno);
Nebula::log("ReM",Log::ERROR,oss);
return -1;
}
rc = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
if ( rc == -1 )
{
ostringstream oss;
oss << "Can not set socket options: " << strerror(errno);
Nebula::log("ReM",Log::ERROR,oss);
close(socket_fd);
return -1;
}
fcntl(socket_fd,F_SETFD,FD_CLOEXEC); // Close socket in MADs
rm_addr.sin_family = AF_INET;
rm_addr.sin_port = htons(port);
rm_addr.sin_addr.s_addr = INADDR_ANY;
rc = bind(socket_fd,(struct sockaddr *) &(rm_addr),sizeof(struct sockaddr));
if ( rc == -1)
{
ostringstream oss;
oss << "Can not bind to port " << port << " : " << strerror(errno);
Nebula::log("ReM",Log::ERROR,oss);
close(socket_fd);
return -1;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int RequestManager::start()
{
pthread_attr_t pattr;
ostringstream oss;
Nebula::log("ReM",Log::INFO,"Starting Request Manager...");
int rc = setup_socket();
if ( rc != 0 )
{
return -1;
}
register_xml_methods();
pthread_attr_init (&pattr);
pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);
pthread_create(&rm_thread,&pattr,rm_action_loop,(void *)this);
pthread_attr_init (&pattr);
pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);
oss << "Starting XML-RPC server, port " << port << " ...";
Nebula::log("ReM",Log::INFO,oss);
pthread_create(&rm_xml_server_thread,&pattr,rm_xml_server_loop,(void *)this);
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void RequestManager::do_action(
const string & action,
void * arg)
{
if (action == ACTION_FINALIZE)
{
Nebula::log("ReM",Log::INFO,"Stopping Request Manager...");
pthread_cancel(rm_xml_server_thread);
pthread_join(rm_xml_server_thread,0);
Nebula::log("ReM",Log::INFO,"XML-RPC server stopped.");
delete AbyssServer;
if ( socket_fd != -1 )
{
close(socket_fd);
}
}
else
{
ostringstream oss;
oss << "Unknown action name: " << action;
Nebula::log("ReM", Log::ERROR, oss);
}
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void RequestManager::register_xml_methods()
{
xmlrpc_c::methodPtr vm_allocate(new
RequestManager::VirtualMachineAllocate);
xmlrpc_c::methodPtr vm_deploy(new
RequestManager::VirtualMachineDeploy(vmpool,hpool));
xmlrpc_c::methodPtr vm_migrate(new
RequestManager::VirtualMachineMigrate(vmpool,hpool));
xmlrpc_c::methodPtr vm_action(new
RequestManager::VirtualMachineAction);
xmlrpc_c::methodPtr vm_info(new
RequestManager::VirtualMachineInfo(vmpool));
xmlrpc_c::methodPtr host_allocate(new
RequestManager::HostAllocate(hpool));
xmlrpc_c::methodPtr host_info(new
RequestManager::HostInfo(hpool));
xmlrpc_c::methodPtr host_delete(new
RequestManager::HostDelete(hpool));
xmlrpc_c::methodPtr host_enable(new
RequestManager::HostEnable(hpool));
xmlrpc_c::methodPtr vn_allocate(new
RequestManager::VirtualNetworkAllocate(vnpool));
xmlrpc_c::methodPtr vn_info(new
RequestManager::VirtualNetworkInfo(vnpool));
xmlrpc_c::methodPtr vn_delete(new
RequestManager::VirtualNetworkDelete(vnpool));
/* VM related methods */
RequestManagerRegistry.addMethod("one.vmallocate", vm_allocate);
RequestManagerRegistry.addMethod("one.vmdeploy", vm_deploy);
RequestManagerRegistry.addMethod("one.vmaction", vm_action);
RequestManagerRegistry.addMethod("one.vmmigrate", vm_migrate);
RequestManagerRegistry.addMethod("one.vmget_info", vm_info);
/* Host related methods*/
RequestManagerRegistry.addMethod("one.hostallocate", host_allocate);
RequestManagerRegistry.addMethod("one.hostinfo", host_info);
RequestManagerRegistry.addMethod("one.hostdelete", host_delete);
RequestManagerRegistry.addMethod("one.hostenable", host_enable);
/* Network related methods*/
RequestManagerRegistry.addMethod("one.vnallocate", vn_allocate);
RequestManagerRegistry.addMethod("one.vninfo", vn_info);
RequestManagerRegistry.addMethod("one.vndelete", vn_delete);
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
<|endoftext|> |
<commit_before>#pragma once
class hid_report {
public:
struct __attribute__((packed)) keyboard_input {
uint8_t modifiers;
uint8_t reserved;
uint8_t keys[6];
};
};
<commit_msg>add hid_report::keyboard_input constructor<commit_after>#pragma once
class hid_report {
public:
class __attribute__((packed)) keyboard_input {
public:
keyboard_input(void) : modifiers(0), reserved(0), keys{0} {}
uint8_t modifiers;
uint8_t reserved;
uint8_t keys[6];
};
};
<|endoftext|> |
<commit_before>//Copyright (c) 2016 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "sliceDataStorage.h"
#include "FffProcessor.h" //To create a mesh group with if none is provided.
#include "infill/SubDivCube.h" // For the destructor
namespace cura
{
Polygons& SliceLayerPart::getOwnInfillArea()
{
if (infill_area_own)
{
return *infill_area_own;
}
else
{
return infill_area;
}
}
Polygons SliceLayer::getOutlines(bool external_polys_only) const
{
Polygons ret;
getOutlines(ret, external_polys_only);
return ret;
}
void SliceLayer::getOutlines(Polygons& result, bool external_polys_only) const
{
for (const SliceLayerPart& part : parts)
{
if (external_polys_only)
{
result.add(const_cast<SliceLayerPart&>(part).outline.outerPolygon()); // TODO: make a const version of outerPolygon()
}
else
{
result.add(part.print_outline);
}
}
}
Polygons SliceLayer::getSecondOrInnermostWalls() const
{
Polygons ret;
getSecondOrInnermostWalls(ret);
return ret;
}
void SliceLayer::getSecondOrInnermostWalls(Polygons& layer_walls) const
{
for (const SliceLayerPart& part : parts)
{
// we want the 2nd inner walls
if (part.insets.size() >= 2) {
layer_walls.add(const_cast<SliceLayerPart&>(part).insets[1]); // TODO const cast!
continue;
}
// but we'll also take the inner wall if the 2nd doesn't exist
if (part.insets.size() == 1) {
layer_walls.add(const_cast<SliceLayerPart&>(part).insets[0]); // TODO const cast!
continue;
}
// offset_from_outlines was so large that it completely destroyed our isle,
// so we'll just use the regular outline
layer_walls.add(part.outline);
continue;
}
}
SliceMeshStorage::~SliceMeshStorage()
{
if (base_subdiv_cube)
{
delete base_subdiv_cube;
}
}
std::vector<RetractionConfig> SliceDataStorage::initializeRetractionConfigs()
{
std::vector<RetractionConfig> ret;
ret.resize(meshgroup->getExtruderCount()); // initializes with constructor RetractionConfig()
return ret;
}
std::vector<GCodePathConfig> SliceDataStorage::initializeTravelConfigs()
{
std::vector<GCodePathConfig> ret;
for (int extruder = 0; extruder < meshgroup->getExtruderCount(); extruder++)
{
travel_config_per_extruder.emplace_back(PrintFeatureType::MoveCombing);
}
return ret;
}
std::vector<GCodePathConfig> SliceDataStorage::initializeSkirtBrimConfigs()
{
std::vector<GCodePathConfig> ret;
for (int extruder = 0; extruder < meshgroup->getExtruderCount(); extruder++)
{
skirt_brim_config.emplace_back(PrintFeatureType::SkirtBrim);
}
return ret;
}
SliceDataStorage::SliceDataStorage(MeshGroup* meshgroup) : SettingsMessenger(meshgroup),
meshgroup(meshgroup != nullptr ? meshgroup : new MeshGroup(FffProcessor::getInstance())), //If no mesh group is provided, we roll our own.
print_layer_count(0),
retraction_config_per_extruder(initializeRetractionConfigs()),
extruder_switch_retraction_config_per_extruder(initializeRetractionConfigs()),
travel_config_per_extruder(initializeTravelConfigs()),
skirt_brim_config(initializeSkirtBrimConfigs()),
raft_base_config(PrintFeatureType::SupportInterface),
raft_interface_config(PrintFeatureType::Support),
raft_surface_config(PrintFeatureType::SupportInterface),
support_config(PrintFeatureType::Support),
support_skin_config(PrintFeatureType::SupportInterface),
max_print_height_second_to_last_extruder(-1),
primeTower(*this)
{
}
Polygons SliceDataStorage::getLayerOutlines(int layer_nr, bool include_helper_parts, bool external_polys_only) const
{
if (layer_nr < 0 && layer_nr < -Raft::getFillerLayerCount(*this))
{ // when processing raft
if (include_helper_parts)
{
if (external_polys_only)
{
std::vector<PolygonsPart> parts = raftOutline.splitIntoParts();
Polygons result;
for (PolygonsPart& part : parts)
{
result.add(part.outerPolygon());
}
return result;
}
else
{
return raftOutline;
}
}
else
{
return Polygons();
}
}
else
{
Polygons total;
if (layer_nr >= 0)
{
for (const SliceMeshStorage& mesh : meshes)
{
if (mesh.getSettingBoolean("infill_mesh") || mesh.getSettingBoolean("anti_overhang_mesh"))
{
continue;
}
const SliceLayer& layer = mesh.layers[layer_nr];
layer.getOutlines(total, external_polys_only);
if (const_cast<SliceMeshStorage&>(mesh).getSettingAsSurfaceMode("magic_mesh_surface_mode") != ESurfaceMode::NORMAL) // TODO: make all getSetting functions const??
{
total = total.unionPolygons(layer.openPolyLines.offsetPolyLine(100));
}
}
}
if (include_helper_parts)
{
if (support.generated)
{
total.add(support.supportLayers[std::max(0, layer_nr)].supportAreas);
total.add(support.supportLayers[std::max(0, layer_nr)].skin);
}
if (primeTower.enabled)
{
total.add(primeTower.ground_poly);
}
}
return total;
}
}
Polygons SliceDataStorage::getLayerSecondOrInnermostWalls(int layer_nr, bool include_helper_parts) const
{
if (layer_nr < 0 && layer_nr < -Raft::getFillerLayerCount(*this))
{ // when processing raft
if (include_helper_parts)
{
return raftOutline;
}
else
{
return Polygons();
}
}
else
{
Polygons total;
if (layer_nr >= 0)
{
for (const SliceMeshStorage& mesh : meshes)
{
const SliceLayer& layer = mesh.layers[layer_nr];
layer.getSecondOrInnermostWalls(total);
if (const_cast<SliceMeshStorage&>(mesh).getSettingAsSurfaceMode("magic_mesh_surface_mode") != ESurfaceMode::NORMAL) // TODO: make getSetting const? make settings.setting_values mapping mutable??
{
total = total.unionPolygons(layer.openPolyLines.offsetPolyLine(100));
}
}
}
if (include_helper_parts)
{
if (support.generated)
{
total.add(support.supportLayers[std::max(0, layer_nr)].supportAreas);
total.add(support.supportLayers[std::max(0, layer_nr)].skin);
}
if (primeTower.enabled)
{
total.add(primeTower.ground_poly);
}
}
return total;
}
}
std::vector<bool> SliceDataStorage::getExtrudersUsed() const
{
std::vector<bool> ret;
ret.resize(meshgroup->getExtruderCount(), false);
if (getSettingAsPlatformAdhesion("adhesion_type") != EPlatformAdhesion::NONE)
{
ret[getSettingAsIndex("adhesion_extruder_nr")] = true;
{ // process brim/skirt
for (int extr_nr = 0; extr_nr < meshgroup->getExtruderCount(); extr_nr++)
{
if (skirt_brim[extr_nr].size() > 0)
{
ret[extr_nr] = true;
continue;
}
}
}
}
// TODO: ooze shield, draft shield ..?
// support
// support is presupposed to be present...
ret[getSettingAsIndex("support_extruder_nr_layer_0")] = true;
ret[getSettingAsIndex("support_infill_extruder_nr")] = true;
ret[getSettingAsIndex("support_interface_extruder_nr")] = true;
// all meshes are presupposed to actually have content
for (const SliceMeshStorage& mesh : meshes)
{
if (!mesh.getSettingBoolean("anti_overhang_mesh")
&& !mesh.getSettingBoolean("support_mesh")
)
{
ret[mesh.getSettingAsIndex("extruder_nr")] = true;
}
}
return ret;
}
std::vector<bool> SliceDataStorage::getExtrudersUsed(int layer_nr) const
{
std::vector<bool> ret;
ret.resize(meshgroup->getExtruderCount(), false);
bool include_adhesion = true;
bool include_helper_parts = true;
bool include_models = true;
if (layer_nr < 0)
{
include_models = false;
if (layer_nr < -Raft::getFillerLayerCount(*this))
{
include_helper_parts = false;
}
else
{
layer_nr = 0; // because the helper parts are copied from the initial layer in the filler layer
include_adhesion = false;
}
}
else if (layer_nr > 0 || getSettingAsPlatformAdhesion("adhesion_type") == EPlatformAdhesion::RAFT)
{ // only include adhesion only for layers where platform adhesion actually occurs
// i.e. layers < 0 are for raft, layer 0 is for brim/skirt
include_adhesion = false;
}
if (include_adhesion)
{
ret[getSettingAsIndex("adhesion_extruder_nr")] = true;
{ // process brim/skirt
for (int extr_nr = 0; extr_nr < meshgroup->getExtruderCount(); extr_nr++)
{
if (skirt_brim[extr_nr].size() > 0)
{
ret[extr_nr] = true;
continue;
}
}
}
}
// TODO: ooze shield, draft shield ..?
if (include_helper_parts)
{
// support
if (layer_nr < int(support.supportLayers.size()))
{
const SupportLayer& support_layer = support.supportLayers[layer_nr];
if (layer_nr == 0)
{
if (support_layer.supportAreas.size() > 0)
{
ret[getSettingAsIndex("support_extruder_nr_layer_0")] = true;
}
}
else
{
if (support_layer.supportAreas.size() > 0)
{
ret[getSettingAsIndex("support_infill_extruder_nr")] = true;
}
}
if (support_layer.skin.size() > 0)
{
ret[getSettingAsIndex("support_interface_extruder_nr")] = true;
}
}
}
if (include_models)
{
for (const SliceMeshStorage& mesh : meshes)
{
if (layer_nr >= int(mesh.layers.size()))
{
continue;
}
const SliceLayer& layer = mesh.layers[layer_nr];
if (layer.parts.size() > 0)
{
ret[mesh.getSettingAsIndex("extruder_nr")] = true;
}
}
}
return ret;
}
} // namespace cura<commit_msg>fix: remove superfluous const_cast (CURA-3372)<commit_after>//Copyright (c) 2016 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "sliceDataStorage.h"
#include "FffProcessor.h" //To create a mesh group with if none is provided.
#include "infill/SubDivCube.h" // For the destructor
namespace cura
{
Polygons& SliceLayerPart::getOwnInfillArea()
{
if (infill_area_own)
{
return *infill_area_own;
}
else
{
return infill_area;
}
}
Polygons SliceLayer::getOutlines(bool external_polys_only) const
{
Polygons ret;
getOutlines(ret, external_polys_only);
return ret;
}
void SliceLayer::getOutlines(Polygons& result, bool external_polys_only) const
{
for (const SliceLayerPart& part : parts)
{
if (external_polys_only)
{
result.add(const_cast<SliceLayerPart&>(part).outline.outerPolygon()); // TODO: make a const version of outerPolygon()
}
else
{
result.add(part.print_outline);
}
}
}
Polygons SliceLayer::getSecondOrInnermostWalls() const
{
Polygons ret;
getSecondOrInnermostWalls(ret);
return ret;
}
void SliceLayer::getSecondOrInnermostWalls(Polygons& layer_walls) const
{
for (const SliceLayerPart& part : parts)
{
// we want the 2nd inner walls
if (part.insets.size() >= 2) {
layer_walls.add(const_cast<SliceLayerPart&>(part).insets[1]); // TODO const cast!
continue;
}
// but we'll also take the inner wall if the 2nd doesn't exist
if (part.insets.size() == 1) {
layer_walls.add(const_cast<SliceLayerPart&>(part).insets[0]); // TODO const cast!
continue;
}
// offset_from_outlines was so large that it completely destroyed our isle,
// so we'll just use the regular outline
layer_walls.add(part.outline);
continue;
}
}
SliceMeshStorage::~SliceMeshStorage()
{
if (base_subdiv_cube)
{
delete base_subdiv_cube;
}
}
std::vector<RetractionConfig> SliceDataStorage::initializeRetractionConfigs()
{
std::vector<RetractionConfig> ret;
ret.resize(meshgroup->getExtruderCount()); // initializes with constructor RetractionConfig()
return ret;
}
std::vector<GCodePathConfig> SliceDataStorage::initializeTravelConfigs()
{
std::vector<GCodePathConfig> ret;
for (int extruder = 0; extruder < meshgroup->getExtruderCount(); extruder++)
{
travel_config_per_extruder.emplace_back(PrintFeatureType::MoveCombing);
}
return ret;
}
std::vector<GCodePathConfig> SliceDataStorage::initializeSkirtBrimConfigs()
{
std::vector<GCodePathConfig> ret;
for (int extruder = 0; extruder < meshgroup->getExtruderCount(); extruder++)
{
skirt_brim_config.emplace_back(PrintFeatureType::SkirtBrim);
}
return ret;
}
SliceDataStorage::SliceDataStorage(MeshGroup* meshgroup) : SettingsMessenger(meshgroup),
meshgroup(meshgroup != nullptr ? meshgroup : new MeshGroup(FffProcessor::getInstance())), //If no mesh group is provided, we roll our own.
print_layer_count(0),
retraction_config_per_extruder(initializeRetractionConfigs()),
extruder_switch_retraction_config_per_extruder(initializeRetractionConfigs()),
travel_config_per_extruder(initializeTravelConfigs()),
skirt_brim_config(initializeSkirtBrimConfigs()),
raft_base_config(PrintFeatureType::SupportInterface),
raft_interface_config(PrintFeatureType::Support),
raft_surface_config(PrintFeatureType::SupportInterface),
support_config(PrintFeatureType::Support),
support_skin_config(PrintFeatureType::SupportInterface),
max_print_height_second_to_last_extruder(-1),
primeTower(*this)
{
}
Polygons SliceDataStorage::getLayerOutlines(int layer_nr, bool include_helper_parts, bool external_polys_only) const
{
if (layer_nr < 0 && layer_nr < -Raft::getFillerLayerCount(*this))
{ // when processing raft
if (include_helper_parts)
{
if (external_polys_only)
{
std::vector<PolygonsPart> parts = raftOutline.splitIntoParts();
Polygons result;
for (PolygonsPart& part : parts)
{
result.add(part.outerPolygon());
}
return result;
}
else
{
return raftOutline;
}
}
else
{
return Polygons();
}
}
else
{
Polygons total;
if (layer_nr >= 0)
{
for (const SliceMeshStorage& mesh : meshes)
{
if (mesh.getSettingBoolean("infill_mesh") || mesh.getSettingBoolean("anti_overhang_mesh"))
{
continue;
}
const SliceLayer& layer = mesh.layers[layer_nr];
layer.getOutlines(total, external_polys_only);
if (const_cast<SliceMeshStorage&>(mesh).getSettingAsSurfaceMode("magic_mesh_surface_mode") != ESurfaceMode::NORMAL) // TODO: make all getSetting functions const??
{
total = total.unionPolygons(layer.openPolyLines.offsetPolyLine(100));
}
}
}
if (include_helper_parts)
{
if (support.generated)
{
total.add(support.supportLayers[std::max(0, layer_nr)].supportAreas);
total.add(support.supportLayers[std::max(0, layer_nr)].skin);
}
if (primeTower.enabled)
{
total.add(primeTower.ground_poly);
}
}
return total;
}
}
Polygons SliceDataStorage::getLayerSecondOrInnermostWalls(int layer_nr, bool include_helper_parts) const
{
if (layer_nr < 0 && layer_nr < -Raft::getFillerLayerCount(*this))
{ // when processing raft
if (include_helper_parts)
{
return raftOutline;
}
else
{
return Polygons();
}
}
else
{
Polygons total;
if (layer_nr >= 0)
{
for (const SliceMeshStorage& mesh : meshes)
{
const SliceLayer& layer = mesh.layers[layer_nr];
layer.getSecondOrInnermostWalls(total);
if (mesh.getSettingAsSurfaceMode("magic_mesh_surface_mode") != ESurfaceMode::NORMAL)
{
total = total.unionPolygons(layer.openPolyLines.offsetPolyLine(100));
}
}
}
if (include_helper_parts)
{
if (support.generated)
{
total.add(support.supportLayers[std::max(0, layer_nr)].supportAreas);
total.add(support.supportLayers[std::max(0, layer_nr)].skin);
}
if (primeTower.enabled)
{
total.add(primeTower.ground_poly);
}
}
return total;
}
}
std::vector<bool> SliceDataStorage::getExtrudersUsed() const
{
std::vector<bool> ret;
ret.resize(meshgroup->getExtruderCount(), false);
if (getSettingAsPlatformAdhesion("adhesion_type") != EPlatformAdhesion::NONE)
{
ret[getSettingAsIndex("adhesion_extruder_nr")] = true;
{ // process brim/skirt
for (int extr_nr = 0; extr_nr < meshgroup->getExtruderCount(); extr_nr++)
{
if (skirt_brim[extr_nr].size() > 0)
{
ret[extr_nr] = true;
continue;
}
}
}
}
// TODO: ooze shield, draft shield ..?
// support
// support is presupposed to be present...
ret[getSettingAsIndex("support_extruder_nr_layer_0")] = true;
ret[getSettingAsIndex("support_infill_extruder_nr")] = true;
ret[getSettingAsIndex("support_interface_extruder_nr")] = true;
// all meshes are presupposed to actually have content
for (const SliceMeshStorage& mesh : meshes)
{
if (!mesh.getSettingBoolean("anti_overhang_mesh")
&& !mesh.getSettingBoolean("support_mesh")
)
{
ret[mesh.getSettingAsIndex("extruder_nr")] = true;
}
}
return ret;
}
std::vector<bool> SliceDataStorage::getExtrudersUsed(int layer_nr) const
{
std::vector<bool> ret;
ret.resize(meshgroup->getExtruderCount(), false);
bool include_adhesion = true;
bool include_helper_parts = true;
bool include_models = true;
if (layer_nr < 0)
{
include_models = false;
if (layer_nr < -Raft::getFillerLayerCount(*this))
{
include_helper_parts = false;
}
else
{
layer_nr = 0; // because the helper parts are copied from the initial layer in the filler layer
include_adhesion = false;
}
}
else if (layer_nr > 0 || getSettingAsPlatformAdhesion("adhesion_type") == EPlatformAdhesion::RAFT)
{ // only include adhesion only for layers where platform adhesion actually occurs
// i.e. layers < 0 are for raft, layer 0 is for brim/skirt
include_adhesion = false;
}
if (include_adhesion)
{
ret[getSettingAsIndex("adhesion_extruder_nr")] = true;
{ // process brim/skirt
for (int extr_nr = 0; extr_nr < meshgroup->getExtruderCount(); extr_nr++)
{
if (skirt_brim[extr_nr].size() > 0)
{
ret[extr_nr] = true;
continue;
}
}
}
}
// TODO: ooze shield, draft shield ..?
if (include_helper_parts)
{
// support
if (layer_nr < int(support.supportLayers.size()))
{
const SupportLayer& support_layer = support.supportLayers[layer_nr];
if (layer_nr == 0)
{
if (support_layer.supportAreas.size() > 0)
{
ret[getSettingAsIndex("support_extruder_nr_layer_0")] = true;
}
}
else
{
if (support_layer.supportAreas.size() > 0)
{
ret[getSettingAsIndex("support_infill_extruder_nr")] = true;
}
}
if (support_layer.skin.size() > 0)
{
ret[getSettingAsIndex("support_interface_extruder_nr")] = true;
}
}
}
if (include_models)
{
for (const SliceMeshStorage& mesh : meshes)
{
if (layer_nr >= int(mesh.layers.size()))
{
continue;
}
const SliceLayer& layer = mesh.layers[layer_nr];
if (layer.parts.size() > 0)
{
ret[mesh.getSettingAsIndex("extruder_nr")] = true;
}
}
}
return ret;
}
} // namespace cura<|endoftext|> |
<commit_before>//Copyright (c) 2016 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "sliceDataStorage.h"
#include "FffProcessor.h" //To create a mesh group with if none is provided.
#include "infill/SubDivCube.h" // For the destructor
namespace cura
{
Polygons& SliceLayerPart::getOwnInfillArea()
{
if (infill_area_own)
{
return *infill_area_own;
}
else
{
return infill_area;
}
}
Polygons SliceLayer::getOutlines(bool external_polys_only) const
{
Polygons ret;
getOutlines(ret, external_polys_only);
return ret;
}
void SliceLayer::getOutlines(Polygons& result, bool external_polys_only) const
{
for (const SliceLayerPart& part : parts)
{
if (external_polys_only)
{
result.add(const_cast<SliceLayerPart&>(part).outline.outerPolygon()); // TODO: make a const version of outerPolygon()
}
else
{
result.add(part.print_outline);
}
}
}
Polygons SliceLayer::getSecondOrInnermostWalls() const
{
Polygons ret;
getSecondOrInnermostWalls(ret);
return ret;
}
void SliceLayer::getSecondOrInnermostWalls(Polygons& layer_walls) const
{
for (const SliceLayerPart& part : parts)
{
// we want the 2nd inner walls
if (part.insets.size() >= 2) {
layer_walls.add(const_cast<SliceLayerPart&>(part).insets[1]); // TODO const cast!
continue;
}
// but we'll also take the inner wall if the 2nd doesn't exist
if (part.insets.size() == 1) {
layer_walls.add(const_cast<SliceLayerPart&>(part).insets[0]); // TODO const cast!
continue;
}
// offset_from_outlines was so large that it completely destroyed our isle,
// so we'll just use the regular outline
layer_walls.add(part.outline);
continue;
}
}
SliceMeshStorage::~SliceMeshStorage()
{
if (base_subdiv_cube)
{
delete base_subdiv_cube;
}
}
std::vector<RetractionConfig> SliceDataStorage::initializeRetractionConfigs()
{
std::vector<RetractionConfig> ret;
ret.resize(meshgroup->getExtruderCount()); // initializes with constructor RetractionConfig()
return ret;
}
std::vector<GCodePathConfig> SliceDataStorage::initializeTravelConfigs()
{
std::vector<GCodePathConfig> ret;
for (int extruder = 0; extruder < meshgroup->getExtruderCount(); extruder++)
{
travel_config_per_extruder.emplace_back(PrintFeatureType::MoveCombing);
}
return ret;
}
std::vector<GCodePathConfig> SliceDataStorage::initializeSkirtBrimConfigs()
{
std::vector<GCodePathConfig> ret;
for (int extruder = 0; extruder < meshgroup->getExtruderCount(); extruder++)
{
skirt_brim_config.emplace_back(PrintFeatureType::SkirtBrim);
}
return ret;
}
SliceDataStorage::SliceDataStorage(MeshGroup* meshgroup) : SettingsMessenger(meshgroup),
meshgroup(meshgroup != nullptr ? meshgroup : new MeshGroup(FffProcessor::getInstance())), //If no mesh group is provided, we roll our own.
print_layer_count(0),
retraction_config_per_extruder(initializeRetractionConfigs()),
extruder_switch_retraction_config_per_extruder(initializeRetractionConfigs()),
travel_config_per_extruder(initializeTravelConfigs()),
skirt_brim_config(initializeSkirtBrimConfigs()),
raft_base_config(PrintFeatureType::SupportInterface),
raft_interface_config(PrintFeatureType::Support),
raft_surface_config(PrintFeatureType::SupportInterface),
support_config(PrintFeatureType::Support),
support_skin_config(PrintFeatureType::SupportInterface),
max_print_height_second_to_last_extruder(-1),
primeTower(*this)
{
}
Polygons SliceDataStorage::getLayerOutlines(int layer_nr, bool include_helper_parts, bool external_polys_only) const
{
if (layer_nr < 0 && layer_nr < -Raft::getFillerLayerCount(*this))
{ // when processing raft
if (include_helper_parts)
{
if (external_polys_only)
{
std::vector<PolygonsPart> parts = raftOutline.splitIntoParts();
Polygons result;
for (PolygonsPart& part : parts)
{
result.add(part.outerPolygon());
}
return result;
}
else
{
return raftOutline;
}
}
else
{
return Polygons();
}
}
else
{
Polygons total;
if (layer_nr >= 0)
{
for (const SliceMeshStorage& mesh : meshes)
{
if (mesh.getSettingBoolean("infill_mesh") || mesh.getSettingBoolean("anti_overhang_mesh"))
{
continue;
}
const SliceLayer& layer = mesh.layers[layer_nr];
layer.getOutlines(total, external_polys_only);
if (const_cast<SliceMeshStorage&>(mesh).getSettingAsSurfaceMode("magic_mesh_surface_mode") != ESurfaceMode::NORMAL) // TODO: make all getSetting functions const??
{
total = total.unionPolygons(layer.openPolyLines.offsetPolyLine(100));
}
}
}
if (include_helper_parts)
{
if (support.generated)
{
total.add(support.supportLayers[std::max(0, layer_nr)].supportAreas);
total.add(support.supportLayers[std::max(0, layer_nr)].skin);
}
if (primeTower.enabled)
{
total.add(primeTower.ground_poly);
}
}
return total;
}
}
Polygons SliceDataStorage::getLayerSecondOrInnermostWalls(int layer_nr, bool include_helper_parts) const
{
if (layer_nr < 0 && layer_nr < -Raft::getFillerLayerCount(*this))
{ // when processing raft
if (include_helper_parts)
{
return raftOutline;
}
else
{
return Polygons();
}
}
else
{
Polygons total;
if (layer_nr >= 0)
{
for (const SliceMeshStorage& mesh : meshes)
{
const SliceLayer& layer = mesh.layers[layer_nr];
layer.getSecondOrInnermostWalls(total);
if (mesh.getSettingAsSurfaceMode("magic_mesh_surface_mode") != ESurfaceMode::NORMAL)
{
total = total.unionPolygons(layer.openPolyLines.offsetPolyLine(100));
}
}
}
if (include_helper_parts)
{
if (support.generated)
{
total.add(support.supportLayers[std::max(0, layer_nr)].supportAreas);
total.add(support.supportLayers[std::max(0, layer_nr)].skin);
}
if (primeTower.enabled)
{
total.add(primeTower.ground_poly);
}
}
return total;
}
}
std::vector<bool> SliceDataStorage::getExtrudersUsed() const
{
std::vector<bool> ret;
ret.resize(meshgroup->getExtruderCount(), false);
if (getSettingAsPlatformAdhesion("adhesion_type") != EPlatformAdhesion::NONE)
{
ret[getSettingAsIndex("adhesion_extruder_nr")] = true;
{ // process brim/skirt
for (int extr_nr = 0; extr_nr < meshgroup->getExtruderCount(); extr_nr++)
{
if (skirt_brim[extr_nr].size() > 0)
{
ret[extr_nr] = true;
continue;
}
}
}
}
// TODO: ooze shield, draft shield ..?
// support
// support is presupposed to be present...
ret[getSettingAsIndex("support_extruder_nr_layer_0")] = true;
ret[getSettingAsIndex("support_infill_extruder_nr")] = true;
ret[getSettingAsIndex("support_interface_extruder_nr")] = true;
// all meshes are presupposed to actually have content
for (const SliceMeshStorage& mesh : meshes)
{
if (!mesh.getSettingBoolean("anti_overhang_mesh")
&& !mesh.getSettingBoolean("support_mesh")
)
{
ret[mesh.getSettingAsIndex("extruder_nr")] = true;
}
}
return ret;
}
std::vector<bool> SliceDataStorage::getExtrudersUsed(int layer_nr) const
{
std::vector<bool> ret;
ret.resize(meshgroup->getExtruderCount(), false);
bool include_adhesion = true;
bool include_helper_parts = true;
bool include_models = true;
if (layer_nr < 0)
{
include_models = false;
if (layer_nr < -Raft::getFillerLayerCount(*this))
{
include_helper_parts = false;
}
else
{
layer_nr = 0; // because the helper parts are copied from the initial layer in the filler layer
include_adhesion = false;
}
}
else if (layer_nr > 0 || getSettingAsPlatformAdhesion("adhesion_type") == EPlatformAdhesion::RAFT)
{ // only include adhesion only for layers where platform adhesion actually occurs
// i.e. layers < 0 are for raft, layer 0 is for brim/skirt
include_adhesion = false;
}
if (include_adhesion)
{
ret[getSettingAsIndex("adhesion_extruder_nr")] = true;
{ // process brim/skirt
for (int extr_nr = 0; extr_nr < meshgroup->getExtruderCount(); extr_nr++)
{
if (skirt_brim[extr_nr].size() > 0)
{
ret[extr_nr] = true;
continue;
}
}
}
}
// TODO: ooze shield, draft shield ..?
if (include_helper_parts)
{
// support
if (layer_nr < int(support.supportLayers.size()))
{
const SupportLayer& support_layer = support.supportLayers[layer_nr];
if (layer_nr == 0)
{
if (support_layer.supportAreas.size() > 0)
{
ret[getSettingAsIndex("support_extruder_nr_layer_0")] = true;
}
}
else
{
if (support_layer.supportAreas.size() > 0)
{
ret[getSettingAsIndex("support_infill_extruder_nr")] = true;
}
}
if (support_layer.skin.size() > 0)
{
ret[getSettingAsIndex("support_interface_extruder_nr")] = true;
}
}
}
if (include_models)
{
for (const SliceMeshStorage& mesh : meshes)
{
if (layer_nr >= int(mesh.layers.size()))
{
continue;
}
const SliceLayer& layer = mesh.layers[layer_nr];
if (layer.parts.size() > 0)
{
ret[mesh.getSettingAsIndex("extruder_nr")] = true;
}
}
}
return ret;
}
} // namespace cura<commit_msg>Only set support extruders to be used if support is enabled<commit_after>//Copyright (c) 2016 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "sliceDataStorage.h"
#include "FffProcessor.h" //To create a mesh group with if none is provided.
#include "infill/SubDivCube.h" // For the destructor
namespace cura
{
Polygons& SliceLayerPart::getOwnInfillArea()
{
if (infill_area_own)
{
return *infill_area_own;
}
else
{
return infill_area;
}
}
Polygons SliceLayer::getOutlines(bool external_polys_only) const
{
Polygons ret;
getOutlines(ret, external_polys_only);
return ret;
}
void SliceLayer::getOutlines(Polygons& result, bool external_polys_only) const
{
for (const SliceLayerPart& part : parts)
{
if (external_polys_only)
{
result.add(const_cast<SliceLayerPart&>(part).outline.outerPolygon()); // TODO: make a const version of outerPolygon()
}
else
{
result.add(part.print_outline);
}
}
}
Polygons SliceLayer::getSecondOrInnermostWalls() const
{
Polygons ret;
getSecondOrInnermostWalls(ret);
return ret;
}
void SliceLayer::getSecondOrInnermostWalls(Polygons& layer_walls) const
{
for (const SliceLayerPart& part : parts)
{
// we want the 2nd inner walls
if (part.insets.size() >= 2) {
layer_walls.add(const_cast<SliceLayerPart&>(part).insets[1]); // TODO const cast!
continue;
}
// but we'll also take the inner wall if the 2nd doesn't exist
if (part.insets.size() == 1) {
layer_walls.add(const_cast<SliceLayerPart&>(part).insets[0]); // TODO const cast!
continue;
}
// offset_from_outlines was so large that it completely destroyed our isle,
// so we'll just use the regular outline
layer_walls.add(part.outline);
continue;
}
}
SliceMeshStorage::~SliceMeshStorage()
{
if (base_subdiv_cube)
{
delete base_subdiv_cube;
}
}
std::vector<RetractionConfig> SliceDataStorage::initializeRetractionConfigs()
{
std::vector<RetractionConfig> ret;
ret.resize(meshgroup->getExtruderCount()); // initializes with constructor RetractionConfig()
return ret;
}
std::vector<GCodePathConfig> SliceDataStorage::initializeTravelConfigs()
{
std::vector<GCodePathConfig> ret;
for (int extruder = 0; extruder < meshgroup->getExtruderCount(); extruder++)
{
travel_config_per_extruder.emplace_back(PrintFeatureType::MoveCombing);
}
return ret;
}
std::vector<GCodePathConfig> SliceDataStorage::initializeSkirtBrimConfigs()
{
std::vector<GCodePathConfig> ret;
for (int extruder = 0; extruder < meshgroup->getExtruderCount(); extruder++)
{
skirt_brim_config.emplace_back(PrintFeatureType::SkirtBrim);
}
return ret;
}
SliceDataStorage::SliceDataStorage(MeshGroup* meshgroup) : SettingsMessenger(meshgroup),
meshgroup(meshgroup != nullptr ? meshgroup : new MeshGroup(FffProcessor::getInstance())), //If no mesh group is provided, we roll our own.
print_layer_count(0),
retraction_config_per_extruder(initializeRetractionConfigs()),
extruder_switch_retraction_config_per_extruder(initializeRetractionConfigs()),
travel_config_per_extruder(initializeTravelConfigs()),
skirt_brim_config(initializeSkirtBrimConfigs()),
raft_base_config(PrintFeatureType::SupportInterface),
raft_interface_config(PrintFeatureType::Support),
raft_surface_config(PrintFeatureType::SupportInterface),
support_config(PrintFeatureType::Support),
support_skin_config(PrintFeatureType::SupportInterface),
max_print_height_second_to_last_extruder(-1),
primeTower(*this)
{
}
Polygons SliceDataStorage::getLayerOutlines(int layer_nr, bool include_helper_parts, bool external_polys_only) const
{
if (layer_nr < 0 && layer_nr < -Raft::getFillerLayerCount(*this))
{ // when processing raft
if (include_helper_parts)
{
if (external_polys_only)
{
std::vector<PolygonsPart> parts = raftOutline.splitIntoParts();
Polygons result;
for (PolygonsPart& part : parts)
{
result.add(part.outerPolygon());
}
return result;
}
else
{
return raftOutline;
}
}
else
{
return Polygons();
}
}
else
{
Polygons total;
if (layer_nr >= 0)
{
for (const SliceMeshStorage& mesh : meshes)
{
if (mesh.getSettingBoolean("infill_mesh") || mesh.getSettingBoolean("anti_overhang_mesh"))
{
continue;
}
const SliceLayer& layer = mesh.layers[layer_nr];
layer.getOutlines(total, external_polys_only);
if (const_cast<SliceMeshStorage&>(mesh).getSettingAsSurfaceMode("magic_mesh_surface_mode") != ESurfaceMode::NORMAL) // TODO: make all getSetting functions const??
{
total = total.unionPolygons(layer.openPolyLines.offsetPolyLine(100));
}
}
}
if (include_helper_parts)
{
if (support.generated)
{
total.add(support.supportLayers[std::max(0, layer_nr)].supportAreas);
total.add(support.supportLayers[std::max(0, layer_nr)].skin);
}
if (primeTower.enabled)
{
total.add(primeTower.ground_poly);
}
}
return total;
}
}
Polygons SliceDataStorage::getLayerSecondOrInnermostWalls(int layer_nr, bool include_helper_parts) const
{
if (layer_nr < 0 && layer_nr < -Raft::getFillerLayerCount(*this))
{ // when processing raft
if (include_helper_parts)
{
return raftOutline;
}
else
{
return Polygons();
}
}
else
{
Polygons total;
if (layer_nr >= 0)
{
for (const SliceMeshStorage& mesh : meshes)
{
const SliceLayer& layer = mesh.layers[layer_nr];
layer.getSecondOrInnermostWalls(total);
if (mesh.getSettingAsSurfaceMode("magic_mesh_surface_mode") != ESurfaceMode::NORMAL)
{
total = total.unionPolygons(layer.openPolyLines.offsetPolyLine(100));
}
}
}
if (include_helper_parts)
{
if (support.generated)
{
total.add(support.supportLayers[std::max(0, layer_nr)].supportAreas);
total.add(support.supportLayers[std::max(0, layer_nr)].skin);
}
if (primeTower.enabled)
{
total.add(primeTower.ground_poly);
}
}
return total;
}
}
std::vector<bool> SliceDataStorage::getExtrudersUsed() const
{
std::vector<bool> ret;
ret.resize(meshgroup->getExtruderCount(), false);
if (getSettingAsPlatformAdhesion("adhesion_type") != EPlatformAdhesion::NONE)
{
ret[getSettingAsIndex("adhesion_extruder_nr")] = true;
{ // process brim/skirt
for (int extr_nr = 0; extr_nr < meshgroup->getExtruderCount(); extr_nr++)
{
if (skirt_brim[extr_nr].size() > 0)
{
ret[extr_nr] = true;
continue;
}
}
}
}
// TODO: ooze shield, draft shield ..?
// support
// support is presupposed to be present...
if (getSettingBoolean("support_enable"))
{
ret[getSettingAsIndex("support_extruder_nr_layer_0")] = true;
ret[getSettingAsIndex("support_infill_extruder_nr")] = true;
if (getSettingBoolean("support_interface_enable"))
{
ret[getSettingAsIndex("support_interface_extruder_nr")] = true;
}
}
// all meshes are presupposed to actually have content
for (const SliceMeshStorage& mesh : meshes)
{
if (!mesh.getSettingBoolean("anti_overhang_mesh")
&& !mesh.getSettingBoolean("support_mesh")
)
{
ret[mesh.getSettingAsIndex("extruder_nr")] = true;
}
}
return ret;
}
std::vector<bool> SliceDataStorage::getExtrudersUsed(int layer_nr) const
{
std::vector<bool> ret;
ret.resize(meshgroup->getExtruderCount(), false);
bool include_adhesion = true;
bool include_helper_parts = true;
bool include_models = true;
if (layer_nr < 0)
{
include_models = false;
if (layer_nr < -Raft::getFillerLayerCount(*this))
{
include_helper_parts = false;
}
else
{
layer_nr = 0; // because the helper parts are copied from the initial layer in the filler layer
include_adhesion = false;
}
}
else if (layer_nr > 0 || getSettingAsPlatformAdhesion("adhesion_type") == EPlatformAdhesion::RAFT)
{ // only include adhesion only for layers where platform adhesion actually occurs
// i.e. layers < 0 are for raft, layer 0 is for brim/skirt
include_adhesion = false;
}
if (include_adhesion)
{
ret[getSettingAsIndex("adhesion_extruder_nr")] = true;
{ // process brim/skirt
for (int extr_nr = 0; extr_nr < meshgroup->getExtruderCount(); extr_nr++)
{
if (skirt_brim[extr_nr].size() > 0)
{
ret[extr_nr] = true;
continue;
}
}
}
}
// TODO: ooze shield, draft shield ..?
if (include_helper_parts)
{
// support
if (layer_nr < int(support.supportLayers.size()))
{
const SupportLayer& support_layer = support.supportLayers[layer_nr];
if (layer_nr == 0)
{
if (support_layer.supportAreas.size() > 0)
{
ret[getSettingAsIndex("support_extruder_nr_layer_0")] = true;
}
}
else
{
if (support_layer.supportAreas.size() > 0)
{
ret[getSettingAsIndex("support_infill_extruder_nr")] = true;
}
}
if (support_layer.skin.size() > 0)
{
ret[getSettingAsIndex("support_interface_extruder_nr")] = true;
}
}
}
if (include_models)
{
for (const SliceMeshStorage& mesh : meshes)
{
if (layer_nr >= int(mesh.layers.size()))
{
continue;
}
const SliceLayer& layer = mesh.layers[layer_nr];
if (layer.parts.size() > 0)
{
ret[mesh.getSettingAsIndex("extruder_nr")] = true;
}
}
}
return ret;
}
} // namespace cura<|endoftext|> |
<commit_before>#include "deploy.h"
#include <boost/filesystem.hpp>
#include <boost/intrusive_ptr.hpp>
#include "authenticate.h"
#include "logging/logging.h"
#include "ostree_object.h"
#include "rate_controller.h"
#include "request_pool.h"
#include "treehub_server.h"
#include "utilities/utils.h"
bool CheckPoolState(const OSTreeObject::ptr &root_object, const RequestPool &request_pool) {
switch (request_pool.run_mode()) {
case RunMode::kWalkTree:
case RunMode::kPushTree:
return !request_pool.is_stopped() && !request_pool.is_idle();
case RunMode::kDefault:
case RunMode::kDryRun:
default:
return root_object->is_on_server() != PresenceOnServer::kObjectPresent && !request_pool.is_stopped();
}
}
bool UploadToTreehub(const OSTreeRepo::ptr &src_repo, const ServerCredentials &push_credentials,
const OSTreeHash &ostree_commit, const std::string &cacerts, const RunMode mode,
const int max_curl_requests) {
TreehubServer push_server;
assert(max_curl_requests > 0);
if (authenticate(cacerts, push_credentials, push_server) != EXIT_SUCCESS) {
LOG_FATAL << "Authentication failed";
return false;
}
OSTreeObject::ptr root_object;
try {
root_object = src_repo->GetObject(ostree_commit, OstreeObjectType::OSTREE_OBJECT_TYPE_COMMIT);
} catch (const OSTreeObjectMissing &error) {
LOG_FATAL << "OSTree commit " << ostree_commit << " was not found in src repository";
return false;
}
RequestPool request_pool(push_server, max_curl_requests, mode);
// Add commit object to the queue.
request_pool.AddQuery(root_object);
// Main curl event loop.
// request_pool takes care of holding number of outstanding requests below.
// OSTreeObject::CurlDone() adds new requests to the pool and stops the pool
// on error.
do {
request_pool.Loop();
} while (CheckPoolState(root_object, request_pool));
if (root_object->is_on_server() == PresenceOnServer::kObjectPresent) {
if (mode == RunMode::kDefault || mode == RunMode::kPushTree) {
LOG_INFO << "Upload to Treehub complete after " << request_pool.total_requests_made() << " requests";
} else {
LOG_INFO << "Dry run. No objects uploaded.";
}
} else {
LOG_ERROR << "One or more errors while pushing";
}
return root_object->is_on_server() == PresenceOnServer::kObjectPresent;
}
bool OfflineSignRepo(const ServerCredentials &push_credentials, const std::string &name, const OSTreeHash &hash,
const std::string &hardwareids) {
const boost::filesystem::path local_repo{"./tuf/aktualizr"};
// OTA-682: Do NOT keep the local tuf directory around in case the user tries
// a different set of push credentials.
if (boost::filesystem::is_directory(local_repo)) {
boost::filesystem::remove_all(local_repo);
}
std::string init_cmd("garage-sign init --repo aktualizr --credentials ");
if (system((init_cmd + push_credentials.GetPathOnDisk().string()).c_str()) != 0) {
LOG_ERROR << "Could not initilaize tuf repo for sign";
return false;
}
if (system("garage-sign targets pull --repo aktualizr") != 0) {
LOG_ERROR << "Could not pull targets";
return false;
}
std::string cmd("garage-sign targets add --repo aktualizr --format OSTREE --length 0 --url \"https://example.com/\"");
cmd += " --name " + name + " --version " + hash.string() + " --sha256 " + hash.string();
cmd += " --hardwareids " + hardwareids;
if (system(cmd.c_str()) != 0) {
LOG_ERROR << "Could not add targets";
return false;
}
LOG_INFO << "Signing...\n";
if (system("garage-sign targets sign --key-name targets --repo aktualizr") != 0) {
LOG_ERROR << "Could not sign targets";
return false;
}
if (system("garage-sign targets push --repo aktualizr") != 0) {
LOG_ERROR << "Could not push signed repo";
return false;
}
boost::filesystem::remove_all(local_repo);
LOG_INFO << "Success";
return true;
}
bool PushRootRef(const ServerCredentials &push_credentials, const OSTreeRef &ref, const std::string &cacerts,
const RunMode mode) {
if (push_credentials.CanSignOffline()) {
// In general, this is the wrong thing. We should be using offline signing
// if private key material is present in credentials.zip
LOG_WARNING << "Pushing by refname despite that credentials.zip can be used to sign offline.";
}
TreehubServer push_server;
if (authenticate(cacerts, push_credentials, push_server) != EXIT_SUCCESS) {
LOG_FATAL << "Authentication failed";
return false;
}
if (mode == RunMode::kDefault || mode == RunMode::kPushTree) {
CurlEasyWrapper easy_handle;
curlEasySetoptWrapper(easy_handle.get(), CURLOPT_VERBOSE, get_curlopt_verbose());
ref.PushRef(push_server, easy_handle.get());
CURLcode err = curl_easy_perform(easy_handle.get());
if (err != 0u) {
LOG_ERROR << "Error pushing root ref: " << curl_easy_strerror(err);
return false;
}
long rescode; // NOLINT(google-runtime-int)
curl_easy_getinfo(easy_handle.get(), CURLINFO_RESPONSE_CODE, &rescode);
if (rescode != 200) {
LOG_ERROR << "Error pushing root ref, got " << rescode << " HTTP response";
return false;
}
}
return true;
}
<commit_msg>OTA-2418: Remove example.com URL from automated garage-sign usage<commit_after>#include "deploy.h"
#include <boost/filesystem.hpp>
#include <boost/intrusive_ptr.hpp>
#include "authenticate.h"
#include "logging/logging.h"
#include "ostree_object.h"
#include "rate_controller.h"
#include "request_pool.h"
#include "treehub_server.h"
#include "utilities/utils.h"
bool CheckPoolState(const OSTreeObject::ptr &root_object, const RequestPool &request_pool) {
switch (request_pool.run_mode()) {
case RunMode::kWalkTree:
case RunMode::kPushTree:
return !request_pool.is_stopped() && !request_pool.is_idle();
case RunMode::kDefault:
case RunMode::kDryRun:
default:
return root_object->is_on_server() != PresenceOnServer::kObjectPresent && !request_pool.is_stopped();
}
}
bool UploadToTreehub(const OSTreeRepo::ptr &src_repo, const ServerCredentials &push_credentials,
const OSTreeHash &ostree_commit, const std::string &cacerts, const RunMode mode,
const int max_curl_requests) {
TreehubServer push_server;
assert(max_curl_requests > 0);
if (authenticate(cacerts, push_credentials, push_server) != EXIT_SUCCESS) {
LOG_FATAL << "Authentication failed";
return false;
}
OSTreeObject::ptr root_object;
try {
root_object = src_repo->GetObject(ostree_commit, OstreeObjectType::OSTREE_OBJECT_TYPE_COMMIT);
} catch (const OSTreeObjectMissing &error) {
LOG_FATAL << "OSTree commit " << ostree_commit << " was not found in src repository";
return false;
}
RequestPool request_pool(push_server, max_curl_requests, mode);
// Add commit object to the queue.
request_pool.AddQuery(root_object);
// Main curl event loop.
// request_pool takes care of holding number of outstanding requests below.
// OSTreeObject::CurlDone() adds new requests to the pool and stops the pool
// on error.
do {
request_pool.Loop();
} while (CheckPoolState(root_object, request_pool));
if (root_object->is_on_server() == PresenceOnServer::kObjectPresent) {
if (mode == RunMode::kDefault || mode == RunMode::kPushTree) {
LOG_INFO << "Upload to Treehub complete after " << request_pool.total_requests_made() << " requests";
} else {
LOG_INFO << "Dry run. No objects uploaded.";
}
} else {
LOG_ERROR << "One or more errors while pushing";
}
return root_object->is_on_server() == PresenceOnServer::kObjectPresent;
}
bool OfflineSignRepo(const ServerCredentials &push_credentials, const std::string &name, const OSTreeHash &hash,
const std::string &hardwareids) {
const boost::filesystem::path local_repo{"./tuf/aktualizr"};
// OTA-682: Do NOT keep the local tuf directory around in case the user tries
// a different set of push credentials.
if (boost::filesystem::is_directory(local_repo)) {
boost::filesystem::remove_all(local_repo);
}
std::string init_cmd("garage-sign init --repo aktualizr --credentials ");
if (system((init_cmd + push_credentials.GetPathOnDisk().string()).c_str()) != 0) {
LOG_ERROR << "Could not initilaize tuf repo for sign";
return false;
}
if (system("garage-sign targets pull --repo aktualizr") != 0) {
LOG_ERROR << "Could not pull targets";
return false;
}
std::string cmd("garage-sign targets add --repo aktualizr --format OSTREE --length 0");
cmd += " --name " + name + " --version " + hash.string() + " --sha256 " + hash.string();
cmd += " --hardwareids " + hardwareids;
if (system(cmd.c_str()) != 0) {
LOG_ERROR << "Could not add targets";
return false;
}
LOG_INFO << "Signing...\n";
if (system("garage-sign targets sign --key-name targets --repo aktualizr") != 0) {
LOG_ERROR << "Could not sign targets";
return false;
}
if (system("garage-sign targets push --repo aktualizr") != 0) {
LOG_ERROR << "Could not push signed repo";
return false;
}
boost::filesystem::remove_all(local_repo);
LOG_INFO << "Success";
return true;
}
bool PushRootRef(const ServerCredentials &push_credentials, const OSTreeRef &ref, const std::string &cacerts,
const RunMode mode) {
if (push_credentials.CanSignOffline()) {
// In general, this is the wrong thing. We should be using offline signing
// if private key material is present in credentials.zip
LOG_WARNING << "Pushing by refname despite that credentials.zip can be used to sign offline.";
}
TreehubServer push_server;
if (authenticate(cacerts, push_credentials, push_server) != EXIT_SUCCESS) {
LOG_FATAL << "Authentication failed";
return false;
}
if (mode == RunMode::kDefault || mode == RunMode::kPushTree) {
CurlEasyWrapper easy_handle;
curlEasySetoptWrapper(easy_handle.get(), CURLOPT_VERBOSE, get_curlopt_verbose());
ref.PushRef(push_server, easy_handle.get());
CURLcode err = curl_easy_perform(easy_handle.get());
if (err != 0u) {
LOG_ERROR << "Error pushing root ref: " << curl_easy_strerror(err);
return false;
}
long rescode; // NOLINT(google-runtime-int)
curl_easy_getinfo(easy_handle.get(), CURLINFO_RESPONSE_CODE, &rescode);
if (rescode != 200) {
LOG_ERROR << "Error pushing root ref, got " << rescode << " HTTP response";
return false;
}
}
return true;
}
<|endoftext|> |
<commit_before>// File: tao_unittests.cc
// Author: Tom Roeder <tmroeder@google.com>
//
// Description: Unit tests for TPMTao and SoftTao.
//
// Copyright (c) 2013, Google Inc. 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 "tao/tao.h"
#include <gflags/gflags.h>
#include <gtest/gtest.h>
#include "tao/attestation.h"
#include "tao/soft_tao.h"
#include "tao/tpm_tao.h"
#include "tao/util.h"
using namespace tao;
DEFINE_string(aik_blob_file, "/home/tmroeder/src/fileProxy/src/apps/aikblob",
"The blob for an AIK loaded in the TPM");
template <typename T>
class TaoTest : public ::testing::Test {
protected:
virtual void Setup(scoped_ptr<TPMTao> *tao) {
string blob;
ASSERT_TRUE(ReadFileToString(FLAGS_aik_blob_file, &blob));
tao->reset(new TPMTao(blob, list<int>{17, 18}));
ASSERT_TRUE(tao->get()->Init());
}
virtual void Setup(scoped_ptr<SoftTao> *tao) {
string blob;
ASSERT_TRUE(ReadFileToString(FLAGS_aik_blob_file, &blob));
tao->reset(new SoftTao());
ASSERT_TRUE(tao->get()->Init());
}
virtual void SetUp() {
Setup(&tao_);
}
scoped_ptr<T> tao_;
};
typedef ::testing::Types<TPMTao, SoftTao> TaoTypes;
TYPED_TEST_CASE(TaoTest, TaoTypes);
TYPED_TEST(TaoTest, SealUnsealTest) {
string bytes("Test bytes for sealing");
string sealed;
string seal_policy = Tao::SealPolicyDefault;
EXPECT_TRUE(this->tao_->Seal(bytes, seal_policy, &sealed));
string unsealed, unseal_policy;
EXPECT_TRUE(this->tao_->Unseal(sealed, &unsealed, &unseal_policy));
EXPECT_EQ(unsealed, bytes);
EXPECT_EQ(seal_policy, unseal_policy);
}
TYPED_TEST(TaoTest, AttestTest) {
Statement s;
s.set_delegate("Key(\"..stuff..\")");
string attestation;
ASSERT_TRUE(this->tao_->Attest(s, &attestation));
Statement s2;
ASSERT_TRUE(ValidateAttestation(attestation, &s2));
EXPECT_EQ(s.delegate(), s2.delegate());
string name;
ASSERT_TRUE(this->tao_->GetTaoName(&name));
EXPECT_NE("", name);
EXPECT_EQ(s2.issuer(), name);
}
TYPED_TEST(TaoTest, RandomTest) {
string bytes;
ASSERT_TRUE(this->tao_->GetRandomBytes(4, &bytes));
ASSERT_EQ(4, bytes.size());
EXPECT_FALSE(bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0 &&
bytes[3] == 0);
}
TYPED_TEST(TaoTest, ExtendTest) {
string name, ename;
ASSERT_TRUE(this->tao_->GetTaoName(&name));
EXPECT_NE("", name);
// TODO(kwalsh) implement extend for TPM
if (name.substr(0, 3) != "TPM") {
ASSERT_TRUE(this->tao_->ExtendTaoName("Test1::Test2"));
ASSERT_TRUE(this->tao_->GetTaoName(&ename));
EXPECT_EQ(name+"::"+"Test1::Test2", ename);
}
}
<commit_msg>uniform uppercase<commit_after>// File: tao_unittests.cc
// Author: Tom Roeder <tmroeder@google.com>
//
// Description: Unit tests for TPMTao and SoftTao.
//
// Copyright (c) 2013, Google Inc. 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 "tao/tao.h"
#include <gflags/gflags.h>
#include <gtest/gtest.h>
#include "tao/attestation.h"
#include "tao/soft_tao.h"
#include "tao/tpm_tao.h"
#include "tao/util.h"
using namespace tao;
DEFINE_string(aik_blob_file, "/home/tmroeder/src/fileProxy/src/apps/aikblob",
"The blob for an AIK loaded in the TPM");
template <typename T>
class TaoTest : public ::testing::Test {
protected:
virtual void SetUp(scoped_ptr<TPMTao> *tao) {
string blob;
ASSERT_TRUE(ReadFileToString(FLAGS_aik_blob_file, &blob));
tao->reset(new TPMTao(blob, list<int>{17, 18}));
ASSERT_TRUE(tao->get()->Init());
}
virtual void SetUp(scoped_ptr<SoftTao> *tao) {
string blob;
ASSERT_TRUE(ReadFileToString(FLAGS_aik_blob_file, &blob));
tao->reset(new SoftTao());
ASSERT_TRUE(tao->get()->Init());
}
virtual void SetUp() {
SetUp(&tao_);
}
scoped_ptr<T> tao_;
};
typedef ::testing::Types<TPMTao, SoftTao> TaoTypes;
TYPED_TEST_CASE(TaoTest, TaoTypes);
TYPED_TEST(TaoTest, SealUnsealTest) {
string bytes("Test bytes for sealing");
string sealed;
string seal_policy = Tao::SealPolicyDefault;
EXPECT_TRUE(this->tao_->Seal(bytes, seal_policy, &sealed));
string unsealed, unseal_policy;
EXPECT_TRUE(this->tao_->Unseal(sealed, &unsealed, &unseal_policy));
EXPECT_EQ(unsealed, bytes);
EXPECT_EQ(seal_policy, unseal_policy);
}
TYPED_TEST(TaoTest, AttestTest) {
Statement s;
s.set_delegate("Key(\"..stuff..\")");
string attestation;
ASSERT_TRUE(this->tao_->Attest(s, &attestation));
Statement s2;
ASSERT_TRUE(ValidateAttestation(attestation, &s2));
EXPECT_EQ(s.delegate(), s2.delegate());
string name;
ASSERT_TRUE(this->tao_->GetTaoName(&name));
EXPECT_NE("", name);
EXPECT_EQ(s2.issuer(), name);
}
TYPED_TEST(TaoTest, RandomTest) {
string bytes;
ASSERT_TRUE(this->tao_->GetRandomBytes(4, &bytes));
ASSERT_EQ(4, bytes.size());
EXPECT_FALSE(bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0 &&
bytes[3] == 0);
}
TYPED_TEST(TaoTest, ExtendTest) {
string name, ename;
ASSERT_TRUE(this->tao_->GetTaoName(&name));
EXPECT_NE("", name);
// TODO(kwalsh) implement extend for TPM
if (name.substr(0, 3) != "TPM") {
ASSERT_TRUE(this->tao_->ExtendTaoName("Test1::Test2"));
ASSERT_TRUE(this->tao_->GetTaoName(&ename));
EXPECT_EQ(name+"::"+"Test1::Test2", ename);
}
}
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen 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 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
template<typename MatrixType> void basicStuff(const MatrixType& m)
{
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
int rows = m.rows();
int cols = m.cols();
// this test relies a lot on Random.h, and there's not much more that we can do
// to test it, hence I consider that we will have tested Random.h
MatrixType m1 = MatrixType::Random(rows, cols),
m2 = MatrixType::Random(rows, cols),
m3(rows, cols),
mzero = MatrixType::Zero(rows, cols),
identity = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>
::Identity(rows, rows),
square = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>::Random(rows, rows);
VectorType v1 = VectorType::Random(rows),
v2 = VectorType::Random(rows),
vzero = VectorType::Zero(rows);
Scalar x = ei_random<Scalar>();
int r = ei_random<int>(0, rows-1),
c = ei_random<int>(0, cols-1);
m1.coeffRef(r,c) = x;
VERIFY_IS_APPROX(x, m1.coeff(r,c));
m1(r,c) = x;
VERIFY_IS_APPROX(x, m1(r,c));
v1.coeffRef(r) = x;
VERIFY_IS_APPROX(x, v1.coeff(r));
v1(r) = x;
VERIFY_IS_APPROX(x, v1(r));
v1[r] = x;
VERIFY_IS_APPROX(x, v1[r]);
VERIFY_IS_APPROX( v1, v1);
VERIFY_IS_NOT_APPROX( v1, 2*v1);
VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1);
if(NumTraits<Scalar>::HasFloatingPoint)
VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1.norm());
VERIFY_IS_NOT_MUCH_SMALLER_THAN(v1, v1);
VERIFY_IS_APPROX( vzero, v1-v1);
VERIFY_IS_APPROX( m1, m1);
VERIFY_IS_NOT_APPROX( m1, 2*m1);
VERIFY_IS_MUCH_SMALLER_THAN( mzero, m1);
VERIFY_IS_NOT_MUCH_SMALLER_THAN(m1, m1);
VERIFY_IS_APPROX( mzero, m1-m1);
// always test operator() on each read-only expression class,
// in order to check const-qualifiers.
// indeed, if an expression class (here Zero) is meant to be read-only,
// hence has no _write() method, the corresponding MatrixBase method (here zero())
// should return a const-qualified object so that it is the const-qualified
// operator() that gets called, which in turn calls _read().
VERIFY_IS_MUCH_SMALLER_THAN(MatrixType::Zero(rows,cols)(r,c), static_cast<Scalar>(1));
// now test copying a row-vector into a (column-)vector and conversely.
square.col(r) = square.row(r).eval();
Matrix<Scalar, 1, MatrixType::RowsAtCompileTime> rv(rows);
Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> cv(rows);
rv = square.row(r);
cv = square.col(r);
VERIFY_IS_APPROX(rv, cv.transpose());
if(cols!=1 && rows!=1 && MatrixType::SizeAtCompileTime!=Dynamic)
{
VERIFY_RAISES_ASSERT(m1 = (m2.block(0,0, rows-1, cols-1)));
}
VERIFY_IS_APPROX(m3 = m1,m1);
MatrixType m4;
VERIFY_IS_APPROX(m4 = m1,m1);
m3.real() = m1.real();
VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), static_cast<const MatrixType&>(m1).real());
VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), m1.real());
}
template<typename MatrixType> void basicStuffComplex(const MatrixType& m)
{
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<RealScalar, MatrixType::RowsAtCompileTime, MatrixType::ColsAtCompileTime> RealMatrixType;
int rows = m.rows();
int cols = m.cols();
Scalar s1 = ei_random<Scalar>(),
s2 = ei_random<Scalar>();
VERIFY(ei_real(s1)==ei_real_ref(s1));
VERIFY(ei_imag(s1)==ei_imag_ref(s1));
ei_real_ref(s1) = ei_real(s2);
ei_imag_ref(s1) = ei_imag(s2);
VERIFY(s1==s2);
RealMatrixType rm1 = RealMatrixType::Random(rows,cols),
rm2 = RealMatrixType::Random(rows,cols);
MatrixType cm(rows,cols);
cm.real() = rm1;
cm.imag() = rm2;
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).real(), rm1);
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).imag(), rm2);
cm.real().setZero();
VERIFY(static_cast<const MatrixType&>(cm).real().isZero());
VERIFY(!static_cast<const MatrixType&>(cm).imag().isZero());
}
void casting()
{
Matrix4f m = Matrix4f::Random(), m2;
Matrix4d n = m.cast<double>();
VERIFY(m.isApprox(n.cast<float>()));
m2 = m.cast<float>(); // check the specialization when NewType == Type
VERIFY(m.isApprox(m2));
}
void test_basicstuff()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( basicStuff(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( basicStuff(Matrix4d()) );
CALL_SUBTEST_3( basicStuff(MatrixXcf(3, 3)) );
CALL_SUBTEST_4( basicStuff(MatrixXi(8, 12)) );
CALL_SUBTEST_5( basicStuff(MatrixXcd(20, 20)) );
CALL_SUBTEST_6( basicStuff(Matrix<float, 100, 100>()) );
CALL_SUBTEST_7( basicStuff(Matrix<long double,Dynamic,Dynamic>(10,10)) );
CALL_SUBTEST_3( basicStuffComplex(MatrixXcf(21, 17)) );
CALL_SUBTEST_5( basicStuffComplex(MatrixXcd(2, 3)) );
}
CALL_SUBTEST_2(casting());
}
<commit_msg>unit tests for == / != operators<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen 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 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
template<typename MatrixType> void basicStuff(const MatrixType& m)
{
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
int rows = m.rows();
int cols = m.cols();
// this test relies a lot on Random.h, and there's not much more that we can do
// to test it, hence I consider that we will have tested Random.h
MatrixType m1 = MatrixType::Random(rows, cols),
m2 = MatrixType::Random(rows, cols),
m3(rows, cols),
mzero = MatrixType::Zero(rows, cols),
identity = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>
::Identity(rows, rows),
square = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>::Random(rows, rows);
VectorType v1 = VectorType::Random(rows),
v2 = VectorType::Random(rows),
vzero = VectorType::Zero(rows);
Scalar x = ei_random<Scalar>();
int r = ei_random<int>(0, rows-1),
c = ei_random<int>(0, cols-1);
m1.coeffRef(r,c) = x;
VERIFY_IS_APPROX(x, m1.coeff(r,c));
m1(r,c) = x;
VERIFY_IS_APPROX(x, m1(r,c));
v1.coeffRef(r) = x;
VERIFY_IS_APPROX(x, v1.coeff(r));
v1(r) = x;
VERIFY_IS_APPROX(x, v1(r));
v1[r] = x;
VERIFY_IS_APPROX(x, v1[r]);
VERIFY_IS_APPROX( v1, v1);
VERIFY_IS_NOT_APPROX( v1, 2*v1);
VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1);
if(NumTraits<Scalar>::HasFloatingPoint)
VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1.norm());
VERIFY_IS_NOT_MUCH_SMALLER_THAN(v1, v1);
VERIFY_IS_APPROX( vzero, v1-v1);
VERIFY_IS_APPROX( m1, m1);
VERIFY_IS_NOT_APPROX( m1, 2*m1);
VERIFY_IS_MUCH_SMALLER_THAN( mzero, m1);
VERIFY_IS_NOT_MUCH_SMALLER_THAN(m1, m1);
VERIFY_IS_APPROX( mzero, m1-m1);
// always test operator() on each read-only expression class,
// in order to check const-qualifiers.
// indeed, if an expression class (here Zero) is meant to be read-only,
// hence has no _write() method, the corresponding MatrixBase method (here zero())
// should return a const-qualified object so that it is the const-qualified
// operator() that gets called, which in turn calls _read().
VERIFY_IS_MUCH_SMALLER_THAN(MatrixType::Zero(rows,cols)(r,c), static_cast<Scalar>(1));
// now test copying a row-vector into a (column-)vector and conversely.
square.col(r) = square.row(r).eval();
Matrix<Scalar, 1, MatrixType::RowsAtCompileTime> rv(rows);
Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> cv(rows);
rv = square.row(r);
cv = square.col(r);
VERIFY_IS_APPROX(rv, cv.transpose());
if(cols!=1 && rows!=1 && MatrixType::SizeAtCompileTime!=Dynamic)
{
VERIFY_RAISES_ASSERT(m1 = (m2.block(0,0, rows-1, cols-1)));
}
VERIFY_IS_APPROX(m3 = m1,m1);
MatrixType m4;
VERIFY_IS_APPROX(m4 = m1,m1);
m3.real() = m1.real();
VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), static_cast<const MatrixType&>(m1).real());
VERIFY_IS_APPROX(static_cast<const MatrixType&>(m3).real(), m1.real());
// check == / != operators
VERIFY(m1==m1);
VERIFY(m1!=m2);
VERIFY(!(m1==m2));
VERIFY(!(m1!=m1));
m1 = m2;
VERIFY(m1==m2);
VERIFY(!(m1!=m2));
}
template<typename MatrixType> void basicStuffComplex(const MatrixType& m)
{
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<RealScalar, MatrixType::RowsAtCompileTime, MatrixType::ColsAtCompileTime> RealMatrixType;
int rows = m.rows();
int cols = m.cols();
Scalar s1 = ei_random<Scalar>(),
s2 = ei_random<Scalar>();
VERIFY(ei_real(s1)==ei_real_ref(s1));
VERIFY(ei_imag(s1)==ei_imag_ref(s1));
ei_real_ref(s1) = ei_real(s2);
ei_imag_ref(s1) = ei_imag(s2);
VERIFY(s1==s2);
RealMatrixType rm1 = RealMatrixType::Random(rows,cols),
rm2 = RealMatrixType::Random(rows,cols);
MatrixType cm(rows,cols);
cm.real() = rm1;
cm.imag() = rm2;
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).real(), rm1);
VERIFY_IS_APPROX(static_cast<const MatrixType&>(cm).imag(), rm2);
cm.real().setZero();
VERIFY(static_cast<const MatrixType&>(cm).real().isZero());
VERIFY(!static_cast<const MatrixType&>(cm).imag().isZero());
}
void casting()
{
Matrix4f m = Matrix4f::Random(), m2;
Matrix4d n = m.cast<double>();
VERIFY(m.isApprox(n.cast<float>()));
m2 = m.cast<float>(); // check the specialization when NewType == Type
VERIFY(m.isApprox(m2));
}
void test_basicstuff()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( basicStuff(Matrix<float, 1, 1>()) );
CALL_SUBTEST_2( basicStuff(Matrix4d()) );
CALL_SUBTEST_3( basicStuff(MatrixXcf(3, 3)) );
CALL_SUBTEST_4( basicStuff(MatrixXi(8, 12)) );
CALL_SUBTEST_5( basicStuff(MatrixXcd(20, 20)) );
CALL_SUBTEST_6( basicStuff(Matrix<float, 100, 100>()) );
CALL_SUBTEST_7( basicStuff(Matrix<long double,Dynamic,Dynamic>(10,10)) );
CALL_SUBTEST_3( basicStuffComplex(MatrixXcf(21, 17)) );
CALL_SUBTEST_5( basicStuffComplex(MatrixXcd(2, 3)) );
}
CALL_SUBTEST_2(casting());
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <string>
#include <cpr.h>
#include "multipart.h"
#include "server.h"
static Server* server = new Server();
auto base = server->GetBaseUrl();
TEST(UrlEncodedPostTests, UrlPostSingleTest) {
auto url = Url{base + "/url_post.html"};
auto response = cpr::Post(url, Payload{{"x", "5"}});
auto expected_text = std::string{"{\n"
" \"x\": 5\n"
"}"};
EXPECT_EQ(expected_text, response.text);
EXPECT_EQ(url, response.url);
EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
EXPECT_EQ(201, response.status_code);
}
TEST(UrlEncodedPostTests, UrlPostManyTest) {
auto url = Url{base + "/url_post.html"};
auto response = cpr::Post(url, Payload{{"x", 5}, {"y", 13}});
auto expected_text = std::string{"{\n"
" \"x\": 5,\n"
" \"y\": 13,\n"
" \"sum\": 18\n"
"}"};
EXPECT_EQ(expected_text, response.text);
EXPECT_EQ(url, response.url);
EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
EXPECT_EQ(201, response.status_code);
}
TEST(UrlEncodedPostTests, UrlPostBadHostTest) {
auto url = Url{"http://bad_host/"};
auto response = cpr::Post(url, Payload{{"hello", "world"}});
EXPECT_EQ(std::string{}, response.text);
EXPECT_EQ(url, response.url);
EXPECT_EQ(std::string{}, response.header["content-type"]);
EXPECT_EQ(0, response.status_code);
}
TEST(UrlEncodedPostTests, FormPostSingleTest) {
auto url = Url{base + "/form_post.html"};
auto response = cpr::Post(url, Multipart{{"x", 5}});
auto expected_text = std::string{"{\n"
" \"x\": 5\n"
"}"};
EXPECT_EQ(expected_text, response.text);
EXPECT_EQ(url, response.url);
EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
EXPECT_EQ(201, response.status_code);
}
TEST(UrlEncodedPostTests, FormPostManyTest) {
auto url = Url{base + "/form_post.html"};
auto response = cpr::Post(url, Multipart{{"x", 5}, {"y", 13}});
auto expected_text = std::string{"{\n"
" \"x\": 5,\n"
" \"y\": 13,\n"
" \"sum\": 18\n"
"}"};
EXPECT_EQ(expected_text, response.text);
EXPECT_EQ(url, response.url);
EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
EXPECT_EQ(201, response.status_code);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
::testing::AddGlobalTestEnvironment(server);
return RUN_ALL_TESTS();
}
<commit_msg>Increase test coverage of post methods Closes #17<commit_after>#include <gtest/gtest.h>
#include <cstdio>
#include <fstream>
#include <string>
#include <cpr.h>
#include "multipart.h"
#include "server.h"
static Server* server = new Server();
auto base = server->GetBaseUrl();
TEST(UrlEncodedPostTests, UrlPostSingleTest) {
auto url = Url{base + "/url_post.html"};
auto response = cpr::Post(url, Payload{{"x", "5"}});
auto expected_text = std::string{"{\n"
" \"x\": 5\n"
"}"};
EXPECT_EQ(expected_text, response.text);
EXPECT_EQ(url, response.url);
EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
EXPECT_EQ(201, response.status_code);
}
TEST(UrlEncodedPostTests, UrlPostEncodeTest) {
auto url = Url{base + "/url_post.html"};
auto response = cpr::Post(url, Payload{{"x", "hello world!!~"}});
auto expected_text = std::string{"{\n"
" \"x\": hello world!!~\n"
"}"};
EXPECT_EQ(expected_text, response.text);
EXPECT_EQ(url, response.url);
EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
EXPECT_EQ(201, response.status_code);
}
TEST(UrlEncodedPostTests, UrlPostManyTest) {
auto url = Url{base + "/url_post.html"};
auto response = cpr::Post(url, Payload{{"x", 5}, {"y", 13}});
auto expected_text = std::string{"{\n"
" \"x\": 5,\n"
" \"y\": 13,\n"
" \"sum\": 18\n"
"}"};
EXPECT_EQ(expected_text, response.text);
EXPECT_EQ(url, response.url);
EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
EXPECT_EQ(201, response.status_code);
}
TEST(UrlEncodedPostTests, UrlPostBadHostTest) {
auto url = Url{"http://bad_host/"};
auto response = cpr::Post(url, Payload{{"hello", "world"}});
EXPECT_EQ(std::string{}, response.text);
EXPECT_EQ(url, response.url);
EXPECT_EQ(std::string{}, response.header["content-type"]);
EXPECT_EQ(0, response.status_code);
}
TEST(UrlEncodedPostTests, FormPostSingleTest) {
auto url = Url{base + "/form_post.html"};
auto response = cpr::Post(url, Multipart{{"x", 5}});
auto expected_text = std::string{"{\n"
" \"x\": 5\n"
"}"};
EXPECT_EQ(expected_text, response.text);
EXPECT_EQ(url, response.url);
EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
EXPECT_EQ(201, response.status_code);
}
TEST(UrlEncodedPostTests, FormPostFileTest) {
auto filename = std::string{"test_file"};
auto content = std::string{"hello world"};
std::ofstream test_file;
test_file.open(filename);
test_file << content;
test_file.close();
auto url = Url{base + "/form_post.html"};
auto response = cpr::Post(url, Multipart{{"x", File{filename}}});
auto expected_text = std::string{"{\n"
" \"x\": " + content + "\n"
"}"};
std::remove(filename.data());
EXPECT_EQ(expected_text, response.text);
EXPECT_EQ(url, response.url);
EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
EXPECT_EQ(201, response.status_code);
}
TEST(UrlEncodedPostTests, FormPostManyTest) {
auto url = Url{base + "/form_post.html"};
auto response = cpr::Post(url, Multipart{{"x", 5}, {"y", 13}});
auto expected_text = std::string{"{\n"
" \"x\": 5,\n"
" \"y\": 13,\n"
" \"sum\": 18\n"
"}"};
EXPECT_EQ(expected_text, response.text);
EXPECT_EQ(url, response.url);
EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
EXPECT_EQ(201, response.status_code);
}
TEST(UrlEncodedPostTests, FormPostContentTypeTest) {
auto url = Url{base + "/form_post.html"};
auto response = cpr::Post(url, Multipart{{"x", 5, "application/number"}});
auto expected_text = std::string{"{\n"
" \"x\": 5\n"
"}"};
EXPECT_EQ(expected_text, response.text);
EXPECT_EQ(url, response.url);
EXPECT_EQ(std::string{"application/json"}, response.header["content-type"]);
EXPECT_EQ(201, response.status_code);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
::testing::AddGlobalTestEnvironment(server);
return RUN_ALL_TESTS();
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.