text stringlengths 54 60.6k |
|---|
<commit_before>/* cuda_wrapper/cuda_wrapper.hpp
*
* Copyright (C) 2013 Felix Höfling
* Copyright (C) 2007 Peter Colberg
*
* This file is part of HALMD.
*
* HALMD 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 <http://www.gnu.org/licenses/>.
*/
/*
* CUDA runtime API wrapper classes
*/
#ifndef CUDA_WRAPPER_HPP
#define CUDA_WRAPPER_HPP
/* Disable warning for CUDA 5.5 headers emitted by Clang ≥ 3.3:
* /usr/local/cuda-5.5/include/cuda_runtime.h:225:33: warning: function
* 'cudaMallocHost' is not needed and will not be emitted [-Wunneeded-internal-declaration]
*/
#if (defined(__clang__) && __clang_major__ >= 3 && __clang_minor__ > 2)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunneeded-internal-declaration"
# include <cuda_runtime.h>
# pragma GCC diagnostic pop
#else
# include <cuda_runtime.h>
#endif
/*
* C++ wrappers requiring runtime functionality (e.g. exceptions)
*/
#ifndef __CUDACC__
# include <cuda_wrapper/allocator.hpp>
# include <cuda_wrapper/copy.hpp>
# include <cuda_wrapper/deprecated/copy.hpp>
# include <cuda_wrapper/device.hpp>
# include <cuda_wrapper/error.hpp>
# include <cuda_wrapper/event.hpp>
# include <cuda_wrapper/host/allocator.hpp>
# include <cuda_wrapper/host/vector.hpp>
# include <cuda_wrapper/stream.hpp>
# include <cuda_wrapper/thread.hpp>
# include <cuda_wrapper/vector.hpp>
# include <cuda_wrapper/version.hpp>
#endif /* ! __CUDACC__ */
/*
* C++ wrappers *not* requiring runtime functionality
*/
#include <cuda_wrapper/function.hpp>
#include <cuda_wrapper/symbol.hpp>
#include <cuda_wrapper/texture.hpp>
#endif /* ! CUDA_WRAPPER_HPP */
<commit_msg>disable Clang ≤ 3.3 warning: unneeded internal declaration<commit_after>/* cuda_wrapper/cuda_wrapper.hpp
*
* Copyright (C) 2013 Felix Höfling
* Copyright (C) 2007 Peter Colberg
*
* This file is part of HALMD.
*
* HALMD 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 <http://www.gnu.org/licenses/>.
*/
/*
* CUDA runtime API wrapper classes
*/
#ifndef CUDA_WRAPPER_HPP
#define CUDA_WRAPPER_HPP
/* Disable warning for CUDA 5.5 headers emitted by Clang ≤ 3.3:
* /usr/local/cuda-5.5/include/cuda_runtime.h:225:33: warning: function
* 'cudaMallocHost' is not needed and will not be emitted [-Wunneeded-internal-declaration]
*
* The CUDA runtime API version cannot be checked at this stage since the macro
* CUDART_VERSION is not yet defined.
*/
#if (defined(__clang__) && __clang_major__ == 3 && __clang_minor__ <= 3)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunneeded-internal-declaration"
# include <cuda_runtime.h>
# pragma GCC diagnostic pop
#else
# include <cuda_runtime.h>
#endif
/*
* C++ wrappers requiring runtime functionality (e.g. exceptions)
*/
#ifndef __CUDACC__
# include <cuda_wrapper/allocator.hpp>
# include <cuda_wrapper/copy.hpp>
# include <cuda_wrapper/deprecated/copy.hpp>
# include <cuda_wrapper/device.hpp>
# include <cuda_wrapper/error.hpp>
# include <cuda_wrapper/event.hpp>
# include <cuda_wrapper/host/allocator.hpp>
# include <cuda_wrapper/host/vector.hpp>
# include <cuda_wrapper/stream.hpp>
# include <cuda_wrapper/thread.hpp>
# include <cuda_wrapper/vector.hpp>
# include <cuda_wrapper/version.hpp>
#endif /* ! __CUDACC__ */
/*
* C++ wrappers *not* requiring runtime functionality
*/
#include <cuda_wrapper/function.hpp>
#include <cuda_wrapper/symbol.hpp>
#include <cuda_wrapper/texture.hpp>
#endif /* ! CUDA_WRAPPER_HPP */
<|endoftext|> |
<commit_before><commit_msg>CID#1103727 the intent is surely to compare nPos, nStart cannot be -1<commit_after><|endoftext|> |
<commit_before>// A full shader uniform block. This is to get away from the machinery that uses boost::variant and some of the crazy namespacing that comes up far too often when writing client-side code.
#pragma once
namespace noob
{
struct uniform_block
{
};
}
<commit_msg>Add smartass comments<commit_after>// A shader uniform block. This is to get away from the machinery that uses boost::variant and some of the crazy namespacing and contortionism that comes up far too often when writing client-side code.
// Still WIP after a brave slog and a clean retreat... :P
// TODO: Implement.
#pragma once
namespace noob
{
struct uniform_block
{
};
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012-2015 Daniele Bartolini and individual contributors.
* License: https://github.com/taylor001/crown/blob/master/LICENSE
*/
#include "config.h"
#include "dynamic_string.h"
#include "filesystem.h"
#include "log.h"
#include "lua_resource.h"
#include "os.h"
#include "temp_allocator.h"
#include "array.h"
#include "compile_options.h"
#if CROWN_DEBUG
#define LUAJIT_FLAGS "-bg" // Keep debug info
#else
#define LUAJIT_FLAGS "-b"
#endif // CROWN_DEBUG
namespace crown
{
namespace lua_resource
{
void compile(const char* path, CompileOptions& opts)
{
static const uint32_t VERSION = 1;
TempAllocator1024 alloc;
DynamicString res_abs_path(alloc);
TempAllocator1024 alloc2;
DynamicString bc_abs_path(alloc2);
opts.get_absolute_path(path, res_abs_path);
opts.get_absolute_path("bc.tmp", bc_abs_path);
const char* luajit[] =
{
#if CROWN_PLATFORM_LINUX
"./luajit",
#else
"luajit.exe",
#endif // CROWN_PLATFORM_LINUX
LUAJIT_FLAGS,
res_abs_path.c_str(),
bc_abs_path.c_str(),
NULL
};
int exitcode = os::execute_process(luajit);
CE_ASSERT(exitcode == 0, "Failed to compile lua");
Buffer blob = opts.read(bc_abs_path.c_str());
opts.delete_file(bc_abs_path.c_str());
LuaResource lr;
lr.version = VERSION;
lr.size = array::size(blob);
opts.write(lr.version);
opts.write(lr.size);
opts.write(blob);
}
void* load(File& file, Allocator& a)
{
const size_t file_size = file.size();
void* res = a.allocate(file_size);
file.read(res, file_size);
return res;
}
void online(StringId64 /*id*/, ResourceManager& /*rm*/)
{
}
void offline(StringId64 /*id*/, ResourceManager& /*rm*/)
{
}
void unload(Allocator& allocator, void* resource)
{
allocator.deallocate(resource);
}
uint32_t size(const LuaResource* lr)
{
return lr->size;
}
const char* program(const LuaResource* lr)
{
return (char*)lr + sizeof(LuaResource);
}
} // namespace lua_resource
} // namespace crown
<commit_msg>Cleanup<commit_after>/*
* Copyright (c) 2012-2015 Daniele Bartolini and individual contributors.
* License: https://github.com/taylor001/crown/blob/master/LICENSE
*/
#include "config.h"
#include "dynamic_string.h"
#include "lua_resource.h"
#include "os.h"
#include "temp_allocator.h"
#include "array.h"
#include "compile_options.h"
#if CROWN_DEBUG
#define LUAJIT_FLAGS "-bg" // Keep debug info
#else
#define LUAJIT_FLAGS "-b"
#endif // CROWN_DEBUG
namespace crown
{
namespace lua_resource
{
void compile(const char* path, CompileOptions& opts)
{
static const uint32_t VERSION = 1;
TempAllocator1024 alloc;
DynamicString res_abs_path(alloc);
TempAllocator1024 alloc2;
DynamicString bc_abs_path(alloc2);
opts.get_absolute_path(path, res_abs_path);
opts.get_absolute_path("bc.tmp", bc_abs_path);
const char* luajit[] =
{
#if CROWN_PLATFORM_LINUX
"./luajit",
#else
"luajit.exe",
#endif // CROWN_PLATFORM_LINUX
LUAJIT_FLAGS,
res_abs_path.c_str(),
bc_abs_path.c_str(),
NULL
};
int exitcode = os::execute_process(luajit);
CE_ASSERT(exitcode == 0, "Failed to compile lua");
Buffer blob = opts.read(bc_abs_path.c_str());
opts.delete_file(bc_abs_path.c_str());
LuaResource lr;
lr.version = VERSION;
lr.size = array::size(blob);
opts.write(lr.version);
opts.write(lr.size);
opts.write(blob);
}
void* load(File& file, Allocator& a)
{
const size_t file_size = file.size();
void* res = a.allocate(file_size);
file.read(res, file_size);
return res;
}
void online(StringId64 /*id*/, ResourceManager& /*rm*/)
{
}
void offline(StringId64 /*id*/, ResourceManager& /*rm*/)
{
}
void unload(Allocator& allocator, void* resource)
{
allocator.deallocate(resource);
}
uint32_t size(const LuaResource* lr)
{
return lr->size;
}
const char* program(const LuaResource* lr)
{
return (char*)lr + sizeof(LuaResource);
}
} // namespace lua_resource
} // namespace crown
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: ResampleImageFilter3.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.
=========================================================================*/
// Software Guide : BeginLatex
//
// Now that the principles behind the \code{ResampleImageFilter} has been
// layed out, let's have some fun with it !
//
// Figure \ref{fig:ResampleImageFilterTransformComposition6} illustrates the
// generic case of the resampling process. The origin and spacing of the
// output image has been choosen to be different from those of the input
// image. The circles represent the \emph{center} of pixels. They are
// inscribed in a rectangle representing the \emph{coverage} of this pixel.
// The spacing specifies the distance between pixel centers along every
// dimension.
//
// The transform applied is a rotation of $30$ degrees. It is important to
// note here that the transform supplied to the \code{ResampleImageFilter} is
// a \emph{counter-clockwise} rotation. This transform rotates the
// \emph{coordinate system} of the output image 30 degrees counter-clockwise.
// When the two images are relocated in a common coordinate system --- as in
// figure \ref{fig:ResampleImageFilterTransformComposition6} --- the result is
// that the frame of the output image appears rotated 30 degrees
// \emph{clockwise}. If the output image is seen with its coordinate system
// straighten up, the image content appears rotated 30 degrees
// \emph{counter-clockwise}. Before continue reading this section, you may
// want to meditate a bit on this fact while enjoying a cup of coffee.
//
// \begin{figure}
// \center
// \includegraphics[width=12cm]{ResampleImageFilterTransformComposition6.eps}
// \caption{Effect of selecting the origin of the output image}
// \label{fig:ResampleImageFilterTransformComposition6}
// \end{figure}
//
// The following code implements these condition with the only difference of
// selecting a spacing 40 times smaller and a number of pixels 40 times larger
// in both dimensions. Without these change, few detail will be recognizable
// on the images. Note that the spacing and origin of the input image should
// be prepared in advance by using other means since this filter cannot alter
// in any way the actual content of the input image.
//
// Software Guide : EndLatex
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkResampleImageFilter.h"
#include "itkAffineTransform.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
int main( int argc, char ** argv )
{
if( argc < 4 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImageFile outputImageFile";
std::cerr << " [exampleAction={0,1}]" << std::endl;
return 1;
}
int exampleAction = 0;
if( argc >= 4 )
{
exampleAction = atoi( argv[3] );
}
const unsigned int Dimension = 2;
typedef unsigned char InputPixelType;
typedef unsigned char OutputPixelType;
typedef itk::Image< InputPixelType, Dimension > InputImageType;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( argv[1] );
writer->SetFileName( argv[2] );
typedef itk::ResampleImageFilter<
InputImageType, OutputImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
typedef itk::AffineTransform< double, Dimension > TransformType;
TransformType::Pointer transform = TransformType::New();
typedef itk::NearestNeighborInterpolateImageFunction<
InputImageType, double > InterpolatorType;
InterpolatorType::Pointer interpolator = InterpolatorType::New();
filter->SetInterpolator( interpolator );
// Software Guide : BeginLatex
//
// In order to facilitate the interpretation of the transform we set the
// default pixel value to a distintly visible gray level.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetDefaultPixelValue( 100 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The spacing is selected here to be 40 times smaller than the one
// illustrated in figure \ref{fig:ResampleImageFilterTransformComposition6}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
double spacing[ Dimension ];
spacing[0] = 40.0 / 40.0; // pixel spacing in millimeters along X
spacing[1] = 30.0 / 40.0; // pixel spacing in millimeters along Y
filter->SetOutputSpacing( spacing );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Let us now set up the origin of the output image. Note that the values
// provided here will be those of the space coordinates for the pixel of
// index $(0,0)$.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
double origin[ Dimension ];
origin[0] = 50.0; // X space coordinate of origin
origin[1] = 130.0; // Y space coordinate of origin
filter->SetOutputOrigin( origin );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The output image size is defined to be 40 times the one illustrated on
// the figure.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
InputImageType::SizeType size;
size[0] = 5 * 40; // number of pixels along X
size[1] = 4 * 40; // number of pixels along Y
filter->SetSize( size );
// Software Guide : EndCodeSnippet
filter->SetInput( reader->GetOutput() );
writer->SetInput( filter->GetOutput() );
// Software Guide : BeginLatex
//
// We set the transform to identity in order to better appreciate the effect
// of the origin selection.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
transform->Rotate2D( 30.0 );
filter->SetTransform( transform );
// Software Guide : EndCodeSnippet
if( exampleAction == 0 )
{
writer->Update();
}
return 0;
}
<commit_msg>ENH: Origin translation corrected. In order to rotate around image origin.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: ResampleImageFilter3.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.
=========================================================================*/
// Software Guide : BeginLatex
//
// Now that the principles behind the \code{ResampleImageFilter} has been
// layed out, let's have some fun with it !
//
// Figure \ref{fig:ResampleImageFilterTransformComposition6} illustrates the
// generic case of the resampling process. The origin and spacing of the
// output image has been choosen to be different from those of the input
// image. The circles represent the \emph{center} of pixels. They are
// inscribed in a rectangle representing the \emph{coverage} of this pixel.
// The spacing specifies the distance between pixel centers along every
// dimension.
//
// The transform applied is a rotation of $30$ degrees. It is important to
// note here that the transform supplied to the \code{ResampleImageFilter} is
// a \emph{counter-clockwise} rotation. This transform rotates the
// \emph{coordinate system} of the output image 30 degrees counter-clockwise.
// When the two images are relocated in a common coordinate system --- as in
// figure \ref{fig:ResampleImageFilterTransformComposition6} --- the result is
// that the frame of the output image appears rotated 30 degrees
// \emph{clockwise}. If the output image is seen with its coordinate system
// straighten up, the image content appears rotated 30 degrees
// \emph{counter-clockwise}. Before continue reading this section, you may
// want to meditate a bit on this fact while enjoying a cup of coffee.
//
// \begin{figure}
// \center
// \includegraphics[width=12cm]{ResampleImageFilterTransformComposition6.eps}
// \caption{Effect of selecting the origin of the output image}
// \label{fig:ResampleImageFilterTransformComposition6}
// \end{figure}
//
// The following code implements these condition with the only difference of
// selecting a spacing 40 times smaller and a number of pixels 40 times larger
// in both dimensions. Without these change, few detail will be recognizable
// on the images. Note that the spacing and origin of the input image should
// be prepared in advance by using other means since this filter cannot alter
// in any way the actual content of the input image.
//
// Software Guide : EndLatex
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkResampleImageFilter.h"
#include "itkAffineTransform.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
int main( int argc, char ** argv )
{
if( argc < 4 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImageFile outputImageFile";
std::cerr << " [exampleAction={0,1}]" << std::endl;
return 1;
}
int exampleAction = 0;
if( argc >= 4 )
{
exampleAction = atoi( argv[3] );
}
const unsigned int Dimension = 2;
typedef unsigned char InputPixelType;
typedef unsigned char OutputPixelType;
typedef itk::Image< InputPixelType, Dimension > InputImageType;
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( argv[1] );
writer->SetFileName( argv[2] );
typedef itk::ResampleImageFilter<
InputImageType, OutputImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
typedef itk::AffineTransform< double, Dimension > TransformType;
TransformType::Pointer transform = TransformType::New();
typedef itk::NearestNeighborInterpolateImageFunction<
InputImageType, double > InterpolatorType;
InterpolatorType::Pointer interpolator = InterpolatorType::New();
filter->SetInterpolator( interpolator );
// Software Guide : BeginLatex
//
// In order to facilitate the interpretation of the transform we set the
// default pixel value to a distintly visible gray level.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetDefaultPixelValue( 100 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The spacing is selected here to be 40 times smaller than the one
// illustrated in figure \ref{fig:ResampleImageFilterTransformComposition6}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
double spacing[ Dimension ];
spacing[0] = 40.0 / 40.0; // pixel spacing in millimeters along X
spacing[1] = 30.0 / 40.0; // pixel spacing in millimeters along Y
filter->SetOutputSpacing( spacing );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Let us now set up the origin of the output image. Note that the values
// provided here will be those of the space coordinates for the pixel of
// index $(0,0)$.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
double origin[ Dimension ];
origin[0] = 50.0; // X space coordinate of origin
origin[1] = 130.0; // Y space coordinate of origin
filter->SetOutputOrigin( origin );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The output image size is defined to be 40 times the one illustrated on
// the figure.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
InputImageType::SizeType size;
size[0] = 5 * 40; // number of pixels along X
size[1] = 4 * 40; // number of pixels along Y
filter->SetSize( size );
// Software Guide : EndCodeSnippet
filter->SetInput( reader->GetOutput() );
writer->SetInput( filter->GetOutput() );
// Software Guide : BeginLatex
//
// Rotations are performed around the origin of coordinates. The process of
// positioning the output image frame as it is shown in the figure reguires
// three steps. First, the image origin must be moved to the origin of the
// coordinate system, this is done by applying a translationof
// $(-50,-130.0))$. In a second step, a rotation of 30 degrees is performed.
// The third and final step implies to translate back the origing to the
// previous location, which can be done with a translation of $(50.0,130)$.
// Note that the AffineTransform uses a second boolean argument to specify
// if the current modification of the transform should be pre-composed or
// post-composed with the current transform content.
//
// Angles are specified in Radians to the Affine transform.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
TransformType::OutputVectorType translation1;
translation1[0] = -50.0;
translation1[1] = -130.0;
transform->Translate( translation1 );
// Software Guide : EndCodeSnippet
// Software Guide : BeginCodeSnippet
const double degreesToRadians = atan(1.0) / 45.0;
transform->Rotate2D( 30.0 * degreesToRadians, false );
filter->SetTransform( transform );
// Software Guide : EndCodeSnippet
// Software Guide : BeginCodeSnippet
TransformType::OutputVectorType translation2;
translation2[0] = 50.0;
translation2[1] = 130.0;
transform->Translate( translation2, false );
// Software Guide : EndCodeSnippet
if( exampleAction == 0 )
{
try
{
writer->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception catched !" << std::endl;
std::cerr << excep << std::endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include "UserCode/diall/interface/anaPuppiProducer.h"
#include "UserCode/diall/interface/lwJet.h"
#include "UserCode/diall/interface/pfParticle.h"
#include "Math/QuantFuncMathCore.h"
#include "Math/SpecFuncMathCore.h"
#include "Math/ProbFunc.h"
#include "TClass.h"
#include "TMath.h"
ClassImp(anaPuppiProducer)
anaPuppiProducer::anaPuppiProducer(const char *name, const char *title)
:anaBaseTask(name,title),
fConeRadius(0.3),
fCentBin(-1),
fNExLJ(2),
fMinPtExLJ(20.),
fdRMaxJet(0.4),
fAddMetricType(kSumPt),
fPtMinParticle(0.),
fPFParticlesName(""),
fPFParticles(0x0),
fJetsName(""),
fJetsCont(0x0),
fPuppiParticlesName(""),
fPuppiParticles(0x0),
fMapEtaRanges(),
fh2CentMedianAlpha(),
fh2CentRMSAlpha(),
fh2CentMedianMetric2(),
fh2CentRMSMetric2()
{
//Set default eta ranges
//[-5,-3,-2.1,2.1,3,5] -> 5 intervals
fMapEtaRanges[1] = -5.;
fMapEtaRanges[2] = -3.;
fMapEtaRanges[3] = -2.1;
fMapEtaRanges[4] = 2.1;
fMapEtaRanges[5] = 3.;
fMapEtaRanges[6] = 5.;
}
//________________________________________________________________________
anaPuppiProducer::~anaPuppiProducer() {
// Destructor
}
//----------------------------------------------------------
void anaPuppiProducer::Exec(Option_t * /*option*/)
{
// printf("anaPuppiProducer executing\n");
anaBaseTask::Exec();
if(!fInitOutput) CreateOutputObjects();
if(!fEventObjects) {
Printf("%s: fEventObjects does not exist. Cannot store output",GetName());
return;
}
//Get objects from event
//Get jet container
if(!fJetsCont && !fJetsName.IsNull())
fJetsCont = dynamic_cast<lwJetContainer*>(fEventObjects->FindObject(fJetsName.Data()));
if(!fJetsCont) {
Printf("%s: Jets not found %s",GetName(),fJetsName.Data());
return;
}
TClonesArray *jets = fJetsCont->GetJets();
if(!jets) return;
//Get pf particles
if(!fPFParticles && !fPFParticlesName.IsNull()) {
fPFParticles = dynamic_cast<TClonesArray*>(fEventObjects->FindObject(fPFParticlesName.Data()));
}
if(!fPFParticles) return;
//Make array for puppi particles
if(!fPuppiParticlesName.IsNull()) {
if(!fEventObjects->FindObject(fPuppiParticlesName) && !fPuppiParticles) {
fPuppiParticles = new TClonesArray("pfParticle");
fPuppiParticles->SetName(fPuppiParticlesName);
fEventObjects->Add(fPuppiParticles);
}
}
if(fPuppiParticles) fPuppiParticles->Delete();
//Determine centrality bin
double cent = 0.;
if(!fHiEvent) Printf("%s: couldn't locate fHiEvent",GetName());
else {
cent = fHiEvent->GetCentrality();
}
if(cent>=0. && cent<10.) fCentBin = 0;
else if(cent>=10. && cent<30.) fCentBin = 1;
else if(cent>=30. && cent<50.) fCentBin = 2;
else if(cent>=50. && cent<80.) fCentBin = 3;
else fCentBin = -1;
//Find signal jets at detector level
Int_t nSignalJetsDet = 0;
// Int_t sigDetIds[999];
Double_t sigDetPhi[999];
Double_t sigDetEta[999];
Int_t nj = TMath::Min(fNExLJ,fJetsCont->GetNJets());
for(Int_t ij = 0; ij<nj; ij++) {
lwJet *jet = static_cast<lwJet*>(jets->At(ij));
if(jet->Pt()>fMinPtExLJ) {
// sigDetIds[nSignalJetsDet] = ij;
sigDetPhi[nSignalJetsDet] = jet->Phi();
sigDetEta[nSignalJetsDet] = jet->Eta();
nSignalJetsDet++;
}
}
//pf candidate loop to calculate alpha for each particle
//plan: apply pt cut to particles, put particles passing in std::vector and work with those for the rest of the algo
std::vector<pfParticle*> fSelPFParticles;
for (int i = 0; i < fPFParticles->GetEntriesFast(); i++) {
pfParticle *p1 = static_cast<pfParticle*>(fPFParticles->At(i));
if(!p1) continue;
if(p1->Pt()<fPtMinParticle) continue;
fSelPFParticles.push_back(p1);
}
//for (int i = 0; i < fPFParticles->GetEntriesFast(); i++) {
//pfParticle *p1 = static_cast<pfParticle*>(fPFParticles->At(i));
for (unsigned int i = 0; i < fSelPFParticles.size(); i++) {
pfParticle *p1 = fSelPFParticles[i];
if(!p1) continue;
Double_t var = 0.;
Double_t var2 = 0.;
TLorentzVector lsum(0.,0.,0.,0.);
//for (int j = 0; j < fPFParticles->GetEntriesFast(); j++) {
for (unsigned int j = 0; j < fSelPFParticles.size(); j++) {
if(i==j) continue;
pfParticle *p2 = fSelPFParticles[j];
if(!p2) continue;
//pfParticle *p2 = static_cast<pfParticle*>(fPFParticles->At(j));
Double_t dr = p1->DeltaR(p2);
if(dr>fConeRadius) continue;
var += p2->Pt() /dr/dr;
if(fAddMetricType==kSumPt)
var2 += p2->Pt();
else if(fAddMetricType==kMass)
lsum+=p2->GetLorentzVector();
}
if(var!=0.) var = log(var);
p1->SetPuppiAlpha(var);
if(fAddMetricType==kMass)
var2+=lsum.M();
p1->SetPuppiMetric2(var2);
}//particles loop
//calculation of median and RMS alpha in eta ranges
std::map<int,double> fMapMedianAlpha; //median alpha in eta regions
std::map<int,double> fMapRmsAlpha; //rms alpha in eta regions
std::map<int,double> fMapMedianMetric2; //median metric2 in eta regions
std::map<int,double> fMapRmsMetric2; //rms metric2 in eta regions
Int_t neta = (Int_t)fMapEtaRanges.size();
for(Int_t ieta = 1; ieta<neta; ieta++) {
static Double_t alphaArrExLJ[9999] = {0.};
static Double_t metric2ArrExLJ[9999] = {0.};
Int_t count = 0;
Double_t etaMin = fMapEtaRanges.at(ieta)+fConeRadius;
Double_t etaMax = fMapEtaRanges.at(ieta+1)-fConeRadius;
//for (int i = 0; i < fPFParticles->GetEntriesFast(); i++) {
// pfParticle *p1 = static_cast<pfParticle*>(fPFParticles->At(i));
// if(!p1) continue;
for (unsigned int i = 0; i < fSelPFParticles.size(); i++) {
pfParticle *p1 = fSelPFParticles[i];
if(!p1) continue;
if(p1->Eta()>=etaMin && p1->Eta()<etaMax) {
//check distance to closest signal jet
Double_t drDet = 999.;
for(Int_t is = 0; is<nSignalJetsDet; is++) {
Double_t dPhi = p1->Phi() - sigDetPhi[is];
Double_t dEta = p1->Eta() - sigDetEta[is];
dPhi = TVector2::Phi_mpi_pi(dPhi);
Double_t dr2tmp = dPhi * dPhi + dEta * dEta;
Double_t drtmp = 0.;
if(dr2tmp>0.) drtmp = TMath::Sqrt(dr2tmp);
if(drtmp<drDet) {
drDet = drtmp;
}
}//signal jets
//Excluding regions close to leading detector-level jet
if(drDet>fdRMaxJet) {
alphaArrExLJ[count] = p1->GetPuppiAlpha();
metric2ArrExLJ[count] = p1->GetPuppiMetric2();
count++;
}
}//eta selection
}//particles loop
static Int_t indexes[9999] = {-1};//indexes for sorting
TMath::Sort(count,alphaArrExLJ,indexes);
Double_t medAlpha = TMath::Median(count,alphaArrExLJ);
static Int_t indexes2[9999] = {-1};//indexes for sorting
TMath::Sort(count,metric2ArrExLJ,indexes2);
Double_t medMetric2 = TMath::Median(count,metric2ArrExLJ);
//Calculate LHS RMS. LHS defined as all entries up to median
Int_t nias = TMath::FloorNint((Double_t)count/2.);
Double_t rmsAlpha = 0.;
Double_t rmsMetric2 = 0.;
for(Int_t ia = 0; ia<count; ia++) { //taking entries starting from nias since sorted from high to low
Double_t alph = alphaArrExLJ[ia];//indexes[ia]];
if(alph<medAlpha)
rmsAlpha += (alph - medAlpha)*(alph - medAlpha);
// if(alph>medAlpha) Printf("WARNING: alph (%f) larger than medAlpha (%f)",alph,medAlpha);
//metric2
Double_t metr2 = metric2ArrExLJ[ia];//indexes[ia]];
if(metr2<medMetric2)
rmsMetric2 += (metr2 - medMetric2)*(metr2 - medMetric2);
// if(metr2>medMetric2) Printf("WARNING: metr2 (%f) larger than medMetric2 (%f)",metr2,medMetric2);
}
if(rmsAlpha>0.) rmsAlpha = TMath::Sqrt(rmsAlpha/((double)nias));
if(rmsMetric2>0.) rmsMetric2 = TMath::Sqrt(rmsMetric2/((double)nias));
//Fill histograms, only for mid rapidity
if(ieta==3) {
fh2CentMedianAlpha->Fill(cent,medAlpha);
fh2CentRMSAlpha->Fill(cent,rmsAlpha);
fh2CentMedianMetric2->Fill(cent,medMetric2);
fh2CentRMSMetric2->Fill(cent,rmsMetric2);
}
fMapMedianAlpha[ieta] = medAlpha;
fMapRmsAlpha[ieta] = rmsAlpha;
fMapMedianMetric2[ieta] = medMetric2;
fMapRmsMetric2[ieta] = rmsMetric2;
}//eta bins
//Set puppi weight for each particle
Int_t npup = 0;
//for (int i = 0; i < fPFParticles->GetEntriesFast(); i++) {
// pfParticle *p1 = static_cast<pfParticle*>(fPFParticles->At(i));
for (unsigned int i = 0; i < fSelPFParticles.size(); i++) {
pfParticle *p1 = fSelPFParticles[i];
if(!p1) continue;
Double_t prob = 1.;
Int_t etaBin = -1;
for(Int_t ieta = 1; ieta<neta; ++ieta) {
Double_t etaMin = fMapEtaRanges.at(ieta);
Double_t etaMax = fMapEtaRanges.at(ieta+1);
if(p1->Eta()>=etaMin && p1->Eta()<etaMax)
etaBin = ieta;
}
Double_t medAlpha = fMapMedianAlpha[etaBin];
Double_t rmsAlpha = fMapRmsAlpha[etaBin];
Double_t chiAlpha = 1.;
if(rmsAlpha>0.) {
chiAlpha = (p1->GetPuppiAlpha() - medAlpha) * fabs(p1->GetPuppiAlpha() - medAlpha) / rmsAlpha / rmsAlpha;
prob = ROOT::Math::chisquared_cdf(chiAlpha,1.);
}
p1->SetPuppiWeight(prob);
//weight metric2
Double_t medMetric2 = fMapMedianMetric2[etaBin];
Double_t rmsMetric2 = fMapRmsMetric2[etaBin];
Double_t prob2 = 1.;
Double_t prob3 = 1.;
if(rmsMetric2>0.) {
Double_t chiMetric2 = (p1->GetPuppiMetric2() - medMetric2) * fabs(p1->GetPuppiMetric2() - medMetric2) / rmsMetric2 / rmsMetric2;
Double_t chii = chiAlpha + chiMetric2;
prob2 = ROOT::Math::chisquared_cdf(chii,2.);
prob3 = ROOT::Math::chisquared_cdf(chiMetric2,1.);
}
p1->SetPuppiWeight2(prob2);
p1->SetPuppiWeight3(prob3);
//put puppi weighted particles in array
double ptpup = prob*p1->Pt();
if(fPuppiParticles && ptpup>1e-4) {
pfParticle *pPart = new ((*fPuppiParticles)[npup])
pfParticle(prob*p1->Pt(),
p1->Eta(),
p1->Phi(),
prob*p1->M(),
p1->GetId());
pPart->SetCharge(p1->GetCharge());
pPart->SetPuppiWeight(prob);
pPart->SetPuppiWeight2(prob2);
pPart->SetPuppiWeight3(prob3);
++npup;
}
}
}
//----------------------------------------------------------
void anaPuppiProducer::CreateOutputObjects() {
anaBaseTask::CreateOutputObjects();
if(!fOutput) {
Printf("anaPuppiProducer: fOutput not present");
return;
}
fh2CentMedianAlpha = new TH2F("fh2CentMedianAlpha","fh2CentMedianAlpha;centrality (%);med{#alpha}",10,0,100,40,0,20);
fOutput->Add(fh2CentMedianAlpha);
fh2CentRMSAlpha = new TH2F("fh2CentRMSAlpha","fh2CentRMSAlpha;centrality (%);RMS{#alpha}",10,0,100,40,0,4);
fOutput->Add(fh2CentRMSAlpha);
fh2CentMedianMetric2 = new TH2F("fh2CentMedianMetric2","fh2CentMedianMetric2;centrality (%);med{metric2}",10,0,100,100,0,100);
fOutput->Add(fh2CentMedianMetric2);
fh2CentRMSMetric2 = new TH2F("fh2CentRMSMetric2","fh2CentRMSMetric2;centrality (%);RMS{metric2}",10,0,100,30,0,30);
fOutput->Add(fh2CentRMSMetric2);
}
<commit_msg>set metrics for puppi particles<commit_after>#include "UserCode/diall/interface/anaPuppiProducer.h"
#include "UserCode/diall/interface/lwJet.h"
#include "UserCode/diall/interface/pfParticle.h"
#include "Math/QuantFuncMathCore.h"
#include "Math/SpecFuncMathCore.h"
#include "Math/ProbFunc.h"
#include "TClass.h"
#include "TMath.h"
ClassImp(anaPuppiProducer)
anaPuppiProducer::anaPuppiProducer(const char *name, const char *title)
:anaBaseTask(name,title),
fConeRadius(0.3),
fCentBin(-1),
fNExLJ(2),
fMinPtExLJ(20.),
fdRMaxJet(0.4),
fAddMetricType(kSumPt),
fPtMinParticle(0.),
fPFParticlesName(""),
fPFParticles(0x0),
fJetsName(""),
fJetsCont(0x0),
fPuppiParticlesName(""),
fPuppiParticles(0x0),
fMapEtaRanges(),
fh2CentMedianAlpha(),
fh2CentRMSAlpha(),
fh2CentMedianMetric2(),
fh2CentRMSMetric2()
{
//Set default eta ranges
//[-5,-3,-2.1,2.1,3,5] -> 5 intervals
fMapEtaRanges[1] = -5.;
fMapEtaRanges[2] = -3.;
fMapEtaRanges[3] = -2.1;
fMapEtaRanges[4] = 2.1;
fMapEtaRanges[5] = 3.;
fMapEtaRanges[6] = 5.;
}
//________________________________________________________________________
anaPuppiProducer::~anaPuppiProducer() {
// Destructor
}
//----------------------------------------------------------
void anaPuppiProducer::Exec(Option_t * /*option*/)
{
// printf("anaPuppiProducer executing\n");
anaBaseTask::Exec();
if(!fInitOutput) CreateOutputObjects();
if(!fEventObjects) {
Printf("%s: fEventObjects does not exist. Cannot store output",GetName());
return;
}
//Get objects from event
//Get jet container
if(!fJetsCont && !fJetsName.IsNull())
fJetsCont = dynamic_cast<lwJetContainer*>(fEventObjects->FindObject(fJetsName.Data()));
if(!fJetsCont) {
Printf("%s: Jets not found %s",GetName(),fJetsName.Data());
return;
}
TClonesArray *jets = fJetsCont->GetJets();
if(!jets) return;
//Get pf particles
if(!fPFParticles && !fPFParticlesName.IsNull()) {
fPFParticles = dynamic_cast<TClonesArray*>(fEventObjects->FindObject(fPFParticlesName.Data()));
}
if(!fPFParticles) return;
//Make array for puppi particles
if(!fPuppiParticlesName.IsNull()) {
if(!fEventObjects->FindObject(fPuppiParticlesName) && !fPuppiParticles) {
fPuppiParticles = new TClonesArray("pfParticle");
fPuppiParticles->SetName(fPuppiParticlesName);
fEventObjects->Add(fPuppiParticles);
}
}
if(fPuppiParticles) fPuppiParticles->Delete();
//Determine centrality bin
double cent = 0.;
if(!fHiEvent) Printf("%s: couldn't locate fHiEvent",GetName());
else {
cent = fHiEvent->GetCentrality();
}
if(cent>=0. && cent<10.) fCentBin = 0;
else if(cent>=10. && cent<30.) fCentBin = 1;
else if(cent>=30. && cent<50.) fCentBin = 2;
else if(cent>=50. && cent<80.) fCentBin = 3;
else fCentBin = -1;
//Find signal jets at detector level
Int_t nSignalJetsDet = 0;
// Int_t sigDetIds[999];
Double_t sigDetPhi[999];
Double_t sigDetEta[999];
Int_t nj = TMath::Min(fNExLJ,fJetsCont->GetNJets());
for(Int_t ij = 0; ij<nj; ij++) {
lwJet *jet = static_cast<lwJet*>(jets->At(ij));
if(jet->Pt()>fMinPtExLJ) {
// sigDetIds[nSignalJetsDet] = ij;
sigDetPhi[nSignalJetsDet] = jet->Phi();
sigDetEta[nSignalJetsDet] = jet->Eta();
nSignalJetsDet++;
}
}
//pf candidate loop to calculate alpha for each particle
//plan: apply pt cut to particles, put particles passing in std::vector and work with those for the rest of the algo
std::vector<pfParticle*> fSelPFParticles;
for (int i = 0; i < fPFParticles->GetEntriesFast(); i++) {
pfParticle *p1 = static_cast<pfParticle*>(fPFParticles->At(i));
if(!p1) continue;
if(p1->Pt()<fPtMinParticle) continue;
fSelPFParticles.push_back(p1);
}
//for (int i = 0; i < fPFParticles->GetEntriesFast(); i++) {
//pfParticle *p1 = static_cast<pfParticle*>(fPFParticles->At(i));
for (unsigned int i = 0; i < fSelPFParticles.size(); i++) {
pfParticle *p1 = fSelPFParticles[i];
if(!p1) continue;
Double_t var = 0.;
Double_t var2 = 0.;
TLorentzVector lsum(0.,0.,0.,0.);
//for (int j = 0; j < fPFParticles->GetEntriesFast(); j++) {
for (unsigned int j = 0; j < fSelPFParticles.size(); j++) {
if(i==j) continue;
pfParticle *p2 = fSelPFParticles[j];
if(!p2) continue;
//pfParticle *p2 = static_cast<pfParticle*>(fPFParticles->At(j));
Double_t dr = p1->DeltaR(p2);
if(dr>fConeRadius) continue;
var += p2->Pt() /dr/dr;
if(fAddMetricType==kSumPt)
var2 += p2->Pt();
else if(fAddMetricType==kMass)
lsum+=p2->GetLorentzVector();
}
if(var!=0.) var = log(var);
p1->SetPuppiAlpha(var);
if(fAddMetricType==kMass)
var2+=lsum.M();
p1->SetPuppiMetric2(var2);
}//particles loop
//calculation of median and RMS alpha in eta ranges
std::map<int,double> fMapMedianAlpha; //median alpha in eta regions
std::map<int,double> fMapRmsAlpha; //rms alpha in eta regions
std::map<int,double> fMapMedianMetric2; //median metric2 in eta regions
std::map<int,double> fMapRmsMetric2; //rms metric2 in eta regions
Int_t neta = (Int_t)fMapEtaRanges.size();
for(Int_t ieta = 1; ieta<neta; ieta++) {
static Double_t alphaArrExLJ[9999] = {0.};
static Double_t metric2ArrExLJ[9999] = {0.};
Int_t count = 0;
Double_t etaMin = fMapEtaRanges.at(ieta)+fConeRadius;
Double_t etaMax = fMapEtaRanges.at(ieta+1)-fConeRadius;
//for (int i = 0; i < fPFParticles->GetEntriesFast(); i++) {
// pfParticle *p1 = static_cast<pfParticle*>(fPFParticles->At(i));
// if(!p1) continue;
for (unsigned int i = 0; i < fSelPFParticles.size(); i++) {
pfParticle *p1 = fSelPFParticles[i];
if(!p1) continue;
if(p1->Eta()>=etaMin && p1->Eta()<etaMax) {
//check distance to closest signal jet
Double_t drDet = 999.;
for(Int_t is = 0; is<nSignalJetsDet; is++) {
Double_t dPhi = p1->Phi() - sigDetPhi[is];
Double_t dEta = p1->Eta() - sigDetEta[is];
dPhi = TVector2::Phi_mpi_pi(dPhi);
Double_t dr2tmp = dPhi * dPhi + dEta * dEta;
Double_t drtmp = 0.;
if(dr2tmp>0.) drtmp = TMath::Sqrt(dr2tmp);
if(drtmp<drDet) {
drDet = drtmp;
}
}//signal jets
//Excluding regions close to leading detector-level jet
if(drDet>fdRMaxJet) {
alphaArrExLJ[count] = p1->GetPuppiAlpha();
metric2ArrExLJ[count] = p1->GetPuppiMetric2();
count++;
}
}//eta selection
}//particles loop
static Int_t indexes[9999] = {-1};//indexes for sorting
TMath::Sort(count,alphaArrExLJ,indexes);
Double_t medAlpha = TMath::Median(count,alphaArrExLJ);
static Int_t indexes2[9999] = {-1};//indexes for sorting
TMath::Sort(count,metric2ArrExLJ,indexes2);
Double_t medMetric2 = TMath::Median(count,metric2ArrExLJ);
//Calculate LHS RMS. LHS defined as all entries up to median
Int_t nias = TMath::FloorNint((Double_t)count/2.);
Double_t rmsAlpha = 0.;
Double_t rmsMetric2 = 0.;
for(Int_t ia = 0; ia<count; ia++) { //taking entries starting from nias since sorted from high to low
Double_t alph = alphaArrExLJ[ia];//indexes[ia]];
if(alph<medAlpha)
rmsAlpha += (alph - medAlpha)*(alph - medAlpha);
// if(alph>medAlpha) Printf("WARNING: alph (%f) larger than medAlpha (%f)",alph,medAlpha);
//metric2
Double_t metr2 = metric2ArrExLJ[ia];//indexes[ia]];
if(metr2<medMetric2)
rmsMetric2 += (metr2 - medMetric2)*(metr2 - medMetric2);
// if(metr2>medMetric2) Printf("WARNING: metr2 (%f) larger than medMetric2 (%f)",metr2,medMetric2);
}
if(rmsAlpha>0.) rmsAlpha = TMath::Sqrt(rmsAlpha/((double)nias));
if(rmsMetric2>0.) rmsMetric2 = TMath::Sqrt(rmsMetric2/((double)nias));
//Fill histograms, only for mid rapidity
if(ieta==3) {
fh2CentMedianAlpha->Fill(cent,medAlpha);
fh2CentRMSAlpha->Fill(cent,rmsAlpha);
fh2CentMedianMetric2->Fill(cent,medMetric2);
fh2CentRMSMetric2->Fill(cent,rmsMetric2);
}
fMapMedianAlpha[ieta] = medAlpha;
fMapRmsAlpha[ieta] = rmsAlpha;
fMapMedianMetric2[ieta] = medMetric2;
fMapRmsMetric2[ieta] = rmsMetric2;
}//eta bins
//Set puppi weight for each particle
Int_t npup = 0;
//for (int i = 0; i < fPFParticles->GetEntriesFast(); i++) {
// pfParticle *p1 = static_cast<pfParticle*>(fPFParticles->At(i));
for (unsigned int i = 0; i < fSelPFParticles.size(); i++) {
pfParticle *p1 = fSelPFParticles[i];
if(!p1) continue;
Double_t prob = 1.;
Int_t etaBin = -1;
for(Int_t ieta = 1; ieta<neta; ++ieta) {
Double_t etaMin = fMapEtaRanges.at(ieta);
Double_t etaMax = fMapEtaRanges.at(ieta+1);
if(p1->Eta()>=etaMin && p1->Eta()<etaMax)
etaBin = ieta;
}
Double_t medAlpha = fMapMedianAlpha[etaBin];
Double_t rmsAlpha = fMapRmsAlpha[etaBin];
Double_t chiAlpha = 1.;
if(rmsAlpha>0.) {
chiAlpha = (p1->GetPuppiAlpha() - medAlpha) * fabs(p1->GetPuppiAlpha() - medAlpha) / rmsAlpha / rmsAlpha;
prob = ROOT::Math::chisquared_cdf(chiAlpha,1.);
}
p1->SetPuppiWeight(prob);
//weight metric2
Double_t medMetric2 = fMapMedianMetric2[etaBin];
Double_t rmsMetric2 = fMapRmsMetric2[etaBin];
Double_t prob2 = 1.;
Double_t prob3 = 1.;
if(rmsMetric2>0.) {
Double_t chiMetric2 = (p1->GetPuppiMetric2() - medMetric2) * fabs(p1->GetPuppiMetric2() - medMetric2) / rmsMetric2 / rmsMetric2;
Double_t chii = chiAlpha + chiMetric2;
prob2 = ROOT::Math::chisquared_cdf(chii,2.);
prob3 = ROOT::Math::chisquared_cdf(chiMetric2,1.);
}
p1->SetPuppiWeight2(prob2);
p1->SetPuppiWeight3(prob3);
//put puppi weighted particles in array
double ptpup = prob*p1->Pt();
if(fPuppiParticles && ptpup>1e-4) {
pfParticle *pPart = new ((*fPuppiParticles)[npup])
pfParticle(prob*p1->Pt(),
p1->Eta(),
p1->Phi(),
prob*p1->M(),
p1->GetId());
pPart->SetCharge(p1->GetCharge());
pPart->SetPuppiAlpha(p1->GetPuppiAlpha());
pPart->SetPuppiMetric2(p1->GetPuppiMetric2());
pPart->SetPuppiWeight(prob);
pPart->SetPuppiWeight2(prob2);
pPart->SetPuppiWeight3(prob3);
++npup;
}
}
}
//----------------------------------------------------------
void anaPuppiProducer::CreateOutputObjects() {
anaBaseTask::CreateOutputObjects();
if(!fOutput) {
Printf("anaPuppiProducer: fOutput not present");
return;
}
fh2CentMedianAlpha = new TH2F("fh2CentMedianAlpha","fh2CentMedianAlpha;centrality (%);med{#alpha}",10,0,100,40,0,20);
fOutput->Add(fh2CentMedianAlpha);
fh2CentRMSAlpha = new TH2F("fh2CentRMSAlpha","fh2CentRMSAlpha;centrality (%);RMS{#alpha}",10,0,100,40,0,4);
fOutput->Add(fh2CentRMSAlpha);
fh2CentMedianMetric2 = new TH2F("fh2CentMedianMetric2","fh2CentMedianMetric2;centrality (%);med{metric2}",10,0,100,100,0,100);
fOutput->Add(fh2CentMedianMetric2);
fh2CentRMSMetric2 = new TH2F("fh2CentRMSMetric2","fh2CentRMSMetric2;centrality (%);RMS{metric2}",10,0,100,30,0,30);
fOutput->Add(fh2CentRMSMetric2);
}
<|endoftext|> |
<commit_before>
/** \copyright
* Copyright (c) 2013, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file EventHandlerTemplates.cxx
*
* Implementations of common event handlers.
*
* @author Balazs Racz
* @date 6 November 2013
*/
#include "nmranet/EventHandlerTemplates.hxx"
#include "if/nmranet_if.h" // for MTI values
BitRangeEventPC::BitRangeEventPC(WriteHelper::node_type node,
uint64_t event_base,
uint32_t* backing_store,
unsigned size)
: event_base_(event_base), node_(node), data_(backing_store), size_(size) {
NMRAnetEventRegistry::instance()->RegisterHandler(this, 0, 0);
}
BitRangeEventPC::~BitRangeEventPC() {
NMRAnetEventRegistry::instance()->UnregisterHandler(this, 0, 0);
}
void BitRangeEventPC::GetBitAndMask(unsigned bit,
uint32_t** data,
uint32_t* mask) const {
*data = nullptr;
if ((bit >= size_) || (bit < 0))
return;
*data = data_ + (bit >> 5);
*mask = 1 << (bit & 31);
}
bool BitRangeEventPC::Get(unsigned bit) const {
uint32_t* ofs;
uint32_t mask;
GetBitAndMask(bit, &ofs, &mask);
if (!ofs)
return false;
return (*ofs) & mask;
}
void BitRangeEventPC::Set(unsigned bit,
bool new_value,
WriteHelper* writer,
Notifiable* done) {
HASSERT(bit < size_);
uint32_t* ofs;
uint32_t mask;
GetBitAndMask(bit, &ofs, &mask);
bool old_value = new_value;
if (ofs)
old_value = (*ofs) & mask;
if (old_value != new_value) {
uint64_t event = event_base_ + bit * 2;
if (!new_value)
event++;
writer->WriteAsync(node_,
MTI_EVENT_REPORT,
WriteHelper::Global(),
EventIdToBuffer(event),
done);
} else {
if (done)
done->Notify();
}
}
void BitRangeEventPC::HandleEventReport(EventReport* event, Notifiable* done) {
done->Notify();
if (event->event < event_base_)
return;
uint64_t d = (event->event - event_base_);
bool new_value = !(d & 1);
d >>= 1;
if (d >= size_)
return;
uint32_t* ofs;
uint32_t mask;
GetBitAndMask(d, &ofs, &mask);
if (new_value) {
*ofs |= mask;
} else {
*ofs &= ~mask;
}
}
void BitRangeEventPC::HandleIdentifyProducer(EventReport* event,
Notifiable* done) {
HandleIdentifyBase(MTI_PRODUCER_IDENTIFIED_VALID, event, done);
}
void BitRangeEventPC::HandleIdentifyConsumer(EventReport* event,
Notifiable* done) {
HandleIdentifyBase(MTI_CONSUMER_IDENTIFIED_VALID, event, done);
}
void BitRangeEventPC::HandleIdentifyBase(int mti_valid,
EventReport* event,
Notifiable* done) {
if (event->event < event_base_)
return done->Notify();
uint64_t d = (event->event - event_base_);
bool new_value = !(d & 1);
d >>= 1;
if (d >= size_)
return done->Notify();
uint32_t* ofs;
uint32_t mask;
GetBitAndMask(d, &ofs, &mask);
int mti = mti_valid;
bool old_value = *ofs & mask;
if (old_value != new_value) {
mti++; // mti INVALID
}
event_write_helper1.WriteAsync(
node_, mti, WriteHelper::Global(), EventIdToBuffer(event->event), done);
}
uint64_t EncodeRange(uint64_t begin, unsigned size) {
// We assemble a valid event range identifier that covers our block.
uint64_t end = begin + size * 2;
uint64_t shift = 1;
while (begin + shift <= end) {
begin &= ~shift;
shift <<= 1;
}
if (begin & shift) {
// last real bit is 1 => range ends with zero.
return begin;
} else {
// last real bit is zero. Set all lower bits to 1.
begin |= shift - 1;
return begin;
}
}
void BitRangeEventPC::HandleIdentifyGlobal(EventReport* event,
Notifiable* done) {
uint64_t range = EncodeRange(event_base_, size_);
event_barrier.Reset(done);
event_write_helper1.WriteAsync(node_,
MTI_PRODUCER_IDENTIFIED_RANGE,
WriteHelper::Global(),
EventIdToBuffer(range),
event_barrier.NewChild());
event_write_helper2.WriteAsync(node_,
MTI_CONSUMER_IDENTIFIED_RANGE,
WriteHelper::Global(),
EventIdToBuffer(range),
event_barrier.NewChild());
event_barrier.MaybeDone();
}
<commit_msg>Adds more assertions to global event handlers.<commit_after>
/** \copyright
* Copyright (c) 2013, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file EventHandlerTemplates.cxx
*
* Implementations of common event handlers.
*
* @author Balazs Racz
* @date 6 November 2013
*/
#include "nmranet/EventHandlerTemplates.hxx"
#include "if/nmranet_if.h" // for MTI values
BitRangeEventPC::BitRangeEventPC(WriteHelper::node_type node,
uint64_t event_base,
uint32_t* backing_store,
unsigned size)
: event_base_(event_base), node_(node), data_(backing_store), size_(size) {
NMRAnetEventRegistry::instance()->RegisterHandler(this, 0, 0);
}
BitRangeEventPC::~BitRangeEventPC() {
NMRAnetEventRegistry::instance()->UnregisterHandler(this, 0, 0);
}
void BitRangeEventPC::GetBitAndMask(unsigned bit,
uint32_t** data,
uint32_t* mask) const {
*data = nullptr;
if ((bit >= size_) || (bit < 0))
return;
*data = data_ + (bit >> 5);
*mask = 1 << (bit & 31);
}
bool BitRangeEventPC::Get(unsigned bit) const {
HASSERT(bit < size_);
uint32_t* ofs;
uint32_t mask;
GetBitAndMask(bit, &ofs, &mask);
if (!ofs)
return false;
return (*ofs) & mask;
}
void BitRangeEventPC::Set(unsigned bit,
bool new_value,
WriteHelper* writer,
Notifiable* done) {
HASSERT(bit < size_);
uint32_t* ofs;
uint32_t mask;
GetBitAndMask(bit, &ofs, &mask);
bool old_value = new_value;
HASSERT(ofs);
if (ofs)
old_value = (*ofs) & mask;
if (old_value != new_value) {
uint64_t event = event_base_ + bit * 2;
if (!new_value)
event++;
writer->WriteAsync(node_,
MTI_EVENT_REPORT,
WriteHelper::Global(),
EventIdToBuffer(event),
done);
} else {
if (done)
done->Notify();
}
}
void BitRangeEventPC::HandleEventReport(EventReport* event, Notifiable* done) {
done->Notify();
if (event->event < event_base_)
return;
uint64_t d = (event->event - event_base_);
bool new_value = !(d & 1);
d >>= 1;
if (d >= size_)
return;
uint32_t* ofs;
uint32_t mask;
GetBitAndMask(d, &ofs, &mask);
if (new_value) {
*ofs |= mask;
} else {
*ofs &= ~mask;
}
}
void BitRangeEventPC::HandleIdentifyProducer(EventReport* event,
Notifiable* done) {
HandleIdentifyBase(MTI_PRODUCER_IDENTIFIED_VALID, event, done);
}
void BitRangeEventPC::HandleIdentifyConsumer(EventReport* event,
Notifiable* done) {
HandleIdentifyBase(MTI_CONSUMER_IDENTIFIED_VALID, event, done);
}
void BitRangeEventPC::HandleIdentifyBase(int mti_valid,
EventReport* event,
Notifiable* done) {
if (event->event < event_base_)
return done->Notify();
uint64_t d = (event->event - event_base_);
bool new_value = !(d & 1);
d >>= 1;
if (d >= size_)
return done->Notify();
uint32_t* ofs;
uint32_t mask;
GetBitAndMask(d, &ofs, &mask);
int mti = mti_valid;
bool old_value = *ofs & mask;
if (old_value != new_value) {
mti++; // mti INVALID
}
event_write_helper1.WriteAsync(
node_, mti, WriteHelper::Global(), EventIdToBuffer(event->event), done);
}
uint64_t EncodeRange(uint64_t begin, unsigned size) {
// We assemble a valid event range identifier that covers our block.
uint64_t end = begin + size * 2;
uint64_t shift = 1;
while (begin + shift <= end) {
begin &= ~shift;
shift <<= 1;
}
if (begin & shift) {
// last real bit is 1 => range ends with zero.
return begin;
} else {
// last real bit is zero. Set all lower bits to 1.
begin |= shift - 1;
return begin;
}
}
void BitRangeEventPC::HandleIdentifyGlobal(EventReport* event,
Notifiable* done) {
uint64_t range = EncodeRange(event_base_, size_);
event_barrier.Reset(done);
event_write_helper1.WriteAsync(node_,
MTI_PRODUCER_IDENTIFIED_RANGE,
WriteHelper::Global(),
EventIdToBuffer(range),
event_barrier.NewChild());
event_write_helper2.WriteAsync(node_,
MTI_CONSUMER_IDENTIFIED_RANGE,
WriteHelper::Global(),
EventIdToBuffer(range),
event_barrier.NewChild());
event_barrier.MaybeDone();
}
<|endoftext|> |
<commit_before>/**
* L I N E A R A L G E B R A O P C O D E S F O R C S O U N D
* Michael Gogins
*
* These opcodes implement many linear algebra operations
* from BLAS and LAPACK, up to and including eigenvalue decompositions.
* They are designed to facilitate MATLAB-style signal processing,
* and of course other mathematical operations, in the Csound orchestra language.
*
* The opcodes work with the following data types:
* 1. Real scalars, which are Csound i-rate (ir) or k-rate scalars (kr),
where x stands for either i or k (xr).
* 2. Complex scalars, which are ordered pairs of Csound scalars (xcr, xci).
* 3. Allocated real vectors (xvr).
* 4. Allocated complex vectors (xvc).
* 5. Allocated real matrices (xmr).
* 6. Allocated complex matrices (xmc).
*
* Some other Csound data types can also be used, as follows:
* 1. Csound a-rate scalars can be used as k-rate real vectors (vr).
* 2. Csound function tables (FUNC) can be used as real vectors (vr).
* 4. Csound fsigs (PVS signals, PVSDAT) can be used as complex vectors (vc).
* 5. Csound wsigs (spectral signals, SPECDAT) can be used as complex vectors (vc).
*
* Opcode names and signatures are determined as follows:
* 1. All opcode names in this library are prefixed "la_" for "linear algebra".
* 2. The opcode name is then additionally prefixed with a data type code.
* Because Csound variables have a fixed precision
* (always single or always double),
* Csound data types (r for real, c for complex) are used instead of
* BLAS data types (S, D, C, Z).
* 3. The body of the opcode name is the same as
* the body of the BLAS or LAPACK name.
* 4. The return values and parameters are prefixed
* first with the Csound rate, then with v for vector or m for matrix,
* then with the data type code, then (if a variable) with an underscore;
* as previously noted complex scalars are pairs of real scalars.
* Thus, the i-rate BLAS complex scalar a is icr_a, ici_a;
* the k-rate BLAS complex vector x is kvc_x; and
* the i-rate or k-rate BLAS real matrix A is xvr_A.
* 5. Because all Csound data types and allocated arrays
* know their own size, BLAS and LAPACK size arguments are omitted,
* except from creator functions; this is similar to the FORTRAN 95
* interface to the BLAS routines.
* 6. Operations that return scalars usually return i-rate or k-rate values
* on the left-hand side of the opcode.
* 7. Operations that return vectors or matrices always copy the return value
* into a preallocated argument on the right-hand side of the opcode.
* 8. The rate (i-rate versus k-rate or a-rate) of the result (return value)
* determines the rate of the operation. The exact same function
* is called for i-rate, k-rate, and a-rate; the only difference is that
* a function with an i-rate result is evaluated only in the init pass,
* while the same function with a k-rate or a-rate result is evaluated
* for each kperiod pass.
* 9. All arrays are 0-based.
*10. All matrices are considered to be row-major
* (x or i goes along rows, y or j goes along columns).
*11. All arrays are considered to be general and dense; therefore, the BLAS
* banded, Hermitian, symmetric, and sparse routines are not implemented.
*12. At this time, only 'driver' routines for LAPACK are implemented.
*
* For more complete information on how to use the opcodes,
* what the arguments are, which arguments are inputs, which arguments are outputs,
* and so on, consult the BLAS and LAPACK documentation,
* e.g. http://www.intel.com/software/products/mkl/docs/WebHelp/mkl.htm.
*
* The operations are:
*
* ALLOCATORS
*
* Allocate real vector.
* ivr la_rv ir_size
*
* Allocate complex vector.
* ivc la_cv ir_size
*
* Allocate real matrix, with optional diagonal.
* imr la_rm ir_rows, ir_columns [, jr_diagonal]
*
* Allocate complex matrix, with optional diagonal.
* imc la_cm irows, icolumns [, jr_diagonal, ji_diagonal]
*
* LEVEL 1 BLAS -- VECTOR-VECTOR OPERATIONS
*
* Vector-vector dot product:
* Return x * y.
* xr la_rdot xvr_x, xvr_y
* xcr, xci la_cdotu xvc_x, xvc_y
*
* Conjugate vector-vector dot product:
* Return conjg(x) * y.
* xcr, xci la_cdotc xvc_x, xvc_y
*
* Compute y := a * x + y.
* la_raxpy xr_a, xvr_x, xvr_y
* la_caxpy xr_a, xcr_x, xcr_y
*
* Givens rotation:
* Given a point in a, b,
* compute the Givens plane rotation in a, b, c, s
* that zeros the y-coordinate of the point.
* la_rrotg xr_a, xr_b, xr_c, xr_s
* la_crotg xcr_a, xci_a, xcr_b, xci_b, xcr_c, xci_c, xcr_s, xci_s
*
* Rotate a vector x by a vector y:
* For all i, x[i] = c * x[i] + s * y[i];
* For all i, y[i] = c * y[i] - s * x[i].
* la_rrot xvr_x, xvr_y, xr_c, xr_s
* la_crot xvc_x, xvc_y, xr_c, xr_s
*
* Vector copy:
* Compute y := x.
* la_rcopy xvr_x, xvr_y
* la_ccopy xcr_x, xvc_y
*
* Vector swap:
* Swap vector x with vector y.
* la_rswap xvr_x, xvr_y
* la_cswap xcr_x, xvc_y
*
* Vector norm:
* Return the Euclidean norm of vector x.
* xr rnrm2 xvr_x
* xcr, xci cnrm2 xcr_x
*
* Vector absolute value:
* Return the real sum of the absolute values of the vector elements.
* xr asum xvr_x
* xr axum xcr_x
*
* Vector scale:
* Compute x := alpha * x.
* la_rscal xr_alpha, xvr_x
* la_cscal xcr_alpha, xci_alpha, xcr_x
*
* Vector absolute maximum:
* Return the index of the maximum absolute value in vector x.
* xr la_ramax xvr_x
* xr la_camax xvc_x
*
* Vector absolute minimum:
* Return the index of the minimum absolute value in vector x.
* xr la_ramin xvr_x
* xr la_camin xvc_x
*
* LEVEL 2 BLAS -- MATRIX-VECTOR OPERATIONS
*
* Matrix-vector dot product:
* Compute y := alpha * A * x + beta * y, if trans is 0.
* Compute y := alpha * A' * x + beta * y, if trans is 1.
* Compute y := alpha * conjg(A') * x + beta * y, if trans is 2.
* la_rgemv xmr_A, xvr_x, xvr_ay [, xr_alpha][, xr_beta][, xr_trans]
* la_cgemv xmc_A, xvc_x, xvc_ay [, xcr_alpha, xci_alpha][, xcr_beta, xci_beta][, xr_trans]
*
* Rank-1 update of a matrix:
* Compute A := alpha * x * y' + A.
* la_rger xr_alpha, xvr_x, xvr_y, xmr_A
* la_cger xcr_alpha, xci_alpha, xvc_x, xvc_y, xmc_A
*
* Rank-1 update of a conjugated matrix:
* Compute A := alpha * x * conjg(y') + A
* la_rgerc xmr_A, xvr_x, xvr_y, [, xr_alpha]
* la_cgerc xmc_A, xvc_x, xvc_y, [, xcr_alpha, xci_alpha]
*
* Solve a system of linear equations:
* Coefficients are in a packed triangular matrix,
* upper triangular if uplo = 0, lower triangular if uplo = 1.
* Solve A * x = b for x, if trans = 0.
* Solve A' * x = b for x, if trans = 1.
* Solve conjg(A') * x = b for x, if trans = 2.
* la_rtpsv xmr_A, xvr_x, xvr_b [, xr_uplo][, xr_trans]
* la_ctpsv xmc_A, xvc_x, xvc_b [, xr_uplo][, xr_trans]
*
* LEVEL 3 BLAS -- MATRIX-MATRIX OPERATIONS
*
* Matrix-matrix dot product:
* Compute C := alpha * op(A) * op(B) + beta * C,
* where op(X) is X, X', or conjg(X);
* transa or transb is 0 for normal (default), 1 for transpose, 2 for conjugate;
* alpha and beta are 1 by default; set beta to 0 if you don't want to zero C first.
* la_rgemm xmr_A, xmr_B, xmr_C [, xr_transa][, xr_transb][, xr_alpha][, xr_beta]
* la_cgemm xmc_A, xmc_B, xmc_C [, xr_transa][, xr_transb][, xcr_alpha, xci_alpha][, xcr_beta, xci_beta]
*
* Solve a matrix equation:
* Solve op(A) * X = alpha * B or X * op(A) = alpha * B for X,
* where op(A) is A, A', or conjg(A);
* transa is 0 for normal, 1 for transpose, or 2 for conjugate;
* side is 0 for op(A) on the left, or 1 for op(A) on the right;
* uplo is 0 for upper triangular A, or 1 for lower triangular A;
* and diag is 0 for unit triangular A, or 1 for non-unit triangular A.
* la_rtrsm xmr_A, xmr_B [, xr_side][, xr_uplo][, xr_transa][, xr_diag] [, xr_alpha]
* la_ctrsm xmc_A, cmc_B [, xr_side][, xr_uplo][, xr_transa][, xr_diag] [, xcr_alpha, xci_alpha]
*
* LAPACK -- LINEAR SOLUTIONS
*
* Solve a system of linear equations:
* Solve A * X = B,
* where A is a square matrix of coefficients,
* the columns of B are individual right-hand sides,
* ipiv is a vector for pivot elements,
* the columns of B are replaced with the corresponding solutions,
* and info is replaced with 0 for success, -i for a bad value in the ith parameter,
* or i if U(i, i) is 0, i.e. U is singular.
* la_rgesv xmr_A, xmr_B [, xvr_ipiv][, xr_info]
* la_cgesv xmc_A, xmc_B [, xvc_ipiv][, xr_info]
*
* LAPACK -- LINEAR LEAST SQUARES PROBLEMS
*
* QR or LQ factorization:
* Minimum-norm complete orthogonal factorization:
* Minimum-normal singular value decomposition:
* Minimum-normal singular value decomposition with divide and conquer:
*
* LAPACK -- SINGULAR VALUE DECOMPOSITION
*
* Singular value decomposition of a general rectangular matrix:
* Singular value decomposition of a general rectangular matrix by divide and conquer:
*
* LAPACK -- NONSYMMETRIX EIGENPROBLEMS
*
* Computes the eigenvalues and Schur factorization of a general matrix,
* and orders the factorization so that selected eigenvalues are at the top left of the Schur form:
* Computes the eigenvalues and left and right eigenvectors of a general matrix:
*
* LAPACK -- GENERALIZED NONSYMMETRIC EIGENPROBLEMS
*
* Compute the generalized eigenvalues, Schur form,
* and the left and/or right Schur vectors for a pair of nonsymmetric matrices:
* Computes the generalized eigenvalues, and the left and/or right generalized eigenvectors
* for a pair of nonsymmetric matrices:
*
*/
extern "C"
{
// a-rate, k-rate, FUNC, SPECDAT
#include <csoundCore.h>
// PVSDAT
#include <pstream.h>
}
#include <OpcodeBase.hpp>
<commit_msg>no message<commit_after>/**
* L I N E A R A L G E B R A O P C O D E S F O R C S O U N D
* Michael Gogins
*
* These opcodes implement many linear algebra operations
* from BLAS and LAPACK, up to and including eigenvalue decompositions.
* They are designed to facilitate signal processing,
* and of course other mathematical operations,
* in the Csound orchestra language.
*
* These opcodes work with the following data types (and data type codes):
* 1. Real scalars, which are Csound i-rate (ir) or k-rate scalars (kr),
* where x stands for either i or k (xr).
* 2. Complex scalars, which are ordered pairs of Csound scalars (xcr, xci).
* 3. Allocated real vectors (xvr).
* 4. Allocated complex vectors (xvc).
* 5. Allocated real matrices (xmr).
* 6. Allocated complex matrices (xmc).
* 7. Storage for each allocated array is created using AUXCH,
* but it is used as a regular Csound variable,
* which is always a pointer to a floating-point number.
* The size and type code of the array are found
* in the first 8 bytes of storage:
* bytes 0 through 4: number of elements in the array.
* bytes 5 through 7: type code (e.g. 'imc'), encoding rate, rank, type.
* byte 8: first byte of the first element of the array.
*
* The BLAS vector-vector copy functions are overloaded,
* and can also be used for copying BLAS arrays
* to and from other Csound data types:
* 1. Csound a-rate scalars (which are already vectors)
* and function tables (i-rate scalars as function table numbers)
* can copied to and from real vectors (xvr)
* of the same size.
* 2. Csound fsigs (PVS signals, PVSDAT)
* and wsigs (spectral signals, SPECDAT)
* can be copied to and from complex vectors (xvc)
* of the same size.
*
* Opcode names and signatures are determined as follows:
* 1. All opcode names in this library are prefixed "la_" for "linear algebra".
* 2. The opcode name is then additionally prefixed with a data type code.
* Because Csound variables have a fixed precision
* (always single or always double),
* Csound data types (r for real, c for complex) are used instead of
* BLAS data types (S, D, C, Z).
* 3. The body of the opcode name is the same as
* the body of the BLAS or LAPACK name.
* 4. The return values and parameters are prefixed
* first with the Csound rate, then with v for vector or m for matrix,
* then with the data type code, then (if a variable) with an underscore;
* as previously noted complex scalars are pairs of real scalars.
* Thus, the i-rate BLAS complex scalar a is icr_a, ici_a;
* the k-rate BLAS complex vector x is kvc_x; and
* the i-rate or k-rate BLAS real matrix A is xvr_A.
* 5. Because all Csound data types and allocated arrays
* know their own size, BLAS and LAPACK size arguments are omitted,
* except from creator functions; this is similar to the FORTRAN 95
* interface to the BLAS routines.
* 6. Operations that return scalars usually return i-rate or k-rate values
* on the left-hand side of the opcode.
* 7. Operations that return vectors or matrices always copy the return value
* into a preallocated argument on the right-hand side of the opcode.
* 8. The rate (i-rate versus k-rate or a-rate) of either the return value,
* or the first argument if there is no return value, determines
* the rate of the operation. The exact same function is called
* for i-rate, k-rate, and a-rate opcodes;
* the only difference is that an i-rate opcode is evaluated only in the init pass,
* while a k-rate or a-rate opcode is evaluated in each kperiod pass.
* 9. All arrays are 0-based.
*10. All matrices are considered to be row-major
* (x or i goes along rows, y or j goes along columns).
*11. All arrays are considered to be general and dense; therefore, the BLAS
* banded, Hermitian, symmetric, and sparse routines are not implemented.
*12. At this time, only the general-purpose 'driver' routines
* for LAPACK are implemented.
*
* For more complete information on how to use the opcodes,
* what the arguments are, which arguments are inputs, which arguments are outputs,
* and so on, consult BLAS and LAPACK documentation,
* e.g. http://www.intel.com/software/products/mkl/docs/WebHelp/mkl.htm.
*
* The operations are:
*
* ALLOCATORS
*
* Allocate real vector.
* xvr la_rv ir_size
*
* Allocate complex vector.
* xvc la_cv ir_size
*
* Allocate real matrix, with optional diagonal.
* xmr la_rm ir_rows, ir_columns [, or_diagonal]
*
* Allocate complex matrix, with optional diagonal.
* xmc la_cm irows, icolumns [, or_diagonal, oi_diagonal]
*
* LEVEL 1 BLAS -- VECTOR-VECTOR OPERATIONS
*
* Vector-vector dot product:
* Return x * y.
* xr la_rdot xvr_x, xvr_y
* xcr, xci la_cdotu xvc_x, xvc_y
*
* Conjugate vector-vector dot product:
* Return conjg(x) * y.
* xcr, xci la_cdotc xvc_x, xvc_y
*
* Compute y := a * x + y.
* la_raxpy xr_a, xvr_x, xvr_y
* la_caxpy xr_a, xcr_x, xcr_y
*
* Givens rotation:
* Given a point in a, b,
* compute the Givens plane rotation in a, b, c, s
* that zeros the y-coordinate of the point.
* la_rrotg xr_a, xr_b, xr_c, xr_s
* la_crotg xcr_a, xci_a, xcr_b, xci_b, xcr_c, xci_c, xcr_s, xci_s
*
* Rotate a vector x by a vector y:
* For all i, x[i] = c * x[i] + s * y[i];
* For all i, y[i] = c * y[i] - s * x[i].
* la_rrot xvr_x, xvr_y, xr_c, xr_s
* la_crot xvc_x, xvc_y, xr_c, xr_s
*
* Vector copy:
* Compute y := x.
* Note that x or y can be a-rate, function table number,
*
* la_rcopy xvr_x, xvr_y
* la_ccopy xcr_x, xvc_y
*
* Vector swap:
* Swap vector x with vector y.
* la_rswap xvr_x, xvr_y
* la_cswap xcr_x, xvc_y
*
* Vector norm:
* Return the Euclidean norm of vector x.
* xr rnrm2 xvr_x
* xcr, xci cnrm2 xcr_x
*
* Vector absolute value:
* Return the real sum of the absolute values of the vector elements.
* xr asum xvr_x
* xr axum xcr_x
*
* Vector scale:
* Compute x := alpha * x.
* la_rscal xr_alpha, xvr_x
* la_cscal xcr_alpha, xci_alpha, xcr_x
*
* Vector absolute maximum:
* Return the index of the maximum absolute value in vector x.
* xr la_ramax xvr_x
* xr la_camax xvc_x
*
* Vector absolute minimum:
* Return the index of the minimum absolute value in vector x.
* xr la_ramin xvr_x
* xr la_camin xvc_x
*
* LEVEL 2 BLAS -- MATRIX-VECTOR OPERATIONS
*
* Matrix-vector dot product:
* Compute y := alpha * A * x + beta * y, if trans is 0.
* Compute y := alpha * A' * x + beta * y, if trans is 1.
* Compute y := alpha * conjg(A') * x + beta * y, if trans is 2.
* la_rgemv xmr_A, xvr_x, xvr_ay [, Pr_alpha][, or_beta][, or_trans]
* la_cgemv xmc_A, xvc_x, xvc_ay [, Pcr_alpha, oci_alpha][, ocr_beta, oci_beta][, or_trans]
*
* Rank-1 update of a matrix:
* Compute A := alpha * x * y' + A.
* la_rger xr_alpha, xvr_x, xvr_y, xmr_A
* la_cger xcr_alpha, xci_alpha, xvc_x, xvc_y, xmc_A
*
* Rank-1 update of a conjugated matrix:
* Compute A := alpha * x * conjg(y') + A
* la_rgerc xmr_A, xvr_x, xvr_y, [, Pr_alpha]
* la_cgerc xmc_A, xvc_x, xvc_y, [, Pcr_alpha, oci_alpha]
*
* Solve a system of linear equations:
* Coefficients are in a packed triangular matrix,
* upper triangular if uplo = 0, lower triangular if uplo = 1.
* Solve A * x = b for x, if trans = 0.
* Solve A' * x = b for x, if trans = 1.
* Solve conjg(A') * x = b for x, if trans = 2.
* la_rtpsv xmr_A, xvr_x, xvr_b [, or_uplo][, or_trans]
* la_ctpsv xmc_A, xvc_x, xvc_b [, or_uplo][, or_trans]
*
* LEVEL 3 BLAS -- MATRIX-MATRIX OPERATIONS
*
* Matrix-matrix dot product:
* Compute C := alpha * op(A) * op(B) + beta * C,
* where transa or transb is 0 if op(X) is X, 1 if op(X) is X', or 2 if op(X) is conjg(X);
* alpha and beta are 1 by default (set beta to 0 if you don't want to zero C first).
* la_rgemm xmr_A, xmr_B, xmr_C [, or_transa][, or_transb][, Pr_alpha][, Pr_beta]
* la_cgemm xmc_A, xmc_B, xmc_C [, or_transa][, or_transb][, Pcr_alpha, oci_alpha][, Pcr_beta, oci_beta]
*
* Solve a matrix equation:
* Solve op(A) * X = alpha * B or X * op(A) = alpha * B for X,
* where transa is 0 if op(X) is X, 1 if op(X) is X', or 2 if op(X) is conjg(X);
* side is 0 for op(A) on the left, or 1 for op(A) on the right;
* uplo is 0 for upper triangular A, or 1 for lower triangular A;
* and diag is 0 for unit triangular A, or 1 for non-unit triangular A.
* la_rtrsm xmr_A, xmr_B [, or_side][, or_uplo][, or_transa][, or_diag] [, Pr_alpha]
* la_ctrsm xmc_A, cmc_B [, or_side][, or_uplo][, or_transa][, or_diag] [, Pcr_alpha, oci_alpha]
*
* LAPACK -- LINEAR SOLUTIONS
*
* Solve a system of linear equations:
* Solve A * X = B,
* where A is a square matrix of coefficients,
* the columns of B are individual right-hand sides,
* ipiv is a vector for pivot elements,
* the columns of B are replaced with the corresponding solutions,
* and info is replaced with 0 for success, -i for a bad value in the ith parameter,
* or i if U(i, i) is 0, i.e. U is singular.
* la_rgesv xmr_A, xmr_B [, ovr_ipiv][, or_info]
* la_cgesv xmc_A, xmc_B [, ovc_ipiv][, or_info]
*
* LAPACK -- LINEAR LEAST SQUARES PROBLEMS
*
* QR or LQ factorization:
* Uses QR or LQ factorization to solve an overdetermined or underdetermined
* linear system with full rank matrix,
* where A is the m x n matrix to factor;
* B is an m x number of right-hand sides,
* containing B as input and solution X as result;
* if trans = 0, A is normal;
* if trans = 1, A is transposed (real matrices only);
* if trans = 2, A is conjugate-transposed (complex matrices only);
* and info is replaced with 0 for success, -i for a bad value in the ith parameter,
* or i if U(i, i) is 0, the i-th diagonal element of the triangular factor
* of A is zero, so that A does not have full rank; the least squares solution could not be computed.
* la_rgels xmr_A, xmr_B [, or_trans] [, or_info]
*
* LAPACK -- SINGULAR VALUE DECOMPOSITION
*
* Singular value decomposition of a general rectangular matrix:
* Singular value decomposition of a general rectangular matrix by divide and conquer:
*
* LAPACK -- NONSYMMETRIX EIGENPROBLEMS
*
* Computes the eigenvalues and Schur factorization of a general matrix,
* and orders the factorization so that selected eigenvalues are at the top left of the Schur form:
* Computes the eigenvalues and left and right eigenvectors of a general matrix:
*
* LAPACK -- GENERALIZED NONSYMMETRIC EIGENPROBLEMS
*
* Compute the generalized eigenvalues, Schur form,
* and the left and/or right Schur vectors for a pair of nonsymmetric matrices:
* Computes the generalized eigenvalues, and the left and/or right generalized eigenvectors
* for a pair of nonsymmetric matrices:
*
*/
extern "C"
{
// a-rate, k-rate, FUNC, SPECDAT
#include <csoundCore.h>
// PVSDAT
#include <pstream.h>
}
/**
* Used for all types of arrays
* (vectors and matrices, real and complex).
*/
struct BLASArray
{
size_t elements;
char[4] typecode;
MYFLT *data;
};
#include <OpcodeBase.hpp>
<|endoftext|> |
<commit_before>// libmesh includes
#include <libmesh/elem.h>
#include <libmesh/enum_elem_type.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/mesh.h>
// unit test includes
#include "test_comm.h"
#include "libmesh_cppunit.h"
using namespace libMesh;
class VolumeTest : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE( VolumeTest );
CPPUNIT_TEST( testEdge3Volume );
CPPUNIT_TEST_SUITE_END();
public:
void setUp()
{
}
void tearDown()
{
}
void testEdge3Volume()
{
Mesh mesh(*TestCommWorld);
MeshTools::Generation::build_line (mesh, /*nelem=*/1, 0., 1., EDGE3);
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(3), mesh.n_nodes());
auto edge3 = mesh.elem_ptr(0);
// Check unperturbed, straight edge case
LIBMESH_ASSERT_FP_EQUAL(1.0, edge3->volume(), TOLERANCE*TOLERANCE);
// Check middle node perturbed in +x direction case. This should
// not change the volume because it's still a straight line
// element.
Real & middle_node_x = edge3->node_ref(2)(0);
middle_node_x += 1.e-3;
LIBMESH_ASSERT_FP_EQUAL(1.0, edge3->volume(), TOLERANCE*TOLERANCE);
// Check middle node perturbed in +x direction case. This should
// not change the volume because it's still a straight line
// element.
middle_node_x -= 2.e-3;
LIBMESH_ASSERT_FP_EQUAL(1.0, edge3->volume(), TOLERANCE*TOLERANCE);
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( VolumeTest );
<commit_msg>Add tests of curved element volume.<commit_after>// libmesh includes
#include <libmesh/elem.h>
#include <libmesh/enum_elem_type.h>
#include <libmesh/mesh_generation.h>
#include <libmesh/mesh.h>
// unit test includes
#include "test_comm.h"
#include "libmesh_cppunit.h"
using namespace libMesh;
class VolumeTest : public CppUnit::TestCase
{
public:
CPPUNIT_TEST_SUITE( VolumeTest );
CPPUNIT_TEST( testEdge3Volume );
CPPUNIT_TEST_SUITE_END();
public:
void setUp()
{
}
void tearDown()
{
}
void testEdge3Volume()
{
Mesh mesh(*TestCommWorld);
MeshTools::Generation::build_line (mesh, /*nelem=*/1, 0., 1., EDGE3);
CPPUNIT_ASSERT_EQUAL(static_cast<dof_id_type>(3), mesh.n_nodes());
auto edge3 = mesh.elem_ptr(0);
// Check unperturbed, straight edge case
LIBMESH_ASSERT_FP_EQUAL(1.0, edge3->volume(), TOLERANCE*TOLERANCE);
// Get references to the individual Edge3 nodes
auto & middle_node = edge3->node_ref(2);
auto & right_node = edge3->node_ref(1);
// Check middle node perturbed in +x direction case. This should
// not change the volume because it's still a straight line
// element.
middle_node = Point(0.5 + 1.e-3, 0., 0.);
LIBMESH_ASSERT_FP_EQUAL(1.0, edge3->volume(), TOLERANCE*TOLERANCE);
// Check middle node perturbed in -x direction case. This should
// not change the volume because it's still a straight line
// element.
middle_node = Point(0.5 - 1.e-3, 0., 0.);
LIBMESH_ASSERT_FP_EQUAL(1.0, edge3->volume(), TOLERANCE*TOLERANCE);
// Check volume of actual curved element against pre-computed value.
middle_node = Point(0.5, 0.25, 0.);
right_node = Point(1., 1., 0.);
LIBMESH_ASSERT_FP_EQUAL(1.4789428575446, edge3->volume(), TOLERANCE);
// Compare with volume computed by base class Elem::volume() call
// which uses quadrature. We don't expect this to have full
// floating point accuracy.
middle_node = Point(0.5, 0.1, 0.);
right_node = Point(1., 0., 0.);
LIBMESH_ASSERT_FP_EQUAL(edge3->Elem::volume(), edge3->volume(), std::sqrt(TOLERANCE));
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( VolumeTest );
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
////////////////////////////////////////////////////////////////////////////////
#include "Thread.h"
#include <errno.h>
#include <signal.h>
#include "ApplicationFeatures/ApplicationServer.h"
#include "Basics/ConditionLocker.h"
#include "Basics/Exceptions.h"
#include "Basics/WorkMonitor.h"
#include "Logger/Logger.h"
#include <velocypack/Builder.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::basics;
////////////////////////////////////////////////////////////////////////////////
/// @brief local thread number
////////////////////////////////////////////////////////////////////////////////
static thread_local uint64_t LOCAL_THREAD_NUMBER = 0;
#if !defined(ARANGODB_HAVE_GETTID) && !defined(_WIN32)
namespace {
std::atomic<uint64_t> NEXT_THREAD_ID(1);
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// @brief current work description as thread local variable
////////////////////////////////////////////////////////////////////////////////
thread_local Thread* Thread::CURRENT_THREAD = nullptr;
////////////////////////////////////////////////////////////////////////////////
/// @brief static started with access to the private variables
////////////////////////////////////////////////////////////////////////////////
void Thread::startThread(void* arg) {
#if defined(ARANGODB_HAVE_GETTID)
LOCAL_THREAD_NUMBER = (uint64_t)gettid();
#elif defined(_WIN32)
LOCAL_THREAD_NUMBER = (uint64_t)GetCurrentThreadId();
#else
LOCAL_THREAD_NUMBER = NEXT_THREAD_ID.fetch_add(1, std::memory_order_seq_cst);
#endif
TRI_ASSERT(arg != nullptr);
Thread* ptr = static_cast<Thread*>(arg);
TRI_ASSERT(ptr != nullptr);
ptr->_threadNumber = LOCAL_THREAD_NUMBER;
bool pushed = WorkMonitor::pushThread(ptr);
try {
ptr->runMe();
} catch (std::exception const& ex) {
LOG_TOPIC(WARN, Logger::THREADS) << "caught exception in thread '" << ptr->_name
<< "': " << ex.what();
if (pushed) {
WorkMonitor::popThread(ptr);
}
throw;
} catch (...) {
if (pushed) {
WorkMonitor::popThread(ptr);
}
throw;
}
if (pushed) {
WorkMonitor::popThread(ptr);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief returns the process id
////////////////////////////////////////////////////////////////////////////////
TRI_pid_t Thread::currentProcessId() {
#ifdef _WIN32
return _getpid();
#else
return getpid();
#endif
}
////////////////////////////////////////////////////////////////////////////////
/// @brief returns the thread process id
////////////////////////////////////////////////////////////////////////////////
uint64_t Thread::currentThreadNumber() { return LOCAL_THREAD_NUMBER; }
////////////////////////////////////////////////////////////////////////////////
/// @brief returns the thread id
////////////////////////////////////////////////////////////////////////////////
TRI_tid_t Thread::currentThreadId() {
#ifdef TRI_HAVE_WIN32_THREADS
return GetCurrentThreadId();
#else
#ifdef TRI_HAVE_POSIX_THREADS
return pthread_self();
#else
#error "Thread::currentThreadId not implemented"
#endif
#endif
}
std::string Thread::stringify(ThreadState state) {
switch (state) {
case ThreadState::CREATED:
return "created";
case ThreadState::STARTED:
return "started";
case ThreadState::STOPPING:
return "stopping";
case ThreadState::STOPPED:
return "stopped";
case ThreadState::DETACHED:
return "detached";
}
return "unknown";
}
////////////////////////////////////////////////////////////////////////////////
/// @brief constructs a thread
////////////////////////////////////////////////////////////////////////////////
Thread::Thread(std::string const& name)
: _name(name),
_thread(),
_threadNumber(0),
_threadId(),
_finishedCondition(nullptr),
_state(ThreadState::CREATED),
_affinity(-1),
_workDescription(nullptr) {
TRI_InitThread(&_thread);
// allow failing memory allocations for all threads by default
TRI_AllowMemoryFailures();
}
////////////////////////////////////////////////////////////////////////////////
/// @brief deletes the thread
////////////////////////////////////////////////////////////////////////////////
Thread::~Thread() {
auto state = _state.load();
LOG_TOPIC(TRACE, Logger::THREADS) << "delete(" << _name
<< "), state: " << stringify(state);
if (state == ThreadState::STOPPED) {
int res = TRI_JoinThread(&_thread);
if (res != 0) {
LOG_TOPIC(INFO, Logger::THREADS) << "cannot detach thread";
}
_state.store(ThreadState::DETACHED);
return;
}
state = _state.load();
if (state != ThreadState::DETACHED && state != ThreadState::CREATED) {
LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "thread '" << _name << "' is not detached but " << stringify(state)
<< ". shutting down hard";
FATAL_ERROR_ABORT();
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief flags the thread as stopping
////////////////////////////////////////////////////////////////////////////////
void Thread::beginShutdown() {
LOG_TOPIC(TRACE, Logger::THREADS)
<< "beginShutdown(" << _name << ") in state " << stringify(_state.load());
ThreadState state = _state.load();
while (state == ThreadState::CREATED) {
_state.compare_exchange_strong(state, ThreadState::STOPPED);
}
while (state != ThreadState::STOPPING && state != ThreadState::STOPPED &&
state != ThreadState::DETACHED) {
_state.compare_exchange_strong(state, ThreadState::STOPPING);
}
LOG_TOPIC(TRACE, Logger::THREADS) << "beginShutdown(" << _name
<< ") reached state "
<< stringify(_state.load());
}
////////////////////////////////////////////////////////////////////////////////
/// @brief called from the destructor
////////////////////////////////////////////////////////////////////////////////
void Thread::shutdown() {
LOG_TOPIC(TRACE, Logger::THREADS) << "shutdown(" << _name << ")";
ThreadState state = _state.load();
while (state == ThreadState::CREATED) {
bool res = _state.compare_exchange_strong(state, ThreadState::DETACHED);
if (res) {
return;
}
}
if (_state.load() == ThreadState::STARTED) {
beginShutdown();
if (!isSilent() && _state.load() != ThreadState::STOPPING) {
LOG_TOPIC(WARN, Logger::THREADS) << "forcefully shutting down thread '"
<< _name << "' in state "
<< stringify(_state.load());
}
}
size_t n = 10 * 60 * 5; // * 100ms = 1s * 60 * 5
for (size_t i = 0; i < n; ++i) {
if (_state.load() == ThreadState::STOPPED) {
break;
}
usleep(100 * 1000);
}
if (_state.load() != ThreadState::STOPPED) {
LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "cannot shutdown thread, giving up";
FATAL_ERROR_ABORT();
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief checks if the current thread was asked to stop
////////////////////////////////////////////////////////////////////////////////
bool Thread::isStopping() const {
auto state = _state.load(std::memory_order_relaxed);
return state == ThreadState::STOPPING || state == ThreadState::STOPPED ||
state == ThreadState::DETACHED;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief starts the thread
////////////////////////////////////////////////////////////////////////////////
bool Thread::start(ConditionVariable* finishedCondition) {
if (!isSystem() && !ApplicationServer::isPrepared()) {
LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "trying to start a thread '" << _name
<< "' before prepare has finished, current state: "
<< (ApplicationServer::server == nullptr
? -1
: (int)ApplicationServer::server->state());
FATAL_ERROR_ABORT();
}
_finishedCondition = finishedCondition;
ThreadState state = _state.load();
if (state != ThreadState::CREATED) {
LOG_TOPIC(FATAL, Logger::THREADS)
<< "called started on an already started thread, thread is in state "
<< stringify(state);
FATAL_ERROR_ABORT();
}
ThreadState expected = ThreadState::CREATED;
bool res = _state.compare_exchange_strong(expected, ThreadState::STARTED);
if (!res) {
LOG_TOPIC(WARN, Logger::THREADS)
<< "thread died before it could start, thread is in state "
<< stringify(expected);
return false;
}
bool ok =
TRI_StartThread(&_thread, &_threadId, _name.c_str(), &startThread, this);
if (ok) {
if (0 <= _affinity) {
TRI_SetProcessorAffinity(&_thread, _affinity);
}
} else {
_state.store(ThreadState::STOPPED);
LOG_TOPIC(ERR, Logger::THREADS) << "could not start thread '" << _name
<< "': " << TRI_last_error();
return false;
}
return ok;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief sets the process affinity
////////////////////////////////////////////////////////////////////////////////
void Thread::setProcessorAffinity(size_t c) { _affinity = (int)c; }
////////////////////////////////////////////////////////////////////////////////
/// @brief sets the current work description
////////////////////////////////////////////////////////////////////////////////
void Thread::setWorkDescription(WorkDescription* desc) {
_workDescription.store(desc);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief sets the previous work description
////////////////////////////////////////////////////////////////////////////////
WorkDescription* Thread::setPrevWorkDescription() {
return _workDescription.exchange(_workDescription.load()->_prev.load());
}
////////////////////////////////////////////////////////////////////////////////
/// @brief sets status
////////////////////////////////////////////////////////////////////////////////
void Thread::addStatus(VPackBuilder* b) {
b->add("affinity", VPackValue(_affinity));
switch (_state.load()) {
case ThreadState::CREATED:
b->add("started", VPackValue("created"));
break;
case ThreadState::STARTED:
b->add("started", VPackValue("started"));
break;
case ThreadState::STOPPING:
b->add("started", VPackValue("stopping"));
break;
case ThreadState::STOPPED:
b->add("started", VPackValue("stopped"));
break;
case ThreadState::DETACHED:
b->add("started", VPackValue("detached"));
break;
}
}
void Thread::runMe() {
try {
run();
_state.store(ThreadState::STOPPED);
} catch (Exception const& ex) {
LOG_TOPIC(ERR, Logger::THREADS) << "exception caught in thread '" << _name
<< "': " << ex.what();
Logger::flush();
_state.store(ThreadState::STOPPED);
throw;
} catch (std::exception const& ex) {
LOG_TOPIC(ERR, Logger::THREADS) << "exception caught in thread '" << _name
<< "': " << ex.what();
Logger::flush();
_state.store(ThreadState::STOPPED);
throw;
} catch (...) {
if (!isSilent()) {
LOG_TOPIC(ERR, Logger::THREADS) << "exception caught in thread '" << _name
<< "'";
Logger::flush();
}
_state.store(ThreadState::STOPPED);
throw;
}
if (_finishedCondition != nullptr) {
CONDITION_LOCKER(locker, *_finishedCondition);
locker.broadcast();
}
}
<commit_msg>suppress non-error warnings on shutdown<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
////////////////////////////////////////////////////////////////////////////////
#include "Thread.h"
#include <errno.h>
#include <signal.h>
#include "ApplicationFeatures/ApplicationServer.h"
#include "Basics/ConditionLocker.h"
#include "Basics/Exceptions.h"
#include "Basics/WorkMonitor.h"
#include "Logger/Logger.h"
#include <velocypack/Builder.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::basics;
////////////////////////////////////////////////////////////////////////////////
/// @brief local thread number
////////////////////////////////////////////////////////////////////////////////
static thread_local uint64_t LOCAL_THREAD_NUMBER = 0;
#if !defined(ARANGODB_HAVE_GETTID) && !defined(_WIN32)
namespace {
std::atomic<uint64_t> NEXT_THREAD_ID(1);
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// @brief current work description as thread local variable
////////////////////////////////////////////////////////////////////////////////
thread_local Thread* Thread::CURRENT_THREAD = nullptr;
////////////////////////////////////////////////////////////////////////////////
/// @brief static started with access to the private variables
////////////////////////////////////////////////////////////////////////////////
void Thread::startThread(void* arg) {
#if defined(ARANGODB_HAVE_GETTID)
LOCAL_THREAD_NUMBER = (uint64_t)gettid();
#elif defined(_WIN32)
LOCAL_THREAD_NUMBER = (uint64_t)GetCurrentThreadId();
#else
LOCAL_THREAD_NUMBER = NEXT_THREAD_ID.fetch_add(1, std::memory_order_seq_cst);
#endif
TRI_ASSERT(arg != nullptr);
Thread* ptr = static_cast<Thread*>(arg);
TRI_ASSERT(ptr != nullptr);
ptr->_threadNumber = LOCAL_THREAD_NUMBER;
bool pushed = WorkMonitor::pushThread(ptr);
try {
ptr->runMe();
} catch (std::exception const& ex) {
LOG_TOPIC(WARN, Logger::THREADS) << "caught exception in thread '" << ptr->_name
<< "': " << ex.what();
if (pushed) {
WorkMonitor::popThread(ptr);
}
throw;
} catch (...) {
if (pushed) {
WorkMonitor::popThread(ptr);
}
throw;
}
if (pushed) {
WorkMonitor::popThread(ptr);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief returns the process id
////////////////////////////////////////////////////////////////////////////////
TRI_pid_t Thread::currentProcessId() {
#ifdef _WIN32
return _getpid();
#else
return getpid();
#endif
}
////////////////////////////////////////////////////////////////////////////////
/// @brief returns the thread process id
////////////////////////////////////////////////////////////////////////////////
uint64_t Thread::currentThreadNumber() { return LOCAL_THREAD_NUMBER; }
////////////////////////////////////////////////////////////////////////////////
/// @brief returns the thread id
////////////////////////////////////////////////////////////////////////////////
TRI_tid_t Thread::currentThreadId() {
#ifdef TRI_HAVE_WIN32_THREADS
return GetCurrentThreadId();
#else
#ifdef TRI_HAVE_POSIX_THREADS
return pthread_self();
#else
#error "Thread::currentThreadId not implemented"
#endif
#endif
}
std::string Thread::stringify(ThreadState state) {
switch (state) {
case ThreadState::CREATED:
return "created";
case ThreadState::STARTED:
return "started";
case ThreadState::STOPPING:
return "stopping";
case ThreadState::STOPPED:
return "stopped";
case ThreadState::DETACHED:
return "detached";
}
return "unknown";
}
////////////////////////////////////////////////////////////////////////////////
/// @brief constructs a thread
////////////////////////////////////////////////////////////////////////////////
Thread::Thread(std::string const& name)
: _name(name),
_thread(),
_threadNumber(0),
_threadId(),
_finishedCondition(nullptr),
_state(ThreadState::CREATED),
_affinity(-1),
_workDescription(nullptr) {
TRI_InitThread(&_thread);
// allow failing memory allocations for all threads by default
TRI_AllowMemoryFailures();
}
////////////////////////////////////////////////////////////////////////////////
/// @brief deletes the thread
////////////////////////////////////////////////////////////////////////////////
Thread::~Thread() {
auto state = _state.load();
LOG_TOPIC(TRACE, Logger::THREADS) << "delete(" << _name
<< "), state: " << stringify(state);
if (state == ThreadState::STOPPED) {
int res = TRI_JoinThread(&_thread);
if (res != 0) {
LOG_TOPIC(INFO, Logger::THREADS) << "cannot detach thread";
}
_state.store(ThreadState::DETACHED);
return;
}
state = _state.load();
if (state != ThreadState::DETACHED && state != ThreadState::CREATED) {
LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "thread '" << _name << "' is not detached but " << stringify(state)
<< ". shutting down hard";
FATAL_ERROR_ABORT();
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief flags the thread as stopping
////////////////////////////////////////////////////////////////////////////////
void Thread::beginShutdown() {
LOG_TOPIC(TRACE, Logger::THREADS)
<< "beginShutdown(" << _name << ") in state " << stringify(_state.load());
ThreadState state = _state.load();
while (state == ThreadState::CREATED) {
_state.compare_exchange_strong(state, ThreadState::STOPPED);
}
while (state != ThreadState::STOPPING && state != ThreadState::STOPPED &&
state != ThreadState::DETACHED) {
_state.compare_exchange_strong(state, ThreadState::STOPPING);
}
LOG_TOPIC(TRACE, Logger::THREADS) << "beginShutdown(" << _name
<< ") reached state "
<< stringify(_state.load());
}
////////////////////////////////////////////////////////////////////////////////
/// @brief called from the destructor
////////////////////////////////////////////////////////////////////////////////
void Thread::shutdown() {
LOG_TOPIC(TRACE, Logger::THREADS) << "shutdown(" << _name << ")";
ThreadState state = _state.load();
while (state == ThreadState::CREATED) {
bool res = _state.compare_exchange_strong(state, ThreadState::DETACHED);
if (res) {
return;
}
}
if (_state.load() == ThreadState::STARTED) {
beginShutdown();
if (!isSilent() &&
_state.load() != ThreadState::STOPPING &&
_state.load() != ThreadState::STOPPED) {
LOG_TOPIC(WARN, Logger::THREADS) << "forcefully shutting down thread '"
<< _name << "' in state "
<< stringify(_state.load());
}
}
size_t n = 10 * 60 * 5; // * 100ms = 1s * 60 * 5
for (size_t i = 0; i < n; ++i) {
if (_state.load() == ThreadState::STOPPED) {
break;
}
usleep(100 * 1000);
}
if (_state.load() != ThreadState::STOPPED) {
LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "cannot shutdown thread, giving up";
FATAL_ERROR_ABORT();
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief checks if the current thread was asked to stop
////////////////////////////////////////////////////////////////////////////////
bool Thread::isStopping() const {
auto state = _state.load(std::memory_order_relaxed);
return state == ThreadState::STOPPING || state == ThreadState::STOPPED ||
state == ThreadState::DETACHED;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief starts the thread
////////////////////////////////////////////////////////////////////////////////
bool Thread::start(ConditionVariable* finishedCondition) {
if (!isSystem() && !ApplicationServer::isPrepared()) {
LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "trying to start a thread '" << _name
<< "' before prepare has finished, current state: "
<< (ApplicationServer::server == nullptr
? -1
: (int)ApplicationServer::server->state());
FATAL_ERROR_ABORT();
}
_finishedCondition = finishedCondition;
ThreadState state = _state.load();
if (state != ThreadState::CREATED) {
LOG_TOPIC(FATAL, Logger::THREADS)
<< "called started on an already started thread, thread is in state "
<< stringify(state);
FATAL_ERROR_ABORT();
}
ThreadState expected = ThreadState::CREATED;
bool res = _state.compare_exchange_strong(expected, ThreadState::STARTED);
if (!res) {
LOG_TOPIC(WARN, Logger::THREADS)
<< "thread died before it could start, thread is in state "
<< stringify(expected);
return false;
}
bool ok =
TRI_StartThread(&_thread, &_threadId, _name.c_str(), &startThread, this);
if (ok) {
if (0 <= _affinity) {
TRI_SetProcessorAffinity(&_thread, _affinity);
}
} else {
_state.store(ThreadState::STOPPED);
LOG_TOPIC(ERR, Logger::THREADS) << "could not start thread '" << _name
<< "': " << TRI_last_error();
return false;
}
return ok;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief sets the process affinity
////////////////////////////////////////////////////////////////////////////////
void Thread::setProcessorAffinity(size_t c) { _affinity = (int)c; }
////////////////////////////////////////////////////////////////////////////////
/// @brief sets the current work description
////////////////////////////////////////////////////////////////////////////////
void Thread::setWorkDescription(WorkDescription* desc) {
_workDescription.store(desc);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief sets the previous work description
////////////////////////////////////////////////////////////////////////////////
WorkDescription* Thread::setPrevWorkDescription() {
return _workDescription.exchange(_workDescription.load()->_prev.load());
}
////////////////////////////////////////////////////////////////////////////////
/// @brief sets status
////////////////////////////////////////////////////////////////////////////////
void Thread::addStatus(VPackBuilder* b) {
b->add("affinity", VPackValue(_affinity));
switch (_state.load()) {
case ThreadState::CREATED:
b->add("started", VPackValue("created"));
break;
case ThreadState::STARTED:
b->add("started", VPackValue("started"));
break;
case ThreadState::STOPPING:
b->add("started", VPackValue("stopping"));
break;
case ThreadState::STOPPED:
b->add("started", VPackValue("stopped"));
break;
case ThreadState::DETACHED:
b->add("started", VPackValue("detached"));
break;
}
}
void Thread::runMe() {
try {
run();
_state.store(ThreadState::STOPPED);
} catch (Exception const& ex) {
LOG_TOPIC(ERR, Logger::THREADS) << "exception caught in thread '" << _name
<< "': " << ex.what();
Logger::flush();
_state.store(ThreadState::STOPPED);
throw;
} catch (std::exception const& ex) {
LOG_TOPIC(ERR, Logger::THREADS) << "exception caught in thread '" << _name
<< "': " << ex.what();
Logger::flush();
_state.store(ThreadState::STOPPED);
throw;
} catch (...) {
if (!isSilent()) {
LOG_TOPIC(ERR, Logger::THREADS) << "exception caught in thread '" << _name
<< "'";
Logger::flush();
}
_state.store(ThreadState::STOPPED);
throw;
}
if (_finishedCondition != nullptr) {
CONDITION_LOCKER(locker, *_finishedCondition);
locker.broadcast();
}
}
<|endoftext|> |
<commit_before>//===- lib/MC/MCStreamer.cpp - Streaming Machine Code Output --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
MCStreamer::MCStreamer(MCContext &_Context) : Context(_Context), CurSection(0) {
}
MCStreamer::~MCStreamer() {
}
raw_ostream &MCStreamer::GetCommentOS() {
// By default, discard comments.
return nulls();
}
/// EmitIntValue - Special case of EmitValue that avoids the client having to
/// pass in a MCExpr for constant integers.
void MCStreamer::EmitIntValue(uint64_t Value, unsigned Size,
unsigned AddrSpace) {
EmitValue(MCConstantExpr::Create(Value, getContext()), Size, AddrSpace);
}
void MCStreamer::EmitSymbolValue(const MCSymbol *Sym, unsigned Size,
unsigned AddrSpace) {
EmitValue(MCSymbolRefExpr::Create(Sym, getContext()), Size, AddrSpace);
}
/// EmitFill - Emit NumBytes bytes worth of the value specified by
/// FillValue. This implements directives such as '.space'.
void MCStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
unsigned AddrSpace) {
const MCExpr *E = MCConstantExpr::Create(FillValue, getContext());
for (uint64_t i = 0, e = NumBytes; i != e; ++i)
EmitValue(E, 1, AddrSpace);
}
/// EmitRawText - If this file is backed by a assembly streamer, this dumps
/// the specified string in the output .s file. This capability is
/// indicated by the hasRawTextSupport() predicate.
void MCStreamer::EmitRawText(StringRef String) {
errs() << "EmitRawText called on an MCStreamer that doesn't support it, "
" something must not be fully mc'ized\n";
abort();
}
<commit_msg>add <cstdlib> header for abort() on linux builders.<commit_after>//===- lib/MC/MCStreamer.cpp - Streaming Machine Code Output --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdlib>
using namespace llvm;
MCStreamer::MCStreamer(MCContext &_Context) : Context(_Context), CurSection(0) {
}
MCStreamer::~MCStreamer() {
}
raw_ostream &MCStreamer::GetCommentOS() {
// By default, discard comments.
return nulls();
}
/// EmitIntValue - Special case of EmitValue that avoids the client having to
/// pass in a MCExpr for constant integers.
void MCStreamer::EmitIntValue(uint64_t Value, unsigned Size,
unsigned AddrSpace) {
EmitValue(MCConstantExpr::Create(Value, getContext()), Size, AddrSpace);
}
void MCStreamer::EmitSymbolValue(const MCSymbol *Sym, unsigned Size,
unsigned AddrSpace) {
EmitValue(MCSymbolRefExpr::Create(Sym, getContext()), Size, AddrSpace);
}
/// EmitFill - Emit NumBytes bytes worth of the value specified by
/// FillValue. This implements directives such as '.space'.
void MCStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
unsigned AddrSpace) {
const MCExpr *E = MCConstantExpr::Create(FillValue, getContext());
for (uint64_t i = 0, e = NumBytes; i != e; ++i)
EmitValue(E, 1, AddrSpace);
}
/// EmitRawText - If this file is backed by a assembly streamer, this dumps
/// the specified string in the output .s file. This capability is
/// indicated by the hasRawTextSupport() predicate.
void MCStreamer::EmitRawText(StringRef String) {
errs() << "EmitRawText called on an MCStreamer that doesn't support it, "
" something must not be fully mc'ized\n";
abort();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.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 "otbImageFileReader.h"
#include "otbImageFileWriter.h"
// This example demonstrates the use of the
// \doxygen{otb}{OrthoRectificationFilter}. This filter is intended to
// orthorectify images which are in a distributor format with the
// appropriate meta-data describing the sensor model. In this example,
// we will choose to use an UTM projection for the output image.
//
// The first step toward the use of these filters is to include the
// proper header files: the one for the ortho-rectification filter and
// the one defining the different projections available in OTB.
#include "otbOrthoRectificationFilter.h"
#include "otbSpatialReference.h"
int main(int argc, char* argv[])
{
if (argc != 11)
{
std::cout << argv[0]
<< " <input_filename> <output_filename> <utm zone> <hemisphere N/S> <x_ground_upper_left_corner> <y_ground_upper_left_corner> <x_Size> <y_Size> "
"<x_groundSamplingDistance> <y_groundSamplingDistance> (should be negative since origin is upper left)>"
<< std::endl;
return EXIT_FAILURE;
}
// We will start by defining the types for the images, the image file
// reader and the image file writer. The writer will be a
// \doxygen{otb}{ImageFileWriter} which will allow us to set
// the number of stream divisions we want to apply when writing the
// output image, which can be very large.
typedef otb::Image<int, 2> ImageType;
typedef otb::VectorImage<int, 2> VectorImageType;
typedef otb::ImageFileReader<VectorImageType> ReaderType;
typedef otb::ImageFileWriter<VectorImageType> WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName(argv[1]);
writer->SetFileName(argv[2]);
// We can now proceed to declare the type for the ortho-rectification
// filter. The class \doxygen{otb}{OrthoRectificationFilter} is
// templated over the input and the output image types as well as over
// the cartographic projection. We define therefore the
// type of the projection we want, which is an UTM projection for this case.
// Software Guide : BeginCodeSnippet
typedef otb::GenericMapProjection<otb::TransformDirection::FORWARD> MapProjectionType;
typedef otb::OrthoRectificationFilter<VectorImageType, VectorImageType,
MapProjectionType>
OrthoRectifFilterType;
OrthoRectifFilterType::Pointer orthoRectifFilter = OrthoRectifFilterType::New();
// Now we need to
// instantiate the map projection, set the {\em zone} and {\em hemisphere}
// parameters and pass this projection to the orthorectification filter.
utmMapProjectionType::Pointer utmMapProjection = utmMapProjectionType::New();
utmMapProjection->SetWkt(otb::SpatialReference::FromUTM(atoi(argv[3]),*argv[4]=='N'? otb::SpatialReference::hemisphere::north : otb::SpatialReference::hemisphere::south).ToWkt());
std::cout<<utmMapProjection->GetWkt()<<std::endl;
orthoRectifFilter->SetMapProjection(utmMapProjection);
// We then wire the input image to the orthorectification filter.
orthoRectifFilter->SetInput(reader->GetOutput());
// Using the user-provided information, we define the output region
// for the image generated by the orthorectification filter.
// We also define the spacing of the deformation grid where actual
// deformation values are estimated. Choosing a bigger deformation field
// spacing will speed up computation.
ImageType::IndexType start;
start[0] = 0;
start[1] = 0;
orthoRectifFilter->SetOutputStartIndex(start);
ImageType::SizeType size;
size[0] = atoi(argv[7]);
size[1] = atoi(argv[8]);
orthoRectifFilter->SetOutputSize(size);
ImageType::SpacingType spacing;
spacing[0] = atof(argv[9]);
spacing[1] = atof(argv[10]);
orthoRectifFilter->SetOutputSpacing(spacing);
ImageType::SpacingType gridSpacing;
gridSpacing[0] = 2. * atof(argv[9]);
gridSpacing[1] = 2. * atof(argv[10]);
orthoRectifFilter->SetDisplacementFieldSpacing(gridSpacing);
ImageType::PointType origin;
origin[0] = strtod(argv[5], nullptr);
origin[1] = strtod(argv[6], nullptr);
orthoRectifFilter->SetOutputOrigin(origin);
// We can now set plug the ortho-rectification filter to the writer
// and set the number of tiles we want to split the output image in
// for the writing step.
writer->SetInput(orthoRectifFilter->GetOutput());
writer->SetAutomaticTiledStreaming();
// Finally, we trigger the pipeline execution by calling the
// \code{Update()} method on the writer. Please note that the
// ortho-rectification filter is derived from the
// \doxygen{otb}{StreamingResampleImageFilter} in order to be able to
// compute the input image regions which are needed to build the
// output image. Since the resampler applies a geometric
// transformation (scale, rotation, etc.), this region computation is
// not trivial.
writer->Update();
return EXIT_SUCCESS;
}
<commit_msg>COMP: fix merge issue<commit_after>/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.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 "otbImageFileReader.h"
#include "otbImageFileWriter.h"
// This example demonstrates the use of the
// \doxygen{otb}{OrthoRectificationFilter}. This filter is intended to
// orthorectify images which are in a distributor format with the
// appropriate meta-data describing the sensor model. In this example,
// we will choose to use an UTM projection for the output image.
//
// The first step toward the use of these filters is to include the
// proper header files: the one for the ortho-rectification filter and
// the one defining the different projections available in OTB.
#include "otbOrthoRectificationFilter.h"
#include "otbSpatialReference.h"
int main(int argc, char* argv[])
{
if (argc != 11)
{
std::cout << argv[0]
<< " <input_filename> <output_filename> <utm zone> <hemisphere N/S> <x_ground_upper_left_corner> <y_ground_upper_left_corner> <x_Size> <y_Size> "
"<x_groundSamplingDistance> <y_groundSamplingDistance> (should be negative since origin is upper left)>"
<< std::endl;
return EXIT_FAILURE;
}
// We will start by defining the types for the images, the image file
// reader and the image file writer. The writer will be a
// \doxygen{otb}{ImageFileWriter} which will allow us to set
// the number of stream divisions we want to apply when writing the
// output image, which can be very large.
typedef otb::Image<int, 2> ImageType;
typedef otb::VectorImage<int, 2> VectorImageType;
typedef otb::ImageFileReader<VectorImageType> ReaderType;
typedef otb::ImageFileWriter<VectorImageType> WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName(argv[1]);
writer->SetFileName(argv[2]);
// We can now proceed to declare the type for the ortho-rectification
// filter. The class \doxygen{otb}{OrthoRectificationFilter} is
// templated over the input and the output image types as well as over
// the cartographic projection. We define therefore the
// type of the projection we want, which is an UTM projection for this case.
// Software Guide : BeginCodeSnippet
typedef otb::GenericMapProjection<otb::TransformDirection::FORWARD> MapProjectionType;
typedef otb::OrthoRectificationFilter<VectorImageType, VectorImageType,
MapProjectionType>
OrthoRectifFilterType;
OrthoRectifFilterType::Pointer orthoRectifFilter = OrthoRectifFilterType::New();
// Now we need to
// instantiate the map projection, set the {\em zone} and {\em hemisphere}
// parameters and pass this projection to the orthorectification filter.
MapProjectionType::Pointer utmMapProjection = MapProjectionType::New();
utmMapProjection->SetWkt(otb::SpatialReference::FromUTM(atoi(argv[3]),*argv[4]=='N'? otb::SpatialReference::hemisphere::north : otb::SpatialReference::hemisphere::south).ToWkt());
std::cout<<utmMapProjection->GetWkt()<<std::endl;
orthoRectifFilter->SetMapProjection(utmMapProjection);
// We then wire the input image to the orthorectification filter.
orthoRectifFilter->SetInput(reader->GetOutput());
// Using the user-provided information, we define the output region
// for the image generated by the orthorectification filter.
// We also define the spacing of the deformation grid where actual
// deformation values are estimated. Choosing a bigger deformation field
// spacing will speed up computation.
ImageType::IndexType start;
start[0] = 0;
start[1] = 0;
orthoRectifFilter->SetOutputStartIndex(start);
ImageType::SizeType size;
size[0] = atoi(argv[7]);
size[1] = atoi(argv[8]);
orthoRectifFilter->SetOutputSize(size);
ImageType::SpacingType spacing;
spacing[0] = atof(argv[9]);
spacing[1] = atof(argv[10]);
orthoRectifFilter->SetOutputSpacing(spacing);
ImageType::SpacingType gridSpacing;
gridSpacing[0] = 2. * atof(argv[9]);
gridSpacing[1] = 2. * atof(argv[10]);
orthoRectifFilter->SetDisplacementFieldSpacing(gridSpacing);
ImageType::PointType origin;
origin[0] = strtod(argv[5], nullptr);
origin[1] = strtod(argv[6], nullptr);
orthoRectifFilter->SetOutputOrigin(origin);
// We can now set plug the ortho-rectification filter to the writer
// and set the number of tiles we want to split the output image in
// for the writing step.
writer->SetInput(orthoRectifFilter->GetOutput());
writer->SetAutomaticTiledStreaming();
// Finally, we trigger the pipeline execution by calling the
// \code{Update()} method on the writer. Please note that the
// ortho-rectification filter is derived from the
// \doxygen{otb}{StreamingResampleImageFilter} in order to be able to
// compute the input image regions which are needed to build the
// output image. Since the resampler applies a geometric
// transformation (scale, rotation, etc.), this region computation is
// not trivial.
writer->Update();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/****************************************
* Include Libraries
****************************************/
#include "Ubidots.h"
/****************************************
* Define Instances and Constants
****************************************/
#ifndef UBIDOTS_TOKEN
#define UBIDOTS_TOKEN "..." // Put here your Ubidots TOKEN
#endif
Ubidots ubidots(UBIDOTS_TOKEN, UBI_INDUSTRIAL, UBI_MESH);
/****************************************
* Auxiliar Functions
****************************************/
// Put here your auxiliar functions
/****************************************
* Main Functions
****************************************/
void setup() {
Serial.begin(115200);
// Uncomment this line to choose a different cloud Protocol to send data
// ubidots.setCloudProtocol(UBI_HTTP);
// Uncomment this line for printing debug messages
ubidots.setDebug(true);
}
void loop() { ubidots.meshLoop(); }
<commit_msg>fixing debug messages comment typo<commit_after>/****************************************
* Include Libraries
****************************************/
#include "Ubidots.h"
/****************************************
* Define Instances and Constants
****************************************/
#ifndef UBIDOTS_TOKEN
#define UBIDOTS_TOKEN "..." // Put here your Ubidots TOKEN
#endif
Ubidots ubidots(UBIDOTS_TOKEN, UBI_INDUSTRIAL, UBI_MESH);
/****************************************
* Auxiliar Functions
****************************************/
// Put here your auxiliar functions
/****************************************
* Main Functions
****************************************/
void setup() {
Serial.begin(115200);
// Uncomment this line to choose a different cloud Protocol to send data
// ubidots.setCloudProtocol(UBI_HTTP);
// ubidots.setDebug(true); // Uncomment this line for printing debug messages
}
void loop() { ubidots.meshLoop(); }
<|endoftext|> |
<commit_before><commit_msg>coverity#736301 the 2nd arg is a gpointer<commit_after><|endoftext|> |
<commit_before>/* Copyright (c) 2008-2017 the MRtrix3 contributors
*
* 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/.
*
* MRtrix 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.
*
* For more details, see http://www.mrtrix.org/.
*/
#include "command.h"
#include "image.h"
#include "dwi/tractography/properties.h"
#include "dwi/tractography/roi.h"
#include "dwi/tractography/tracking/exec.h"
#include "dwi/tractography/tracking/method.h"
#include "dwi/tractography/tracking/tractography.h"
#include "dwi/tractography/ACT/act.h"
#include "dwi/tractography/algorithms/fact.h"
#include "dwi/tractography/algorithms/iFOD1.h"
#include "dwi/tractography/algorithms/iFOD2.h"
#include "dwi/tractography/algorithms/nulldist.h"
#include "dwi/tractography/algorithms/sd_stream.h"
#include "dwi/tractography/algorithms/seedtest.h"
#include "dwi/tractography/algorithms/tensor_det.h"
#include "dwi/tractography/algorithms/tensor_prob.h"
#include "dwi/tractography/seeding/seeding.h"
using namespace MR;
using namespace App;
const char* algorithms[] = { "fact", "ifod1", "ifod2", "nulldist1", "nulldist2", "sd_stream", "seedtest", "tensor_det", "tensor_prob", nullptr };
void usage ()
{
AUTHOR = "J-Donald Tournier (jdtournier@gmail.com) and Robert E. Smith (robert.smith@florey.edu.au)";
SYNOPSIS = "Perform streamlines tractography";
REFERENCES
+ "References based on streamlines algorithm used:"
+ "* FACT:\n"
"Mori, S.; Crain, B. J.; Chacko, V. P. & van Zijl, P. C. M. "
"Three-dimensional tracking of axonal projections in the brain by magnetic resonance imaging. "
"Annals of Neurology, 1999, 45, 265-269"
+ "* iFOD1 or SD_STREAM:\n"
"Tournier, J.-D.; Calamante, F. & Connelly, A. " // Internal
"MRtrix: Diffusion tractography in crossing fiber regions. "
"Int. J. Imaging Syst. Technol., 2012, 22, 53-66"
+ "* iFOD2:\n"
"Tournier, J.-D.; Calamante, F. & Connelly, A. " // Internal
"Improved probabilistic streamlines tractography by 2nd order integration over fibre orientation distributions. "
"Proceedings of the International Society for Magnetic Resonance in Medicine, 2010, 1670"
+ "* Nulldist1 / Nulldist2:\n"
"Morris, D. M.; Embleton, K. V. & Parker, G. J. "
"Probabilistic fibre tracking: Differentiation of connections from chance events. "
"NeuroImage, 2008, 42, 1329-1339"
+ "* Tensor_Det:\n"
"Basser, P. J.; Pajevic, S.; Pierpaoli, C.; Duda, J. & Aldroubi, A. "
"In vivo fiber tractography using DT-MRI data. "
"Magnetic Resonance in Medicine, 2000, 44, 625-632"
+ "* Tensor_Prob:\n"
"Jones, D. "
"Tractography Gone Wild: Probabilistic Fibre Tracking Using the Wild Bootstrap With Diffusion Tensor MRI. "
"IEEE Transactions on Medical Imaging, 2008, 27, 1268-1274"
+ "References based on command-line options:"
+ "* -rk4:\n"
"Basser, P. J.; Pajevic, S.; Pierpaoli, C.; Duda, J. & Aldroubi, A. "
"In vivo fiber tractography using DT-MRI data. "
"Magnetic Resonance in Medicine, 2000, 44, 625-632"
+ "* -act, -backtrack, -seed_gmwmi:\n"
"Smith, R. E.; Tournier, J.-D.; Calamante, F. & Connelly, A. " // Internal
"Anatomically-constrained tractography: Improved diffusion MRI streamlines tractography through effective use of anatomical information. "
"NeuroImage, 2012, 62, 1924-1938"
+ "* -seed_dynamic:\n"
"Smith, R. E.; Tournier, J.-D.; Calamante, F. & Connelly, A. " // Internal
"SIFT2: Enabling dense quantitative assessment of brain white matter connectivity using streamlines tractography. "
"NeuroImage, 2015, 119, 338-351";
ARGUMENTS
+ Argument ("source",
"the image containing the source data. The type of data depends on the algorithm used:\n"
"- FACT: the directions file (each triplet of volumes is the X,Y,Z direction of a fibre population).\n"
"- iFOD1/2, Nulldist2 & SD_Stream: the SH image resulting from CSD.\n"
"- Nulldist1 & SeedTest: any image (will not be used).\n"
"- Tensor_Det / Tensor_Prob: the DWI image.\n"
).type_image_in()
+ Argument ("tracks", "the output file containing the tracks generated.").type_tracks_out();
OPTIONS
+ Option ("algorithm",
"specify the tractography algorithm to use. Valid choices are: "
"FACT, iFOD1, iFOD2, Nulldist1, Nulldist2, SD_Stream, Seedtest, Tensor_Det, Tensor_Prob (default: iFOD2).")
+ Argument ("name").type_choice (algorithms)
+ DWI::Tractography::Tracking::TrackOption
+ DWI::Tractography::Seeding::SeedMechanismOption
+ DWI::Tractography::Seeding::SeedParameterOption
+ DWI::Tractography::ROIOption
+ DWI::Tractography::ACT::ACTOption
+ DWI::GradImportOptions();
}
void run ()
{
using namespace DWI::Tractography;
using namespace DWI::Tractography::Tracking;
using namespace DWI::Tractography::Algorithms;
Properties properties;
int algorithm = 2; // default = ifod2
auto opt = get_options ("algorithm");
if (opt.size()) algorithm = opt[0][0];
load_rois (properties);
Tracking::load_streamline_properties (properties);
ACT::load_act_properties (properties);
Seeding::load_seed_mechanisms (properties);
Seeding::load_seed_parameters (properties);
// Check validity of options -number and -maxnum; these are meaningless if seeds are number-limited
// By over-riding the values in properties, the progress bar should still be valid
if (properties.seeds.is_finite()) {
if (properties["max_num_tracks"].size())
WARN ("Overriding -number option (desired number of successful streamlines) as seeds can only provide a finite number");
properties["max_num_tracks"] = str (properties.seeds.get_total_count());
if (properties["max_num_attempts"].size())
WARN ("Overriding -maxnum option (maximum number of streamline attempts) as seeds can only provide a finite number");
properties["max_num_attempts"] = str (properties.seeds.get_total_count());
}
switch (algorithm) {
case 0:
Exec<FACT> ::run (argument[0], argument[1], properties);
break;
case 1:
Exec<iFOD1> ::run (argument[0], argument[1], properties);
break;
case 2:
Exec<iFOD2> ::run (argument[0], argument[1], properties);
break;
case 3:
Exec<NullDist1> ::run (argument[0], argument[1], properties);
break;
case 4:
Exec<NullDist2> ::run (argument[0], argument[1], properties);
break;
case 5:
Exec<SDStream> ::run (argument[0], argument[1], properties);
break;
case 6:
Exec<Seedtest> ::run (argument[0], argument[1], properties);
break;
case 7:
Exec<Tensor_Det> ::run (argument[0], argument[1], properties);
break;
case 8:
Exec<Tensor_Prob>::run (argument[0], argument[1], properties);
break;
default:
assert (0);
}
}
<commit_msg>other corrections to use -select and -seeds in warnings<commit_after>/* Copyright (c) 2008-2017 the MRtrix3 contributors
*
* 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/.
*
* MRtrix 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.
*
* For more details, see http://www.mrtrix.org/.
*/
#include "command.h"
#include "image.h"
#include "dwi/tractography/properties.h"
#include "dwi/tractography/roi.h"
#include "dwi/tractography/tracking/exec.h"
#include "dwi/tractography/tracking/method.h"
#include "dwi/tractography/tracking/tractography.h"
#include "dwi/tractography/ACT/act.h"
#include "dwi/tractography/algorithms/fact.h"
#include "dwi/tractography/algorithms/iFOD1.h"
#include "dwi/tractography/algorithms/iFOD2.h"
#include "dwi/tractography/algorithms/nulldist.h"
#include "dwi/tractography/algorithms/sd_stream.h"
#include "dwi/tractography/algorithms/seedtest.h"
#include "dwi/tractography/algorithms/tensor_det.h"
#include "dwi/tractography/algorithms/tensor_prob.h"
#include "dwi/tractography/seeding/seeding.h"
using namespace MR;
using namespace App;
const char* algorithms[] = { "fact", "ifod1", "ifod2", "nulldist1", "nulldist2", "sd_stream", "seedtest", "tensor_det", "tensor_prob", nullptr };
void usage ()
{
AUTHOR = "J-Donald Tournier (jdtournier@gmail.com) and Robert E. Smith (robert.smith@florey.edu.au)";
SYNOPSIS = "Perform streamlines tractography";
REFERENCES
+ "References based on streamlines algorithm used:"
+ "* FACT:\n"
"Mori, S.; Crain, B. J.; Chacko, V. P. & van Zijl, P. C. M. "
"Three-dimensional tracking of axonal projections in the brain by magnetic resonance imaging. "
"Annals of Neurology, 1999, 45, 265-269"
+ "* iFOD1 or SD_STREAM:\n"
"Tournier, J.-D.; Calamante, F. & Connelly, A. " // Internal
"MRtrix: Diffusion tractography in crossing fiber regions. "
"Int. J. Imaging Syst. Technol., 2012, 22, 53-66"
+ "* iFOD2:\n"
"Tournier, J.-D.; Calamante, F. & Connelly, A. " // Internal
"Improved probabilistic streamlines tractography by 2nd order integration over fibre orientation distributions. "
"Proceedings of the International Society for Magnetic Resonance in Medicine, 2010, 1670"
+ "* Nulldist1 / Nulldist2:\n"
"Morris, D. M.; Embleton, K. V. & Parker, G. J. "
"Probabilistic fibre tracking: Differentiation of connections from chance events. "
"NeuroImage, 2008, 42, 1329-1339"
+ "* Tensor_Det:\n"
"Basser, P. J.; Pajevic, S.; Pierpaoli, C.; Duda, J. & Aldroubi, A. "
"In vivo fiber tractography using DT-MRI data. "
"Magnetic Resonance in Medicine, 2000, 44, 625-632"
+ "* Tensor_Prob:\n"
"Jones, D. "
"Tractography Gone Wild: Probabilistic Fibre Tracking Using the Wild Bootstrap With Diffusion Tensor MRI. "
"IEEE Transactions on Medical Imaging, 2008, 27, 1268-1274"
+ "References based on command-line options:"
+ "* -rk4:\n"
"Basser, P. J.; Pajevic, S.; Pierpaoli, C.; Duda, J. & Aldroubi, A. "
"In vivo fiber tractography using DT-MRI data. "
"Magnetic Resonance in Medicine, 2000, 44, 625-632"
+ "* -act, -backtrack, -seed_gmwmi:\n"
"Smith, R. E.; Tournier, J.-D.; Calamante, F. & Connelly, A. " // Internal
"Anatomically-constrained tractography: Improved diffusion MRI streamlines tractography through effective use of anatomical information. "
"NeuroImage, 2012, 62, 1924-1938"
+ "* -seed_dynamic:\n"
"Smith, R. E.; Tournier, J.-D.; Calamante, F. & Connelly, A. " // Internal
"SIFT2: Enabling dense quantitative assessment of brain white matter connectivity using streamlines tractography. "
"NeuroImage, 2015, 119, 338-351";
ARGUMENTS
+ Argument ("source",
"the image containing the source data. The type of data depends on the algorithm used:\n"
"- FACT: the directions file (each triplet of volumes is the X,Y,Z direction of a fibre population).\n"
"- iFOD1/2, Nulldist2 & SD_Stream: the SH image resulting from CSD.\n"
"- Nulldist1 & SeedTest: any image (will not be used).\n"
"- Tensor_Det / Tensor_Prob: the DWI image.\n"
).type_image_in()
+ Argument ("tracks", "the output file containing the tracks generated.").type_tracks_out();
OPTIONS
+ Option ("algorithm",
"specify the tractography algorithm to use. Valid choices are: "
"FACT, iFOD1, iFOD2, Nulldist1, Nulldist2, SD_Stream, Seedtest, Tensor_Det, Tensor_Prob (default: iFOD2).")
+ Argument ("name").type_choice (algorithms)
+ DWI::Tractography::Tracking::TrackOption
+ DWI::Tractography::Seeding::SeedMechanismOption
+ DWI::Tractography::Seeding::SeedParameterOption
+ DWI::Tractography::ROIOption
+ DWI::Tractography::ACT::ACTOption
+ DWI::GradImportOptions();
}
void run ()
{
using namespace DWI::Tractography;
using namespace DWI::Tractography::Tracking;
using namespace DWI::Tractography::Algorithms;
Properties properties;
int algorithm = 2; // default = ifod2
auto opt = get_options ("algorithm");
if (opt.size()) algorithm = opt[0][0];
load_rois (properties);
Tracking::load_streamline_properties (properties);
ACT::load_act_properties (properties);
Seeding::load_seed_mechanisms (properties);
Seeding::load_seed_parameters (properties);
// Check validity of options -number and -maxnum; these are meaningless if seeds are number-limited
// By over-riding the values in properties, the progress bar should still be valid
if (properties.seeds.is_finite()) {
if (properties["max_num_tracks"].size())
WARN ("Overriding -select option (desired number of successful streamline selections), as seeds can only provide a finite number");
properties["max_num_tracks"] = str (properties.seeds.get_total_count());
if (properties["max_num_seeds"].size())
WARN ("Overriding -seeds option (maximum number of seeds that will be attempted to track from), as seeds can only provide a finite number");
properties["max_num_seeds"] = str (properties.seeds.get_total_count());
}
switch (algorithm) {
case 0:
Exec<FACT> ::run (argument[0], argument[1], properties);
break;
case 1:
Exec<iFOD1> ::run (argument[0], argument[1], properties);
break;
case 2:
Exec<iFOD2> ::run (argument[0], argument[1], properties);
break;
case 3:
Exec<NullDist1> ::run (argument[0], argument[1], properties);
break;
case 4:
Exec<NullDist2> ::run (argument[0], argument[1], properties);
break;
case 5:
Exec<SDStream> ::run (argument[0], argument[1], properties);
break;
case 6:
Exec<Seedtest> ::run (argument[0], argument[1], properties);
break;
case 7:
Exec<Tensor_Det> ::run (argument[0], argument[1], properties);
break;
case 8:
Exec<Tensor_Prob>::run (argument[0], argument[1], properties);
break;
default:
assert (0);
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Library: TubeTK/VTree3D
Authors: Stephen Aylward, Julien Jomier, and Elizabeth Bullitt
Original implementation:
Copyright University of North Carolina, Chapel Hill, NC, USA.
Revised implementation:
Copyright Kitware Inc., Carrboro, NC, USA.
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 "tubeOptGoldenMean1D.h"
#include <cmath>
#include <iostream>
namespace tube
{
OptGoldenMean1D::OptGoldenMean1D( )
: Optimizer1D( )
{
}
OptGoldenMean1D::OptGoldenMean1D( UserFunc<double, double> *newFuncVal )
: Optimizer1D( newFuncVal, NULL )
{
}
OptGoldenMean1D::~OptGoldenMean1D( )
{
}
void OptGoldenMean1D::use( UserFunc<double, double> * newFuncVal )
{
Optimizer1D::use( newFuncVal, NULL );
}
bool OptGoldenMean1D::m_Extreme( double *extX, double *extVal )
{
double maxSign = 1;
if( m_SearchForMin )
{
maxSign = -1;
}
double v = maxSign * m_FuncVal->value( *extX );
double prevV = v;
double xstep = m_XStep;
int dir = 1;
double v1 = v-m_Tolerance;
if( *extX+dir*xstep <= m_XMax && *extX+dir*xstep >= m_XMin )
{
v1 = maxSign * m_FuncVal->value( *extX+dir*xstep );
}
double v2 = v1-m_Tolerance;
if( *extX-dir*xstep <= m_XMax && *extX-dir*xstep >= m_XMin )
{
v2 = maxSign * m_FuncVal->value( *extX-dir*xstep );
}
if( v2>v1 )
{
dir = -1;
v = v2;
}
else
{
v = v1;
}
unsigned int iter = 0;
int dirInit = dir;
while( v < prevV && xstep > 2 * m_Tolerance && iter < m_MaxIterations )
{
dir *= -1;
if( *extX+dir*xstep <= m_XMax && *extX+dir*xstep >= m_XMin )
{
v = maxSign * m_FuncVal->value( *extX+dir*xstep );
}
else
{
dir *= -1;
}
if( v<prevV && dir == dirInit )
{
xstep /= 1.618;
}
++iter;
}
prevV = v;
*extX += dir*xstep;
if( *extX > m_XMax )
{
*extX = m_XMax;
*extVal = maxSign * m_FuncVal->value( *extX );
return false;
}
if( *extX < m_XMin )
{
*extX = m_XMin;
*extVal = maxSign * m_FuncVal->value( *extX );
return false;
}
dirInit = dir;
while( xstep > m_Tolerance && iter < m_MaxIterations )
{
if( *extX+dir*xstep <= m_XMax && *extX+dir*xstep >= m_XMin )
{
v = maxSign * m_FuncVal->value( *extX+dir*xstep );
}
else
{
if( *extX > m_XMax )
{
*extX = m_XMax;
*extVal = maxSign * m_FuncVal->value( *extX );
return false;
}
if( *extX < m_XMin )
{
*extX = m_XMin;
*extVal = maxSign * m_FuncVal->value( *extX );
return false;
}
}
while( v > prevV && iter < m_MaxIterations )
{
dirInit = dir;
prevV = v;
*extX += dir*xstep;
if( *extX > m_XMax )
{
*extX = m_XMax;
*extVal = maxSign * m_FuncVal->value( *extX );
return false;
}
if( *extX < m_XMin )
{
*extX = m_XMin;
*extVal = maxSign * m_FuncVal->value( *extX );
return false;
}
v = maxSign * m_FuncVal->value( *extX+dir*xstep );
++iter;
}
if( dir == dirInit )
{
xstep /= 1.618;
}
dir *= -1;
}
*extVal = prevV;
return true;
}
} // namespace tube
<commit_msg>BUG: Return value should be the raw function value<commit_after>/*=========================================================================
Library: TubeTK/VTree3D
Authors: Stephen Aylward, Julien Jomier, and Elizabeth Bullitt
Original implementation:
Copyright University of North Carolina, Chapel Hill, NC, USA.
Revised implementation:
Copyright Kitware Inc., Carrboro, NC, USA.
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 "tubeOptGoldenMean1D.h"
#include <cmath>
#include <iostream>
namespace tube
{
OptGoldenMean1D::OptGoldenMean1D( )
: Optimizer1D( )
{
}
OptGoldenMean1D::OptGoldenMean1D( UserFunc<double, double> *newFuncVal )
: Optimizer1D( newFuncVal, NULL )
{
}
OptGoldenMean1D::~OptGoldenMean1D( )
{
}
void OptGoldenMean1D::use( UserFunc<double, double> * newFuncVal )
{
Optimizer1D::use( newFuncVal, NULL );
}
bool OptGoldenMean1D::m_Extreme( double *extX, double *extVal )
{
double maxSign = 1;
if( m_SearchForMin )
{
maxSign = -1;
}
double v = maxSign * m_FuncVal->value( *extX );
double prevV = v;
double xstep = m_XStep;
int dir = 1;
double v1 = v-m_Tolerance;
if( *extX+dir*xstep <= m_XMax && *extX+dir*xstep >= m_XMin )
{
v1 = maxSign * m_FuncVal->value( *extX+dir*xstep );
}
double v2 = v1-m_Tolerance;
if( *extX-dir*xstep <= m_XMax && *extX-dir*xstep >= m_XMin )
{
v2 = maxSign * m_FuncVal->value( *extX-dir*xstep );
}
if( v2>v1 )
{
dir = -1;
v = v2;
}
else
{
v = v1;
}
unsigned int iter = 0;
int dirInit = dir;
while( v < prevV && xstep > 2 * m_Tolerance && iter < m_MaxIterations )
{
dir *= -1;
if( *extX+dir*xstep <= m_XMax && *extX+dir*xstep >= m_XMin )
{
v = maxSign * m_FuncVal->value( *extX+dir*xstep );
}
else
{
dir *= -1;
}
if( v<prevV && dir == dirInit )
{
xstep /= 1.618;
}
++iter;
}
prevV = v;
*extX += dir*xstep;
if( *extX > m_XMax )
{
*extX = m_XMax;
*extVal = m_FuncVal->value( *extX );
return false;
}
if( *extX < m_XMin )
{
*extX = m_XMin;
*extVal = m_FuncVal->value( *extX );
return false;
}
dirInit = dir;
while( xstep > m_Tolerance && iter < m_MaxIterations )
{
if( *extX+dir*xstep <= m_XMax && *extX+dir*xstep >= m_XMin )
{
v = maxSign * m_FuncVal->value( *extX+dir*xstep );
}
else
{
if( *extX > m_XMax )
{
*extX = m_XMax;
*extVal = m_FuncVal->value( *extX );
return false;
}
if( *extX < m_XMin )
{
*extX = m_XMin;
*extVal = m_FuncVal->value( *extX );
return false;
}
}
while( v > prevV && iter < m_MaxIterations )
{
dirInit = dir;
prevV = v;
*extX += dir*xstep;
if( *extX > m_XMax )
{
*extX = m_XMax;
*extVal = m_FuncVal->value( *extX );
return false;
}
if( *extX < m_XMin )
{
*extX = m_XMin;
*extVal = m_FuncVal->value( *extX );
return false;
}
v = maxSign * m_FuncVal->value( *extX+dir*xstep );
++iter;
}
if( dir == dirInit )
{
xstep /= 1.618;
}
dir *= -1;
}
*extVal = maxSign * prevV;
return true;
}
} // namespace tube
<|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 "webkit/tools/test_shell/webwidget_host.h"
#include <cairo/cairo.h>
#include <gtk/gtk.h>
#include "base/logging.h"
#include "skia/ext/bitmap_platform_device_linux.h"
#include "skia/ext/platform_canvas_linux.h"
#include "skia/ext/platform_device_linux.h"
#include "webkit/glue/webinputevent.h"
#include "webkit/glue/webwidget.h"
namespace {
// The web contents are completely drawn and handled by WebKit, except that
// windowed plugins are GtkSockets on top of it. GtkSockets are unhappy
// if they cannot be put within a parent container, so what we want is basically
// a GtkDrawingArea that is also a GtkContainer. The existing Gtk classes for
// this sort of thing (reasonably) assume that the positioning of the children
// will be handled by the parent, which isn't the case for us where WebKit
// drives everything. So we create a custom widget that is just a GtkContainer
// that contains a native window.
// Sends a "configure" event to the widget, allowing it to repaint.
// Used internally by the WebWidgetHostGtk implementation.
void WebWidgetHostGtkSendConfigure(GtkWidget* widget) {
GdkEvent* event = gdk_event_new(GDK_CONFIGURE);
// This ref matches GtkDrawingArea code. It must be balanced by the
// event-handling code.
g_object_ref(widget->window);
event->configure.window = widget->window;
event->configure.send_event = TRUE;
event->configure.x = widget->allocation.x;
event->configure.y = widget->allocation.y;
event->configure.width = widget->allocation.width;
event->configure.height = widget->allocation.height;
gtk_widget_event(widget, event);
gdk_event_free(event);
}
// Implementation of the "realize" event for the custom WebWidgetHostGtk
// widget. Creates an X window. (Nearly identical to GtkDrawingArea code.)
void WebWidgetHostGtkRealize(GtkWidget* widget) {
GTK_WIDGET_SET_FLAGS(widget, GTK_REALIZED);
GdkWindowAttr attributes;
attributes.window_type = GDK_WINDOW_CHILD;
attributes.x = widget->allocation.x;
attributes.y = widget->allocation.y;
attributes.width = widget->allocation.width;
attributes.height = widget->allocation.height;
attributes.wclass = GDK_INPUT_OUTPUT;
attributes.visual = gtk_widget_get_visual(widget);
attributes.colormap = gtk_widget_get_colormap(widget);
attributes.event_mask = gtk_widget_get_events(widget) | GDK_EXPOSURE_MASK;
int attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
widget->window = gdk_window_new(gtk_widget_get_parent_window(widget),
&attributes, attributes_mask);
gdk_window_set_user_data(widget->window, widget);
WebWidgetHostGtkSendConfigure(widget);
}
// Implementation of the "size-allocate" event for the custom WebWidgetHostGtk
// widget. Resizes the window. (Nearly identical to GtkDrawingArea code.)
void WebWidgetHostGtkSizeAllocate(GtkWidget* widget,
GtkAllocation* allocation) {
widget->allocation = *allocation;
if (!GTK_WIDGET_REALIZED(widget)) {
// We don't have a window yet, so nothing to do.
return;
}
gdk_window_move_resize(widget->window,
allocation->x, allocation->y,
allocation->width, allocation->height);
WebWidgetHostGtkSendConfigure(widget);
}
// Implementation of "remove" for our GtkContainer subclass.
// This called when plugins shut down. We can just ignore it.
void WebWidgetHostGtkRemove(GtkContainer* container, GtkWidget* widget) {
// Do nothing.
}
// Implementation of the class init function for WebWidgetHostGtk.
void WebWidgetHostGtkClassInit(GtkContainerClass* container_class) {
GtkWidgetClass* widget_class =
reinterpret_cast<GtkWidgetClass*>(container_class);
widget_class->realize = WebWidgetHostGtkRealize;
widget_class->size_allocate = WebWidgetHostGtkSizeAllocate;
container_class->remove = WebWidgetHostGtkRemove;
}
// Constructs the GType for the custom Gtk widget.
// (Gtk boilerplate, basically.)
GType WebWidgetHostGtkGetType() {
static GType type = 0;
if (!type) {
static const GTypeInfo info = {
sizeof(GtkContainerClass),
NULL, NULL,
(GClassInitFunc)WebWidgetHostGtkClassInit,
NULL, NULL,
sizeof(GtkContainer), // We are identical in memory to a GtkContainer.
0, NULL,
};
type = g_type_register_static(GTK_TYPE_CONTAINER, "WebWidgetHostGtk",
&info, (GTypeFlags)0);
}
return type;
}
// Create a new WebWidgetHostGtk.
GtkWidget* WebWidgetHostGtkNew() {
return GTK_WIDGET(g_object_new(WebWidgetHostGtkGetType(), NULL));
}
// In response to an invalidation, we call into WebKit to do layout. On
// Windows, WM_PAINT is a virtual message so any extra invalidates that come up
// while it's doing layout are implicitly swallowed as soon as we actually do
// drawing via BeginPaint.
//
// Though GTK does know how to collapse multiple paint requests, it won't erase
// paint requests from the future when we start drawing. To avoid an infinite
// cycle of repaints, we track whether we're currently handling a redraw, and
// during that if we get told by WebKit that a region has become invalid, we
// still add that region to the local dirty rect but *don't* enqueue yet
// another "do a paint" message.
bool handling_expose = false;
// -----------------------------------------------------------------------------
// Callback functions to proxy to host...
gboolean ConfigureEvent(GtkWidget* widget, GdkEventConfigure* config,
WebWidgetHost* host) {
host->Resize(gfx::Size(config->width, config->height));
return FALSE;
}
gboolean ExposeEvent(GtkWidget* widget, GdkEventExpose* expose,
WebWidgetHost* host) {
// See comments above about what handling_expose is for.
handling_expose = true;
gfx::Rect rect(expose->area);
host->UpdatePaintRect(rect);
host->Paint();
handling_expose = false;
return FALSE;
}
gboolean WindowDestroyed(GtkWidget* widget, WebWidgetHost* host) {
host->WindowDestroyed();
return FALSE;
}
gboolean KeyPressReleaseEvent(GtkWidget* widget, GdkEventKey* event,
WebWidgetHost* host) {
WebKeyboardEvent wke(event);
host->webwidget()->HandleInputEvent(&wke);
// The WebKeyboardEvent model, when holding down a key, is:
// KEY_DOWN, CHAR, (repeated CHAR as key repeats,) KEY_UP
// The GDK model for the same sequence is just:
// KEY_PRESS, (repeated KEY_PRESS as key repeats,) KEY_RELEASE
// So we must simulate a CHAR event for every key press.
if (event->type == GDK_KEY_PRESS) {
wke.type = WebKeyboardEvent::CHAR;
host->webwidget()->HandleInputEvent(&wke);
}
return FALSE;
}
// This signal is called when arrow keys or tab is pressed. If we return true,
// we prevent focus from being moved to another widget. If we want to allow
// focus to be moved outside of web contents, we need to implement
// WebViewDelegate::TakeFocus in the test webview delegate.
gboolean FocusMove(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
return TRUE;
}
gboolean FocusIn(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
host->webwidget()->SetFocus(true);
return FALSE;
}
gboolean FocusOut(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
host->webwidget()->SetFocus(false);
return FALSE;
}
gboolean ButtonPressReleaseEvent(GtkWidget* widget, GdkEventButton* event,
WebWidgetHost* host) {
WebMouseEvent wme(event);
host->webwidget()->HandleInputEvent(&wme);
return FALSE;
}
gboolean MouseMoveEvent(GtkWidget* widget, GdkEventMotion* event,
WebWidgetHost* host) {
WebMouseEvent wme(event);
host->webwidget()->HandleInputEvent(&wme);
return FALSE;
}
gboolean MouseScrollEvent(GtkWidget* widget, GdkEventScroll* event,
WebWidgetHost* host) {
WebMouseWheelEvent wmwe(event);
host->webwidget()->HandleInputEvent(&wmwe);
return FALSE;
}
} // anonymous namespace
// -----------------------------------------------------------------------------
GtkWidget* WebWidgetHost::CreateWindow(GtkWidget* parent_view,
void* host) {
GtkWidget* widget = WebWidgetHostGtkNew();
gtk_box_pack_start(GTK_BOX(parent_view), widget, TRUE, TRUE, 0);
// TODO(evanm): it might be cleaner to just have the custom widget set
// all of this up rather than connecting signals.
gtk_widget_add_events(widget, GDK_EXPOSURE_MASK |
GDK_POINTER_MOTION_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK |
GDK_KEY_PRESS_MASK |
GDK_KEY_RELEASE_MASK);
GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_FOCUS);
g_signal_connect(widget, "configure-event", G_CALLBACK(ConfigureEvent), host);
g_signal_connect(widget, "expose-event", G_CALLBACK(ExposeEvent), host);
g_signal_connect(widget, "destroy", G_CALLBACK(::WindowDestroyed), host);
g_signal_connect(widget, "key-press-event", G_CALLBACK(KeyPressReleaseEvent),
host);
g_signal_connect(widget, "key-release-event",
G_CALLBACK(KeyPressReleaseEvent), host);
g_signal_connect(widget, "focus", G_CALLBACK(FocusMove), host);
g_signal_connect(widget, "focus-in-event", G_CALLBACK(FocusIn), host);
g_signal_connect(widget, "focus-out-event", G_CALLBACK(FocusOut), host);
g_signal_connect(widget, "button-press-event",
G_CALLBACK(ButtonPressReleaseEvent), host);
g_signal_connect(widget, "button-release-event",
G_CALLBACK(ButtonPressReleaseEvent), host);
g_signal_connect(widget, "motion-notify-event", G_CALLBACK(MouseMoveEvent),
host);
g_signal_connect(widget, "scroll-event", G_CALLBACK(MouseScrollEvent),
host);
return widget;
}
WebWidgetHost* WebWidgetHost::Create(GtkWidget* parent_view,
WebWidgetDelegate* delegate) {
WebWidgetHost* host = new WebWidgetHost();
host->view_ = CreateWindow(parent_view, host);
host->webwidget_ = WebWidget::Create(delegate);
// We manage our own double buffering because we need to be able to update
// the expose area in an ExposeEvent within the lifetime of the event handler.
gtk_widget_set_double_buffered(GTK_WIDGET(host->view_), false);
return host;
}
void WebWidgetHost::UpdatePaintRect(const gfx::Rect& rect) {
paint_rect_ = paint_rect_.Union(rect);
}
void WebWidgetHost::DidInvalidateRect(const gfx::Rect& damaged_rect) {
DLOG_IF(WARNING, painting_) << "unexpected invalidation while painting";
UpdatePaintRect(damaged_rect);
if (!handling_expose) {
gtk_widget_queue_draw_area(GTK_WIDGET(view_), damaged_rect.x(),
damaged_rect.y(), damaged_rect.width(), damaged_rect.height());
}
}
void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
// This is used for optimizing painting when the renderer is scrolled. We're
// currently not doing any optimizations so just invalidate the region.
DidInvalidateRect(clip_rect);
}
WebWidgetHost::WebWidgetHost()
: view_(NULL),
webwidget_(NULL),
scroll_dx_(0),
scroll_dy_(0),
track_mouse_leave_(false) {
set_painting(false);
}
WebWidgetHost::~WebWidgetHost() {
webwidget_->Close();
webwidget_->Release();
}
void WebWidgetHost::Resize(const gfx::Size &newsize) {
// The pixel buffer backing us is now the wrong size
canvas_.reset();
webwidget_->Resize(gfx::Size(newsize.width(), newsize.height()));
}
void WebWidgetHost::Paint() {
int width = view_->allocation.width;
int height = view_->allocation.height;
gfx::Rect client_rect(width, height);
// Allocate a canvas if necessary
if (!canvas_.get()) {
ResetScrollRect();
paint_rect_ = client_rect;
canvas_.reset(new skia::PlatformCanvas(width, height, true));
if (!canvas_.get()) {
// memory allocation failed, we can't paint.
LOG(ERROR) << "Failed to allocate memory for " << width << "x" << height;
return;
}
}
// This may result in more invalidation
webwidget_->Layout();
// Paint the canvas if necessary. Allow painting to generate extra rects the
// first time we call it. This is necessary because some WebCore rendering
// objects update their layout only when painted.
// Store the total area painted in total_paint. Then tell the gdk window
// to update that area after we're done painting it.
gfx::Rect total_paint;
for (int i = 0; i < 2; ++i) {
paint_rect_ = client_rect.Intersect(paint_rect_);
if (!paint_rect_.IsEmpty()) {
gfx::Rect rect(paint_rect_);
paint_rect_ = gfx::Rect();
DLOG_IF(WARNING, i == 1) << "painting caused additional invalidations";
PaintRect(rect);
total_paint = total_paint.Union(rect);
}
}
DCHECK(paint_rect_.IsEmpty());
// Invalidate the paint region on the widget's underlying gdk window. Note
// that gdk_window_invalidate_* will generate extra expose events, which
// we wish to avoid. So instead we use calls to begin_paint/end_paint.
GdkRectangle grect = {
total_paint.x(),
total_paint.y(),
total_paint.width(),
total_paint.height(),
};
GdkWindow* window = view_->window;
gdk_window_begin_paint_rect(window, &grect);
// BitBlit to the gdk window.
skia::PlatformDeviceLinux &platdev = canvas_->getTopPlatformDevice();
skia::BitmapPlatformDeviceLinux* const bitdev =
static_cast<skia::BitmapPlatformDeviceLinux* >(&platdev);
cairo_t* cairo_drawable = gdk_cairo_create(window);
cairo_set_source_surface(cairo_drawable, bitdev->surface(), 0, 0);
cairo_paint(cairo_drawable);
cairo_destroy(cairo_drawable);
gdk_window_end_paint(window);
}
void WebWidgetHost::ResetScrollRect() {
// This method is only needed for optimized scroll painting, which we don't
// care about in the test shell, yet.
}
void WebWidgetHost::PaintRect(const gfx::Rect& rect) {
set_painting(true);
webwidget_->Paint(canvas_.get(), rect);
set_painting(false);
}
void WebWidgetHost::WindowDestroyed() {
delete this;
}
<commit_msg>Refactor the custom GTK container implementation into a class of statics. No effective change, just grouping some methods together to make the implementation more clear.<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 "webkit/tools/test_shell/webwidget_host.h"
#include <cairo/cairo.h>
#include <gtk/gtk.h>
#include "base/basictypes.h"
#include "base/logging.h"
#include "skia/ext/bitmap_platform_device_linux.h"
#include "skia/ext/platform_canvas_linux.h"
#include "skia/ext/platform_device_linux.h"
#include "webkit/glue/webinputevent.h"
#include "webkit/glue/webwidget.h"
namespace {
// The web contents are completely drawn and handled by WebKit, except that
// windowed plugins are GtkSockets on top of it. GtkSockets are unhappy
// if they cannot be put within a parent container, so what we want is basically
// a GtkDrawingArea that is also a GtkContainer. The existing Gtk classes for
// this sort of thing (reasonably) assume that the positioning of the children
// will be handled by the parent, which isn't the case for us where WebKit
// drives everything. So we create a custom widget that is just a GtkContainer
// that contains a native window. This class is just a collection of static
// methods, which implement the GTK functions for the container.
class CustomGtkContainer {
public:
// Create a new instance of our GTK widget object.
static GtkWidget* CreateNewWidget() {
return GTK_WIDGET(g_object_new(GetType(), NULL));
}
private:
// Create and register our custom container type with GTK.
static GType GetType() {
static GType type = 0; // We only want to register our type once.
if (!type) {
static const GTypeInfo info = {
sizeof(GtkContainerClass),
NULL, NULL,
static_cast<GClassInitFunc>(&ClassInit),
NULL, NULL,
sizeof(GtkContainer), // We are identical in memory to a GtkContainer.
0, NULL,
};
type = g_type_register_static(GTK_TYPE_CONTAINER, "WebWidgetHostGtk",
&info, static_cast<GTypeFlags>(0));
}
return type;
}
// Implementation of the class initializer.
static void ClassInit(gpointer klass, gpointer class_data_unusued) {
GtkWidgetClass* widget_class = reinterpret_cast<GtkWidgetClass*>(klass);
GtkContainerClass* container_class =
reinterpret_cast<GtkContainerClass*>(klass);
widget_class->realize = &HandleRealize;
widget_class->size_allocate = &HandleSizeAllocate;
container_class->remove = &HandleRemove;
}
// Implementation of the "realize" event. Creates an X window.
// (Nearly identical to GtkDrawingArea code.)
static void HandleRealize(GtkWidget* widget) {
GTK_WIDGET_SET_FLAGS(widget, GTK_REALIZED);
GdkWindowAttr attributes;
attributes.window_type = GDK_WINDOW_CHILD;
attributes.x = widget->allocation.x;
attributes.y = widget->allocation.y;
attributes.width = widget->allocation.width;
attributes.height = widget->allocation.height;
attributes.wclass = GDK_INPUT_OUTPUT;
attributes.visual = gtk_widget_get_visual(widget);
attributes.colormap = gtk_widget_get_colormap(widget);
attributes.event_mask = gtk_widget_get_events(widget) | GDK_EXPOSURE_MASK;
int attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
widget->window = gdk_window_new(gtk_widget_get_parent_window(widget),
&attributes, attributes_mask);
gdk_window_set_user_data(widget->window, widget);
SendConfigureMessage(widget);
}
// Implementation of the "size-allocate" event. Resizes the window.
// (Nearly identical to GtkDrawingArea code.)
static void HandleSizeAllocate(GtkWidget* widget,
GtkAllocation* allocation) {
widget->allocation = *allocation;
if (!GTK_WIDGET_REALIZED(widget)) {
// We don't have a window yet, so nothing to do.
return;
}
gdk_window_move_resize(widget->window,
allocation->x, allocation->y,
allocation->width, allocation->height);
SendConfigureMessage(widget);
}
// Implementation of "remove" event. This called when plugins shut down.
// We can just ignore it.
static void HandleRemove(GtkContainer* container, GtkWidget* widget) {
// Do nothing.
}
// Sends a "configure" event to the widget, allowing it to repaint.
static void SendConfigureMessage(GtkWidget* widget) {
GdkEvent* event = gdk_event_new(GDK_CONFIGURE);
// This ref matches GtkDrawingArea code. It must be balanced by the
// event-handling code.
g_object_ref(widget->window);
event->configure.window = widget->window;
event->configure.send_event = TRUE;
event->configure.x = widget->allocation.x;
event->configure.y = widget->allocation.y;
event->configure.width = widget->allocation.width;
event->configure.height = widget->allocation.height;
gtk_widget_event(widget, event);
gdk_event_free(event);
}
DISALLOW_IMPLICIT_CONSTRUCTORS(CustomGtkContainer);
};
// In response to an invalidation, we call into WebKit to do layout. On
// Windows, WM_PAINT is a virtual message so any extra invalidates that come up
// while it's doing layout are implicitly swallowed as soon as we actually do
// drawing via BeginPaint.
//
// Though GTK does know how to collapse multiple paint requests, it won't erase
// paint requests from the future when we start drawing. To avoid an infinite
// cycle of repaints, we track whether we're currently handling a redraw, and
// during that if we get told by WebKit that a region has become invalid, we
// still add that region to the local dirty rect but *don't* enqueue yet
// another "do a paint" message.
bool handling_expose = false;
// -----------------------------------------------------------------------------
// Callback functions to proxy to host...
gboolean ConfigureEvent(GtkWidget* widget, GdkEventConfigure* config,
WebWidgetHost* host) {
host->Resize(gfx::Size(config->width, config->height));
return FALSE;
}
gboolean ExposeEvent(GtkWidget* widget, GdkEventExpose* expose,
WebWidgetHost* host) {
// See comments above about what handling_expose is for.
handling_expose = true;
gfx::Rect rect(expose->area);
host->UpdatePaintRect(rect);
host->Paint();
handling_expose = false;
return FALSE;
}
gboolean WindowDestroyed(GtkWidget* widget, WebWidgetHost* host) {
host->WindowDestroyed();
return FALSE;
}
gboolean KeyPressReleaseEvent(GtkWidget* widget, GdkEventKey* event,
WebWidgetHost* host) {
WebKeyboardEvent wke(event);
host->webwidget()->HandleInputEvent(&wke);
// The WebKeyboardEvent model, when holding down a key, is:
// KEY_DOWN, CHAR, (repeated CHAR as key repeats,) KEY_UP
// The GDK model for the same sequence is just:
// KEY_PRESS, (repeated KEY_PRESS as key repeats,) KEY_RELEASE
// So we must simulate a CHAR event for every key press.
if (event->type == GDK_KEY_PRESS) {
wke.type = WebKeyboardEvent::CHAR;
host->webwidget()->HandleInputEvent(&wke);
}
return FALSE;
}
// This signal is called when arrow keys or tab is pressed. If we return true,
// we prevent focus from being moved to another widget. If we want to allow
// focus to be moved outside of web contents, we need to implement
// WebViewDelegate::TakeFocus in the test webview delegate.
gboolean FocusMove(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
return TRUE;
}
gboolean FocusIn(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
host->webwidget()->SetFocus(true);
return FALSE;
}
gboolean FocusOut(GtkWidget* widget, GdkEventFocus* focus,
WebWidgetHost* host) {
host->webwidget()->SetFocus(false);
return FALSE;
}
gboolean ButtonPressReleaseEvent(GtkWidget* widget, GdkEventButton* event,
WebWidgetHost* host) {
WebMouseEvent wme(event);
host->webwidget()->HandleInputEvent(&wme);
return FALSE;
}
gboolean MouseMoveEvent(GtkWidget* widget, GdkEventMotion* event,
WebWidgetHost* host) {
WebMouseEvent wme(event);
host->webwidget()->HandleInputEvent(&wme);
return FALSE;
}
gboolean MouseScrollEvent(GtkWidget* widget, GdkEventScroll* event,
WebWidgetHost* host) {
WebMouseWheelEvent wmwe(event);
host->webwidget()->HandleInputEvent(&wmwe);
return FALSE;
}
} // namespace
GtkWidget* WebWidgetHost::CreateWindow(GtkWidget* parent_view, void* host) {
GtkWidget* widget = CustomGtkContainer::CreateNewWidget();
gtk_box_pack_start(GTK_BOX(parent_view), widget, TRUE, TRUE, 0);
// TODO(evanm): it might be cleaner to just have the custom widget set
// all of this up rather than connecting signals.
gtk_widget_add_events(widget, GDK_EXPOSURE_MASK |
GDK_POINTER_MOTION_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK |
GDK_KEY_PRESS_MASK |
GDK_KEY_RELEASE_MASK);
GTK_WIDGET_SET_FLAGS(widget, GTK_CAN_FOCUS);
g_signal_connect(widget, "configure-event", G_CALLBACK(ConfigureEvent), host);
g_signal_connect(widget, "expose-event", G_CALLBACK(ExposeEvent), host);
g_signal_connect(widget, "destroy", G_CALLBACK(::WindowDestroyed), host);
g_signal_connect(widget, "key-press-event", G_CALLBACK(KeyPressReleaseEvent),
host);
g_signal_connect(widget, "key-release-event",
G_CALLBACK(KeyPressReleaseEvent), host);
g_signal_connect(widget, "focus", G_CALLBACK(FocusMove), host);
g_signal_connect(widget, "focus-in-event", G_CALLBACK(FocusIn), host);
g_signal_connect(widget, "focus-out-event", G_CALLBACK(FocusOut), host);
g_signal_connect(widget, "button-press-event",
G_CALLBACK(ButtonPressReleaseEvent), host);
g_signal_connect(widget, "button-release-event",
G_CALLBACK(ButtonPressReleaseEvent), host);
g_signal_connect(widget, "motion-notify-event", G_CALLBACK(MouseMoveEvent),
host);
g_signal_connect(widget, "scroll-event", G_CALLBACK(MouseScrollEvent),
host);
return widget;
}
WebWidgetHost* WebWidgetHost::Create(GtkWidget* parent_view,
WebWidgetDelegate* delegate) {
WebWidgetHost* host = new WebWidgetHost();
host->view_ = CreateWindow(parent_view, host);
host->webwidget_ = WebWidget::Create(delegate);
// We manage our own double buffering because we need to be able to update
// the expose area in an ExposeEvent within the lifetime of the event handler.
gtk_widget_set_double_buffered(GTK_WIDGET(host->view_), false);
return host;
}
void WebWidgetHost::UpdatePaintRect(const gfx::Rect& rect) {
paint_rect_ = paint_rect_.Union(rect);
}
void WebWidgetHost::DidInvalidateRect(const gfx::Rect& damaged_rect) {
DLOG_IF(WARNING, painting_) << "unexpected invalidation while painting";
UpdatePaintRect(damaged_rect);
if (!handling_expose) {
gtk_widget_queue_draw_area(GTK_WIDGET(view_), damaged_rect.x(),
damaged_rect.y(), damaged_rect.width(), damaged_rect.height());
}
}
void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) {
// This is used for optimizing painting when the renderer is scrolled. We're
// currently not doing any optimizations so just invalidate the region.
DidInvalidateRect(clip_rect);
}
WebWidgetHost::WebWidgetHost()
: view_(NULL),
webwidget_(NULL),
scroll_dx_(0),
scroll_dy_(0),
track_mouse_leave_(false) {
set_painting(false);
}
WebWidgetHost::~WebWidgetHost() {
webwidget_->Close();
webwidget_->Release();
}
void WebWidgetHost::Resize(const gfx::Size &newsize) {
// The pixel buffer backing us is now the wrong size
canvas_.reset();
webwidget_->Resize(gfx::Size(newsize.width(), newsize.height()));
}
void WebWidgetHost::Paint() {
int width = view_->allocation.width;
int height = view_->allocation.height;
gfx::Rect client_rect(width, height);
// Allocate a canvas if necessary
if (!canvas_.get()) {
ResetScrollRect();
paint_rect_ = client_rect;
canvas_.reset(new skia::PlatformCanvas(width, height, true));
if (!canvas_.get()) {
// memory allocation failed, we can't paint.
LOG(ERROR) << "Failed to allocate memory for " << width << "x" << height;
return;
}
}
// This may result in more invalidation
webwidget_->Layout();
// Paint the canvas if necessary. Allow painting to generate extra rects the
// first time we call it. This is necessary because some WebCore rendering
// objects update their layout only when painted.
// Store the total area painted in total_paint. Then tell the gdk window
// to update that area after we're done painting it.
gfx::Rect total_paint;
for (int i = 0; i < 2; ++i) {
paint_rect_ = client_rect.Intersect(paint_rect_);
if (!paint_rect_.IsEmpty()) {
gfx::Rect rect(paint_rect_);
paint_rect_ = gfx::Rect();
DLOG_IF(WARNING, i == 1) << "painting caused additional invalidations";
PaintRect(rect);
total_paint = total_paint.Union(rect);
}
}
DCHECK(paint_rect_.IsEmpty());
// Invalidate the paint region on the widget's underlying gdk window. Note
// that gdk_window_invalidate_* will generate extra expose events, which
// we wish to avoid. So instead we use calls to begin_paint/end_paint.
GdkRectangle grect = {
total_paint.x(),
total_paint.y(),
total_paint.width(),
total_paint.height(),
};
GdkWindow* window = view_->window;
gdk_window_begin_paint_rect(window, &grect);
// BitBlit to the gdk window.
skia::PlatformDeviceLinux &platdev = canvas_->getTopPlatformDevice();
skia::BitmapPlatformDeviceLinux* const bitdev =
static_cast<skia::BitmapPlatformDeviceLinux* >(&platdev);
cairo_t* cairo_drawable = gdk_cairo_create(window);
cairo_set_source_surface(cairo_drawable, bitdev->surface(), 0, 0);
cairo_paint(cairo_drawable);
cairo_destroy(cairo_drawable);
gdk_window_end_paint(window);
}
void WebWidgetHost::ResetScrollRect() {
// This method is only needed for optimized scroll painting, which we don't
// care about in the test shell, yet.
}
void WebWidgetHost::PaintRect(const gfx::Rect& rect) {
set_painting(true);
webwidget_->Paint(canvas_.get(), rect);
set_painting(false);
}
void WebWidgetHost::WindowDestroyed() {
delete this;
}
<|endoftext|> |
<commit_before>#include "PlainPrinter.h"
#include "ASTExprTraits.h"
#include <clang/Lex/Lexer.h>
PlainPrinterAction::PlainPrinterAction(const llvm::StringRef &filename) :
ASTAction<PlainPrinterAction>(),
OutputFile(std::make_shared<std::fstream>()) {
OutputFile->open(filename, std::fstream::out);
}
PlainPrinterAction::~PlainPrinterAction() {
OutputFile->close();
}
std::fstream &PlainPrinterAction::getStream() {
return *OutputFile;
}
PlainPrinterAction::PlainPrinterAction(const PlainPrinterAction &action) :
ASTAction<PlainPrinterAction>(), OutputFile(action.OutputFile) { }
template <>
void PlainPrinter::Visit(FunctionDecl *func) {
parent.getStream() << ", $\n";
VisitImpl(func);
}
template <>
void PlainPrinter::Visit(TranslationUnitDecl *d) { }
#define DEFINE_FOR_ALL(CLASS) \
template void PlainPrinter::VisitImpl<CLASS>(CLASS *);
#include "ASTMacroHelpers.h"
namespace {
struct PrinterHelper {
std::fstream &out;
const clang::SourceManager &manager;
const clang::PrintingPolicy &policy;
};
template <class ExprT>
inline constexpr auto getNodeName(ExprT *node) ->
decltype(ASTExprTraits<ExprT>::name) {
return ASTExprTraits<ExprT>::name;
}
template <class ExprT>
inline std::string getSourceRepr(ExprT *node, ...) {
llvm::errs() << "Not a single category: " << getNodeName(node) << "\n";
return "";
}
template <class ExprT>
inline auto getSourceRepr(ExprT *node, PrinterHelper helper) ->
decltype((void)node->desugar(), std::string()) {
llvm::errs() << "desugar category: " << getNodeName(node) << "\n";
QualType desugaredType = node->desugar();
return desugaredType.getAsString(helper.policy);
}
template <class ExprT>
inline auto getSourceRepr(ExprT *node, PrinterHelper helper) ->
decltype((void)node->getSourceRange(), std::string()) {
llvm::errs() << "getSourceRange category: " << getNodeName(node) << "\n";
// (T, U) => "T,,"
std::string text = clang::Lexer::getSourceText(
CharSourceRange::getTokenRange(node->getSourceRange()), helper.manager,
LangOptions(), 0);
if (text.size() != 0 && text.at(text.size()-1) == ',')
return clang::Lexer::getSourceText(
CharSourceRange::getCharRange(node->getSourceRange()), helper.manager,
LangOptions(), 0);
return text;
}
template <class ExprT>
inline void defaultVisit(ExprT *node, PrinterHelper helper) {
helper.out << "(" << getNodeName(node) << "@@ " <<
getSourceRepr(node, helper) << "), ";
}
}
template <class ExprT>
void PlainPrinter::VisitImpl(ExprT *node) {
defaultVisit(node, {parent.getStream(),
context->getSourceManager(),
context->getPrintingPolicy()});
}
<commit_msg>Represent compound statements with less symbols.<commit_after>#include "PlainPrinter.h"
#include "ASTExprTraits.h"
#include <clang/Lex/Lexer.h>
PlainPrinterAction::PlainPrinterAction(const llvm::StringRef &filename) :
ASTAction<PlainPrinterAction>(),
OutputFile(std::make_shared<std::fstream>()) {
OutputFile->open(filename, std::fstream::out);
}
PlainPrinterAction::~PlainPrinterAction() {
OutputFile->close();
}
std::fstream &PlainPrinterAction::getStream() {
return *OutputFile;
}
PlainPrinterAction::PlainPrinterAction(const PlainPrinterAction &action) :
ASTAction<PlainPrinterAction>(), OutputFile(action.OutputFile) { }
template <>
void PlainPrinter::Visit(FunctionDecl *func) {
parent.getStream() << ", $\n";
VisitImpl(func);
}
template <>
void PlainPrinter::Visit(TranslationUnitDecl *d) { }
#define DEFINE_FOR_ALL(CLASS) \
template void PlainPrinter::VisitImpl<CLASS>(CLASS *);
#include "ASTMacroHelpers.h"
namespace {
struct PrinterHelper {
std::fstream &out;
const clang::SourceManager &manager;
const clang::PrintingPolicy &policy;
};
template <class ExprT>
inline constexpr auto getNodeName(ExprT *node) ->
decltype(ASTExprTraits<ExprT>::name) {
return ASTExprTraits<ExprT>::name;
}
template <class ExprT>
inline std::string getSourceRepr(ExprT *node, ...) {
llvm::errs() << "Not a single category: " << getNodeName(node) << "\n";
return "";
}
template <class ExprT>
inline auto getSourceRepr(ExprT *node, PrinterHelper helper) ->
decltype((void)node->desugar(), std::string()) {
llvm::errs() << "desugar category: " << getNodeName(node) << "\n";
QualType desugaredType = node->desugar();
return desugaredType.getAsString(helper.policy);
}
template <class ExprT>
inline SourceRange getSourceRange(ExprT *node, ...) {
return node->getSourceRange();
}
template <class ExprT>
inline auto getSourceRange(ExprT *node, PrinterHelper helper) ->
decltype((void)node->children(), SourceRange()) {
SourceRange range = node->getSourceRange();
SourceLocation nodeBegin = range.getBegin(),
childBegin = range.getEnd() , current;
llvm::errs() << "start: " << nodeBegin.printToString(helper.manager)
<< "; end: " << childBegin.printToString(helper.manager) << "\n";
for (auto child: node->children()) {
current = child->getSourceRange().getBegin();
llvm::errs() << "child begin: " << current.printToString(helper.manager) << "\n";
if (current < childBegin) {
childBegin = current;
}
}
return {nodeBegin, childBegin};
}
template <class ExprT>
inline auto getSourceRepr(ExprT *node, PrinterHelper helper) ->
decltype((void)node->getSourceRange(), std::string()) {
llvm::errs() << "getSourceRange category: " << getNodeName(node) << "\n";
std::string text = clang::Lexer::getSourceText(
CharSourceRange::getCharRange(getSourceRange(node, helper)),
helper.manager, LangOptions(), 0);
return text;
}
template <class ExprT>
inline void defaultVisit(ExprT *node, PrinterHelper helper) {
helper.out << "(" << getNodeName(node) << "@@ " <<
getSourceRepr(node, helper) << "), ";
}
}
template <class ExprT>
void PlainPrinter::VisitImpl(ExprT *node) {
defaultVisit(node, {parent.getStream(),
context->getSourceManager(),
context->getPrintingPolicy()});
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Modules/Legacy/String/PrintMatrixIntoString.h>
#include <stdio.h>
#include <Dataflow/Network/Module.h>
#include <Core/Datatypes/String.h>
#include <Core/Datatypes/Matrix.h>
//#include <Core/Datatypes/Legacy/Matrix/DenseColMajMatrix.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/MatrixTypeConverter.h>
#ifdef _WIN32
#define snprintf _snprintf
#endif
/// @class PrintMatrixIntoString
/// @brief This module does a sprintf with input matrices into a new string.
using namespace SCIRun::Modules::StringManip;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
SCIRun::Core::Algorithms::AlgorithmParameterName PrintMatrixIntoString::FormatString("FormatString");
const ModuleLookupInfo PrintMatrixIntoString::staticInfo_("PrintMatrixIntoString", "String", "SCIRun");
PrintMatrixIntoString::PrintMatrixIntoString() : Module(staticInfo_)
{
INITIALIZE_PORT(Format);
INITIALIZE_PORT(Input);
INITIALIZE_PORT(Output);
}
void PrintMatrixIntoString::setStateDefaults()
{
auto state = get_state();
state->setValue(FormatString,std::string ("time: %5.4f ms"));
}
void
PrintMatrixIntoString::execute()
{
std::string format, output;
MatrixHandle currentmatrix = 0;
int inputport = 0;
index_type matrixindex = 0;
double datavalue = 0;
double* dataptr = 0;
bool lastport = false;
bool lastdata = false;
bool isformat = false;
std::vector<char> buffer(256);
auto stringH = getOptionalInput(Format);
auto state = get_state();
// check for port input and in none use gui input
if (stringH && *stringH)
{
state -> setValue(FormatString, (*stringH) -> value());
}
format = state -> getValue(FormatString).toString();
// Get the dynamic handles
auto matrixH = getOptionalDynamicInputs(Input);
if (needToExecute())
{
size_t i = 0;
while(i < format.size())
{
if (format[i] == '%')
{
if (i == format.size()-1)
{
error("Improper format string '%' is last character");
return;
}
if (format[i+1] == '%')
{
output += '%'; i += 2;
}
else
{
size_t j = i+1;
// Just to name a few printing options
while((j < format.size())&&(format[j] != 'd')&&(format[j] != 'e')&&(format[j] != 'g')&&(format[j] != 'c')
&&(format[j] != 'i')&&(format[j] != 'E')&&(format[j] != 'x')&&(format[j] != 'X')&&(format[j] != 's')
&&(format[j] != 'u')&&(format[j] != 'o')&&(format[j] != 'g')&&(format[j] != 'G')&&(format[j] != 'f')
&&(format[j] != 'F')&&(format[j] != 'A')&&(format[j] != 'a')&&(format[j] != 'p')&&(format[j] != 'P')) j++;
if (j == format.size())
{
error("Improper format string '%..type' clause was incomplete");
return;
}
std::string fstr = format.substr(i,j-i+1);
if ((format[j] != 's')&&(format[j] != 'S')&&(format[j] != 'C')&&(format[j] != 'c')&&(format[j] != 'p')&&(format[j] != 'P'))
{
isformat = true;
datavalue = 0.0;
while ((currentmatrix.get_rep() == 0)&&(lastport==false))
{
if (static_cast<size_t>(inputport) >= matrixH.size())
{
lastport = true;
lastdata = true;
}
else
{
currentmatrix = matrixH[inputport];
inputport++;
matrixindex = 0;
if (currentmatrix.get_rep())
{
if (currentmatrix->get_data_size() == 0) currentmatrix = 0;
}
if (currentmatrix.get_rep())
{
// Check whether we need to transpose matrix
// If so we transpose the whole matrix
if (matrix_is::dense_col_maj(currentmatrix))
{
currentmatrix = currentmatrix->dense();
}
}
}
}
if (currentmatrix.get_rep())
{
dataptr = currentmatrix->get_data_pointer();
if (matrixindex < currentmatrix->get_data_size())
{
datavalue = dataptr[matrixindex]; matrixindex++;
}
else
{
datavalue = 0.0;
}
if (matrixindex == currentmatrix->get_data_size())
{
currentmatrix = 0;
if (static_cast<size_t>(inputport) == matrixH.size())
{
lastdata = true;
lastport = true;
}
}
}
}
if ((format[j] == 's')||(format[j] == 'S')||(format[j] == 'c')||(format[j] == 'C'))
{
// We put the %s %S back in the string so it can be filled out lateron
// By a different module
output += fstr;
i = j+1;
}
else if ((format[j] == 'd')||(format[j] == 'o'))
{
int scalar = static_cast<int>(datavalue);
snprintf(&(buffer[0]),256,fstr.c_str(),scalar);
output += std::string(reinterpret_cast<char *>(&(buffer[0])));
i = j+1;
}
else if ((format[j] == 'i')||(format[j] == 'u')||(format[j] == 'x')||(format[j] == 'X'))
{
unsigned int scalar = static_cast<unsigned int>(datavalue);
snprintf(&(buffer[0]),256,fstr.c_str(),scalar);
output += std::string(reinterpret_cast<char *>(&(buffer[0])));
i = j+1;
}
else if ((format[j] == 'e')||(format[j] == 'E')||(format[j] == 'f')||(format[j] == 'F')||
(format[j] == 'g')||(format[j] == 'G')||(format[j] == 'a')||(format[j] == 'A'))
{
snprintf(&(buffer[0]),256,fstr.c_str(),datavalue);
output += std::string(reinterpret_cast<char *>(&(buffer[0])));
i = j+1;
}
else if ((format[j] == 'p')||(format[j] == 'P'))
{
fstr[fstr.size()-1] = 'g';
double ptime = get_time();
snprintf(&(buffer[0]),256,fstr.c_str(),ptime);
output += std::string(reinterpret_cast<char *>(&(buffer[0])));
i = j+1;
}
}
}
else if ( format[i] == '\\')
{
if (i < (format.size()-1))
{
switch (format[i+1])
{
case 'n': output += '\n'; break;
case 'b': output += '\b'; break;
case 't': output += '\t'; break;
case 'r': output += '\r'; break;
case '\\': output += '\\'; break;
case '0': output += '\0'; break;
case 'v': output += '\v'; break;
default:
error("unknown escape character");
return;
}
i = i+2;
}
}
else
{
output += format[i]; i++;
}
if ((i== format.size())&&(isformat == true)&&(lastdata == false))
{
i = 0;
}
}
StringHandle handle(new String(output));
sendOutput(Output, handle);
}
}
<commit_msg>working on build errors<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Modules/Legacy/String/PrintMatrixIntoString.h>
#include <stdio.h>
#include <Dataflow/Network/Module.h>
#include <Core/Datatypes/String.h>
#include <Core/Datatypes/Matrix.h>
//#include <Core/Datatypes/Legacy/Matrix/DenseColMajMatrix.h>
#include <Core/Math/MiscMath.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/MatrixTypeConversions.h>
#ifdef _WIN32
#define snprintf _snprintf
#endif
/// @class PrintMatrixIntoString
/// @brief This module does a sprintf with input matrices into a new string.
using namespace SCIRun::Modules::StringManip;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
SCIRun::Core::Algorithms::AlgorithmParameterName PrintMatrixIntoString::FormatString("FormatString");
const ModuleLookupInfo PrintMatrixIntoString::staticInfo_("PrintMatrixIntoString", "String", "SCIRun");
PrintMatrixIntoString::PrintMatrixIntoString() : Module(staticInfo_)
{
INITIALIZE_PORT(Format);
INITIALIZE_PORT(Input);
INITIALIZE_PORT(Output);
}
void PrintMatrixIntoString::setStateDefaults()
{
auto state = get_state();
state->setValue(FormatString,std::string ("time: %5.4f ms"));
}
void
PrintMatrixIntoString::execute()
{
std::string format, output;
MatrixHandle currentmatrix;
int inputport = 0;
index_type matrixindex = 0;
double datavalue = 0;
double* dataptr = 0;
bool lastport = false;
bool lastdata = false;
bool isformat = false;
std::vector<char> buffer(256);
auto stringH = getOptionalInput(Format);
auto state = get_state();
// check for port input and in none use gui input
if (stringH && *stringH)
{
state -> setValue(FormatString, (*stringH) -> value());
}
format = state -> getValue(FormatString).toString();
// Get the dynamic handles
auto matrixH = getOptionalDynamicInputs(Input);
if (needToExecute())
{
size_t i = 0;
while(i < format.size())
{
if (format[i] == '%')
{
if (i == format.size()-1)
{
error("Improper format string '%' is last character");
return;
}
if (format[i+1] == '%')
{
output += '%'; i += 2;
}
else
{
size_t j = i+1;
// Just to name a few printing options
while((j < format.size())&&(format[j] != 'd')&&(format[j] != 'e')&&(format[j] != 'g')&&(format[j] != 'c')
&&(format[j] != 'i')&&(format[j] != 'E')&&(format[j] != 'x')&&(format[j] != 'X')&&(format[j] != 's')
&&(format[j] != 'u')&&(format[j] != 'o')&&(format[j] != 'g')&&(format[j] != 'G')&&(format[j] != 'f')
&&(format[j] != 'F')&&(format[j] != 'A')&&(format[j] != 'a')&&(format[j] != 'p')&&(format[j] != 'P')) j++;
if (j == format.size())
{
error("Improper format string '%..type' clause was incomplete");
return;
}
std::string fstr = format.substr(i,j-i+1);
if ((format[j] != 's')&&(format[j] != 'S')&&(format[j] != 'C')&&(format[j] != 'c')&&(format[j] != 'p')&&(format[j] != 'P'))
{
isformat = true;
datavalue = 0.0;
while ((currentmatrix.get_rep() == 0)&&(lastport==false))
{
if (static_cast<size_t>(inputport) >= matrixH.size())
{
lastport = true;
lastdata = true;
}
else
{
currentmatrix = matrixH[inputport];
inputport++;
matrixindex = 0;
if (currentmatrix.get_rep())
{
if (currentmatrix->get_data_size() == 0) currentmatrix = 0;
}
if (currentmatrix.get_rep())
{
// Check whether we need to transpose matrix
// If so we transpose the whole matrix
if (matrix_is::dense_col_maj(currentmatrix))
{
currentmatrix = currentmatrix->dense();
}
}
}
}
if (currentmatrix.get_rep())
{
dataptr = currentmatrix->get_data_pointer();
if (matrixindex < currentmatrix->get_data_size())
{
datavalue = dataptr[matrixindex]; matrixindex++;
}
else
{
datavalue = 0.0;
}
if (matrixindex == currentmatrix->get_data_size())
{
currentmatrix = 0;
if (static_cast<size_t>(inputport) == matrixH.size())
{
lastdata = true;
lastport = true;
}
}
}
}
if ((format[j] == 's')||(format[j] == 'S')||(format[j] == 'c')||(format[j] == 'C'))
{
// We put the %s %S back in the string so it can be filled out lateron
// By a different module
output += fstr;
i = j+1;
}
else if ((format[j] == 'd')||(format[j] == 'o'))
{
int scalar = static_cast<int>(datavalue);
snprintf(&(buffer[0]),256,fstr.c_str(),scalar);
output += std::string(reinterpret_cast<char *>(&(buffer[0])));
i = j+1;
}
else if ((format[j] == 'i')||(format[j] == 'u')||(format[j] == 'x')||(format[j] == 'X'))
{
unsigned int scalar = static_cast<unsigned int>(datavalue);
snprintf(&(buffer[0]),256,fstr.c_str(),scalar);
output += std::string(reinterpret_cast<char *>(&(buffer[0])));
i = j+1;
}
else if ((format[j] == 'e')||(format[j] == 'E')||(format[j] == 'f')||(format[j] == 'F')||
(format[j] == 'g')||(format[j] == 'G')||(format[j] == 'a')||(format[j] == 'A'))
{
snprintf(&(buffer[0]),256,fstr.c_str(),datavalue);
output += std::string(reinterpret_cast<char *>(&(buffer[0])));
i = j+1;
}
else if ((format[j] == 'p')||(format[j] == 'P'))
{
fstr[fstr.size()-1] = 'g';
double ptime = get_time();
snprintf(&(buffer[0]),256,fstr.c_str(),ptime);
output += std::string(reinterpret_cast<char *>(&(buffer[0])));
i = j+1;
}
}
}
else if ( format[i] == '\\')
{
if (i < (format.size()-1))
{
switch (format[i+1])
{
case 'n': output += '\n'; break;
case 'b': output += '\b'; break;
case 't': output += '\t'; break;
case 'r': output += '\r'; break;
case '\\': output += '\\'; break;
case '0': output += '\0'; break;
case 'v': output += '\v'; break;
default:
error("unknown escape character");
return;
}
i = i+2;
}
}
else
{
output += format[i]; i++;
}
if ((i== format.size())&&(isformat == true)&&(lastdata == false))
{
i = 0;
}
}
StringHandle handle(new String(output));
sendOutput(Output, handle);
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2018 The Apollo 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 "cyber/record/record_reader.h"
#include <utility>
namespace apollo {
namespace cyber {
namespace record {
using proto::SectionType;
RecordReader::~RecordReader() {}
RecordReader::RecordReader(const std::string& file) {
file_reader_.reset(new RecordFileReader());
if (!file_reader_->Open(file)) {
AERROR << "Open record file failed, file: " << file;
return;
}
is_valid_ = true;
header_ = file_reader_->GetHeader();
if (file_reader_->ReadIndex()) {
index_ = file_reader_->GetIndex();
const int kIndexSize = index_.indexes_size();
for (int i = 0; i < kIndexSize; ++i) {
auto single_idx = index_.mutable_indexes(i);
if (single_idx->type() != SectionType::SECTION_CHANNEL) {
continue;
}
if (!single_idx->has_channel_cache()) {
AERROR << "single channel index does not have channel_cache.";
continue;
}
auto channel_cache = single_idx->mutable_channel_cache();
channel_info_.insert(
std::make_pair(channel_cache->name(), *channel_cache));
}
}
file_reader_->Reset();
}
void RecordReader::Reset() {
file_reader_->Reset();
reach_end_ = false;
message_index_ = 0;
chunk_ = ChunkBody();
}
std::set<std::string> RecordReader::GetChannelList() const {
std::set<std::string> channel_list;
for (auto& item : channel_info_) {
channel_list.insert(item.first);
}
return channel_list;
}
bool RecordReader::ReadMessage(RecordMessage* message, uint64_t begin_time,
uint64_t end_time) {
if (!is_valid_) {
return false;
}
while (message_index_ < chunk_.messages_size()) {
const auto& next_message = chunk_.messages(message_index_);
uint64_t time = next_message.time();
if (time > end_time) {
return false;
}
++message_index_;
if (time < begin_time) {
continue;
}
message->channel_name = next_message.channel_name();
message->content = next_message.content();
message->time = time;
return true;
}
if (ReadNextChunk(begin_time, end_time)) {
message_index_ = 0;
return ReadMessage(message, begin_time, end_time);
}
return false;
}
bool RecordReader::ReadNextChunk(uint64_t begin_time, uint64_t end_time) {
bool skip_next_chunk_body = false;
while (!reach_end_) {
Section section;
if (!file_reader_->ReadSection(§ion)) {
AERROR << "Read section failed, file: " << file_reader_->GetPath();
return false;
}
switch (section.type) {
case SectionType::SECTION_INDEX: {
file_reader_->SkipSection(section.size);
reach_end_ = true;
break;
}
case SectionType::SECTION_CHANNEL: {
ADEBUG << "Read channel section of size: " << section.size;
Channel channel;
if (!file_reader_->ReadSection<Channel>(section.size, &channel)) {
AERROR << "Failed to read channel section.";
return false;
}
break;
}
case SectionType::SECTION_CHUNK_HEADER: {
ADEBUG << "Read chunk header section of size: " << section.size;
ChunkHeader header;
if (!file_reader_->ReadSection<ChunkHeader>(section.size, &header)) {
AERROR << "Failed to read chunk header section.";
return false;
}
if (header.end_time() < begin_time) {
skip_next_chunk_body = true;
}
if (header.begin_time() > end_time) {
return false;
}
break;
}
case SectionType::SECTION_CHUNK_BODY: {
if (skip_next_chunk_body) {
file_reader_->SkipSection(section.size);
skip_next_chunk_body = false;
break;
}
if (!file_reader_->ReadSection<ChunkBody>(section.size, &chunk_)) {
AERROR << "Failed to read chunk body section.";
return false;
}
return true;
}
default: {
AERROR << "Invalid section, type: " << section.type
<< ", size: " << section.size;
return false;
}
}
}
return false;
}
uint64_t RecordReader::GetMessageNumber(const std::string& channel_name) const {
auto search = channel_info_.find(channel_name);
if (search == channel_info_.end()) {
return 0;
}
return search->second.message_number();
}
const std::string& RecordReader::GetMessageType(
const std::string& channel_name) const {
auto search = channel_info_.find(channel_name);
if (search == channel_info_.end()) {
return null_type_;
}
return search->second.message_type();
}
const std::string& RecordReader::GetProtoDesc(
const std::string& channel_name) const {
auto search = channel_info_.find(channel_name);
if (search == channel_info_.end()) {
return null_type_;
}
return search->second.proto_desc();
}
} // namespace record
} // namespace cyber
} // namespace apollo
<commit_msg>framework: add judgement of time interval to return early<commit_after>/******************************************************************************
* Copyright 2018 The Apollo 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 "cyber/record/record_reader.h"
#include <utility>
namespace apollo {
namespace cyber {
namespace record {
using proto::SectionType;
RecordReader::~RecordReader() {}
RecordReader::RecordReader(const std::string& file) {
file_reader_.reset(new RecordFileReader());
if (!file_reader_->Open(file)) {
AERROR << "Open record file failed, file: " << file;
return;
}
is_valid_ = true;
header_ = file_reader_->GetHeader();
if (file_reader_->ReadIndex()) {
index_ = file_reader_->GetIndex();
const int kIndexSize = index_.indexes_size();
for (int i = 0; i < kIndexSize; ++i) {
auto single_idx = index_.mutable_indexes(i);
if (single_idx->type() != SectionType::SECTION_CHANNEL) {
continue;
}
if (!single_idx->has_channel_cache()) {
AERROR << "single channel index does not have channel_cache.";
continue;
}
auto channel_cache = single_idx->mutable_channel_cache();
channel_info_.insert(
std::make_pair(channel_cache->name(), *channel_cache));
}
}
file_reader_->Reset();
}
void RecordReader::Reset() {
file_reader_->Reset();
reach_end_ = false;
message_index_ = 0;
chunk_ = ChunkBody();
}
std::set<std::string> RecordReader::GetChannelList() const {
std::set<std::string> channel_list;
for (auto& item : channel_info_) {
channel_list.insert(item.first);
}
return channel_list;
}
bool RecordReader::ReadMessage(RecordMessage* message, uint64_t begin_time,
uint64_t end_time) {
if (!is_valid_) {
return false;
}
if (begin_time > header_.end_time() || end_time < header_.begin_time()) {
return false;
}
while (message_index_ < chunk_.messages_size()) {
const auto& next_message = chunk_.messages(message_index_);
uint64_t time = next_message.time();
if (time > end_time) {
return false;
}
++message_index_;
if (time < begin_time) {
continue;
}
message->channel_name = next_message.channel_name();
message->content = next_message.content();
message->time = time;
return true;
}
if (ReadNextChunk(begin_time, end_time)) {
message_index_ = 0;
return ReadMessage(message, begin_time, end_time);
}
return false;
}
bool RecordReader::ReadNextChunk(uint64_t begin_time, uint64_t end_time) {
bool skip_next_chunk_body = false;
while (!reach_end_) {
Section section;
if (!file_reader_->ReadSection(§ion)) {
AERROR << "Read section failed, file: " << file_reader_->GetPath();
return false;
}
switch (section.type) {
case SectionType::SECTION_INDEX: {
file_reader_->SkipSection(section.size);
reach_end_ = true;
break;
}
case SectionType::SECTION_CHANNEL: {
ADEBUG << "Read channel section of size: " << section.size;
Channel channel;
if (!file_reader_->ReadSection<Channel>(section.size, &channel)) {
AERROR << "Failed to read channel section.";
return false;
}
break;
}
case SectionType::SECTION_CHUNK_HEADER: {
ADEBUG << "Read chunk header section of size: " << section.size;
ChunkHeader header;
if (!file_reader_->ReadSection<ChunkHeader>(section.size, &header)) {
AERROR << "Failed to read chunk header section.";
return false;
}
if (header.end_time() < begin_time) {
skip_next_chunk_body = true;
}
if (header.begin_time() > end_time) {
return false;
}
break;
}
case SectionType::SECTION_CHUNK_BODY: {
if (skip_next_chunk_body) {
file_reader_->SkipSection(section.size);
skip_next_chunk_body = false;
break;
}
if (!file_reader_->ReadSection<ChunkBody>(section.size, &chunk_)) {
AERROR << "Failed to read chunk body section.";
return false;
}
return true;
}
default: {
AERROR << "Invalid section, type: " << section.type
<< ", size: " << section.size;
return false;
}
}
}
return false;
}
uint64_t RecordReader::GetMessageNumber(const std::string& channel_name) const {
auto search = channel_info_.find(channel_name);
if (search == channel_info_.end()) {
return 0;
}
return search->second.message_number();
}
const std::string& RecordReader::GetMessageType(
const std::string& channel_name) const {
auto search = channel_info_.find(channel_name);
if (search == channel_info_.end()) {
return null_type_;
}
return search->second.message_type();
}
const std::string& RecordReader::GetProtoDesc(
const std::string& channel_name) const {
auto search = channel_info_.find(channel_name);
if (search == channel_info_.end()) {
return null_type_;
}
return search->second.proto_desc();
}
} // namespace record
} // namespace cyber
} // namespace apollo
<|endoftext|> |
<commit_before>#include "chasky/core/framework/function_def_builder.h"
#include "chasky/core/framework/argument_def_builder.h"
#include "chasky/core/framework/attr_value_util.h"
using namespace std;
namespace chasky {
// Set default width for each output
FunctionDef FunctionDefBuilder::Finalize() {
size_t default_width = 0;
if (def_.inputs_size() > 0) {
default_width = def_.inputs(0).shape().width();
}
for (size_t i = 0; i < def_.outputs_size(); i++) {
if (def_.outputs(i).shape().width() == 0) {
def_.mutable_outputs(i)->mutable_shape()->set_width(default_width);
}
}
return def_;
}
Status FunctionDefLibrary::Register(const string &name, FunctionDef &&def) {
if (def_library_.count(name) != 0) {
return Status(error::INVALID_ARGUMENT,
strings::Printf("An operator called %s has been registered",
name.c_str()));
}
if (!def_library_.insert({name, def}).second) {
return Status(error::UNKNOWN, strings::empty_string);
}
return Status();
}
Status FunctionDefLibrary::LookUp(const string &name, FunctionDef **def) {
auto it = def_library_.find(name);
if (it == def_library_.end()) {
return Status(
error::OUT_OF_RANGE,
strings::Printf("no operator definition called %s.", name.c_str()));
}
*def = &it->second;
return Status();
}
string FunctionDefLibrary::DebugString() const {
string res =
strings::Printf("FunctionDefLibrary size: %lu\n", def_library_.size());
for (const auto &item : def_library_) {
strings::Appendf(&res, "%s : \n%s\n", item.first.c_str(),
item.second.DebugString().c_str());
}
return res;
}
}
<commit_msg>refector FunctionBuilder with CH_STEST_RETURN2<commit_after>#include "chasky/core/framework/function_def_builder.h"
#include "chasky/core/framework/argument_def_builder.h"
#include "chasky/core/framework/attr_value_util.h"
using namespace std;
namespace chasky {
// Set default width for each output
FunctionDef FunctionDefBuilder::Finalize() {
size_t default_width = 0;
for (size_t i = 0; i < def_.inputs_size(); i++) {
if (def_.inputs(i).has_shape()) {
default_width = def_.inputs(i).shape().width();
if (default_width > 0)
break;
}
}
if (default_width == 0) {
DLOG(WARNING) << "FunctionDef " << def_.name() << " no shape is set";
return def_;
}
for (size_t i = 0; i < def_.outputs_size(); i++) {
if (def_.outputs(i).shape().width() == 0) {
def_.mutable_outputs(i)->mutable_shape()->set_width(default_width);
}
}
return def_;
}
Status FunctionDefLibrary::Register(const string &name, FunctionDef &&def) {
Status status;
DLOG(INFO) << ".. begin register def " << name;
CH_STEST_RETURN2(def_library_.count(name) == 0, error::INVALID_ARGUMENT,
"An operator called %s has been registered", name.c_str());
CH_STEST_RETURN2(def_library_.insert({name, def}).second, error::UNKNOWN,
"insert map error");
return status;
}
Status FunctionDefLibrary::LookUp(const string &name, FunctionDef **def) {
auto it = def_library_.find(name);
if (it == def_library_.end()) {
return Status(
error::OUT_OF_RANGE,
strings::Printf("no operator definition called %s.", name.c_str()));
}
*def = &it->second;
return Status();
}
string FunctionDefLibrary::DebugString() const {
string res =
strings::Printf("FunctionDefLibrary size: %lu\n", def_library_.size());
for (const auto &item : def_library_) {
strings::Appendf(&res, "%s : \n%s\n", item.first.c_str(),
item.second.DebugString().c_str());
}
return res;
}
}
<|endoftext|> |
<commit_before>#include "TBackgroundVuMeter.h"
//using namespace bgslibrary::algorithms::vumeter;
namespace bgslibrary
{
namespace algorithms
{
namespace vumeter
{
const int PROCESS_PAR_COUNT = 3;
TBackgroundVuMeter::TBackgroundVuMeter(void)
: m_pHist(NULL)
, m_nBinCount(0)
, m_nBinSize(8)
, m_nCount(0)
, m_fAlpha(0.995)
, m_fThreshold(0.03)
{
std::cout << "TBackgroundVuMeter()" << std::endl;
}
TBackgroundVuMeter::~TBackgroundVuMeter(void)
{
Clear();
std::cout << "~TBackgroundVuMeter()" << std::endl;
}
void TBackgroundVuMeter::Clear(void)
{
TBackground::Clear();
if (m_pHist != NULL)
{
for (int i = 0; i < m_nBinCount; ++i)
{
if (m_pHist[i] != NULL)
cvReleaseImage(&m_pHist[i]);
}
delete[] m_pHist;
m_pHist = NULL;
m_nBinCount = 0;
}
m_nCount = 0;
}
void TBackgroundVuMeter::Reset(void)
{
float fVal = 0.0;
TBackground::Reset();
if (m_pHist != NULL)
{
// fVal = (m_nBinCount != 0) ? (float)(1.0 / (double)m_nBinCount) : (float)0.0;
fVal = 0.0;
for (int i = 0; i < m_nBinCount; ++i)
{
if (m_pHist[i] != NULL)
{
cvSetZero(m_pHist[i]);
cvAddS(m_pHist[i], cvScalar(fVal), m_pHist[i]);
}
}
}
m_nCount = 0;
}
int TBackgroundVuMeter::GetParameterCount(void)
{
return TBackground::GetParameterCount() + PROCESS_PAR_COUNT;
}
std::string TBackgroundVuMeter::GetParameterName(int nInd)
{
std::string csResult;
int nNb;
nNb = TBackground::GetParameterCount();
if (nInd >= nNb)
{
nInd -= nNb;
switch (nInd)
{
case 0: csResult = "Bin size"; break;
case 1: csResult = "Alpha"; break;
case 2: csResult = "Threshold"; break;
}
}
else
csResult = TBackground::GetParameterName(nInd);
return csResult;
}
std::string TBackgroundVuMeter::GetParameterValue(int nInd)
{
std::string csResult;
int nNb;
nNb = TBackground::GetParameterCount();
if (nInd >= nNb)
{
nInd -= nNb;
char buff[100];
switch (nInd)
{
case 0: sprintf_s(buff, "%d", m_nBinSize); break;
case 1: sprintf_s(buff, "%.3f", m_fAlpha); break;
case 2: sprintf_s(buff, "%.2f", m_fThreshold); break;
}
csResult = buff;
}
else
csResult = TBackground::GetParameterValue(nInd);
return csResult;
}
int TBackgroundVuMeter::SetParameterValue(int nInd, std::string csNew)
{
int nErr = 0;
int nNb;
nNb = TBackground::GetParameterCount();
if (nInd >= nNb)
{
nInd -= nNb;
switch (nInd)
{
case 0: SetBinSize(atoi(csNew.c_str())); break;
case 1: SetAlpha(atof(csNew.c_str())); break;
case 2: SetThreshold(atof(csNew.c_str())); break;
default: nErr = 1;
}
}
else
nErr = TBackground::SetParameterValue(nInd, csNew);
return nErr;
}
int TBackgroundVuMeter::Init(IplImage * pSource)
{
int nErr = 0;
int nbl, nbc;
Clear();
nErr = TBackground::Init(pSource);
if (pSource == NULL)
nErr = 1;
// calcul le nb de bin
if (!nErr)
{
nbl = pSource->height;
nbc = pSource->width;
m_nBinCount = (m_nBinSize != 0) ? 256 / m_nBinSize : 0;
if (m_nBinCount <= 0 || m_nBinCount > 256)
nErr = 1;
}
// creation du tableau de pointeur
if (!nErr)
{
m_pHist = new IplImage *[m_nBinCount];
if (m_pHist == NULL)
nErr = 1;
}
// creation des images
if (!nErr)
{
for (int i = 0; i < m_nBinCount; ++i)
{
m_pHist[i] = cvCreateImage(cvSize(nbc, nbl), IPL_DEPTH_32F, 1);
if (m_pHist[i] == NULL)
nErr = 1;
}
}
if (!nErr)
Reset();
else
Clear();
return nErr;
}
bool TBackgroundVuMeter::isInitOk(IplImage * pSource, IplImage *pBackground, IplImage *pMotionMask)
{
bool bResult = true;
int i;
bResult = TBackground::isInitOk(pSource, pBackground, pMotionMask);
if (pSource == NULL)
bResult = false;
if (m_nBinSize == 0)
bResult = false;
if (bResult)
{
i = (m_nBinSize != 0) ? 256 / m_nBinSize : 0;
if (i != m_nBinCount || m_pHist == NULL)
bResult = false;
}
if (bResult)
{
int nbl = pSource->height;
int nbc = pSource->width;
for (i = 0; i < m_nBinCount; ++i)
{
if (m_pHist[i] == NULL || m_pHist[i]->width != nbc || m_pHist[i]->height != nbl)
bResult = false;
}
}
return bResult;
}
int TBackgroundVuMeter::UpdateBackground(IplImage *pSource, IplImage *pBackground, IplImage *pMotionMask)
{
int nErr = 0;
unsigned char *ptrs, *ptrb, *ptrm;
float *ptr1, *ptr2;
if (!isInitOk(pSource, pBackground, pMotionMask))
nErr = Init(pSource);
if (!nErr)
{
m_nCount++;
int nbc = pSource->width;
int nbl = pSource->height;
unsigned char v = m_nBinSize;
// multiplie tout par alpha
for (int i = 0; i < m_nBinCount; ++i)
cvConvertScale(m_pHist[i], m_pHist[i], m_fAlpha, 0.0);
for (int l = 0; l < nbl; ++l)
{
ptrs = (unsigned char *)(pSource->imageData + pSource->widthStep * l);
ptrm = (unsigned char *)(pMotionMask->imageData + pMotionMask->widthStep * l);
ptrb = (unsigned char *)(pBackground->imageData + pBackground->widthStep * l);
for (int c = 0; c < nbc; ++c, ptrs++, ptrb++, ptrm++)
{
// recherche le bin à augmenter
int i = *ptrs / v;
if (i < 0 || i >= m_nBinCount)
i = 0;
ptr1 = (float *)(m_pHist[i]->imageData + m_pHist[i]->widthStep * l);
ptr1 += c;
*ptr1 += (float)(1.0 - m_fAlpha);
*ptrm = (*ptr1 < m_fThreshold) ? 255 : 0;
// recherche le bin du fond actuel
i = *ptrb / v;
if (i < 0 || i >= m_nBinCount)
i = 0;
ptr2 = (float *)(m_pHist[i]->imageData + m_pHist[i]->widthStep * l);
ptr2 += c;
if (*ptr2 < *ptr1)
*ptrb = *ptrs;
}
}
if (m_nCount < 5)
cvSetZero(pMotionMask);
}
return nErr;
}
IplImage *TBackgroundVuMeter::CreateTestImg()
{
IplImage *pImage = NULL;
if (m_nBinCount > 0)
pImage = cvCreateImage(cvSize(m_nBinCount, 100), IPL_DEPTH_8U, 3);
if (pImage != NULL)
cvSetZero(pImage);
return pImage;
}
int TBackgroundVuMeter::UpdateTest(IplImage *pSource, IplImage *pBackground, IplImage *pTest, int nX, int nY, int nInd)
{
int nErr = 0;
float *ptrf;
if (pTest == NULL || !isInitOk(pSource, pBackground, pSource))
nErr = 1;
if (!nErr)
{
int nbl = pTest->height;
int nbc = pTest->width;
if (nbl != 100 || nbc != m_nBinCount)
nErr = 1;
if (nX < 0 || nX >= pSource->width || nY < 0 || nY >= pSource->height)
nErr = 1;
}
if (!nErr)
{
cvSetZero(pTest);
for (int i = 0; i < m_nBinCount; ++i)
{
ptrf = (float *)(m_pHist[i]->imageData + m_pHist[i]->widthStep * nY);
ptrf += nX;
if (*ptrf >= 0 || *ptrf <= 1.0) {
cvLine(pTest, cvPoint(i, 100), cvPoint(i, (int)(100.0 * (1.0 - *ptrf))), cvScalar(0, 255, 0));
}
}
cvLine(pTest, cvPoint(0, (int)(100.0 * (1.0 - m_fThreshold))), cvPoint(m_nBinCount, (int)(100.0 * (1.0 - m_fThreshold))), cvScalar(0, 128, 0));
}
return nErr;
}
}
}
}
<commit_msg>revert sprintf_s to sprintf related to https://stackoverflow.com/questions/2169016/mac-solution-for-safe-alternatives-to-unsafe-c-c-standard-library-function<commit_after>#include "TBackgroundVuMeter.h"
//using namespace bgslibrary::algorithms::vumeter;
namespace bgslibrary
{
namespace algorithms
{
namespace vumeter
{
const int PROCESS_PAR_COUNT = 3;
TBackgroundVuMeter::TBackgroundVuMeter(void)
: m_pHist(NULL)
, m_nBinCount(0)
, m_nBinSize(8)
, m_nCount(0)
, m_fAlpha(0.995)
, m_fThreshold(0.03)
{
std::cout << "TBackgroundVuMeter()" << std::endl;
}
TBackgroundVuMeter::~TBackgroundVuMeter(void)
{
Clear();
std::cout << "~TBackgroundVuMeter()" << std::endl;
}
void TBackgroundVuMeter::Clear(void)
{
TBackground::Clear();
if (m_pHist != NULL)
{
for (int i = 0; i < m_nBinCount; ++i)
{
if (m_pHist[i] != NULL)
cvReleaseImage(&m_pHist[i]);
}
delete[] m_pHist;
m_pHist = NULL;
m_nBinCount = 0;
}
m_nCount = 0;
}
void TBackgroundVuMeter::Reset(void)
{
float fVal = 0.0;
TBackground::Reset();
if (m_pHist != NULL)
{
// fVal = (m_nBinCount != 0) ? (float)(1.0 / (double)m_nBinCount) : (float)0.0;
fVal = 0.0;
for (int i = 0; i < m_nBinCount; ++i)
{
if (m_pHist[i] != NULL)
{
cvSetZero(m_pHist[i]);
cvAddS(m_pHist[i], cvScalar(fVal), m_pHist[i]);
}
}
}
m_nCount = 0;
}
int TBackgroundVuMeter::GetParameterCount(void)
{
return TBackground::GetParameterCount() + PROCESS_PAR_COUNT;
}
std::string TBackgroundVuMeter::GetParameterName(int nInd)
{
std::string csResult;
int nNb;
nNb = TBackground::GetParameterCount();
if (nInd >= nNb)
{
nInd -= nNb;
switch (nInd)
{
case 0: csResult = "Bin size"; break;
case 1: csResult = "Alpha"; break;
case 2: csResult = "Threshold"; break;
}
}
else
csResult = TBackground::GetParameterName(nInd);
return csResult;
}
std::string TBackgroundVuMeter::GetParameterValue(int nInd)
{
std::string csResult;
int nNb;
nNb = TBackground::GetParameterCount();
if (nInd >= nNb)
{
nInd -= nNb;
char buff[100];
switch (nInd)
{
case 0: sprintf(buff, "%d", m_nBinSize); break;
case 1: sprintf(buff, "%.3f", m_fAlpha); break;
case 2: sprintf(buff, "%.2f", m_fThreshold); break;
}
csResult = buff;
}
else
csResult = TBackground::GetParameterValue(nInd);
return csResult;
}
int TBackgroundVuMeter::SetParameterValue(int nInd, std::string csNew)
{
int nErr = 0;
int nNb;
nNb = TBackground::GetParameterCount();
if (nInd >= nNb)
{
nInd -= nNb;
switch (nInd)
{
case 0: SetBinSize(atoi(csNew.c_str())); break;
case 1: SetAlpha(atof(csNew.c_str())); break;
case 2: SetThreshold(atof(csNew.c_str())); break;
default: nErr = 1;
}
}
else
nErr = TBackground::SetParameterValue(nInd, csNew);
return nErr;
}
int TBackgroundVuMeter::Init(IplImage * pSource)
{
int nErr = 0;
int nbl, nbc;
Clear();
nErr = TBackground::Init(pSource);
if (pSource == NULL)
nErr = 1;
// calcul le nb de bin
if (!nErr)
{
nbl = pSource->height;
nbc = pSource->width;
m_nBinCount = (m_nBinSize != 0) ? 256 / m_nBinSize : 0;
if (m_nBinCount <= 0 || m_nBinCount > 256)
nErr = 1;
}
// creation du tableau de pointeur
if (!nErr)
{
m_pHist = new IplImage *[m_nBinCount];
if (m_pHist == NULL)
nErr = 1;
}
// creation des images
if (!nErr)
{
for (int i = 0; i < m_nBinCount; ++i)
{
m_pHist[i] = cvCreateImage(cvSize(nbc, nbl), IPL_DEPTH_32F, 1);
if (m_pHist[i] == NULL)
nErr = 1;
}
}
if (!nErr)
Reset();
else
Clear();
return nErr;
}
bool TBackgroundVuMeter::isInitOk(IplImage * pSource, IplImage *pBackground, IplImage *pMotionMask)
{
bool bResult = true;
int i;
bResult = TBackground::isInitOk(pSource, pBackground, pMotionMask);
if (pSource == NULL)
bResult = false;
if (m_nBinSize == 0)
bResult = false;
if (bResult)
{
i = (m_nBinSize != 0) ? 256 / m_nBinSize : 0;
if (i != m_nBinCount || m_pHist == NULL)
bResult = false;
}
if (bResult)
{
int nbl = pSource->height;
int nbc = pSource->width;
for (i = 0; i < m_nBinCount; ++i)
{
if (m_pHist[i] == NULL || m_pHist[i]->width != nbc || m_pHist[i]->height != nbl)
bResult = false;
}
}
return bResult;
}
int TBackgroundVuMeter::UpdateBackground(IplImage *pSource, IplImage *pBackground, IplImage *pMotionMask)
{
int nErr = 0;
unsigned char *ptrs, *ptrb, *ptrm;
float *ptr1, *ptr2;
if (!isInitOk(pSource, pBackground, pMotionMask))
nErr = Init(pSource);
if (!nErr)
{
m_nCount++;
int nbc = pSource->width;
int nbl = pSource->height;
unsigned char v = m_nBinSize;
// multiplie tout par alpha
for (int i = 0; i < m_nBinCount; ++i)
cvConvertScale(m_pHist[i], m_pHist[i], m_fAlpha, 0.0);
for (int l = 0; l < nbl; ++l)
{
ptrs = (unsigned char *)(pSource->imageData + pSource->widthStep * l);
ptrm = (unsigned char *)(pMotionMask->imageData + pMotionMask->widthStep * l);
ptrb = (unsigned char *)(pBackground->imageData + pBackground->widthStep * l);
for (int c = 0; c < nbc; ++c, ptrs++, ptrb++, ptrm++)
{
// recherche le bin à augmenter
int i = *ptrs / v;
if (i < 0 || i >= m_nBinCount)
i = 0;
ptr1 = (float *)(m_pHist[i]->imageData + m_pHist[i]->widthStep * l);
ptr1 += c;
*ptr1 += (float)(1.0 - m_fAlpha);
*ptrm = (*ptr1 < m_fThreshold) ? 255 : 0;
// recherche le bin du fond actuel
i = *ptrb / v;
if (i < 0 || i >= m_nBinCount)
i = 0;
ptr2 = (float *)(m_pHist[i]->imageData + m_pHist[i]->widthStep * l);
ptr2 += c;
if (*ptr2 < *ptr1)
*ptrb = *ptrs;
}
}
if (m_nCount < 5)
cvSetZero(pMotionMask);
}
return nErr;
}
IplImage *TBackgroundVuMeter::CreateTestImg()
{
IplImage *pImage = NULL;
if (m_nBinCount > 0)
pImage = cvCreateImage(cvSize(m_nBinCount, 100), IPL_DEPTH_8U, 3);
if (pImage != NULL)
cvSetZero(pImage);
return pImage;
}
int TBackgroundVuMeter::UpdateTest(IplImage *pSource, IplImage *pBackground, IplImage *pTest, int nX, int nY, int nInd)
{
int nErr = 0;
float *ptrf;
if (pTest == NULL || !isInitOk(pSource, pBackground, pSource))
nErr = 1;
if (!nErr)
{
int nbl = pTest->height;
int nbc = pTest->width;
if (nbl != 100 || nbc != m_nBinCount)
nErr = 1;
if (nX < 0 || nX >= pSource->width || nY < 0 || nY >= pSource->height)
nErr = 1;
}
if (!nErr)
{
cvSetZero(pTest);
for (int i = 0; i < m_nBinCount; ++i)
{
ptrf = (float *)(m_pHist[i]->imageData + m_pHist[i]->widthStep * nY);
ptrf += nX;
if (*ptrf >= 0 || *ptrf <= 1.0) {
cvLine(pTest, cvPoint(i, 100), cvPoint(i, (int)(100.0 * (1.0 - *ptrf))), cvScalar(0, 255, 0));
}
}
cvLine(pTest, cvPoint(0, (int)(100.0 * (1.0 - m_fThreshold))), cvPoint(m_nBinCount, (int)(100.0 * (1.0 - m_fThreshold))), cvScalar(0, 128, 0));
}
return nErr;
}
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gtk/edit_keyword_controller.h"
#include <gtk/gtk.h>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/string_util.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/common/gtk_util.h"
#include "googleurl/src/gurl.h"
#include "grit/app_resources.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
namespace {
std::string GetDisplayURL(const TemplateURL& turl) {
return turl.url() ? WideToUTF8(turl.url()->DisplayURL()) : std::string();
}
GtkWidget* CreateEntryImageHBox(GtkWidget* entry, GtkWidget* image) {
GtkWidget* hbox = gtk_hbox_new(FALSE, gtk_util::kControlSpacing);
gtk_box_pack_start(GTK_BOX(hbox), entry, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(hbox), image, FALSE, FALSE, 0);
return hbox;
}
// Forces text to lowercase when connected to an editable's "insert-text"
// signal. (Like views Textfield::STYLE_LOWERCASE.)
void LowercaseInsertTextHandler(GtkEditable *editable, const gchar *text,
gint length, gint *position, gpointer data) {
string16 original_text = UTF8ToUTF16(text);
string16 lower_text = l10n_util::ToLower(original_text);
if (lower_text != original_text) {
std::string result = UTF16ToUTF8(lower_text);
// Prevent ourselves getting called recursively about our own edit.
g_signal_handlers_block_by_func(G_OBJECT(editable),
reinterpret_cast<gpointer>(LowercaseInsertTextHandler), data);
gtk_editable_insert_text(editable, result.c_str(), result.size(), position);
g_signal_handlers_unblock_by_func(G_OBJECT(editable),
reinterpret_cast<gpointer>(LowercaseInsertTextHandler), data);
// We've inserted our modified version, stop the defalut handler from
// inserting the original.
g_signal_stop_emission_by_name(G_OBJECT(editable), "insert_text");
}
}
} // namespace
// static
void EditKeywordControllerBase::Create(gfx::NativeWindow parent_window,
const TemplateURL* template_url,
Delegate* delegate,
Profile* profile) {
new EditKeywordController(parent_window, template_url, delegate, profile);
}
EditKeywordController::EditKeywordController(
GtkWindow* parent_window,
const TemplateURL* template_url,
Delegate* delegate,
Profile* profile)
: EditKeywordControllerBase(template_url, delegate, profile) {
Init(parent_window);
}
void EditKeywordController::Init(GtkWindow* parent_window) {
dialog_ = gtk_dialog_new_with_buttons(
l10n_util::GetStringUTF8(
template_url() ?
IDS_SEARCH_ENGINES_EDITOR_EDIT_WINDOW_TITLE :
IDS_SEARCH_ENGINES_EDITOR_NEW_WINDOW_TITLE).c_str(),
parent_window,
static_cast<GtkDialogFlags>(GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR),
GTK_STOCK_CANCEL,
GTK_RESPONSE_CANCEL,
NULL);
ok_button_ = gtk_dialog_add_button(GTK_DIALOG(dialog_),
GTK_STOCK_OK, GTK_RESPONSE_OK);
gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_OK);
// The dialog layout hierarchy looks like this:
//
// \ GtkVBox |dialog_->vbox|
// +-\ GtkTable |controls|
// | +-\ row 0
// | | +- GtkLabel
// | | +-\ GtkHBox
// | | +- GtkEntry |title_entry_|
// | | +- GtkImage |title_image_|
// | +-\ row 1
// | | +- GtkLabel
// | | +-\ GtkHBox
// | | +- GtkEntry |keyword_entry_|
// | | +- GtkImage |keyword_image_|
// | +-\ row 2
// | +- GtkLabel
// | +-\ GtkHBox
// | +- GtkEntry |url_entry_|
// | +- GtkImage |url_image_|
// +- GtkLabel |description_label|
title_entry_ = gtk_entry_new();
gtk_entry_set_activates_default(GTK_ENTRY(title_entry_), TRUE);
g_signal_connect(G_OBJECT(title_entry_), "changed",
G_CALLBACK(OnEntryChanged), this);
keyword_entry_ = gtk_entry_new();
gtk_entry_set_activates_default(GTK_ENTRY(keyword_entry_), TRUE);
g_signal_connect(G_OBJECT(keyword_entry_), "changed",
G_CALLBACK(OnEntryChanged), this);
g_signal_connect(G_OBJECT(keyword_entry_), "insert-text",
G_CALLBACK(LowercaseInsertTextHandler), NULL);
url_entry_ = gtk_entry_new();
gtk_entry_set_activates_default(GTK_ENTRY(url_entry_), TRUE);
g_signal_connect(G_OBJECT(url_entry_), "changed",
G_CALLBACK(OnEntryChanged), this);
title_image_ = gtk_image_new_from_pixbuf(NULL);
keyword_image_ = gtk_image_new_from_pixbuf(NULL);
url_image_ = gtk_image_new_from_pixbuf(NULL);
if (template_url()) {
gtk_entry_set_text(GTK_ENTRY(title_entry_),
WideToUTF8(template_url()->short_name()).c_str());
gtk_entry_set_text(GTK_ENTRY(keyword_entry_),
WideToUTF8(template_url()->keyword()).c_str());
gtk_entry_set_text(GTK_ENTRY(url_entry_),
GetDisplayURL(*template_url()).c_str());
// We don't allow users to edit prepopulated URLs.
gtk_editable_set_editable(GTK_EDITABLE(url_entry_),
template_url()->prepopulate_id() == 0);
}
GtkWidget* controls = gtk_util::CreateLabeledControlsGroup(
l10n_util::GetStringUTF8(
IDS_SEARCH_ENGINES_EDITOR_DESCRIPTION_LABEL).c_str(),
CreateEntryImageHBox(title_entry_, title_image_),
l10n_util::GetStringUTF8(IDS_SEARCH_ENGINES_EDITOR_KEYWORD_LABEL).c_str(),
CreateEntryImageHBox(keyword_entry_, keyword_image_),
l10n_util::GetStringUTF8(IDS_SEARCH_ENGINES_EDITOR_URL_LABEL).c_str(),
CreateEntryImageHBox(url_entry_, url_image_),
NULL);
gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog_)->vbox), controls,
FALSE, FALSE, 0);
// On RTL UIs (such as Arabic and Hebrew) the description text is not
// displayed correctly since it contains the substring "%s". This substring
// is not interpreted by the Unicode BiDi algorithm as an LTR string and
// therefore the end result is that the following right to left text is
// displayed: ".three two s% one" (where 'one', 'two', etc. are words in
// Hebrew).
//
// In order to fix this problem we transform the substring "%s" so that it
// is displayed correctly when rendered in an RTL context.
std::string description =
l10n_util::GetStringUTF8(IDS_SEARCH_ENGINES_EDITOR_URL_DESCRIPTION_LABEL);
if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) {
const std::string reversed_percent("s%");
std::wstring::size_type percent_index =
description.find("%s", static_cast<std::string::size_type>(0));
if (percent_index != std::string::npos)
description.replace(percent_index,
reversed_percent.length(),
reversed_percent);
}
GtkWidget* description_label = gtk_label_new(description.c_str());
gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog_)->vbox), description_label,
FALSE, FALSE, 0);
gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox),
gtk_util::kContentAreaSpacing);
gtk_widget_show_all(dialog_);
g_signal_connect(dialog_, "response", G_CALLBACK(OnResponse), this);
g_signal_connect(dialog_, "destroy", G_CALLBACK(OnWindowDestroy), this);
}
std::wstring EditKeywordController::GetURLInput() const {
return UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(url_entry_)));
}
std::wstring EditKeywordController::GetKeywordInput() const {
return UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(keyword_entry_)));
}
std::wstring EditKeywordController::GetTitleInput() const {
return UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(title_entry_)));
}
void EditKeywordController::EnableControls() {
gtk_widget_set_sensitive(ok_button_,
IsKeywordValid() && IsTitleValid() && IsURLValid());
UpdateImage(keyword_image_, IsKeywordValid(),
IDS_SEARCH_ENGINES_INVALID_KEYWORD_TT);
UpdateImage(url_image_, IsURLValid(), IDS_SEARCH_ENGINES_INVALID_URL_TT);
UpdateImage(title_image_, IsTitleValid(),
IDS_SEARCH_ENGINES_INVALID_TITLE_TT);
}
void EditKeywordController::UpdateImage(GtkWidget* image,
bool is_valid,
int invalid_message_id) {
if (is_valid) {
gtk_widget_set_has_tooltip(image, FALSE);
gtk_image_set_from_pixbuf(GTK_IMAGE(image),
ResourceBundle::GetSharedInstance().GetPixbufNamed(
IDR_INPUT_GOOD));
} else {
gtk_widget_set_tooltip_text(
image, l10n_util::GetStringUTF8(invalid_message_id).c_str());
gtk_image_set_from_pixbuf(GTK_IMAGE(image),
ResourceBundle::GetSharedInstance().GetPixbufNamed(
IDR_INPUT_ALERT));
}
}
// static
void EditKeywordController::OnEntryChanged(
GtkEditable* editable, EditKeywordController* window) {
window->EnableControls();
}
// static
void EditKeywordController::OnResponse(GtkDialog* dialog, int response_id,
EditKeywordController* window) {
if (response_id == GTK_RESPONSE_OK) {
window->AcceptAddOrEdit();
} else {
window->CleanUpCancelledAdd();
}
gtk_widget_destroy(window->dialog_);
}
// static
void EditKeywordController::OnWindowDestroy(
GtkWidget* widget, EditKeywordController* window) {
MessageLoop::current()->DeleteSoon(FROM_HERE, window);
}
<commit_msg>gtk EditKeywordController properly enables controls when created without a TemplateURL (when creating with one, the entry changed signal would do it.)<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gtk/edit_keyword_controller.h"
#include <gtk/gtk.h>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/string_util.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/common/gtk_util.h"
#include "googleurl/src/gurl.h"
#include "grit/app_resources.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
namespace {
std::string GetDisplayURL(const TemplateURL& turl) {
return turl.url() ? WideToUTF8(turl.url()->DisplayURL()) : std::string();
}
GtkWidget* CreateEntryImageHBox(GtkWidget* entry, GtkWidget* image) {
GtkWidget* hbox = gtk_hbox_new(FALSE, gtk_util::kControlSpacing);
gtk_box_pack_start(GTK_BOX(hbox), entry, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(hbox), image, FALSE, FALSE, 0);
return hbox;
}
// Forces text to lowercase when connected to an editable's "insert-text"
// signal. (Like views Textfield::STYLE_LOWERCASE.)
void LowercaseInsertTextHandler(GtkEditable *editable, const gchar *text,
gint length, gint *position, gpointer data) {
string16 original_text = UTF8ToUTF16(text);
string16 lower_text = l10n_util::ToLower(original_text);
if (lower_text != original_text) {
std::string result = UTF16ToUTF8(lower_text);
// Prevent ourselves getting called recursively about our own edit.
g_signal_handlers_block_by_func(G_OBJECT(editable),
reinterpret_cast<gpointer>(LowercaseInsertTextHandler), data);
gtk_editable_insert_text(editable, result.c_str(), result.size(), position);
g_signal_handlers_unblock_by_func(G_OBJECT(editable),
reinterpret_cast<gpointer>(LowercaseInsertTextHandler), data);
// We've inserted our modified version, stop the defalut handler from
// inserting the original.
g_signal_stop_emission_by_name(G_OBJECT(editable), "insert_text");
}
}
} // namespace
// static
void EditKeywordControllerBase::Create(gfx::NativeWindow parent_window,
const TemplateURL* template_url,
Delegate* delegate,
Profile* profile) {
new EditKeywordController(parent_window, template_url, delegate, profile);
}
EditKeywordController::EditKeywordController(
GtkWindow* parent_window,
const TemplateURL* template_url,
Delegate* delegate,
Profile* profile)
: EditKeywordControllerBase(template_url, delegate, profile) {
Init(parent_window);
}
void EditKeywordController::Init(GtkWindow* parent_window) {
dialog_ = gtk_dialog_new_with_buttons(
l10n_util::GetStringUTF8(
template_url() ?
IDS_SEARCH_ENGINES_EDITOR_EDIT_WINDOW_TITLE :
IDS_SEARCH_ENGINES_EDITOR_NEW_WINDOW_TITLE).c_str(),
parent_window,
static_cast<GtkDialogFlags>(GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR),
GTK_STOCK_CANCEL,
GTK_RESPONSE_CANCEL,
NULL);
ok_button_ = gtk_dialog_add_button(GTK_DIALOG(dialog_),
GTK_STOCK_OK, GTK_RESPONSE_OK);
gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_OK);
// The dialog layout hierarchy looks like this:
//
// \ GtkVBox |dialog_->vbox|
// +-\ GtkTable |controls|
// | +-\ row 0
// | | +- GtkLabel
// | | +-\ GtkHBox
// | | +- GtkEntry |title_entry_|
// | | +- GtkImage |title_image_|
// | +-\ row 1
// | | +- GtkLabel
// | | +-\ GtkHBox
// | | +- GtkEntry |keyword_entry_|
// | | +- GtkImage |keyword_image_|
// | +-\ row 2
// | +- GtkLabel
// | +-\ GtkHBox
// | +- GtkEntry |url_entry_|
// | +- GtkImage |url_image_|
// +- GtkLabel |description_label|
title_entry_ = gtk_entry_new();
gtk_entry_set_activates_default(GTK_ENTRY(title_entry_), TRUE);
g_signal_connect(G_OBJECT(title_entry_), "changed",
G_CALLBACK(OnEntryChanged), this);
keyword_entry_ = gtk_entry_new();
gtk_entry_set_activates_default(GTK_ENTRY(keyword_entry_), TRUE);
g_signal_connect(G_OBJECT(keyword_entry_), "changed",
G_CALLBACK(OnEntryChanged), this);
g_signal_connect(G_OBJECT(keyword_entry_), "insert-text",
G_CALLBACK(LowercaseInsertTextHandler), NULL);
url_entry_ = gtk_entry_new();
gtk_entry_set_activates_default(GTK_ENTRY(url_entry_), TRUE);
g_signal_connect(G_OBJECT(url_entry_), "changed",
G_CALLBACK(OnEntryChanged), this);
title_image_ = gtk_image_new_from_pixbuf(NULL);
keyword_image_ = gtk_image_new_from_pixbuf(NULL);
url_image_ = gtk_image_new_from_pixbuf(NULL);
if (template_url()) {
gtk_entry_set_text(GTK_ENTRY(title_entry_),
WideToUTF8(template_url()->short_name()).c_str());
gtk_entry_set_text(GTK_ENTRY(keyword_entry_),
WideToUTF8(template_url()->keyword()).c_str());
gtk_entry_set_text(GTK_ENTRY(url_entry_),
GetDisplayURL(*template_url()).c_str());
// We don't allow users to edit prepopulated URLs.
gtk_editable_set_editable(GTK_EDITABLE(url_entry_),
template_url()->prepopulate_id() == 0);
}
GtkWidget* controls = gtk_util::CreateLabeledControlsGroup(
l10n_util::GetStringUTF8(
IDS_SEARCH_ENGINES_EDITOR_DESCRIPTION_LABEL).c_str(),
CreateEntryImageHBox(title_entry_, title_image_),
l10n_util::GetStringUTF8(IDS_SEARCH_ENGINES_EDITOR_KEYWORD_LABEL).c_str(),
CreateEntryImageHBox(keyword_entry_, keyword_image_),
l10n_util::GetStringUTF8(IDS_SEARCH_ENGINES_EDITOR_URL_LABEL).c_str(),
CreateEntryImageHBox(url_entry_, url_image_),
NULL);
gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog_)->vbox), controls,
FALSE, FALSE, 0);
// On RTL UIs (such as Arabic and Hebrew) the description text is not
// displayed correctly since it contains the substring "%s". This substring
// is not interpreted by the Unicode BiDi algorithm as an LTR string and
// therefore the end result is that the following right to left text is
// displayed: ".three two s% one" (where 'one', 'two', etc. are words in
// Hebrew).
//
// In order to fix this problem we transform the substring "%s" so that it
// is displayed correctly when rendered in an RTL context.
std::string description =
l10n_util::GetStringUTF8(IDS_SEARCH_ENGINES_EDITOR_URL_DESCRIPTION_LABEL);
if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) {
const std::string reversed_percent("s%");
std::wstring::size_type percent_index =
description.find("%s", static_cast<std::string::size_type>(0));
if (percent_index != std::string::npos)
description.replace(percent_index,
reversed_percent.length(),
reversed_percent);
}
GtkWidget* description_label = gtk_label_new(description.c_str());
gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog_)->vbox), description_label,
FALSE, FALSE, 0);
gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox),
gtk_util::kContentAreaSpacing);
EnableControls();
gtk_widget_show_all(dialog_);
g_signal_connect(dialog_, "response", G_CALLBACK(OnResponse), this);
g_signal_connect(dialog_, "destroy", G_CALLBACK(OnWindowDestroy), this);
}
std::wstring EditKeywordController::GetURLInput() const {
return UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(url_entry_)));
}
std::wstring EditKeywordController::GetKeywordInput() const {
return UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(keyword_entry_)));
}
std::wstring EditKeywordController::GetTitleInput() const {
return UTF8ToWide(gtk_entry_get_text(GTK_ENTRY(title_entry_)));
}
void EditKeywordController::EnableControls() {
gtk_widget_set_sensitive(ok_button_,
IsKeywordValid() && IsTitleValid() && IsURLValid());
UpdateImage(keyword_image_, IsKeywordValid(),
IDS_SEARCH_ENGINES_INVALID_KEYWORD_TT);
UpdateImage(url_image_, IsURLValid(), IDS_SEARCH_ENGINES_INVALID_URL_TT);
UpdateImage(title_image_, IsTitleValid(),
IDS_SEARCH_ENGINES_INVALID_TITLE_TT);
}
void EditKeywordController::UpdateImage(GtkWidget* image,
bool is_valid,
int invalid_message_id) {
if (is_valid) {
gtk_widget_set_has_tooltip(image, FALSE);
gtk_image_set_from_pixbuf(GTK_IMAGE(image),
ResourceBundle::GetSharedInstance().GetPixbufNamed(
IDR_INPUT_GOOD));
} else {
gtk_widget_set_tooltip_text(
image, l10n_util::GetStringUTF8(invalid_message_id).c_str());
gtk_image_set_from_pixbuf(GTK_IMAGE(image),
ResourceBundle::GetSharedInstance().GetPixbufNamed(
IDR_INPUT_ALERT));
}
}
// static
void EditKeywordController::OnEntryChanged(
GtkEditable* editable, EditKeywordController* window) {
window->EnableControls();
}
// static
void EditKeywordController::OnResponse(GtkDialog* dialog, int response_id,
EditKeywordController* window) {
if (response_id == GTK_RESPONSE_OK) {
window->AcceptAddOrEdit();
} else {
window->CleanUpCancelledAdd();
}
gtk_widget_destroy(window->dialog_);
}
// static
void EditKeywordController::OnWindowDestroy(
GtkWidget* widget, EditKeywordController* window) {
MessageLoop::current()->DeleteSoon(FROM_HERE, window);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2018-2020 Morwenn
* SPDX-License-Identifier: MIT
*/
#include <type_traits>
#include <catch2/catch.hpp>
#include <tight_pair.h>
#include "archetypes.h"
TEST_CASE( "default noexcept" )
{
using NonThrowingDefault = NonThrowingTypes::DefaultOnly;
#ifdef __clang__
using ThrowingDefault = NonTrivialTypes::DefaultOnly;
// NOTE: the behaviour for these test cases depends on whether the compiler implements
// the resolution of P0003R5 which removes a noexcept special case with regard to
// constant expressions, which apparently was a serendipitous change so we can't
// rely on a guaranteed behaviour right now
static_assert(not std::is_nothrow_default_constructible_v<cruft::tight_pair<ThrowingDefault, ThrowingDefault>>);
static_assert(not std::is_nothrow_default_constructible_v<cruft::tight_pair<NonThrowingDefault, ThrowingDefault>>);
static_assert(not std::is_nothrow_default_constructible_v<cruft::tight_pair<ThrowingDefault, NonThrowingDefault>>);
#endif
static_assert(std::is_nothrow_default_constructible_v<cruft::tight_pair<NonThrowingDefault, NonThrowingDefault>>);
}
<commit_msg>Test libcxx/default.cpp with more compilers<commit_after>/*
* Copyright (c) 2018-2021 Morwenn
* SPDX-License-Identifier: MIT
*/
#include <type_traits>
#include <catch2/catch.hpp>
#include <tight_pair.h>
#include "archetypes.h"
TEST_CASE( "default noexcept" )
{
using NonThrowingDefault = NonThrowingTypes::DefaultOnly;
#if !defined(__GNUC__) || (defined(__GNUC__) && __GNUC__ >= 9)
using ThrowingDefault = NonTrivialTypes::DefaultOnly;
// NOTE: the behaviour for these test cases depends on whether the compiler implements
// the resolution of P0003R5 which removes a noexcept special case with regard to
// constant expressions, which apparently was a serendipitous change so compilers
// took some time to adapt.
static_assert(not std::is_nothrow_default_constructible_v<cruft::tight_pair<ThrowingDefault, ThrowingDefault>>);
static_assert(not std::is_nothrow_default_constructible_v<cruft::tight_pair<NonThrowingDefault, ThrowingDefault>>);
static_assert(not std::is_nothrow_default_constructible_v<cruft::tight_pair<ThrowingDefault, NonThrowingDefault>>);
#endif
static_assert(std::is_nothrow_default_constructible_v<cruft::tight_pair<NonThrowingDefault, NonThrowingDefault>>);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/browser_dialogs.h"
#include "content/public/browser/color_chooser.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/views/color_chooser/color_chooser_listener.h"
#include "ui/views/color_chooser/color_chooser_view.h"
#include "ui/views/widget/widget.h"
namespace {
class ColorChooserAura : public content::ColorChooser,
public views::ColorChooserListener {
public:
static ColorChooserAura* Open(content::WebContents* web_contents,
SkColor initial_color);
ColorChooserAura(content::WebContents* web_contents, SkColor initial_color);
private:
static ColorChooserAura* current_color_chooser_;
// content::ColorChooser overrides:
virtual void End() OVERRIDE;
virtual void SetSelectedColor(SkColor color) OVERRIDE;
// views::ColorChooserListener overrides:
virtual void OnColorChosen(SkColor color) OVERRIDE;
virtual void OnColorChooserDialogClosed() OVERRIDE;
void DidEndColorChooser();
// The actual view of the color chooser. No ownership because its parent
// view will take care of its lifetime.
views::ColorChooserView* view_;
// The widget for the color chooser. No ownership because it's released
// automatically when closed.
views::Widget* widget_;
// The web contents invoking the color chooser. No ownership because it will
// outlive this class.
content::WebContents* web_contents_;
DISALLOW_COPY_AND_ASSIGN(ColorChooserAura);
};
ColorChooserAura* ColorChooserAura::current_color_chooser_ = NULL;
ColorChooserAura::ColorChooserAura(content::WebContents* web_contents,
SkColor initial_color)
: web_contents_(web_contents) {
view_ = new views::ColorChooserView(this, initial_color);
widget_ = views::Widget::CreateWindowWithContext(
view_, web_contents->GetView()->GetNativeView());
widget_->SetAlwaysOnTop(true);
widget_->Show();
}
void ColorChooserAura::OnColorChosen(SkColor color) {
if (web_contents_)
web_contents_->DidChooseColorInColorChooser(color);
}
void ColorChooserAura::OnColorChooserDialogClosed() {
view_ = NULL;
widget_ = NULL;
DidEndColorChooser();
}
void ColorChooserAura::End() {
if (widget_ && widget_->IsVisible()) {
view_->set_listener(NULL);
widget_->Close();
view_ = NULL;
widget_ = NULL;
// DidEndColorChooser will invoke Browser::DidEndColorChooser, which deletes
// this. Take care of the call order.
DidEndColorChooser();
}
}
void ColorChooserAura::DidEndColorChooser() {
DCHECK(current_color_chooser_ == this);
current_color_chooser_ = NULL;
if (web_contents_)
web_contents_->DidEndColorChooser();
}
void ColorChooserAura::SetSelectedColor(SkColor color) {
if (view_)
view_->OnColorChanged(color);
}
// static
ColorChooserAura* ColorChooserAura::Open(
content::WebContents* web_contents, SkColor initial_color) {
if (current_color_chooser_)
current_color_chooser_->End();
DCHECK(current_color_chooser_);
current_color_chooser_ = new ColorChooserAura(web_contents, initial_color);
return current_color_chooser_;
}
} // namespace
namespace chrome {
content::ColorChooser* ShowColorChooser(content::WebContents* web_contents,
SkColor initial_color) {
return ColorChooserAura::Open(web_contents, initial_color);
}
} // namespace chrome
<commit_msg>Assertion failure for input type color on aura<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/browser_dialogs.h"
#include "content/public/browser/color_chooser.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/views/color_chooser/color_chooser_listener.h"
#include "ui/views/color_chooser/color_chooser_view.h"
#include "ui/views/widget/widget.h"
namespace {
class ColorChooserAura : public content::ColorChooser,
public views::ColorChooserListener {
public:
static ColorChooserAura* Open(content::WebContents* web_contents,
SkColor initial_color);
ColorChooserAura(content::WebContents* web_contents, SkColor initial_color);
private:
static ColorChooserAura* current_color_chooser_;
// content::ColorChooser overrides:
virtual void End() OVERRIDE;
virtual void SetSelectedColor(SkColor color) OVERRIDE;
// views::ColorChooserListener overrides:
virtual void OnColorChosen(SkColor color) OVERRIDE;
virtual void OnColorChooserDialogClosed() OVERRIDE;
void DidEndColorChooser();
// The actual view of the color chooser. No ownership because its parent
// view will take care of its lifetime.
views::ColorChooserView* view_;
// The widget for the color chooser. No ownership because it's released
// automatically when closed.
views::Widget* widget_;
// The web contents invoking the color chooser. No ownership because it will
// outlive this class.
content::WebContents* web_contents_;
DISALLOW_COPY_AND_ASSIGN(ColorChooserAura);
};
ColorChooserAura* ColorChooserAura::current_color_chooser_ = NULL;
ColorChooserAura::ColorChooserAura(content::WebContents* web_contents,
SkColor initial_color)
: web_contents_(web_contents) {
view_ = new views::ColorChooserView(this, initial_color);
widget_ = views::Widget::CreateWindowWithContext(
view_, web_contents->GetView()->GetNativeView());
widget_->SetAlwaysOnTop(true);
widget_->Show();
}
void ColorChooserAura::OnColorChosen(SkColor color) {
if (web_contents_)
web_contents_->DidChooseColorInColorChooser(color);
}
void ColorChooserAura::OnColorChooserDialogClosed() {
view_ = NULL;
widget_ = NULL;
DidEndColorChooser();
}
void ColorChooserAura::End() {
if (widget_ && widget_->IsVisible()) {
view_->set_listener(NULL);
widget_->Close();
view_ = NULL;
widget_ = NULL;
// DidEndColorChooser will invoke Browser::DidEndColorChooser, which deletes
// this. Take care of the call order.
DidEndColorChooser();
}
}
void ColorChooserAura::DidEndColorChooser() {
DCHECK(current_color_chooser_ == this);
current_color_chooser_ = NULL;
if (web_contents_)
web_contents_->DidEndColorChooser();
}
void ColorChooserAura::SetSelectedColor(SkColor color) {
if (view_)
view_->OnColorChanged(color);
}
// static
ColorChooserAura* ColorChooserAura::Open(
content::WebContents* web_contents, SkColor initial_color) {
if (current_color_chooser_)
current_color_chooser_->End();
DCHECK(!current_color_chooser_);
current_color_chooser_ = new ColorChooserAura(web_contents, initial_color);
return current_color_chooser_;
}
} // namespace
namespace chrome {
content::ColorChooser* ShowColorChooser(content::WebContents* web_contents,
SkColor initial_color) {
return ColorChooserAura::Open(web_contents, initial_color);
}
} // namespace chrome
<|endoftext|> |
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2007 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <memory.h>
#include <stdlib.h>
#include <string.h>
#include <osgSim/ShapeAttribute>
namespace osgSim
{
ShapeAttribute::ShapeAttribute() :
_type(UNKNOWN),
_integer(0)
{}
ShapeAttribute::ShapeAttribute(const char * name) :
_name(name),
_type(UNKNOWN),
_integer(0)
{}
ShapeAttribute::ShapeAttribute(const char * name, int value) :
_name(name),
_type(UNKNOWN),
_integer(value)
{}
ShapeAttribute::ShapeAttribute(const char * name, double value) :
_name(name),
_type(DOUBLE),
_double(value)
{}
ShapeAttribute::ShapeAttribute(const char * name, const char * value) :
_name(name),
_type(STRING),
_string(value ? strdup(value) : 0)
{
}
ShapeAttribute::ShapeAttribute(const ShapeAttribute & sa)
{
copy(sa);
}
ShapeAttribute::~ShapeAttribute()
{
free();
}
void ShapeAttribute::free()
{
if ((_type == STRING) && (_string))
{
::free(_string);
_string = 0;
}
}
void ShapeAttribute::setValue(const char * value)
{
free();
_type = STRING;
_string = (value ? strdup(value) : 0);
}
void ShapeAttribute::copy(const ShapeAttribute& sa)
{
_name = sa._name;
_type = sa._type;
switch (_type)
{
case INTEGER:
{
_integer = sa._integer;
break;
}
case STRING:
{
_string = sa._string ? strdup(sa._string) : 0;
break;
}
case DOUBLE:
{
_double = sa._double;
break;
}
case UNKNOWN:
default:
{
_integer = 0;
break;
}
}
}
ShapeAttribute& ShapeAttribute::operator = (const ShapeAttribute& sa)
{
if (&sa == this) return *this;
free();
copy(sa);
return *this;
}
int ShapeAttribute::compare(const osgSim::ShapeAttribute& sa) const
{
if (_name<sa._name) return -1;
if (sa._name<_name) return 1;
if (_type<sa._type) return -1;
if (sa._type<_type) return 1;
if (_name<sa._name) return -1;
if (sa._name<_name) return 1;
switch (_type)
{
case STRING:
{
if (_string<sa._string) return -1;
if (sa._string<_string) return 1;
}
case DOUBLE:
{
if (_double<sa._double) return -1;
if (sa._double<_double) return 1;
}
case INTEGER:
case UNKNOWN:
default:
{
if (_integer<sa._integer) return -1;
if (sa._integer<_integer) return 1;
}
}
return 0;
}
/** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/
int ShapeAttributeList::compare(const osgSim::ShapeAttributeList& sal) const
{
const_iterator salIt, thisIt, thisEnd = end();
int ret;
for (thisIt = begin(), salIt = sal.begin(); thisIt!= thisEnd; ++thisIt, ++salIt)
if ((ret = thisIt->compare(*salIt)) != 0) return ret;
return 0;
}
}
<commit_msg>From Martin Innus, fixed erroneous change of INTEGER to UNKNOWN, reverting back to INTEGER.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2007 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <memory.h>
#include <stdlib.h>
#include <string.h>
#include <osgSim/ShapeAttribute>
namespace osgSim
{
ShapeAttribute::ShapeAttribute() :
_type(UNKNOWN),
_integer(0)
{}
ShapeAttribute::ShapeAttribute(const char * name) :
_name(name),
_type(UNKNOWN),
_integer(0)
{}
ShapeAttribute::ShapeAttribute(const char * name, int value) :
_name(name),
_type(INTEGER),
_integer(value)
{}
ShapeAttribute::ShapeAttribute(const char * name, double value) :
_name(name),
_type(DOUBLE),
_double(value)
{}
ShapeAttribute::ShapeAttribute(const char * name, const char * value) :
_name(name),
_type(STRING),
_string(value ? strdup(value) : 0)
{
}
ShapeAttribute::ShapeAttribute(const ShapeAttribute & sa)
{
copy(sa);
}
ShapeAttribute::~ShapeAttribute()
{
free();
}
void ShapeAttribute::free()
{
if ((_type == STRING) && (_string))
{
::free(_string);
_string = 0;
}
}
void ShapeAttribute::setValue(const char * value)
{
free();
_type = STRING;
_string = (value ? strdup(value) : 0);
}
void ShapeAttribute::copy(const ShapeAttribute& sa)
{
_name = sa._name;
_type = sa._type;
switch (_type)
{
case INTEGER:
{
_integer = sa._integer;
break;
}
case STRING:
{
_string = sa._string ? strdup(sa._string) : 0;
break;
}
case DOUBLE:
{
_double = sa._double;
break;
}
case UNKNOWN:
default:
{
_integer = 0;
break;
}
}
}
ShapeAttribute& ShapeAttribute::operator = (const ShapeAttribute& sa)
{
if (&sa == this) return *this;
free();
copy(sa);
return *this;
}
int ShapeAttribute::compare(const osgSim::ShapeAttribute& sa) const
{
if (_name<sa._name) return -1;
if (sa._name<_name) return 1;
if (_type<sa._type) return -1;
if (sa._type<_type) return 1;
if (_name<sa._name) return -1;
if (sa._name<_name) return 1;
switch (_type)
{
case STRING:
{
if (_string<sa._string) return -1;
if (sa._string<_string) return 1;
}
case DOUBLE:
{
if (_double<sa._double) return -1;
if (sa._double<_double) return 1;
}
case INTEGER:
case UNKNOWN:
default:
{
if (_integer<sa._integer) return -1;
if (sa._integer<_integer) return 1;
}
}
return 0;
}
/** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/
int ShapeAttributeList::compare(const osgSim::ShapeAttributeList& sal) const
{
const_iterator salIt, thisIt, thisEnd = end();
int ret;
for (thisIt = begin(), salIt = sal.begin(); thisIt!= thisEnd; ++thisIt, ++salIt)
if ((ret = thisIt->compare(*salIt)) != 0) return ret;
return 0;
}
}
<|endoftext|> |
<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <Riostream.h>
#include "TSystem.h"
#include "TFile.h"
#include "TTree.h"
#include "TCanvas.h"
#include "TH1.h"
#include "TFile.h"
#include "TObject.h"
#include "TStyle.h"
#include "TROOT.h"
#include "AliAODEvent.h"
#include "AliAODHeader.h"
#include "AliAODEventInfo.h"
#include "AliAODVertex.h"
#include "AliAODTrack.h"
#include "AliAODCluster.h"
#include "AliAODDimuon.h"
#endif
void ReadSpecAOD(const char *fileName = "AliMuonAOD.root") {
gSystem->Load("libTree.so");
gSystem->Load("libVMC.so");
gSystem->Load("libPhysics.so");
gSystem->Load("STEERBase/libSTEERBase");
gSystem->Load("AOD/libAOD");
gROOT->LoadMacro("AliAODEventInfo.cxx++");
gROOT->LoadMacro("AliAODDimuon.cxx++");
gStyle->SetOptStat(111111);
gStyle->SetFrameFillColor(10);
gStyle->SetCanvasColor(10);
gStyle->SetOptStat(0);
TH1F *mass=new TH1F("mass","Invariant mass",100,0.,20.);
TH1F *rap=new TH1F("rap","Rapidity",100,-5.,0.);
TH1F *cost=new TH1F("cost","Cost_CS",100,-1.,1.);
TH1F *pt=new TH1F("pt","Pt",100,0.,50.);
TH1F *ptmuon=new TH1F("ptmuon","single muon Pt",100,0.,50.);
// open input file and get the TTree
TFile inFile(fileName, "READ");
TTree *aodTree = (TTree*)inFile.Get("AOD");
AliAODEvent *aod = (AliAODEvent*)aodTree->GetUserInfo()->FindObject("AliAODEvent");
TClonesArray *Dimuons;
TClonesArray *tracks;
TClonesArray *vertices;
AliAODEventInfo *MuonInfos;
aodTree->SetBranchAddress("Dimuons",&Dimuons);
aodTree->SetBranchAddress("tracks",&tracks);
aodTree->SetBranchAddress("vertices",&vertices);
aodTree->SetBranchAddress("MuonInfos",&MuonInfos);
// loop over events
Int_t nEvents = aodTree->GetEntries();
for (Int_t nEv = 0; nEv < nEvents; nEv++) {
cout << "Event: " << nEv+1 << "/" << nEvents << endl;
aodTree->GetEntry(nEv);
// loop over tracks
Int_t nTracks = tracks->GetEntries();
for (Int_t nTr = 0; nTr < nTracks; nTr++) {
AliAODTrack *tr = (AliAODTrack *)tracks->At(nTr);
ptmuon->Fill(tr->Pt());
// print track info
cout << nTr+1 << "/" << nTracks << ": track pt: " << tr->Pt();
if (tr->GetProdVertex()) {
cout << ", vertex z of this track: " << tr->GetProdVertex()->GetZ();
}
cout << endl;
}
// loop over dimuons
Int_t nDimuons = Dimuons->GetEntries();
cout << nDimuons << " dimuon(s)" << endl;
for(Int_t nDi=0; nDi < nDimuons; nDi++){
AliAODDimuon *di=(AliAODDimuon*)Dimuons->At(nDi);
if((MuonInfos->MUON_Unlike_HPt_L0())){
mass->Fill(di->M());
pt->Fill(di->Pt());
rap->Fill(di->Y());
cost->Fill(di->CostCS());
cout << "Dimuon: " << nDi << " q: " << di->Charge()
<< " m: " << di->M() << " Y: " << di->Y() << " Pt: " << di->Pt()<< " CostCS: " << di->CostCS() << endl ;
}
}
// // loop over vertices
// Int_t nVtxs = vertices->GetEntries();
// for (Int_t nVtx = 0; nVtx < nVtxs; nVtx++) {
//
// // print track info
// cout << nVtx+1 << "/" << nVtxs << ": vertex z position: " <<vertices->At(nVtx)->GetZ() << endl;
// }
}
inFile.Close();
TCanvas *c1=new TCanvas();
c1->Show();
c1->Divide(2,2);
c1->ForceUpdate();
c1->cd(1);
mass->DrawClone();
c1->cd(2);
rap->DrawClone();
c1->cd(3);
pt->DrawClone();
c1->cd(4);
cost->DrawClone();
TCanvas *c2 = new TCanvas();
c2->cd();
ptmuon->DrawClone();
return;
}
<commit_msg>Right definition of libraries to be loaded<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <Riostream.h>
#include "TSystem.h"
#include "TFile.h"
#include "TTree.h"
#include "TCanvas.h"
#include "TH1.h"
#include "TFile.h"
#include "TObject.h"
#include "TStyle.h"
#include "TROOT.h"
#include "AliAODEvent.h"
#include "AliAODHeader.h"
#include "AliAODEventInfo.h"
#include "AliAODVertex.h"
#include "AliAODTrack.h"
#include "AliAODCluster.h"
#include "AliAODDimuon.h"
#endif
void ReadSpecAOD(const char *fileName = "AliMuonAOD.root") {
gSystem->Load("libTree");
gSystem->Load("libGeom");
gSystem->Load("libSTEERBase");
gSystem->Load("libAOD");
gSystem->Load("libANALYSIS");
gSystem->Load("libPWG3base.so");
gStyle->SetOptStat(111111);
gStyle->SetFrameFillColor(10);
gStyle->SetCanvasColor(10);
gStyle->SetOptStat(0);
TH1F *mass=new TH1F("mass","Invariant mass",100,0.,20.);
TH1F *rap=new TH1F("rap","Rapidity",100,-5.,0.);
TH1F *cost=new TH1F("cost","Cost_CS",100,-1.,1.);
TH1F *pt=new TH1F("pt","Pt",100,0.,50.);
TH1F *ptmuon=new TH1F("ptmuon","single muon Pt",100,0.,50.);
// open input file and get the TTree
TFile inFile(fileName, "READ");
TTree *aodTree = (TTree*)inFile.Get("AOD");
AliAODEvent *aod = (AliAODEvent*)aodTree->GetUserInfo()->FindObject("AliAODEvent");
TClonesArray *Dimuons;
TClonesArray *tracks;
TClonesArray *vertices;
AliAODEventInfo *MuonInfos;
aodTree->SetBranchAddress("Dimuons",&Dimuons);
aodTree->SetBranchAddress("tracks",&tracks);
aodTree->SetBranchAddress("vertices",&vertices);
aodTree->SetBranchAddress("MuonInfos",&MuonInfos);
// loop over events
Int_t nEvents = aodTree->GetEntries();
for (Int_t nEv = 0; nEv < nEvents; nEv++) {
cout << "Event: " << nEv+1 << "/" << nEvents << endl;
aodTree->GetEntry(nEv);
// loop over tracks
Int_t nTracks = tracks->GetEntries();
for (Int_t nTr = 0; nTr < nTracks; nTr++) {
AliAODTrack *tr = (AliAODTrack *)tracks->At(nTr);
ptmuon->Fill(tr->Pt());
// print track info
cout << nTr+1 << "/" << nTracks << ": track pt: " << tr->Pt();
if (tr->GetProdVertex()) {
cout << ", vertex z of this track: " << tr->GetProdVertex()->GetZ();
}
cout << endl;
}
// loop over dimuons
Int_t nDimuons = Dimuons->GetEntries();
cout << nDimuons << " dimuon(s)" << endl;
for(Int_t nDi=0; nDi < nDimuons; nDi++){
AliAODDimuon *di=(AliAODDimuon*)Dimuons->At(nDi);
if((MuonInfos->MUON_Unlike_HPt_L0())){
mass->Fill(di->M());
pt->Fill(di->Pt());
rap->Fill(di->Y());
cost->Fill(di->CostCS());
cout << "Dimuon: " << nDi << " q: " << di->Charge()
<< " m: " << di->M() << " Y: " << di->Y() << " Pt: " << di->Pt()<< " CostCS: " << di->CostCS() << endl ;
}
}
// // loop over vertices
// Int_t nVtxs = vertices->GetEntries();
// for (Int_t nVtx = 0; nVtx < nVtxs; nVtx++) {
//
// // print track info
// cout << nVtx+1 << "/" << nVtxs << ": vertex z position: " <<vertices->At(nVtx)->GetZ() << endl;
// }
}
inFile.Close();
TCanvas *c1=new TCanvas();
c1->Show();
c1->Divide(2,2);
c1->ForceUpdate();
c1->cd(1);
mass->DrawClone();
c1->cd(2);
rap->DrawClone();
c1->cd(3);
pt->DrawClone();
c1->cd(4);
cost->DrawClone();
TCanvas *c2 = new TCanvas();
c2->cd();
ptmuon->DrawClone();
return;
}
<|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/renderer/user_script_idle_scheduler.h"
#include "base/message_loop.h"
#include "chrome/renderer/render_view.h"
namespace {
// The length of time to wait after the DOM is complete to try and run user
// scripts.
const int kUserScriptIdleTimeoutMs = 200;
}
UserScriptIdleScheduler::UserScriptIdleScheduler(RenderView* view,
WebKit::WebFrame* frame)
: ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)), view_(view),
frame_(frame), has_run_(false) {
}
void UserScriptIdleScheduler::DidFinishDocumentLoad() {
MessageLoop::current()->PostDelayedTask(FROM_HERE,
method_factory_.NewRunnableMethod(&UserScriptIdleScheduler::MaybeRun),
kUserScriptIdleTimeoutMs);
}
void UserScriptIdleScheduler::DidFinishLoad() {
// Ensure that running scripts does not keep any progress UI running.
MessageLoop::current()->PostTask(FROM_HERE,
method_factory_.NewRunnableMethod(&UserScriptIdleScheduler::MaybeRun));
}
void UserScriptIdleScheduler::Cancel() {
view_ = NULL;
frame_ = NULL;
}
void UserScriptIdleScheduler::MaybeRun() {
if (!view_)
return;
DCHECK(frame_);
view_->OnUserScriptIdleTriggered(frame_);
Cancel();
has_run_ = true;
}
<commit_msg>Fix a bug where content scripts would get run twice in some cases.<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/renderer/user_script_idle_scheduler.h"
#include "base/message_loop.h"
#include "chrome/renderer/render_view.h"
namespace {
// The length of time to wait after the DOM is complete to try and run user
// scripts.
const int kUserScriptIdleTimeoutMs = 200;
}
UserScriptIdleScheduler::UserScriptIdleScheduler(RenderView* view,
WebKit::WebFrame* frame)
: ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)), view_(view),
frame_(frame), has_run_(false) {
}
void UserScriptIdleScheduler::DidFinishDocumentLoad() {
MessageLoop::current()->PostDelayedTask(FROM_HERE,
method_factory_.NewRunnableMethod(&UserScriptIdleScheduler::MaybeRun),
kUserScriptIdleTimeoutMs);
}
void UserScriptIdleScheduler::DidFinishLoad() {
// Ensure that running scripts does not keep any progress UI running.
MessageLoop::current()->PostTask(FROM_HERE,
method_factory_.NewRunnableMethod(&UserScriptIdleScheduler::MaybeRun));
}
void UserScriptIdleScheduler::Cancel() {
view_ = NULL;
frame_ = NULL;
}
void UserScriptIdleScheduler::MaybeRun() {
if (!view_ || has_run())
return;
// Note: we must set this before calling OnUserScriptIdleTriggered, because
// that may result in a synchronous call back into MaybeRun if there is a
// pending task currently in the queue.
// http://code.google.com/p/chromium/issues/detail?id=29644
has_run_ = true;
DCHECK(frame_);
view_->OnUserScriptIdleTriggered(frame_);
Cancel();
}
<|endoftext|> |
<commit_before><commit_msg>Replace deprecated OUString::valueOf -> OUString::number<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: uunxapi.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2006-04-07 08:07:15 $
*
* 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 _OSL_UUNXAPI_H_
#include "uunxapi.h"
#endif
#ifndef __OSL_SYSTEM_H__
#include "system.h"
#endif
#ifndef _LIMITS_H
#include <limits.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
//###########################
inline rtl::OString OUStringToOString(const rtl_uString* s)
{
return rtl::OUStringToOString(
rtl::OUString(const_cast<rtl_uString*>(s)),
osl_getThreadTextEncoding());
}
//###########################
#ifdef MACOSX
/*
* Helper function for resolving Mac native alias files (not the same as unix alias files)
* and to return the resolved alias as rtl::OString
*/
inline rtl::OString macxp_resolveAliasAndConvert(const rtl_uString* s)
{
rtl::OString p = OUStringToOString(s);
sal_Char path[PATH_MAX];
if (p.getLength() < PATH_MAX)
{
strcpy(path, p.getStr());
macxp_resolveAlias(path, PATH_MAX);
p = rtl::OString(path);
}
return p;
}
#endif /* MACOSX */
//###########################
//access_u
int access_u(const rtl_uString* pustrPath, int mode)
{
#ifndef MACOSX // not MACOSX
return access(OUStringToOString(pustrPath).getStr(), mode);
#else
return access(macxp_resolveAliasAndConvert(pustrPath).getStr(), mode);
#endif
}
//#########################
//realpath_u
sal_Bool realpath_u(const rtl_uString* pustrFileName, rtl_uString** ppustrResolvedName)
{
#ifndef MACOSX // not MACOSX
rtl::OString fn = OUStringToOString(pustrFileName);
#else
rtl::OString fn = macxp_resolveAliasAndConvert(pustrFileName);
#endif
char rp[PATH_MAX];
bool bRet = realpath(fn.getStr(), rp);
if (bRet)
{
rtl::OUString resolved = rtl::OStringToOUString(
rtl::OString(static_cast<sal_Char*>(rp)),
osl_getThreadTextEncoding());
rtl_uString_assign(ppustrResolvedName, resolved.pData);
}
return bRet;
}
//#########################
//lstat_u
int lstat_u(const rtl_uString* pustrPath, struct stat* buf)
{
#ifndef MACOSX // not MACOSX
return lstat(OUStringToOString(pustrPath).getStr(), buf);
#else
return lstat(macxp_resolveAliasAndConvert(pustrPath).getStr(), buf);
#endif
}
//#########################
// @see mkdir
int mkdir_u(const rtl_uString* path, mode_t mode)
{
return mkdir(OUStringToOString(path).getStr(), mode);
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.62); FILE MERGED 2006/09/01 17:34:01 kaib 1.5.62.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: uunxapi.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-17 08:46:50 $
*
* 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_sal.hxx"
#ifndef _OSL_UUNXAPI_H_
#include "uunxapi.h"
#endif
#ifndef __OSL_SYSTEM_H__
#include "system.h"
#endif
#ifndef _LIMITS_H
#include <limits.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
//###########################
inline rtl::OString OUStringToOString(const rtl_uString* s)
{
return rtl::OUStringToOString(
rtl::OUString(const_cast<rtl_uString*>(s)),
osl_getThreadTextEncoding());
}
//###########################
#ifdef MACOSX
/*
* Helper function for resolving Mac native alias files (not the same as unix alias files)
* and to return the resolved alias as rtl::OString
*/
inline rtl::OString macxp_resolveAliasAndConvert(const rtl_uString* s)
{
rtl::OString p = OUStringToOString(s);
sal_Char path[PATH_MAX];
if (p.getLength() < PATH_MAX)
{
strcpy(path, p.getStr());
macxp_resolveAlias(path, PATH_MAX);
p = rtl::OString(path);
}
return p;
}
#endif /* MACOSX */
//###########################
//access_u
int access_u(const rtl_uString* pustrPath, int mode)
{
#ifndef MACOSX // not MACOSX
return access(OUStringToOString(pustrPath).getStr(), mode);
#else
return access(macxp_resolveAliasAndConvert(pustrPath).getStr(), mode);
#endif
}
//#########################
//realpath_u
sal_Bool realpath_u(const rtl_uString* pustrFileName, rtl_uString** ppustrResolvedName)
{
#ifndef MACOSX // not MACOSX
rtl::OString fn = OUStringToOString(pustrFileName);
#else
rtl::OString fn = macxp_resolveAliasAndConvert(pustrFileName);
#endif
char rp[PATH_MAX];
bool bRet = realpath(fn.getStr(), rp);
if (bRet)
{
rtl::OUString resolved = rtl::OStringToOUString(
rtl::OString(static_cast<sal_Char*>(rp)),
osl_getThreadTextEncoding());
rtl_uString_assign(ppustrResolvedName, resolved.pData);
}
return bRet;
}
//#########################
//lstat_u
int lstat_u(const rtl_uString* pustrPath, struct stat* buf)
{
#ifndef MACOSX // not MACOSX
return lstat(OUStringToOString(pustrPath).getStr(), buf);
#else
return lstat(macxp_resolveAliasAndConvert(pustrPath).getStr(), buf);
#endif
}
//#########################
// @see mkdir
int mkdir_u(const rtl_uString* path, mode_t mode)
{
return mkdir(OUStringToOString(path).getStr(), mode);
}
<|endoftext|> |
<commit_before>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2014 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/ui/gl/gl_context.h"
#include <mutex>
#include <string>
#include "xenia/base/assert.h"
#include "xenia/base/logging.h"
#include "xenia/base/math.h"
#include "xenia/profiling.h"
#include "xenia/ui/gl/gl_profiler_display.h"
#include "xenia/ui/gl/gl4_elemental_renderer.h"
#include "xenia/ui/window.h"
DEFINE_bool(thread_safe_gl, false,
"Only allow one GL context to be active at a time.");
DEFINE_bool(disable_gl_context_reset, false,
"Do not aggressively reset the GL context (helps with capture "
"programs such as OBS or FRAPS).");
DEFINE_bool(gl_debug, false, "Enable OpenGL debug validation layer.");
DEFINE_bool(gl_debug_output, false, "Dump ARB_debug_output to stderr.");
DEFINE_bool(gl_debug_output_synchronous, true,
"ARB_debug_output will synchronize to be thread safe.");
namespace xe {
namespace ui {
namespace gl {
static std::recursive_mutex global_gl_mutex_;
thread_local GLEWContext* tls_glew_context_ = nullptr;
thread_local WGLEWContext* tls_wglew_context_ = nullptr;
extern "C" GLEWContext* glewGetContext() { return tls_glew_context_; }
extern "C" WGLEWContext* wglewGetContext() { return tls_wglew_context_; }
std::unique_ptr<GLContext> GLContext::Create(Window* target_window) {
auto context = std::unique_ptr<GLContext>(new GLContext(target_window));
if (!context->Initialize(target_window)) {
return nullptr;
}
context->AssertExtensionsPresent();
return context;
}
GLContext::GLContext(Window* target_window) : GraphicsContext(target_window) {}
GLContext::GLContext(Window* target_window, HGLRC glrc)
: GraphicsContext(target_window), glrc_(glrc) {
dc_ = GetDC(HWND(target_window_->native_handle()));
}
GLContext::~GLContext() {
MakeCurrent();
blitter_.Shutdown();
ClearCurrent();
if (glrc_) {
wglDeleteContext(glrc_);
}
if (dc_) {
ReleaseDC(HWND(target_window_->native_handle()), dc_);
}
}
bool GLContext::Initialize(Window* target_window) {
target_window_ = target_window;
dc_ = GetDC(HWND(target_window_->native_handle()));
PIXELFORMATDESCRIPTOR pfd = {0};
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
int pixel_format = ChoosePixelFormat(dc_, &pfd);
if (!pixel_format) {
XELOGE("Unable to choose pixel format");
return false;
}
if (!SetPixelFormat(dc_, pixel_format, &pfd)) {
XELOGE("Unable to set pixel format");
return false;
}
HGLRC temp_context = wglCreateContext(dc_);
if (!temp_context) {
XELOGE("Unable to create temporary GL context");
return false;
}
wglMakeCurrent(dc_, temp_context);
tls_glew_context_ = &glew_context_;
tls_wglew_context_ = &wglew_context_;
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) {
XELOGE("Unable to initialize GLEW");
return false;
}
if (wglewInit() != GLEW_OK) {
XELOGE("Unable to initialize WGLEW");
return false;
}
if (!WGLEW_ARB_create_context) {
XELOGE("WGL_ARG_create_context not supported by GL ICD");
return false;
}
int context_flags = 0;
if (FLAGS_gl_debug) {
context_flags |= WGL_CONTEXT_DEBUG_BIT_ARB;
}
int attrib_list[] = {WGL_CONTEXT_MAJOR_VERSION_ARB, 4, //
WGL_CONTEXT_MINOR_VERSION_ARB, 5, //
WGL_CONTEXT_FLAGS_ARB, context_flags, //
0};
glrc_ = wglCreateContextAttribsARB(dc_, nullptr, attrib_list);
wglMakeCurrent(nullptr, nullptr);
wglDeleteContext(temp_context);
if (!glrc_) {
XELOGE("Unable to create real GL context");
return false;
}
if (!MakeCurrent()) {
XELOGE("Could not make real GL context current");
return false;
}
XELOGI("Successfully created OpenGL context:");
XELOGI(" GL_VENDOR: %s", glGetString(GL_VENDOR));
XELOGI(" GL_VERSION: %s", glGetString(GL_VERSION));
XELOGI(" GL_RENDERER: %s", glGetString(GL_RENDERER));
XELOGI(" GL_SHADING_LANGUAGE_VERSION: %s",
glGetString(GL_SHADING_LANGUAGE_VERSION));
while (glGetError()) {
// Clearing errors.
}
SetupDebugging();
if (!blitter_.Initialize()) {
XELOGE("Unable to initialize blitter");
ClearCurrent();
return false;
}
ClearCurrent();
return true;
}
std::unique_ptr<GraphicsContext> GLContext::CreateShared() {
assert_not_null(glrc_);
HGLRC new_glrc = nullptr;
{
GraphicsContextLock context_lock(this);
int context_flags = 0;
// int profile = WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
int profile = WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
if (FLAGS_gl_debug) {
context_flags |= WGL_CONTEXT_DEBUG_BIT_ARB;
}
int attrib_list[] = {WGL_CONTEXT_MAJOR_VERSION_ARB, 4, //
WGL_CONTEXT_MINOR_VERSION_ARB, 5, //
WGL_CONTEXT_FLAGS_ARB, context_flags, //
WGL_CONTEXT_PROFILE_MASK_ARB, profile, //
0};
new_glrc = wglCreateContextAttribsARB(dc_, glrc_, attrib_list);
if (!new_glrc) {
XELOGE("Could not create shared context");
return nullptr;
}
}
auto new_context =
std::unique_ptr<GLContext>(new GLContext(target_window_, new_glrc));
if (!new_context->MakeCurrent()) {
XELOGE("Could not make new GL context current");
return nullptr;
}
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) {
new_context->ClearCurrent();
XELOGE("Unable to initialize GLEW");
return nullptr;
}
if (wglewInit() != GLEW_OK) {
new_context->ClearCurrent();
XELOGE("Unable to initialize WGLEW");
return nullptr;
}
SetupDebugging();
if (!new_context->blitter_.Initialize()) {
XELOGE("Unable to initialize blitter");
return nullptr;
}
new_context->ClearCurrent();
return std::unique_ptr<GraphicsContext>(new_context.release());
}
void FatalGLError(std::string error) {
XEFATAL(
(error +
"\nEnsure you have the latest drivers for your GPU and that it supports "
"OpenGL 4.5. See http://xenia.jp/faq/ for more information.").c_str());
}
void GLContext::AssertExtensionsPresent() {
if (!MakeCurrent()) {
XEFATAL("Unable to make GL context current");
return;
}
// Check shader version at least 4.5 (matching GL 4.5).
auto glsl_version_raw =
reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION));
std::string glsl_version(glsl_version_raw);
if (glsl_version.find("4.50") != 0) {
XELOGW("GLSL version reported as %s; you may have a bad time!",
glsl_version_raw);
}
if (!GLEW_ARB_bindless_texture) {
FatalGLError("OpenGL extension ARB_bindless_texture is required.");
return;
}
// TODO(benvanik): figure out why this query fails.
// if (!GLEW_ARB_fragment_coord_conventions) {
// FatalGLError(
// "OpenGL extension ARB_fragment_coord_conventions is required.");
// return;
// }
}
void GLContext::DebugMessage(GLenum source, GLenum type, GLuint id,
GLenum severity, GLsizei length,
const GLchar* message) {
const char* source_name = nullptr;
switch (source) {
case GL_DEBUG_SOURCE_API_ARB:
source_name = "OpenGL";
break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB:
source_name = "Windows";
break;
case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB:
source_name = "Shader Compiler";
break;
case GL_DEBUG_SOURCE_THIRD_PARTY_ARB:
source_name = "Third Party";
break;
case GL_DEBUG_SOURCE_APPLICATION_ARB:
source_name = "Application";
break;
case GL_DEBUG_SOURCE_OTHER_ARB:
source_name = "Other";
break;
default:
source_name = "(unknown source)";
break;
}
const char* type_name = nullptr;
switch (type) {
case GL_DEBUG_TYPE_ERROR:
type_name = "error";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
type_name = "deprecated behavior";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
type_name = "undefined behavior";
break;
case GL_DEBUG_TYPE_PORTABILITY:
type_name = "portability";
break;
case GL_DEBUG_TYPE_PERFORMANCE:
type_name = "performance";
break;
case GL_DEBUG_TYPE_OTHER:
type_name = "message";
break;
case GL_DEBUG_TYPE_MARKER:
type_name = "marker";
break;
case GL_DEBUG_TYPE_PUSH_GROUP:
type_name = "push group";
break;
case GL_DEBUG_TYPE_POP_GROUP:
type_name = "pop group";
break;
default:
type_name = "(unknown type)";
break;
}
const char* severity_name = nullptr;
switch (severity) {
case GL_DEBUG_SEVERITY_HIGH_ARB:
severity_name = "high";
break;
case GL_DEBUG_SEVERITY_MEDIUM_ARB:
severity_name = "medium";
break;
case GL_DEBUG_SEVERITY_LOW_ARB:
severity_name = "low";
break;
case GL_DEBUG_SEVERITY_NOTIFICATION:
severity_name = "notification";
break;
default:
severity_name = "(unknown severity)";
break;
}
XELOGE("GL4 %s: %s(%s) %d: %s", source_name, type_name, severity_name, id,
message);
}
void GLAPIENTRY
GLContext::DebugMessageThunk(GLenum source, GLenum type, GLuint id,
GLenum severity, GLsizei length,
const GLchar* message, GLvoid* user_param) {
reinterpret_cast<GLContext*>(user_param)
->DebugMessage(source, type, id, severity, length, message);
}
void GLContext::SetupDebugging() {
if (!FLAGS_gl_debug || !FLAGS_gl_debug_output) {
return;
}
glEnable(GL_DEBUG_OUTPUT);
// Synchronous output hurts, but is required if we want to line up the logs.
if (FLAGS_gl_debug_output_synchronous) {
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
} else {
glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
}
// Enable everything by default.
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL,
GL_TRUE);
// Disable annoying messages.
GLuint disable_message_ids[] = {
0x00020004, // Usage warning: Generic vertex attribute array 0 uses a
// pointer with a small value (0x0000000000000000). Is this
// intended to be used as an offset into a buffer object?
};
glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_OTHER, GL_DONT_CARE,
GLsizei(xe::countof(disable_message_ids)),
disable_message_ids, GL_FALSE);
// Callback will be made from driver threads.
glDebugMessageCallback(reinterpret_cast<GLDEBUGPROC>(&DebugMessageThunk),
this);
}
std::unique_ptr<ProfilerDisplay> GLContext::CreateProfilerDisplay() {
return std::make_unique<GLProfilerDisplay>(target_window_);
}
std::unique_ptr<el::graphics::Renderer> GLContext::CreateElementalRenderer() {
return GL4ElementalRenderer::Create(this);
}
bool GLContext::MakeCurrent() {
SCOPE_profile_cpu_f("gpu");
if (FLAGS_thread_safe_gl) {
global_gl_mutex_.lock();
}
if (!wglMakeCurrent(dc_, glrc_)) {
if (FLAGS_thread_safe_gl) {
global_gl_mutex_.unlock();
}
XELOGE("Unable to make GL context current");
return false;
}
tls_glew_context_ = &glew_context_;
tls_wglew_context_ = &wglew_context_;
return true;
}
void GLContext::ClearCurrent() {
if (!FLAGS_disable_gl_context_reset) {
wglMakeCurrent(nullptr, nullptr);
}
tls_glew_context_ = nullptr;
tls_wglew_context_ = nullptr;
if (FLAGS_thread_safe_gl) {
global_gl_mutex_.unlock();
}
}
void GLContext::BeginSwap() {
SCOPE_profile_cpu_i("gpu", "xe::ui::gl::GLContext::BeginSwap");
float clear_color[] = {rand() / (float)RAND_MAX, 1.0f, 0, 1.0f};
glClearNamedFramebufferfv(0, GL_COLOR, 0, clear_color);
}
void GLContext::EndSwap() {
SCOPE_profile_cpu_i("gpu", "xe::ui::gl::GLContext::EndSwap");
SwapBuffers(dc());
}
} // namespace gl
} // namespace ui
} // namespace xe
<commit_msg>Double check ARB_bindless_texture. May help #342.<commit_after>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2014 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/ui/gl/gl_context.h"
#include <mutex>
#include <string>
#include "xenia/base/assert.h"
#include "xenia/base/logging.h"
#include "xenia/base/math.h"
#include "xenia/profiling.h"
#include "xenia/ui/gl/gl_profiler_display.h"
#include "xenia/ui/gl/gl4_elemental_renderer.h"
#include "xenia/ui/window.h"
DEFINE_bool(thread_safe_gl, false,
"Only allow one GL context to be active at a time.");
DEFINE_bool(disable_gl_context_reset, false,
"Do not aggressively reset the GL context (helps with capture "
"programs such as OBS or FRAPS).");
DEFINE_bool(gl_debug, false, "Enable OpenGL debug validation layer.");
DEFINE_bool(gl_debug_output, false, "Dump ARB_debug_output to stderr.");
DEFINE_bool(gl_debug_output_synchronous, true,
"ARB_debug_output will synchronize to be thread safe.");
namespace xe {
namespace ui {
namespace gl {
static std::recursive_mutex global_gl_mutex_;
thread_local GLEWContext* tls_glew_context_ = nullptr;
thread_local WGLEWContext* tls_wglew_context_ = nullptr;
extern "C" GLEWContext* glewGetContext() { return tls_glew_context_; }
extern "C" WGLEWContext* wglewGetContext() { return tls_wglew_context_; }
std::unique_ptr<GLContext> GLContext::Create(Window* target_window) {
auto context = std::unique_ptr<GLContext>(new GLContext(target_window));
if (!context->Initialize(target_window)) {
return nullptr;
}
context->AssertExtensionsPresent();
return context;
}
GLContext::GLContext(Window* target_window) : GraphicsContext(target_window) {}
GLContext::GLContext(Window* target_window, HGLRC glrc)
: GraphicsContext(target_window), glrc_(glrc) {
dc_ = GetDC(HWND(target_window_->native_handle()));
}
GLContext::~GLContext() {
MakeCurrent();
blitter_.Shutdown();
ClearCurrent();
if (glrc_) {
wglDeleteContext(glrc_);
}
if (dc_) {
ReleaseDC(HWND(target_window_->native_handle()), dc_);
}
}
bool GLContext::Initialize(Window* target_window) {
target_window_ = target_window;
dc_ = GetDC(HWND(target_window_->native_handle()));
PIXELFORMATDESCRIPTOR pfd = {0};
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
int pixel_format = ChoosePixelFormat(dc_, &pfd);
if (!pixel_format) {
XELOGE("Unable to choose pixel format");
return false;
}
if (!SetPixelFormat(dc_, pixel_format, &pfd)) {
XELOGE("Unable to set pixel format");
return false;
}
HGLRC temp_context = wglCreateContext(dc_);
if (!temp_context) {
XELOGE("Unable to create temporary GL context");
return false;
}
wglMakeCurrent(dc_, temp_context);
tls_glew_context_ = &glew_context_;
tls_wglew_context_ = &wglew_context_;
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) {
XELOGE("Unable to initialize GLEW");
return false;
}
if (wglewInit() != GLEW_OK) {
XELOGE("Unable to initialize WGLEW");
return false;
}
if (!WGLEW_ARB_create_context) {
XELOGE("WGL_ARG_create_context not supported by GL ICD");
return false;
}
int context_flags = 0;
if (FLAGS_gl_debug) {
context_flags |= WGL_CONTEXT_DEBUG_BIT_ARB;
}
int attrib_list[] = {WGL_CONTEXT_MAJOR_VERSION_ARB, 4, //
WGL_CONTEXT_MINOR_VERSION_ARB, 5, //
WGL_CONTEXT_FLAGS_ARB, context_flags, //
0};
glrc_ = wglCreateContextAttribsARB(dc_, nullptr, attrib_list);
wglMakeCurrent(nullptr, nullptr);
wglDeleteContext(temp_context);
if (!glrc_) {
XELOGE("Unable to create real GL context");
return false;
}
if (!MakeCurrent()) {
XELOGE("Could not make real GL context current");
return false;
}
XELOGI("Successfully created OpenGL context:");
XELOGI(" GL_VENDOR: %s", glGetString(GL_VENDOR));
XELOGI(" GL_VERSION: %s", glGetString(GL_VERSION));
XELOGI(" GL_RENDERER: %s", glGetString(GL_RENDERER));
XELOGI(" GL_SHADING_LANGUAGE_VERSION: %s",
glGetString(GL_SHADING_LANGUAGE_VERSION));
while (glGetError()) {
// Clearing errors.
}
SetupDebugging();
if (!blitter_.Initialize()) {
XELOGE("Unable to initialize blitter");
ClearCurrent();
return false;
}
ClearCurrent();
return true;
}
std::unique_ptr<GraphicsContext> GLContext::CreateShared() {
assert_not_null(glrc_);
HGLRC new_glrc = nullptr;
{
GraphicsContextLock context_lock(this);
int context_flags = 0;
// int profile = WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
int profile = WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
if (FLAGS_gl_debug) {
context_flags |= WGL_CONTEXT_DEBUG_BIT_ARB;
}
int attrib_list[] = {WGL_CONTEXT_MAJOR_VERSION_ARB, 4, //
WGL_CONTEXT_MINOR_VERSION_ARB, 5, //
WGL_CONTEXT_FLAGS_ARB, context_flags, //
WGL_CONTEXT_PROFILE_MASK_ARB, profile, //
0};
new_glrc = wglCreateContextAttribsARB(dc_, glrc_, attrib_list);
if (!new_glrc) {
XELOGE("Could not create shared context");
return nullptr;
}
}
auto new_context =
std::unique_ptr<GLContext>(new GLContext(target_window_, new_glrc));
if (!new_context->MakeCurrent()) {
XELOGE("Could not make new GL context current");
return nullptr;
}
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) {
new_context->ClearCurrent();
XELOGE("Unable to initialize GLEW");
return nullptr;
}
if (wglewInit() != GLEW_OK) {
new_context->ClearCurrent();
XELOGE("Unable to initialize WGLEW");
return nullptr;
}
SetupDebugging();
if (!new_context->blitter_.Initialize()) {
XELOGE("Unable to initialize blitter");
return nullptr;
}
new_context->ClearCurrent();
return std::unique_ptr<GraphicsContext>(new_context.release());
}
void FatalGLError(std::string error) {
XEFATAL(
(error +
"\nEnsure you have the latest drivers for your GPU and that it supports "
"OpenGL 4.5. See http://xenia.jp/faq/ for more information.").c_str());
}
void GLContext::AssertExtensionsPresent() {
if (!MakeCurrent()) {
XEFATAL("Unable to make GL context current");
return;
}
// Check shader version at least 4.5 (matching GL 4.5).
auto glsl_version_raw =
reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION));
std::string glsl_version(glsl_version_raw);
if (glsl_version.find("4.50") != 0) {
XELOGW("GLSL version reported as %s; you may have a bad time!",
glsl_version_raw);
}
if (!GLEW_ARB_bindless_texture || !glMakeTextureHandleResidentARB) {
FatalGLError("OpenGL extension ARB_bindless_texture is required.");
return;
}
// TODO(benvanik): figure out why this query fails.
// if (!GLEW_ARB_fragment_coord_conventions) {
// FatalGLError(
// "OpenGL extension ARB_fragment_coord_conventions is required.");
// return;
// }
}
void GLContext::DebugMessage(GLenum source, GLenum type, GLuint id,
GLenum severity, GLsizei length,
const GLchar* message) {
const char* source_name = nullptr;
switch (source) {
case GL_DEBUG_SOURCE_API_ARB:
source_name = "OpenGL";
break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB:
source_name = "Windows";
break;
case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB:
source_name = "Shader Compiler";
break;
case GL_DEBUG_SOURCE_THIRD_PARTY_ARB:
source_name = "Third Party";
break;
case GL_DEBUG_SOURCE_APPLICATION_ARB:
source_name = "Application";
break;
case GL_DEBUG_SOURCE_OTHER_ARB:
source_name = "Other";
break;
default:
source_name = "(unknown source)";
break;
}
const char* type_name = nullptr;
switch (type) {
case GL_DEBUG_TYPE_ERROR:
type_name = "error";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
type_name = "deprecated behavior";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
type_name = "undefined behavior";
break;
case GL_DEBUG_TYPE_PORTABILITY:
type_name = "portability";
break;
case GL_DEBUG_TYPE_PERFORMANCE:
type_name = "performance";
break;
case GL_DEBUG_TYPE_OTHER:
type_name = "message";
break;
case GL_DEBUG_TYPE_MARKER:
type_name = "marker";
break;
case GL_DEBUG_TYPE_PUSH_GROUP:
type_name = "push group";
break;
case GL_DEBUG_TYPE_POP_GROUP:
type_name = "pop group";
break;
default:
type_name = "(unknown type)";
break;
}
const char* severity_name = nullptr;
switch (severity) {
case GL_DEBUG_SEVERITY_HIGH_ARB:
severity_name = "high";
break;
case GL_DEBUG_SEVERITY_MEDIUM_ARB:
severity_name = "medium";
break;
case GL_DEBUG_SEVERITY_LOW_ARB:
severity_name = "low";
break;
case GL_DEBUG_SEVERITY_NOTIFICATION:
severity_name = "notification";
break;
default:
severity_name = "(unknown severity)";
break;
}
XELOGE("GL4 %s: %s(%s) %d: %s", source_name, type_name, severity_name, id,
message);
}
void GLAPIENTRY
GLContext::DebugMessageThunk(GLenum source, GLenum type, GLuint id,
GLenum severity, GLsizei length,
const GLchar* message, GLvoid* user_param) {
reinterpret_cast<GLContext*>(user_param)
->DebugMessage(source, type, id, severity, length, message);
}
void GLContext::SetupDebugging() {
if (!FLAGS_gl_debug || !FLAGS_gl_debug_output) {
return;
}
glEnable(GL_DEBUG_OUTPUT);
// Synchronous output hurts, but is required if we want to line up the logs.
if (FLAGS_gl_debug_output_synchronous) {
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
} else {
glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
}
// Enable everything by default.
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL,
GL_TRUE);
// Disable annoying messages.
GLuint disable_message_ids[] = {
0x00020004, // Usage warning: Generic vertex attribute array 0 uses a
// pointer with a small value (0x0000000000000000). Is this
// intended to be used as an offset into a buffer object?
};
glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_OTHER, GL_DONT_CARE,
GLsizei(xe::countof(disable_message_ids)),
disable_message_ids, GL_FALSE);
// Callback will be made from driver threads.
glDebugMessageCallback(reinterpret_cast<GLDEBUGPROC>(&DebugMessageThunk),
this);
}
std::unique_ptr<ProfilerDisplay> GLContext::CreateProfilerDisplay() {
return std::make_unique<GLProfilerDisplay>(target_window_);
}
std::unique_ptr<el::graphics::Renderer> GLContext::CreateElementalRenderer() {
return GL4ElementalRenderer::Create(this);
}
bool GLContext::MakeCurrent() {
SCOPE_profile_cpu_f("gpu");
if (FLAGS_thread_safe_gl) {
global_gl_mutex_.lock();
}
if (!wglMakeCurrent(dc_, glrc_)) {
if (FLAGS_thread_safe_gl) {
global_gl_mutex_.unlock();
}
XELOGE("Unable to make GL context current");
return false;
}
tls_glew_context_ = &glew_context_;
tls_wglew_context_ = &wglew_context_;
return true;
}
void GLContext::ClearCurrent() {
if (!FLAGS_disable_gl_context_reset) {
wglMakeCurrent(nullptr, nullptr);
}
tls_glew_context_ = nullptr;
tls_wglew_context_ = nullptr;
if (FLAGS_thread_safe_gl) {
global_gl_mutex_.unlock();
}
}
void GLContext::BeginSwap() {
SCOPE_profile_cpu_i("gpu", "xe::ui::gl::GLContext::BeginSwap");
float clear_color[] = {rand() / (float)RAND_MAX, 1.0f, 0, 1.0f};
glClearNamedFramebufferfv(0, GL_COLOR, 0, clear_color);
}
void GLContext::EndSwap() {
SCOPE_profile_cpu_i("gpu", "xe::ui::gl::GLContext::EndSwap");
SwapBuffers(dc());
}
} // namespace gl
} // namespace ui
} // namespace xe
<|endoftext|> |
<commit_before>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2014 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/ui/gl/gl_context.h"
#include <mutex>
#include <string>
#include "xenia/base/assert.h"
#include "xenia/base/logging.h"
#include "xenia/base/math.h"
#include "xenia/profiling.h"
#include "xenia/ui/gl/gl_profiler_display.h"
#include "xenia/ui/gl/gl4_elemental_renderer.h"
#include "xenia/ui/window.h"
// TODO(benvanik): move win32 code to _win?
#include "xenia/base/platform_win.h"
#include "third_party/GL/wglew.h"
DEFINE_bool(thread_safe_gl, false,
"Only allow one GL context to be active at a time.");
DEFINE_bool(disable_gl_context_reset, false,
"Do not aggressively reset the GL context (helps with capture "
"programs such as OBS or FRAPS).");
DEFINE_bool(gl_debug, false, "Enable OpenGL debug validation layer.");
DEFINE_bool(gl_debug_output, false, "Dump ARB_debug_output to stderr.");
DEFINE_bool(gl_debug_output_synchronous, true,
"ARB_debug_output will synchronize to be thread safe.");
namespace xe {
namespace ui {
namespace gl {
static std::recursive_mutex global_gl_mutex_;
thread_local GLEWContext* tls_glew_context_ = nullptr;
thread_local WGLEWContext* tls_wglew_context_ = nullptr;
extern "C" GLEWContext* glewGetContext() { return tls_glew_context_; }
extern "C" WGLEWContext* wglewGetContext() { return tls_wglew_context_; }
std::unique_ptr<GLContext> GLContext::Create(Window* target_window) {
auto context = std::unique_ptr<GLContext>(new GLContext(target_window));
if (!context->Initialize(target_window)) {
return nullptr;
}
context->AssertExtensionsPresent();
return context;
}
GLContext::GLContext(Window* target_window) : GraphicsContext(target_window) {
glew_context_.reset(new GLEWContext());
wglew_context_.reset(new WGLEWContext());
}
GLContext::GLContext(Window* target_window, HGLRC glrc)
: GraphicsContext(target_window), glrc_(glrc) {
dc_ = GetDC(HWND(target_window_->native_handle()));
glew_context_.reset(new GLEWContext());
wglew_context_.reset(new WGLEWContext());
}
GLContext::~GLContext() {
MakeCurrent();
blitter_.Shutdown();
ClearCurrent();
if (glrc_) {
wglDeleteContext(glrc_);
}
if (dc_) {
ReleaseDC(HWND(target_window_->native_handle()), dc_);
}
}
bool GLContext::Initialize(Window* target_window) {
target_window_ = target_window;
dc_ = GetDC(HWND(target_window_->native_handle()));
PIXELFORMATDESCRIPTOR pfd = {0};
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
int pixel_format = ChoosePixelFormat(dc_, &pfd);
if (!pixel_format) {
XELOGE("Unable to choose pixel format");
return false;
}
if (!SetPixelFormat(dc_, pixel_format, &pfd)) {
XELOGE("Unable to set pixel format");
return false;
}
HGLRC temp_context = wglCreateContext(dc_);
if (!temp_context) {
XELOGE("Unable to create temporary GL context");
return false;
}
wglMakeCurrent(dc_, temp_context);
tls_glew_context_ = glew_context_.get();
tls_wglew_context_ = wglew_context_.get();
if (glewInit() != GLEW_OK) {
XELOGE("Unable to initialize GLEW");
return false;
}
if (wglewInit() != GLEW_OK) {
XELOGE("Unable to initialize WGLEW");
return false;
}
if (!WGLEW_ARB_create_context) {
XELOGE("WGL_ARG_create_context not supported by GL ICD");
return false;
}
int context_flags = 0;
if (FLAGS_gl_debug) {
context_flags |= WGL_CONTEXT_DEBUG_BIT_ARB;
}
int attrib_list[] = {WGL_CONTEXT_MAJOR_VERSION_ARB,
4,
WGL_CONTEXT_MINOR_VERSION_ARB,
5,
WGL_CONTEXT_FLAGS_ARB,
context_flags,
WGL_CONTEXT_PROFILE_MASK_ARB,
WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
0};
glrc_ = wglCreateContextAttribsARB(dc_, nullptr, attrib_list);
wglMakeCurrent(nullptr, nullptr);
wglDeleteContext(temp_context);
if (!glrc_) {
XELOGE("Unable to create real GL context");
return false;
}
if (!MakeCurrent()) {
XELOGE("Could not make real GL context current");
return false;
}
XELOGI("Successfully created OpenGL context:");
XELOGI(" GL_VENDOR: %s", glGetString(GL_VENDOR));
XELOGI(" GL_VERSION: %s", glGetString(GL_VERSION));
XELOGI(" GL_RENDERER: %s", glGetString(GL_RENDERER));
XELOGI(" GL_SHADING_LANGUAGE_VERSION: %s",
glGetString(GL_SHADING_LANGUAGE_VERSION));
while (glGetError()) {
// Clearing errors.
}
SetupDebugging();
if (!blitter_.Initialize()) {
XELOGE("Unable to initialize blitter");
ClearCurrent();
return false;
}
ClearCurrent();
return true;
}
std::unique_ptr<GraphicsContext> GLContext::CreateShared() {
assert_not_null(glrc_);
HGLRC new_glrc = nullptr;
{
GraphicsContextLock context_lock(this);
int context_flags = 0;
if (FLAGS_gl_debug) {
context_flags |= WGL_CONTEXT_DEBUG_BIT_ARB;
}
int attrib_list[] = {WGL_CONTEXT_MAJOR_VERSION_ARB,
4,
WGL_CONTEXT_MINOR_VERSION_ARB,
5,
WGL_CONTEXT_FLAGS_ARB,
context_flags,
WGL_CONTEXT_PROFILE_MASK_ARB,
WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
0};
new_glrc = wglCreateContextAttribsARB(dc_, glrc_, attrib_list);
if (!new_glrc) {
XELOGE("Could not create shared context");
return nullptr;
}
}
auto new_context =
std::unique_ptr<GLContext>(new GLContext(target_window_, new_glrc));
if (!new_context->MakeCurrent()) {
XELOGE("Could not make new GL context current");
return nullptr;
}
if (!glGetString(GL_EXTENSIONS)) {
new_context->ClearCurrent();
XELOGE("New GL context did not have extensions");
return nullptr;
}
if (glewInit() != GLEW_OK) {
new_context->ClearCurrent();
XELOGE("Unable to initialize GLEW");
return nullptr;
}
if (wglewInit() != GLEW_OK) {
new_context->ClearCurrent();
XELOGE("Unable to initialize WGLEW");
return nullptr;
}
SetupDebugging();
if (!new_context->blitter_.Initialize()) {
XELOGE("Unable to initialize blitter");
return nullptr;
}
new_context->ClearCurrent();
return std::unique_ptr<GraphicsContext>(new_context.release());
}
void FatalGLError(std::string error) {
XEFATAL(
(error +
"\nEnsure you have the latest drivers for your GPU and that it supports "
"OpenGL 4.5. See http://xenia.jp/faq/ for more information.")
.c_str());
}
void GLContext::AssertExtensionsPresent() {
if (!MakeCurrent()) {
XEFATAL("Unable to make GL context current");
return;
}
// Check shader version at least 4.5 (matching GL 4.5).
auto glsl_version_raw =
reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION));
std::string glsl_version(glsl_version_raw);
if (glsl_version.find("4.50") != 0) {
XELOGW("GLSL version reported as %s; you may have a bad time!",
glsl_version_raw);
}
if (!GLEW_ARB_bindless_texture || !glMakeTextureHandleResidentARB) {
FatalGLError("OpenGL extension ARB_bindless_texture is required.");
return;
}
if (!GLEW_ARB_fragment_coord_conventions) {
FatalGLError(
"OpenGL extension ARB_fragment_coord_conventions is required.");
return;
}
}
void GLContext::DebugMessage(GLenum source, GLenum type, GLuint id,
GLenum severity, GLsizei length,
const GLchar* message) {
const char* source_name = nullptr;
switch (source) {
case GL_DEBUG_SOURCE_API_ARB:
source_name = "OpenGL";
break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB:
source_name = "Windows";
break;
case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB:
source_name = "Shader Compiler";
break;
case GL_DEBUG_SOURCE_THIRD_PARTY_ARB:
source_name = "Third Party";
break;
case GL_DEBUG_SOURCE_APPLICATION_ARB:
source_name = "Application";
break;
case GL_DEBUG_SOURCE_OTHER_ARB:
source_name = "Other";
break;
default:
source_name = "(unknown source)";
break;
}
const char* type_name = nullptr;
switch (type) {
case GL_DEBUG_TYPE_ERROR:
type_name = "error";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
type_name = "deprecated behavior";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
type_name = "undefined behavior";
break;
case GL_DEBUG_TYPE_PORTABILITY:
type_name = "portability";
break;
case GL_DEBUG_TYPE_PERFORMANCE:
type_name = "performance";
break;
case GL_DEBUG_TYPE_OTHER:
type_name = "message";
break;
case GL_DEBUG_TYPE_MARKER:
type_name = "marker";
break;
case GL_DEBUG_TYPE_PUSH_GROUP:
type_name = "push group";
break;
case GL_DEBUG_TYPE_POP_GROUP:
type_name = "pop group";
break;
default:
type_name = "(unknown type)";
break;
}
const char* severity_name = nullptr;
switch (severity) {
case GL_DEBUG_SEVERITY_HIGH_ARB:
severity_name = "high";
break;
case GL_DEBUG_SEVERITY_MEDIUM_ARB:
severity_name = "medium";
break;
case GL_DEBUG_SEVERITY_LOW_ARB:
severity_name = "low";
break;
case GL_DEBUG_SEVERITY_NOTIFICATION:
severity_name = "notification";
break;
default:
severity_name = "(unknown severity)";
break;
}
XELOGE("GL4 %s: %s(%s) %d: %s", source_name, type_name, severity_name, id,
message);
}
void GLAPIENTRY GLContext::DebugMessageThunk(GLenum source, GLenum type,
GLuint id, GLenum severity,
GLsizei length,
const GLchar* message,
GLvoid* user_param) {
reinterpret_cast<GLContext*>(user_param)
->DebugMessage(source, type, id, severity, length, message);
}
void GLContext::SetupDebugging() {
if (!FLAGS_gl_debug || !FLAGS_gl_debug_output) {
return;
}
glEnable(GL_DEBUG_OUTPUT);
// Synchronous output hurts, but is required if we want to line up the logs.
if (FLAGS_gl_debug_output_synchronous) {
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
} else {
glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
}
// Enable everything by default.
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL,
GL_TRUE);
// Disable annoying messages.
GLuint disable_message_ids[] = {
0x00020004, // Usage warning: Generic vertex attribute array 0 uses a
// pointer with a small value (0x0000000000000000). Is this
// intended to be used as an offset into a buffer object?
};
glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_OTHER, GL_DONT_CARE,
GLsizei(xe::countof(disable_message_ids)),
disable_message_ids, GL_FALSE);
// Callback will be made from driver threads.
glDebugMessageCallback(reinterpret_cast<GLDEBUGPROC>(&DebugMessageThunk),
this);
}
std::unique_ptr<ProfilerDisplay> GLContext::CreateProfilerDisplay() {
return std::make_unique<GLProfilerDisplay>(target_window_);
}
std::unique_ptr<el::graphics::Renderer> GLContext::CreateElementalRenderer() {
return GL4ElementalRenderer::Create(this);
}
bool GLContext::MakeCurrent() {
SCOPE_profile_cpu_f("gpu");
if (FLAGS_thread_safe_gl) {
global_gl_mutex_.lock();
}
if (!wglMakeCurrent(dc_, glrc_)) {
if (FLAGS_thread_safe_gl) {
global_gl_mutex_.unlock();
}
XELOGE("Unable to make GL context current");
return false;
}
tls_glew_context_ = glew_context_.get();
tls_wglew_context_ = wglew_context_.get();
return true;
}
void GLContext::ClearCurrent() {
if (!FLAGS_disable_gl_context_reset) {
wglMakeCurrent(nullptr, nullptr);
}
tls_glew_context_ = nullptr;
tls_wglew_context_ = nullptr;
if (FLAGS_thread_safe_gl) {
global_gl_mutex_.unlock();
}
}
void GLContext::BeginSwap() {
SCOPE_profile_cpu_i("gpu", "xe::ui::gl::GLContext::BeginSwap");
float clear_color[] = {rand() / (float)RAND_MAX, 1.0f, 0, 1.0f};
glClearNamedFramebufferfv(0, GL_COLOR, 0, clear_color);
}
void GLContext::EndSwap() {
SCOPE_profile_cpu_i("gpu", "xe::ui::gl::GLContext::EndSwap");
SwapBuffers(dc());
}
} // namespace gl
} // namespace ui
} // namespace xe
<commit_msg>--random_clear_color, and making default grey.<commit_after>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2014 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/ui/gl/gl_context.h"
#include <gflags/gflags.h>
#include <mutex>
#include <string>
#include "xenia/base/assert.h"
#include "xenia/base/logging.h"
#include "xenia/base/math.h"
#include "xenia/profiling.h"
#include "xenia/ui/gl/gl_profiler_display.h"
#include "xenia/ui/gl/gl4_elemental_renderer.h"
#include "xenia/ui/window.h"
// TODO(benvanik): move win32 code to _win?
#include "xenia/base/platform_win.h"
#include "third_party/GL/wglew.h"
DEFINE_bool(thread_safe_gl, false,
"Only allow one GL context to be active at a time.");
DEFINE_bool(disable_gl_context_reset, false,
"Do not aggressively reset the GL context (helps with capture "
"programs such as OBS or FRAPS).");
DEFINE_bool(random_clear_color, false, "Randomizes GL clear color.");
DEFINE_bool(gl_debug, false, "Enable OpenGL debug validation layer.");
DEFINE_bool(gl_debug_output, false, "Dump ARB_debug_output to stderr.");
DEFINE_bool(gl_debug_output_synchronous, true,
"ARB_debug_output will synchronize to be thread safe.");
namespace xe {
namespace ui {
namespace gl {
static std::recursive_mutex global_gl_mutex_;
thread_local GLEWContext* tls_glew_context_ = nullptr;
thread_local WGLEWContext* tls_wglew_context_ = nullptr;
extern "C" GLEWContext* glewGetContext() { return tls_glew_context_; }
extern "C" WGLEWContext* wglewGetContext() { return tls_wglew_context_; }
std::unique_ptr<GLContext> GLContext::Create(Window* target_window) {
auto context = std::unique_ptr<GLContext>(new GLContext(target_window));
if (!context->Initialize(target_window)) {
return nullptr;
}
context->AssertExtensionsPresent();
return context;
}
GLContext::GLContext(Window* target_window) : GraphicsContext(target_window) {
glew_context_.reset(new GLEWContext());
wglew_context_.reset(new WGLEWContext());
}
GLContext::GLContext(Window* target_window, HGLRC glrc)
: GraphicsContext(target_window), glrc_(glrc) {
dc_ = GetDC(HWND(target_window_->native_handle()));
glew_context_.reset(new GLEWContext());
wglew_context_.reset(new WGLEWContext());
}
GLContext::~GLContext() {
MakeCurrent();
blitter_.Shutdown();
ClearCurrent();
if (glrc_) {
wglDeleteContext(glrc_);
}
if (dc_) {
ReleaseDC(HWND(target_window_->native_handle()), dc_);
}
}
bool GLContext::Initialize(Window* target_window) {
target_window_ = target_window;
dc_ = GetDC(HWND(target_window_->native_handle()));
PIXELFORMATDESCRIPTOR pfd = {0};
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
int pixel_format = ChoosePixelFormat(dc_, &pfd);
if (!pixel_format) {
XELOGE("Unable to choose pixel format");
return false;
}
if (!SetPixelFormat(dc_, pixel_format, &pfd)) {
XELOGE("Unable to set pixel format");
return false;
}
HGLRC temp_context = wglCreateContext(dc_);
if (!temp_context) {
XELOGE("Unable to create temporary GL context");
return false;
}
wglMakeCurrent(dc_, temp_context);
tls_glew_context_ = glew_context_.get();
tls_wglew_context_ = wglew_context_.get();
if (glewInit() != GLEW_OK) {
XELOGE("Unable to initialize GLEW");
return false;
}
if (wglewInit() != GLEW_OK) {
XELOGE("Unable to initialize WGLEW");
return false;
}
if (!WGLEW_ARB_create_context) {
XELOGE("WGL_ARG_create_context not supported by GL ICD");
return false;
}
int context_flags = 0;
if (FLAGS_gl_debug) {
context_flags |= WGL_CONTEXT_DEBUG_BIT_ARB;
}
int attrib_list[] = {WGL_CONTEXT_MAJOR_VERSION_ARB,
4,
WGL_CONTEXT_MINOR_VERSION_ARB,
5,
WGL_CONTEXT_FLAGS_ARB,
context_flags,
WGL_CONTEXT_PROFILE_MASK_ARB,
WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
0};
glrc_ = wglCreateContextAttribsARB(dc_, nullptr, attrib_list);
wglMakeCurrent(nullptr, nullptr);
wglDeleteContext(temp_context);
if (!glrc_) {
XELOGE("Unable to create real GL context");
return false;
}
if (!MakeCurrent()) {
XELOGE("Could not make real GL context current");
return false;
}
XELOGI("Successfully created OpenGL context:");
XELOGI(" GL_VENDOR: %s", glGetString(GL_VENDOR));
XELOGI(" GL_VERSION: %s", glGetString(GL_VERSION));
XELOGI(" GL_RENDERER: %s", glGetString(GL_RENDERER));
XELOGI(" GL_SHADING_LANGUAGE_VERSION: %s",
glGetString(GL_SHADING_LANGUAGE_VERSION));
while (glGetError()) {
// Clearing errors.
}
SetupDebugging();
if (!blitter_.Initialize()) {
XELOGE("Unable to initialize blitter");
ClearCurrent();
return false;
}
ClearCurrent();
return true;
}
std::unique_ptr<GraphicsContext> GLContext::CreateShared() {
assert_not_null(glrc_);
HGLRC new_glrc = nullptr;
{
GraphicsContextLock context_lock(this);
int context_flags = 0;
if (FLAGS_gl_debug) {
context_flags |= WGL_CONTEXT_DEBUG_BIT_ARB;
}
int attrib_list[] = {WGL_CONTEXT_MAJOR_VERSION_ARB,
4,
WGL_CONTEXT_MINOR_VERSION_ARB,
5,
WGL_CONTEXT_FLAGS_ARB,
context_flags,
WGL_CONTEXT_PROFILE_MASK_ARB,
WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
0};
new_glrc = wglCreateContextAttribsARB(dc_, glrc_, attrib_list);
if (!new_glrc) {
XELOGE("Could not create shared context");
return nullptr;
}
}
auto new_context =
std::unique_ptr<GLContext>(new GLContext(target_window_, new_glrc));
if (!new_context->MakeCurrent()) {
XELOGE("Could not make new GL context current");
return nullptr;
}
if (!glGetString(GL_EXTENSIONS)) {
new_context->ClearCurrent();
XELOGE("New GL context did not have extensions");
return nullptr;
}
if (glewInit() != GLEW_OK) {
new_context->ClearCurrent();
XELOGE("Unable to initialize GLEW");
return nullptr;
}
if (wglewInit() != GLEW_OK) {
new_context->ClearCurrent();
XELOGE("Unable to initialize WGLEW");
return nullptr;
}
SetupDebugging();
if (!new_context->blitter_.Initialize()) {
XELOGE("Unable to initialize blitter");
return nullptr;
}
new_context->ClearCurrent();
return std::unique_ptr<GraphicsContext>(new_context.release());
}
void FatalGLError(std::string error) {
XEFATAL(
(error +
"\nEnsure you have the latest drivers for your GPU and that it supports "
"OpenGL 4.5. See http://xenia.jp/faq/ for more information.")
.c_str());
}
void GLContext::AssertExtensionsPresent() {
if (!MakeCurrent()) {
XEFATAL("Unable to make GL context current");
return;
}
// Check shader version at least 4.5 (matching GL 4.5).
auto glsl_version_raw =
reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION));
std::string glsl_version(glsl_version_raw);
if (glsl_version.find("4.50") != 0) {
XELOGW("GLSL version reported as %s; you may have a bad time!",
glsl_version_raw);
}
if (!GLEW_ARB_bindless_texture || !glMakeTextureHandleResidentARB) {
FatalGLError("OpenGL extension ARB_bindless_texture is required.");
return;
}
if (!GLEW_ARB_fragment_coord_conventions) {
FatalGLError(
"OpenGL extension ARB_fragment_coord_conventions is required.");
return;
}
}
void GLContext::DebugMessage(GLenum source, GLenum type, GLuint id,
GLenum severity, GLsizei length,
const GLchar* message) {
const char* source_name = nullptr;
switch (source) {
case GL_DEBUG_SOURCE_API_ARB:
source_name = "OpenGL";
break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB:
source_name = "Windows";
break;
case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB:
source_name = "Shader Compiler";
break;
case GL_DEBUG_SOURCE_THIRD_PARTY_ARB:
source_name = "Third Party";
break;
case GL_DEBUG_SOURCE_APPLICATION_ARB:
source_name = "Application";
break;
case GL_DEBUG_SOURCE_OTHER_ARB:
source_name = "Other";
break;
default:
source_name = "(unknown source)";
break;
}
const char* type_name = nullptr;
switch (type) {
case GL_DEBUG_TYPE_ERROR:
type_name = "error";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
type_name = "deprecated behavior";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
type_name = "undefined behavior";
break;
case GL_DEBUG_TYPE_PORTABILITY:
type_name = "portability";
break;
case GL_DEBUG_TYPE_PERFORMANCE:
type_name = "performance";
break;
case GL_DEBUG_TYPE_OTHER:
type_name = "message";
break;
case GL_DEBUG_TYPE_MARKER:
type_name = "marker";
break;
case GL_DEBUG_TYPE_PUSH_GROUP:
type_name = "push group";
break;
case GL_DEBUG_TYPE_POP_GROUP:
type_name = "pop group";
break;
default:
type_name = "(unknown type)";
break;
}
const char* severity_name = nullptr;
switch (severity) {
case GL_DEBUG_SEVERITY_HIGH_ARB:
severity_name = "high";
break;
case GL_DEBUG_SEVERITY_MEDIUM_ARB:
severity_name = "medium";
break;
case GL_DEBUG_SEVERITY_LOW_ARB:
severity_name = "low";
break;
case GL_DEBUG_SEVERITY_NOTIFICATION:
severity_name = "notification";
break;
default:
severity_name = "(unknown severity)";
break;
}
XELOGE("GL4 %s: %s(%s) %d: %s", source_name, type_name, severity_name, id,
message);
}
void GLAPIENTRY GLContext::DebugMessageThunk(GLenum source, GLenum type,
GLuint id, GLenum severity,
GLsizei length,
const GLchar* message,
GLvoid* user_param) {
reinterpret_cast<GLContext*>(user_param)
->DebugMessage(source, type, id, severity, length, message);
}
void GLContext::SetupDebugging() {
if (!FLAGS_gl_debug || !FLAGS_gl_debug_output) {
return;
}
glEnable(GL_DEBUG_OUTPUT);
// Synchronous output hurts, but is required if we want to line up the logs.
if (FLAGS_gl_debug_output_synchronous) {
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
} else {
glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
}
// Enable everything by default.
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL,
GL_TRUE);
// Disable annoying messages.
GLuint disable_message_ids[] = {
0x00020004, // Usage warning: Generic vertex attribute array 0 uses a
// pointer with a small value (0x0000000000000000). Is this
// intended to be used as an offset into a buffer object?
};
glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_OTHER, GL_DONT_CARE,
GLsizei(xe::countof(disable_message_ids)),
disable_message_ids, GL_FALSE);
// Callback will be made from driver threads.
glDebugMessageCallback(reinterpret_cast<GLDEBUGPROC>(&DebugMessageThunk),
this);
}
std::unique_ptr<ProfilerDisplay> GLContext::CreateProfilerDisplay() {
return std::make_unique<GLProfilerDisplay>(target_window_);
}
std::unique_ptr<el::graphics::Renderer> GLContext::CreateElementalRenderer() {
return GL4ElementalRenderer::Create(this);
}
bool GLContext::MakeCurrent() {
SCOPE_profile_cpu_f("gpu");
if (FLAGS_thread_safe_gl) {
global_gl_mutex_.lock();
}
if (!wglMakeCurrent(dc_, glrc_)) {
if (FLAGS_thread_safe_gl) {
global_gl_mutex_.unlock();
}
XELOGE("Unable to make GL context current");
return false;
}
tls_glew_context_ = glew_context_.get();
tls_wglew_context_ = wglew_context_.get();
return true;
}
void GLContext::ClearCurrent() {
if (!FLAGS_disable_gl_context_reset) {
wglMakeCurrent(nullptr, nullptr);
}
tls_glew_context_ = nullptr;
tls_wglew_context_ = nullptr;
if (FLAGS_thread_safe_gl) {
global_gl_mutex_.unlock();
}
}
void GLContext::BeginSwap() {
SCOPE_profile_cpu_i("gpu", "xe::ui::gl::GLContext::BeginSwap");
float clear_color[] = {238 / 255.0f, 238 / 255.0f, 238 / 255.0f, 1.0f};
if (FLAGS_random_clear_color) {
clear_color[0] = rand() / (float)RAND_MAX;
clear_color[1] = 1.0f;
clear_color[2] = 0.0f;
clear_color[3] = 1.0f;
}
glClearNamedFramebufferfv(0, GL_COLOR, 0, clear_color);
}
void GLContext::EndSwap() {
SCOPE_profile_cpu_i("gpu", "xe::ui::gl::GLContext::EndSwap");
SwapBuffers(dc());
}
} // namespace gl
} // namespace ui
} // namespace xe
<|endoftext|> |
<commit_before>#include "ast.hpp"
#include "context.hpp"
#include "parser.hpp"
#include "to_string.hpp"
#include <string>
using namespace Sass;
Context ctx = Context(Context::Data());
To_String to_string;
Compound_Selector* compound_selector(string src, Context& ctx)
{ return Parser::from_c_str(src.c_str(), ctx, "", 0).parse_simple_selector_sequence(); }
void check(Compound_Selector* s1, Compound_Selector* s2)
{
cout << "Is "
<< s1->perform(&to_string)
<< " a superselector of "
<< s2->perform(&to_string)
<< "?\t"
<< s1->is_superselector_of(s2)
<< endl;
}
int main() {
Compound_Selector* s1 = compound_selector(".foo.bar;", ctx);
Compound_Selector* s2 = compound_selector(".foo;", ctx);
Compound_Selector* s3 = compound_selector("div.foo;", ctx);
Compound_Selector* s4 = compound_selector("div.bar.foo;", ctx);
Compound_Selector* s5 = compound_selector("p.foo;", ctx);
check(s2, s1);
check(s1, s2);
check(s1, s3);
check(s2, s3);
check(s3, s2);
check(s3, s4);
check(s5, s4);
return 0;
}
<commit_msg>making the tester easier to use<commit_after>#include "ast.hpp"
#include "context.hpp"
#include "parser.hpp"
#include "to_string.hpp"
#include <string>
using namespace Sass;
Context ctx = Context(Context::Data());
To_String to_string;
Compound_Selector* compound_selector(string src)
{ return Parser::from_c_str(src.c_str(), ctx, "", 0).parse_simple_selector_sequence(); }
void check(string s1, string s2)
{
cout << "Is "
<< s1
<< " a superselector of "
<< s2
<< "?\t"
<< compound_selector(s1 + ";")->is_superselector_of(compound_selector(s2 + ";"))
<< endl;
}
int main() {
check(".foo", ".foo.bar");
check(".foo.bar", ".foo");
check(".foo.bar", "div.foo");
check(".foo", "div.foo");
check("div.foo", ".foo");
check("div.foo", "div.bar.foo");
check("p.foo", "div.bar.foo");
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>ragdoll is serialized relative to entity - fixes #930<commit_after><|endoftext|> |
<commit_before>// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "Application.h"
#include <cmath>
using namespace std;
using namespace ouzel;
Application::~Application()
{
sharedEngine->getEventDispatcher()->removeEventHandler(eventHandler);
}
void Application::begin()
{
#if defined(OUZEL_PLATFORM_WINDOWS) || defined(OUZEL_PLATFORM_LINUX)
sharedEngine->getFileSystem()->addResourcePath("Resources");
#endif
sharedEngine->getLocalization()->addLanguage("latvian", "lv.mo");
sharedEngine->getLocalization()->setLanguage("latvian");
eventHandler = make_shared<EventHandler>();
eventHandler->keyboardHandler = std::bind(&Application::handleKeyboard, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
eventHandler->mouseHandler = std::bind(&Application::handleMouse, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
eventHandler->touchHandler = std::bind(&Application::handleTouch, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
eventHandler->gamepadHandler = std::bind(&Application::handleGamepad, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
eventHandler->uiHandler = std::bind(&Application::handleUI, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
sharedEngine->getEventDispatcher()->addEventHandler(eventHandler);
sharedEngine->getRenderer()->setClearColor(graphics::Color(64, 0, 0));
sharedEngine->getWindow()->setTitle("Sample");
scene::ScenePtr scene = make_shared<scene::Scene>();
sharedEngine->getSceneManager()->setScene(scene);
rtLayer = std::make_shared<scene::Layer>();
scene->addLayer(rtLayer);
renderTarget = ouzel::sharedEngine->getRenderer()->createRenderTarget(Size2(256.0f, 256.0f), false);
rtLayer->setCamera(std::make_shared<scene::Camera>());
rtLayer->setRenderTarget(renderTarget);
layer = std::make_shared<scene::Layer>();
scene->addLayer(layer);
layer->setCamera(std::make_shared<scene::Camera>());
uiLayer = std::make_shared<scene::Layer>();
scene->addLayer(uiLayer);
uiLayer->setCamera(std::make_shared<scene::Camera>());
scene::DebugDrawablePtr debugDrawable = std::make_shared<scene::DebugDrawable>();
debugDrawable->rectangle(Rectangle(100.0f, 100.0f), graphics::Color(0, 128, 128, 255), true);
debugDrawable->rectangle(Rectangle(100.0f, 100.0f), graphics::Color(255, 255, 255, 255), false);
debugDrawable->line(Vector2(0.0f, 0.0f), Vector2(50.0f, 50.0f), graphics::Color(0, 255, 255, 255));
debugDrawable->point(Vector2(75.0f, 75.0f), graphics::Color(255, 0, 0, 255));
debugDrawable->circle(Vector2(75.0f, 75.0f), 20.0f, graphics::Color(0, 0, 255, 255));
debugDrawable->circle(Vector2(25.0f, 75.0f), 20.0f, graphics::Color(0, 0, 255, 255), true);
scene::NodePtr drawNode = std::make_shared<scene::Node>();
drawNode->addDrawable(debugDrawable);
drawNode->setPosition(Vector2(-300, 0.0f));
layer->addChild(drawNode);
drawNode->animate(std::make_shared<ouzel::scene::Shake>(10.0f, Vector2(10.0f, 20.0f), 20.0f));
scene::SpritePtr characterSprite = scene::Sprite::createFromFile("run.json");
characterSprite->play(true);
character = std::make_shared<scene::Node>();
character->addDrawable(characterSprite);
layer->addChild(character);
character->setPosition(Vector2(-300.0f, 0.0f));
std::vector<scene::AnimatorPtr> sequence = {
make_shared<scene::Move>(4.0f, Vector2(300.0f, 0.0f)),
make_shared<scene::Fade>(2.0f, 0.4f)
};
character->animate(make_shared<scene::Sequence>(sequence));
scene::SpritePtr fireSprite = scene::Sprite::createFromFile("fire.json");
fireSprite->play(true);
scene::NodePtr fireNode = std::make_shared<scene::Node>();
fireNode->addDrawable(fireSprite);
fireNode->setPosition(Vector2(-100.0f, -100.0f));
layer->addChild(fireNode);
fireNode->animate(make_shared<scene::Fade>(5.0f, 0.5f));
scene::ParticleSystemPtr flameParticleSystem = scene::ParticleSystem::createFromFile("flame.json");
flame = std::make_shared<scene::Node>();
flame->addDrawable(flameParticleSystem);
layer->addChild(flame);
scene::SpritePtr witchSprite = scene::Sprite::createFromFile("witch.png");
//witchSprite->setColor(graphics::Color(128, 0, 255, 255));
witch = std::make_shared<scene::Node>();
witch->addDrawable(witchSprite);
witch->setPosition(Vector2(100.0f, 100.0f));
layer->addChild(witch);
witch->animate(make_shared<scene::Repeat>(make_shared<scene::Rotate>(1.0f, TAU, false), 3));
gui::LabelPtr label = gui::Label::create("font.fnt", sharedEngine->getLocalization()->getString("Test"));
uiLayer->addChild(label);
std::vector<scene::AnimatorPtr> sequence2 = {
make_shared<scene::Animator>(1.0f), // delay
make_shared<scene::Ease>(make_shared<scene::Move>(2.0f, Vector2(0.0f, -240.0f), false), scene::Ease::Type::OUT, scene::Ease::Func::BOUNCE)
};
label->animate(make_shared<scene::Sequence>(sequence2));
button = gui::Button::create("button.png", "button.png", "button_down.png", "", "", graphics::Color(), "");
button->setPosition(Vector2(-200.0f, 200.0f));
uiLayer->addChild(button);
// Render target
ouzel::scene::NodePtr rtCharacter = std::make_shared<scene::Node>();
rtCharacter->addDrawable(characterSprite);
rtLayer->addChild(rtCharacter);
ouzel::scene::SpriteFramePtr rtFrame = ouzel::scene::SpriteFrame::create(Rectangle(0.0f, 0.0f, 256.0f, 256.0f), renderTarget->getTexture(), false, renderTarget->getTexture()->getSize(), Vector2(), Vector2(0.5f, 0.5f));
ouzel::scene::SpritePtr rtSprite = ouzel::scene::Sprite::createFromSpriteFrames({ rtFrame });
ouzel::scene::NodePtr rtNode = std::make_shared<ouzel::scene::Node>();
rtNode->addDrawable(rtSprite);
rtNode->setPosition(Vector2(200.0f, 200.0f));
layer->addChild(rtNode);
sharedEngine->getInput()->startGamepadDiscovery();
}
bool Application::handleKeyboard(ouzel::Event::Type type, const KeyboardEvent& event, const VoidPtr& sender) const
{
OUZEL_UNUSED(sender);
if (type == Event::Type::KEY_DOWN)
{
Vector2 position = layer->getCamera()->getPosition();
switch (event.key)
{
case input::KeyboardKey::UP:
position.y += 10.0f;
break;
case input::KeyboardKey::DOWN:
position.y -= 10.0f;
break;
case input::KeyboardKey::LEFT:
position.x -= 10.0f;
break;
case input::KeyboardKey::RIGHT:
position.x += 10.0f;
break;
case input::KeyboardKey::SPACE:
witch->setVisible(!witch->isVisible());
break;
case input::KeyboardKey::RETURN:
sharedEngine->getWindow()->setSize(Size2(640.0f, 480.0f));
break;
case input::KeyboardKey::TAB:
button->setEnabled(!button->isEnabled());
break;
default:
break;
}
layer->getCamera()->setPosition(position);
}
return true;
}
bool Application::handleMouse(ouzel::Event::Type type, const MouseEvent& event, const VoidPtr& sender) const
{
OUZEL_UNUSED(sender);
switch (type)
{
case Event::Type::MOUSE_DOWN:
{
sharedEngine->getInput()->setCursorVisible(!sharedEngine->getInput()->isCursorVisible());
break;
}
case Event::Type::MOUSE_MOVE:
{
Vector2 worldLocation = layer->getCamera()->convertScreenToWorld(event.position);
flame->setPosition(worldLocation);
break;
}
default:
break;
}
return true;
}
bool Application::handleTouch(ouzel::Event::Type type, const TouchEvent& event, const VoidPtr& sender) const
{
OUZEL_UNUSED(type);
OUZEL_UNUSED(sender);
Vector2 worldLocation = layer->getCamera()->convertScreenToWorld(event.position);
flame->setPosition(worldLocation);
return true;
}
bool Application::handleGamepad(ouzel::Event::Type type, const GamepadEvent& event, const VoidPtr& sender) const
{
OUZEL_UNUSED(sender);
if (type == Event::Type::GAMEPAD_BUTTON_CHANGE)
{
Vector2 position = layer->getCamera()->convertWorldToScreen(flame->getPosition());
switch (event.button)
{
case input::GamepadButton::DPAD_UP:
case input::GamepadButton::LEFT_THUMB_UP:
case input::GamepadButton::RIGHT_THUMB_UP:
position.y = event.value;
break;
case input::GamepadButton::DPAD_DOWN:
case input::GamepadButton::LEFT_THUMB_DOWN:
case input::GamepadButton::RIGHT_THUMB_DOWN:
position.y = -event.value;
break;
case input::GamepadButton::DPAD_LEFT:
case input::GamepadButton::LEFT_THUMB_LEFT:
case input::GamepadButton::RIGHT_THUMB_LEFT:
position.x = -event.value;
break;
case input::GamepadButton::DPAD_RIGHT:
case input::GamepadButton::LEFT_THUMB_RIGHT:
case input::GamepadButton::RIGHT_THUMB_RIGHT:
position.x = event.value;
break;
case input::GamepadButton::A:
witch->setVisible(!event.pressed);
break;
default:
break;
}
Vector2 worldLocation = layer->getCamera()->convertScreenToWorld(position);
flame->setPosition(worldLocation);
}
return true;
}
bool Application::handleUI(ouzel::Event::Type type, const UIEvent& event, const VoidPtr& sender) const
{
OUZEL_UNUSED(event);
if (type == Event::Type::UI_CLICK_NODE && sender == button)
{
character->setVisible(!character->isVisible());
}
return true;
}
<commit_msg>Remove std:: and ouzel:: prefixes from sample code<commit_after>// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "Application.h"
#include <cmath>
using namespace std;
using namespace ouzel;
Application::~Application()
{
sharedEngine->getEventDispatcher()->removeEventHandler(eventHandler);
}
void Application::begin()
{
#if defined(OUZEL_PLATFORM_WINDOWS) || defined(OUZEL_PLATFORM_LINUX)
sharedEngine->getFileSystem()->addResourcePath("Resources");
#endif
sharedEngine->getLocalization()->addLanguage("latvian", "lv.mo");
sharedEngine->getLocalization()->setLanguage("latvian");
eventHandler = make_shared<EventHandler>();
eventHandler->keyboardHandler = bind(&Application::handleKeyboard, this, placeholders::_1, placeholders::_2, placeholders::_3);
eventHandler->mouseHandler = bind(&Application::handleMouse, this, placeholders::_1, placeholders::_2, placeholders::_3);
eventHandler->touchHandler = bind(&Application::handleTouch, this, placeholders::_1, placeholders::_2, placeholders::_3);
eventHandler->gamepadHandler = bind(&Application::handleGamepad, this, placeholders::_1, placeholders::_2, placeholders::_3);
eventHandler->uiHandler = bind(&Application::handleUI, this, placeholders::_1, placeholders::_2, placeholders::_3);
sharedEngine->getEventDispatcher()->addEventHandler(eventHandler);
sharedEngine->getRenderer()->setClearColor(graphics::Color(64, 0, 0));
sharedEngine->getWindow()->setTitle("Sample");
scene::ScenePtr scene = make_shared<scene::Scene>();
sharedEngine->getSceneManager()->setScene(scene);
rtLayer = make_shared<scene::Layer>();
scene->addLayer(rtLayer);
renderTarget = sharedEngine->getRenderer()->createRenderTarget(Size2(256.0f, 256.0f), false);
rtLayer->setCamera(make_shared<scene::Camera>());
rtLayer->setRenderTarget(renderTarget);
layer = make_shared<scene::Layer>();
scene->addLayer(layer);
layer->setCamera(make_shared<scene::Camera>());
uiLayer = make_shared<scene::Layer>();
scene->addLayer(uiLayer);
uiLayer->setCamera(make_shared<scene::Camera>());
scene::DebugDrawablePtr debugDrawable = make_shared<scene::DebugDrawable>();
debugDrawable->rectangle(Rectangle(100.0f, 100.0f), graphics::Color(0, 128, 128, 255), true);
debugDrawable->rectangle(Rectangle(100.0f, 100.0f), graphics::Color(255, 255, 255, 255), false);
debugDrawable->line(Vector2(0.0f, 0.0f), Vector2(50.0f, 50.0f), graphics::Color(0, 255, 255, 255));
debugDrawable->point(Vector2(75.0f, 75.0f), graphics::Color(255, 0, 0, 255));
debugDrawable->circle(Vector2(75.0f, 75.0f), 20.0f, graphics::Color(0, 0, 255, 255));
debugDrawable->circle(Vector2(25.0f, 75.0f), 20.0f, graphics::Color(0, 0, 255, 255), true);
scene::NodePtr drawNode = make_shared<scene::Node>();
drawNode->addDrawable(debugDrawable);
drawNode->setPosition(Vector2(-300, 0.0f));
layer->addChild(drawNode);
drawNode->animate(make_shared<scene::Shake>(10.0f, Vector2(10.0f, 20.0f), 20.0f));
scene::SpritePtr characterSprite = scene::Sprite::createFromFile("run.json");
characterSprite->play(true);
character = make_shared<scene::Node>();
character->addDrawable(characterSprite);
layer->addChild(character);
character->setPosition(Vector2(-300.0f, 0.0f));
vector<scene::AnimatorPtr> sequence = {
make_shared<scene::Move>(4.0f, Vector2(300.0f, 0.0f)),
make_shared<scene::Fade>(2.0f, 0.4f)
};
character->animate(make_shared<scene::Sequence>(sequence));
scene::SpritePtr fireSprite = scene::Sprite::createFromFile("fire.json");
fireSprite->play(true);
scene::NodePtr fireNode = make_shared<scene::Node>();
fireNode->addDrawable(fireSprite);
fireNode->setPosition(Vector2(-100.0f, -100.0f));
layer->addChild(fireNode);
fireNode->animate(make_shared<scene::Fade>(5.0f, 0.5f));
scene::ParticleSystemPtr flameParticleSystem = scene::ParticleSystem::createFromFile("flame.json");
flame = make_shared<scene::Node>();
flame->addDrawable(flameParticleSystem);
layer->addChild(flame);
scene::SpritePtr witchSprite = scene::Sprite::createFromFile("witch.png");
//witchSprite->setColor(graphics::Color(128, 0, 255, 255));
witch = make_shared<scene::Node>();
witch->addDrawable(witchSprite);
witch->setPosition(Vector2(100.0f, 100.0f));
layer->addChild(witch);
witch->animate(make_shared<scene::Repeat>(make_shared<scene::Rotate>(1.0f, TAU, false), 3));
gui::LabelPtr label = gui::Label::create("font.fnt", sharedEngine->getLocalization()->getString("Test"));
uiLayer->addChild(label);
vector<scene::AnimatorPtr> sequence2 = {
make_shared<scene::Animator>(1.0f), // delay
make_shared<scene::Ease>(make_shared<scene::Move>(2.0f, Vector2(0.0f, -240.0f), false), scene::Ease::Type::OUT, scene::Ease::Func::BOUNCE)
};
label->animate(make_shared<scene::Sequence>(sequence2));
button = gui::Button::create("button.png", "button.png", "button_down.png", "", "", graphics::Color(), "");
button->setPosition(Vector2(-200.0f, 200.0f));
uiLayer->addChild(button);
// Render target
scene::NodePtr rtCharacter = make_shared<scene::Node>();
rtCharacter->addDrawable(characterSprite);
rtLayer->addChild(rtCharacter);
scene::SpriteFramePtr rtFrame = scene::SpriteFrame::create(Rectangle(0.0f, 0.0f, 256.0f, 256.0f), renderTarget->getTexture(), false, renderTarget->getTexture()->getSize(), Vector2(), Vector2(0.5f, 0.5f));
scene::SpritePtr rtSprite = scene::Sprite::createFromSpriteFrames({ rtFrame });
scene::NodePtr rtNode = make_shared<scene::Node>();
rtNode->addDrawable(rtSprite);
rtNode->setPosition(Vector2(200.0f, 200.0f));
layer->addChild(rtNode);
sharedEngine->getInput()->startGamepadDiscovery();
}
bool Application::handleKeyboard(Event::Type type, const KeyboardEvent& event, const VoidPtr& sender) const
{
OUZEL_UNUSED(sender);
if (type == Event::Type::KEY_DOWN)
{
Vector2 position = layer->getCamera()->getPosition();
switch (event.key)
{
case input::KeyboardKey::UP:
position.y += 10.0f;
break;
case input::KeyboardKey::DOWN:
position.y -= 10.0f;
break;
case input::KeyboardKey::LEFT:
position.x -= 10.0f;
break;
case input::KeyboardKey::RIGHT:
position.x += 10.0f;
break;
case input::KeyboardKey::SPACE:
witch->setVisible(!witch->isVisible());
break;
case input::KeyboardKey::RETURN:
sharedEngine->getWindow()->setSize(Size2(640.0f, 480.0f));
break;
case input::KeyboardKey::TAB:
button->setEnabled(!button->isEnabled());
break;
default:
break;
}
layer->getCamera()->setPosition(position);
}
return true;
}
bool Application::handleMouse(Event::Type type, const MouseEvent& event, const VoidPtr& sender) const
{
OUZEL_UNUSED(sender);
switch (type)
{
case Event::Type::MOUSE_DOWN:
{
sharedEngine->getInput()->setCursorVisible(!sharedEngine->getInput()->isCursorVisible());
break;
}
case Event::Type::MOUSE_MOVE:
{
Vector2 worldLocation = layer->getCamera()->convertScreenToWorld(event.position);
flame->setPosition(worldLocation);
break;
}
default:
break;
}
return true;
}
bool Application::handleTouch(Event::Type type, const TouchEvent& event, const VoidPtr& sender) const
{
OUZEL_UNUSED(type);
OUZEL_UNUSED(sender);
Vector2 worldLocation = layer->getCamera()->convertScreenToWorld(event.position);
flame->setPosition(worldLocation);
return true;
}
bool Application::handleGamepad(Event::Type type, const GamepadEvent& event, const VoidPtr& sender) const
{
OUZEL_UNUSED(sender);
if (type == Event::Type::GAMEPAD_BUTTON_CHANGE)
{
Vector2 position = layer->getCamera()->convertWorldToScreen(flame->getPosition());
switch (event.button)
{
case input::GamepadButton::DPAD_UP:
case input::GamepadButton::LEFT_THUMB_UP:
case input::GamepadButton::RIGHT_THUMB_UP:
position.y = event.value;
break;
case input::GamepadButton::DPAD_DOWN:
case input::GamepadButton::LEFT_THUMB_DOWN:
case input::GamepadButton::RIGHT_THUMB_DOWN:
position.y = -event.value;
break;
case input::GamepadButton::DPAD_LEFT:
case input::GamepadButton::LEFT_THUMB_LEFT:
case input::GamepadButton::RIGHT_THUMB_LEFT:
position.x = -event.value;
break;
case input::GamepadButton::DPAD_RIGHT:
case input::GamepadButton::LEFT_THUMB_RIGHT:
case input::GamepadButton::RIGHT_THUMB_RIGHT:
position.x = event.value;
break;
case input::GamepadButton::A:
witch->setVisible(!event.pressed);
break;
default:
break;
}
Vector2 worldLocation = layer->getCamera()->convertScreenToWorld(position);
flame->setPosition(worldLocation);
}
return true;
}
bool Application::handleUI(Event::Type type, const UIEvent& event, const VoidPtr& sender) const
{
OUZEL_UNUSED(event);
if (type == Event::Type::UI_CLICK_NODE && sender == button)
{
character->setVisible(!character->isVisible());
}
return true;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: DTables.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: oj $ $Date: 2000-10-24 16:14:04 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_DBASE_TABLES_HXX_
#include "dbase/DTables.hxx"
#endif
#ifndef _CONNECTIVITY_DBASE_TABLE_HXX_
#include "dbase/DTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef _CONNECTIVITY_FILE_CATALOG_HXX_
#include "file/FCatalog.hxx"
#endif
#ifndef _CONNECTIVITY_FILE_BCONNECTION_HXX_
#include "file/FConnection.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#define CONNECTIVITY_PROPERTY_NAME_SPACE dbase
#ifndef _CONNECTIVITY_PROPERTYIDS_HXX_
#include "propertyids.hxx"
#endif
using namespace connectivity::dbase;
using namespace connectivity::file;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
namespace starutil = ::com::sun::star::util;
Reference< XNamed > ODbaseTables::createObject(const ::rtl::OUString& _rName)
{
::rtl::OUString aName,aSchema;
ODbaseTable* pRet = new ODbaseTable((ODbaseConnection*)static_cast<OFileCatalog&>(m_rParent).getConnection(),
_rName,::rtl::OUString::createFromAscii("TABLE"));
Reference< XNamed > xRet = pRet;
return xRet;
}
// -------------------------------------------------------------------------
void ODbaseTables::impl_refresh( ) throw(RuntimeException)
{
// static_cast<OFileCatalog&>(m_rParent).refreshTables();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > ODbaseTables::createEmptyObject()
{
ODbaseTable* pRet = new ODbaseTable((ODbaseConnection*)static_cast<OFileCatalog&>(m_rParent).getConnection());
Reference< XPropertySet > xRet = pRet;
return xRet;
}
typedef connectivity::sdbcx::OCollection ODbaseTables_BASE_BASE;
// -------------------------------------------------------------------------
// XAppend
void SAL_CALL ODbaseTables::appendByDescriptor( const Reference< XPropertySet >& descriptor ) throw(SQLException, ElementExistException, RuntimeException)
{
::osl::MutexGuard aGuard(m_rMutex);
::rtl::OUString aName = getString(descriptor->getPropertyValue(PROPERTY_NAME));
ObjectMap::iterator aIter = m_aNameMap.find(aName);
if( aIter != m_aNameMap.end())
throw ElementExistException(aName,*this);
Reference<XUnoTunnel> xTunnel(descriptor,UNO_QUERY);
if(xTunnel.is())
{
ODbaseTable* pTable = (ODbaseTable*)xTunnel->getSomething(ODbaseTable::getUnoTunnelImplementationId());
if(pTable && pTable->CreateImpl())
ODbaseTables_BASE_BASE::appendByDescriptor(descriptor);
}
}
// -------------------------------------------------------------------------
// XDrop
void SAL_CALL ODbaseTables::dropByName( const ::rtl::OUString& elementName ) throw(SQLException, NoSuchElementException, RuntimeException)
{
::osl::MutexGuard aGuard(m_rMutex);
ObjectMap::iterator aIter = m_aNameMap.find(elementName);
if( aIter == m_aNameMap.end())
throw NoSuchElementException(elementName,*this);
Reference< XUnoTunnel> xTunnel(aIter->second.get(),UNO_QUERY);
if(xTunnel.is())
{
ODbaseTable* pTable = (ODbaseTable*)xTunnel->getSomething(ODbaseTable::getUnoTunnelImplementationId());
if(pTable && pTable->DropImpl())
ODbaseTables_BASE_BASE::dropByName(elementName);
}
}
// -------------------------------------------------------------------------
void SAL_CALL ODbaseTables::dropByIndex( sal_Int32 index ) throw(SQLException, IndexOutOfBoundsException, RuntimeException)
{
::osl::MutexGuard aGuard(m_rMutex);
if (index < 0 || index >= getCount())
throw IndexOutOfBoundsException();
dropByName((*m_aElements[index]).first);
}
// -------------------------------------------------------------------------
<commit_msg>queryinterface impl<commit_after>/*************************************************************************
*
* $RCSfile: DTables.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: oj $ $Date: 2000-10-25 11:30:56 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_DBASE_TABLES_HXX_
#include "dbase/DTables.hxx"
#endif
#ifndef _CONNECTIVITY_DBASE_TABLE_HXX_
#include "dbase/DTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef _CONNECTIVITY_FILE_CATALOG_HXX_
#include "file/FCatalog.hxx"
#endif
#ifndef _CONNECTIVITY_FILE_BCONNECTION_HXX_
#include "file/FConnection.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#define CONNECTIVITY_PROPERTY_NAME_SPACE dbase
#ifndef _CONNECTIVITY_PROPERTYIDS_HXX_
#include "propertyids.hxx"
#endif
using namespace connectivity::dbase;
using namespace connectivity::file;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::container;
namespace starutil = ::com::sun::star::util;
Reference< XNamed > ODbaseTables::createObject(const ::rtl::OUString& _rName)
{
::rtl::OUString aName,aSchema;
ODbaseTable* pRet = new ODbaseTable((ODbaseConnection*)static_cast<OFileCatalog&>(m_rParent).getConnection(),
_rName,::rtl::OUString::createFromAscii("TABLE"));
Reference< XNamed > xRet = pRet;
return xRet;
}
// -------------------------------------------------------------------------
void ODbaseTables::impl_refresh( ) throw(RuntimeException)
{
// static_cast<OFileCatalog&>(m_rParent).refreshTables();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > ODbaseTables::createEmptyObject()
{
ODbaseTable* pRet = new ODbaseTable((ODbaseConnection*)static_cast<OFileCatalog&>(m_rParent).getConnection());
Reference< XPropertySet > xRet = pRet;
return xRet;
}
typedef connectivity::sdbcx::OCollection ODbaseTables_BASE_BASE;
// -------------------------------------------------------------------------
// XAppend
void SAL_CALL ODbaseTables::appendByDescriptor( const Reference< XPropertySet >& descriptor ) throw(SQLException, ElementExistException, RuntimeException)
{
::osl::MutexGuard aGuard(m_rMutex);
::rtl::OUString aName = getString(descriptor->getPropertyValue(PROPERTY_NAME));
ObjectMap::iterator aIter = m_aNameMap.find(aName);
if( aIter != m_aNameMap.end())
throw ElementExistException(aName,*this);
Reference<XUnoTunnel> xTunnel(descriptor,UNO_QUERY);
if(xTunnel.is())
{
ODbaseTable* pTable = (ODbaseTable*)xTunnel->getSomething(ODbaseTable::getUnoTunnelImplementationId());
if(pTable && pTable->CreateImpl())
ODbaseTables_BASE_BASE::appendByDescriptor(descriptor);
}
}
// -------------------------------------------------------------------------
// XDrop
void SAL_CALL ODbaseTables::dropByName( const ::rtl::OUString& elementName ) throw(SQLException, NoSuchElementException, RuntimeException)
{
::osl::MutexGuard aGuard(m_rMutex);
ObjectMap::iterator aIter = m_aNameMap.find(elementName);
if( aIter == m_aNameMap.end())
throw NoSuchElementException(elementName,*this);
Reference< XUnoTunnel> xTunnel(aIter->second.get(),UNO_QUERY);
if(xTunnel.is())
{
ODbaseTable* pTable = (ODbaseTable*)xTunnel->getSomething(ODbaseTable::getUnoTunnelImplementationId());
if(pTable && pTable->DropImpl())
ODbaseTables_BASE_BASE::dropByName(elementName);
}
}
// -------------------------------------------------------------------------
void SAL_CALL ODbaseTables::dropByIndex( sal_Int32 index ) throw(SQLException, IndexOutOfBoundsException, RuntimeException)
{
::osl::MutexGuard aGuard(m_rMutex);
if (index < 0 || index >= getCount())
throw IndexOutOfBoundsException();
dropByName((*m_aElements[index]).first);
}
// -------------------------------------------------------------------------
//------------------------------------------------------------------
Any SAL_CALL ODbaseTables::queryInterface( const Type & rType ) throw(RuntimeException)
{
typedef sdbcx::OCollection OTables_BASE;
return OTables_BASE::queryInterface(rType);
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "vcsmanager.h"
#include "iversioncontrol.h"
#include "icore.h"
#include "filemanager.h"
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <QtCore/QDir>
#include <QtCore/QString>
#include <QtCore/QList>
#include <QtCore/QMap>
#include <QtCore/QCoreApplication>
#include <QtCore/QFileInfo>
#include <QtGui/QMessageBox>
namespace Core {
typedef QList<IVersionControl *> VersionControlList;
static inline VersionControlList allVersionControls()
{
return ExtensionSystem::PluginManager::instance()->getObjects<IVersionControl>();
}
// ---- VCSManagerPrivate:
// Maintains a cache of top-level directory->version control.
class VcsManagerPrivate
{
public:
class VcsInfo {
public:
VcsInfo(IVersionControl *vc, const QString &tl) :
versionControl(vc), topLevel(tl)
{ }
bool operator == (const VcsInfo &other) const
{
return versionControl == other.versionControl &&
topLevel == other.topLevel;
}
IVersionControl *versionControl;
QString topLevel;
};
~VcsManagerPrivate()
{
qDeleteAll(m_vcsInfoList);
}
VcsInfo *findInCache(const QString &dir)
{
Q_ASSERT(QDir(dir).isAbsolute());
Q_ASSERT(!dir.endsWith(QLatin1Char('/')));
Q_ASSERT(QDir::fromNativeSeparators(dir) == dir);
const QMap<QString, VcsInfo *>::const_iterator it = m_cachedMatches.constFind(dir);
if (it != m_cachedMatches.constEnd())
return it.value();
return 0;
}
VcsInfo *findUpInCache(const QString &directory)
{
VcsInfo *result = 0;
const QChar slash = QLatin1Char('/');
// Split the path, trying to find the matching repository. We start from the reverse
// in order to detected nested repositories correctly (say, a git checkout under SVN).
for (int pos = directory.size() - 1; pos >= 0; pos = directory.lastIndexOf(slash, pos) - 1) {
const QString directoryPart = directory.left(pos);
result = findInCache(directoryPart);
if (result != 0)
break;
}
return result;
}
void resetCache(const QString &dir)
{
QTC_ASSERT(QDir(dir).isAbsolute(), return);
QTC_ASSERT(!dir.endsWith(QLatin1Char('/')), return);
QTC_ASSERT(QDir::fromNativeSeparators(dir) == dir, return);
const QString dirSlash = dir + QLatin1Char('/');
foreach (const QString &key, m_cachedMatches.keys()) {
if (key == dir || key.startsWith(dirSlash))
m_cachedMatches.remove(key);
}
}
void cache(IVersionControl *vc, const QString &topLevel, const QString &dir)
{
QTC_ASSERT(QDir(dir).isAbsolute(), return);
QTC_ASSERT(!dir.endsWith(QLatin1Char('/')), return);
QTC_ASSERT(QDir::fromNativeSeparators(dir) == dir, return);
QTC_ASSERT(dir.startsWith(topLevel + QLatin1Char('/')) || topLevel == dir, return);
VcsInfo *newInfo = new VcsInfo(vc, topLevel);
bool createdNewInfo(true);
// Do we have a matching VcsInfo already?
foreach(VcsInfo *i, m_vcsInfoList) {
if (*i == *newInfo) {
delete newInfo;
newInfo = i;
createdNewInfo = false;
break;
}
}
if (createdNewInfo)
m_vcsInfoList.append(newInfo);
QString tmpDir = dir;
const QChar slash = QLatin1Char('/');
while (tmpDir.count() >= topLevel.count() && tmpDir.count() > 0) {
m_cachedMatches.insert(tmpDir, newInfo);
const int slashPos = tmpDir.lastIndexOf(slash);
if (slashPos >= 0) {
tmpDir.truncate(slashPos);
} else {
tmpDir.clear();
}
}
}
QMap<QString, VcsInfo *> m_cachedMatches;
QList<VcsInfo *> m_vcsInfoList;
};
VcsManager::VcsManager(QObject *parent) :
QObject(parent),
d(new VcsManagerPrivate)
{
}
// ---- VCSManager:
VcsManager::~VcsManager()
{
delete d;
}
void VcsManager::extensionsInitialized()
{
// Change signal connections
FileManager *fileManager = ICore::instance()->fileManager();
foreach (IVersionControl *versionControl, allVersionControls()) {
connect(versionControl, SIGNAL(filesChanged(QStringList)),
fileManager, SIGNAL(filesChangedInternally(QStringList)));
connect(versionControl, SIGNAL(repositoryChanged(QString)),
this, SIGNAL(repositoryChanged(QString)));
}
}
static bool longerThanPath(QPair<QString, IVersionControl *> &pair1, QPair<QString, IVersionControl *> &pair2)
{
return pair1.first.size() > pair2.first.size();
}
void VcsManager::resetVersionControlForDirectory(const QString &inputDirectory)
{
if (inputDirectory.isEmpty())
return;
const QString directory = QDir(inputDirectory).absolutePath();
d->resetCache(directory);
emit repositoryChanged(directory);
}
IVersionControl* VcsManager::findVersionControlForDirectory(const QString &inputDirectory,
QString *topLevelDirectory)
{
typedef QPair<QString, IVersionControl *> StringVersionControlPair;
typedef QList<StringVersionControlPair> StringVersionControlPairs;
if (inputDirectory.isEmpty())
return 0;
// Make sure we a clean absolute path:
const QString directory = QDir(inputDirectory).absolutePath();
VcsManagerPrivate::VcsInfo *cachedData = d->findInCache(directory);
if (cachedData) {
if (topLevelDirectory)
*topLevelDirectory = cachedData->topLevel;
return cachedData->versionControl;
}
// Nothing: ask the IVersionControls directly.
const VersionControlList versionControls = allVersionControls();
StringVersionControlPairs allThatCanManage;
foreach (IVersionControl * versionControl, versionControls) {
QString topLevel;
if (versionControl->managesDirectory(directory, &topLevel))
allThatCanManage.push_back(StringVersionControlPair(topLevel, versionControl));
}
// To properly find a nested repository (say, git checkout inside SVN),
// we need to select the version control with the longest toplevel pathname.
qSort(allThatCanManage.begin(), allThatCanManage.end(), longerThanPath);
if (allThatCanManage.isEmpty()) {
d->cache(0, QString(), directory); // register that nothing was found!
// report result;
if (topLevelDirectory)
topLevelDirectory->clear();
return 0;
}
// Register Vcs(s) with the cache
QString tmpDir = directory;
const QChar slash = QLatin1Char('/');
const StringVersionControlPairs::const_iterator cend = allThatCanManage.constEnd();
for (StringVersionControlPairs::const_iterator i = allThatCanManage.constBegin(); i != cend; ++i) {
d->cache(i->second, i->first, tmpDir);
tmpDir = i->first;
const int slashPos = tmpDir.lastIndexOf(slash);
if (slashPos >= 0)
tmpDir.truncate(slashPos);
}
// return result
if (topLevelDirectory)
*topLevelDirectory = allThatCanManage.first().first;
return allThatCanManage.first().second;
}
bool VcsManager::promptToDelete(const QString &fileName)
{
if (IVersionControl *vc = findVersionControlForDirectory(QFileInfo(fileName).absolutePath()))
return promptToDelete(vc, fileName);
return true;
}
IVersionControl *VcsManager::checkout(const QString &versionControlType,
const QString &directory,
const QByteArray &url)
{
foreach (IVersionControl *versionControl, allVersionControls()) {
if (versionControl->displayName() == versionControlType
&& versionControl->supportsOperation(Core::IVersionControl::CheckoutOperation)) {
if (versionControl->vcsCheckout(directory, url)) {
d->cache(versionControl, directory, directory);
return versionControl;
}
return 0;
}
}
return 0;
}
bool VcsManager::findVersionControl(const QString &versionControlType)
{
foreach (IVersionControl * versionControl, allVersionControls()) {
if (versionControl->displayName() == versionControlType)
return true;
}
return false;
}
QString VcsManager::repositoryUrl(const QString &directory)
{
IVersionControl *vc = findVersionControlForDirectory(directory);
if (vc && vc->supportsOperation(Core::IVersionControl::GetRepositoryRootOperation))
return vc->vcsGetRepositoryURL(directory);
return QString();
}
bool VcsManager::promptToDelete(IVersionControl *vc, const QString &fileName)
{
QTC_ASSERT(vc, return true)
if (!vc->supportsOperation(IVersionControl::DeleteOperation))
return true;
const QString title = tr("Version Control");
const QString msg = tr("Would you like to remove this file from the version control system (%1)?\n"
"Note: This might remove the local file.").arg(vc->displayName());
const QMessageBox::StandardButton button =
QMessageBox::question(0, title, msg, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
if (button != QMessageBox::Yes)
return true;
return vc->vcsDelete(fileName);
}
} // namespace Core
<commit_msg>vcs: better sanity checking<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "vcsmanager.h"
#include "iversioncontrol.h"
#include "icore.h"
#include "filemanager.h"
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <QtCore/QDir>
#include <QtCore/QString>
#include <QtCore/QList>
#include <QtCore/QMap>
#include <QtCore/QCoreApplication>
#include <QtCore/QFileInfo>
#include <QtGui/QMessageBox>
namespace Core {
typedef QList<IVersionControl *> VersionControlList;
static inline VersionControlList allVersionControls()
{
return ExtensionSystem::PluginManager::instance()->getObjects<IVersionControl>();
}
// ---- VCSManagerPrivate:
// Maintains a cache of top-level directory->version control.
class VcsManagerPrivate
{
public:
class VcsInfo {
public:
VcsInfo(IVersionControl *vc, const QString &tl) :
versionControl(vc), topLevel(tl)
{ }
bool operator == (const VcsInfo &other) const
{
return versionControl == other.versionControl &&
topLevel == other.topLevel;
}
IVersionControl *versionControl;
QString topLevel;
};
~VcsManagerPrivate()
{
qDeleteAll(m_vcsInfoList);
}
VcsInfo *findInCache(const QString &dir)
{
Q_ASSERT(QDir(dir).isAbsolute());
Q_ASSERT(!dir.endsWith(QLatin1Char('/')));
Q_ASSERT(QDir::fromNativeSeparators(dir) == dir);
const QMap<QString, VcsInfo *>::const_iterator it = m_cachedMatches.constFind(dir);
if (it != m_cachedMatches.constEnd())
return it.value();
return 0;
}
VcsInfo *findUpInCache(const QString &directory)
{
VcsInfo *result = 0;
const QChar slash = QLatin1Char('/');
// Split the path, trying to find the matching repository. We start from the reverse
// in order to detected nested repositories correctly (say, a git checkout under SVN).
for (int pos = directory.size() - 1; pos >= 0; pos = directory.lastIndexOf(slash, pos) - 1) {
const QString directoryPart = directory.left(pos);
result = findInCache(directoryPart);
if (result != 0)
break;
}
return result;
}
void resetCache(const QString &dir)
{
QTC_ASSERT(QDir(dir).isAbsolute(), return);
QTC_ASSERT(!dir.endsWith(QLatin1Char('/')), return);
QTC_ASSERT(QDir::fromNativeSeparators(dir) == dir, return);
const QString dirSlash = dir + QLatin1Char('/');
foreach (const QString &key, m_cachedMatches.keys()) {
if (key == dir || key.startsWith(dirSlash))
m_cachedMatches.remove(key);
}
}
void cache(IVersionControl *vc, const QString &topLevel, const QString &dir)
{
QTC_ASSERT(QDir(dir).isAbsolute(), return);
QTC_ASSERT(!dir.endsWith(QLatin1Char('/')), return);
QTC_ASSERT(QDir::fromNativeSeparators(dir) == dir, return);
QTC_ASSERT(dir.startsWith(topLevel + QLatin1Char('/'))
|| topLevel == dir || topLevel.isEmpty(), return);
QTC_ASSERT((topLevel.isEmpty() && !vc) || (!topLevel.isEmpty() && vc), return);
VcsInfo *newInfo = new VcsInfo(vc, topLevel);
bool createdNewInfo(true);
// Do we have a matching VcsInfo already?
foreach(VcsInfo *i, m_vcsInfoList) {
if (*i == *newInfo) {
delete newInfo;
newInfo = i;
createdNewInfo = false;
break;
}
}
if (createdNewInfo)
m_vcsInfoList.append(newInfo);
QString tmpDir = dir;
const QChar slash = QLatin1Char('/');
while (tmpDir.count() >= topLevel.count() && tmpDir.count() > 0) {
m_cachedMatches.insert(tmpDir, newInfo);
const int slashPos = tmpDir.lastIndexOf(slash);
if (slashPos >= 0) {
tmpDir.truncate(slashPos);
} else {
tmpDir.clear();
}
}
}
QMap<QString, VcsInfo *> m_cachedMatches;
QList<VcsInfo *> m_vcsInfoList;
};
VcsManager::VcsManager(QObject *parent) :
QObject(parent),
d(new VcsManagerPrivate)
{
}
// ---- VCSManager:
VcsManager::~VcsManager()
{
delete d;
}
void VcsManager::extensionsInitialized()
{
// Change signal connections
FileManager *fileManager = ICore::instance()->fileManager();
foreach (IVersionControl *versionControl, allVersionControls()) {
connect(versionControl, SIGNAL(filesChanged(QStringList)),
fileManager, SIGNAL(filesChangedInternally(QStringList)));
connect(versionControl, SIGNAL(repositoryChanged(QString)),
this, SIGNAL(repositoryChanged(QString)));
}
}
static bool longerThanPath(QPair<QString, IVersionControl *> &pair1, QPair<QString, IVersionControl *> &pair2)
{
return pair1.first.size() > pair2.first.size();
}
void VcsManager::resetVersionControlForDirectory(const QString &inputDirectory)
{
if (inputDirectory.isEmpty())
return;
const QString directory = QDir(inputDirectory).absolutePath();
d->resetCache(directory);
emit repositoryChanged(directory);
}
IVersionControl* VcsManager::findVersionControlForDirectory(const QString &inputDirectory,
QString *topLevelDirectory)
{
typedef QPair<QString, IVersionControl *> StringVersionControlPair;
typedef QList<StringVersionControlPair> StringVersionControlPairs;
if (inputDirectory.isEmpty())
return 0;
// Make sure we a clean absolute path:
const QString directory = QDir(inputDirectory).absolutePath();
VcsManagerPrivate::VcsInfo *cachedData = d->findInCache(directory);
if (cachedData) {
if (topLevelDirectory)
*topLevelDirectory = cachedData->topLevel;
return cachedData->versionControl;
}
// Nothing: ask the IVersionControls directly.
const VersionControlList versionControls = allVersionControls();
StringVersionControlPairs allThatCanManage;
foreach (IVersionControl * versionControl, versionControls) {
QString topLevel;
if (versionControl->managesDirectory(directory, &topLevel))
allThatCanManage.push_back(StringVersionControlPair(topLevel, versionControl));
}
// To properly find a nested repository (say, git checkout inside SVN),
// we need to select the version control with the longest toplevel pathname.
qSort(allThatCanManage.begin(), allThatCanManage.end(), longerThanPath);
if (allThatCanManage.isEmpty()) {
d->cache(0, QString(), directory); // register that nothing was found!
// report result;
if (topLevelDirectory)
topLevelDirectory->clear();
return 0;
}
// Register Vcs(s) with the cache
QString tmpDir = directory;
const QChar slash = QLatin1Char('/');
const StringVersionControlPairs::const_iterator cend = allThatCanManage.constEnd();
for (StringVersionControlPairs::const_iterator i = allThatCanManage.constBegin(); i != cend; ++i) {
d->cache(i->second, i->first, tmpDir);
tmpDir = i->first;
const int slashPos = tmpDir.lastIndexOf(slash);
if (slashPos >= 0)
tmpDir.truncate(slashPos);
}
// return result
if (topLevelDirectory)
*topLevelDirectory = allThatCanManage.first().first;
return allThatCanManage.first().second;
}
bool VcsManager::promptToDelete(const QString &fileName)
{
if (IVersionControl *vc = findVersionControlForDirectory(QFileInfo(fileName).absolutePath()))
return promptToDelete(vc, fileName);
return true;
}
IVersionControl *VcsManager::checkout(const QString &versionControlType,
const QString &directory,
const QByteArray &url)
{
foreach (IVersionControl *versionControl, allVersionControls()) {
if (versionControl->displayName() == versionControlType
&& versionControl->supportsOperation(Core::IVersionControl::CheckoutOperation)) {
if (versionControl->vcsCheckout(directory, url)) {
d->cache(versionControl, directory, directory);
return versionControl;
}
return 0;
}
}
return 0;
}
bool VcsManager::findVersionControl(const QString &versionControlType)
{
foreach (IVersionControl * versionControl, allVersionControls()) {
if (versionControl->displayName() == versionControlType)
return true;
}
return false;
}
QString VcsManager::repositoryUrl(const QString &directory)
{
IVersionControl *vc = findVersionControlForDirectory(directory);
if (vc && vc->supportsOperation(Core::IVersionControl::GetRepositoryRootOperation))
return vc->vcsGetRepositoryURL(directory);
return QString();
}
bool VcsManager::promptToDelete(IVersionControl *vc, const QString &fileName)
{
QTC_ASSERT(vc, return true)
if (!vc->supportsOperation(IVersionControl::DeleteOperation))
return true;
const QString title = tr("Version Control");
const QString msg = tr("Would you like to remove this file from the version control system (%1)?\n"
"Note: This might remove the local file.").arg(vc->displayName());
const QMessageBox::StandardButton button =
QMessageBox::question(0, title, msg, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
if (button != QMessageBox::Yes)
return true;
return vc->vcsDelete(fileName);
}
} // namespace Core
<|endoftext|> |
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.
// Implementation of Coefficient class
#include "fem.hpp"
#include <cmath>
#include <limits>
namespace mfem
{
using namespace std;
double PWConstCoefficient::Eval(ElementTransformation & T,
const IntegrationPoint & ip)
{
int att = T.Attribute;
return (constants(att-1));
}
double FunctionCoefficient::Eval(ElementTransformation & T,
const IntegrationPoint & ip)
{
double x[3];
Vector transip(x, 3);
T.Transform(ip, transip);
if (Function)
{
return ((*Function)(transip));
}
else
{
return (*TDFunction)(transip, GetTime());
}
}
double GridFunctionCoefficient::Eval (ElementTransformation &T,
const IntegrationPoint &ip)
{
return GridF -> GetValue (T.ElementNo, ip, Component);
}
double TransformedCoefficient::Eval(ElementTransformation &T,
const IntegrationPoint &ip)
{
if (Q2)
{
return (*Transform2)(Q1->Eval(T, ip, GetTime()),
Q2->Eval(T, ip, GetTime()));
}
else
{
return (*Transform1)(Q1->Eval(T, ip, GetTime()));
}
}
void DeltaCoefficient::SetDeltaCenter(const Vector& vcenter)
{
MFEM_VERIFY(vcenter.Size() <= 3,
"SetDeltaCenter::Maximum number of dim supported is 3")
for (int i = 0; i < vcenter.Size(); i++) { center[i] = vcenter[i]; }
sdim = vcenter.Size();
}
void DeltaCoefficient::GetDeltaCenter(Vector& vcenter)
{
vcenter.SetSize(sdim);
vcenter = center;
}
double DeltaCoefficient::EvalDelta(ElementTransformation &T,
const IntegrationPoint &ip)
{
double w = Scale();
return weight ? weight->Eval(T, ip, GetTime())*w : w;
}
void VectorCoefficient::Eval(DenseMatrix &M, ElementTransformation &T,
const IntegrationRule &ir)
{
Vector Mi;
M.SetSize(vdim, ir.GetNPoints());
for (int i = 0; i < ir.GetNPoints(); i++)
{
M.GetColumnReference(i, Mi);
const IntegrationPoint &ip = ir.IntPoint(i);
T.SetIntPoint(&ip);
Eval(Mi, T, ip);
}
}
void VectorFunctionCoefficient::Eval(Vector &V, ElementTransformation &T,
const IntegrationPoint &ip)
{
double x[3];
Vector transip(x, 3);
T.Transform(ip, transip);
V.SetSize(vdim);
if (Function)
{
(*Function)(transip, V);
}
else
{
(*TDFunction)(transip, GetTime(), V);
}
if (Q)
{
V *= Q->Eval(T, ip, GetTime());
}
}
VectorArrayCoefficient::VectorArrayCoefficient (int dim)
: VectorCoefficient(dim), Coeff(dim)
{
for (int i = 0; i < dim; i++)
{
Coeff[i] = NULL;
}
}
VectorArrayCoefficient::~VectorArrayCoefficient()
{
for (int i = 0; i < vdim; i++)
{
delete Coeff[i];
}
}
void VectorArrayCoefficient::Eval(Vector &V, ElementTransformation &T,
const IntegrationPoint &ip)
{
V.SetSize(vdim);
for (int i = 0; i < vdim; i++)
{
V(i) = this->Eval(i, T, ip);
}
}
VectorGridFunctionCoefficient::VectorGridFunctionCoefficient (
GridFunction *gf) : VectorCoefficient (gf -> VectorDim())
{
GridFunc = gf;
}
void VectorGridFunctionCoefficient::Eval(Vector &V, ElementTransformation &T,
const IntegrationPoint &ip)
{
GridFunc->GetVectorValue(T.ElementNo, ip, V);
}
void VectorGridFunctionCoefficient::Eval(
DenseMatrix &M, ElementTransformation &T, const IntegrationRule &ir)
{
GridFunc->GetVectorValues(T, ir, M);
}
void VectorDeltaCoefficient::SetDirection(const Vector &_d)
{
dir = _d;
(*this).vdim = dir.Size();
}
void VectorDeltaCoefficient::EvalDelta(
Vector &V, ElementTransformation &T, const IntegrationPoint &ip)
{
V = dir;
d.SetTime(GetTime());
V *= d.EvalDelta(T, ip);
}
void VectorRestrictedCoefficient::Eval(Vector &V, ElementTransformation &T,
const IntegrationPoint &ip)
{
V.SetSize(vdim);
if (active_attr[T.Attribute-1])
{
c->SetTime(GetTime());
c->Eval(V, T, ip);
}
else
{
V = 0.0;
}
}
void VectorRestrictedCoefficient::Eval(
DenseMatrix &M, ElementTransformation &T, const IntegrationRule &ir)
{
if (active_attr[T.Attribute-1])
{
c->SetTime(GetTime());
c->Eval(M, T, ir);
}
else
{
M.SetSize(vdim);
M = 0.0;
}
}
void MatrixFunctionCoefficient::Eval(DenseMatrix &K, ElementTransformation &T,
const IntegrationPoint &ip)
{
double x[3];
Vector transip(x, 3);
T.Transform(ip, transip);
K.SetSize(height, width);
if (Function)
{
(*Function)(transip, K);
}
else if (TDFunction)
{
(*TDFunction)(transip, GetTime(), K);
}
else
{
K = mat;
}
if (Q)
{
K *= Q->Eval(T, ip, GetTime());
}
}
MatrixArrayCoefficient::MatrixArrayCoefficient (int dim)
: MatrixCoefficient (dim)
{
Coeff.SetSize(height*width);
for (int i = 0; i < (height*width); i++)
{
Coeff[i] = NULL;
}
}
MatrixArrayCoefficient::~MatrixArrayCoefficient ()
{
for (int i=0; i < height*width; i++)
{
delete Coeff[i];
}
}
void MatrixArrayCoefficient::Eval(DenseMatrix &K, ElementTransformation &T,
const IntegrationPoint &ip)
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
K(i,j) = this->Eval(i, j, T, ip);
}
}
}
void MatrixRestrictedCoefficient::Eval(DenseMatrix &K, ElementTransformation &T,
const IntegrationPoint &ip)
{
if (active_attr[T.Attribute-1])
{
c->SetTime(GetTime());
c->Eval(K, T, ip);
}
else
{
K.SetSize(height, width);
K = 0.0;
}
}
double LpNormLoop(double p, Coefficient &coeff, Mesh &mesh,
const IntegrationRule *irs[])
{
double norm = 0.0;
ElementTransformation *tr;
for (int i = 0; i < mesh.GetNE(); i++)
{
tr = mesh.GetElementTransformation(i);
const IntegrationRule &ir = *irs[mesh.GetElementType(i)];
for (int j = 0; j < ir.GetNPoints(); j++)
{
const IntegrationPoint &ip = ir.IntPoint(j);
tr->SetIntPoint(&ip);
double val = fabs(coeff.Eval(*tr, ip));
if (p < infinity())
{
norm += ip.weight * tr->Weight() * pow(val, p);
}
else
{
if (norm < val)
{
norm = val;
}
}
}
}
return norm;
}
double LpNormLoop(double p, VectorCoefficient &coeff, Mesh &mesh,
const IntegrationRule *irs[])
{
double norm = 0.0;
ElementTransformation *tr;
int vdim = coeff.GetVDim();
Vector vval(vdim);
double val;
for (int i = 0; i < mesh.GetNE(); i++)
{
tr = mesh.GetElementTransformation(i);
const IntegrationRule &ir = *irs[mesh.GetElementType(i)];
for (int j = 0; j < ir.GetNPoints(); j++)
{
const IntegrationPoint &ip = ir.IntPoint(j);
tr->SetIntPoint(&ip);
coeff.Eval(vval, *tr, ip);
if (p < infinity())
{
for (int idim(0); idim < vdim; ++idim)
{
norm += ip.weight * tr->Weight() * pow(fabs( vval(idim) ), p);
}
}
else
{
for (int idim(0); idim < vdim; ++idim)
{
val = fabs(vval(idim));
if (norm < val)
{
norm = val;
}
}
}
}
}
return norm;
}
double ComputeLpNorm(double p, Coefficient &coeff, Mesh &mesh,
const IntegrationRule *irs[])
{
double norm = LpNormLoop(p, coeff, mesh, irs);
if (p < infinity())
{
// negative quadrature weights may cause norm to be negative
if (norm < 0.0)
{
norm = -pow(-norm, 1.0/p);
}
else
{
norm = pow(norm, 1.0/p);
}
}
return norm;
}
double ComputeLpNorm(double p, VectorCoefficient &coeff, Mesh &mesh,
const IntegrationRule *irs[])
{
double norm = LpNormLoop(p, coeff, mesh, irs);
if (p < infinity())
{
// negative quadrature weights may cause norm to be negative
if (norm < 0.0)
{
norm = -pow(-norm, 1.0/p);
}
else
{
norm = pow(norm, 1.0/p);
}
}
return norm;
}
#ifdef MFEM_USE_MPI
double ComputeGlobalLpNorm(double p, Coefficient &coeff, ParMesh &pmesh,
const IntegrationRule *irs[])
{
double loc_norm = LpNormLoop(p, coeff, pmesh, irs);
double glob_norm = 0;
MPI_Comm comm = pmesh.GetComm();
if (p < infinity())
{
MPI_Allreduce(&loc_norm, &glob_norm, 1, MPI_DOUBLE, MPI_SUM, comm);
// negative quadrature weights may cause norm to be negative
if (glob_norm < 0.0)
{
glob_norm = -pow(-glob_norm, 1.0/p);
}
else
{
glob_norm = pow(glob_norm, 1.0/p);
}
}
else
{
MPI_Allreduce(&loc_norm, &glob_norm, 1, MPI_DOUBLE, MPI_MAX, comm);
}
return glob_norm;
}
double ComputeGlobalLpNorm(double p, VectorCoefficient &coeff, ParMesh &pmesh,
const IntegrationRule *irs[])
{
double loc_norm = LpNormLoop(p, coeff, pmesh, irs);
double glob_norm = 0;
MPI_Comm comm = pmesh.GetComm();
if (p < infinity())
{
MPI_Allreduce(&loc_norm, &glob_norm, 1, MPI_DOUBLE, MPI_SUM, comm);
// negative quadrature weights may cause norm to be negative
if (glob_norm < 0.0)
{
glob_norm = -pow(-glob_norm, 1.0/p);
}
else
{
glob_norm = pow(glob_norm, 1.0/p);
}
}
else
{
MPI_Allreduce(&loc_norm, &glob_norm, 1, MPI_DOUBLE, MPI_MAX, comm);
}
return glob_norm;
}
#endif
}
<commit_msg>Fixed DenseMatrix::SetSize call argument<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.
// Implementation of Coefficient class
#include "fem.hpp"
#include <cmath>
#include <limits>
namespace mfem
{
using namespace std;
double PWConstCoefficient::Eval(ElementTransformation & T,
const IntegrationPoint & ip)
{
int att = T.Attribute;
return (constants(att-1));
}
double FunctionCoefficient::Eval(ElementTransformation & T,
const IntegrationPoint & ip)
{
double x[3];
Vector transip(x, 3);
T.Transform(ip, transip);
if (Function)
{
return ((*Function)(transip));
}
else
{
return (*TDFunction)(transip, GetTime());
}
}
double GridFunctionCoefficient::Eval (ElementTransformation &T,
const IntegrationPoint &ip)
{
return GridF -> GetValue (T.ElementNo, ip, Component);
}
double TransformedCoefficient::Eval(ElementTransformation &T,
const IntegrationPoint &ip)
{
if (Q2)
{
return (*Transform2)(Q1->Eval(T, ip, GetTime()),
Q2->Eval(T, ip, GetTime()));
}
else
{
return (*Transform1)(Q1->Eval(T, ip, GetTime()));
}
}
void DeltaCoefficient::SetDeltaCenter(const Vector& vcenter)
{
MFEM_VERIFY(vcenter.Size() <= 3,
"SetDeltaCenter::Maximum number of dim supported is 3")
for (int i = 0; i < vcenter.Size(); i++) { center[i] = vcenter[i]; }
sdim = vcenter.Size();
}
void DeltaCoefficient::GetDeltaCenter(Vector& vcenter)
{
vcenter.SetSize(sdim);
vcenter = center;
}
double DeltaCoefficient::EvalDelta(ElementTransformation &T,
const IntegrationPoint &ip)
{
double w = Scale();
return weight ? weight->Eval(T, ip, GetTime())*w : w;
}
void VectorCoefficient::Eval(DenseMatrix &M, ElementTransformation &T,
const IntegrationRule &ir)
{
Vector Mi;
M.SetSize(vdim, ir.GetNPoints());
for (int i = 0; i < ir.GetNPoints(); i++)
{
M.GetColumnReference(i, Mi);
const IntegrationPoint &ip = ir.IntPoint(i);
T.SetIntPoint(&ip);
Eval(Mi, T, ip);
}
}
void VectorFunctionCoefficient::Eval(Vector &V, ElementTransformation &T,
const IntegrationPoint &ip)
{
double x[3];
Vector transip(x, 3);
T.Transform(ip, transip);
V.SetSize(vdim);
if (Function)
{
(*Function)(transip, V);
}
else
{
(*TDFunction)(transip, GetTime(), V);
}
if (Q)
{
V *= Q->Eval(T, ip, GetTime());
}
}
VectorArrayCoefficient::VectorArrayCoefficient (int dim)
: VectorCoefficient(dim), Coeff(dim)
{
for (int i = 0; i < dim; i++)
{
Coeff[i] = NULL;
}
}
VectorArrayCoefficient::~VectorArrayCoefficient()
{
for (int i = 0; i < vdim; i++)
{
delete Coeff[i];
}
}
void VectorArrayCoefficient::Eval(Vector &V, ElementTransformation &T,
const IntegrationPoint &ip)
{
V.SetSize(vdim);
for (int i = 0; i < vdim; i++)
{
V(i) = this->Eval(i, T, ip);
}
}
VectorGridFunctionCoefficient::VectorGridFunctionCoefficient (
GridFunction *gf) : VectorCoefficient (gf -> VectorDim())
{
GridFunc = gf;
}
void VectorGridFunctionCoefficient::Eval(Vector &V, ElementTransformation &T,
const IntegrationPoint &ip)
{
GridFunc->GetVectorValue(T.ElementNo, ip, V);
}
void VectorGridFunctionCoefficient::Eval(
DenseMatrix &M, ElementTransformation &T, const IntegrationRule &ir)
{
GridFunc->GetVectorValues(T, ir, M);
}
void VectorDeltaCoefficient::SetDirection(const Vector &_d)
{
dir = _d;
(*this).vdim = dir.Size();
}
void VectorDeltaCoefficient::EvalDelta(
Vector &V, ElementTransformation &T, const IntegrationPoint &ip)
{
V = dir;
d.SetTime(GetTime());
V *= d.EvalDelta(T, ip);
}
void VectorRestrictedCoefficient::Eval(Vector &V, ElementTransformation &T,
const IntegrationPoint &ip)
{
V.SetSize(vdim);
if (active_attr[T.Attribute-1])
{
c->SetTime(GetTime());
c->Eval(V, T, ip);
}
else
{
V = 0.0;
}
}
void VectorRestrictedCoefficient::Eval(
DenseMatrix &M, ElementTransformation &T, const IntegrationRule &ir)
{
if (active_attr[T.Attribute-1])
{
c->SetTime(GetTime());
c->Eval(M, T, ir);
}
else
{
M.SetSize(vdim, ir.GetNPoints());
M = 0.0;
}
}
void MatrixFunctionCoefficient::Eval(DenseMatrix &K, ElementTransformation &T,
const IntegrationPoint &ip)
{
double x[3];
Vector transip(x, 3);
T.Transform(ip, transip);
K.SetSize(height, width);
if (Function)
{
(*Function)(transip, K);
}
else if (TDFunction)
{
(*TDFunction)(transip, GetTime(), K);
}
else
{
K = mat;
}
if (Q)
{
K *= Q->Eval(T, ip, GetTime());
}
}
MatrixArrayCoefficient::MatrixArrayCoefficient (int dim)
: MatrixCoefficient (dim)
{
Coeff.SetSize(height*width);
for (int i = 0; i < (height*width); i++)
{
Coeff[i] = NULL;
}
}
MatrixArrayCoefficient::~MatrixArrayCoefficient ()
{
for (int i=0; i < height*width; i++)
{
delete Coeff[i];
}
}
void MatrixArrayCoefficient::Eval(DenseMatrix &K, ElementTransformation &T,
const IntegrationPoint &ip)
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
K(i,j) = this->Eval(i, j, T, ip);
}
}
}
void MatrixRestrictedCoefficient::Eval(DenseMatrix &K, ElementTransformation &T,
const IntegrationPoint &ip)
{
if (active_attr[T.Attribute-1])
{
c->SetTime(GetTime());
c->Eval(K, T, ip);
}
else
{
K.SetSize(height, width);
K = 0.0;
}
}
double LpNormLoop(double p, Coefficient &coeff, Mesh &mesh,
const IntegrationRule *irs[])
{
double norm = 0.0;
ElementTransformation *tr;
for (int i = 0; i < mesh.GetNE(); i++)
{
tr = mesh.GetElementTransformation(i);
const IntegrationRule &ir = *irs[mesh.GetElementType(i)];
for (int j = 0; j < ir.GetNPoints(); j++)
{
const IntegrationPoint &ip = ir.IntPoint(j);
tr->SetIntPoint(&ip);
double val = fabs(coeff.Eval(*tr, ip));
if (p < infinity())
{
norm += ip.weight * tr->Weight() * pow(val, p);
}
else
{
if (norm < val)
{
norm = val;
}
}
}
}
return norm;
}
double LpNormLoop(double p, VectorCoefficient &coeff, Mesh &mesh,
const IntegrationRule *irs[])
{
double norm = 0.0;
ElementTransformation *tr;
int vdim = coeff.GetVDim();
Vector vval(vdim);
double val;
for (int i = 0; i < mesh.GetNE(); i++)
{
tr = mesh.GetElementTransformation(i);
const IntegrationRule &ir = *irs[mesh.GetElementType(i)];
for (int j = 0; j < ir.GetNPoints(); j++)
{
const IntegrationPoint &ip = ir.IntPoint(j);
tr->SetIntPoint(&ip);
coeff.Eval(vval, *tr, ip);
if (p < infinity())
{
for (int idim(0); idim < vdim; ++idim)
{
norm += ip.weight * tr->Weight() * pow(fabs( vval(idim) ), p);
}
}
else
{
for (int idim(0); idim < vdim; ++idim)
{
val = fabs(vval(idim));
if (norm < val)
{
norm = val;
}
}
}
}
}
return norm;
}
double ComputeLpNorm(double p, Coefficient &coeff, Mesh &mesh,
const IntegrationRule *irs[])
{
double norm = LpNormLoop(p, coeff, mesh, irs);
if (p < infinity())
{
// negative quadrature weights may cause norm to be negative
if (norm < 0.0)
{
norm = -pow(-norm, 1.0/p);
}
else
{
norm = pow(norm, 1.0/p);
}
}
return norm;
}
double ComputeLpNorm(double p, VectorCoefficient &coeff, Mesh &mesh,
const IntegrationRule *irs[])
{
double norm = LpNormLoop(p, coeff, mesh, irs);
if (p < infinity())
{
// negative quadrature weights may cause norm to be negative
if (norm < 0.0)
{
norm = -pow(-norm, 1.0/p);
}
else
{
norm = pow(norm, 1.0/p);
}
}
return norm;
}
#ifdef MFEM_USE_MPI
double ComputeGlobalLpNorm(double p, Coefficient &coeff, ParMesh &pmesh,
const IntegrationRule *irs[])
{
double loc_norm = LpNormLoop(p, coeff, pmesh, irs);
double glob_norm = 0;
MPI_Comm comm = pmesh.GetComm();
if (p < infinity())
{
MPI_Allreduce(&loc_norm, &glob_norm, 1, MPI_DOUBLE, MPI_SUM, comm);
// negative quadrature weights may cause norm to be negative
if (glob_norm < 0.0)
{
glob_norm = -pow(-glob_norm, 1.0/p);
}
else
{
glob_norm = pow(glob_norm, 1.0/p);
}
}
else
{
MPI_Allreduce(&loc_norm, &glob_norm, 1, MPI_DOUBLE, MPI_MAX, comm);
}
return glob_norm;
}
double ComputeGlobalLpNorm(double p, VectorCoefficient &coeff, ParMesh &pmesh,
const IntegrationRule *irs[])
{
double loc_norm = LpNormLoop(p, coeff, pmesh, irs);
double glob_norm = 0;
MPI_Comm comm = pmesh.GetComm();
if (p < infinity())
{
MPI_Allreduce(&loc_norm, &glob_norm, 1, MPI_DOUBLE, MPI_SUM, comm);
// negative quadrature weights may cause norm to be negative
if (glob_norm < 0.0)
{
glob_norm = -pow(-glob_norm, 1.0/p);
}
else
{
glob_norm = pow(glob_norm, 1.0/p);
}
}
else
{
MPI_Allreduce(&loc_norm, &glob_norm, 1, MPI_DOUBLE, MPI_MAX, comm);
}
return glob_norm;
}
#endif
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "diffeditor.h"
#include "diffeditorfile.h"
#include "diffeditorwidget.h"
#include "diffeditorconstants.h"
#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
#include <QCoreApplication>
#include <QToolButton>
#include <QSpinBox>
#include <QStyle>
#include <QLabel>
#include <QHBoxLayout>
#include <QToolBar>
#include <QComboBox>
#include <QFileInfo>
namespace DiffEditor {
///////////////////////////////// DiffEditor //////////////////////////////////
DiffEditor::DiffEditor(DiffEditorWidget *editorWidget)
: IEditor(0),
m_file(new Internal::DiffEditorFile(QLatin1String(Constants::DIFF_EDITOR_MIMETYPE), this)),
m_editorWidget(editorWidget),
m_toolWidget(0),
m_entriesComboBox(0)
{
setWidget(editorWidget);
connect(m_editorWidget, SIGNAL(navigatedToDiffFile(int)),
this, SLOT(activateEntry(int)));
}
DiffEditor::~DiffEditor()
{
delete m_toolWidget;
if (m_widget)
delete m_widget;
}
bool DiffEditor::createNew(const QString &contents)
{
Q_UNUSED(contents)
return true;
}
bool DiffEditor::open(QString *errorString, const QString &fileName, const QString &realFileName)
{
Q_UNUSED(errorString)
Q_UNUSED(fileName)
Q_UNUSED(realFileName)
return true;
}
Core::IDocument *DiffEditor::document()
{
return m_file;
}
QString DiffEditor::displayName() const
{
if (m_displayName.isEmpty())
m_displayName = QCoreApplication::translate("DiffEditor", Constants::DIFF_EDITOR_DISPLAY_NAME);
return m_displayName;
}
void DiffEditor::setDisplayName(const QString &title)
{
m_displayName = title;
emit changed();
}
Core::Id DiffEditor::id() const
{
return Constants::DIFF_EDITOR_ID;
}
static QToolBar *createToolBar(const QWidget *someWidget)
{
// Create
QToolBar *toolBar = new QToolBar;
toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
const int size = someWidget->style()->pixelMetric(QStyle::PM_SmallIconSize);
toolBar->setIconSize(QSize(size, size));
return toolBar;
}
QWidget *DiffEditor::toolBar()
{
if (m_toolWidget)
return m_toolWidget;
// Create
m_toolWidget = createToolBar(m_editorWidget);
m_entriesComboBox = new QComboBox;
m_entriesComboBox->setMinimumContentsLength(20);
// Make the combo box prefer to expand
QSizePolicy policy = m_entriesComboBox->sizePolicy();
policy.setHorizontalPolicy(QSizePolicy::Expanding);
m_entriesComboBox->setSizePolicy(policy);
connect(m_entriesComboBox, SIGNAL(activated(int)),
this, SLOT(entryActivated(int)));
m_toolWidget->addWidget(m_entriesComboBox);
QToolButton *whitespaceButton = new QToolButton(m_toolWidget);
whitespaceButton->setText(tr("Ignore Whitespace"));
whitespaceButton->setCheckable(true);
whitespaceButton->setChecked(true);
connect(whitespaceButton, SIGNAL(clicked(bool)),
m_editorWidget, SLOT(setIgnoreWhitespaces(bool)));
m_toolWidget->addWidget(whitespaceButton);
QLabel *contextLabel = new QLabel(m_toolWidget);
contextLabel->setText(tr("Context Lines:"));
contextLabel->setMargin(6);
m_toolWidget->addWidget(contextLabel);
QSpinBox *contextSpinBox = new QSpinBox(m_toolWidget);
contextSpinBox->setRange(-1, 100);
contextSpinBox->setValue(3);
contextSpinBox->setFrame(false);
connect(contextSpinBox, SIGNAL(valueChanged(int)),
m_editorWidget, SLOT(setContextLinesNumber(int)));
m_toolWidget->addWidget(contextSpinBox);
QToolButton *toggleSync = new QToolButton(m_toolWidget);
toggleSync->setIcon(QIcon(QLatin1String(Core::Constants::ICON_LINK)));
toggleSync->setCheckable(true);
toggleSync->setChecked(true);
toggleSync->setToolTip(tr("Synchronize Horizontal Scroll Bars"));
connect(toggleSync, SIGNAL(clicked(bool)),
m_editorWidget, SLOT(setHorizontalScrollBarSynchronization(bool)));
m_toolWidget->addWidget(toggleSync);
return m_toolWidget;
}
void DiffEditor::setDiff(const QList<DiffEditorWidget::DiffFilesContents> &diffFileList,
const QString &workingDirectory)
{
m_entriesComboBox->clear();
const int count = diffFileList.count();
for (int i = 0; i < count; i++) {
const DiffEditorWidget::DiffFileInfo leftEntry = diffFileList.at(i).leftFileInfo;
const DiffEditorWidget::DiffFileInfo rightEntry = diffFileList.at(i).rightFileInfo;
const QString leftShortFileName = QFileInfo(leftEntry.fileName).fileName();
const QString rightShortFileName = QFileInfo(rightEntry.fileName).fileName();
QString itemText;
QString itemToolTip;
if (leftEntry.fileName == rightEntry.fileName) {
itemText = leftShortFileName;
if (leftEntry.typeInfo.isEmpty() && rightEntry.typeInfo.isEmpty()) {
itemToolTip = leftEntry.fileName;
} else {
itemToolTip = tr("[%1] vs. [%2] %3")
.arg(leftEntry.typeInfo, rightEntry.typeInfo, leftEntry.fileName);
}
} else {
if (leftShortFileName == rightShortFileName) {
itemText = leftShortFileName;
} else {
itemText = tr("%1 vs. %2")
.arg(leftShortFileName, rightShortFileName);
}
if (leftEntry.typeInfo.isEmpty() && rightEntry.typeInfo.isEmpty()) {
itemToolTip = tr("%1 vs. %2")
.arg(leftEntry.fileName, rightEntry.fileName);
} else {
itemToolTip = tr("[%1] %2 vs. [%3] %4")
.arg(leftEntry.typeInfo, leftEntry.fileName, rightEntry.typeInfo, rightEntry.fileName);
}
}
m_entriesComboBox->addItem(itemText);
m_entriesComboBox->setItemData(m_entriesComboBox->count() - 1, itemToolTip, Qt::ToolTipRole);
}
updateEntryToolTip();
m_editorWidget->setDiff(diffFileList, workingDirectory);
}
void DiffEditor::clear(const QString &message)
{
m_entriesComboBox->clear();
updateEntryToolTip();
m_editorWidget->clear(message);
}
void DiffEditor::updateEntryToolTip()
{
const QString &toolTip = m_entriesComboBox->itemData(
m_entriesComboBox->currentIndex(), Qt::ToolTipRole).toString();
m_entriesComboBox->setToolTip(toolTip);
}
void DiffEditor::entryActivated(int index)
{
updateEntryToolTip();
m_editorWidget->navigateToDiffFile(index);
}
void DiffEditor::activateEntry(int index)
{
m_entriesComboBox->blockSignals(true);
m_entriesComboBox->setCurrentIndex(index);
m_entriesComboBox->blockSignals(false);
updateEntryToolTip();
}
} // namespace DiffEditor
<commit_msg>DiffEditor: Fix context lines spin box layout.<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "diffeditor.h"
#include "diffeditorfile.h"
#include "diffeditorwidget.h"
#include "diffeditorconstants.h"
#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
#include <QCoreApplication>
#include <QToolButton>
#include <QSpinBox>
#include <QStyle>
#include <QLabel>
#include <QHBoxLayout>
#include <QToolBar>
#include <QComboBox>
#include <QFileInfo>
namespace DiffEditor {
///////////////////////////////// DiffEditor //////////////////////////////////
DiffEditor::DiffEditor(DiffEditorWidget *editorWidget)
: IEditor(0),
m_file(new Internal::DiffEditorFile(QLatin1String(Constants::DIFF_EDITOR_MIMETYPE), this)),
m_editorWidget(editorWidget),
m_toolWidget(0),
m_entriesComboBox(0)
{
setWidget(editorWidget);
connect(m_editorWidget, SIGNAL(navigatedToDiffFile(int)),
this, SLOT(activateEntry(int)));
}
DiffEditor::~DiffEditor()
{
delete m_toolWidget;
if (m_widget)
delete m_widget;
}
bool DiffEditor::createNew(const QString &contents)
{
Q_UNUSED(contents)
return true;
}
bool DiffEditor::open(QString *errorString, const QString &fileName, const QString &realFileName)
{
Q_UNUSED(errorString)
Q_UNUSED(fileName)
Q_UNUSED(realFileName)
return true;
}
Core::IDocument *DiffEditor::document()
{
return m_file;
}
QString DiffEditor::displayName() const
{
if (m_displayName.isEmpty())
m_displayName = QCoreApplication::translate("DiffEditor", Constants::DIFF_EDITOR_DISPLAY_NAME);
return m_displayName;
}
void DiffEditor::setDisplayName(const QString &title)
{
m_displayName = title;
emit changed();
}
Core::Id DiffEditor::id() const
{
return Constants::DIFF_EDITOR_ID;
}
static QToolBar *createToolBar(const QWidget *someWidget)
{
// Create
QToolBar *toolBar = new QToolBar;
toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
const int size = someWidget->style()->pixelMetric(QStyle::PM_SmallIconSize);
toolBar->setIconSize(QSize(size, size));
return toolBar;
}
QWidget *DiffEditor::toolBar()
{
if (m_toolWidget)
return m_toolWidget;
// Create
m_toolWidget = createToolBar(m_editorWidget);
m_entriesComboBox = new QComboBox;
m_entriesComboBox->setMinimumContentsLength(20);
// Make the combo box prefer to expand
QSizePolicy policy = m_entriesComboBox->sizePolicy();
policy.setHorizontalPolicy(QSizePolicy::Expanding);
m_entriesComboBox->setSizePolicy(policy);
connect(m_entriesComboBox, SIGNAL(activated(int)),
this, SLOT(entryActivated(int)));
m_toolWidget->addWidget(m_entriesComboBox);
QToolButton *whitespaceButton = new QToolButton(m_toolWidget);
whitespaceButton->setText(tr("Ignore Whitespace"));
whitespaceButton->setCheckable(true);
whitespaceButton->setChecked(true);
connect(whitespaceButton, SIGNAL(clicked(bool)),
m_editorWidget, SLOT(setIgnoreWhitespaces(bool)));
m_toolWidget->addWidget(whitespaceButton);
QLabel *contextLabel = new QLabel(m_toolWidget);
contextLabel->setText(tr("Context Lines:"));
contextLabel->setContentsMargins(6, 0, 6, 0);
m_toolWidget->addWidget(contextLabel);
QSpinBox *contextSpinBox = new QSpinBox(m_toolWidget);
contextSpinBox->setRange(-1, 100);
contextSpinBox->setValue(3);
contextSpinBox->setFrame(false);
contextSpinBox->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding); // Mac Qt5
connect(contextSpinBox, SIGNAL(valueChanged(int)),
m_editorWidget, SLOT(setContextLinesNumber(int)));
m_toolWidget->addWidget(contextSpinBox);
QToolButton *toggleSync = new QToolButton(m_toolWidget);
toggleSync->setIcon(QIcon(QLatin1String(Core::Constants::ICON_LINK)));
toggleSync->setCheckable(true);
toggleSync->setChecked(true);
toggleSync->setToolTip(tr("Synchronize Horizontal Scroll Bars"));
connect(toggleSync, SIGNAL(clicked(bool)),
m_editorWidget, SLOT(setHorizontalScrollBarSynchronization(bool)));
m_toolWidget->addWidget(toggleSync);
return m_toolWidget;
}
void DiffEditor::setDiff(const QList<DiffEditorWidget::DiffFilesContents> &diffFileList,
const QString &workingDirectory)
{
m_entriesComboBox->clear();
const int count = diffFileList.count();
for (int i = 0; i < count; i++) {
const DiffEditorWidget::DiffFileInfo leftEntry = diffFileList.at(i).leftFileInfo;
const DiffEditorWidget::DiffFileInfo rightEntry = diffFileList.at(i).rightFileInfo;
const QString leftShortFileName = QFileInfo(leftEntry.fileName).fileName();
const QString rightShortFileName = QFileInfo(rightEntry.fileName).fileName();
QString itemText;
QString itemToolTip;
if (leftEntry.fileName == rightEntry.fileName) {
itemText = leftShortFileName;
if (leftEntry.typeInfo.isEmpty() && rightEntry.typeInfo.isEmpty()) {
itemToolTip = leftEntry.fileName;
} else {
itemToolTip = tr("[%1] vs. [%2] %3")
.arg(leftEntry.typeInfo, rightEntry.typeInfo, leftEntry.fileName);
}
} else {
if (leftShortFileName == rightShortFileName) {
itemText = leftShortFileName;
} else {
itemText = tr("%1 vs. %2")
.arg(leftShortFileName, rightShortFileName);
}
if (leftEntry.typeInfo.isEmpty() && rightEntry.typeInfo.isEmpty()) {
itemToolTip = tr("%1 vs. %2")
.arg(leftEntry.fileName, rightEntry.fileName);
} else {
itemToolTip = tr("[%1] %2 vs. [%3] %4")
.arg(leftEntry.typeInfo, leftEntry.fileName, rightEntry.typeInfo, rightEntry.fileName);
}
}
m_entriesComboBox->addItem(itemText);
m_entriesComboBox->setItemData(m_entriesComboBox->count() - 1, itemToolTip, Qt::ToolTipRole);
}
updateEntryToolTip();
m_editorWidget->setDiff(diffFileList, workingDirectory);
}
void DiffEditor::clear(const QString &message)
{
m_entriesComboBox->clear();
updateEntryToolTip();
m_editorWidget->clear(message);
}
void DiffEditor::updateEntryToolTip()
{
const QString &toolTip = m_entriesComboBox->itemData(
m_entriesComboBox->currentIndex(), Qt::ToolTipRole).toString();
m_entriesComboBox->setToolTip(toolTip);
}
void DiffEditor::entryActivated(int index)
{
updateEntryToolTip();
m_editorWidget->navigateToDiffFile(index);
}
void DiffEditor::activateEntry(int index)
{
m_entriesComboBox->blockSignals(true);
m_entriesComboBox->setCurrentIndex(index);
m_entriesComboBox->blockSignals(false);
updateEntryToolTip();
}
} // namespace DiffEditor
<|endoftext|> |
<commit_before>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** 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 chemkit project nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
******************************************************************************/
#include "inchilineformat.h"
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include "../../3rdparty/inchi/inchi_api.h"
#include <chemkit/atom.h>
#include <chemkit/bond.h>
#include <chemkit/foreach.h>
InchiLineFormat::InchiLineFormat()
: chemkit::LineFormat("inchi")
{
}
bool InchiLineFormat::read(const std::string &formula, chemkit::Molecule *molecule)
{
// verify formula
if(formula.empty()){
return 0;
}
std::string formulaString = formula;
// add `InChI=` to the start if it is not there
if(!boost::starts_with(formula, "InChI=")){
formulaString = "InChI=" + formulaString;
}
// setup input struct
inchi_InputINCHI input;
input.szInChI = const_cast<char *>(formulaString.c_str());
input.szOptions = 0;
// get inchi output
inchi_OutputStruct output;
int ret = GetStructFromStdINCHI(&input, &output);
CHEMKIT_UNUSED(ret);
// add atoms
for(int i = 0; i < output.num_atoms; i++){
molecule->addAtom(output.atom[i].elname);
}
// add bonds
for(int i = 0; i < output.num_atoms; i++){
inchi_Atom *inchiAtom = &output.atom[i];
for(int j = 0; j < inchiAtom->num_bonds; j++){
molecule->addBond(i, inchiAtom->neighbor[j], inchiAtom->bond_type[j]);
}
}
// add implicit hydrogens (if enabled)
bool addHydrogens = option("add-implicit-hydrogens").toBool();
if(addHydrogens){
for(int i = 0; i < output.num_atoms; i++){
chemkit::Atom *atom = molecule->atom(i);
inchi_Atom *inchiAtom = &output.atom[i];
for(int j = 0; j < inchiAtom->num_iso_H[0]; j++){
chemkit::Atom *hydrogen = molecule->addAtom(chemkit::Atom::Hydrogen);
molecule->addBond(atom, hydrogen);
}
}
}
// free output structure
FreeStructFromStdINCHI(&output);
return true;
}
std::string InchiLineFormat::write(const chemkit::Molecule *molecule)
{
// check for valid molecule
if(molecule->atomCount() > 1024){
setErrorString("InChI does not support molecules with more that 1024 atoms.");
return std::string();
}
// setup inchi input structure
inchi_Input input;
input.atom = new inchi_Atom[molecule->atomCount()];
input.stereo0D = 0;
input.szOptions = 0;
input.num_atoms = molecule->atomCount();
input.num_stereo0D = 0;
inchi_Atom *inputAtom = &input.atom[0];
std::vector<const chemkit::Atom *> chiralAtoms;
foreach(const chemkit::Atom *atom, molecule->atoms()){
// coordinates
inputAtom->x = 0;
inputAtom->y = 0;
inputAtom->z = 0;
// bonds and neighbors
int neighborCount = 0;
foreach(const chemkit::Bond *bond, atom->bonds()){
const chemkit::Atom *neighbor = bond->otherAtom(atom);
if(neighbor->index() < atom->index())
continue;
inputAtom->neighbor[neighborCount] = neighbor->index();
inputAtom->bond_type[neighborCount] = bond->order();
inputAtom->bond_stereo[neighborCount] = INCHI_BOND_STEREO_NONE;
neighborCount++;
}
inputAtom->num_bonds = neighborCount;
// element symbol
strncpy(inputAtom->elname, atom->symbol().c_str(), ATOM_EL_LEN);
// isotopic hydrogens
inputAtom->num_iso_H[0] = -1;
inputAtom->num_iso_H[1] = 0;
inputAtom->num_iso_H[2] = 0;
inputAtom->num_iso_H[3] = 0;
// misc data
inputAtom->isotopic_mass = 0;
inputAtom->radical = 0;
inputAtom->charge = 0;
// chiral atoms
if(atom->isChiral()){
chiralAtoms.push_back(atom);
}
// move pointer to the next position in the atom array
inputAtom++;
}
// count double bonds with stereochemistry
std::vector<const chemkit::Bond *> stereogenicBonds;
foreach(const chemkit::Bond *bond, molecule->bonds()){
if(bond->order() == chemkit::Bond::Double &&
bond->stereochemistry() != chemkit::Stereochemistry::None){
stereogenicBonds.push_back(bond);
}
}
// add stereochemistry if enabled
bool stereochemistry = option("stereochemistry").toBool();
if(stereochemistry){
input.num_stereo0D = chiralAtoms.size() + stereogenicBonds.size();
input.stereo0D = new inchi_Stereo0D[input.num_stereo0D];
int chiralIndex = 0;
foreach(const chemkit::Atom *atom, chiralAtoms){
inchi_Stereo0D *stereo = &input.stereo0D[chiralIndex];
memset(stereo, 0, sizeof(*stereo));
stereo->central_atom = atom->index();
int neighborIndex = 0;
foreach(const chemkit::Atom *neighbor, atom->neighbors()){
stereo->neighbor[neighborIndex++] = neighbor->index();
}
stereo->type = INCHI_StereoType_Tetrahedral;
if(atom->chirality() == chemkit::Stereochemistry::R){
stereo->parity = INCHI_PARITY_ODD;
}
else if(atom->chirality() == chemkit::Stereochemistry::S){
stereo->parity = INCHI_PARITY_EVEN;
}
else if(atom->chirality() == chemkit::Stereochemistry::Unspecified){
stereo->parity = INCHI_PARITY_UNDEFINED;
}
else{
stereo->parity = INCHI_PARITY_UNKNOWN;
}
chiralIndex++;
}
foreach(const chemkit::Bond *bond, stereogenicBonds){
inchi_Stereo0D *stereo = &input.stereo0D[chiralIndex];
memset(stereo, 0, sizeof(*stereo));
stereo->central_atom = NO_ATOM;
stereo->type = INCHI_StereoType_DoubleBond;
if(bond->stereochemistry() == chemkit::Stereochemistry::E){
stereo->parity = INCHI_PARITY_EVEN;
}
else if(bond->stereochemistry() == chemkit::Stereochemistry::Z){
stereo->parity = INCHI_PARITY_ODD;
}
else{
stereo->parity = INCHI_PARITY_UNKNOWN;
}
// bond atoms
stereo->neighbor[1] = bond->atom1()->index();
stereo->neighbor[2] = bond->atom2()->index();
// neighbor atoms
const chemkit::Atom *highestPriorityNeighbor = 0;
foreach(const chemkit::Atom *neighbor, bond->atom1()->neighbors()){
if(neighbor == bond->atom2()){
continue;
}
if(!highestPriorityNeighbor){
highestPriorityNeighbor = neighbor;
}
else if(neighbor->atomicNumber() > highestPriorityNeighbor->atomicNumber()){
highestPriorityNeighbor = neighbor;
}
}
stereo->neighbor[0] = highestPriorityNeighbor->index();
highestPriorityNeighbor = 0;
foreach(const chemkit::Atom *neighbor, bond->atom2()->neighbors()){
if(neighbor == bond->atom1()){
continue;
}
if(!highestPriorityNeighbor){
highestPriorityNeighbor = neighbor;
}
else if(neighbor->atomicNumber() > highestPriorityNeighbor->atomicNumber()){
highestPriorityNeighbor = neighbor;
}
}
stereo->neighbor[3] = highestPriorityNeighbor->index();
chiralIndex++;
}
}
else{
input.stereo0D = 0;
input.num_stereo0D = 0;
}
// create inchi generator object
INCHIGEN_HANDLE generator = STDINCHIGEN_Create();
// setup generator object
INCHIGEN_DATA generatorData;
STDINCHIGEN_Setup(generator, &generatorData, &input);
// perform structure normalization
STDINCHIGEN_DoNormalization(generator, &generatorData);
// perform structure canonicalization
STDINCHIGEN_DoCanonicalization(generator, &generatorData);
// write inchi output structure
inchi_Output output;
STDINCHIGEN_DoSerialization(generator, &generatorData, &output);
// get inchi string from output
std::string inchiString;
if(output.szInChI){
inchiString = output.szInChI;
}
// destroy inchi input structure
delete [] input.atom;
delete [] input.stereo0D;
// destroy inchi generator object
STDINCHIGEN_Destroy(generator);
return inchiString;
}
chemkit::Variant InchiLineFormat::defaultOption(const std::string &name) const
{
if(name == "stereochemistry")
return true;
else if(name == "add-implicit-hydrogens")
return true;
else
return chemkit::Variant();
}
<commit_msg>Fix error handling in InchiLineFormat::read()<commit_after>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** 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 chemkit project nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
******************************************************************************/
#include "inchilineformat.h"
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include "../../3rdparty/inchi/inchi_api.h"
#include <chemkit/atom.h>
#include <chemkit/bond.h>
#include <chemkit/foreach.h>
InchiLineFormat::InchiLineFormat()
: chemkit::LineFormat("inchi")
{
}
bool InchiLineFormat::read(const std::string &formula, chemkit::Molecule *molecule)
{
// verify formula
if(formula.empty()){
setErrorString("Formula is empty.");
return false;
}
std::string formulaString = formula;
// add `InChI=` to the start if it is not there
if(!boost::starts_with(formula, "InChI=")){
formulaString = "InChI=" + formulaString;
}
// setup input struct
inchi_InputINCHI input;
input.szInChI = const_cast<char *>(formulaString.c_str());
input.szOptions = 0;
// get inchi output
inchi_OutputStruct output;
int ret = GetStructFromStdINCHI(&input, &output);
CHEMKIT_UNUSED(ret);
// add atoms
for(int i = 0; i < output.num_atoms; i++){
molecule->addAtom(output.atom[i].elname);
}
// add bonds
for(int i = 0; i < output.num_atoms; i++){
inchi_Atom *inchiAtom = &output.atom[i];
for(int j = 0; j < inchiAtom->num_bonds; j++){
molecule->addBond(i, inchiAtom->neighbor[j], inchiAtom->bond_type[j]);
}
}
// add implicit hydrogens (if enabled)
bool addHydrogens = option("add-implicit-hydrogens").toBool();
if(addHydrogens){
for(int i = 0; i < output.num_atoms; i++){
chemkit::Atom *atom = molecule->atom(i);
inchi_Atom *inchiAtom = &output.atom[i];
for(int j = 0; j < inchiAtom->num_iso_H[0]; j++){
chemkit::Atom *hydrogen = molecule->addAtom(chemkit::Atom::Hydrogen);
molecule->addBond(atom, hydrogen);
}
}
}
// free output structure
FreeStructFromStdINCHI(&output);
return true;
}
std::string InchiLineFormat::write(const chemkit::Molecule *molecule)
{
// check for valid molecule
if(molecule->atomCount() > 1024){
setErrorString("InChI does not support molecules with more that 1024 atoms.");
return std::string();
}
// setup inchi input structure
inchi_Input input;
input.atom = new inchi_Atom[molecule->atomCount()];
input.stereo0D = 0;
input.szOptions = 0;
input.num_atoms = molecule->atomCount();
input.num_stereo0D = 0;
inchi_Atom *inputAtom = &input.atom[0];
std::vector<const chemkit::Atom *> chiralAtoms;
foreach(const chemkit::Atom *atom, molecule->atoms()){
// coordinates
inputAtom->x = 0;
inputAtom->y = 0;
inputAtom->z = 0;
// bonds and neighbors
int neighborCount = 0;
foreach(const chemkit::Bond *bond, atom->bonds()){
const chemkit::Atom *neighbor = bond->otherAtom(atom);
if(neighbor->index() < atom->index())
continue;
inputAtom->neighbor[neighborCount] = neighbor->index();
inputAtom->bond_type[neighborCount] = bond->order();
inputAtom->bond_stereo[neighborCount] = INCHI_BOND_STEREO_NONE;
neighborCount++;
}
inputAtom->num_bonds = neighborCount;
// element symbol
strncpy(inputAtom->elname, atom->symbol().c_str(), ATOM_EL_LEN);
// isotopic hydrogens
inputAtom->num_iso_H[0] = -1;
inputAtom->num_iso_H[1] = 0;
inputAtom->num_iso_H[2] = 0;
inputAtom->num_iso_H[3] = 0;
// misc data
inputAtom->isotopic_mass = 0;
inputAtom->radical = 0;
inputAtom->charge = 0;
// chiral atoms
if(atom->isChiral()){
chiralAtoms.push_back(atom);
}
// move pointer to the next position in the atom array
inputAtom++;
}
// count double bonds with stereochemistry
std::vector<const chemkit::Bond *> stereogenicBonds;
foreach(const chemkit::Bond *bond, molecule->bonds()){
if(bond->order() == chemkit::Bond::Double &&
bond->stereochemistry() != chemkit::Stereochemistry::None){
stereogenicBonds.push_back(bond);
}
}
// add stereochemistry if enabled
bool stereochemistry = option("stereochemistry").toBool();
if(stereochemistry){
input.num_stereo0D = chiralAtoms.size() + stereogenicBonds.size();
input.stereo0D = new inchi_Stereo0D[input.num_stereo0D];
int chiralIndex = 0;
foreach(const chemkit::Atom *atom, chiralAtoms){
inchi_Stereo0D *stereo = &input.stereo0D[chiralIndex];
memset(stereo, 0, sizeof(*stereo));
stereo->central_atom = atom->index();
int neighborIndex = 0;
foreach(const chemkit::Atom *neighbor, atom->neighbors()){
stereo->neighbor[neighborIndex++] = neighbor->index();
}
stereo->type = INCHI_StereoType_Tetrahedral;
if(atom->chirality() == chemkit::Stereochemistry::R){
stereo->parity = INCHI_PARITY_ODD;
}
else if(atom->chirality() == chemkit::Stereochemistry::S){
stereo->parity = INCHI_PARITY_EVEN;
}
else if(atom->chirality() == chemkit::Stereochemistry::Unspecified){
stereo->parity = INCHI_PARITY_UNDEFINED;
}
else{
stereo->parity = INCHI_PARITY_UNKNOWN;
}
chiralIndex++;
}
foreach(const chemkit::Bond *bond, stereogenicBonds){
inchi_Stereo0D *stereo = &input.stereo0D[chiralIndex];
memset(stereo, 0, sizeof(*stereo));
stereo->central_atom = NO_ATOM;
stereo->type = INCHI_StereoType_DoubleBond;
if(bond->stereochemistry() == chemkit::Stereochemistry::E){
stereo->parity = INCHI_PARITY_EVEN;
}
else if(bond->stereochemistry() == chemkit::Stereochemistry::Z){
stereo->parity = INCHI_PARITY_ODD;
}
else{
stereo->parity = INCHI_PARITY_UNKNOWN;
}
// bond atoms
stereo->neighbor[1] = bond->atom1()->index();
stereo->neighbor[2] = bond->atom2()->index();
// neighbor atoms
const chemkit::Atom *highestPriorityNeighbor = 0;
foreach(const chemkit::Atom *neighbor, bond->atom1()->neighbors()){
if(neighbor == bond->atom2()){
continue;
}
if(!highestPriorityNeighbor){
highestPriorityNeighbor = neighbor;
}
else if(neighbor->atomicNumber() > highestPriorityNeighbor->atomicNumber()){
highestPriorityNeighbor = neighbor;
}
}
stereo->neighbor[0] = highestPriorityNeighbor->index();
highestPriorityNeighbor = 0;
foreach(const chemkit::Atom *neighbor, bond->atom2()->neighbors()){
if(neighbor == bond->atom1()){
continue;
}
if(!highestPriorityNeighbor){
highestPriorityNeighbor = neighbor;
}
else if(neighbor->atomicNumber() > highestPriorityNeighbor->atomicNumber()){
highestPriorityNeighbor = neighbor;
}
}
stereo->neighbor[3] = highestPriorityNeighbor->index();
chiralIndex++;
}
}
else{
input.stereo0D = 0;
input.num_stereo0D = 0;
}
// create inchi generator object
INCHIGEN_HANDLE generator = STDINCHIGEN_Create();
// setup generator object
INCHIGEN_DATA generatorData;
STDINCHIGEN_Setup(generator, &generatorData, &input);
// perform structure normalization
STDINCHIGEN_DoNormalization(generator, &generatorData);
// perform structure canonicalization
STDINCHIGEN_DoCanonicalization(generator, &generatorData);
// write inchi output structure
inchi_Output output;
STDINCHIGEN_DoSerialization(generator, &generatorData, &output);
// get inchi string from output
std::string inchiString;
if(output.szInChI){
inchiString = output.szInChI;
}
// destroy inchi input structure
delete [] input.atom;
delete [] input.stereo0D;
// destroy inchi generator object
STDINCHIGEN_Destroy(generator);
return inchiString;
}
chemkit::Variant InchiLineFormat::defaultOption(const std::string &name) const
{
if(name == "stereochemistry")
return true;
else if(name == "add-implicit-hydrogens")
return true;
else
return chemkit::Variant();
}
<|endoftext|> |
<commit_before>// ffmpeg_acoustid.cpp
// part of MusicPlayer, https://github.com/albertz/music-player
// Copyright (c) 2012, Albert Zeyer, www.az2000.de
// All rights reserved.
// This code is under the 2-clause BSD license, see License.txt in the root directory of this project.
#include "ffmpeg.h"
#include <chromaprint.h>
PyObject *
pyCalcAcoustIdFingerprint(PyObject* self, PyObject* args) {
PyObject* songObj = NULL;
if(!PyArg_ParseTuple(args, "O:calcAcoustIdFingerprint", &songObj))
return NULL;
PyObject* returnObj = NULL;
PlayerObject* player = NULL;
ChromaprintContext *chromaprint_ctx = NULL;
unsigned long totalFrameCount = 0;
player = (PlayerObject*) pyCreatePlayer(NULL);
if(!player) goto final;
player->lock.enabled = false;
player->nextSongOnEof = 0;
player->skipPyExceptions = 0;
player->playing = 1; // otherwise audio_decode_frame() wont read
player->volume = 1; player->volumeSmoothClip.setX(1, 1); // avoid volume adjustments
Py_INCREF(songObj);
player->curSong = songObj;
if(!player->openInStream()) goto final;
if(PyErr_Occurred()) goto final;
if(player->inStream == NULL) goto final;
// fpcalc source for reference:
// https://github.com/lalinsky/chromaprint/blob/master/examples/fpcalc.c
chromaprint_ctx = chromaprint_new(CHROMAPRINT_ALGORITHM_DEFAULT);
chromaprint_start(chromaprint_ctx, player->outSamplerate, player->outNumChannels);
// Note that we don't have any max_length handling yet.
// fpcalc uses a default of 120 seconds.
// This function right now doesn't rely on any external song duration
// source, so it is a perfect reliable way to calculate also the
// song duration.
// I'm not sure how expensive audio_decode_frame is compared to
// chromaprint_feed, so if we just decode everything to calculate
// a reliable song duration, it might make sense to just feed
// everything to chromaprint.
// Maybe we can optimize audio_decode_frame though to just return the
// len and don't do any decoding if we just want to calculate the len.
// This is all open for future hacking ... But it works good enough now.
while(player->processInStream()) {
if(PyErr_Occurred()) goto final;
for(auto& it : player->inStreamBuffer()->chunks) {
totalFrameCount += it.size() / player->outNumChannels / 2 /* S16 */;
if (!chromaprint_feed(chromaprint_ctx, it.pt(), it.size() / 2)) {
fprintf(stderr, "ERROR: fingerprint feed calculation failed\n");
goto final;
}
}
player->inStreamBuffer()->clear();
}
// If we have too less data -> fail. chromaprint_finish will print a warning/error but wont fail.
// 16 seems like a good lower limit. It is also the limit of the default Chromaprint Fingerprint algorithm.
if(totalFrameCount < 16) {
fprintf(stderr, "ERROR: too less data for fingerprint\n");
goto final;
}
{
double songDuration = (double)totalFrameCount / player->outSamplerate;
char* fingerprint = NULL;
if (!chromaprint_finish(chromaprint_ctx)) {
fprintf(stderr, "ERROR: fingerprint finish calculation failed\n");
goto final;
}
if (!chromaprint_get_fingerprint(chromaprint_ctx, &fingerprint)) {
fprintf(stderr, "ERROR: unable to calculate fingerprint, get_fingerprint failed\n");
goto final;
}
returnObj = PyTuple_New(2);
PyTuple_SetItem(returnObj, 0, PyFloat_FromDouble(songDuration));
PyTuple_SetItem(returnObj, 1, PyString_FromString(fingerprint));
chromaprint_dealloc(fingerprint);
}
final:
if(chromaprint_ctx)
chromaprint_free(chromaprint_ctx);
if(!PyErr_Occurred() && !returnObj) {
returnObj = Py_None;
Py_INCREF(returnObj);
}
Py_XDECREF(player);
return returnObj;
}
<commit_msg>ffmpeg.calcAcoustIdFingerprint: better error handling<commit_after>// ffmpeg_acoustid.cpp
// part of MusicPlayer, https://github.com/albertz/music-player
// Copyright (c) 2012, Albert Zeyer, www.az2000.de
// All rights reserved.
// This code is under the 2-clause BSD license, see License.txt in the root directory of this project.
#include "ffmpeg.h"
#include <chromaprint.h>
PyObject *
pyCalcAcoustIdFingerprint(PyObject* self, PyObject* args) {
PyObject* songObj = NULL;
if(!PyArg_ParseTuple(args, "O:calcAcoustIdFingerprint", &songObj))
return NULL;
PyObject* returnObj = NULL;
PlayerObject* player = NULL;
ChromaprintContext *chromaprint_ctx = NULL;
unsigned long totalFrameCount = 0;
player = (PlayerObject*) pyCreatePlayer(NULL);
if(!player) goto final;
player->lock.enabled = false;
player->nextSongOnEof = 0;
player->skipPyExceptions = 0;
player->playing = 1; // otherwise audio_decode_frame() wont read
player->volume = 1; player->volumeSmoothClip.setX(1, 1); // avoid volume adjustments
Py_INCREF(songObj);
player->curSong = songObj;
if(!player->openInStream()) goto final;
if(PyErr_Occurred()) goto final;
if(player->inStream == NULL) goto final;
// fpcalc source for reference:
// https://github.com/lalinsky/chromaprint/blob/master/examples/fpcalc.c
chromaprint_ctx = chromaprint_new(CHROMAPRINT_ALGORITHM_DEFAULT);
chromaprint_start(chromaprint_ctx, player->outSamplerate, player->outNumChannels);
// Note that we don't have any max_length handling yet.
// fpcalc uses a default of 120 seconds.
// This function right now doesn't rely on any external song duration
// source, so it is a perfect reliable way to calculate also the
// song duration.
// I'm not sure how expensive audio_decode_frame is compared to
// chromaprint_feed, so if we just decode everything to calculate
// a reliable song duration, it might make sense to just feed
// everything to chromaprint.
// Maybe we can optimize audio_decode_frame though to just return the
// len and don't do any decoding if we just want to calculate the len.
// This is all open for future hacking ... But it works good enough now.
while(player->processInStream()) {
if(PyErr_Occurred()) goto final;
for(auto& it : player->inStreamBuffer()->chunks) {
totalFrameCount += it.size() / player->outNumChannels / 2 /* S16 */;
if (!chromaprint_feed(chromaprint_ctx, it.pt(), it.size() / 2)) {
PyErr_SetString(PyExc_RuntimeError, "fingerprint feed calculation failed");
goto final;
}
}
player->inStreamBuffer()->clear();
}
// If we have too less data -> fail. chromaprint_finish will print a warning/error but wont fail.
// 16 seems like a good lower limit. It is also the limit of the default Chromaprint Fingerprint algorithm.
if(totalFrameCount < 16) {
PyErr_SetString(PyExc_RuntimeError, "too less data for fingerprint");
goto final;
}
{
double songDuration = (double)totalFrameCount / player->outSamplerate;
char* fingerprint = NULL;
if (!chromaprint_finish(chromaprint_ctx)) {
PyErr_SetString(PyExc_RuntimeError, "fingerprint finish calculation failed");
goto final;
}
if (!chromaprint_get_fingerprint(chromaprint_ctx, &fingerprint)) {
PyErr_SetString(PyExc_RuntimeError, "unable to calculate fingerprint, get_fingerprint failed");
goto final;
}
returnObj = PyTuple_New(2);
PyTuple_SetItem(returnObj, 0, PyFloat_FromDouble(songDuration));
PyTuple_SetItem(returnObj, 1, PyString_FromString(fingerprint));
chromaprint_dealloc(fingerprint);
}
final:
if(chromaprint_ctx)
chromaprint_free(chromaprint_ctx);
if(!PyErr_Occurred() && !returnObj) {
returnObj = Py_None;
Py_INCREF(returnObj);
}
Py_XDECREF(player);
return returnObj;
}
<|endoftext|> |
<commit_before>//
// This file is a part of pomerol - a scientific ED code for obtaining
// properties of a Hubbard model on a finite-size lattice
//
// Copyright (C) 2010-2012 Andrey Antipov <Andrey.E.Antipov@gmail.com>
// Copyright (C) 2010-2012 Igor Krivenko <Igor.S.Krivenko@gmail.com>
//
// pomerol 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.
//
// pomerol 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 pomerol. If not, see <http://www.gnu.org/licenses/>.
/** \file src/TwoParticleGF.cpp
** \brief Two-particle Green's function in the Matsubara representation.
**
** \author Igor Krivenko (Igor.S.Krivenko@gmail.com)
** \author Andrey Antipov (Andrey.E.Antipov@gmail.com)
*/
#include "pomerol/TwoParticleGF.h"
#include <boost/serialization/complex.hpp>
#include <boost/serialization/vector.hpp>
#include "mpi_dispatcher/mpi_skel.hpp"
namespace Pomerol{
TwoParticleGF::TwoParticleGF(const StatesClassification& S, const Hamiltonian& H,
const AnnihilationOperator& C1, const AnnihilationOperator& C2,
const CreationOperator& CX3, const CreationOperator& CX4,
const DensityMatrix& DM) :
Thermal(DM.beta), ComputableObject(),
S(S), H(H), C1(C1), C2(C2), CX3(CX3), CX4(CX4), DM(DM),
MatsubaraData_(DM.beta),
parts(0), Vanishing(true),
KroneckerSymbolTolerance (std::numeric_limits<RealType>::epsilon()),
ReduceResonanceTolerance (1e-8),
CoefficientTolerance (1e-16),
ReduceInvocationThreshold (1e5)
{
}
TwoParticleGF::~TwoParticleGF()
{
for(std::vector<TwoParticleGFPart*>::iterator iter = parts.begin(); iter != parts.end(); iter++)
delete *iter;
}
BlockNumber TwoParticleGF::getLeftIndex(size_t PermutationNumber, size_t OperatorPosition, BlockNumber RightIndex) const
{
switch(permutations3[PermutationNumber].perm[OperatorPosition]){
case 0: return C1.getLeftIndex(RightIndex);
case 1: return C2.getLeftIndex(RightIndex);
case 2: return CX3.getLeftIndex(RightIndex);
default: return ERROR_BLOCK_NUMBER;
}
}
BlockNumber TwoParticleGF::getRightIndex(size_t PermutationNumber, size_t OperatorPosition, BlockNumber LeftIndex) const
{
switch(permutations3[PermutationNumber].perm[OperatorPosition]){
case 0: return C1.getRightIndex(LeftIndex);
case 1: return C2.getRightIndex(LeftIndex);
case 2: return CX3.getRightIndex(LeftIndex);
default: return ERROR_BLOCK_NUMBER;
}
}
const FieldOperatorPart& TwoParticleGF::OperatorPartAtPosition(size_t PermutationNumber, size_t OperatorPosition, BlockNumber LeftIndex) const
{
switch(permutations3[PermutationNumber].perm[OperatorPosition]){
case 0: return C1.getPartFromLeftIndex(LeftIndex);
case 1: return C2.getPartFromLeftIndex(LeftIndex);
case 2: return CX3.getPartFromLeftIndex(LeftIndex);
default: assert(0);
}
throw std::logic_error("TwoParticleGF : could not find operator part");
}
void TwoParticleGF::prepare(void)
{
if(Status>=Prepared) return;
// Find out non-trivial blocks of CX4.
FieldOperator::BlocksBimap const& CX4NontrivialBlocks = CX4.getBlockMapping();
for(FieldOperator::BlocksBimap::right_const_iterator outer_iter = CX4NontrivialBlocks.right.begin();
outer_iter != CX4NontrivialBlocks.right.end(); outer_iter++){ // Iterate over the outermost index.
for(size_t p=0; p<6; ++p){ // Choose a permutation
BlockNumber LeftIndices[4];
LeftIndices[0] = outer_iter->first;
LeftIndices[3] = outer_iter->second;
LeftIndices[2] = getLeftIndex(p,2,LeftIndices[3]);
LeftIndices[1] = getRightIndex(p,0,LeftIndices[0]);
// < LeftIndices[0] | O_1 | LeftIndices[1] >
// < LeftIndices[1] | O_2 | getRightIndex(p,1,LeftIndices[1]) >
// < LeftIndices[2]| O_3 | LeftIndices[3] >
// < LeftIndices[3] | CX4 | LeftIndices[0] >
// Select a relevant 'world stripe' (sequence of blocks).
if(getRightIndex(p,1,LeftIndices[1]) == LeftIndices[2] && LeftIndices[1].isCorrect() && LeftIndices[2].isCorrect()){
// DEBUG
/*DEBUG("new part: " << S.getBlockInfo(LeftIndices[0]) << " "
<< S.getBlockInfo(LeftIndices[1]) << " "
<< S.getBlockInfo(LeftIndices[2]) << " "
<< S.getBlockInfo(LeftIndices[3]) << " "
<<"BlockNumbers part: " << LeftIndices[0] << " " << LeftIndices[1] << " " << LeftIndices[2] << " " << LeftIndices[3]);
*/
parts.push_back(new TwoParticleGFPart(
OperatorPartAtPosition(p,0,LeftIndices[0]),
OperatorPartAtPosition(p,1,LeftIndices[1]),
OperatorPartAtPosition(p,2,LeftIndices[2]),
(CreationOperatorPart&)CX4.getPartFromLeftIndex(LeftIndices[3]),
H.getPart(LeftIndices[0]), H.getPart(LeftIndices[1]), H.getPart(LeftIndices[2]), H.getPart(LeftIndices[3]),
DM.getPart(LeftIndices[0]), DM.getPart(LeftIndices[1]), DM.getPart(LeftIndices[2]), DM.getPart(LeftIndices[3]),
permutations3[p]));
(*parts.rbegin())->KroneckerSymbolTolerance = KroneckerSymbolTolerance;
(*parts.rbegin())->ReduceResonanceTolerance = ReduceResonanceTolerance;
(*parts.rbegin())->CoefficientTolerance = CoefficientTolerance;
(*parts.rbegin())->ReduceInvocationThreshold = ReduceInvocationThreshold;
(*parts.rbegin())->MultiTermCoefficientTolerance = MultiTermCoefficientTolerance;
}
}
}
if ( parts.size() > 0 ) {
Vanishing = false;
INFO("TwoParticleGF(" << getIndex(0) << getIndex(1) << getIndex(2) << getIndex(3) << "): " << parts.size() << " parts will be calculated");
}
Status = Prepared;
}
bool TwoParticleGF::isVanishing(void) const
{
return Vanishing;
}
// An mpi adapter to 1) compute 2pgf terms; 2) convert them to a MatsubaraContainer; 3) purge terms
struct ComputeAndClearWrap
{
int complexity;
void run(){p->compute(); p->fillContainer(data_); if (clear_) p->clear();};
ComputeAndClearWrap(TwoParticleGFPart::MatsubaraContainer &x, TwoParticleGFPart &p, bool clear, int complexity = 1):
data_(x),p(&p),clear_(clear), complexity(complexity){};
protected:
TwoParticleGFPart::MatsubaraContainer& data_;
TwoParticleGFPart *p;
bool clear_;
};
void TwoParticleGF::compute(bool clear, const boost::mpi::communicator & comm)
{
if (Status < Prepared) throw (exStatusMismatch());
if (Status >= Computed) return;
if (!Vanishing) {
// Create a "skeleton" class with pointers to part that can call a compute method
pMPI::mpi_skel<ComputeAndClearWrap> skel;
skel.parts.reserve(parts.size());
for (size_t i=0; i<parts.size(); i++) {
skel.parts.push_back(ComputeAndClearWrap(MatsubaraData_, *parts[i], clear, 1));
};
std::map<pMPI::JobId, pMPI::WorkerId> job_map = skel.run(comm, true); // actual running - very costly
int rank = comm.rank();
int comm_size = comm.size();
// Start distributing data
//DEBUG(comm.rank() << getIndex(0) << getIndex(1) << getIndex(2) << getIndex(3) << " Start distributing data");
comm.barrier();
if (!clear) {
for (size_t p = 0; p<parts.size(); p++) {
boost::mpi::broadcast(comm, parts[p]->NonResonantTerms, job_map[p]);
boost::mpi::broadcast(comm, parts[p]->ResonantTerms, job_map[p]);
if (rank == job_map[p]) {
parts[p]->Status = TwoParticleGFPart::Computed;
};
};
comm.barrier();
}
};
Status = Computed;
}
// size_t TwoParticleGF::getNumResonantTerms() const
// {
// size_t num = 0;
// for(std::vector<TwoParticleGFPart*>::const_iterator iter = parts.begin(); iter != parts.end(); iter++)
// num += (*iter)->getNumResonantTerms();
// return num;
// }
//
// size_t TwoParticleGF::getNumNonResonantTerms() const
// {
// size_t num = 0;
// for(std::vector<TwoParticleGFPart*>::const_iterator iter = parts.begin(); iter != parts.end(); iter++)
// num += (*iter)->getNumNonResonantTerms();
// return num;
// }
ParticleIndex TwoParticleGF::getIndex(size_t Position) const
{
switch(Position){
case 0: return C1.getIndex();
case 1: return C2.getIndex();
case 2: return CX3.getIndex();
case 3: return CX4.getIndex();
default: assert(0);
}
throw std::logic_error("TwoParticleGF : could not get operator index");
}
unsigned short TwoParticleGF::getPermutationNumber ( const Permutation3& in )
{
for (unsigned short i=0; i<6; ++i) if (in == permutations3[i]) return i;
ERROR("TwoParticleGF: Permutation " << in << " not found in all permutations3");
return 0;
}
} // end of namespace Pomerol
<commit_msg>compatibility upd<commit_after>//
// This file is a part of pomerol - a scientific ED code for obtaining
// properties of a Hubbard model on a finite-size lattice
//
// Copyright (C) 2010-2012 Andrey Antipov <Andrey.E.Antipov@gmail.com>
// Copyright (C) 2010-2012 Igor Krivenko <Igor.S.Krivenko@gmail.com>
//
// pomerol 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.
//
// pomerol 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 pomerol. If not, see <http://www.gnu.org/licenses/>.
/** \file src/TwoParticleGF.cpp
** \brief Two-particle Green's function in the Matsubara representation.
**
** \author Igor Krivenko (Igor.S.Krivenko@gmail.com)
** \author Andrey Antipov (Andrey.E.Antipov@gmail.com)
*/
#include "pomerol/TwoParticleGF.h"
#include <boost/serialization/complex.hpp>
#include <boost/serialization/vector.hpp>
#include "mpi_dispatcher/mpi_skel.hpp"
namespace Pomerol{
TwoParticleGF::TwoParticleGF(const StatesClassification& S, const Hamiltonian& H,
const AnnihilationOperator& C1, const AnnihilationOperator& C2,
const CreationOperator& CX3, const CreationOperator& CX4,
const DensityMatrix& DM) :
Thermal(DM.beta), ComputableObject(),
S(S), H(H), C1(C1), C2(C2), CX3(CX3), CX4(CX4), DM(DM),
MatsubaraData_(DM.beta),
parts(0), Vanishing(true),
KroneckerSymbolTolerance (std::numeric_limits<RealType>::epsilon()),
ReduceResonanceTolerance (1e-8),
CoefficientTolerance (1e-16),
ReduceInvocationThreshold (1e5)
{
}
TwoParticleGF::~TwoParticleGF()
{
for(std::vector<TwoParticleGFPart*>::iterator iter = parts.begin(); iter != parts.end(); iter++)
delete *iter;
}
BlockNumber TwoParticleGF::getLeftIndex(size_t PermutationNumber, size_t OperatorPosition, BlockNumber RightIndex) const
{
switch(permutations3[PermutationNumber].perm[OperatorPosition]){
case 0: return C1.getLeftIndex(RightIndex);
case 1: return C2.getLeftIndex(RightIndex);
case 2: return CX3.getLeftIndex(RightIndex);
default: return ERROR_BLOCK_NUMBER;
}
}
BlockNumber TwoParticleGF::getRightIndex(size_t PermutationNumber, size_t OperatorPosition, BlockNumber LeftIndex) const
{
switch(permutations3[PermutationNumber].perm[OperatorPosition]){
case 0: return C1.getRightIndex(LeftIndex);
case 1: return C2.getRightIndex(LeftIndex);
case 2: return CX3.getRightIndex(LeftIndex);
default: return ERROR_BLOCK_NUMBER;
}
}
const FieldOperatorPart& TwoParticleGF::OperatorPartAtPosition(size_t PermutationNumber, size_t OperatorPosition, BlockNumber LeftIndex) const
{
switch(permutations3[PermutationNumber].perm[OperatorPosition]){
case 0: return C1.getPartFromLeftIndex(LeftIndex);
case 1: return C2.getPartFromLeftIndex(LeftIndex);
case 2: return CX3.getPartFromLeftIndex(LeftIndex);
default: assert(0);
}
throw std::logic_error("TwoParticleGF : could not find operator part");
}
void TwoParticleGF::prepare(void)
{
if(Status>=Prepared) return;
// Find out non-trivial blocks of CX4.
FieldOperator::BlocksBimap const& CX4NontrivialBlocks = CX4.getBlockMapping();
for(FieldOperator::BlocksBimap::right_const_iterator outer_iter = CX4NontrivialBlocks.right.begin();
outer_iter != CX4NontrivialBlocks.right.end(); outer_iter++){ // Iterate over the outermost index.
for(size_t p=0; p<6; ++p){ // Choose a permutation
BlockNumber LeftIndices[4];
LeftIndices[0] = outer_iter->first;
LeftIndices[3] = outer_iter->second;
LeftIndices[2] = getLeftIndex(p,2,LeftIndices[3]);
LeftIndices[1] = getRightIndex(p,0,LeftIndices[0]);
// < LeftIndices[0] | O_1 | LeftIndices[1] >
// < LeftIndices[1] | O_2 | getRightIndex(p,1,LeftIndices[1]) >
// < LeftIndices[2]| O_3 | LeftIndices[3] >
// < LeftIndices[3] | CX4 | LeftIndices[0] >
// Select a relevant 'world stripe' (sequence of blocks).
if(getRightIndex(p,1,LeftIndices[1]) == LeftIndices[2] && LeftIndices[1].isCorrect() && LeftIndices[2].isCorrect()){
// DEBUG
/*DEBUG("new part: " << S.getBlockInfo(LeftIndices[0]) << " "
<< S.getBlockInfo(LeftIndices[1]) << " "
<< S.getBlockInfo(LeftIndices[2]) << " "
<< S.getBlockInfo(LeftIndices[3]) << " "
<<"BlockNumbers part: " << LeftIndices[0] << " " << LeftIndices[1] << " " << LeftIndices[2] << " " << LeftIndices[3]);
*/
parts.push_back(new TwoParticleGFPart(
OperatorPartAtPosition(p,0,LeftIndices[0]),
OperatorPartAtPosition(p,1,LeftIndices[1]),
OperatorPartAtPosition(p,2,LeftIndices[2]),
(CreationOperatorPart&)CX4.getPartFromLeftIndex(LeftIndices[3]),
H.getPart(LeftIndices[0]), H.getPart(LeftIndices[1]), H.getPart(LeftIndices[2]), H.getPart(LeftIndices[3]),
DM.getPart(LeftIndices[0]), DM.getPart(LeftIndices[1]), DM.getPart(LeftIndices[2]), DM.getPart(LeftIndices[3]),
permutations3[p]));
(*parts.rbegin())->KroneckerSymbolTolerance = KroneckerSymbolTolerance;
(*parts.rbegin())->ReduceResonanceTolerance = ReduceResonanceTolerance;
(*parts.rbegin())->CoefficientTolerance = CoefficientTolerance;
(*parts.rbegin())->ReduceInvocationThreshold = ReduceInvocationThreshold;
(*parts.rbegin())->MultiTermCoefficientTolerance = MultiTermCoefficientTolerance;
}
}
}
if ( parts.size() > 0 ) {
Vanishing = false;
INFO("TwoParticleGF(" << getIndex(0) << getIndex(1) << getIndex(2) << getIndex(3) << "): " << parts.size() << " parts will be calculated");
}
Status = Prepared;
}
bool TwoParticleGF::isVanishing(void) const
{
return Vanishing;
}
// An mpi adapter to 1) compute 2pgf terms; 2) convert them to a MatsubaraContainer; 3) purge terms
struct ComputeAndClearWrap
{
int complexity;
void run(){p->compute(); p->fillContainer(*data_); if (clear_) p->clear();};
ComputeAndClearWrap(TwoParticleGFPart::MatsubaraContainer &x, TwoParticleGFPart &p, bool clear, int complexity = 1):
data_(&x),p(&p),clear_(clear), complexity(complexity){};
protected:
TwoParticleGFPart::MatsubaraContainer* data_;
TwoParticleGFPart *p;
bool clear_;
};
void TwoParticleGF::compute(bool clear, const boost::mpi::communicator & comm)
{
if (Status < Prepared) throw (exStatusMismatch());
if (Status >= Computed) return;
if (!Vanishing) {
// Create a "skeleton" class with pointers to part that can call a compute method
pMPI::mpi_skel<ComputeAndClearWrap> skel;
skel.parts.reserve(parts.size());
for (size_t i=0; i<parts.size(); i++) {
skel.parts.push_back(ComputeAndClearWrap(MatsubaraData_, *parts[i], clear, 1));
};
std::map<pMPI::JobId, pMPI::WorkerId> job_map = skel.run(comm, true); // actual running - very costly
int rank = comm.rank();
int comm_size = comm.size();
// Start distributing data
//DEBUG(comm.rank() << getIndex(0) << getIndex(1) << getIndex(2) << getIndex(3) << " Start distributing data");
comm.barrier();
if (!clear) {
for (size_t p = 0; p<parts.size(); p++) {
boost::mpi::broadcast(comm, parts[p]->NonResonantTerms, job_map[p]);
boost::mpi::broadcast(comm, parts[p]->ResonantTerms, job_map[p]);
if (rank == job_map[p]) {
parts[p]->Status = TwoParticleGFPart::Computed;
};
};
comm.barrier();
}
};
Status = Computed;
}
// size_t TwoParticleGF::getNumResonantTerms() const
// {
// size_t num = 0;
// for(std::vector<TwoParticleGFPart*>::const_iterator iter = parts.begin(); iter != parts.end(); iter++)
// num += (*iter)->getNumResonantTerms();
// return num;
// }
//
// size_t TwoParticleGF::getNumNonResonantTerms() const
// {
// size_t num = 0;
// for(std::vector<TwoParticleGFPart*>::const_iterator iter = parts.begin(); iter != parts.end(); iter++)
// num += (*iter)->getNumNonResonantTerms();
// return num;
// }
ParticleIndex TwoParticleGF::getIndex(size_t Position) const
{
switch(Position){
case 0: return C1.getIndex();
case 1: return C2.getIndex();
case 2: return CX3.getIndex();
case 3: return CX4.getIndex();
default: assert(0);
}
throw std::logic_error("TwoParticleGF : could not get operator index");
}
unsigned short TwoParticleGF::getPermutationNumber ( const Permutation3& in )
{
for (unsigned short i=0; i<6; ++i) if (in == permutations3[i]) return i;
ERROR("TwoParticleGF: Permutation " << in << " not found in all permutations3");
return 0;
}
} // end of namespace Pomerol
<|endoftext|> |
<commit_before>/* Copyright 2006-2008, The Android Open Source Project
**
** 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 "SkFontHost.h"
SkTypeface* SkFontHost::FindTypeface(const SkTypeface* familyFace,
const char famillyName[],
SkTypeface::Style style) {
SkASSERT(!"SkFontHost::FindTypeface unimplemented");
return NULL;
}
SkTypeface* SkFontHost::ResolveTypeface(uint32_t uniqueID) {
SkASSERT(!"SkFontHost::ResolveTypeface unimplemented");
return NULL;
}
SkStream* SkFontHost::OpenStream(uint32_t uniqueID) {
SkASSERT(!"SkFontHost::OpenStream unimplemented");
return NULL;
}
void SkFontHost::CloseStream(uint32_t uniqueID, SkStream*) {
SkASSERT(!"SkFontHost::CloseStream unimplemented");
}
SkTypeface* SkFontHost::CreateTypeface(SkStream*) {
SkASSERT(!"SkFontHost::CreateTypeface unimplemented");
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
void SkFontHost::Serialize(const SkTypeface* face, SkWStream* stream) {
SkASSERT(!"SkFontHost::Serialize unimplemented");
}
SkTypeface* SkFontHost::Deserialize(SkStream* stream) {
SkASSERT(!"SkFontHost::Deserialize unimplemented");
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
SkASSERT(!"SkFontHost::CreateScalarContext unimplemented");
return NULL;
}
SkScalerContext* SkFontHost::CreateFallbackScalerContext(
const SkScalerContext::Rec&) {
SkASSERT(!"SkFontHost::CreateFallbackScalerContext unimplemented");
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
size_t SkFontHost::ShouldPurgeFontCache(size_t sizeAllocatedSoFar) {
return 0; // nothing to do (change me if you want to limit the font cache)
}
int SkFontHost::ComputeGammaFlag(const SkPaint& paint) {
return 0;
}
void SkFontHost::GetGammaTables(const uint8_t* tables[2]) {
tables[0] = NULL; // black gamma (e.g. exp=1.4)
tables[1] = NULL; // white gamma (e.g. exp= 1/1.4)
}
<commit_msg>Initial automake and autoconf files to build core into libskia.a.<commit_after>/* Copyright 2006-2008, The Android Open Source Project
**
** 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 "SkFontHost.h"
SkTypeface* SkFontHost::FindTypeface(const SkTypeface* familyFace,
const char famillyName[],
SkTypeface::Style style) {
SkASSERT(!"SkFontHost::FindTypeface unimplemented");
return NULL;
}
SkTypeface* SkFontHost::ResolveTypeface(uint32_t uniqueID) {
SkASSERT(!"SkFontHost::ResolveTypeface unimplemented");
return NULL;
}
SkStream* SkFontHost::OpenStream(uint32_t uniqueID) {
SkASSERT(!"SkFontHost::OpenStream unimplemented");
return NULL;
}
void SkFontHost::CloseStream(uint32_t uniqueID, SkStream*) {
SkASSERT(!"SkFontHost::CloseStream unimplemented");
}
SkTypeface* SkFontHost::CreateTypeface(SkStream*) {
SkASSERT(!"SkFontHost::CreateTypeface unimplemented");
return NULL;
}
SkTypeface* SkFontHost::CreateTypefaceFromFile(char const*) {
SkASSERT(!"SkFontHost::CreateTypefaceFromFile unimplemented");
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
void SkFontHost::Serialize(const SkTypeface* face, SkWStream* stream) {
SkASSERT(!"SkFontHost::Serialize unimplemented");
}
SkTypeface* SkFontHost::Deserialize(SkStream* stream) {
SkASSERT(!"SkFontHost::Deserialize unimplemented");
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
SkASSERT(!"SkFontHost::CreateScalarContext unimplemented");
return NULL;
}
SkScalerContext* SkFontHost::CreateFallbackScalerContext(
const SkScalerContext::Rec&) {
SkASSERT(!"SkFontHost::CreateFallbackScalerContext unimplemented");
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
size_t SkFontHost::ShouldPurgeFontCache(size_t sizeAllocatedSoFar) {
return 0; // nothing to do (change me if you want to limit the font cache)
}
int SkFontHost::ComputeGammaFlag(const SkPaint& paint) {
return 0;
}
void SkFontHost::GetGammaTables(const uint8_t* tables[2]) {
tables[0] = NULL; // black gamma (e.g. exp=1.4)
tables[1] = NULL; // white gamma (e.g. exp= 1/1.4)
}
<|endoftext|> |
<commit_before>///
/// @file ParallelPrimeSieve.cpp
/// @brief Sieve primes in parallel using OpenMP.
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/ParallelPrimeSieve.hpp>
#include <primesieve/PrimeSieve.hpp>
#include <primesieve/pmath.hpp>
#include <stdint.h>
#include <cstddef>
#include <cassert>
#include <algorithm>
#ifdef _OPENMP
#include <omp.h>
#include <primesieve/ParallelPrimeSieve-lock.hpp>
#endif
using namespace std;
namespace primesieve {
ParallelPrimeSieve::ParallelPrimeSieve() :
lock_(NULL),
shm_(NULL),
numThreads_(IDEAL_NUM_THREADS)
{ }
void ParallelPrimeSieve::init(SharedMemory& shm)
{
setStart(shm.start);
setStop(shm.stop);
setSieveSize(shm.sieveSize);
setFlags(shm.flags);
setNumThreads(shm.threads);
shm_ = &shm;
}
int ParallelPrimeSieve::getNumThreads() const
{
if (numThreads_ == IDEAL_NUM_THREADS)
return idealNumThreads();
return numThreads_;
}
void ParallelPrimeSieve::setNumThreads(int threads)
{
numThreads_ = threads;
if (numThreads_ != IDEAL_NUM_THREADS)
numThreads_ = inBetween(1, numThreads_, getMaxThreads());
}
/// Get an ideal number of threads for the current
/// set start_ and stop_ numbers.
///
int ParallelPrimeSieve::idealNumThreads() const
{
if (start_ > stop_)
return 1;
uint64_t threshold = max(config::MIN_THREAD_INTERVAL, isqrt(stop_) / 5);
uint64_t threads = getInterval() / threshold;
threads = inBetween(1, threads, getMaxThreads());
return static_cast<int>(threads);
}
/// Get an interval size that ensures a good load
/// balance when using multiple threads.
///
uint64_t ParallelPrimeSieve::getThreadInterval(int threads) const
{
assert(threads > 0);
uint64_t unbalanced = getInterval() / threads;
uint64_t balanced = isqrt(stop_) * 1000;
uint64_t fastest = min(balanced, unbalanced);
uint64_t threadInterval = inBetween(config::MIN_THREAD_INTERVAL, fastest, config::MAX_THREAD_INTERVAL);
uint64_t chunks = getInterval() / threadInterval;
if (chunks < threads * 5u)
threadInterval = max(config::MIN_THREAD_INTERVAL, unbalanced);
threadInterval += 30 - threadInterval % 30;
return threadInterval;
}
/// Align n to modulo 30 + 2 to prevent prime k-tuplet
/// (twin primes, prime triplets, ...) gaps.
///
uint64_t ParallelPrimeSieve::align(uint64_t n) const
{
uint64_t n32 = add_overflow_safe(n, 32);
if (n32 >= stop_)
return stop_;
n = n32 - n % 30;
return min(n, stop_);
}
bool ParallelPrimeSieve::tooMany(int threads) const
{
uint64_t threadInterval = getInterval() / threads;
return (threads > 1 && threadInterval < config::MIN_THREAD_INTERVAL);
}
#ifdef _OPENMP
int ParallelPrimeSieve::getMaxThreads()
{
return omp_get_max_threads();
}
double ParallelPrimeSieve::getWallTime() const
{
return omp_get_wtime();
}
/// Sieve the primes and prime k-tuplets within [start_, stop_]
/// in parallel using OpenMP multi-threading.
///
void ParallelPrimeSieve::sieve()
{
reset();
if (start_ > stop_)
return;
OmpInitLock ompInit(&lock_);
int threads = getNumThreads();
if (tooMany(threads))
threads = idealNumThreads();
if (threads == 1)
PrimeSieve::sieve();
else
{
uint64_t threadInterval = getThreadInterval(threads);
uint64_t count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0;
int64_t iters = 1 + (getInterval() - 1) / threadInterval;
double t1 = getWallTime();
#pragma omp parallel for schedule(dynamic) num_threads(threads) \
reduction(+: count0, count1, count2, count3, count4, count5)
for (int64_t i = 0; i < iters; i++)
{
uint64_t threadStart = start_ + i * threadInterval;
uint64_t threadStop = add_overflow_safe(threadStart, threadInterval);
if (i > 0) threadStart = align(threadStart) + 1;
threadStop = align(threadStop);
PrimeSieve ps(*this, omp_get_thread_num());
ps.sieve(threadStart, threadStop);
count0 += ps.getCount(0);
count1 += ps.getCount(1);
count2 += ps.getCount(2);
count3 += ps.getCount(3);
count4 += ps.getCount(4);
count5 += ps.getCount(5);
}
seconds_ = getWallTime() - t1;
counts_[0] = count0;
counts_[1] = count1;
counts_[2] = count2;
counts_[3] = count3;
counts_[4] = count4;
counts_[5] = count5;
}
if (shm_)
{
// communicate the sieving results to
// the primesieve GUI application
copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
/// Calculate the sieving status.
/// @param processed Sum of recently processed segments.
///
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock)
{
OmpLockGuard lock(getLock<omp_lock_t*>(), waitForLock);
if (lock.isSet())
{
PrimeSieve::updateStatus(processed, false);
if (shm_)
shm_->status = getStatus();
}
return lock.isSet();
}
/// Used to synchronize threads for prime number generation
void ParallelPrimeSieve::setLock()
{
omp_lock_t* lock = getLock<omp_lock_t*>();
omp_set_lock(lock);
}
void ParallelPrimeSieve::unsetLock()
{
omp_lock_t* lock = getLock<omp_lock_t*>();
omp_unset_lock(lock);
}
#endif /* _OPENMP */
/// If OpenMP is disabled then ParallelPrimeSieve behaves like
/// the single threaded PrimeSieve.
///
#if !defined(_OPENMP)
int ParallelPrimeSieve::getMaxThreads()
{
return 1;
}
void ParallelPrimeSieve::sieve()
{
PrimeSieve::sieve();
if (shm_)
{
// communicate the sieving results to the
// primesieve GUI application
copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
double ParallelPrimeSieve::getWallTime() const
{
return PrimeSieve::getWallTime();
}
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock)
{
bool isUpdate = PrimeSieve::updateStatus(processed, waitForLock);
if (shm_)
shm_->status = getStatus();
return isUpdate;
}
void ParallelPrimeSieve::setLock() { }
void ParallelPrimeSieve::unsetLock() { }
#endif
} // namespace
<commit_msg>Refactor<commit_after>///
/// @file ParallelPrimeSieve.cpp
/// @brief Sieve primes in parallel using OpenMP.
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/ParallelPrimeSieve.hpp>
#include <primesieve/PrimeSieve.hpp>
#include <primesieve/pmath.hpp>
#include <stdint.h>
#include <cstddef>
#include <cassert>
#include <algorithm>
#ifdef _OPENMP
#include <omp.h>
#include <primesieve/ParallelPrimeSieve-lock.hpp>
#endif
using namespace std;
namespace primesieve {
ParallelPrimeSieve::ParallelPrimeSieve() :
lock_(NULL),
shm_(NULL),
numThreads_(IDEAL_NUM_THREADS)
{ }
void ParallelPrimeSieve::init(SharedMemory& shm)
{
setStart(shm.start);
setStop(shm.stop);
setSieveSize(shm.sieveSize);
setFlags(shm.flags);
setNumThreads(shm.threads);
shm_ = &shm;
}
int ParallelPrimeSieve::getNumThreads() const
{
if (numThreads_ == IDEAL_NUM_THREADS)
return idealNumThreads();
return numThreads_;
}
void ParallelPrimeSieve::setNumThreads(int threads)
{
numThreads_ = threads;
if (numThreads_ != IDEAL_NUM_THREADS)
numThreads_ = inBetween(1, numThreads_, getMaxThreads());
}
/// Get an ideal number of threads for the current
/// set start_ and stop_ numbers.
///
int ParallelPrimeSieve::idealNumThreads() const
{
if (start_ > stop_)
return 1;
uint64_t threshold = max(config::MIN_THREAD_INTERVAL, isqrt(stop_) / 5);
uint64_t threads = getInterval() / threshold;
threads = inBetween(1, threads, getMaxThreads());
return static_cast<int>(threads);
}
/// Get an interval size that ensures a good load
/// balance when using multiple threads.
///
uint64_t ParallelPrimeSieve::getThreadInterval(int threads) const
{
assert(threads > 0);
uint64_t unbalanced = getInterval() / threads;
uint64_t balanced = isqrt(stop_) * 1000;
uint64_t fastest = min(balanced, unbalanced);
uint64_t threadInterval = inBetween(config::MIN_THREAD_INTERVAL, fastest, config::MAX_THREAD_INTERVAL);
uint64_t chunks = getInterval() / threadInterval;
if (chunks < threads * 5u)
threadInterval = max(config::MIN_THREAD_INTERVAL, unbalanced);
threadInterval += 30 - threadInterval % 30;
return threadInterval;
}
/// Align n to modulo 30 + 2 to prevent prime k-tuplet
/// (twin primes, prime triplets, ...) gaps.
///
uint64_t ParallelPrimeSieve::align(uint64_t n) const
{
if (add_overflow_safe(n, 32) >= stop_)
return stop_;
n = add_overflow_safe(n, 32) - n % 30;
return min(n, stop_);
}
bool ParallelPrimeSieve::tooMany(int threads) const
{
uint64_t threadInterval = getInterval() / threads;
return (threads > 1 && threadInterval < config::MIN_THREAD_INTERVAL);
}
#ifdef _OPENMP
int ParallelPrimeSieve::getMaxThreads()
{
return omp_get_max_threads();
}
double ParallelPrimeSieve::getWallTime() const
{
return omp_get_wtime();
}
/// Sieve the primes and prime k-tuplets within [start_, stop_]
/// in parallel using OpenMP multi-threading.
///
void ParallelPrimeSieve::sieve()
{
reset();
if (start_ > stop_)
return;
OmpInitLock ompInit(&lock_);
int threads = getNumThreads();
if (tooMany(threads))
threads = idealNumThreads();
if (threads == 1)
PrimeSieve::sieve();
else
{
uint64_t threadInterval = getThreadInterval(threads);
uint64_t count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0;
int64_t iters = 1 + (getInterval() - 1) / threadInterval;
double t1 = getWallTime();
#pragma omp parallel for schedule(dynamic) num_threads(threads) \
reduction(+: count0, count1, count2, count3, count4, count5)
for (int64_t i = 0; i < iters; i++)
{
uint64_t threadStart = start_ + i * threadInterval;
uint64_t threadStop = add_overflow_safe(threadStart, threadInterval);
if (i > 0) threadStart = align(threadStart) + 1;
threadStop = align(threadStop);
PrimeSieve ps(*this, omp_get_thread_num());
ps.sieve(threadStart, threadStop);
count0 += ps.getCount(0);
count1 += ps.getCount(1);
count2 += ps.getCount(2);
count3 += ps.getCount(3);
count4 += ps.getCount(4);
count5 += ps.getCount(5);
}
seconds_ = getWallTime() - t1;
counts_[0] = count0;
counts_[1] = count1;
counts_[2] = count2;
counts_[3] = count3;
counts_[4] = count4;
counts_[5] = count5;
}
if (shm_)
{
// communicate the sieving results to
// the primesieve GUI application
copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
/// Calculate the sieving status.
/// @param processed Sum of recently processed segments.
///
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock)
{
OmpLockGuard lock(getLock<omp_lock_t*>(), waitForLock);
if (lock.isSet())
{
PrimeSieve::updateStatus(processed, false);
if (shm_)
shm_->status = getStatus();
}
return lock.isSet();
}
/// Used to synchronize threads for prime number generation
void ParallelPrimeSieve::setLock()
{
omp_lock_t* lock = getLock<omp_lock_t*>();
omp_set_lock(lock);
}
void ParallelPrimeSieve::unsetLock()
{
omp_lock_t* lock = getLock<omp_lock_t*>();
omp_unset_lock(lock);
}
#endif /* _OPENMP */
/// If OpenMP is disabled then ParallelPrimeSieve behaves like
/// the single threaded PrimeSieve.
///
#if !defined(_OPENMP)
int ParallelPrimeSieve::getMaxThreads()
{
return 1;
}
void ParallelPrimeSieve::sieve()
{
PrimeSieve::sieve();
if (shm_)
{
// communicate the sieving results to the
// primesieve GUI application
copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
double ParallelPrimeSieve::getWallTime() const
{
return PrimeSieve::getWallTime();
}
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock)
{
bool isUpdate = PrimeSieve::updateStatus(processed, waitForLock);
if (shm_)
shm_->status = getStatus();
return isUpdate;
}
void ParallelPrimeSieve::setLock() { }
void ParallelPrimeSieve::unsetLock() { }
#endif
} // namespace
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2019 The Android Open Source Project
*
* 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 "perfetto/profiling/deobfuscator.h"
#include "perfetto/ext/base/file_utils.h"
#include "perfetto/ext/base/scoped_file.h"
#include "perfetto/ext/base/string_splitter.h"
#include "perfetto/ext/base/optional.h"
#include "perfetto/protozero/scattered_heap_buffer.h"
#include "protos/perfetto/trace/profiling/deobfuscation.pbzero.h"
#include "protos/perfetto/trace/trace.pbzero.h"
#include "protos/perfetto/trace/trace_packet.pbzero.h"
namespace perfetto {
namespace profiling {
namespace {
struct ProguardClass {
std::string obfuscated_name;
std::string deobfuscated_name;
};
base::Optional<ProguardClass> ParseClass(std::string line) {
base::StringSplitter ss(std::move(line), ' ');
if (!ss.Next()) {
PERFETTO_ELOG("Missing deobfuscated name.");
return base::nullopt;
}
std::string deobfuscated_name(ss.cur_token(), ss.cur_token_size());
if (!ss.Next() || ss.cur_token_size() != 2 ||
strncmp("->", ss.cur_token(), 2) != 0) {
PERFETTO_ELOG("Missing ->");
return base::nullopt;
}
if (!ss.Next()) {
PERFETTO_ELOG("Missing obfuscated name.");
return base::nullopt;
}
std::string obfuscated_name(ss.cur_token(), ss.cur_token_size());
if (obfuscated_name.empty()) {
PERFETTO_ELOG("Empty obfuscated name.");
return base::nullopt;
}
if (obfuscated_name.back() != ':') {
PERFETTO_ELOG("Expected colon.");
return base::nullopt;
}
obfuscated_name.resize(obfuscated_name.size() - 1);
if (ss.Next()) {
PERFETTO_ELOG("Unexpected data.");
return base::nullopt;
}
return ProguardClass{std::move(obfuscated_name),
std::move(deobfuscated_name)};
}
enum class ProguardMemberType {
kField,
kMethod,
};
struct ProguardMember {
ProguardMemberType type;
std::string obfuscated_name;
std::string deobfuscated_name;
};
base::Optional<ProguardMember> ParseMember(std::string line) {
base::StringSplitter ss(std::move(line), ' ');
if (!ss.Next()) {
PERFETTO_ELOG("Missing type name.");
return base::nullopt;
}
std::string type_name(ss.cur_token(), ss.cur_token_size());
if (!ss.Next()) {
PERFETTO_ELOG("Missing deobfuscated name.");
return base::nullopt;
}
std::string deobfuscated_name(ss.cur_token(), ss.cur_token_size());
if (!ss.Next() || ss.cur_token_size() != 2 ||
strncmp("->", ss.cur_token(), 2) != 0) {
PERFETTO_ELOG("Missing ->");
return base::nullopt;
}
if (!ss.Next()) {
PERFETTO_ELOG("Missing obfuscated name.");
return base::nullopt;
}
std::string obfuscated_name(ss.cur_token(), ss.cur_token_size());
if (ss.Next()) {
PERFETTO_ELOG("Unexpected data.");
return base::nullopt;
}
ProguardMemberType member_type;
auto paren_idx = deobfuscated_name.find("(");
if (paren_idx != std::string::npos) {
member_type = ProguardMemberType::kMethod;
deobfuscated_name = deobfuscated_name.substr(0, paren_idx);
auto colon_idx = type_name.find(":");
if (colon_idx != std::string::npos) {
type_name = type_name.substr(colon_idx + 1);
}
} else {
member_type = ProguardMemberType::kField;
}
return ProguardMember{member_type, std::move(obfuscated_name),
std::move(deobfuscated_name)};
}
std::string FlattenMethods(const std::vector<std::string>& v) {
if (v.size() == 1) {
return v[0];
}
return "[ambiguous]";
}
} // namespace
std::string FlattenClasses(
const std::map<std::string, std::vector<std::string>>& m) {
std::string result;
bool first = true;
for (const auto& p : m) {
if (!first) {
result += " | ";
}
result += p.first + "." + FlattenMethods(p.second);
first = false;
}
return result;
}
// See https://www.guardsquare.com/en/products/proguard/manual/retrace for the
// file format we are parsing.
bool ProguardParser::AddLine(std::string line) {
if (line.length() == 0)
return true;
bool is_member = line[0] == ' ';
if (is_member && !current_class_) {
PERFETTO_ELOG("Failed to parse proguard map. Saw member before class.");
return false;
}
if (!is_member) {
auto opt_cls = ParseClass(std::move(line));
if (!opt_cls)
return false;
auto p = mapping_.emplace(std::move(opt_cls->obfuscated_name),
std::move(opt_cls->deobfuscated_name));
if (!p.second) {
PERFETTO_ELOG("Duplicate class.");
return false;
}
current_class_ = &p.first->second;
} else {
auto opt_member = ParseMember(std::move(line));
if (!opt_member)
return false;
switch (opt_member->type) {
case (ProguardMemberType::kField): {
if (!current_class_->AddField(opt_member->obfuscated_name,
opt_member->deobfuscated_name)) {
PERFETTO_ELOG("Member redefinition: %s.%s. Proguard map invalid",
current_class_->deobfuscated_name().c_str(),
opt_member->deobfuscated_name.c_str());
return false;
}
break;
}
case (ProguardMemberType::kMethod): {
current_class_->AddMethod(opt_member->obfuscated_name,
opt_member->deobfuscated_name);
break;
}
}
}
return true;
}
bool ProguardParser::AddLines(std::string contents) {
for (base::StringSplitter lines(std::move(contents), '\n'); lines.Next();) {
if (!AddLine(lines.cur_token()))
return false;
}
return true;
}
void MakeDeobfuscationPackets(
const std::string& package_name,
const std::map<std::string, profiling::ObfuscatedClass>& mapping,
std::function<void(const std::string&)> callback) {
protozero::HeapBuffered<perfetto::protos::pbzero::Trace> trace;
auto* packet = trace->add_packet();
// TODO(fmayer): Add handling for package name and version code here so we
// can support multiple dumps in the same trace.
auto* proto_mapping = packet->set_deobfuscation_mapping();
proto_mapping->set_package_name(package_name);
for (const auto& p : mapping) {
const std::string& obfuscated_class_name = p.first;
const profiling::ObfuscatedClass& cls = p.second;
auto* proto_class = proto_mapping->add_obfuscated_classes();
proto_class->set_obfuscated_name(obfuscated_class_name);
proto_class->set_deobfuscated_name(cls.deobfuscated_name());
for (const auto& field_p : cls.deobfuscated_fields()) {
const std::string& obfuscated_field_name = field_p.first;
const std::string& deobfuscated_field_name = field_p.second;
auto* proto_member = proto_class->add_obfuscated_members();
proto_member->set_obfuscated_name(obfuscated_field_name);
proto_member->set_deobfuscated_name(deobfuscated_field_name);
}
for (const auto& field_p : cls.deobfuscated_methods()) {
const std::string& obfuscated_method_name = field_p.first;
const std::string& deobfuscated_method_name = field_p.second;
auto* proto_member = proto_class->add_obfuscated_methods();
proto_member->set_obfuscated_name(obfuscated_method_name);
proto_member->set_deobfuscated_name(deobfuscated_method_name);
}
}
callback(trace.SerializeAsString());
}
bool ReadProguardMapsToDeobfuscationPackets(
const std::vector<ProguardMap>& maps,
std::function<void(std::string)> fn) {
for (const ProguardMap& map : maps) {
const char* filename = map.filename.c_str();
base::ScopedFstream f(fopen(filename, "r"));
if (!f) {
PERFETTO_ELOG("Failed to open %s", filename);
return false;
}
profiling::ProguardParser parser;
std::string contents;
PERFETTO_CHECK(base::ReadFileStream(*f, &contents));
if (!parser.AddLines(std::move(contents))) {
PERFETTO_ELOG("Failed to parse %s", filename);
return false;
}
std::map<std::string, profiling::ObfuscatedClass> obfuscation_map =
parser.ConsumeMapping();
// TODO(fmayer): right now, we don't use the profile we are given. We can
// filter the output to only contain the classes actually seen in the
// profile.
MakeDeobfuscationPackets(map.package, obfuscation_map, fn);
}
return true;
}
std::vector<ProguardMap> GetPerfettoProguardMapPath() {
const char* env = getenv("PERFETTO_PROGUARD_MAP");
if (env == nullptr)
return {};
std::vector<ProguardMap> res;
for (base::StringSplitter sp(std::string(env), ':'); sp.Next();) {
std::string token(sp.cur_token(), sp.cur_token_size());
size_t eq = token.find('=');
if (eq == std::string::npos) {
PERFETTO_ELOG(
"Invalid PERFETTO_PROGUARD_MAP. "
"Expected format packagename=filename[:packagename=filename...], "
"e.g. com.example.package1=foo.txt:com.example.package2=bar.txt.");
return {};
}
res.emplace_back(ProguardMap{token.substr(0, eq), token.substr(eq + 1)});
}
return res; // for Wreturn-std-move-in-c++11.
}
} // namespace profiling
} // namespace perfetto
<commit_msg>Open file with CLOEXEC in deobfuscator.<commit_after>/*
* Copyright (C) 2019 The Android Open Source Project
*
* 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 "perfetto/profiling/deobfuscator.h"
#include "perfetto/ext/base/file_utils.h"
#include "perfetto/ext/base/scoped_file.h"
#include "perfetto/ext/base/string_splitter.h"
#include "perfetto/ext/base/optional.h"
#include "perfetto/protozero/scattered_heap_buffer.h"
#include "protos/perfetto/trace/profiling/deobfuscation.pbzero.h"
#include "protos/perfetto/trace/trace.pbzero.h"
#include "protos/perfetto/trace/trace_packet.pbzero.h"
namespace perfetto {
namespace profiling {
namespace {
struct ProguardClass {
std::string obfuscated_name;
std::string deobfuscated_name;
};
base::Optional<ProguardClass> ParseClass(std::string line) {
base::StringSplitter ss(std::move(line), ' ');
if (!ss.Next()) {
PERFETTO_ELOG("Missing deobfuscated name.");
return base::nullopt;
}
std::string deobfuscated_name(ss.cur_token(), ss.cur_token_size());
if (!ss.Next() || ss.cur_token_size() != 2 ||
strncmp("->", ss.cur_token(), 2) != 0) {
PERFETTO_ELOG("Missing ->");
return base::nullopt;
}
if (!ss.Next()) {
PERFETTO_ELOG("Missing obfuscated name.");
return base::nullopt;
}
std::string obfuscated_name(ss.cur_token(), ss.cur_token_size());
if (obfuscated_name.empty()) {
PERFETTO_ELOG("Empty obfuscated name.");
return base::nullopt;
}
if (obfuscated_name.back() != ':') {
PERFETTO_ELOG("Expected colon.");
return base::nullopt;
}
obfuscated_name.resize(obfuscated_name.size() - 1);
if (ss.Next()) {
PERFETTO_ELOG("Unexpected data.");
return base::nullopt;
}
return ProguardClass{std::move(obfuscated_name),
std::move(deobfuscated_name)};
}
enum class ProguardMemberType {
kField,
kMethod,
};
struct ProguardMember {
ProguardMemberType type;
std::string obfuscated_name;
std::string deobfuscated_name;
};
base::Optional<ProguardMember> ParseMember(std::string line) {
base::StringSplitter ss(std::move(line), ' ');
if (!ss.Next()) {
PERFETTO_ELOG("Missing type name.");
return base::nullopt;
}
std::string type_name(ss.cur_token(), ss.cur_token_size());
if (!ss.Next()) {
PERFETTO_ELOG("Missing deobfuscated name.");
return base::nullopt;
}
std::string deobfuscated_name(ss.cur_token(), ss.cur_token_size());
if (!ss.Next() || ss.cur_token_size() != 2 ||
strncmp("->", ss.cur_token(), 2) != 0) {
PERFETTO_ELOG("Missing ->");
return base::nullopt;
}
if (!ss.Next()) {
PERFETTO_ELOG("Missing obfuscated name.");
return base::nullopt;
}
std::string obfuscated_name(ss.cur_token(), ss.cur_token_size());
if (ss.Next()) {
PERFETTO_ELOG("Unexpected data.");
return base::nullopt;
}
ProguardMemberType member_type;
auto paren_idx = deobfuscated_name.find("(");
if (paren_idx != std::string::npos) {
member_type = ProguardMemberType::kMethod;
deobfuscated_name = deobfuscated_name.substr(0, paren_idx);
auto colon_idx = type_name.find(":");
if (colon_idx != std::string::npos) {
type_name = type_name.substr(colon_idx + 1);
}
} else {
member_type = ProguardMemberType::kField;
}
return ProguardMember{member_type, std::move(obfuscated_name),
std::move(deobfuscated_name)};
}
std::string FlattenMethods(const std::vector<std::string>& v) {
if (v.size() == 1) {
return v[0];
}
return "[ambiguous]";
}
} // namespace
std::string FlattenClasses(
const std::map<std::string, std::vector<std::string>>& m) {
std::string result;
bool first = true;
for (const auto& p : m) {
if (!first) {
result += " | ";
}
result += p.first + "." + FlattenMethods(p.second);
first = false;
}
return result;
}
// See https://www.guardsquare.com/en/products/proguard/manual/retrace for the
// file format we are parsing.
bool ProguardParser::AddLine(std::string line) {
if (line.length() == 0)
return true;
bool is_member = line[0] == ' ';
if (is_member && !current_class_) {
PERFETTO_ELOG("Failed to parse proguard map. Saw member before class.");
return false;
}
if (!is_member) {
auto opt_cls = ParseClass(std::move(line));
if (!opt_cls)
return false;
auto p = mapping_.emplace(std::move(opt_cls->obfuscated_name),
std::move(opt_cls->deobfuscated_name));
if (!p.second) {
PERFETTO_ELOG("Duplicate class.");
return false;
}
current_class_ = &p.first->second;
} else {
auto opt_member = ParseMember(std::move(line));
if (!opt_member)
return false;
switch (opt_member->type) {
case (ProguardMemberType::kField): {
if (!current_class_->AddField(opt_member->obfuscated_name,
opt_member->deobfuscated_name)) {
PERFETTO_ELOG("Member redefinition: %s.%s. Proguard map invalid",
current_class_->deobfuscated_name().c_str(),
opt_member->deobfuscated_name.c_str());
return false;
}
break;
}
case (ProguardMemberType::kMethod): {
current_class_->AddMethod(opt_member->obfuscated_name,
opt_member->deobfuscated_name);
break;
}
}
}
return true;
}
bool ProguardParser::AddLines(std::string contents) {
for (base::StringSplitter lines(std::move(contents), '\n'); lines.Next();) {
if (!AddLine(lines.cur_token()))
return false;
}
return true;
}
void MakeDeobfuscationPackets(
const std::string& package_name,
const std::map<std::string, profiling::ObfuscatedClass>& mapping,
std::function<void(const std::string&)> callback) {
protozero::HeapBuffered<perfetto::protos::pbzero::Trace> trace;
auto* packet = trace->add_packet();
// TODO(fmayer): Add handling for package name and version code here so we
// can support multiple dumps in the same trace.
auto* proto_mapping = packet->set_deobfuscation_mapping();
proto_mapping->set_package_name(package_name);
for (const auto& p : mapping) {
const std::string& obfuscated_class_name = p.first;
const profiling::ObfuscatedClass& cls = p.second;
auto* proto_class = proto_mapping->add_obfuscated_classes();
proto_class->set_obfuscated_name(obfuscated_class_name);
proto_class->set_deobfuscated_name(cls.deobfuscated_name());
for (const auto& field_p : cls.deobfuscated_fields()) {
const std::string& obfuscated_field_name = field_p.first;
const std::string& deobfuscated_field_name = field_p.second;
auto* proto_member = proto_class->add_obfuscated_members();
proto_member->set_obfuscated_name(obfuscated_field_name);
proto_member->set_deobfuscated_name(deobfuscated_field_name);
}
for (const auto& field_p : cls.deobfuscated_methods()) {
const std::string& obfuscated_method_name = field_p.first;
const std::string& deobfuscated_method_name = field_p.second;
auto* proto_member = proto_class->add_obfuscated_methods();
proto_member->set_obfuscated_name(obfuscated_method_name);
proto_member->set_deobfuscated_name(deobfuscated_method_name);
}
}
callback(trace.SerializeAsString());
}
bool ReadProguardMapsToDeobfuscationPackets(
const std::vector<ProguardMap>& maps,
std::function<void(std::string)> fn) {
for (const ProguardMap& map : maps) {
const char* filename = map.filename.c_str();
base::ScopedFstream f(fopen(filename, "re"));
if (!f) {
PERFETTO_ELOG("Failed to open %s", filename);
return false;
}
profiling::ProguardParser parser;
std::string contents;
PERFETTO_CHECK(base::ReadFileStream(*f, &contents));
if (!parser.AddLines(std::move(contents))) {
PERFETTO_ELOG("Failed to parse %s", filename);
return false;
}
std::map<std::string, profiling::ObfuscatedClass> obfuscation_map =
parser.ConsumeMapping();
// TODO(fmayer): right now, we don't use the profile we are given. We can
// filter the output to only contain the classes actually seen in the
// profile.
MakeDeobfuscationPackets(map.package, obfuscation_map, fn);
}
return true;
}
std::vector<ProguardMap> GetPerfettoProguardMapPath() {
const char* env = getenv("PERFETTO_PROGUARD_MAP");
if (env == nullptr)
return {};
std::vector<ProguardMap> res;
for (base::StringSplitter sp(std::string(env), ':'); sp.Next();) {
std::string token(sp.cur_token(), sp.cur_token_size());
size_t eq = token.find('=');
if (eq == std::string::npos) {
PERFETTO_ELOG(
"Invalid PERFETTO_PROGUARD_MAP. "
"Expected format packagename=filename[:packagename=filename...], "
"e.g. com.example.package1=foo.txt:com.example.package2=bar.txt.");
return {};
}
res.emplace_back(ProguardMap{token.substr(0, eq), token.substr(eq + 1)});
}
return res; // for Wreturn-std-move-in-c++11.
}
} // namespace profiling
} // namespace perfetto
<|endoftext|> |
<commit_before>// ------------------------------------------------------------------------
// Pion is a development platform for building Reactors that process Events
// ------------------------------------------------------------------------
// Copyright (C) 2007-2009 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Pion is free software: you can redistribute it and/or modify it under the
// terms of the GNU Affero General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// Pion 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 Pion. If not, see <http://www.gnu.org/licenses/>.
//
#ifndef __PION_SCRIPTREACTOR_HEADER__
#define __PION_SCRIPTREACTOR_HEADER__
#ifdef _MSC_VER
#include <windows.h>
#include <string.h>
#else
#include <errno.h>
#include <unistd.h>
#include <sys/wait.h>
#endif
#include <iosfwd>
#include <string>
#include <vector>
#include <boost/scoped_ptr.hpp>
#include <boost/thread/thread.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <pion/PionConfig.hpp>
#include <pion/PionLogger.hpp>
#include <pion/PionException.hpp>
#include <pion/PionScheduler.hpp>
#include <pion/platform/Codec.hpp>
#include <pion/platform/Reactor.hpp>
#ifdef _MSC_VER
#define FILE_DESC_TYPE HANDLE
#define INVALID_DESCRIPTOR INVALID_HANDLE_VALUE
#define CLOSE_DESCRIPTOR(x) CloseHandle(x)
#define PROCESS_INFO_TYPE LPPROCESS_INFORMATION
#define INVALID_PROCESS NULL
#else
#define FILE_DESC_TYPE int
#define INVALID_DESCRIPTOR -1
#define CLOSE_DESCRIPTOR(x) ::close(x)
#define PROCESS_INFO_TYPE pid_t
#define INVALID_PROCESS -1
#endif
namespace pion { // begin namespace pion
namespace plugins { // begin namespace plugins
///
/// ScriptReactor: interfaces with an external shell script or program
///
class ScriptReactor :
public pion::platform::Reactor
{
public:
/// exception thrown if the Reactor configuration does not define an Input Codec
class EmptyInputCodecException : public PionException {
public:
EmptyInputCodecException(const std::string& reactor_id)
: PionException("ScriptReactor configuration is missing a required InputCodec parameter: ", reactor_id) {}
};
/// exception thrown if the Reactor configuration does not define an Output Codec
class EmptyOutputCodecException : public PionException {
public:
EmptyOutputCodecException(const std::string& reactor_id)
: PionException("ScriptReactor configuration is missing a required OutputCodec parameter: ", reactor_id) {}
};
/// exception thrown if the Reactor configuration does not define a Command
class EmptyCommandException : public PionException {
public:
EmptyCommandException(const std::string& reactor_id)
: PionException("ScriptReactor configuration is missing a required Command parameter: ", reactor_id) {}
};
/// exception thrown if there is a problem parsing arguments out of the command string
class CommandParsingException : public PionException {
public:
CommandParsingException(const std::string& command)
: PionException("ScriptReactor was unable to parse arguments out of command string: ", command) {}
};
/// exception thrown if opening a pipe to the shell command fails
class OpenPipeException : public PionException {
public:
OpenPipeException(const std::string& command)
: PionException("ScriptReactor failed to open pipe: ", command) {}
};
/// exception thrown if the Reactor has trouble reading events from the pipe
class ReadFromPipeException : public PionException {
public:
ReadFromPipeException(const std::string& reactor_id)
: PionException("ScriptReactor failed reading an event from pipe: ", reactor_id) {}
};
/// exception thrown if the Reactor has trouble writing events to the pipe
class WriteToPipeException : public PionException {
public:
WriteToPipeException(const std::string& reactor_id)
: PionException("ScriptReactor failed writing an event to pipe: ", reactor_id) {}
};
/// constructs a new ScriptReactor object
ScriptReactor(void)
: Reactor(TYPE_PROCESSING),
m_logger(PION_GET_LOGGER("pion.ScriptReactor")),
m_input_pipe(INVALID_DESCRIPTOR), m_output_pipe(INVALID_DESCRIPTOR), m_child(INVALID_PROCESS)
{
}
/// virtual destructor: this class is meant to be extended
virtual ~ScriptReactor() { stop(); }
/// called by the ReactorEngine to start Event processing
virtual void start(void);
/// called by the ReactorEngine to stop Event processing
virtual void stop(void) { stopIfRunning(); }
/**
* sets configuration parameters for this Reactor
*
* @param v the Vocabulary that this Reactor will use to describe Terms
* @param config_ptr pointer to a list of XML nodes containing Reactor
* configuration parameters
*/
virtual void setConfig(const pion::platform::Vocabulary& v, const xmlNodePtr config_ptr);
/**
* this updates the Vocabulary information used by this Reactor; it should
* be called whenever the global Vocabulary is updated
*
* @param v the Vocabulary that this Reactor will use to describe Terms
*/
virtual void updateVocabulary(const pion::platform::Vocabulary& v);
/**
* this updates the Codecs that are used by this Reactor; it should
* be called whenever any Codec's configuration is updated
*/
virtual void updateCodecs(void);
/**
* processes an Event by delivering it to the shell script or program
*
* @param e pointer to the Event to process
*/
virtual void process(const pion::platform::EventPtr& e);
/// sets the logger to be used
inline void setLogger(PionLogger log_ptr) { m_logger = log_ptr; }
/// returns the logger currently in use
inline PionLogger getLogger(void) { return m_logger; }
private:
/// stops the reactor and returns true if it was running
bool stopIfRunning(void);
/// thread function to read events from the script command
void readEvents(void);
/// opens a pipe to the script command
void openPipe(void);
/// closes the pipe to the script command
void closePipe(void);
/// parses out individual arguments from a command string
void parseArguments(void);
#ifdef BOOST_IOSTREAMS_WINDOWS
struct winpipe_handle_source : private boost::iostreams::file_descriptor {
typedef char char_type;
struct category : boost::iostreams::source_tag, boost::iostreams::closable_tag { };
std::streamsize read(char_type* s, std::streamsize n) {
DWORD result = 0, error = 0;
if (!::ReadFile(handle(), s, n, &result, NULL) && (error = GetLastError()) != ERROR_BROKEN_PIPE)
throw boost::iostreams::detail::bad_read();
return error == ERROR_BROKEN_PIPE ? -1 : static_cast<std::streamsize>(result);
}
using boost::iostreams::file_descriptor::close;
using boost::iostreams::file_descriptor::handle;
explicit winpipe_handle_source(HANDLE h) : boost::iostreams::file_descriptor(h) { }
};
struct winpipe_handle_sink : private boost::iostreams::file_descriptor {
typedef char char_type;
struct category : boost::iostreams::sink_tag, boost::iostreams::closable_tag { };
std::streamsize write(const char_type* s, std::streamsize n) {
DWORD ignore = 0;
if (!::WriteFile(handle(), s, n, &ignore, NULL))
throw boost::iostreams::detail::bad_write();
return n;
}
using boost::iostreams::file_descriptor::close;
using boost::iostreams::file_descriptor::handle;
explicit winpipe_handle_sink(HANDLE h) : boost::iostreams::file_descriptor(h) { }
};
/// data types for iostreams streambufs that use Windows pipe file-handles
typedef boost::iostreams::stream_buffer<winpipe_handle_source> IStreamBuffer;
typedef boost::iostreams::stream_buffer<winpipe_handle_sink> OStreamBuffer;
#else
/// data types for iostreams streambufs that use C-style file descriptors
typedef boost::iostreams::stream_buffer<boost::iostreams::file_descriptor_source> IStreamBuffer;
typedef boost::iostreams::stream_buffer<boost::iostreams::file_descriptor_sink> OStreamBuffer;
#endif
/// name of the InputCodec element for Pion XML config files
static const std::string INPUT_CODEC_ELEMENT_NAME;
/// name of the OutputCodec element for Pion XML config files
static const std::string OUTPUT_CODEC_ELEMENT_NAME;
/// name of the Command element for Pion XML config files
static const std::string COMMAND_ELEMENT_NAME;
/// primary logging interface used by this class
PionLogger m_logger;
/// pointer to the Codec that is used for writing Events to the script
pion::platform::CodecPtr m_input_codec_ptr;
/// pointer to the Codec that is used for reading Events from the script
pion::platform::CodecPtr m_output_codec_ptr;
/// unique identifier of the Codec that is used for writing Events
std::string m_input_codec_id;
/// unique identifier of the Codec that is used for reading Events
std::string m_output_codec_id;
/// name of the shell script or program to execute (includes all arguments)
std::string m_command;
/// vector of command arguments parsed out (the first is the executable or script)
std::vector<std::string> m_args;
/// pipe used to write Events to the shell script or program
FILE_DESC_TYPE m_input_pipe;
/// pipe used to read Events from the shell script or program
FILE_DESC_TYPE m_output_pipe;
/// process id for the shell script or program
PROCESS_INFO_TYPE m_child;
/// pointer to a C++ stream buffer used to write Events to the pipe
boost::scoped_ptr<OStreamBuffer> m_input_streambuf_ptr;
/// pointer to a C++ stream buffer used to read Events from the pipe
boost::scoped_ptr<IStreamBuffer> m_output_streambuf_ptr;
/// pointer to a C++ iostream used to write Events to the pipe
boost::scoped_ptr<std::ostream> m_input_stream_ptr;
/// pointer to a C++ iostream used to read Events from the pipe
boost::scoped_ptr<std::istream> m_output_stream_ptr;
/// thread used to read events generated by the script
boost::scoped_ptr<boost::thread> m_thread_ptr;
/// used to ensure only event may be written at a time
boost::mutex m_write_mutex;
};
} // end namespace plugins
} // end namespace pion
#endif
<commit_msg>fix for boost 1.42 (on Windows)<commit_after>// ------------------------------------------------------------------------
// Pion is a development platform for building Reactors that process Events
// ------------------------------------------------------------------------
// Copyright (C) 2007-2009 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Pion is free software: you can redistribute it and/or modify it under the
// terms of the GNU Affero General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// Pion 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 Pion. If not, see <http://www.gnu.org/licenses/>.
//
#ifndef __PION_SCRIPTREACTOR_HEADER__
#define __PION_SCRIPTREACTOR_HEADER__
#ifdef _MSC_VER
#include <windows.h>
#include <string.h>
#else
#include <errno.h>
#include <unistd.h>
#include <sys/wait.h>
#endif
#include <iosfwd>
#include <string>
#include <vector>
#include <boost/scoped_ptr.hpp>
#include <boost/thread/thread.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <pion/PionConfig.hpp>
#include <pion/PionLogger.hpp>
#include <pion/PionException.hpp>
#include <pion/PionScheduler.hpp>
#include <pion/platform/Codec.hpp>
#include <pion/platform/Reactor.hpp>
#ifdef _MSC_VER
#define FILE_DESC_TYPE HANDLE
#define INVALID_DESCRIPTOR INVALID_HANDLE_VALUE
#define CLOSE_DESCRIPTOR(x) CloseHandle(x)
#define PROCESS_INFO_TYPE LPPROCESS_INFORMATION
#define INVALID_PROCESS NULL
#else
#define FILE_DESC_TYPE int
#define INVALID_DESCRIPTOR -1
#define CLOSE_DESCRIPTOR(x) ::close(x)
#define PROCESS_INFO_TYPE pid_t
#define INVALID_PROCESS -1
#endif
namespace pion { // begin namespace pion
namespace plugins { // begin namespace plugins
///
/// ScriptReactor: interfaces with an external shell script or program
///
class ScriptReactor :
public pion::platform::Reactor
{
public:
/// exception thrown if the Reactor configuration does not define an Input Codec
class EmptyInputCodecException : public PionException {
public:
EmptyInputCodecException(const std::string& reactor_id)
: PionException("ScriptReactor configuration is missing a required InputCodec parameter: ", reactor_id) {}
};
/// exception thrown if the Reactor configuration does not define an Output Codec
class EmptyOutputCodecException : public PionException {
public:
EmptyOutputCodecException(const std::string& reactor_id)
: PionException("ScriptReactor configuration is missing a required OutputCodec parameter: ", reactor_id) {}
};
/// exception thrown if the Reactor configuration does not define a Command
class EmptyCommandException : public PionException {
public:
EmptyCommandException(const std::string& reactor_id)
: PionException("ScriptReactor configuration is missing a required Command parameter: ", reactor_id) {}
};
/// exception thrown if there is a problem parsing arguments out of the command string
class CommandParsingException : public PionException {
public:
CommandParsingException(const std::string& command)
: PionException("ScriptReactor was unable to parse arguments out of command string: ", command) {}
};
/// exception thrown if opening a pipe to the shell command fails
class OpenPipeException : public PionException {
public:
OpenPipeException(const std::string& command)
: PionException("ScriptReactor failed to open pipe: ", command) {}
};
/// exception thrown if the Reactor has trouble reading events from the pipe
class ReadFromPipeException : public PionException {
public:
ReadFromPipeException(const std::string& reactor_id)
: PionException("ScriptReactor failed reading an event from pipe: ", reactor_id) {}
};
/// exception thrown if the Reactor has trouble writing events to the pipe
class WriteToPipeException : public PionException {
public:
WriteToPipeException(const std::string& reactor_id)
: PionException("ScriptReactor failed writing an event to pipe: ", reactor_id) {}
};
/// constructs a new ScriptReactor object
ScriptReactor(void)
: Reactor(TYPE_PROCESSING),
m_logger(PION_GET_LOGGER("pion.ScriptReactor")),
m_input_pipe(INVALID_DESCRIPTOR), m_output_pipe(INVALID_DESCRIPTOR), m_child(INVALID_PROCESS)
{
}
/// virtual destructor: this class is meant to be extended
virtual ~ScriptReactor() { stop(); }
/// called by the ReactorEngine to start Event processing
virtual void start(void);
/// called by the ReactorEngine to stop Event processing
virtual void stop(void) { stopIfRunning(); }
/**
* sets configuration parameters for this Reactor
*
* @param v the Vocabulary that this Reactor will use to describe Terms
* @param config_ptr pointer to a list of XML nodes containing Reactor
* configuration parameters
*/
virtual void setConfig(const pion::platform::Vocabulary& v, const xmlNodePtr config_ptr);
/**
* this updates the Vocabulary information used by this Reactor; it should
* be called whenever the global Vocabulary is updated
*
* @param v the Vocabulary that this Reactor will use to describe Terms
*/
virtual void updateVocabulary(const pion::platform::Vocabulary& v);
/**
* this updates the Codecs that are used by this Reactor; it should
* be called whenever any Codec's configuration is updated
*/
virtual void updateCodecs(void);
/**
* processes an Event by delivering it to the shell script or program
*
* @param e pointer to the Event to process
*/
virtual void process(const pion::platform::EventPtr& e);
/// sets the logger to be used
inline void setLogger(PionLogger log_ptr) { m_logger = log_ptr; }
/// returns the logger currently in use
inline PionLogger getLogger(void) { return m_logger; }
private:
/// stops the reactor and returns true if it was running
bool stopIfRunning(void);
/// thread function to read events from the script command
void readEvents(void);
/// opens a pipe to the script command
void openPipe(void);
/// closes the pipe to the script command
void closePipe(void);
/// parses out individual arguments from a command string
void parseArguments(void);
#ifdef BOOST_IOSTREAMS_WINDOWS
struct winpipe_handle_source : private boost::iostreams::file_descriptor {
typedef char char_type;
struct category : boost::iostreams::source_tag, boost::iostreams::closable_tag { };
std::streamsize read(char_type* s, std::streamsize n) {
DWORD result = 0, error = 0;
if (!::ReadFile(handle(), s, n, &result, NULL) && (error = GetLastError()) != ERROR_BROKEN_PIPE)
throw boost::iostreams::detail::bad_read();
return error == ERROR_BROKEN_PIPE ? -1 : static_cast<std::streamsize>(result);
}
using boost::iostreams::file_descriptor::close;
using boost::iostreams::file_descriptor::handle;
explicit winpipe_handle_source(HANDLE h) : boost::iostreams::file_descriptor(h) { }
winpipe_handle_source(const winpipe_handle_source& w) :
boost::iostreams::file_descriptor(static_cast<const boost::iostreams::file_descriptor&>(w)) { }
};
struct winpipe_handle_sink : private boost::iostreams::file_descriptor {
typedef char char_type;
struct category : boost::iostreams::sink_tag, boost::iostreams::closable_tag { };
std::streamsize write(const char_type* s, std::streamsize n) {
DWORD ignore = 0;
if (!::WriteFile(handle(), s, n, &ignore, NULL))
throw boost::iostreams::detail::bad_write();
return n;
}
using boost::iostreams::file_descriptor::close;
using boost::iostreams::file_descriptor::handle;
explicit winpipe_handle_sink(HANDLE h) : boost::iostreams::file_descriptor(h) { }
winpipe_handle_sink(const winpipe_handle_sink& w) :
boost::iostreams::file_descriptor(static_cast<const boost::iostreams::file_descriptor&>(w)) { }
};
/// data types for iostreams streambufs that use Windows pipe file-handles
typedef boost::iostreams::stream_buffer<winpipe_handle_source> IStreamBuffer;
typedef boost::iostreams::stream_buffer<winpipe_handle_sink> OStreamBuffer;
#else
/// data types for iostreams streambufs that use C-style file descriptors
typedef boost::iostreams::stream_buffer<boost::iostreams::file_descriptor_source> IStreamBuffer;
typedef boost::iostreams::stream_buffer<boost::iostreams::file_descriptor_sink> OStreamBuffer;
#endif
/// name of the InputCodec element for Pion XML config files
static const std::string INPUT_CODEC_ELEMENT_NAME;
/// name of the OutputCodec element for Pion XML config files
static const std::string OUTPUT_CODEC_ELEMENT_NAME;
/// name of the Command element for Pion XML config files
static const std::string COMMAND_ELEMENT_NAME;
/// primary logging interface used by this class
PionLogger m_logger;
/// pointer to the Codec that is used for writing Events to the script
pion::platform::CodecPtr m_input_codec_ptr;
/// pointer to the Codec that is used for reading Events from the script
pion::platform::CodecPtr m_output_codec_ptr;
/// unique identifier of the Codec that is used for writing Events
std::string m_input_codec_id;
/// unique identifier of the Codec that is used for reading Events
std::string m_output_codec_id;
/// name of the shell script or program to execute (includes all arguments)
std::string m_command;
/// vector of command arguments parsed out (the first is the executable or script)
std::vector<std::string> m_args;
/// pipe used to write Events to the shell script or program
FILE_DESC_TYPE m_input_pipe;
/// pipe used to read Events from the shell script or program
FILE_DESC_TYPE m_output_pipe;
/// process id for the shell script or program
PROCESS_INFO_TYPE m_child;
/// pointer to a C++ stream buffer used to write Events to the pipe
boost::scoped_ptr<OStreamBuffer> m_input_streambuf_ptr;
/// pointer to a C++ stream buffer used to read Events from the pipe
boost::scoped_ptr<IStreamBuffer> m_output_streambuf_ptr;
/// pointer to a C++ iostream used to write Events to the pipe
boost::scoped_ptr<std::ostream> m_input_stream_ptr;
/// pointer to a C++ iostream used to read Events from the pipe
boost::scoped_ptr<std::istream> m_output_stream_ptr;
/// thread used to read events generated by the script
boost::scoped_ptr<boost::thread> m_thread_ptr;
/// used to ensure only event may be written at a time
boost::mutex m_write_mutex;
};
} // end namespace plugins
} // end namespace pion
#endif
<|endoftext|> |
<commit_before>// RhoLaunch.cpp : Defines the entry point for the application.
//
#include "windows.h"
#include "RhoLaunch.h"
#define MAX_LOADSTRING 100
#define PB_WINDOW_RESTORE WM_USER + 10
// Global Functions:
int LaunchProcess( LPTSTR pFilePath, LPTSTR pCmdLine);
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
COPYDATASTRUCT launchData;
//validate the command line
int iLen = wcslen(lpCmdLine);
if(iLen < 3){
return 1;
}
//LPWSTR pAppName = new WCHAR[iLen + 3];//allow space for the index
LPWSTR pAppName,pTabName,pTemp;
pAppName = pTemp= lpCmdLine;
int iLoop;
bool bStart,bTabStart,bAppName;
bStart = bTabStart = bAppName= false;
for(iLoop = 0;iLoop < iLen ;iLoop++)
{
if(lpCmdLine[iLoop] == L' '){
if(bStart){
if(!bAppName){
*pTemp = NULL;//terminate the app name
pTemp++;
bAppName = true;
pTabName = pTemp;
}
else if(bTabStart){
*pTemp = NULL;//terminate the tab name
break;//finished so exit loop
}
}
continue;//ignore spaces
}
if(lpCmdLine[iLoop] == L'/'){
if(!bStart){
bStart = !bStart;
continue;
}
if(!bAppName){
*pTemp= NULL;
bAppName = !bAppName;
bTabStart = true;
}
if(!bTabStart){
bTabStart = true;
continue;
}
}
*pTemp= lpCmdLine[iLoop];
pTemp++;
}
*pTemp = NULL;
HWND hwndRunningRE = FindWindow(NULL, pAppName);
if (hwndRunningRE){
// Found the running instance
//rhode expects a MultiByte string so convert
int ilen = wcslen(pTabName);
char *pTabNameMB = new char[ilen+1];
wcstombs(pTabNameMB, pTabName,ilen);
launchData.lpData = pTabNameMB;
launchData.cbData = (ilen+1);
ShowWindow(hwndRunningRE, SW_RESTORE);
SendMessage(hwndRunningRE,PB_WINDOW_RESTORE,(WPARAM) NULL,(LPARAM)TRUE);
//send a message to inform Rho of the requested index
SendMessage(hwndRunningRE,WM_COPYDATA,(WPARAM)NULL,(LPARAM) (LPVOID) &launchData );
delete [] pTabNameMB;
// switch to it
SetForegroundWindow(hwndRunningRE);
}
else{
//no window handle, so try to start the app
//will only work if RhoLaunch is in the same directory as the app
//build the Rho app name
WCHAR pApp[MAX_PATH + 1];
int iIndex,iLen;
if(!(iLen = GetModuleFileName(NULL,pApp,MAX_PATH))){
return 1;//error could not find the path
}
//remove 'RhoLaunch' from the path
for(iIndex = iLen - 1;pApp[iIndex]!=L'\\';iIndex--);
pApp[iIndex+ 1] = NULL;
//LPWSTR pApp = new WCHAR[wcslen(pAppName)+10];
wcscat(pApp,pAppName);
wcscat(pApp,L".exe");
LPWSTR pTabCommand = new WCHAR[wcslen(pTabName)+20];
wsprintf(pTabCommand,L"/tabname=\"%s\"",pTabName);
LaunchProcess(pApp,pTabCommand);
delete [] pTabCommand;
}
return 0;
}
int LaunchProcess( LPTSTR pFilePath, LPTSTR pCmdLine)
{
STARTUPINFO StartInfo;
PROCESS_INFORMATION ProcessInfo;
BOOL bOk;
// Reset the contents of the 'Process Information' and 'Start Up' structures.
memset( &ProcessInfo, 0, sizeof( PROCESS_INFORMATION));
memset( &StartInfo, 0, sizeof( STARTUPINFO));
StartInfo.cb = sizeof( STARTUPINFO);
// Create the 'browser' in a seperate process.
bOk = CreateProcess( pFilePath, // LPCTSTR lpApplicationName,//L"\\program files\\Neon\\BIN\\SVC_Controls.exe",
pCmdLine, // LPTSTR lpCommandLine,
NULL, // LPSECURITY_ATTRIBUTES lpProcessAttributes,
NULL, // LPSECURITY_ATTRIBUTES lpThreadAttributes,
FALSE, // BOOL bInheritHandles,
0, // DWORD dwCreationFlags,
NULL, // LPVOID lpEnvironment,
NULL, // LPCTSTR lpCurrentDirectory,
&StartInfo, // LPSTARTUPINFO lpStartupInfo,
&ProcessInfo); // LPPROCESS_INFORMATION lpProcessInformation
//m_dwProcessID = ProcessInfo.dwProcessId;
// If all is Ok, then return '0' else return the last error code.
return bOk ? 0 : GetLastError();
}<commit_msg>Modifying RhoLaunch to look for Window's ClassName<commit_after>// RhoLaunch.cpp : Defines the entry point for the application.
//
#include "windows.h"
#include "RhoLaunch.h"
#define MAX_LOADSTRING 100
#define PB_WINDOW_RESTORE WM_USER + 10
// Global Functions:
int LaunchProcess( LPTSTR pFilePath, LPTSTR pCmdLine);
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
COPYDATASTRUCT launchData;
//validate the command line
int iLen = wcslen(lpCmdLine);
if(iLen < 3){
return 1;
}
//LPWSTR pAppName = new WCHAR[iLen + 3];//allow space for the index
LPWSTR pAppName,pTabName,pTemp;
pAppName = pTemp= lpCmdLine;
int iLoop;
bool bStart,bTabStart,bAppName;
bStart = bTabStart = bAppName= false;
for(iLoop = 0;iLoop < iLen ;iLoop++)
{
if(lpCmdLine[iLoop] == L' '){
if(bStart){
if(!bAppName){
*pTemp = NULL;//terminate the app name
pTemp++;
bAppName = true;
pTabName = pTemp;
}
else if(bTabStart){
*pTemp = NULL;//terminate the tab name
break;//finished so exit loop
}
}
continue;//ignore spaces
}
if(lpCmdLine[iLoop] == L'/'){
if(!bStart){
bStart = !bStart;
continue;
}
if(!bAppName){
*pTemp= NULL;
bAppName = !bAppName;
bTabStart = true;
}
if(!bTabStart){
bTabStart = true;
continue;
}
}
*pTemp= lpCmdLine[iLoop];
pTemp++;
}
*pTemp = NULL;
// HWND hwndRunningRE = FindWindow(NULL, pAppName);
// DCC Main Window now has Classname <pAppName>.MainWindow
WCHAR* szClassName = new WCHAR[wcslen(pAppName) + wcslen(L".MainWindow") + 1];
wcscpy(szClassName, pAppName);
wcscat(szClassName, L".MainWindow");
HWND hwndRunningRE = FindWindow(szClassName, NULL);
delete[] szClassName;
if (hwndRunningRE){
// Found the running instance
//rhode expects a MultiByte string so convert
int ilen = wcslen(pTabName);
char *pTabNameMB = new char[ilen+1];
wcstombs(pTabNameMB, pTabName,ilen);
launchData.lpData = pTabNameMB;
launchData.cbData = (ilen+1);
ShowWindow(hwndRunningRE, SW_RESTORE);
SendMessage(hwndRunningRE,PB_WINDOW_RESTORE,(WPARAM) NULL,(LPARAM)TRUE);
//send a message to inform Rho of the requested index
SendMessage(hwndRunningRE,WM_COPYDATA,(WPARAM)NULL,(LPARAM) (LPVOID) &launchData );
delete [] pTabNameMB;
// switch to it
SetForegroundWindow(hwndRunningRE);
}
else{
//no window handle, so try to start the app
//will only work if RhoLaunch is in the same directory as the app
//build the Rho app name
WCHAR pApp[MAX_PATH + 1];
int iIndex,iLen;
if(!(iLen = GetModuleFileName(NULL,pApp,MAX_PATH))){
return 1;//error could not find the path
}
//remove 'RhoLaunch' from the path
for(iIndex = iLen - 1;pApp[iIndex]!=L'\\';iIndex--);
pApp[iIndex+ 1] = NULL;
//LPWSTR pApp = new WCHAR[wcslen(pAppName)+10];
wcscat(pApp,pAppName);
wcscat(pApp,L".exe");
LPWSTR pTabCommand = new WCHAR[wcslen(pTabName)+20];
wsprintf(pTabCommand,L"/tabname=\"%s\"",pTabName);
LaunchProcess(pApp,pTabCommand);
delete [] pTabCommand;
}
return 0;
}
int LaunchProcess( LPTSTR pFilePath, LPTSTR pCmdLine)
{
STARTUPINFO StartInfo;
PROCESS_INFORMATION ProcessInfo;
BOOL bOk;
// Reset the contents of the 'Process Information' and 'Start Up' structures.
memset( &ProcessInfo, 0, sizeof( PROCESS_INFORMATION));
memset( &StartInfo, 0, sizeof( STARTUPINFO));
StartInfo.cb = sizeof( STARTUPINFO);
// Create the 'browser' in a seperate process.
bOk = CreateProcess( pFilePath, // LPCTSTR lpApplicationName,//L"\\program files\\Neon\\BIN\\SVC_Controls.exe",
pCmdLine, // LPTSTR lpCommandLine,
NULL, // LPSECURITY_ATTRIBUTES lpProcessAttributes,
NULL, // LPSECURITY_ATTRIBUTES lpThreadAttributes,
FALSE, // BOOL bInheritHandles,
0, // DWORD dwCreationFlags,
NULL, // LPVOID lpEnvironment,
NULL, // LPCTSTR lpCurrentDirectory,
&StartInfo, // LPSTARTUPINFO lpStartupInfo,
&ProcessInfo); // LPPROCESS_INFORMATION lpProcessInformation
//m_dwProcessID = ProcessInfo.dwProcessId;
// If all is Ok, then return '0' else return the last error code.
return bOk ? 0 : GetLastError();
}<|endoftext|> |
<commit_before>#include "myofferwhitelisttablemodel.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "wallet/wallet.h"
#include "base58.h"
#include <QFont>
using namespace std;
struct MyOfferWhitelistTableEntry
{
QString offer;
QString alias;
QString expires;
QString discount;
MyOfferWhitelistTableEntry() {}
MyOfferWhitelistTableEntry(const QString &offer, const QString &alias, const QString &expires,const QString &discount):
offer(offer), alias(alias), expires(expires),discount(discount) {}
};
// Private implementation
class MyOfferWhitelistTablePriv
{
public:
QList<MyOfferWhitelistTableEntry> cachedEntryTable;
MyOfferWhitelistTableModel *parent;
MyOfferWhitelistTablePriv(MyOfferWhitelistTableModel *parent):
parent(parent) {}
void updateEntry(const QString &offer, const QString &alias, const QString &expires,const QString &discount, int status)
{
if(!parent)
{
return;
}
switch(status)
{
case CT_NEW:
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedEntryTable.insert(lowerIndex, MyOfferWhitelistTableEntry(offer, alias, expires, discount));
parent->endInsertRows();
break;
case CT_UPDATED:
lower->offer = offer;
lower->alias = alias;
lower->expires = expires;
lower->discount = discount;
parent->emitDataChanged(lowerIndex);
break;
case CT_DELETED:
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
cachedEntryTable.erase(lower, upper);
parent->endRemoveRows();
break;
}
}
int size()
{
return cachedEntryTable.size();
}
MyOfferWhitelistTableEntry *index(int idx)
{
if(idx >= 0 && idx < cachedEntryTable.size())
{
return &cachedEntryTable[idx];
}
else
{
return 0;
}
}
};
MyOfferWhitelistTableModel::MyOfferWhitelistTableModel(WalletModel *parent) :
QAbstractTableModel(parent)
{
columns << tr("Offer") << tr("Alias") << tr("Discount") << tr("Expires In");
priv = new OfferWhitelistTablePriv(this);
}
MyOfferWhitelistTableModel::~MyOfferWhitelistTableModel()
{
delete priv;
}
int MyOfferWhitelistTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int MyOfferWhitelistTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant MyOfferWhitelistTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
MyOfferWhitelistTableEntry *rec = static_cast<MyOfferWhitelistTableEntry*>(index.internalPointer());
if(role == Qt::DisplayRole || role == Qt::EditRole)
{
switch(index.column())
{
case Offer:
return rec->offer;
case Alias:
return rec->alias;
case Discount:
return rec->discount;
case Expires:
return rec->expires;
}
}
else if (role == AliasRole)
{
return rec->alias;
}
return QVariant();
}
bool MyOfferWhitelistTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if(!index.isValid())
return false;
MyOfferWhitelistTableEntry *rec = static_cast<MyOfferWhitelistTableEntry*>(index.internalPointer());
editStatus = OK;
if(role == Qt::EditRole)
{
switch(index.column())
{
case Offer:
// Do nothing, if old value == new value
if(rec->offer == value.toString())
{
editStatus = NO_CHANGES;
return false;
}
break;
case Alias:
// Do nothing, if old value == new value
if(rec->alias == value.toString())
{
editStatus = NO_CHANGES;
return false;
}
break;
case Discount:
// Do nothing, if old value == new value
if(rec->discount == value.toString())
{
editStatus = NO_CHANGES;
return false;
}
break;
case Expires:
// Do nothing, if old value == new value
if(rec->expires == value.toString())
{
editStatus = NO_CHANGES;
return false;
}
break;
return true;
}
}
return false;
}
QVariant MyOfferWhitelistTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole)
{
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags MyOfferWhitelistTableModel::flags(const QModelIndex &index) const
{
if(!index.isValid())
return 0;
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
return retval;
}
QModelIndex MyOfferWhitelistTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
MyOfferWhitelistTableEntry *data = priv->index(row);
if(data)
{
return createIndex(row, column, priv->index(row));
}
else
{
return QModelIndex();
}
}
void MyOfferWhitelistTableModel::updateEntry(const QString &offer, const QString &alias, const QString &expires,const QString &discount, int status)
{
priv->updateEntry(offer, alias, expires, discount, status);
}
QString MyOfferWhitelistTableModel::addRow(const QString &offer, const QString &alias, const QString &expires,const QString &discount)
{
std::string strAlias = alias.toStdString();
editStatus = OK;
return QString::fromStdString(strAlias);
}
void MyOfferWhitelistTableModel::clear()
{
beginResetModel();
priv->cachedEntryTable.clear();
endResetModel();
}
void MyOfferWhitelistTableModel::emitDataChanged(int idx)
{
Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));
}
<commit_msg>typo<commit_after>#include "offerwhitelisttablemodel.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "wallet/wallet.h"
#include "base58.h"
#include <QFont>
using namespace std;
struct MyOfferWhitelistTableEntry
{
QString offer;
QString alias;
QString expires;
QString discount;
MyOfferWhitelistTableEntry() {}
MyOfferWhitelistTableEntry(const QString &offer, const QString &alias, const QString &expires,const QString &discount):
offer(offer), alias(alias), expires(expires),discount(discount) {}
};
struct MyOfferWhitelistTableEntryLessThan
{
bool operator()(const MyOfferWhitelistTableEntry &a, const MyOfferWhitelistTableEntry &b) const
{
return a.offer < b.offer;
}
bool operator()(const MyOfferWhitelistTableEntry &a, const QString &b) const
{
return a.offer < b;
}
bool operator()(const QString &a, const MyOfferWhitelistTableEntry &b) const
{
return a < b.offer;
}
};
// Private implementation
class MyOfferWhitelistTablePriv
{
public:
QList<MyOfferWhitelistTableEntry> cachedEntryTable;
MyOfferWhitelistTableModel *parent;
OfferWhitelistTablePriv(MyOfferWhitelistTableModel *parent):
parent(parent) {}
void updateEntry(const QString &offer, const QString &alias, const QString &expires,const QString &discount, int status)
{
if(!parent)
{
return;
}
// Find offer / value in model
QList<MyOfferWhitelistTableEntry>::iterator lower = qLowerBound(
cachedEntryTable.begin(), cachedEntryTable.end(), offer, MyOfferWhitelistTableEntryLessThan());
QList<MyOfferWhitelistTableEntry>::iterator upper = qUpperBound(
cachedEntryTable.begin(), cachedEntryTable.end(), offer, MyOfferWhitelistTableEntryLessThan());
int lowerIndex = (lower - cachedEntryTable.begin());
int upperIndex = (upper - cachedEntryTable.begin());
bool inModel = (lower != upper);
switch(status)
{
case CT_NEW:
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedEntryTable.insert(lowerIndex, OfferWhitelistTableEntry(alias, expires, discount));
parent->endInsertRows();
break;
case CT_UPDATED:
lower->alias = alias;
lower->expires = expires;
lower->discount = discount;
parent->emitDataChanged(lowerIndex);
break;
case CT_DELETED:
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);
cachedEntryTable.erase(lower, upper);
parent->endRemoveRows();
break;
}
}
int size()
{
return cachedEntryTable.size();
}
OfferWhitelistTableEntry *index(int idx)
{
if(idx >= 0 && idx < cachedEntryTable.size())
{
return &cachedEntryTable[idx];
}
else
{
return 0;
}
}
};
MyOfferWhitelistTableModel::MyOfferWhitelistTableModel(WalletModel *parent) :
QAbstractTableModel(parent)
{
columns << tr("Alias") << tr("Discount") << tr("Expires In");
priv = new OfferWhitelistTablePriv(this);
}
MyOfferWhitelistTableModel::~MyOfferWhitelistTableModel()
{
delete priv;
}
int MyOfferWhitelistTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int MyOfferWhitelistTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant MyOfferWhitelistTableModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
return QVariant();
OfferWhitelistTableEntry *rec = static_cast<OfferWhitelistTableEntry*>(index.internalPointer());
if(role == Qt::DisplayRole || role == Qt::EditRole)
{
switch(index.column())
{
case Alias:
return rec->alias;
case Discount:
return rec->discount;
case Expires:
return rec->expires;
}
}
else if (role == AliasRole)
{
return rec->alias;
}
return QVariant();
}
bool MyOfferWhitelistTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if(!index.isValid())
return false;
OfferWhitelistTableEntry *rec = static_cast<OfferWhitelistTableEntry*>(index.internalPointer());
editStatus = OK;
if(role == Qt::EditRole)
{
switch(index.column())
{
case Alias:
// Do nothing, if old value == new value
if(rec->alias == value.toString())
{
editStatus = NO_CHANGES;
return false;
}
break;
case Discount:
// Do nothing, if old value == new value
if(rec->discount == value.toString())
{
editStatus = NO_CHANGES;
return false;
}
break;
case Expires:
// Do nothing, if old value == new value
if(rec->expires == value.toString())
{
editStatus = NO_CHANGES;
return false;
}
break;
return true;
}
}
return false;
}
QVariant MyOfferWhitelistTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(orientation == Qt::Horizontal)
{
if(role == Qt::DisplayRole)
{
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags MyOfferWhitelistTableModel::flags(const QModelIndex &index) const
{
if(!index.isValid())
return 0;
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
return retval;
}
QModelIndex MyOfferWhitelistTableModel::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent);
OfferWhitelistTableEntry *data = priv->index(row);
if(data)
{
return createIndex(row, column, priv->index(row));
}
else
{
return QModelIndex();
}
}
void MyOfferWhitelistTableModel::updateEntry(const QString &alias, const QString &expires,const QString &discount, int status)
{
priv->updateEntry(alias, expires, discount, status);
}
QString MyOfferWhitelistTableModel::addRow(const QString &alias, const QString &expires,const QString &discount)
{
std::string strAlias = alias.toStdString();
editStatus = OK;
return QString::fromStdString(strAlias);
}
void MyOfferWhitelistTableModel::clear()
{
beginResetModel();
priv->cachedEntryTable.clear();
endResetModel();
}
void MyOfferWhitelistTableModel::emitDataChanged(int idx)
{
Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));
}
<|endoftext|> |
<commit_before>//Code from KGPG
/***************************************************************************
listkeys.cpp - description
-------------------
begin : Thu Jul 4 2002
copyright : (C) 2002 by y0k0
email : bj@altern.org
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
////////////////////////////////////////////////////// code for the key management
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <qlayout.h>
#include <qlabel.h>
#include <klistview.h>
#include <klocale.h>
#include <qcheckbox.h>
#include <kprocess.h>
#include <kiconloader.h>
#include "kgpgselkey.h"
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////// Secret key selection dialog, used when user wants to sign a key
KgpgSelKey::KgpgSelKey(QWidget *parent, const char *name,bool showlocal):KDialogBase( parent, name, true,i18n("Private Key List"),Ok | Cancel)
{
QString keyname;
QWidget *page = new QWidget(this);
QLabel *labeltxt;
KIconLoader *loader = KGlobal::iconLoader();
keyPair=loader->loadIcon("kgpg_key2",KIcon::Small,20);
setMinimumSize(300,200);
keysListpr = new KListView( page );
keysListpr->setRootIsDecorated(true);
keysListpr->addColumn( i18n( "Name" ) );
keysListpr->setShowSortIndicator(true);
keysListpr->setFullWidth(true);
labeltxt=new QLabel(i18n("Choose secret key:"),page);
QVBoxLayout *vbox=new QVBoxLayout(page,3);
vbox->addWidget(labeltxt);
vbox->addWidget(keysListpr);
if (showlocal==true)
{
local = new QCheckBox(i18n("Local signature (cannot be exported)"),page);
vbox->addWidget(local);
}
FILE *fp,*fp2;
QString tst,tst2;
char line[130];
// FIXME: Why use popen instead of KProcess, QProcess or KProcIO?!?
// Are we interested in having buffer overflows now? - Martijn
fp = popen( "gpg --no-tty --with-colon --list-secret-keys", "r" );
while ( fgets( line, sizeof(line), fp))
{
tst=line;
if (tst.startsWith("sec"))
{
const QString trust=tst.section(':',1,1);
QString val=tst.section(':',6,6);
QString id=QString("0x"+tst.section(':',4,4).right(8));
if (val=="")
val=i18n("Unlimited");
QString tr;
switch( trust[0] )
{
case 'o':
tr= i18n("Unknown");
break;
case 'i':
tr= i18n("Invalid");
break;
case 'd':
tr=i18n("Disabled");
break;
case 'r':
tr=i18n("Revoked");
break;
case 'e':
tr=i18n("Expired");
break;
case 'q':
tr=i18n("Undefined");
break;
case 'n':
tr=i18n("None");
break;
case 'm':
tr=i18n("Marginal");
break;
case 'f':
tr=i18n("Full");
break;
case 'u':
tr=i18n("Ultimate");
break;
default:
tr=i18n("?");
break;
}
tst=tst.section(":",9,9);
// FIXME: Same here: don't use popen! - Martijn
fp2 = popen( QString( "gpg --no-tty --with-colon --list-key %1" ).arg( KShellProcess::quote( id ) ).latin1(), "r" );
bool dead=true;
while ( fgets( line, sizeof(line), fp2))
{
tst2=line;
if (tst2.startsWith("pub"))
{
const QString trust2=tst2.section(':',1,1);
switch( trust2[0] )
{
case 'f':
dead=false;
break;
case 'u':
dead=false;
break;
default:
break;
}
}
}
pclose(fp2);
if (!tst.isEmpty() && (!dead))
{
KListViewItem *item=new KListViewItem(keysListpr,extractKeyName(tst));
KListViewItem *sub= new KListViewItem(item,i18n("ID: %1, trust: %2, expiration: %3").arg(id).arg(tr).arg(val));
sub->setSelectable(false);
item->setPixmap(0,keyPair);
}
}
}
pclose(fp);
QObject::connect(keysListpr,SIGNAL(doubleClicked(QListViewItem *,const QPoint &,int)),this,SLOT(slotpreOk()));
QObject::connect(keysListpr,SIGNAL(clicked(QListViewItem *)),this,SLOT(slotSelect(QListViewItem *)));
keysListpr->setSelected(keysListpr->firstChild(),true);
page->show();
resize(this->minimumSize());
setMainWidget(page);
}
QString KgpgSelKey::extractKeyName(QString fullName)
{
QString kMail;
if (fullName.find("<")!=-1)
{
kMail=fullName.section('<',-1,-1);
kMail.truncate(kMail.length()-1);
}
QString kName=fullName.section('<',0,0);
if (kName.find("(")!=-1) kName=kName.section('(',0,0);
return QString(kMail+" ("+kName+")").stripWhiteSpace();
}
void KgpgSelKey::slotpreOk()
{
if (keysListpr->currentItem()->depth()!=0)
return;
else
slotOk();
}
void KgpgSelKey::slotOk()
{
if (keysListpr->currentItem()==NULL)
reject();
else
accept();
}
void KgpgSelKey::slotSelect(QListViewItem *item)
{
if (item==NULL) return;
if (item->depth()!=0)
{
keysListpr->setSelected(item->parent(),true);
keysListpr->setCurrentItem(item->parent());
}
}
QString KgpgSelKey::getkeyID()
{
QString userid;
///// emit selected key
if (keysListpr->currentItem()==NULL) return("");
else
{
userid=keysListpr->currentItem()->firstChild()->text(0);
userid=userid.section(',',0,0);
userid=userid.section(':',1,1);
userid=userid.stripWhiteSpace();
return(userid);
}
}
QString KgpgSelKey::getkeyMail()
{
QString username;
///// emit selected key
if (keysListpr->currentItem()==NULL) return("");
else
{
username=keysListpr->currentItem()->text(0);
//username=username.section(' ',0,0);
username=username.stripWhiteSpace();
return(username);
}
}
bool KgpgSelKey::getlocal()
{
///// emit exportation choice
return(local->isChecked());
}
#include "kgpgselkey.moc"
<commit_msg>=="" -> .isEmpty(). Found by kdetestscripts.<commit_after>//Code from KGPG
/***************************************************************************
listkeys.cpp - description
-------------------
begin : Thu Jul 4 2002
copyright : (C) 2002 by y0k0
email : bj@altern.org
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
////////////////////////////////////////////////////// code for the key management
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <qlayout.h>
#include <qlabel.h>
#include <klistview.h>
#include <klocale.h>
#include <qcheckbox.h>
#include <kprocess.h>
#include <kiconloader.h>
#include "kgpgselkey.h"
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////// Secret key selection dialog, used when user wants to sign a key
KgpgSelKey::KgpgSelKey(QWidget *parent, const char *name,bool showlocal):KDialogBase( parent, name, true,i18n("Private Key List"),Ok | Cancel)
{
QString keyname;
QWidget *page = new QWidget(this);
QLabel *labeltxt;
KIconLoader *loader = KGlobal::iconLoader();
keyPair=loader->loadIcon("kgpg_key2",KIcon::Small,20);
setMinimumSize(300,200);
keysListpr = new KListView( page );
keysListpr->setRootIsDecorated(true);
keysListpr->addColumn( i18n( "Name" ) );
keysListpr->setShowSortIndicator(true);
keysListpr->setFullWidth(true);
labeltxt=new QLabel(i18n("Choose secret key:"),page);
QVBoxLayout *vbox=new QVBoxLayout(page,3);
vbox->addWidget(labeltxt);
vbox->addWidget(keysListpr);
if (showlocal==true)
{
local = new QCheckBox(i18n("Local signature (cannot be exported)"),page);
vbox->addWidget(local);
}
FILE *fp,*fp2;
QString tst,tst2;
char line[130];
// FIXME: Why use popen instead of KProcess, QProcess or KProcIO?!?
// Are we interested in having buffer overflows now? - Martijn
fp = popen( "gpg --no-tty --with-colon --list-secret-keys", "r" );
while ( fgets( line, sizeof(line), fp))
{
tst=line;
if (tst.startsWith("sec"))
{
const QString trust=tst.section(':',1,1);
QString val=tst.section(':',6,6);
QString id=QString("0x"+tst.section(':',4,4).right(8));
if (val.isEmpty())
val=i18n("Unlimited");
QString tr;
switch( trust[0] )
{
case 'o':
tr= i18n("Unknown");
break;
case 'i':
tr= i18n("Invalid");
break;
case 'd':
tr=i18n("Disabled");
break;
case 'r':
tr=i18n("Revoked");
break;
case 'e':
tr=i18n("Expired");
break;
case 'q':
tr=i18n("Undefined");
break;
case 'n':
tr=i18n("None");
break;
case 'm':
tr=i18n("Marginal");
break;
case 'f':
tr=i18n("Full");
break;
case 'u':
tr=i18n("Ultimate");
break;
default:
tr=i18n("?");
break;
}
tst=tst.section(":",9,9);
// FIXME: Same here: don't use popen! - Martijn
fp2 = popen( QString( "gpg --no-tty --with-colon --list-key %1" ).arg( KShellProcess::quote( id ) ).latin1(), "r" );
bool dead=true;
while ( fgets( line, sizeof(line), fp2))
{
tst2=line;
if (tst2.startsWith("pub"))
{
const QString trust2=tst2.section(':',1,1);
switch( trust2[0] )
{
case 'f':
dead=false;
break;
case 'u':
dead=false;
break;
default:
break;
}
}
}
pclose(fp2);
if (!tst.isEmpty() && (!dead))
{
KListViewItem *item=new KListViewItem(keysListpr,extractKeyName(tst));
KListViewItem *sub= new KListViewItem(item,i18n("ID: %1, trust: %2, expiration: %3").arg(id).arg(tr).arg(val));
sub->setSelectable(false);
item->setPixmap(0,keyPair);
}
}
}
pclose(fp);
QObject::connect(keysListpr,SIGNAL(doubleClicked(QListViewItem *,const QPoint &,int)),this,SLOT(slotpreOk()));
QObject::connect(keysListpr,SIGNAL(clicked(QListViewItem *)),this,SLOT(slotSelect(QListViewItem *)));
keysListpr->setSelected(keysListpr->firstChild(),true);
page->show();
resize(this->minimumSize());
setMainWidget(page);
}
QString KgpgSelKey::extractKeyName(QString fullName)
{
QString kMail;
if (fullName.find("<")!=-1)
{
kMail=fullName.section('<',-1,-1);
kMail.truncate(kMail.length()-1);
}
QString kName=fullName.section('<',0,0);
if (kName.find("(")!=-1) kName=kName.section('(',0,0);
return QString(kMail+" ("+kName+")").stripWhiteSpace();
}
void KgpgSelKey::slotpreOk()
{
if (keysListpr->currentItem()->depth()!=0)
return;
else
slotOk();
}
void KgpgSelKey::slotOk()
{
if (keysListpr->currentItem()==NULL)
reject();
else
accept();
}
void KgpgSelKey::slotSelect(QListViewItem *item)
{
if (item==NULL) return;
if (item->depth()!=0)
{
keysListpr->setSelected(item->parent(),true);
keysListpr->setCurrentItem(item->parent());
}
}
QString KgpgSelKey::getkeyID()
{
QString userid;
///// emit selected key
if (keysListpr->currentItem()==NULL) return("");
else
{
userid=keysListpr->currentItem()->firstChild()->text(0);
userid=userid.section(',',0,0);
userid=userid.section(':',1,1);
userid=userid.stripWhiteSpace();
return(userid);
}
}
QString KgpgSelKey::getkeyMail()
{
QString username;
///// emit selected key
if (keysListpr->currentItem()==NULL) return("");
else
{
username=keysListpr->currentItem()->text(0);
//username=username.section(' ',0,0);
username=username.stripWhiteSpace();
return(username);
}
}
bool KgpgSelKey::getlocal()
{
///// emit exportation choice
return(local->isChecked());
}
#include "kgpgselkey.moc"
<|endoftext|> |
<commit_before>// Copyright (c) 2009 - Mozy, Inc.
#include "mordor/pch.h"
#include "http.h"
#include "mordor/http/client.h"
#include "null.h"
#include "transfer.h"
using namespace Mordor::HTTP;
namespace Mordor {
HTTPStream::HTTPStream(const URI &uri, RequestBroker::ptr requestBroker,
boost::function<bool (size_t)> delayDg)
: FilterStream(Stream::ptr(), false),
m_requestBroker(requestBroker),
m_pos(0),
m_size(-1),
m_delayDg(delayDg),
mp_retries(NULL)
{
m_requestHeaders.requestLine.uri = uri;
}
HTTPStream::HTTPStream(const Request &requestHeaders, RequestBroker::ptr requestBroker,
boost::function<bool (size_t)> delayDg)
: FilterStream(Stream::ptr(), false),
m_requestHeaders(requestHeaders),
m_requestBroker(requestBroker),
m_pos(0),
m_size(-1),
m_delayDg(delayDg),
mp_retries(NULL)
{}
ETag
HTTPStream::eTag()
{
stat();
return m_eTag;
}
void
HTTPStream::start()
{
if (!parent()) {
m_requestHeaders.requestLine.method = GET;
m_requestHeaders.request.ifNoneMatch.clear();
if (!m_eTag.unspecified) {
if (m_pos != 0) {
m_requestHeaders.request.ifRange = m_eTag;
m_requestHeaders.request.ifMatch.clear();
} else {
m_requestHeaders.request.ifMatch.insert(m_eTag);
m_requestHeaders.request.ifRange = ETag();
}
} else {
m_requestHeaders.request.ifRange = ETag();
m_requestHeaders.request.ifMatch.clear();
}
m_requestHeaders.request.range.clear();
if (m_pos != 0)
m_requestHeaders.request.range.push_back(
std::make_pair((unsigned long long)m_pos, ~0ull));
ClientRequest::ptr request = m_requestBroker->request(m_requestHeaders);
const Response response = request->response();
Stream::ptr responseStream;
switch (response.status.status) {
case OK:
case PARTIAL_CONTENT:
if (response.entity.contentRange.instance != ~0ull)
m_size = (long long)response.entity.contentRange.instance;
else if (response.entity.contentLength != ~0ull)
m_size = (long long)response.entity.contentLength;
else
m_size = -2;
if (m_eTag.unspecified &&
!response.response.eTag.unspecified) {
m_eTag = response.response.eTag;
} else if (!m_eTag.unspecified &&
!response.response.eTag.unspecified &&
response.response.eTag != m_eTag) {
m_eTag = response.response.eTag;
if (m_pos != 0 && response.status.status ==
PARTIAL_CONTENT) {
// Server doesn't support If-Range
request->cancel(true);
parent(Stream::ptr());
} else {
parent(request->responseStream());
}
m_pos = 0;
MORDOR_THROW_EXCEPTION(EntityChangedException());
}
responseStream = request->responseStream();
// Server doesn't support Range
if (m_pos != 0 && response.status.status == OK)
transferStream(responseStream,
NullStream::get(), m_pos);
parent(responseStream);
break;
default:
MORDOR_THROW_EXCEPTION(InvalidResponseException(request));
}
}
}
bool
HTTPStream::checkModified()
{
MORDOR_ASSERT(!m_eTag.unspecified);
if (parent())
parent(Stream::ptr());
m_requestHeaders.requestLine.method = GET;
m_requestHeaders.request.ifMatch.clear();
m_requestHeaders.request.ifRange = ETag();
m_requestHeaders.request.range.clear();
m_requestHeaders.request.ifNoneMatch.insert(m_eTag);
if (m_pos != 0)
m_requestHeaders.request.range.push_back(
std::make_pair((unsigned long long)m_pos, ~0ull));
ClientRequest::ptr request = m_requestBroker->request(m_requestHeaders);
const Response response = request->response();
switch (response.status.status) {
case OK:
case PARTIAL_CONTENT:
case NOT_MODIFIED:
if (response.entity.contentRange.instance != ~0ull)
m_size = (long long)response.entity.contentRange.instance;
else if (response.entity.contentLength != ~0ull)
m_size = (long long)response.entity.contentLength;
else
m_size = -2;
break;
default:
MORDOR_THROW_EXCEPTION(InvalidResponseException(request));
}
if (response.status.status != NOT_MODIFIED)
m_eTag = response.response.eTag;
else
return false;
Stream::ptr responseStream = request->responseStream();
// Server doesn't support Range
if (m_pos != 0 && response.status.status == OK) {
// We don't really care about any data transfer problems here,
// since that's not what the caller is asking for
try {
transferStream(responseStream, NullStream::get(), m_pos);
} catch (...) {
return true;
}
}
parent(responseStream);
return true;
}
size_t
HTTPStream::read(Buffer &buffer, size_t length)
{
//TODO Remove this lines because they prevent to reach the EOF and thus the notifyeof method doesn't get called.
//Cody needs to verify this and if it is needed, then we need a way to get notifyeof to get called.
//if (m_size >= 0 && m_pos >= m_size)
// return 0;
size_t localRetries = 0;
size_t *retries = mp_retries ? mp_retries : &localRetries;
while (true) {
start();
MORDOR_ASSERT(parent());
try {
size_t result = parent()->read(buffer, length);
m_pos += result;
*retries = 0;
return result;
} catch (SocketException &) {
parent(Stream::ptr());
if (!m_delayDg || !m_delayDg(++*retries))
throw;
continue;
} catch (UnexpectedEofException &) {
parent(Stream::ptr());
if (!m_delayDg || !m_delayDg(++*retries))
throw;
continue;
}
}
}
long long
HTTPStream::seek(long long offset, Anchor anchor)
{
switch (anchor) {
case CURRENT:
offset = m_pos + offset;
break;
case END:
stat();
MORDOR_ASSERT(m_size >= 0);
offset = m_size + offset;
break;
case BEGIN:
break;
default:
MORDOR_NOTREACHED();
}
if (offset < 0)
MORDOR_THROW_EXCEPTION(std::invalid_argument(
"resulting offset is before the beginning of the file"));
if (offset == m_pos)
return m_pos;
parent(Stream::ptr());
return m_pos = offset;
}
bool
HTTPStream::supportsSize()
{
stat();
MORDOR_ASSERT(m_size != -1);
MORDOR_ASSERT(m_size >= -2);
if (m_size == -2)
return false;
else
return true;
}
void
HTTPStream::stat()
{
if (m_size == -1) {
m_requestHeaders.requestLine.method = HEAD;
ClientRequest::ptr request = m_requestBroker->request(m_requestHeaders);
const Response response = request->response();
switch (response.status.status) {
case OK:
if (response.entity.contentLength != ~0ull)
m_size = (long long)response.entity.contentLength;
else
m_size = -2;
if (m_eTag.unspecified &&
!response.response.eTag.unspecified) {
m_eTag = response.response.eTag;
} else if (!m_eTag.unspecified &&
response.response.eTag != m_eTag) {
m_eTag = response.response.eTag;
parent(Stream::ptr());
m_pos = 0;
MORDOR_THROW_EXCEPTION(EntityChangedException());
}
break;
default:
MORDOR_THROW_EXCEPTION(InvalidResponseException(request));
}
}
}
long long
HTTPStream::size()
{
stat();
MORDOR_ASSERT(supportsSize());
return m_size;
}
}
<commit_msg>You are correct, pancho.<commit_after>// Copyright (c) 2009 - Mozy, Inc.
#include "mordor/pch.h"
#include "http.h"
#include "mordor/http/client.h"
#include "null.h"
#include "transfer.h"
using namespace Mordor::HTTP;
namespace Mordor {
HTTPStream::HTTPStream(const URI &uri, RequestBroker::ptr requestBroker,
boost::function<bool (size_t)> delayDg)
: FilterStream(Stream::ptr(), false),
m_requestBroker(requestBroker),
m_pos(0),
m_size(-1),
m_delayDg(delayDg),
mp_retries(NULL)
{
m_requestHeaders.requestLine.uri = uri;
}
HTTPStream::HTTPStream(const Request &requestHeaders, RequestBroker::ptr requestBroker,
boost::function<bool (size_t)> delayDg)
: FilterStream(Stream::ptr(), false),
m_requestHeaders(requestHeaders),
m_requestBroker(requestBroker),
m_pos(0),
m_size(-1),
m_delayDg(delayDg),
mp_retries(NULL)
{}
ETag
HTTPStream::eTag()
{
stat();
return m_eTag;
}
void
HTTPStream::start()
{
if (!parent()) {
m_requestHeaders.requestLine.method = GET;
m_requestHeaders.request.ifNoneMatch.clear();
if (!m_eTag.unspecified) {
if (m_pos != 0) {
m_requestHeaders.request.ifRange = m_eTag;
m_requestHeaders.request.ifMatch.clear();
} else {
m_requestHeaders.request.ifMatch.insert(m_eTag);
m_requestHeaders.request.ifRange = ETag();
}
} else {
m_requestHeaders.request.ifRange = ETag();
m_requestHeaders.request.ifMatch.clear();
}
m_requestHeaders.request.range.clear();
if (m_pos != 0)
m_requestHeaders.request.range.push_back(
std::make_pair((unsigned long long)m_pos, ~0ull));
ClientRequest::ptr request = m_requestBroker->request(m_requestHeaders);
const Response response = request->response();
Stream::ptr responseStream;
switch (response.status.status) {
case OK:
case PARTIAL_CONTENT:
if (response.entity.contentRange.instance != ~0ull)
m_size = (long long)response.entity.contentRange.instance;
else if (response.entity.contentLength != ~0ull)
m_size = (long long)response.entity.contentLength;
else
m_size = -2;
if (m_eTag.unspecified &&
!response.response.eTag.unspecified) {
m_eTag = response.response.eTag;
} else if (!m_eTag.unspecified &&
!response.response.eTag.unspecified &&
response.response.eTag != m_eTag) {
m_eTag = response.response.eTag;
if (m_pos != 0 && response.status.status ==
PARTIAL_CONTENT) {
// Server doesn't support If-Range
request->cancel(true);
parent(Stream::ptr());
} else {
parent(request->responseStream());
}
m_pos = 0;
MORDOR_THROW_EXCEPTION(EntityChangedException());
}
responseStream = request->responseStream();
// Server doesn't support Range
if (m_pos != 0 && response.status.status == OK)
transferStream(responseStream,
NullStream::get(), m_pos);
parent(responseStream);
break;
default:
MORDOR_THROW_EXCEPTION(InvalidResponseException(request));
}
}
}
bool
HTTPStream::checkModified()
{
MORDOR_ASSERT(!m_eTag.unspecified);
if (parent())
parent(Stream::ptr());
m_requestHeaders.requestLine.method = GET;
m_requestHeaders.request.ifMatch.clear();
m_requestHeaders.request.ifRange = ETag();
m_requestHeaders.request.range.clear();
m_requestHeaders.request.ifNoneMatch.insert(m_eTag);
if (m_pos != 0)
m_requestHeaders.request.range.push_back(
std::make_pair((unsigned long long)m_pos, ~0ull));
ClientRequest::ptr request = m_requestBroker->request(m_requestHeaders);
const Response response = request->response();
switch (response.status.status) {
case OK:
case PARTIAL_CONTENT:
case NOT_MODIFIED:
if (response.entity.contentRange.instance != ~0ull)
m_size = (long long)response.entity.contentRange.instance;
else if (response.entity.contentLength != ~0ull)
m_size = (long long)response.entity.contentLength;
else
m_size = -2;
break;
default:
MORDOR_THROW_EXCEPTION(InvalidResponseException(request));
}
if (response.status.status != NOT_MODIFIED)
m_eTag = response.response.eTag;
else
return false;
Stream::ptr responseStream = request->responseStream();
// Server doesn't support Range
if (m_pos != 0 && response.status.status == OK) {
// We don't really care about any data transfer problems here,
// since that's not what the caller is asking for
try {
transferStream(responseStream, NullStream::get(), m_pos);
} catch (...) {
return true;
}
}
parent(responseStream);
return true;
}
size_t
HTTPStream::read(Buffer &buffer, size_t length)
{
size_t localRetries = 0;
size_t *retries = mp_retries ? mp_retries : &localRetries;
while (true) {
start();
MORDOR_ASSERT(parent());
try {
size_t result = parent()->read(buffer, length);
m_pos += result;
*retries = 0;
return result;
} catch (SocketException &) {
parent(Stream::ptr());
if (!m_delayDg || !m_delayDg(++*retries))
throw;
continue;
} catch (UnexpectedEofException &) {
parent(Stream::ptr());
if (!m_delayDg || !m_delayDg(++*retries))
throw;
continue;
}
}
}
long long
HTTPStream::seek(long long offset, Anchor anchor)
{
switch (anchor) {
case CURRENT:
offset = m_pos + offset;
break;
case END:
stat();
MORDOR_ASSERT(m_size >= 0);
offset = m_size + offset;
break;
case BEGIN:
break;
default:
MORDOR_NOTREACHED();
}
if (offset < 0)
MORDOR_THROW_EXCEPTION(std::invalid_argument(
"resulting offset is before the beginning of the file"));
if (offset == m_pos)
return m_pos;
parent(Stream::ptr());
return m_pos = offset;
}
bool
HTTPStream::supportsSize()
{
stat();
MORDOR_ASSERT(m_size != -1);
MORDOR_ASSERT(m_size >= -2);
if (m_size == -2)
return false;
else
return true;
}
void
HTTPStream::stat()
{
if (m_size == -1) {
m_requestHeaders.requestLine.method = HEAD;
ClientRequest::ptr request = m_requestBroker->request(m_requestHeaders);
const Response response = request->response();
switch (response.status.status) {
case OK:
if (response.entity.contentLength != ~0ull)
m_size = (long long)response.entity.contentLength;
else
m_size = -2;
if (m_eTag.unspecified &&
!response.response.eTag.unspecified) {
m_eTag = response.response.eTag;
} else if (!m_eTag.unspecified &&
response.response.eTag != m_eTag) {
m_eTag = response.response.eTag;
parent(Stream::ptr());
m_pos = 0;
MORDOR_THROW_EXCEPTION(EntityChangedException());
}
break;
default:
MORDOR_THROW_EXCEPTION(InvalidResponseException(request));
}
}
}
long long
HTTPStream::size()
{
stat();
MORDOR_ASSERT(supportsSize());
return m_size;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "stdafx.h"
#include "diagnostics/assert.h"
#include "diagnostics/xquery_diagnostics.h"
#include "simple_collection.h"
#include "simple_index.h"
#include "store/api/ic.h"
#include "store/api/annotation.h"
#include "loader.h"
#include "simple_store.h"
#include "store_defs.h"
#include "node_items.h"
#ifdef ZORBA_WITH_JSON
# include "json_items.h"
#endif
#include "zorbatypes/numconversions.h"
namespace zorba { namespace simplestore {
/*******************************************************************************
********************************************************************************/
SimpleCollection::SimpleCollection(
const store::Item_t& name,
const std::vector<store::Annotation_t>& annotations,
bool isDynamic)
:
Collection(name),
theIsDynamic(isDynamic),
theAnnotations(annotations)
{
theId = GET_STORE().createCollectionId();
theTreeIdGenerator = GET_STORE().getTreeIdGeneratorFactory().createTreeGenerator(0);
}
/*******************************************************************************
Default constructor added in order to allow subclasses to instantiate a
collection without name.
********************************************************************************/
SimpleCollection::SimpleCollection()
:
theIsDynamic(false)
{
theTreeIdGenerator = GET_STORE().getTreeIdGeneratorFactory().createTreeGenerator(0);
}
/*******************************************************************************
********************************************************************************/
SimpleCollection::~SimpleCollection()
{
delete theTreeIdGenerator;
}
/*******************************************************************************
********************************************************************************/
void SimpleCollection::getAnnotations(
std::vector<store::Annotation_t>& annotations) const
{
annotations = theAnnotations;
}
/*******************************************************************************
Return an iterator over the nodes of this collection.
Note: it is allowed to have several concurrent iterators on the same collection
but each iterator should be used by a single thread only.
********************************************************************************/
store::Iterator_t SimpleCollection::getIterator(
const xs_integer& skip,
const zstring& startRef)
{
store::Item_t startNode;
xs_integer startPos = xs_integer::zero();
if (startRef.size() != 0 &&
(!GET_STORE().getNodeByReference(startNode, startRef) ||
!findNode(startNode.getp(), startPos)))
{
throw ZORBA_EXCEPTION(zerr::ZSTR0066_REFERENCED_NODE_NOT_IN_COLLECTION,
ERROR_PARAMS(startRef, theName->getStringValue()));
}
return new CollectionIter(this, skip + startPos);
}
/*******************************************************************************
Check if the tree rooted at the given node belongs to this collection. If yes,
return true and the position of the tree within the collection. Otherwise,
return false.
********************************************************************************/
bool SimpleCollection::findNode(const store::Item* item, xs_integer& position) const
{
if (!(item->isStructuredItem()))
{
throw ZORBA_EXCEPTION(zerr::ZSTR0013_COLLECTION_ITEM_MUST_BE_STRUCTURED,
ERROR_PARAMS(getName()->getStringValue()));
}
const StructuredItem* structuredItem = static_cast<const StructuredItem*>(item);
if (structuredItem->isNode())
{
const XmlNode* node = static_cast<const XmlNode*>(item);
if (node->getTree()->getRoot() != node)
{
throw ZORBA_EXCEPTION(zerr::ZSTR0011_COLLECTION_NON_ROOT_NODE,
ERROR_PARAMS(getName()->getStringValue()));
}
}
if (theTrees.empty())
return false;
if (item->getCollection() != this)
return false;
position = structuredItem->getPosition();
csize pos = to_xs_unsignedInt(position);
StructuredItem* collectionItem =
static_cast<StructuredItem*>(theTrees[pos].getp());
if (pos < theTrees.size() &&
collectionItem->getTreeId() == structuredItem->getTreeId())
{
return true;
}
csize numTrees = theTrees.size();
for (csize i = 0; i < numTrees; ++i)
{
// check if the nodes are the same
if (item->equals(theTrees[i]))
{
ZORBA_ASSERT(theTrees[i]->getCollection() == this);
position = i;
return true;
}
}
return false;
}
/*******************************************************************************
Return the node at the given position within the collection, or NULL if the
given position is >= than the number of nodes in the collection.
********************************************************************************/
store::Item_t SimpleCollection::nodeAt(xs_integer position)
{
csize pos = to_xs_unsignedInt(position);
if (pos >= theTrees.size())
{
return NULL;
}
return theTrees[pos];
}
/*******************************************************************************
********************************************************************************/
TreeId SimpleCollection::createTreeId()
{
return theTreeIdGenerator->create();
}
/*******************************************************************************
Insert the given node to the collection. If the node is in any collection
already or if the node is an xml node with a parent, this method raises an
error. Otherwise, the node is inserted into the given position.
********************************************************************************/
void SimpleCollection::addNode(store::Item* item, xs_integer position)
{
if (!(item->isStructuredItem()))
{
throw ZORBA_EXCEPTION(zerr::ZSTR0013_COLLECTION_ITEM_MUST_BE_STRUCTURED,
ERROR_PARAMS(getName()->getStringValue()));
}
if (item->getCollection() != NULL)
{
throw ZORBA_EXCEPTION(zerr::ZSTR0010_COLLECTION_NODE_ALREADY_IN_COLLECTION,
ERROR_PARAMS(getName()->getStringValue(),
item->getCollection()->getName()->getStringValue()));
}
StructuredItem* structuredItem = static_cast<StructuredItem*>(item);
if (structuredItem->isNode())
{
XmlNode* node = static_cast<XmlNode*>(item);
if (node->getRoot() != node)
{
throw ZORBA_EXCEPTION(zerr::ZSTR0011_COLLECTION_NON_ROOT_NODE,
ERROR_PARAMS(getName()->getStringValue()));
}
}
xs_long pos = to_xs_long(position);
SYNC_CODE(AutoLatch lock(theLatch, Latch::WRITE););
if (pos < 0 || to_xs_unsignedLong(position) >= theTrees.size())
{
theTrees.push_back(item);
structuredItem->attachToCollection(this,
createTreeId(),
xs_integer(theTrees.size()));
}
else
{
theTrees.insert(theTrees.begin() + pos, item);
structuredItem->attachToCollection(this, createTreeId(), position);
}
}
/*******************************************************************************
Insert the given nodes to the collection before or after the given target node.
If any of the nodes is a non root xml node or is in any collection already,
this method raises an error. The moethod returns the position occupied by the
first new node after the insertion is done.
********************************************************************************/
xs_integer SimpleCollection::addNodes(
std::vector<store::Item_t>& items,
const store::Item* targetNode,
bool before)
{
SYNC_CODE(AutoLatch lock(theLatch, Latch::WRITE);)
xs_integer pos;
bool found = findNode(targetNode, pos);
if (!found)
{
throw ZORBA_EXCEPTION(zerr::ZDDY0011_COLLECTION_NODE_NOT_FOUND,
ERROR_PARAMS(theName->getStringValue()));
}
csize targetPos = to_xs_unsignedInt(pos);
if (!before)
{
++targetPos;
}
csize numNodes = theTrees.size();
csize numNewNodes = items.size();
for (csize i = 0; i < numNewNodes; ++i)
{
store::Item* item = items[i].getp();
if (!(item->isStructuredItem()))
{
throw ZORBA_EXCEPTION(zerr::ZSTR0013_COLLECTION_ITEM_MUST_BE_STRUCTURED,
ERROR_PARAMS(getName()->getStringValue()));
}
if (item->getCollection() != NULL)
{
throw ZORBA_EXCEPTION(zerr::ZSTR0010_COLLECTION_NODE_ALREADY_IN_COLLECTION,
ERROR_PARAMS(getName()->getStringValue(),
item->getCollection()->getName()->getStringValue()));
}
StructuredItem* structuredItem = static_cast<StructuredItem*>(item);
if (structuredItem->isNode())
{
XmlNode* node = static_cast<XmlNode*>(item);
if (node->getRoot() != node)
{
throw ZORBA_EXCEPTION(zerr::ZSTR0011_COLLECTION_NON_ROOT_NODE,
ERROR_PARAMS(getName()->getStringValue()));
}
}
pos = targetPos + i;
structuredItem->attachToCollection(this, createTreeId(), pos);
} // for each new node
theTrees.resize(numNodes + numNewNodes);
if (targetPos < numNodes)
{
memmove(&theTrees[targetPos + numNewNodes],
&theTrees[targetPos],
(numNodes-targetPos) * sizeof(store::Item_t));
}
for (csize i = targetPos; i < targetPos + numNewNodes; ++i)
{
theTrees[i].setNull();
}
for (csize i = 0; i < numNewNodes; ++i)
{
theTrees[targetPos + i].transfer(items[i]);
}
return xs_integer(targetPos);
}
/*******************************************************************************
Remove the tree rooted at the given node, if the tree actually belongs to the
collection. If the tree was found return true and the position of the tree;
otherwise, return false.
********************************************************************************/
bool SimpleCollection::removeNode(store::Item* item, xs_integer& position)
{
if (!(item->isStructuredItem()))
{
throw ZORBA_EXCEPTION(zerr::ZSTR0013_COLLECTION_ITEM_MUST_BE_STRUCTURED,
ERROR_PARAMS(getName()->getStringValue()));
}
SYNC_CODE(AutoLatch lock(theLatch, Latch::WRITE);)
bool found = findNode(item, position);
if (found)
{
ZORBA_ASSERT(item->getCollection() == this);
StructuredItem* structuredItem = static_cast<StructuredItem*>(item);
structuredItem->detachFromCollection();
csize pos = to_xs_unsignedInt(position);
theTrees.erase(theTrees.begin() + pos);
return true;
}
else
{
return false;
}
}
/*******************************************************************************
Remove the tree at the given position. If the position is >= than the number
of trees in the collection, this mothod is a noop. The method returns true if
a tree is actually deleted, otherwise it returns false.
********************************************************************************/
bool SimpleCollection::removeNode(xs_integer position)
{
SYNC_CODE(AutoLatch lock(theLatch, Latch::WRITE);)
std::size_t pos = to_xs_unsignedInt(position);
if (pos >= theTrees.size())
{
return false;
}
else
{
store::Item* item = theTrees[pos].getp();
ZORBA_ASSERT(item->getCollection() == this);
ZORBA_ASSERT(item->isStructuredItem());
StructuredItem* structuredItem = static_cast<StructuredItem*>(item);
structuredItem->detachFromCollection();
theTrees.erase(theTrees.begin() + pos);
return true;
}
}
/*******************************************************************************
Remove a given number of trees starting with the tree at the given position.
If the given number is 0 or the given position is >= than the number of trees
in the collection, this method is a noop. The method returns the number of
trees that are actually deleted.
********************************************************************************/
xs_integer SimpleCollection::removeNodes(xs_integer position, xs_integer numNodes)
{
SYNC_CODE(AutoLatch lock(theLatch, Latch::WRITE);)
csize pos = to_xs_unsignedInt(position);
csize num = to_xs_unsignedInt(numNodes);
if (num == 0 || pos >= theTrees.size())
{
return xs_integer::zero();
}
else
{
csize last = pos + num;
if (last > theTrees.size())
{
last = theTrees.size();
}
for (csize i = pos; i < last; ++i)
{
store::Item* item = theTrees[pos].getp();
ZORBA_ASSERT(item->getCollection() == this);
ZORBA_ASSERT(item->isStructuredItem());
StructuredItem* structuredItem = static_cast<StructuredItem*>(item);
structuredItem->detachFromCollection();
theTrees.erase(theTrees.begin() + pos);
}
return xs_integer(last - pos);
}
}
/*******************************************************************************
Remove all the nodes from the collection
********************************************************************************/
void SimpleCollection::removeAll()
{
SYNC_CODE(AutoLatch lock(theLatch, Latch::WRITE);)
csize numTrees = theTrees.size();
for (csize i = 0; i < numTrees; ++i)
{
store::Item* item = theTrees[i].getp();
ZORBA_ASSERT(item->getCollection() == this);
ZORBA_ASSERT(item->isStructuredItem());
StructuredItem* structuredItem = static_cast<StructuredItem*>(item);
structuredItem->detachFromCollection();
}
theTrees.clear();
}
/*******************************************************************************
For each tree in the collection, set its current position within the collection.
********************************************************************************/
void SimpleCollection::adjustTreePositions()
{
csize numTrees = theTrees.size();
for (csize i = 0; i < numTrees; ++i)
{
static_cast<StructuredItem*>(theTrees[i].getp())->setPosition(xs_integer(i));
}
}
/*******************************************************************************
********************************************************************************/
SimpleCollection::CollectionIter::CollectionIter(
SimpleCollection* collection,
const xs_integer& skip)
:
theCollection(collection),
theHaveLock(false),
theSkip(to_xs_unsignedLong(skip))
{
}
/*******************************************************************************
********************************************************************************/
SimpleCollection::CollectionIter::~CollectionIter()
{
SYNC_CODE(if (theHaveLock) \
theCollection->theLatch.unlock();)
}
/*******************************************************************************
********************************************************************************/
void SimpleCollection::CollectionIter::skip()
{
// skip by position
if (theSkip >= theCollection->size())
{
// we need to skip more then possible -> jump to the end
theIterator = theEnd;
}
else
{
theIterator += theSkip;
}
}
/*******************************************************************************
********************************************************************************/
void SimpleCollection::CollectionIter::open()
{
SYNC_CODE(theCollection->theLatch.rlock();)
theHaveLock = true;
theIterator = theCollection->theTrees.begin();
theEnd = theCollection->theTrees.end();
skip();
}
/*******************************************************************************
********************************************************************************/
bool SimpleCollection::CollectionIter::next(store::Item_t& result)
{
if (!theHaveLock)
{
throw ZORBA_EXCEPTION(zerr::ZDDY0019_COLLECTION_ITERATOR_NOT_OPEN,
ERROR_PARAMS(theCollection->getName()->getStringValue()));
}
if (theIterator == theEnd)
{
result = NULL;
return false;
}
result = *theIterator;
++theIterator;
return true;
}
/*******************************************************************************
********************************************************************************/
void SimpleCollection::CollectionIter::reset()
{
theIterator = theCollection->theTrees.begin();
theEnd = theCollection->theTrees.end();
skip();
}
/*******************************************************************************
********************************************************************************/
void SimpleCollection::CollectionIter::close()
{
assert(theHaveLock);
theHaveLock = false;
SYNC_CODE(theCollection->theLatch.unlock();)
}
} // namespace simplestore
} // namespace zorba
/* vim:set et sw=2 ts=2: */
<commit_msg>Catching range errors in simple collection code.<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "stdafx.h"
#include "diagnostics/assert.h"
#include "diagnostics/xquery_diagnostics.h"
#include "simple_collection.h"
#include "simple_index.h"
#include "store/api/ic.h"
#include "store/api/annotation.h"
#include "loader.h"
#include "simple_store.h"
#include "store_defs.h"
#include "node_items.h"
#ifdef ZORBA_WITH_JSON
# include "json_items.h"
#endif
#include "zorbatypes/numconversions.h"
namespace zorba { namespace simplestore {
/*******************************************************************************
********************************************************************************/
SimpleCollection::SimpleCollection(
const store::Item_t& name,
const std::vector<store::Annotation_t>& annotations,
bool isDynamic)
:
Collection(name),
theIsDynamic(isDynamic),
theAnnotations(annotations)
{
theId = GET_STORE().createCollectionId();
theTreeIdGenerator = GET_STORE().getTreeIdGeneratorFactory().createTreeGenerator(0);
}
/*******************************************************************************
Default constructor added in order to allow subclasses to instantiate a
collection without name.
********************************************************************************/
SimpleCollection::SimpleCollection()
:
theIsDynamic(false)
{
theTreeIdGenerator = GET_STORE().getTreeIdGeneratorFactory().createTreeGenerator(0);
}
/*******************************************************************************
********************************************************************************/
SimpleCollection::~SimpleCollection()
{
delete theTreeIdGenerator;
}
/*******************************************************************************
********************************************************************************/
void SimpleCollection::getAnnotations(
std::vector<store::Annotation_t>& annotations) const
{
annotations = theAnnotations;
}
/*******************************************************************************
Return an iterator over the nodes of this collection.
Note: it is allowed to have several concurrent iterators on the same collection
but each iterator should be used by a single thread only.
********************************************************************************/
store::Iterator_t SimpleCollection::getIterator(
const xs_integer& skip,
const zstring& startRef)
{
store::Item_t startNode;
xs_integer startPos = xs_integer::zero();
if (startRef.size() != 0 &&
(!GET_STORE().getNodeByReference(startNode, startRef) ||
!findNode(startNode.getp(), startPos)))
{
throw ZORBA_EXCEPTION(zerr::ZSTR0066_REFERENCED_NODE_NOT_IN_COLLECTION,
ERROR_PARAMS(startRef, theName->getStringValue()));
}
try
{
return new CollectionIter(this, skip + startPos);
}
catch (std::range_error)
{
assert(false);
return new CollectionIter(this, xs_integer::zero());
}
}
/*******************************************************************************
Check if the tree rooted at the given node belongs to this collection. If yes,
return true and the position of the tree within the collection. Otherwise,
return false.
********************************************************************************/
bool SimpleCollection::findNode(const store::Item* item, xs_integer& position) const
{
if (!(item->isStructuredItem()))
{
throw ZORBA_EXCEPTION(zerr::ZSTR0013_COLLECTION_ITEM_MUST_BE_STRUCTURED,
ERROR_PARAMS(getName()->getStringValue()));
}
const StructuredItem* structuredItem = static_cast<const StructuredItem*>(item);
if (structuredItem->isNode())
{
const XmlNode* node = static_cast<const XmlNode*>(item);
if (node->getTree()->getRoot() != node)
{
throw ZORBA_EXCEPTION(zerr::ZSTR0011_COLLECTION_NON_ROOT_NODE,
ERROR_PARAMS(getName()->getStringValue()));
}
}
if (theTrees.empty())
return false;
if (item->getCollection() != this)
return false;
position = structuredItem->getPosition();
csize pos = 0;
try
{
pos = to_xs_unsignedInt(position);
} catch (std::range_error)
{
assert(false);
return false;
}
StructuredItem* collectionItem =
static_cast<StructuredItem*>(theTrees[pos].getp());
if (pos < theTrees.size() &&
collectionItem->getTreeId() == structuredItem->getTreeId())
{
return true;
}
csize numTrees = theTrees.size();
for (csize i = 0; i < numTrees; ++i)
{
// check if the nodes are the same
if (item->equals(theTrees[i]))
{
ZORBA_ASSERT(theTrees[i]->getCollection() == this);
position = i;
return true;
}
}
return false;
}
/*******************************************************************************
Return the node at the given position within the collection, or NULL if the
given position is >= than the number of nodes in the collection.
********************************************************************************/
store::Item_t SimpleCollection::nodeAt(xs_integer position)
{
try
{
csize pos = to_xs_unsignedInt(position);
if (pos >= theTrees.size())
{
return NULL;
}
return theTrees[pos];
}
catch (std::range_error)
{
assert(false);
return NULL;
}
}
/*******************************************************************************
********************************************************************************/
TreeId SimpleCollection::createTreeId()
{
return theTreeIdGenerator->create();
}
/*******************************************************************************
Insert the given node to the collection. If the node is in any collection
already or if the node is an xml node with a parent, this method raises an
error. Otherwise, the node is inserted into the given position.
********************************************************************************/
void SimpleCollection::addNode(store::Item* item, xs_integer position)
{
if (!(item->isStructuredItem()))
{
throw ZORBA_EXCEPTION(zerr::ZSTR0013_COLLECTION_ITEM_MUST_BE_STRUCTURED,
ERROR_PARAMS(getName()->getStringValue()));
}
if (item->getCollection() != NULL)
{
throw ZORBA_EXCEPTION(zerr::ZSTR0010_COLLECTION_NODE_ALREADY_IN_COLLECTION,
ERROR_PARAMS(getName()->getStringValue(),
item->getCollection()->getName()->getStringValue()));
}
StructuredItem* structuredItem = static_cast<StructuredItem*>(item);
if (structuredItem->isNode())
{
XmlNode* node = static_cast<XmlNode*>(item);
if (node->getRoot() != node)
{
throw ZORBA_EXCEPTION(zerr::ZSTR0011_COLLECTION_NON_ROOT_NODE,
ERROR_PARAMS(getName()->getStringValue()));
}
}
try
{
xs_long pos = to_xs_long(position);
SYNC_CODE(AutoLatch lock(theLatch, Latch::WRITE););
if (pos < 0 || to_xs_unsignedLong(position) >= theTrees.size())
{
theTrees.push_back(item);
structuredItem->attachToCollection(this,
createTreeId(),
xs_integer(theTrees.size()));
}
else
{
theTrees.insert(theTrees.begin() + pos, item);
structuredItem->attachToCollection(this, createTreeId(), position);
}
}
catch (std::range_error)
{
assert(false);
return;
}
}
/*******************************************************************************
Insert the given nodes to the collection before or after the given target node.
If any of the nodes is a non root xml node or is in any collection already,
this method raises an error. The moethod returns the position occupied by the
first new node after the insertion is done.
********************************************************************************/
xs_integer SimpleCollection::addNodes(
std::vector<store::Item_t>& items,
const store::Item* targetNode,
bool before)
{
SYNC_CODE(AutoLatch lock(theLatch, Latch::WRITE);)
xs_integer pos;
bool found = findNode(targetNode, pos);
if (!found)
{
throw ZORBA_EXCEPTION(zerr::ZDDY0011_COLLECTION_NODE_NOT_FOUND,
ERROR_PARAMS(theName->getStringValue()));
}
csize targetPos = 0;
try {
targetPos = to_xs_unsignedInt(pos);
}
catch (std::range_error)
{
assert(false);
return xs_integer::zero();
}
if (!before)
{
++targetPos;
}
csize numNodes = theTrees.size();
csize numNewNodes = items.size();
for (csize i = 0; i < numNewNodes; ++i)
{
store::Item* item = items[i].getp();
if (!(item->isStructuredItem()))
{
throw ZORBA_EXCEPTION(zerr::ZSTR0013_COLLECTION_ITEM_MUST_BE_STRUCTURED,
ERROR_PARAMS(getName()->getStringValue()));
}
if (item->getCollection() != NULL)
{
throw ZORBA_EXCEPTION(zerr::ZSTR0010_COLLECTION_NODE_ALREADY_IN_COLLECTION,
ERROR_PARAMS(getName()->getStringValue(),
item->getCollection()->getName()->getStringValue()));
}
StructuredItem* structuredItem = static_cast<StructuredItem*>(item);
if (structuredItem->isNode())
{
XmlNode* node = static_cast<XmlNode*>(item);
if (node->getRoot() != node)
{
throw ZORBA_EXCEPTION(zerr::ZSTR0011_COLLECTION_NON_ROOT_NODE,
ERROR_PARAMS(getName()->getStringValue()));
}
}
pos = targetPos + i;
structuredItem->attachToCollection(this, createTreeId(), pos);
} // for each new node
theTrees.resize(numNodes + numNewNodes);
if (targetPos < numNodes)
{
memmove(&theTrees[targetPos + numNewNodes],
&theTrees[targetPos],
(numNodes-targetPos) * sizeof(store::Item_t));
}
for (csize i = targetPos; i < targetPos + numNewNodes; ++i)
{
theTrees[i].setNull();
}
for (csize i = 0; i < numNewNodes; ++i)
{
theTrees[targetPos + i].transfer(items[i]);
}
return xs_integer(targetPos);
}
/*******************************************************************************
Remove the tree rooted at the given node, if the tree actually belongs to the
collection. If the tree was found return true and the position of the tree;
otherwise, return false.
********************************************************************************/
bool SimpleCollection::removeNode(store::Item* item, xs_integer& position)
{
if (!(item->isStructuredItem()))
{
throw ZORBA_EXCEPTION(zerr::ZSTR0013_COLLECTION_ITEM_MUST_BE_STRUCTURED,
ERROR_PARAMS(getName()->getStringValue()));
}
SYNC_CODE(AutoLatch lock(theLatch, Latch::WRITE);)
bool found = findNode(item, position);
if (found)
{
ZORBA_ASSERT(item->getCollection() == this);
StructuredItem* structuredItem = static_cast<StructuredItem*>(item);
structuredItem->detachFromCollection();
try
{
csize pos = to_xs_unsignedInt(position);
theTrees.erase(theTrees.begin() + pos);
return true;
}
catch (std::range_error)
{
assert(false);
return false;
}
}
else
{
return false;
}
}
/*******************************************************************************
Remove the tree at the given position. If the position is >= than the number
of trees in the collection, this mothod is a noop. The method returns true if
a tree is actually deleted, otherwise it returns false.
********************************************************************************/
bool SimpleCollection::removeNode(xs_integer position)
{
SYNC_CODE(AutoLatch lock(theLatch, Latch::WRITE);)
std::size_t pos = 0;
try {
pos = to_xs_unsignedInt(position);
}
catch (std::range_error)
{
assert(false);
return false;
}
if (pos >= theTrees.size())
{
return false;
}
else
{
store::Item* item = theTrees[pos].getp();
ZORBA_ASSERT(item->getCollection() == this);
ZORBA_ASSERT(item->isStructuredItem());
StructuredItem* structuredItem = static_cast<StructuredItem*>(item);
structuredItem->detachFromCollection();
theTrees.erase(theTrees.begin() + pos);
return true;
}
}
/*******************************************************************************
Remove a given number of trees starting with the tree at the given position.
If the given number is 0 or the given position is >= than the number of trees
in the collection, this method is a noop. The method returns the number of
trees that are actually deleted.
********************************************************************************/
xs_integer SimpleCollection::removeNodes(xs_integer position, xs_integer numNodes)
{
SYNC_CODE(AutoLatch lock(theLatch, Latch::WRITE);)
csize pos, num;
try
{
pos = to_xs_unsignedInt(position);
num = to_xs_unsignedInt(numNodes);
}
catch (std::range_error)
{
assert(false);
return xs_integer::zero();
}
if (num == 0 || pos >= theTrees.size())
{
return xs_integer::zero();
}
else
{
csize last = pos + num;
if (last > theTrees.size())
{
last = theTrees.size();
}
for (csize i = pos; i < last; ++i)
{
store::Item* item = theTrees[pos].getp();
ZORBA_ASSERT(item->getCollection() == this);
ZORBA_ASSERT(item->isStructuredItem());
StructuredItem* structuredItem = static_cast<StructuredItem*>(item);
structuredItem->detachFromCollection();
theTrees.erase(theTrees.begin() + pos);
}
return xs_integer(last - pos);
}
}
/*******************************************************************************
Remove all the nodes from the collection
********************************************************************************/
void SimpleCollection::removeAll()
{
SYNC_CODE(AutoLatch lock(theLatch, Latch::WRITE);)
csize numTrees = theTrees.size();
for (csize i = 0; i < numTrees; ++i)
{
store::Item* item = theTrees[i].getp();
ZORBA_ASSERT(item->getCollection() == this);
ZORBA_ASSERT(item->isStructuredItem());
StructuredItem* structuredItem = static_cast<StructuredItem*>(item);
structuredItem->detachFromCollection();
}
theTrees.clear();
}
/*******************************************************************************
For each tree in the collection, set its current position within the collection.
********************************************************************************/
void SimpleCollection::adjustTreePositions()
{
csize numTrees = theTrees.size();
for (csize i = 0; i < numTrees; ++i)
{
static_cast<StructuredItem*>(theTrees[i].getp())->setPosition(xs_integer(i));
}
}
/*******************************************************************************
********************************************************************************/
SimpleCollection::CollectionIter::CollectionIter(
SimpleCollection* collection,
const xs_integer& skip)
:
theCollection(collection),
theHaveLock(false),
theSkip(to_xs_unsignedLong(skip))
{
}
/*******************************************************************************
********************************************************************************/
SimpleCollection::CollectionIter::~CollectionIter()
{
SYNC_CODE(if (theHaveLock) \
theCollection->theLatch.unlock();)
}
/*******************************************************************************
********************************************************************************/
void SimpleCollection::CollectionIter::skip()
{
// skip by position
if (theSkip >= theCollection->size())
{
// we need to skip more then possible -> jump to the end
theIterator = theEnd;
}
else
{
theIterator += theSkip;
}
}
/*******************************************************************************
********************************************************************************/
void SimpleCollection::CollectionIter::open()
{
SYNC_CODE(theCollection->theLatch.rlock();)
theHaveLock = true;
theIterator = theCollection->theTrees.begin();
theEnd = theCollection->theTrees.end();
skip();
}
/*******************************************************************************
********************************************************************************/
bool SimpleCollection::CollectionIter::next(store::Item_t& result)
{
if (!theHaveLock)
{
throw ZORBA_EXCEPTION(zerr::ZDDY0019_COLLECTION_ITERATOR_NOT_OPEN,
ERROR_PARAMS(theCollection->getName()->getStringValue()));
}
if (theIterator == theEnd)
{
result = NULL;
return false;
}
result = *theIterator;
++theIterator;
return true;
}
/*******************************************************************************
********************************************************************************/
void SimpleCollection::CollectionIter::reset()
{
theIterator = theCollection->theTrees.begin();
theEnd = theCollection->theTrees.end();
skip();
}
/*******************************************************************************
********************************************************************************/
void SimpleCollection::CollectionIter::close()
{
assert(theHaveLock);
theHaveLock = false;
SYNC_CODE(theCollection->theLatch.unlock();)
}
} // namespace simplestore
} // namespace zorba
/* vim:set et sw=2 ts=2: */
<|endoftext|> |
<commit_before>/*
* Copyright 2008 The Native Client 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 "native_client/src/trusted/plugin/service_runtime.h"
#include <map>
#include <vector>
#include "native_client/src/include/nacl_string.h"
#include "native_client/src/include/nacl_macros.h"
#include "native_client/src/shared/imc/nacl_imc.h"
#include "native_client/src/shared/platform/nacl_log.h"
#include "native_client/src/trusted/desc/nacl_desc_imc.h"
#include "native_client/src/trusted/desc/nrd_xfer.h"
#include "native_client/src/trusted/desc/nrd_xfer_effector.h"
#include "native_client/src/trusted/handle_pass/browser_handle.h"
#include "native_client/src/trusted/nonnacl_util/sel_ldr_launcher.h"
#include "native_client/src/trusted/plugin/browser_interface.h"
#include "native_client/src/trusted/plugin/connected_socket.h"
#include "native_client/src/trusted/plugin/plugin.h"
#include "native_client/src/trusted/plugin/scriptable_handle.h"
#include "native_client/src/trusted/plugin/shared_memory.h"
#include "native_client/src/trusted/plugin/socket_address.h"
#include "native_client/src/trusted/plugin/srt_socket.h"
#include "native_client/src/trusted/plugin/utility.h"
#include "native_client/src/trusted/service_runtime/nacl_error_code.h"
#include "native_client/src/trusted/service_runtime/include/sys/nacl_imc_api.h"
using std::vector;
namespace plugin {
ServiceRuntime::ServiceRuntime(Plugin* plugin)
: default_socket_address_(NULL),
plugin_(plugin),
browser_interface_(plugin->browser_interface()),
runtime_channel_(NULL),
subprocess_(NULL),
async_receive_desc_(NULL),
async_send_desc_(NULL) {
}
bool ServiceRuntime::InitCommunication(nacl::Handle bootstrap_socket,
nacl::DescWrapper* shm) {
// TODO(sehr): this should use the new
// SelLdrLauncher::OpenSrpcChannels interface, which should be free
// of resource leaks.
// bootstrap_socket was opened to communicate with the sel_ldr instance.
// Get the first IMC message and receive a socket address FD from it.
PLUGIN_PRINTF(("ServiceRuntime::InitCommunication"
" (this=%p, subprocess=%p, bootstrap_socket=%p)\n",
static_cast<void*>(this), static_cast<void*>(subprocess_),
reinterpret_cast<void*>(bootstrap_socket)));
// GetSocketAddress implicitly invokes Close(bootstrap_socket).
// Get service channel descriptor.
default_socket_address_ = GetSocketAddress(plugin_, bootstrap_socket);
PLUGIN_PRINTF(("ServiceRuntime::InitCommunication"
" (default_socket_address=%p)\n",
static_cast<void*>(default_socket_address_)));
if (NULL == default_socket_address_) {
return Failure("service runtime: no valid socket address");
}
// The first connect on the socket address returns the service
// runtime command channel. This channel is created before the NaCl
// module runs, and is private to the service runtime. This channel
// is used for a secure plugin<->service runtime communication path
// that can be used to forcibly shut down the sel_ldr.
PortableHandle* portable_socket_address = default_socket_address_->handle();
ScriptableHandle* raw_channel = portable_socket_address->Connect();
PLUGIN_PRINTF(("ServiceRuntime::InitCommunication (raw_channel=%p)\n",
static_cast<void*>(raw_channel)));
if (NULL == raw_channel) {
return Failure("service runtime: connect failed");
}
runtime_channel_ = new(std::nothrow) SrtSocket(raw_channel,
browser_interface_);
PLUGIN_PRINTF(("ServiceRuntime::InitCommunication (runtime_channel=%p)\n",
static_cast<void*>(runtime_channel_)));
if (NULL == runtime_channel_) {
raw_channel->Unref();
return Failure("service runtime: runtime channel creation failed");
}
if (shm != NULL) {
// This code is executed only if NaCl is running as a built-in plugin
// in Chrome.
// We now have an open communication channel to the sel_ldr process,
// so we can send the nexe bits over
if (!runtime_channel_->LoadModule(shm->desc())) {
// TODO(gregoryd): close communication channels
return Failure("service runtime: failed to send nexe");
}
#if NACL_WINDOWS && !defined(NACL_STANDALONE)
// Establish the communication for handle passing protocol
struct NaClDesc* desc = NaClHandlePassBrowserGetSocketAddress();
if (!runtime_channel_->InitHandlePassing(desc, subprocess_->child())) {
return Failure("service runtime: failed handle passing protocol");
}
#endif
}
// start the module. otherwise we cannot connect for multimedia
// subsystem since that is handled by user-level code (not secure!)
// in libsrpc.
int load_status;
if (!runtime_channel_->StartModule(&load_status)) {
return Failure("service runtime: could not start nacl module");
}
PLUGIN_PRINTF(("ServiceRuntime::InitCommunication (load_status=%d)\n",
load_status));
if (LOAD_OK != load_status) {
nacl::string error = "loading of module failed with status " + load_status;
return Failure(error);
}
return true;
}
bool ServiceRuntime::Failure(const nacl::string& error) {
PLUGIN_PRINTF(("ServiceRuntime::Failure (error='%s')\n", error.c_str()));
browser_interface_->AddToConsole(plugin()->instance_id(), error);
delete subprocess_;
subprocess_ = NULL;
return false;
}
bool ServiceRuntime::StartFromCommandLine(const char* nacl_file) {
PLUGIN_PRINTF(("ServiceRuntime::Start (nacl_file='%s')\n", nacl_file));
subprocess_ = new(std::nothrow) nacl::SelLdrLauncher();
if (NULL == subprocess_) {
return Failure("Failed to create sel_ldr launcher");
}
// The arguments we want to pass to the service runtime are
// "-X 5" causes the service runtime to create a bound socket and socket
// address at descriptors 3 and 4. The socket address is transferred as
// the first IMC message on descriptor 5. This is used when connecting
// to socket addresses.
// "-d" (not default) invokes the service runtime in debug mode.
const char* kSelLdrArgs[] = { "-X", "5" };
const int kSelLdrArgLength = NACL_ARRAY_SIZE(kSelLdrArgs);
vector<nacl::string> kArgv(kSelLdrArgs, kSelLdrArgs + kSelLdrArgLength);
vector<nacl::string> kEmpty;
subprocess_->InitCommandLine(nacl_file, -1, kArgv, kEmpty);
nacl::Handle receive_handle = subprocess_->ExportImcFD(6);
if (receive_handle == nacl::kInvalidHandle) {
return Failure("Failed to create async receive handle");
}
async_receive_desc_ =
plugin()->wrapper_factory()->MakeImcSock(receive_handle);
nacl::Handle send_handle = subprocess_->ExportImcFD(7);
if (send_handle == nacl::kInvalidHandle) {
return Failure("Failed to create async send handle");
}
async_send_desc_ = plugin()->wrapper_factory()->MakeImcSock(send_handle);
nacl::Handle bootstrap_socket = subprocess_->ExportImcFD(5);
if (bootstrap_socket == nacl::kInvalidHandle) {
return Failure("Failed to create socket handle");
}
if (!subprocess_->LaunchFromCommandLine()) {
return Failure("Failed to launch sel_ldr");
}
if (!InitCommunication(bootstrap_socket, NULL)) {
return Failure("Failed to initialize sel_ldr communication");
}
PLUGIN_PRINTF(("ServiceRuntime::Start (return 1)\n"));
return true;
}
bool ServiceRuntime::StartFromBrowser(const char* url,
nacl::DescWrapper* shm) {
PLUGIN_PRINTF(("ServiceRuntime::StartFromBrowser (url=%s, shm=%p)\n",
url, reinterpret_cast<void*>(shm)));
subprocess_ = new(std::nothrow) nacl::SelLdrLauncher();
if (NULL == subprocess_) {
return Failure("Failed to create sel_ldr launcher");
}
nacl::Handle sockets[3];
if (!subprocess_->StartFromBrowser(url, NACL_ARRAY_SIZE(sockets),
sockets)) {
return Failure("Failed to start sel_ldr");
}
nacl::Handle bootstrap_socket = sockets[0];
async_receive_desc_ = plugin()->wrapper_factory()->MakeImcSock(sockets[1]);
async_send_desc_ = plugin()->wrapper_factory()->MakeImcSock(sockets[2]);
if (!InitCommunication(bootstrap_socket, shm)) {
return Failure("Failed to initialize sel_ldr communication");
}
PLUGIN_PRINTF(("ServiceRuntime::StartFromBrowser (return 1)\n"));
return true;
}
bool ServiceRuntime::Kill() {
return subprocess_->KillChildProcess();
}
bool ServiceRuntime::Log(int severity, nacl::string msg) {
return runtime_channel_->Log(severity, msg);
}
void ServiceRuntime::Shutdown() {
if (subprocess_ != NULL) {
Kill();
}
// Note that this does waitpid() to get rid of any zombie subprocess.
delete subprocess_;
subprocess_ = NULL;
delete runtime_channel_;
runtime_channel_ = NULL;
}
ServiceRuntime::~ServiceRuntime() {
PLUGIN_PRINTF(("ServiceRuntime::~ServiceRuntime (this=%p)\n",
static_cast<void*>(this)));
// We do this just in case Terminate() was not called.
delete subprocess_;
delete runtime_channel_;
// TODO(sehr,mseaborn): use scoped_ptr for management of DescWrappers.
delete async_receive_desc_;
delete async_send_desc_;
}
ScriptableHandle* ServiceRuntime::default_socket_address() const {
PLUGIN_PRINTF(("ServiceRuntime::default_socket_address"
" (this=%p, default_socket_address=%p)\n",
static_cast<void*>(const_cast<ServiceRuntime*>(this)),
static_cast<void*>(const_cast<ScriptableHandle*>(
default_socket_address_))));
return default_socket_address_;
}
ScriptableHandle* ServiceRuntime::GetSocketAddress(Plugin* plugin,
nacl::Handle channel) {
nacl::DescWrapper::MsgHeader header;
nacl::DescWrapper::MsgIoVec iovec[1];
unsigned char bytes[NACL_ABI_IMC_USER_BYTES_MAX];
nacl::DescWrapper* descs[NACL_ABI_IMC_USER_DESC_MAX];
PLUGIN_PRINTF(("ServiceRuntime::GetSocketAddress (plugin=%p, channel=%p)\n",
static_cast<void*>(plugin),
reinterpret_cast<void*>(channel)));
ScriptableHandle* retval = NULL;
nacl::DescWrapper* imc_desc = plugin->wrapper_factory()->MakeImcSock(channel);
// Set up to receive a message.
iovec[0].base = bytes;
iovec[0].length = NACL_ABI_IMC_USER_BYTES_MAX;
header.iov = iovec;
header.iov_length = NACL_ARRAY_SIZE(iovec);
header.ndescv = descs;
header.ndescv_length = NACL_ARRAY_SIZE(descs);
header.flags = 0;
// Receive the message.
ssize_t ret = imc_desc->RecvMsg(&header, 0);
// Check that there was exactly one descriptor passed.
if (0 > ret || 1 != header.ndescv_length) {
PLUGIN_PRINTF(("ServiceRuntime::GetSocketAddress"
" (message receive failed %" NACL_PRIdS " %"
NACL_PRIdNACL_SIZE " %" NACL_PRIdNACL_SIZE ")\n", ret,
header.ndescv_length,
header.iov_length));
goto cleanup;
}
PLUGIN_PRINTF(("ServiceRuntime::GetSocketAddress"
" (-X result descriptor descs[0]=%p)\n",
static_cast<void*>(descs[0])));
retval = browser_interface_->NewScriptableHandle(
SocketAddress::New(plugin, descs[0]));
cleanup:
// TODO(sehr,mseaborn): use scoped_ptr for management of DescWrappers.
delete imc_desc;
PLUGIN_PRINTF(("ServiceRuntime::GetSocketAddress (return %p)\n",
static_cast<void*>(retval)));
return retval;
}
} // namespace plugin
<commit_msg>Fix the windows Chrome integration build. The child member of SelLdrLauncher was changed to child_process without complete updates. TBR=polina@google.com BUG=none (trivial build issue) TEST=XP chrome integration build<commit_after>/*
* Copyright 2008 The Native Client 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 "native_client/src/trusted/plugin/service_runtime.h"
#include <map>
#include <vector>
#include "native_client/src/include/nacl_string.h"
#include "native_client/src/include/nacl_macros.h"
#include "native_client/src/shared/imc/nacl_imc.h"
#include "native_client/src/shared/platform/nacl_log.h"
#include "native_client/src/trusted/desc/nacl_desc_imc.h"
#include "native_client/src/trusted/desc/nrd_xfer.h"
#include "native_client/src/trusted/desc/nrd_xfer_effector.h"
#include "native_client/src/trusted/handle_pass/browser_handle.h"
#include "native_client/src/trusted/nonnacl_util/sel_ldr_launcher.h"
#include "native_client/src/trusted/plugin/browser_interface.h"
#include "native_client/src/trusted/plugin/connected_socket.h"
#include "native_client/src/trusted/plugin/plugin.h"
#include "native_client/src/trusted/plugin/scriptable_handle.h"
#include "native_client/src/trusted/plugin/shared_memory.h"
#include "native_client/src/trusted/plugin/socket_address.h"
#include "native_client/src/trusted/plugin/srt_socket.h"
#include "native_client/src/trusted/plugin/utility.h"
#include "native_client/src/trusted/service_runtime/nacl_error_code.h"
#include "native_client/src/trusted/service_runtime/include/sys/nacl_imc_api.h"
using std::vector;
namespace plugin {
ServiceRuntime::ServiceRuntime(Plugin* plugin)
: default_socket_address_(NULL),
plugin_(plugin),
browser_interface_(plugin->browser_interface()),
runtime_channel_(NULL),
subprocess_(NULL),
async_receive_desc_(NULL),
async_send_desc_(NULL) {
}
bool ServiceRuntime::InitCommunication(nacl::Handle bootstrap_socket,
nacl::DescWrapper* shm) {
// TODO(sehr): this should use the new
// SelLdrLauncher::OpenSrpcChannels interface, which should be free
// of resource leaks.
// bootstrap_socket was opened to communicate with the sel_ldr instance.
// Get the first IMC message and receive a socket address FD from it.
PLUGIN_PRINTF(("ServiceRuntime::InitCommunication"
" (this=%p, subprocess=%p, bootstrap_socket=%p)\n",
static_cast<void*>(this), static_cast<void*>(subprocess_),
reinterpret_cast<void*>(bootstrap_socket)));
// GetSocketAddress implicitly invokes Close(bootstrap_socket).
// Get service channel descriptor.
default_socket_address_ = GetSocketAddress(plugin_, bootstrap_socket);
PLUGIN_PRINTF(("ServiceRuntime::InitCommunication"
" (default_socket_address=%p)\n",
static_cast<void*>(default_socket_address_)));
if (NULL == default_socket_address_) {
return Failure("service runtime: no valid socket address");
}
// The first connect on the socket address returns the service
// runtime command channel. This channel is created before the NaCl
// module runs, and is private to the service runtime. This channel
// is used for a secure plugin<->service runtime communication path
// that can be used to forcibly shut down the sel_ldr.
PortableHandle* portable_socket_address = default_socket_address_->handle();
ScriptableHandle* raw_channel = portable_socket_address->Connect();
PLUGIN_PRINTF(("ServiceRuntime::InitCommunication (raw_channel=%p)\n",
static_cast<void*>(raw_channel)));
if (NULL == raw_channel) {
return Failure("service runtime: connect failed");
}
runtime_channel_ = new(std::nothrow) SrtSocket(raw_channel,
browser_interface_);
PLUGIN_PRINTF(("ServiceRuntime::InitCommunication (runtime_channel=%p)\n",
static_cast<void*>(runtime_channel_)));
if (NULL == runtime_channel_) {
raw_channel->Unref();
return Failure("service runtime: runtime channel creation failed");
}
if (shm != NULL) {
// This code is executed only if NaCl is running as a built-in plugin
// in Chrome.
// We now have an open communication channel to the sel_ldr process,
// so we can send the nexe bits over
if (!runtime_channel_->LoadModule(shm->desc())) {
// TODO(gregoryd): close communication channels
return Failure("service runtime: failed to send nexe");
}
#if NACL_WINDOWS && !defined(NACL_STANDALONE)
// Establish the communication for handle passing protocol
struct NaClDesc* desc = NaClHandlePassBrowserGetSocketAddress();
if (!runtime_channel_->InitHandlePassing(desc,
subprocess_->child_process())) {
return Failure("service runtime: failed handle passing protocol");
}
#endif
}
// start the module. otherwise we cannot connect for multimedia
// subsystem since that is handled by user-level code (not secure!)
// in libsrpc.
int load_status;
if (!runtime_channel_->StartModule(&load_status)) {
return Failure("service runtime: could not start nacl module");
}
PLUGIN_PRINTF(("ServiceRuntime::InitCommunication (load_status=%d)\n",
load_status));
if (LOAD_OK != load_status) {
nacl::string error = "loading of module failed with status " + load_status;
return Failure(error);
}
return true;
}
bool ServiceRuntime::Failure(const nacl::string& error) {
PLUGIN_PRINTF(("ServiceRuntime::Failure (error='%s')\n", error.c_str()));
browser_interface_->AddToConsole(plugin()->instance_id(), error);
delete subprocess_;
subprocess_ = NULL;
return false;
}
bool ServiceRuntime::StartFromCommandLine(const char* nacl_file) {
PLUGIN_PRINTF(("ServiceRuntime::Start (nacl_file='%s')\n", nacl_file));
subprocess_ = new(std::nothrow) nacl::SelLdrLauncher();
if (NULL == subprocess_) {
return Failure("Failed to create sel_ldr launcher");
}
// The arguments we want to pass to the service runtime are
// "-X 5" causes the service runtime to create a bound socket and socket
// address at descriptors 3 and 4. The socket address is transferred as
// the first IMC message on descriptor 5. This is used when connecting
// to socket addresses.
// "-d" (not default) invokes the service runtime in debug mode.
const char* kSelLdrArgs[] = { "-X", "5" };
const int kSelLdrArgLength = NACL_ARRAY_SIZE(kSelLdrArgs);
vector<nacl::string> kArgv(kSelLdrArgs, kSelLdrArgs + kSelLdrArgLength);
vector<nacl::string> kEmpty;
subprocess_->InitCommandLine(nacl_file, -1, kArgv, kEmpty);
nacl::Handle receive_handle = subprocess_->ExportImcFD(6);
if (receive_handle == nacl::kInvalidHandle) {
return Failure("Failed to create async receive handle");
}
async_receive_desc_ =
plugin()->wrapper_factory()->MakeImcSock(receive_handle);
nacl::Handle send_handle = subprocess_->ExportImcFD(7);
if (send_handle == nacl::kInvalidHandle) {
return Failure("Failed to create async send handle");
}
async_send_desc_ = plugin()->wrapper_factory()->MakeImcSock(send_handle);
nacl::Handle bootstrap_socket = subprocess_->ExportImcFD(5);
if (bootstrap_socket == nacl::kInvalidHandle) {
return Failure("Failed to create socket handle");
}
if (!subprocess_->LaunchFromCommandLine()) {
return Failure("Failed to launch sel_ldr");
}
if (!InitCommunication(bootstrap_socket, NULL)) {
return Failure("Failed to initialize sel_ldr communication");
}
PLUGIN_PRINTF(("ServiceRuntime::Start (return 1)\n"));
return true;
}
bool ServiceRuntime::StartFromBrowser(const char* url,
nacl::DescWrapper* shm) {
PLUGIN_PRINTF(("ServiceRuntime::StartFromBrowser (url=%s, shm=%p)\n",
url, reinterpret_cast<void*>(shm)));
subprocess_ = new(std::nothrow) nacl::SelLdrLauncher();
if (NULL == subprocess_) {
return Failure("Failed to create sel_ldr launcher");
}
nacl::Handle sockets[3];
if (!subprocess_->StartFromBrowser(url, NACL_ARRAY_SIZE(sockets),
sockets)) {
return Failure("Failed to start sel_ldr");
}
nacl::Handle bootstrap_socket = sockets[0];
async_receive_desc_ = plugin()->wrapper_factory()->MakeImcSock(sockets[1]);
async_send_desc_ = plugin()->wrapper_factory()->MakeImcSock(sockets[2]);
if (!InitCommunication(bootstrap_socket, shm)) {
return Failure("Failed to initialize sel_ldr communication");
}
PLUGIN_PRINTF(("ServiceRuntime::StartFromBrowser (return 1)\n"));
return true;
}
bool ServiceRuntime::Kill() {
return subprocess_->KillChildProcess();
}
bool ServiceRuntime::Log(int severity, nacl::string msg) {
return runtime_channel_->Log(severity, msg);
}
void ServiceRuntime::Shutdown() {
if (subprocess_ != NULL) {
Kill();
}
// Note that this does waitpid() to get rid of any zombie subprocess.
delete subprocess_;
subprocess_ = NULL;
delete runtime_channel_;
runtime_channel_ = NULL;
}
ServiceRuntime::~ServiceRuntime() {
PLUGIN_PRINTF(("ServiceRuntime::~ServiceRuntime (this=%p)\n",
static_cast<void*>(this)));
// We do this just in case Terminate() was not called.
delete subprocess_;
delete runtime_channel_;
// TODO(sehr,mseaborn): use scoped_ptr for management of DescWrappers.
delete async_receive_desc_;
delete async_send_desc_;
}
ScriptableHandle* ServiceRuntime::default_socket_address() const {
PLUGIN_PRINTF(("ServiceRuntime::default_socket_address"
" (this=%p, default_socket_address=%p)\n",
static_cast<void*>(const_cast<ServiceRuntime*>(this)),
static_cast<void*>(const_cast<ScriptableHandle*>(
default_socket_address_))));
return default_socket_address_;
}
ScriptableHandle* ServiceRuntime::GetSocketAddress(Plugin* plugin,
nacl::Handle channel) {
nacl::DescWrapper::MsgHeader header;
nacl::DescWrapper::MsgIoVec iovec[1];
unsigned char bytes[NACL_ABI_IMC_USER_BYTES_MAX];
nacl::DescWrapper* descs[NACL_ABI_IMC_USER_DESC_MAX];
PLUGIN_PRINTF(("ServiceRuntime::GetSocketAddress (plugin=%p, channel=%p)\n",
static_cast<void*>(plugin),
reinterpret_cast<void*>(channel)));
ScriptableHandle* retval = NULL;
nacl::DescWrapper* imc_desc = plugin->wrapper_factory()->MakeImcSock(channel);
// Set up to receive a message.
iovec[0].base = bytes;
iovec[0].length = NACL_ABI_IMC_USER_BYTES_MAX;
header.iov = iovec;
header.iov_length = NACL_ARRAY_SIZE(iovec);
header.ndescv = descs;
header.ndescv_length = NACL_ARRAY_SIZE(descs);
header.flags = 0;
// Receive the message.
ssize_t ret = imc_desc->RecvMsg(&header, 0);
// Check that there was exactly one descriptor passed.
if (0 > ret || 1 != header.ndescv_length) {
PLUGIN_PRINTF(("ServiceRuntime::GetSocketAddress"
" (message receive failed %" NACL_PRIdS " %"
NACL_PRIdNACL_SIZE " %" NACL_PRIdNACL_SIZE ")\n", ret,
header.ndescv_length,
header.iov_length));
goto cleanup;
}
PLUGIN_PRINTF(("ServiceRuntime::GetSocketAddress"
" (-X result descriptor descs[0]=%p)\n",
static_cast<void*>(descs[0])));
retval = browser_interface_->NewScriptableHandle(
SocketAddress::New(plugin, descs[0]));
cleanup:
// TODO(sehr,mseaborn): use scoped_ptr for management of DescWrappers.
delete imc_desc;
PLUGIN_PRINTF(("ServiceRuntime::GetSocketAddress (return %p)\n",
static_cast<void*>(retval)));
return retval;
}
} // namespace plugin
<|endoftext|> |
<commit_before>// @(#)root/oracle:$Id$
// Author: Yan Liu and Shaowen Wang 23/11/04
/*************************************************************************
* Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TOracleResult.h"
#include "TOracleRow.h"
#include "TList.h"
using namespace std;
using namespace oracle::occi;
ClassImp(TOracleResult)
////////////////////////////////////////////////////////////////////////////////
/// Oracle query result.
void TOracleResult::initResultSet(Statement *stmt)
{
if (!stmt) {
Error("initResultSet", "construction: empty statement");
} else {
try {
fStmt = stmt;
if (stmt->status() == Statement::RESULT_SET_AVAILABLE) {
fResultType = 1;
fResult = stmt->getResultSet();
fFieldInfo = (fResult==0) ? 0 : new vector<MetaData>(fResult->getColumnListMetaData());
fFieldCount = (fFieldInfo==0) ? 0 : fFieldInfo->size();
} else if (stmt->status() == Statement::UPDATE_COUNT_AVAILABLE) {
fResultType = 3; // this is update_count_available
fResult = 0;
fFieldInfo = 0;
fFieldCount = 0;
fUpdateCount = stmt->getUpdateCount();
}
} catch (SQLException &oraex) {
Error("initResultSet", "%s", (oraex.getMessage()).c_str());
MakeZombie();
}
}
}
////////////////////////////////////////////////////////////////////////////////
TOracleResult::TOracleResult(Connection *conn, Statement *stmt)
{
fConn = conn;
fResult = 0;
fStmt = 0;
fPool = 0;
fRowCount = 0;
fFieldInfo = 0;
fResultType = 0;
fUpdateCount = 0;
initResultSet(stmt);
if (fResult) ProducePool();
}
////////////////////////////////////////////////////////////////////////////////
/// This construction func is only used to get table metainfo.
TOracleResult::TOracleResult(Connection *conn, const char *tableName)
{
fResult = 0;
fStmt = 0;
fConn = 0;
fPool = 0;
fRowCount = 0;
fFieldInfo = 0;
fResultType = 0;
fUpdateCount = 0;
if (!tableName || !conn) {
Error("TOracleResult", "construction: empty input parameter");
} else {
MetaData connMD = conn->getMetaData(tableName, MetaData::PTYPE_TABLE);
fFieldInfo = new vector<MetaData>(connMD.getVector(MetaData::ATTR_LIST_COLUMNS));
fFieldCount = fFieldInfo->size();
fResultType = 2; // indicates that this is just an table metainfo
}
}
////////////////////////////////////////////////////////////////////////////////
/// Cleanup Oracle query result.
TOracleResult::~TOracleResult()
{
Close();
}
////////////////////////////////////////////////////////////////////////////////
/// Close query result.
void TOracleResult::Close(Option_t *)
{
if (fConn && fStmt) {
if (fResult) fStmt->closeResultSet(fResult);
fConn->terminateStatement(fStmt);
}
if (fPool) {
fPool->Delete();
delete fPool;
}
if (fFieldInfo)
delete fFieldInfo;
fResultType = 0;
fStmt = 0;
fResult = 0;
fFieldInfo = 0;
fPool = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Check if result set is open and field index within range.
Bool_t TOracleResult::IsValid(Int_t field)
{
if (field < 0 || field >= fFieldCount) {
Error("IsValid", "field index out of bounds");
return kFALSE;
}
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
/// Get number of fields in result.
Int_t TOracleResult::GetFieldCount()
{
return fFieldCount;
}
////////////////////////////////////////////////////////////////////////////////
/// Get name of specified field.
const char *TOracleResult::GetFieldName(Int_t field)
{
if (!IsValid(field))
return 0;
fNameBuffer = (*fFieldInfo)[field].getString(MetaData::ATTR_NAME);
return fNameBuffer.c_str();
}
////////////////////////////////////////////////////////////////////////////////
/// Get next query result row. The returned object must be
/// deleted by the user.
TSQLRow *TOracleResult::Next()
{
if (!fResult || (fResultType!=1)) return 0;
if (fPool!=0) {
TSQLRow* row = (TSQLRow*) fPool->First();
if (row!=0) fPool->Remove(row);
return row;
}
// if select query,
try {
if (fResult->next() != oracle::occi::ResultSet::END_OF_FETCH) {
fRowCount++;
return new TOracleRow(fResult, fFieldInfo);
} else
return 0;
} catch (SQLException &oraex) {
Error("Next", "%s", (oraex.getMessage()).c_str());
MakeZombie();
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
Int_t TOracleResult::GetRowCount() const
{
if (!fResult) return 0;
if (fPool==0) ((TOracleResult*) this)->ProducePool();
return fRowCount;
}
////////////////////////////////////////////////////////////////////////////////
void TOracleResult::ProducePool()
{
if (fPool!=0) return;
TList* pool = new TList;
TSQLRow* res = 0;
while ((res = Next()) !=0) {
pool->Add(res);
}
fPool = pool;
}
<commit_msg>coverity 94049: class member not initialised<commit_after>// @(#)root/oracle:$Id$
// Author: Yan Liu and Shaowen Wang 23/11/04
/*************************************************************************
* Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TOracleResult.h"
#include "TOracleRow.h"
#include "TList.h"
using namespace std;
using namespace oracle::occi;
ClassImp(TOracleResult)
////////////////////////////////////////////////////////////////////////////////
/// Oracle query result.
void TOracleResult::initResultSet(Statement *stmt)
{
if (!stmt) {
Error("initResultSet", "construction: empty statement");
} else {
try {
fStmt = stmt;
if (stmt->status() == Statement::RESULT_SET_AVAILABLE) {
fResultType = 1;
fResult = stmt->getResultSet();
fFieldInfo = (fResult==0) ? 0 : new vector<MetaData>(fResult->getColumnListMetaData());
fFieldCount = (fFieldInfo==0) ? 0 : fFieldInfo->size();
} else if (stmt->status() == Statement::UPDATE_COUNT_AVAILABLE) {
fResultType = 3; // this is update_count_available
fResult = 0;
fFieldInfo = 0;
fFieldCount = 0;
fUpdateCount = stmt->getUpdateCount();
}
} catch (SQLException &oraex) {
Error("initResultSet", "%s", (oraex.getMessage()).c_str());
MakeZombie();
}
}
}
////////////////////////////////////////////////////////////////////////////////
TOracleResult::TOracleResult(Connection *conn, Statement *stmt)
{
fConn = conn;
fResult = 0;
fStmt = 0;
fPool = 0;
fRowCount = 0;
fFieldInfo = 0;
fResultType = 0;
fUpdateCount = 0;
initResultSet(stmt);
if (fResult) ProducePool();
}
////////////////////////////////////////////////////////////////////////////////
/// This construction func is only used to get table metainfo.
TOracleResult::TOracleResult(Connection *conn, const char *tableName)
{
fResult = 0;
fStmt = 0;
fConn = 0;
fPool = 0;
fRowCount = 0;
fFieldInfo = 0;
fResultType = 0;
fUpdateCount = 0;
fFieldCount = 0;
if (!tableName || !conn) {
Error("TOracleResult", "construction: empty input parameter");
} else {
MetaData connMD = conn->getMetaData(tableName, MetaData::PTYPE_TABLE);
fFieldInfo = new vector<MetaData>(connMD.getVector(MetaData::ATTR_LIST_COLUMNS));
fFieldCount = fFieldInfo->size();
fResultType = 2; // indicates that this is just an table metainfo
}
}
////////////////////////////////////////////////////////////////////////////////
/// Cleanup Oracle query result.
TOracleResult::~TOracleResult()
{
Close();
}
////////////////////////////////////////////////////////////////////////////////
/// Close query result.
void TOracleResult::Close(Option_t *)
{
if (fConn && fStmt) {
if (fResult) fStmt->closeResultSet(fResult);
fConn->terminateStatement(fStmt);
}
if (fPool) {
fPool->Delete();
delete fPool;
}
if (fFieldInfo)
delete fFieldInfo;
fResultType = 0;
fStmt = 0;
fResult = 0;
fFieldInfo = 0;
fPool = 0;
}
////////////////////////////////////////////////////////////////////////////////
/// Check if result set is open and field index within range.
Bool_t TOracleResult::IsValid(Int_t field)
{
if (field < 0 || field >= fFieldCount) {
Error("IsValid", "field index out of bounds");
return kFALSE;
}
return kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
/// Get number of fields in result.
Int_t TOracleResult::GetFieldCount()
{
return fFieldCount;
}
////////////////////////////////////////////////////////////////////////////////
/// Get name of specified field.
const char *TOracleResult::GetFieldName(Int_t field)
{
if (!IsValid(field))
return 0;
fNameBuffer = (*fFieldInfo)[field].getString(MetaData::ATTR_NAME);
return fNameBuffer.c_str();
}
////////////////////////////////////////////////////////////////////////////////
/// Get next query result row. The returned object must be
/// deleted by the user.
TSQLRow *TOracleResult::Next()
{
if (!fResult || (fResultType!=1)) return 0;
if (fPool!=0) {
TSQLRow* row = (TSQLRow*) fPool->First();
if (row!=0) fPool->Remove(row);
return row;
}
// if select query,
try {
if (fResult->next() != oracle::occi::ResultSet::END_OF_FETCH) {
fRowCount++;
return new TOracleRow(fResult, fFieldInfo);
} else
return 0;
} catch (SQLException &oraex) {
Error("Next", "%s", (oraex.getMessage()).c_str());
MakeZombie();
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
Int_t TOracleResult::GetRowCount() const
{
if (!fResult) return 0;
if (fPool==0) ((TOracleResult*) this)->ProducePool();
return fRowCount;
}
////////////////////////////////////////////////////////////////////////////////
void TOracleResult::ProducePool()
{
if (fPool!=0) return;
TList* pool = new TList;
TSQLRow* res = 0;
while ((res = Next()) !=0) {
pool->Add(res);
}
fPool = pool;
}
<|endoftext|> |
<commit_before>#pragma once
#include "probing_hash_utils.hh"
#include "huffmanish.hh"
#include "hash.hh" //Includes line splitter
#include <sys/stat.h> //For finding size of file
#include "helpers/vocabid.hh"
char * read_binary_file(char * filename);
class QueryEngine {
unsigned char * binary_mmaped; //The binari phrase table file
std::map<unsigned int, std::string> vocabids;
std::map<uint64_t, std::string> source_vocabids;
Table table;
char *mem; //Memory for the table, necessary so that we can correctly destroy the object
HuffmanDecoder decoder;
size_t binary_filesize;
size_t table_filesize;
public:
QueryEngine (const char *);
~QueryEngine();
std::pair<bool, std::vector<target_text> > query(StringPiece source_phrase);
std::pair<bool, std::vector<target_text> > query(std::vector<uint64_t> source_phrase);
void printTargetInfo(std::vector<target_text> target_phrases);
const std::map<unsigned int, std::string> getVocab() const
{ return decoder.get_target_lookup_map(); }
const std::map<uint64_t, std::string> getSourceVocab() const {
return source_vocabids;
}
};
<commit_msg>Fix an include<commit_after>#pragma once
#include "probing_hash_utils.hh"
#include "huffmanish.hh"
#include "hash.hh" //Includes line splitter
#include <sys/stat.h> //For finding size of file
#include "vocabid.hh"
char * read_binary_file(char * filename);
class QueryEngine {
unsigned char * binary_mmaped; //The binari phrase table file
std::map<unsigned int, std::string> vocabids;
std::map<uint64_t, std::string> source_vocabids;
Table table;
char *mem; //Memory for the table, necessary so that we can correctly destroy the object
HuffmanDecoder decoder;
size_t binary_filesize;
size_t table_filesize;
public:
QueryEngine (const char *);
~QueryEngine();
std::pair<bool, std::vector<target_text> > query(StringPiece source_phrase);
std::pair<bool, std::vector<target_text> > query(std::vector<uint64_t> source_phrase);
void printTargetInfo(std::vector<target_text> target_phrases);
const std::map<unsigned int, std::string> getVocab() const
{ return decoder.get_target_lookup_map(); }
const std::map<uint64_t, std::string> getSourceVocab() const {
return source_vocabids;
}
};
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: imgdef.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2003-04-04 17:21:02 $
*
* 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 _SVTOOLS_IMGDEF_HXX
#define _SVTOOLS_IMGDEF_HXX
enum SfxSymbolSet
{
SFX_SYMBOLS_SMALL,
SFX_SYMBOLS_LARGE,
SFX_SYMBOLS_AUTO
};
#define SFX_TOOLBOX_CHANGESYMBOLSET 0x0001
#define SFX_TOOLBOX_CHANGEOUTSTYLE 0x0002
#define SFX_TOOLBOX_CHANGEBUTTONTYPE 0x0004
#endif // _SVTOOLS_IMGDEF_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.918); FILE MERGED 2005/09/05 14:50:45 rt 1.2.918.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: imgdef.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 09:42:15 $
*
* 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 _SVTOOLS_IMGDEF_HXX
#define _SVTOOLS_IMGDEF_HXX
enum SfxSymbolSet
{
SFX_SYMBOLS_SMALL,
SFX_SYMBOLS_LARGE,
SFX_SYMBOLS_AUTO
};
#define SFX_TOOLBOX_CHANGESYMBOLSET 0x0001
#define SFX_TOOLBOX_CHANGEOUTSTYLE 0x0002
#define SFX_TOOLBOX_CHANGEBUTTONTYPE 0x0004
#endif // _SVTOOLS_IMGDEF_HXX
<|endoftext|> |
<commit_before>//============================================================================
// vSMC/example/rng/include/rng_test.hpp
//----------------------------------------------------------------------------
// vSMC: Scalable Monte Carlo
//----------------------------------------------------------------------------
// Copyright (c) 2013-2015, Yan Zhou
// 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.
//============================================================================
#ifndef VSMC_EXAMPLE_RNG_TEST_HPP
#define VSMC_EXAMPLE_RNG_TEST_HPP
#include <vsmc/rng/rng.hpp>
#include <vsmc/utility/stop_watch.hpp>
#define VSMC_RNG_TEST_PRE(prog) \
std::size_t N = 1000000; \
std::string prog_name(#prog); \
if (argc > 1) \
N = static_cast<std::size_t>(std::atoi(argv[1])); \
vsmc::Vector<std::string> names; \
vsmc::Vector<std::size_t> size; \
vsmc::Vector<vsmc::StopWatch> sw;
#define VSMC_RNG_TEST(RNGType) rng_test<RNGType>(N, #RNGType, names, size, sw);
#define VSMC_RNG_TEST_POST rng_output_sw(prog_name, names, size, sw);
template <typename RNGType>
inline void rng_test(std::size_t N, const std::string &name,
vsmc::Vector<std::string> &names, vsmc::Vector<std::size_t> &size,
vsmc::Vector<vsmc::StopWatch> &sw)
{
names.push_back(name);
size.push_back(sizeof(RNGType));
RNGType rng;
vsmc::StopWatch watch;
double result = 0;
vsmc::Vector<double> r(N);
vsmc::Vector<typename RNGType::result_type> u(N);
MKL_INT n = static_cast<MKL_INT>(N);
MKL_INT m = n / 1000;
std::uniform_real_distribution<double> runif_std(0, 1);
watch.reset();
watch.start();
for (std::size_t i = 0; i != N; ++i)
r[i] = runif_std(rng);
watch.stop();
result += std::accumulate(r.begin(), r.end(), 0.0);
sw.push_back(watch);
vsmc::UniformRealDistribution<double> runif_vsmc(0, 1);
watch.reset();
watch.start();
for (std::size_t i = 0; i != N; ++i)
r[i] = runif_vsmc(rng);
watch.stop();
result += std::accumulate(r.begin(), r.end(), 0.0);
sw.push_back(watch);
runif_vsmc(rng, N / 1000, r.data());
watch.reset();
watch.start();
runif_vsmc(rng, N, r.data());
watch.stop();
result += std::accumulate(r.begin(), r.end(), 0.0);
sw.push_back(watch);
std::ofstream rnd("rnd");
rnd << result << std::endl;
rnd.close();
}
inline void rng_output_sw(const std::string &prog_name,
const vsmc::Vector<std::string> &names,
const vsmc::Vector<std::size_t> &size,
const vsmc::Vector<vsmc::StopWatch> &sw)
{
std::size_t N = names.size();
std::size_t R = sw.size() / N;
std::size_t lwid = 80;
int twid = 15;
int swid = 5;
int Twid = twid * static_cast<int>(R);
int nwid = static_cast<int>(lwid) - swid - Twid;
std::cout << std::string(lwid, '=') << std::endl;
std::cout << std::left << std::setw(nwid) << prog_name;
std::cout << std::right << std::setw(swid) << "Size";
std::cout << std::right << std::setw(twid) << "Time (STD)";
std::cout << std::right << std::setw(twid) << "Time (vSMC)";
std::cout << std::right << std::setw(twid) << "Time (Batch)";
std::cout << std::endl;
std::cout << std::string(lwid, '-') << std::endl;
for (std::size_t i = 0; i != N; ++i) {
std::cout << std::left << std::setw(nwid) << names[i];
std::cout << std::right << std::setw(swid) << size[i];
for (std::size_t r = 0; r != R; ++r) {
double time = sw[i * R + r].milliseconds();
std::cout << std::right << std::setw(twid) << std::fixed << time;
}
std::cout << std::endl;
}
std::cout << std::string(lwid, '=') << std::endl;
}
#endif // VSMC_EXAMPLE_RNG_TEST_HPP
<commit_msg>remove unused variables<commit_after>//============================================================================
// vSMC/example/rng/include/rng_test.hpp
//----------------------------------------------------------------------------
// vSMC: Scalable Monte Carlo
//----------------------------------------------------------------------------
// Copyright (c) 2013-2015, Yan Zhou
// 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.
//============================================================================
#ifndef VSMC_EXAMPLE_RNG_TEST_HPP
#define VSMC_EXAMPLE_RNG_TEST_HPP
#include <vsmc/rng/rng.hpp>
#include <vsmc/utility/stop_watch.hpp>
#define VSMC_RNG_TEST_PRE(prog) \
std::size_t N = 1000000; \
std::string prog_name(#prog); \
if (argc > 1) \
N = static_cast<std::size_t>(std::atoi(argv[1])); \
vsmc::Vector<std::string> names; \
vsmc::Vector<std::size_t> size; \
vsmc::Vector<vsmc::StopWatch> sw;
#define VSMC_RNG_TEST(RNGType) rng_test<RNGType>(N, #RNGType, names, size, sw);
#define VSMC_RNG_TEST_POST rng_output_sw(prog_name, names, size, sw);
template <typename RNGType>
inline void rng_test(std::size_t N, const std::string &name,
vsmc::Vector<std::string> &names, vsmc::Vector<std::size_t> &size,
vsmc::Vector<vsmc::StopWatch> &sw)
{
names.push_back(name);
size.push_back(sizeof(RNGType));
RNGType rng;
vsmc::StopWatch watch;
double result = 0;
vsmc::Vector<double> r(N);
vsmc::Vector<typename RNGType::result_type> u(N);
std::uniform_real_distribution<double> runif_std(0, 1);
watch.reset();
watch.start();
for (std::size_t i = 0; i != N; ++i)
r[i] = runif_std(rng);
watch.stop();
result += std::accumulate(r.begin(), r.end(), 0.0);
sw.push_back(watch);
vsmc::UniformRealDistribution<double> runif_vsmc(0, 1);
watch.reset();
watch.start();
for (std::size_t i = 0; i != N; ++i)
r[i] = runif_vsmc(rng);
watch.stop();
result += std::accumulate(r.begin(), r.end(), 0.0);
sw.push_back(watch);
runif_vsmc(rng, N / 1000, r.data());
watch.reset();
watch.start();
runif_vsmc(rng, N, r.data());
watch.stop();
result += std::accumulate(r.begin(), r.end(), 0.0);
sw.push_back(watch);
std::ofstream rnd("rnd");
rnd << result << std::endl;
rnd.close();
}
inline void rng_output_sw(const std::string &prog_name,
const vsmc::Vector<std::string> &names,
const vsmc::Vector<std::size_t> &size,
const vsmc::Vector<vsmc::StopWatch> &sw)
{
std::size_t N = names.size();
std::size_t R = sw.size() / N;
std::size_t lwid = 80;
int twid = 15;
int swid = 5;
int Twid = twid * static_cast<int>(R);
int nwid = static_cast<int>(lwid) - swid - Twid;
std::cout << std::string(lwid, '=') << std::endl;
std::cout << std::left << std::setw(nwid) << prog_name;
std::cout << std::right << std::setw(swid) << "Size";
std::cout << std::right << std::setw(twid) << "Time (STD)";
std::cout << std::right << std::setw(twid) << "Time (vSMC)";
std::cout << std::right << std::setw(twid) << "Time (Batch)";
std::cout << std::endl;
std::cout << std::string(lwid, '-') << std::endl;
for (std::size_t i = 0; i != N; ++i) {
std::cout << std::left << std::setw(nwid) << names[i];
std::cout << std::right << std::setw(swid) << size[i];
for (std::size_t r = 0; r != R; ++r) {
double time = sw[i * R + r].milliseconds();
std::cout << std::right << std::setw(twid) << std::fixed << time;
}
std::cout << std::endl;
}
std::cout << std::string(lwid, '=') << std::endl;
}
#endif // VSMC_EXAMPLE_RNG_TEST_HPP
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qversitcontactexporter.h"
#include "qversitcontactexporter_p.h"
#include "qmobilityglobal.h"
#include <qcontact.h>
#include <qcontactdetail.h>
QTM_BEGIN_NAMESPACE
/*!
\class QVersitContactExporter
\brief The QVersitContactExporter class exports QContact(s) into QVersitDocument(s).
\ingroup versit
If the exported QContact has some detail with an image as its value,
signal \l QVersitContactExporter::scale() is emitted and
the client can scale the image's data to the size it wishes.
The client may retrieve the list contact details
which were not exported using QVersitContactExporter::unknownContactDetails().
\code
// An example of exporting a QContact:
QVersitContactExporter contactExporter;
QContact contact;
// Create a name
QContactName name;
name.setFirst(QString::fromAscii("John"));
contact.saveDetail(&name);
// Create an avatar type which is not supported by the exporter
QContactAvatar contactAvatar;
contactAvatar.setAvatar(QString::fromAscii("/my/image/avatar_path/texture.type"));
contactAvatar.setSubType(QContactAvatar::SubTypeTexturedMesh);
contact.saveDetail(&contactAvatar);
// Create an organization detail with a title and a logo
QContactOrganization organization;
organization.setTitle(QString::fromAscii("Developer"));
organization.setLogo(QString::fromAscii("/my/image/logo_path/logo.jpg"));
contact.saveDetail(&organization);
QVersitDocument versitDocument = contactExporter.exportContact(contact);
// Client will receive the signal "scale" with the logo image path
QList<QContactDetail> unknownDetails = contactExporter.unknownContactDetails();
// The returned unknownDetails can be processed by the client and
// the client can append details directly into QVersitDocument if needed.
// (In this example QContactAvatar::SubTypeTexturedMesh.
// Currently for QContactAvatar details,
// only exporting subtypes QContactAvatar::SubTypeImage and
// QContactAvatar::SubTypeAudioRingtone is supported.)
\endcode
\sa QVersitDocument, QVersitProperty
*/
/*!
* \fn void QVersitContactExporter::scale(const QString& imageFileName, QByteArray& imageData)
* This signal is emitted by \l QVersitContactExporter::exportContact(),
* when a contact detail containing an image is found in a QContact.
* The input for the client is the path of the image in \a imageFileName.
* When the client has performed the scaling,
* it should write the result to \a imageData.
* Image scaling can be done for example by using class QImage.
*/
/*!
* Constructs a new contact exporter
*/
QVersitContactExporter::QVersitContactExporter()
: d(new QVersitContactExporterPrivate())
{
connect(d, SIGNAL(scale(const QString&,QByteArray&)),
this, SIGNAL(scale(const QString&,QByteArray&)));
}
/*!
* Frees any memory in use by this contact exporter.
*/
QVersitContactExporter::~QVersitContactExporter()
{
}
/*!
* Returns the versit document corresponding
* to the \a contact and \a versitType.
*/
QVersitDocument QVersitContactExporter::exportContact(
const QContact& contact,
QVersitDocument::VersitType versitType)
{
QVersitDocument versitDocument;
versitDocument.setVersitType(versitType);
d->exportContact(versitDocument,contact);
return versitDocument;
}
/*!
* Returns the list of contact details, which were not exported
* by the most recent call of \l QVersitContactExporter::exportContact().
*/
QList<QContactDetail> QVersitContactExporter::unknownContactDetails()
{
return d->mUnknownContactDetails;
}
#include "moc_qversitcontactexporter.cpp"
QTM_END_NAMESPACE
<commit_msg>Fix memory leak.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qversitcontactexporter.h"
#include "qversitcontactexporter_p.h"
#include "qmobilityglobal.h"
#include <qcontact.h>
#include <qcontactdetail.h>
QTM_BEGIN_NAMESPACE
/*!
\class QVersitContactExporter
\brief The QVersitContactExporter class exports QContact(s) into QVersitDocument(s).
\ingroup versit
If the exported QContact has some detail with an image as its value,
signal \l QVersitContactExporter::scale() is emitted and
the client can scale the image's data to the size it wishes.
The client may retrieve the list contact details
which were not exported using QVersitContactExporter::unknownContactDetails().
\code
// An example of exporting a QContact:
QVersitContactExporter contactExporter;
QContact contact;
// Create a name
QContactName name;
name.setFirst(QString::fromAscii("John"));
contact.saveDetail(&name);
// Create an avatar type which is not supported by the exporter
QContactAvatar contactAvatar;
contactAvatar.setAvatar(QString::fromAscii("/my/image/avatar_path/texture.type"));
contactAvatar.setSubType(QContactAvatar::SubTypeTexturedMesh);
contact.saveDetail(&contactAvatar);
// Create an organization detail with a title and a logo
QContactOrganization organization;
organization.setTitle(QString::fromAscii("Developer"));
organization.setLogo(QString::fromAscii("/my/image/logo_path/logo.jpg"));
contact.saveDetail(&organization);
QVersitDocument versitDocument = contactExporter.exportContact(contact);
// Client will receive the signal "scale" with the logo image path
QList<QContactDetail> unknownDetails = contactExporter.unknownContactDetails();
// The returned unknownDetails can be processed by the client and
// the client can append details directly into QVersitDocument if needed.
// (In this example QContactAvatar::SubTypeTexturedMesh.
// Currently for QContactAvatar details,
// only exporting subtypes QContactAvatar::SubTypeImage and
// QContactAvatar::SubTypeAudioRingtone is supported.)
\endcode
\sa QVersitDocument, QVersitProperty
*/
/*!
* \fn void QVersitContactExporter::scale(const QString& imageFileName, QByteArray& imageData)
* This signal is emitted by \l QVersitContactExporter::exportContact(),
* when a contact detail containing an image is found in a QContact.
* The input for the client is the path of the image in \a imageFileName.
* When the client has performed the scaling,
* it should write the result to \a imageData.
* Image scaling can be done for example by using class QImage.
*/
/*!
* Constructs a new contact exporter
*/
QVersitContactExporter::QVersitContactExporter()
: d(new QVersitContactExporterPrivate())
{
connect(d, SIGNAL(scale(const QString&,QByteArray&)),
this, SIGNAL(scale(const QString&,QByteArray&)));
}
/*!
* Frees any memory in use by this contact exporter.
*/
QVersitContactExporter::~QVersitContactExporter()
{
delete d;
}
/*!
* Returns the versit document corresponding
* to the \a contact and \a versitType.
*/
QVersitDocument QVersitContactExporter::exportContact(
const QContact& contact,
QVersitDocument::VersitType versitType)
{
QVersitDocument versitDocument;
versitDocument.setVersitType(versitType);
d->exportContact(versitDocument,contact);
return versitDocument;
}
/*!
* Returns the list of contact details, which were not exported
* by the most recent call of \l QVersitContactExporter::exportContact().
*/
QList<QContactDetail> QVersitContactExporter::unknownContactDetails()
{
return d->mUnknownContactDetails;
}
#include "moc_qversitcontactexporter.cpp"
QTM_END_NAMESPACE
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: interceptionhelper.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2006-05-08 14:43:35 $
*
* 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
*
************************************************************************/
//_______________________________________________
// my own includes
#ifndef __FRAMEWORK_DISPATCH_INTERCEPTIONHELPER_HXX_
#include <dispatch/interceptionhelper.hxx>
#endif
//_______________________________________________
// interface includes
#ifndef _COM_SUN_STAR_FRAME_XINTERCEPTORINFO_HPP_
#include <com/sun/star/frame/XInterceptorInfo.hpp>
#endif
//_______________________________________________
// includes of other projects
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
//_______________________________________________
// namespace
namespace framework{
//_______________________________________________
// non exported const
sal_Bool InterceptionHelper::m_bPreferrFirstInterceptor = sal_True;
//_______________________________________________
// non exported definitions
//_______________________________________________
// declarations
/*-----------------------------------------------------------------------------
31.03.2003 09:02
-----------------------------------------------------------------------------*/
DEFINE_XINTERFACE_3(InterceptionHelper ,
OWeakObject ,
DIRECT_INTERFACE(css::frame::XDispatchProvider ),
DIRECT_INTERFACE(css::frame::XDispatchProviderInterception),
DIRECT_INTERFACE(css::lang::XEventListener ))
/*-----------------------------------------------------------------------------
31.03.2003 09:02
-----------------------------------------------------------------------------*/
InterceptionHelper::InterceptionHelper(const css::uno::Reference< css::frame::XFrame >& xOwner,
const css::uno::Reference< css::frame::XDispatchProvider >& xSlave)
// Init baseclasses first
: ThreadHelpBase(&Application::GetSolarMutex())
, OWeakObject ( )
// Init member
, m_xOwnerWeak (xOwner )
, m_xSlave (xSlave )
{
}
/*-----------------------------------------------------------------------------
31.03.2003 09:02
-----------------------------------------------------------------------------*/
InterceptionHelper::~InterceptionHelper()
{
}
/*-----------------------------------------------------------------------------
31.03.2003 09:09
-----------------------------------------------------------------------------*/
css::uno::Reference< css::frame::XDispatch > SAL_CALL InterceptionHelper::queryDispatch(const css::util::URL& aURL ,
const ::rtl::OUString& sTargetFrameName,
sal_Int32 nSearchFlags )
throw(css::uno::RuntimeException)
{
// SAFE {
ReadGuard aReadLock(m_aLock);
// a) first search an interceptor, which match to this URL by it's URL pattern registration
// Note: if it return NULL - it does not mean an empty interceptor list automaticly!
css::uno::Reference< css::frame::XDispatchProvider > xInterceptor;
InterceptorList::const_iterator pIt = m_lInterceptionRegs.findByPattern(aURL.Complete);
if (pIt != m_lInterceptionRegs.end())
xInterceptor = pIt->xInterceptor;
// b) No match by registration - but a valid interceptor list.
// Use first interceptor everytimes.
// Note: it doesn't matter, which direction this helper implementation use to ask interceptor objects.
// Using of member m_aInterceptorList will starts at the beginning everytimes.
// It depends from the filling operation, in which direction it works realy!
if (!xInterceptor.is() && m_lInterceptionRegs.size()>0)
{
pIt = m_lInterceptionRegs.begin();
xInterceptor = pIt->xInterceptor;
}
// c) No registered interceptor => use our direct slave.
// This helper exist by design and must be valid everytimes ...
// But to be more feature proof - we should check that .-)
if (!xInterceptor.is() && m_xSlave.is())
xInterceptor = m_xSlave;
aReadLock.unlock();
// } SAFE
css::uno::Reference< css::frame::XDispatch > xReturn;
if (xInterceptor.is())
xReturn = xInterceptor->queryDispatch(aURL, sTargetFrameName, nSearchFlags);
return xReturn;
}
/*-----------------------------------------------------------------------------
31.03.2003 07:58
-----------------------------------------------------------------------------*/
css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL InterceptionHelper::queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptor )
throw(css::uno::RuntimeException)
{
sal_Int32 c = lDescriptor.getLength();
css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > lDispatches (c);
css::uno::Reference< css::frame::XDispatch >* pDispatches = lDispatches.getArray();
const css::frame::DispatchDescriptor* pDescriptor = lDescriptor.getConstArray();
for (sal_Int32 i=0; i<c; ++i)
pDispatches[i] = queryDispatch(pDescriptor[i].FeatureURL, pDescriptor[i].FrameName, pDescriptor[i].SearchFlags);
return lDispatches;
}
/*-----------------------------------------------------------------------------
31.03.2003 10:20
-----------------------------------------------------------------------------*/
void SAL_CALL InterceptionHelper::registerDispatchProviderInterceptor(const css::uno::Reference< css::frame::XDispatchProviderInterceptor >& xInterceptor)
throw(css::uno::RuntimeException)
{
// reject wrong calling of this interface method
css::uno::Reference< css::frame::XDispatchProvider > xThis(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY);
if (!xInterceptor.is())
throw css::uno::RuntimeException(DECLARE_ASCII("NULL references not allowed as in parameter"), xThis);
// Fill a new info structure for new interceptor.
// Save his reference and try to get an additional URL/pattern list from him.
// If no list exist register these interceptor for all dispatch events with "*"!
InterceptorInfo aInfo;
aInfo.xInterceptor = css::uno::Reference< css::frame::XDispatchProvider >(xInterceptor, css::uno::UNO_QUERY);
css::uno::Reference< css::frame::XInterceptorInfo > xInfo(xInterceptor, css::uno::UNO_QUERY);
if (xInfo.is())
aInfo.lURLPattern = xInfo->getInterceptedURLs();
else
{
aInfo.lURLPattern.realloc(1);
aInfo.lURLPattern[0] = ::rtl::OUString::createFromAscii("*");
}
// SAFE {
WriteGuard aWriteLock(m_aLock);
// a) no interceptor at all - set this instance as master for given interceptor
// and set our slave as it's slave - and put this interceptor to the list.
// It's place there doesn matter. Because this list is currently empty.
if (m_lInterceptionRegs.size()<1)
{
xInterceptor->setMasterDispatchProvider(xThis );
xInterceptor->setSlaveDispatchProvider (m_xSlave);
m_lInterceptionRegs.push_back(aInfo);
}
// b) OK - there is at least one interceptor already registered.
// It's slave and it's master must be valid references ...
// because we created it. But we have to look for the static bool which
// regulate direction of using of interceptor objects!
// b1) If "m_bPreferrFirstInterceptor" is set to true, we have to
// insert it behind any other existing interceptor - means at the end of our list.
else if (m_bPreferrFirstInterceptor)
{
css::uno::Reference< css::frame::XDispatchProvider > xMasterD = m_lInterceptionRegs.rbegin()->xInterceptor;
css::uno::Reference< css::frame::XDispatchProviderInterceptor > xMasterI (xMasterD, css::uno::UNO_QUERY);
xInterceptor->setMasterDispatchProvider(xMasterD );
xInterceptor->setSlaveDispatchProvider (m_xSlave );
xMasterI->setSlaveDispatchProvider (aInfo.xInterceptor);
m_lInterceptionRegs.push_back(aInfo);
}
// b2) If "m_bPreferrFirstInterceptor" is set to false, we have to
// insert it before any other existing interceptor - means at the beginning of our list.
else
{
css::uno::Reference< css::frame::XDispatchProvider > xSlaveD = m_lInterceptionRegs.begin()->xInterceptor;
css::uno::Reference< css::frame::XDispatchProviderInterceptor > xSlaveI (xSlaveD , css::uno::UNO_QUERY);
xInterceptor->setMasterDispatchProvider(xThis );
xInterceptor->setSlaveDispatchProvider (xSlaveD );
xSlaveI->setMasterDispatchProvider (aInfo.xInterceptor);
m_lInterceptionRegs.push_front(aInfo);
}
css::uno::Reference< css::frame::XFrame > xOwner(m_xOwnerWeak.get(), css::uno::UNO_QUERY);
aWriteLock.unlock();
// } SAFE
// Don't forget to send a frame action event "context changed".
// Any cached dispatch objects must be validated now!
if (xOwner.is())
xOwner->contextChanged();
}
/*-----------------------------------------------------------------------------
31.03.2003 10:27
-----------------------------------------------------------------------------*/
void SAL_CALL InterceptionHelper::releaseDispatchProviderInterceptor(const css::uno::Reference< css::frame::XDispatchProviderInterceptor >& xInterceptor)
throw(css::uno::RuntimeException)
{
// reject wrong calling of this interface method
css::uno::Reference< css::frame::XDispatchProvider > xThis(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY);
if (!xInterceptor.is())
throw css::uno::RuntimeException(DECLARE_ASCII("NULL references not allowed as in parameter"), xThis);
// SAFE {
WriteGuard aWriteLock(m_aLock);
// search this interceptor ...
// If it could be located inside cache -
// use it's slave/master relations to update the interception list;
// set empty references for it as new master and slave;
// and relase it from out cache.
InterceptorList::iterator pIt = m_lInterceptionRegs.findByReference(xInterceptor);
if (pIt != m_lInterceptionRegs.end())
{
css::uno::Reference< css::frame::XDispatchProvider > xSlaveD (xInterceptor->getSlaveDispatchProvider() , css::uno::UNO_QUERY);
css::uno::Reference< css::frame::XDispatchProvider > xMasterD (xInterceptor->getMasterDispatchProvider(), css::uno::UNO_QUERY);
css::uno::Reference< css::frame::XDispatchProviderInterceptor > xSlaveI (xSlaveD , css::uno::UNO_QUERY);
css::uno::Reference< css::frame::XDispatchProviderInterceptor > xMasterI (xMasterD , css::uno::UNO_QUERY);
if (xMasterI.is())
xMasterI->setSlaveDispatchProvider(xSlaveD);
if (xSlaveI.is())
xSlaveI->setMasterDispatchProvider(xMasterD);
xInterceptor->setSlaveDispatchProvider (css::uno::Reference< css::frame::XDispatchProvider >());
xInterceptor->setMasterDispatchProvider(css::uno::Reference< css::frame::XDispatchProvider >());
m_lInterceptionRegs.erase(pIt);
}
css::uno::Reference< css::frame::XFrame > xOwner(m_xOwnerWeak.get(), css::uno::UNO_QUERY);
aWriteLock.unlock();
// } SAFE
// Don't forget to send a frame action event "context changed".
// Any cached dispatch objects must be validated now!
if (xOwner.is())
xOwner->contextChanged();
}
/*-----------------------------------------------------------------------------
31.03.2003 10:31
-----------------------------------------------------------------------------*/
#define FORCE_DESTRUCTION_OF_INTERCEPTION_CHAIN
void SAL_CALL InterceptionHelper::disposing(const css::lang::EventObject& aEvent)
throw(css::uno::RuntimeException)
{
#ifdef FORCE_DESTRUCTION_OF_INTERCEPTION_CHAIN
// SAFE ->
ReadGuard aReadLock(m_aLock);
// check calli ... we accept such disposing call's only from our onwer frame.
css::uno::Reference< css::frame::XFrame > xOwner(m_xOwnerWeak.get(), css::uno::UNO_QUERY);
if (aEvent.Source != xOwner)
return;
// Because every interceptor hold at least one reference to us ... and we destruct this list
// of interception objects ... we should hold ourself alive .-)
css::uno::Reference< css::frame::XDispatchProvider > xThis(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY_THROW);
// We need a full copy of all currently registered interceptor objects.
// Otherwhise we cant iterate over this vector without the risk, that our iterator will be invalid.
// Because this vetor will be influenced by every deregistered interceptor.
InterceptionHelper::InterceptorList aCopy = m_lInterceptionRegs;
aReadLock.unlock();
// <- SAFE
InterceptionHelper::InterceptorList::iterator pIt;
for ( pIt = aCopy.begin();
pIt != aCopy.end() ;
++pIt )
{
InterceptionHelper::InterceptorInfo& rInfo = *pIt;
if (rInfo.xInterceptor.is())
{
css::uno::Reference< css::frame::XDispatchProviderInterceptor > xInterceptor(rInfo.xInterceptor, css::uno::UNO_QUERY_THROW);
releaseDispatchProviderInterceptor(xInterceptor);
rInfo.xInterceptor.clear();
}
}
aCopy.clear();
#if OSL_DEBUG_LEVEL > 0
// SAFE ->
aReadLock.lock();
if (m_lInterceptionRegs.size() > 0)
OSL_ENSURE(sal_False, "There are some pending interceptor objects, which seams to be registered during (!) the destruction of a frame.");
aReadLock.unlock();
// <- SAFE
#endif // ODL_DEBUG_LEVEL>0
#endif // FORCE_DESTRUCTION_OF_INTERCEPTION_CHAIN
}
} // namespace framework
<commit_msg>INTEGRATION: CWS pchfix02 (1.4.70); FILE MERGED 2006/09/01 17:29:07 kaib 1.4.70.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: interceptionhelper.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-16 13:54:33 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
//_______________________________________________
// my own includes
#ifndef __FRAMEWORK_DISPATCH_INTERCEPTIONHELPER_HXX_
#include <dispatch/interceptionhelper.hxx>
#endif
//_______________________________________________
// interface includes
#ifndef _COM_SUN_STAR_FRAME_XINTERCEPTORINFO_HPP_
#include <com/sun/star/frame/XInterceptorInfo.hpp>
#endif
//_______________________________________________
// includes of other projects
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
//_______________________________________________
// namespace
namespace framework{
//_______________________________________________
// non exported const
sal_Bool InterceptionHelper::m_bPreferrFirstInterceptor = sal_True;
//_______________________________________________
// non exported definitions
//_______________________________________________
// declarations
/*-----------------------------------------------------------------------------
31.03.2003 09:02
-----------------------------------------------------------------------------*/
DEFINE_XINTERFACE_3(InterceptionHelper ,
OWeakObject ,
DIRECT_INTERFACE(css::frame::XDispatchProvider ),
DIRECT_INTERFACE(css::frame::XDispatchProviderInterception),
DIRECT_INTERFACE(css::lang::XEventListener ))
/*-----------------------------------------------------------------------------
31.03.2003 09:02
-----------------------------------------------------------------------------*/
InterceptionHelper::InterceptionHelper(const css::uno::Reference< css::frame::XFrame >& xOwner,
const css::uno::Reference< css::frame::XDispatchProvider >& xSlave)
// Init baseclasses first
: ThreadHelpBase(&Application::GetSolarMutex())
, OWeakObject ( )
// Init member
, m_xOwnerWeak (xOwner )
, m_xSlave (xSlave )
{
}
/*-----------------------------------------------------------------------------
31.03.2003 09:02
-----------------------------------------------------------------------------*/
InterceptionHelper::~InterceptionHelper()
{
}
/*-----------------------------------------------------------------------------
31.03.2003 09:09
-----------------------------------------------------------------------------*/
css::uno::Reference< css::frame::XDispatch > SAL_CALL InterceptionHelper::queryDispatch(const css::util::URL& aURL ,
const ::rtl::OUString& sTargetFrameName,
sal_Int32 nSearchFlags )
throw(css::uno::RuntimeException)
{
// SAFE {
ReadGuard aReadLock(m_aLock);
// a) first search an interceptor, which match to this URL by it's URL pattern registration
// Note: if it return NULL - it does not mean an empty interceptor list automaticly!
css::uno::Reference< css::frame::XDispatchProvider > xInterceptor;
InterceptorList::const_iterator pIt = m_lInterceptionRegs.findByPattern(aURL.Complete);
if (pIt != m_lInterceptionRegs.end())
xInterceptor = pIt->xInterceptor;
// b) No match by registration - but a valid interceptor list.
// Use first interceptor everytimes.
// Note: it doesn't matter, which direction this helper implementation use to ask interceptor objects.
// Using of member m_aInterceptorList will starts at the beginning everytimes.
// It depends from the filling operation, in which direction it works realy!
if (!xInterceptor.is() && m_lInterceptionRegs.size()>0)
{
pIt = m_lInterceptionRegs.begin();
xInterceptor = pIt->xInterceptor;
}
// c) No registered interceptor => use our direct slave.
// This helper exist by design and must be valid everytimes ...
// But to be more feature proof - we should check that .-)
if (!xInterceptor.is() && m_xSlave.is())
xInterceptor = m_xSlave;
aReadLock.unlock();
// } SAFE
css::uno::Reference< css::frame::XDispatch > xReturn;
if (xInterceptor.is())
xReturn = xInterceptor->queryDispatch(aURL, sTargetFrameName, nSearchFlags);
return xReturn;
}
/*-----------------------------------------------------------------------------
31.03.2003 07:58
-----------------------------------------------------------------------------*/
css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL InterceptionHelper::queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptor )
throw(css::uno::RuntimeException)
{
sal_Int32 c = lDescriptor.getLength();
css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > lDispatches (c);
css::uno::Reference< css::frame::XDispatch >* pDispatches = lDispatches.getArray();
const css::frame::DispatchDescriptor* pDescriptor = lDescriptor.getConstArray();
for (sal_Int32 i=0; i<c; ++i)
pDispatches[i] = queryDispatch(pDescriptor[i].FeatureURL, pDescriptor[i].FrameName, pDescriptor[i].SearchFlags);
return lDispatches;
}
/*-----------------------------------------------------------------------------
31.03.2003 10:20
-----------------------------------------------------------------------------*/
void SAL_CALL InterceptionHelper::registerDispatchProviderInterceptor(const css::uno::Reference< css::frame::XDispatchProviderInterceptor >& xInterceptor)
throw(css::uno::RuntimeException)
{
// reject wrong calling of this interface method
css::uno::Reference< css::frame::XDispatchProvider > xThis(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY);
if (!xInterceptor.is())
throw css::uno::RuntimeException(DECLARE_ASCII("NULL references not allowed as in parameter"), xThis);
// Fill a new info structure for new interceptor.
// Save his reference and try to get an additional URL/pattern list from him.
// If no list exist register these interceptor for all dispatch events with "*"!
InterceptorInfo aInfo;
aInfo.xInterceptor = css::uno::Reference< css::frame::XDispatchProvider >(xInterceptor, css::uno::UNO_QUERY);
css::uno::Reference< css::frame::XInterceptorInfo > xInfo(xInterceptor, css::uno::UNO_QUERY);
if (xInfo.is())
aInfo.lURLPattern = xInfo->getInterceptedURLs();
else
{
aInfo.lURLPattern.realloc(1);
aInfo.lURLPattern[0] = ::rtl::OUString::createFromAscii("*");
}
// SAFE {
WriteGuard aWriteLock(m_aLock);
// a) no interceptor at all - set this instance as master for given interceptor
// and set our slave as it's slave - and put this interceptor to the list.
// It's place there doesn matter. Because this list is currently empty.
if (m_lInterceptionRegs.size()<1)
{
xInterceptor->setMasterDispatchProvider(xThis );
xInterceptor->setSlaveDispatchProvider (m_xSlave);
m_lInterceptionRegs.push_back(aInfo);
}
// b) OK - there is at least one interceptor already registered.
// It's slave and it's master must be valid references ...
// because we created it. But we have to look for the static bool which
// regulate direction of using of interceptor objects!
// b1) If "m_bPreferrFirstInterceptor" is set to true, we have to
// insert it behind any other existing interceptor - means at the end of our list.
else if (m_bPreferrFirstInterceptor)
{
css::uno::Reference< css::frame::XDispatchProvider > xMasterD = m_lInterceptionRegs.rbegin()->xInterceptor;
css::uno::Reference< css::frame::XDispatchProviderInterceptor > xMasterI (xMasterD, css::uno::UNO_QUERY);
xInterceptor->setMasterDispatchProvider(xMasterD );
xInterceptor->setSlaveDispatchProvider (m_xSlave );
xMasterI->setSlaveDispatchProvider (aInfo.xInterceptor);
m_lInterceptionRegs.push_back(aInfo);
}
// b2) If "m_bPreferrFirstInterceptor" is set to false, we have to
// insert it before any other existing interceptor - means at the beginning of our list.
else
{
css::uno::Reference< css::frame::XDispatchProvider > xSlaveD = m_lInterceptionRegs.begin()->xInterceptor;
css::uno::Reference< css::frame::XDispatchProviderInterceptor > xSlaveI (xSlaveD , css::uno::UNO_QUERY);
xInterceptor->setMasterDispatchProvider(xThis );
xInterceptor->setSlaveDispatchProvider (xSlaveD );
xSlaveI->setMasterDispatchProvider (aInfo.xInterceptor);
m_lInterceptionRegs.push_front(aInfo);
}
css::uno::Reference< css::frame::XFrame > xOwner(m_xOwnerWeak.get(), css::uno::UNO_QUERY);
aWriteLock.unlock();
// } SAFE
// Don't forget to send a frame action event "context changed".
// Any cached dispatch objects must be validated now!
if (xOwner.is())
xOwner->contextChanged();
}
/*-----------------------------------------------------------------------------
31.03.2003 10:27
-----------------------------------------------------------------------------*/
void SAL_CALL InterceptionHelper::releaseDispatchProviderInterceptor(const css::uno::Reference< css::frame::XDispatchProviderInterceptor >& xInterceptor)
throw(css::uno::RuntimeException)
{
// reject wrong calling of this interface method
css::uno::Reference< css::frame::XDispatchProvider > xThis(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY);
if (!xInterceptor.is())
throw css::uno::RuntimeException(DECLARE_ASCII("NULL references not allowed as in parameter"), xThis);
// SAFE {
WriteGuard aWriteLock(m_aLock);
// search this interceptor ...
// If it could be located inside cache -
// use it's slave/master relations to update the interception list;
// set empty references for it as new master and slave;
// and relase it from out cache.
InterceptorList::iterator pIt = m_lInterceptionRegs.findByReference(xInterceptor);
if (pIt != m_lInterceptionRegs.end())
{
css::uno::Reference< css::frame::XDispatchProvider > xSlaveD (xInterceptor->getSlaveDispatchProvider() , css::uno::UNO_QUERY);
css::uno::Reference< css::frame::XDispatchProvider > xMasterD (xInterceptor->getMasterDispatchProvider(), css::uno::UNO_QUERY);
css::uno::Reference< css::frame::XDispatchProviderInterceptor > xSlaveI (xSlaveD , css::uno::UNO_QUERY);
css::uno::Reference< css::frame::XDispatchProviderInterceptor > xMasterI (xMasterD , css::uno::UNO_QUERY);
if (xMasterI.is())
xMasterI->setSlaveDispatchProvider(xSlaveD);
if (xSlaveI.is())
xSlaveI->setMasterDispatchProvider(xMasterD);
xInterceptor->setSlaveDispatchProvider (css::uno::Reference< css::frame::XDispatchProvider >());
xInterceptor->setMasterDispatchProvider(css::uno::Reference< css::frame::XDispatchProvider >());
m_lInterceptionRegs.erase(pIt);
}
css::uno::Reference< css::frame::XFrame > xOwner(m_xOwnerWeak.get(), css::uno::UNO_QUERY);
aWriteLock.unlock();
// } SAFE
// Don't forget to send a frame action event "context changed".
// Any cached dispatch objects must be validated now!
if (xOwner.is())
xOwner->contextChanged();
}
/*-----------------------------------------------------------------------------
31.03.2003 10:31
-----------------------------------------------------------------------------*/
#define FORCE_DESTRUCTION_OF_INTERCEPTION_CHAIN
void SAL_CALL InterceptionHelper::disposing(const css::lang::EventObject& aEvent)
throw(css::uno::RuntimeException)
{
#ifdef FORCE_DESTRUCTION_OF_INTERCEPTION_CHAIN
// SAFE ->
ReadGuard aReadLock(m_aLock);
// check calli ... we accept such disposing call's only from our onwer frame.
css::uno::Reference< css::frame::XFrame > xOwner(m_xOwnerWeak.get(), css::uno::UNO_QUERY);
if (aEvent.Source != xOwner)
return;
// Because every interceptor hold at least one reference to us ... and we destruct this list
// of interception objects ... we should hold ourself alive .-)
css::uno::Reference< css::frame::XDispatchProvider > xThis(static_cast< ::cppu::OWeakObject* >(this), css::uno::UNO_QUERY_THROW);
// We need a full copy of all currently registered interceptor objects.
// Otherwhise we cant iterate over this vector without the risk, that our iterator will be invalid.
// Because this vetor will be influenced by every deregistered interceptor.
InterceptionHelper::InterceptorList aCopy = m_lInterceptionRegs;
aReadLock.unlock();
// <- SAFE
InterceptionHelper::InterceptorList::iterator pIt;
for ( pIt = aCopy.begin();
pIt != aCopy.end() ;
++pIt )
{
InterceptionHelper::InterceptorInfo& rInfo = *pIt;
if (rInfo.xInterceptor.is())
{
css::uno::Reference< css::frame::XDispatchProviderInterceptor > xInterceptor(rInfo.xInterceptor, css::uno::UNO_QUERY_THROW);
releaseDispatchProviderInterceptor(xInterceptor);
rInfo.xInterceptor.clear();
}
}
aCopy.clear();
#if OSL_DEBUG_LEVEL > 0
// SAFE ->
aReadLock.lock();
if (m_lInterceptionRegs.size() > 0)
OSL_ENSURE(sal_False, "There are some pending interceptor objects, which seams to be registered during (!) the destruction of a frame.");
aReadLock.unlock();
// <- SAFE
#endif // ODL_DEBUG_LEVEL>0
#endif // FORCE_DESTRUCTION_OF_INTERCEPTION_CHAIN
}
} // namespace framework
<|endoftext|> |
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "rdb_protocol/lazy_json.hpp"
#include "containers/archive/buffer_group_stream.hpp"
#include "containers/archive/versioned.hpp"
#include "rdb_protocol/blob_wrapper.hpp"
counted_t<const ql::datum_t> get_data(const rdb_value_t *value, buf_parent_t parent) {
// RSI: Just use deserialize_from_blob?
rdb_blob_wrapper_t blob(parent.cache()->max_block_size(),
const_cast<rdb_value_t *>(value)->value_ref(),
blob::btree_maxreflen);
counted_t<const ql::datum_t> data;
blob_acq_t acq_group;
buffer_group_t buffer_group;
blob.expose_all(parent, access_t::read, &buffer_group, &acq_group);
buffer_group_read_stream_t read_stream(const_view(&buffer_group));
// RSI: ONLY_VERSION here.
archive_result_t res = deserialize_for_version(cluster_version_t::ONLY_VERSION,
&read_stream, &data);
guarantee_deserialization(res, "rdb value");
return data;
}
const counted_t<const ql::datum_t> &lazy_json_t::get() const {
guarantee(pointee.has());
if (!pointee->ptr.has()) {
pointee->ptr = get_data(pointee->rdb_value, pointee->parent);
pointee->rdb_value = NULL;
pointee->parent = buf_parent_t();
}
return pointee->ptr;
}
bool lazy_json_t::references_parent() const {
return pointee.has() && !pointee->parent.empty();
}
void lazy_json_t::reset() {
pointee.reset();
}
<commit_msg>Removed some RSIs.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "rdb_protocol/lazy_json.hpp"
#include "containers/archive/buffer_group_stream.hpp"
#include "containers/archive/versioned.hpp"
#include "rdb_protocol/blob_wrapper.hpp"
counted_t<const ql::datum_t> get_data(const rdb_value_t *value, buf_parent_t parent) {
// TODO: Just use deserialize_from_blob?
rdb_blob_wrapper_t blob(parent.cache()->max_block_size(),
const_cast<rdb_value_t *>(value)->value_ref(),
blob::btree_maxreflen);
counted_t<const ql::datum_t> data;
blob_acq_t acq_group;
buffer_group_t buffer_group;
blob.expose_all(parent, access_t::read, &buffer_group, &acq_group);
buffer_group_read_stream_t read_stream(const_view(&buffer_group));
archive_result_t res
= deserialize<cluster_version_t::ONLY_VERSION>(&read_stream, &data);
guarantee_deserialization(res, "rdb value");
return data;
}
const counted_t<const ql::datum_t> &lazy_json_t::get() const {
guarantee(pointee.has());
if (!pointee->ptr.has()) {
pointee->ptr = get_data(pointee->rdb_value, pointee->parent);
pointee->rdb_value = NULL;
pointee->parent = buf_parent_t();
}
return pointee->ptr;
}
bool lazy_json_t::references_parent() const {
return pointee.has() && !pointee->parent.empty();
}
void lazy_json_t::reset() {
pointee.reset();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <vector>
using namespace std;
//util classes
struct Input {
int r, c, l, h;
vector<vector<bool>> tomatoes;
};
struct Slice {
int r1, c1, r2, c2;
};
struct Output {
vector<Slice> slices;
};
bool checkSliceHorizontal(Input &input, Slice &s)
{
bool t = false;
bool f = false;
for (int j = s.c1; j <= s.c2; j++)
{
if (input.tomatoes[s.r1][j])
t = true;
else
f = true;
if (t == true && f == true)
return true;
}
return false;
}
bool checkSliceVertical(Input &input, Slice &s)
{
bool t = false;
bool f = false;
for (int i = s.r1; i <= s.r2; i++)
{
if (input.tomatoes[i][s.c1])
t = true;
else
f = true;
if (t == true && f == true)
return true;
}
return false;
}
void solveSimpleHorizontal(Input& input, Output& output) {
for (int i = 0; i < input.r; i++)
{
for (int j = 0; j < input.c; j += input.h)
{
Slice s;
s.r1 = i;
s.c1 = j;
s.r2 = i;
s.c2 = min(j+input.h-1, input.c-1);
if (checkSliceHorizontal(input, s))
output.slices.push_back(s);
}
}
}
void solveSimpleVertical(Input& input, Output& output) {
for (int j = 0; j < input.c; j++)
{
for (int i = 0; i < input.r; i += input.h)
{
Slice s;
s.r1 = i;
s.c1 = j;
s.r2 = min(i+input.h-1, input.r-1);
s.c2 = j;
if (checkSliceVertical(input, s))
output.slices.push_back(s);
}
}
}
int add_slice(const vector<bool> &a, int l, int r, int cnt_min) {
int cnt1 = 0, cnt2 = 0;
for (int i = l; i <= r; i++)
if (a[i])
cnt1++;
else
cnt2++;
if (cnt1 >= cnt_min && cnt2 >= cnt_min)
return r-l+1;
return 0;
}
void solve_row(const vector<bool> &a, int row_num, int n, int l, int h, vector<Slice> &ans) {
vector<int> d(n,0), prev(n,0);
for (int i = 0; i < n; i++)
for (int j = 2*l; j <= h; j++)
if (i-j+1 >= 0)
{
int temp = add_slice(a,i-j+1,i,l);
int prev_res = (i-j >= 0 ? d[i-j] : 0);
if (d[i] < prev_res + temp)
{
d[i] = prev_res + temp;
prev[i] = i-j+1;
}
}
//for (int i = 0; i < n; i++)
// cerr << d[i] << ' ' << prev[i] << endl;;
//cerr << endl;
int i_max = 0;
for (int i = 0; i < n; i++)
if (d[i] > d[i_max])
i_max = i;
Slice c;
c.r1 = c.r2 = row_num;
for (int i = i_max; i > 0;)
{
c.c1 = prev[i]; c.c2 = i;
i = prev[i]-1;
ans.push_back(c);
}
}
void solveDP(Input& input, Output& output) {
for (int i = 0; i < input.r; i++)
solve_row(input.tomatoes[i],i,input.c,input.l,input.h,output.slices);
}
//input/output code
int main(int argc, char* argv[]) {
ios::sync_with_stdio(false);
//read input
Input input;
cin >> input.r >> input.c >> input.l >> input.h;
for(int i = 0; i < input.r; i++) {
vector<bool> row(input.c);
for(int j = 0; j < input.c; j++) {
char cell;
cin >> cell;
row[j] = cell == 'T';
}
input.tomatoes.push_back(row);
//TODO do we read line breaks?
}
//read command line args
string algorithm = "simplehorizontal";
if(argc > 2) {
algorithm = argv[1];
}
//solve problem
Output output;
cerr << "using algorithm " << algorithm << endl;
if(algorithm == "simplehorizontal") {
solveSimpleHorizontal(input, output);
}
else if(algorithm == "simplevertical") {
solveSimpleVertical(input, output);
}
else if(algorithm == "dp") {
solveDP(input, output);
}
else {
cerr << "unknown algorithm" << endl;
return 1;
}
//print output
cout << output.slices.size() << endl;
int area = 0;
for(Slice slice: output.slices) {
area += (slice.r2 - slice.r1 + 1) * (slice.c2 - slice.c1 + 1);
cout << slice.r1 << ' ' << slice.c1 << ' ' << slice.r2 << ' ' << slice.c2 << endl;
}
cerr << area << endl;
};
<commit_msg>fix argument parsing<commit_after>#include <iostream>
#include <string>
#include <vector>
using namespace std;
//util classes
struct Input {
int r, c, l, h;
vector<vector<bool>> tomatoes;
};
struct Slice {
int r1, c1, r2, c2;
};
struct Output {
vector<Slice> slices;
};
bool checkSliceHorizontal(Input &input, Slice &s)
{
bool t = false;
bool f = false;
for (int j = s.c1; j <= s.c2; j++)
{
if (input.tomatoes[s.r1][j])
t = true;
else
f = true;
if (t == true && f == true)
return true;
}
return false;
}
bool checkSliceVertical(Input &input, Slice &s)
{
bool t = false;
bool f = false;
for (int i = s.r1; i <= s.r2; i++)
{
if (input.tomatoes[i][s.c1])
t = true;
else
f = true;
if (t == true && f == true)
return true;
}
return false;
}
void solveSimpleHorizontal(Input& input, Output& output) {
for (int i = 0; i < input.r; i++)
{
for (int j = 0; j < input.c; j += input.h)
{
Slice s;
s.r1 = i;
s.c1 = j;
s.r2 = i;
s.c2 = min(j+input.h-1, input.c-1);
if (checkSliceHorizontal(input, s))
output.slices.push_back(s);
}
}
}
void solveSimpleVertical(Input& input, Output& output) {
for (int j = 0; j < input.c; j++)
{
for (int i = 0; i < input.r; i += input.h)
{
Slice s;
s.r1 = i;
s.c1 = j;
s.r2 = min(i+input.h-1, input.r-1);
s.c2 = j;
if (checkSliceVertical(input, s))
output.slices.push_back(s);
}
}
}
int add_slice(const vector<bool> &a, int l, int r, int cnt_min) {
int cnt1 = 0, cnt2 = 0;
for (int i = l; i <= r; i++)
if (a[i])
cnt1++;
else
cnt2++;
if (cnt1 >= cnt_min && cnt2 >= cnt_min)
return r-l+1;
return 0;
}
void solve_row(const vector<bool> &a, int row_num, int n, int l, int h, vector<Slice> &ans) {
vector<int> d(n,0), prev(n,0);
for (int i = 0; i < n; i++)
for (int j = 2*l; j <= h; j++)
if (i-j+1 >= 0)
{
int temp = add_slice(a,i-j+1,i,l);
int prev_res = (i-j >= 0 ? d[i-j] : 0);
if (d[i] < prev_res + temp)
{
d[i] = prev_res + temp;
prev[i] = i-j+1;
}
}
//for (int i = 0; i < n; i++)
// cerr << d[i] << ' ' << prev[i] << endl;;
//cerr << endl;
int i_max = 0;
for (int i = 0; i < n; i++)
if (d[i] > d[i_max])
i_max = i;
Slice c;
c.r1 = c.r2 = row_num;
for (int i = i_max; i > 0;)
{
c.c1 = prev[i]; c.c2 = i;
i = prev[i]-1;
ans.push_back(c);
}
}
void solveDP(Input& input, Output& output) {
for (int i = 0; i < input.r; i++)
solve_row(input.tomatoes[i],i,input.c,input.l,input.h,output.slices);
}
//input/output code
int main(int argc, char* argv[]) {
ios::sync_with_stdio(false);
//read input
Input input;
cin >> input.r >> input.c >> input.l >> input.h;
for(int i = 0; i < input.r; i++) {
vector<bool> row(input.c);
for(int j = 0; j < input.c; j++) {
char cell;
cin >> cell;
row[j] = cell == 'T';
}
input.tomatoes.push_back(row);
//TODO do we read line breaks?
}
//read command line args
string algorithm = "simplehorizontal";
if(argc > 1) {
algorithm = argv[1];
}
//solve problem
Output output;
cerr << "using algorithm " << algorithm << endl;
if(algorithm == "simplehorizontal") {
solveSimpleHorizontal(input, output);
}
else if(algorithm == "simplevertical") {
solveSimpleVertical(input, output);
}
else if(algorithm == "dp") {
solveDP(input, output);
}
else {
cerr << "unknown algorithm" << endl;
return 1;
}
//print output
cout << output.slices.size() << endl;
int area = 0;
for(Slice slice: output.slices) {
area += (slice.r2 - slice.r1 + 1) * (slice.c2 - slice.c1 + 1);
cout << slice.r1 << ' ' << slice.c1 << ' ' << slice.r2 << ' ' << slice.c2 << endl;
}
cerr << area << endl;
};
<|endoftext|> |
<commit_before>#include "logging.hpp"
#include <android/log.h>
#include <cassert>
#include "../../../../../base/assert.hpp"
#include "../../../../../base/logging.hpp"
#include "../../../../../base/exception.hpp"
namespace jni
{
using namespace my;
void AndroidLogMessage(LogLevel l, SrcPoint const & src, string const & s)
{
android_LogPriority pr = ANDROID_LOG_SILENT;
switch (l)
{
case LINFO: pr = ANDROID_LOG_INFO; break;
case LDEBUG: pr = ANDROID_LOG_DEBUG; break;
case LWARNING: pr = ANDROID_LOG_WARN; break;
case LERROR: pr = ANDROID_LOG_ERROR; break;
case LCRITICAL: pr = ANDROID_LOG_FATAL; break;
}
string const out = DebugPrint(src) + " " + s;
__android_log_print(pr, "MapsWithMe_JNI", out.c_str());
}
void AndroidAssertMessage(SrcPoint const & src, string const & s)
{
AndroidLogMessage(LERROR, src, s);
#ifdef DEBUG
assert(false);
#else
MYTHROW(RootException, (s));
#endif
}
void InitSystemLog()
{
SetLogMessageFn(&AndroidLogMessage);
}
void InitAssertLog()
{
SetAssertFunction(&AndroidAssertMessage);
}
}
<commit_msg>[android] Fixed insecure and slow call to log<commit_after>#include "logging.hpp"
#include <android/log.h>
#include <cassert>
#include "../../../../../base/assert.hpp"
#include "../../../../../base/logging.hpp"
#include "../../../../../base/exception.hpp"
namespace jni
{
using namespace my;
void AndroidLogMessage(LogLevel l, SrcPoint const & src, string const & s)
{
android_LogPriority pr = ANDROID_LOG_SILENT;
switch (l)
{
case LINFO: pr = ANDROID_LOG_INFO; break;
case LDEBUG: pr = ANDROID_LOG_DEBUG; break;
case LWARNING: pr = ANDROID_LOG_WARN; break;
case LERROR: pr = ANDROID_LOG_ERROR; break;
case LCRITICAL: pr = ANDROID_LOG_FATAL; break;
}
string const out = DebugPrint(src) + " " + s;
__android_log_write(pr, "MapsWithMe_JNI", out.c_str());
}
void AndroidAssertMessage(SrcPoint const & src, string const & s)
{
AndroidLogMessage(LERROR, src, s);
#ifdef DEBUG
assert(false);
#else
MYTHROW(RootException, (s));
#endif
}
void InitSystemLog()
{
SetLogMessageFn(&AndroidLogMessage);
}
void InitAssertLog()
{
SetAssertFunction(&AndroidAssertMessage);
}
}
<|endoftext|> |
<commit_before>/**
* Appcelerator Titanium Mobile
* Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#include <jni.h>
#include <stdio.h>
#include <string.h>
#include <v8.h>
#include <v8-debug.h>
#include "AndroidUtil.h"
#include "EventEmitter.h"
#include "JavaObject.h"
#include "JNIUtil.h"
#include "JSException.h"
#include "KrollBindings.h"
#include "ProxyFactory.h"
#include "ScriptsModule.h"
#include "TypeConverter.h"
#include "V8Util.h"
#include "V8Runtime.h"
#include "org_appcelerator_kroll_runtime_v8_V8Runtime.h"
#define TAG "V8Runtime"
// The port number on which the V8 debugger will listen on.
#define V8_DEBUGGER_PORT 9999
namespace titanium {
Persistent<Context> V8Runtime::globalContext;
Persistent<Object> V8Runtime::krollGlobalObject;
Persistent<Array> V8Runtime::moduleContexts;
jobject V8Runtime::javaInstance;
bool V8Runtime::debuggerEnabled = false;
bool V8Runtime::DBG = false;
/* static */
void V8Runtime::collectWeakRef(Persistent<Value> ref, void *parameter)
{
jobject v8Object = (jobject) parameter;
ref.Dispose();
JNIScope::getEnv()->DeleteGlobalRef(v8Object);
}
// Minimalistic logging function for internal JS
static Handle<Value> krollLog(const Arguments& args)
{
HandleScope scope;
uint32_t len = args.Length();
if (len < 2) {
return JSException::Error("log: missing required tag and message arguments");
}
Handle<String> tag = args[0]->ToString();
Handle<String> message = args[1]->ToString();
for (uint32_t i = 2; i < len; ++i) {
message = String::Concat(String::Concat(message, String::New(" ")), args[i]->ToString());
}
String::Utf8Value tagValue(tag);
String::Utf8Value messageValue(message);
__android_log_print(ANDROID_LOG_DEBUG, *tagValue, *messageValue);
return Undefined();
}
/* static */
void V8Runtime::bootstrap(Local<Object> global)
{
EventEmitter::initTemplate();
krollGlobalObject = Persistent<Object>::New(Object::New());
moduleContexts = Persistent<Array>::New(Array::New());
KrollBindings::initFunctions(krollGlobalObject);
DEFINE_METHOD(krollGlobalObject, "log", krollLog);
DEFINE_TEMPLATE(krollGlobalObject, "EventEmitter", EventEmitter::constructorTemplate);
krollGlobalObject->Set(String::NewSymbol("runtime"), String::New("v8"));
krollGlobalObject->Set(String::NewSymbol("DBG"), v8::Boolean::New(V8Runtime::DBG));
krollGlobalObject->Set(String::NewSymbol("moduleContexts"), moduleContexts);
LOG_TIMER(TAG, "Executing kroll.js");
TryCatch tryCatch;
Handle<Value> result = V8Util::executeString(KrollBindings::getMainSource(), String::New("ti:/kroll.js"));
if (tryCatch.HasCaught()) {
V8Util::reportException(tryCatch, true);
}
if (!result->IsFunction()) {
LOGF(TAG, "kroll.js result is not a function");
V8Util::reportException(tryCatch, true);
}
Handle<Function> mainFunction = Handle<Function>::Cast(result);
Local<Value> args[] = { Local<Value>::New(krollGlobalObject) };
mainFunction->Call(global, 1, args);
if (tryCatch.HasCaught()) {
V8Util::reportException(tryCatch, true);
LOGE(TAG, "Caught exception while bootstrapping Kroll");
}
}
static void logV8Exception(Handle<Message> msg, Handle<Value> data)
{
HandleScope scope;
// Log reason and location of the error.
LOGD(TAG, *String::Utf8Value(msg->Get()));
LOGD(TAG, "%s @ %d >>> %s",
*String::Utf8Value(msg->GetScriptResourceName()),
msg->GetLineNumber(),
*String::Utf8Value(msg->GetSourceLine()));
}
static jmethodID dispatchDebugMessage = NULL;
static void dispatchHandler()
{
static JNIEnv *env = NULL;
if (!env) {
titanium::JNIUtil::javaVm->AttachCurrentThread(&env, NULL);
}
env->CallVoidMethod(V8Runtime::javaInstance, dispatchDebugMessage);
}
} // namespace titanium
#ifdef __cplusplus
extern "C" {
#endif
using namespace titanium;
/*
* Class: org_appcelerator_kroll_runtime_v8_V8Runtime
* Method: nativeInit
* Signature: (Lorg/appcelerator/kroll/runtime/v8/V8Runtime;)J
*/
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeInit(JNIEnv *env, jobject self, jboolean useGlobalRefs, jint debuggerPort, jboolean DBG)
{
HandleScope scope;
titanium::JNIScope jniScope(env);
// Log all uncaught V8 exceptions.
V8::AddMessageListener(logV8Exception);
V8::SetCaptureStackTraceForUncaughtExceptions(true);
JavaObject::useGlobalRefs = useGlobalRefs;
V8Runtime::debuggerEnabled = debuggerPort >= 0;
V8Runtime::DBG = DBG;
V8Runtime::javaInstance = env->NewGlobalRef(self);
JNIUtil::initCache();
Persistent<Context> context = Persistent<Context>::New(Context::New());
context->Enter();
V8Runtime::globalContext = context;
V8Runtime::bootstrap(context->Global());
if (V8Runtime::debuggerEnabled) {
jclass v8RuntimeClass = env->FindClass("org/appcelerator/kroll/runtime/v8/V8Runtime");
dispatchDebugMessage = env->GetMethodID(v8RuntimeClass, "dispatchDebugMessages", "()V");
Debug::SetDebugMessageDispatchHandler(dispatchHandler);
Debug::EnableAgent("titanium", debuggerPort, true);
}
LOG_HEAP_STATS(TAG);
}
static Persistent<Object> moduleObject;
static Persistent<Function> runModuleFunction;
/*
* Class: org_appcelerator_kroll_runtime_v8_V8Runtime
* Method: nativeRunModule
* Signature: (Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeRunModule
(JNIEnv *env, jobject self, jstring source, jstring filename, jobject activityProxy)
{
ENTER_V8(V8Runtime::globalContext);
titanium::JNIScope jniScope(env);
if (moduleObject.IsEmpty()) {
moduleObject = Persistent<Object>::New(
V8Runtime::krollGlobalObject->Get(String::New("Module"))->ToObject());
runModuleFunction = Persistent<Function>::New(
Handle<Function>::Cast(moduleObject->Get(String::New("runModule"))));
}
Handle<Value> jsSource = TypeConverter::javaStringToJsString(source);
Handle<Value> jsFilename = TypeConverter::javaStringToJsString(filename);
Handle<Value> jsActivity = TypeConverter::javaObjectToJsValue(activityProxy);
Handle<Value> args[] = { jsSource, jsFilename, jsActivity };
TryCatch tryCatch;
runModuleFunction->Call(moduleObject, 3, args);
if (tryCatch.HasCaught()) {
V8Util::openJSErrorDialog(tryCatch);
V8Util::reportException(tryCatch, true);
}
}
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeProcessDebugMessages(JNIEnv *env, jobject self)
{
v8::Debug::ProcessDebugMessages();
}
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeIdle(JNIEnv *env, jobject self)
{
v8::V8::IdleNotification();
}
// This method disposes of all native resources used by V8 when
// all activities have been destroyed by the application.
//
// When a Persistent handle is Dispose()'d in V8, the internal
// pointer is not changed, handle->IsEmpty() returns false.
// As a consequence, we have to explicitly reset the handle
// to an empty handle using Persistent<Type>()
//
// Since we use lazy initialization in a lot of our code,
// there's probably not an easier way (unless we use boolean flags)
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeDispose(JNIEnv *env, jobject runtime)
{
JNIScope jniScope(env);
// We use a new scope here so any new handles we create
// while disposing are cleaned up before our global context
// is disposed below.
{
HandleScope scope;
// Any module that has been require()'d or opened via Window URL
// will be cleaned up here. We setup the initial "moduleContexts"
// Array and expose it on kroll above in nativeInit, and
// module.js will insert module contexts into this array in
// Module.prototype._runScript
uint32_t length = V8Runtime::moduleContexts->Length();
for (uint32_t i = 0; i < length; ++i) {
Handle<Value> moduleContext = V8Runtime::moduleContexts->Get(i);
// WrappedContext is simply a C++ wrapper for the V8 Context object,
// and is used to expose the Context to javascript. See ScriptsModule for
// implementation details
WrappedContext *wrappedContext = NativeObject::Unwrap<WrappedContext>(moduleContext->ToObject());
// Detach each context's global object, and dispose the context
wrappedContext->GetV8Context()->DetachGlobal();
wrappedContext->GetV8Context().Dispose();
}
// KrollBindings
KrollBindings::dispose();
EventEmitter::dispose();
V8Runtime::moduleContexts.Dispose();
V8Runtime::moduleContexts = Persistent<Array>();
V8Runtime::globalContext->DetachGlobal();
}
// Dispose of each class' static cache / resources
V8Util::dispose();
ProxyFactory::dispose();
moduleObject.Dispose();
moduleObject = Persistent<Object>();
runModuleFunction.Dispose();
runModuleFunction = Persistent<Function>();
V8Runtime::krollGlobalObject.Dispose();
V8Runtime::globalContext->Exit();
V8Runtime::globalContext.Dispose();
// Removes the retained global reference to the V8Runtime
env->DeleteGlobalRef(V8Runtime::javaInstance);
V8Runtime::javaInstance = NULL;
}
jint JNI_OnLoad(JavaVM *vm, void *reserved)
{
JNIUtil::javaVm = vm;
return JNI_VERSION_1_4;
}
#ifdef __cplusplus
}
#endif
<commit_msg>Use WrappedContext::Unwrap to get a valid pointer.<commit_after>/**
* Appcelerator Titanium Mobile
* Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#include <jni.h>
#include <stdio.h>
#include <string.h>
#include <v8.h>
#include <v8-debug.h>
#include "AndroidUtil.h"
#include "EventEmitter.h"
#include "JavaObject.h"
#include "JNIUtil.h"
#include "JSException.h"
#include "KrollBindings.h"
#include "ProxyFactory.h"
#include "ScriptsModule.h"
#include "TypeConverter.h"
#include "V8Util.h"
#include "V8Runtime.h"
#include "org_appcelerator_kroll_runtime_v8_V8Runtime.h"
#define TAG "V8Runtime"
// The port number on which the V8 debugger will listen on.
#define V8_DEBUGGER_PORT 9999
namespace titanium {
Persistent<Context> V8Runtime::globalContext;
Persistent<Object> V8Runtime::krollGlobalObject;
Persistent<Array> V8Runtime::moduleContexts;
jobject V8Runtime::javaInstance;
bool V8Runtime::debuggerEnabled = false;
bool V8Runtime::DBG = false;
/* static */
void V8Runtime::collectWeakRef(Persistent<Value> ref, void *parameter)
{
jobject v8Object = (jobject) parameter;
ref.Dispose();
JNIScope::getEnv()->DeleteGlobalRef(v8Object);
}
// Minimalistic logging function for internal JS
static Handle<Value> krollLog(const Arguments& args)
{
HandleScope scope;
uint32_t len = args.Length();
if (len < 2) {
return JSException::Error("log: missing required tag and message arguments");
}
Handle<String> tag = args[0]->ToString();
Handle<String> message = args[1]->ToString();
for (uint32_t i = 2; i < len; ++i) {
message = String::Concat(String::Concat(message, String::New(" ")), args[i]->ToString());
}
String::Utf8Value tagValue(tag);
String::Utf8Value messageValue(message);
__android_log_print(ANDROID_LOG_DEBUG, *tagValue, *messageValue);
return Undefined();
}
/* static */
void V8Runtime::bootstrap(Local<Object> global)
{
EventEmitter::initTemplate();
krollGlobalObject = Persistent<Object>::New(Object::New());
moduleContexts = Persistent<Array>::New(Array::New());
KrollBindings::initFunctions(krollGlobalObject);
DEFINE_METHOD(krollGlobalObject, "log", krollLog);
DEFINE_TEMPLATE(krollGlobalObject, "EventEmitter", EventEmitter::constructorTemplate);
krollGlobalObject->Set(String::NewSymbol("runtime"), String::New("v8"));
krollGlobalObject->Set(String::NewSymbol("DBG"), v8::Boolean::New(V8Runtime::DBG));
krollGlobalObject->Set(String::NewSymbol("moduleContexts"), moduleContexts);
LOG_TIMER(TAG, "Executing kroll.js");
TryCatch tryCatch;
Handle<Value> result = V8Util::executeString(KrollBindings::getMainSource(), String::New("ti:/kroll.js"));
if (tryCatch.HasCaught()) {
V8Util::reportException(tryCatch, true);
}
if (!result->IsFunction()) {
LOGF(TAG, "kroll.js result is not a function");
V8Util::reportException(tryCatch, true);
}
Handle<Function> mainFunction = Handle<Function>::Cast(result);
Local<Value> args[] = { Local<Value>::New(krollGlobalObject) };
mainFunction->Call(global, 1, args);
if (tryCatch.HasCaught()) {
V8Util::reportException(tryCatch, true);
LOGE(TAG, "Caught exception while bootstrapping Kroll");
}
}
static void logV8Exception(Handle<Message> msg, Handle<Value> data)
{
HandleScope scope;
// Log reason and location of the error.
LOGD(TAG, *String::Utf8Value(msg->Get()));
LOGD(TAG, "%s @ %d >>> %s",
*String::Utf8Value(msg->GetScriptResourceName()),
msg->GetLineNumber(),
*String::Utf8Value(msg->GetSourceLine()));
}
static jmethodID dispatchDebugMessage = NULL;
static void dispatchHandler()
{
static JNIEnv *env = NULL;
if (!env) {
titanium::JNIUtil::javaVm->AttachCurrentThread(&env, NULL);
}
env->CallVoidMethod(V8Runtime::javaInstance, dispatchDebugMessage);
}
} // namespace titanium
#ifdef __cplusplus
extern "C" {
#endif
using namespace titanium;
/*
* Class: org_appcelerator_kroll_runtime_v8_V8Runtime
* Method: nativeInit
* Signature: (Lorg/appcelerator/kroll/runtime/v8/V8Runtime;)J
*/
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeInit(JNIEnv *env, jobject self, jboolean useGlobalRefs, jint debuggerPort, jboolean DBG)
{
HandleScope scope;
titanium::JNIScope jniScope(env);
// Log all uncaught V8 exceptions.
V8::AddMessageListener(logV8Exception);
V8::SetCaptureStackTraceForUncaughtExceptions(true);
JavaObject::useGlobalRefs = useGlobalRefs;
V8Runtime::debuggerEnabled = debuggerPort >= 0;
V8Runtime::DBG = DBG;
V8Runtime::javaInstance = env->NewGlobalRef(self);
JNIUtil::initCache();
Persistent<Context> context = Persistent<Context>::New(Context::New());
context->Enter();
V8Runtime::globalContext = context;
V8Runtime::bootstrap(context->Global());
if (V8Runtime::debuggerEnabled) {
jclass v8RuntimeClass = env->FindClass("org/appcelerator/kroll/runtime/v8/V8Runtime");
dispatchDebugMessage = env->GetMethodID(v8RuntimeClass, "dispatchDebugMessages", "()V");
Debug::SetDebugMessageDispatchHandler(dispatchHandler);
Debug::EnableAgent("titanium", debuggerPort, true);
}
LOG_HEAP_STATS(TAG);
}
static Persistent<Object> moduleObject;
static Persistent<Function> runModuleFunction;
/*
* Class: org_appcelerator_kroll_runtime_v8_V8Runtime
* Method: nativeRunModule
* Signature: (Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeRunModule
(JNIEnv *env, jobject self, jstring source, jstring filename, jobject activityProxy)
{
ENTER_V8(V8Runtime::globalContext);
titanium::JNIScope jniScope(env);
if (moduleObject.IsEmpty()) {
moduleObject = Persistent<Object>::New(
V8Runtime::krollGlobalObject->Get(String::New("Module"))->ToObject());
runModuleFunction = Persistent<Function>::New(
Handle<Function>::Cast(moduleObject->Get(String::New("runModule"))));
}
Handle<Value> jsSource = TypeConverter::javaStringToJsString(source);
Handle<Value> jsFilename = TypeConverter::javaStringToJsString(filename);
Handle<Value> jsActivity = TypeConverter::javaObjectToJsValue(activityProxy);
Handle<Value> args[] = { jsSource, jsFilename, jsActivity };
TryCatch tryCatch;
runModuleFunction->Call(moduleObject, 3, args);
if (tryCatch.HasCaught()) {
V8Util::openJSErrorDialog(tryCatch);
V8Util::reportException(tryCatch, true);
}
}
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeProcessDebugMessages(JNIEnv *env, jobject self)
{
v8::Debug::ProcessDebugMessages();
}
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeIdle(JNIEnv *env, jobject self)
{
v8::V8::IdleNotification();
}
// This method disposes of all native resources used by V8 when
// all activities have been destroyed by the application.
//
// When a Persistent handle is Dispose()'d in V8, the internal
// pointer is not changed, handle->IsEmpty() returns false.
// As a consequence, we have to explicitly reset the handle
// to an empty handle using Persistent<Type>()
//
// Since we use lazy initialization in a lot of our code,
// there's probably not an easier way (unless we use boolean flags)
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeDispose(JNIEnv *env, jobject runtime)
{
JNIScope jniScope(env);
// We use a new scope here so any new handles we create
// while disposing are cleaned up before our global context
// is disposed below.
{
HandleScope scope;
// Any module that has been require()'d or opened via Window URL
// will be cleaned up here. We setup the initial "moduleContexts"
// Array and expose it on kroll above in nativeInit, and
// module.js will insert module contexts into this array in
// Module.prototype._runScript
uint32_t length = V8Runtime::moduleContexts->Length();
for (uint32_t i = 0; i < length; ++i) {
Handle<Value> moduleContext = V8Runtime::moduleContexts->Get(i);
// WrappedContext is simply a C++ wrapper for the V8 Context object,
// and is used to expose the Context to javascript. See ScriptsModule for
// implementation details
WrappedContext *wrappedContext = WrappedContext::Unwrap(moduleContext->ToObject());
ASSERT(wrappedContext != NULL);
// Detach each context's global object, and dispose the context
wrappedContext->GetV8Context()->DetachGlobal();
wrappedContext->GetV8Context().Dispose();
}
// KrollBindings
KrollBindings::dispose();
EventEmitter::dispose();
V8Runtime::moduleContexts.Dispose();
V8Runtime::moduleContexts = Persistent<Array>();
V8Runtime::globalContext->DetachGlobal();
}
// Dispose of each class' static cache / resources
V8Util::dispose();
ProxyFactory::dispose();
moduleObject.Dispose();
moduleObject = Persistent<Object>();
runModuleFunction.Dispose();
runModuleFunction = Persistent<Function>();
V8Runtime::krollGlobalObject.Dispose();
V8Runtime::globalContext->Exit();
V8Runtime::globalContext.Dispose();
// Removes the retained global reference to the V8Runtime
env->DeleteGlobalRef(V8Runtime::javaInstance);
V8Runtime::javaInstance = NULL;
}
jint JNI_OnLoad(JavaVM *vm, void *reserved)
{
JNIUtil::javaVm = vm;
return JNI_VERSION_1_4;
}
#ifdef __cplusplus
}
#endif
<|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.
#if defined(ENABLE_GPU)
#include "content/common/gpu/image_transport_surface.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/debug/trace_event.h"
#include "content/common/gpu/gpu_channel.h"
#include "content/common/gpu/gpu_channel_manager.h"
#include "content/common/gpu/gpu_command_buffer_stub.h"
#include "content/common/gpu/gpu_messages.h"
#include "gpu/command_buffer/service/gpu_scheduler.h"
#include "ui/gfx/gl/gl_switches.h"
ImageTransportSurface::ImageTransportSurface() {
}
ImageTransportSurface::~ImageTransportSurface() {
}
void ImageTransportSurface::GetRegionsToCopy(
const gfx::Rect& previous_damage_rect,
const gfx::Rect& new_damage_rect,
std::vector<gfx::Rect>* regions) {
gfx::Rect intersection = previous_damage_rect.Intersect(new_damage_rect);
if (intersection.IsEmpty()) {
regions->push_back(previous_damage_rect);
return;
}
// Top (above the intersection).
regions->push_back(gfx::Rect(previous_damage_rect.x(),
previous_damage_rect.y(),
previous_damage_rect.width(),
intersection.y() - previous_damage_rect.y()));
// Left (of the intersection).
regions->push_back(gfx::Rect(previous_damage_rect.x(),
intersection.y(),
intersection.x() - previous_damage_rect.x(),
intersection.height()));
// Right (of the intersection).
regions->push_back(gfx::Rect(intersection.right(),
intersection.y(),
previous_damage_rect.right() - intersection.right(),
intersection.height()));
// Bottom (below the intersection).
regions->push_back(gfx::Rect(previous_damage_rect.x(),
intersection.bottom(),
previous_damage_rect.width(),
previous_damage_rect.bottom() - intersection.bottom()));
}
ImageTransportHelper::ImageTransportHelper(ImageTransportSurface* surface,
GpuChannelManager* manager,
GpuCommandBufferStub* stub,
gfx::PluginWindowHandle handle)
: surface_(surface),
manager_(manager),
stub_(stub->AsWeakPtr()),
handle_(handle) {
route_id_ = manager_->GenerateRouteID();
manager_->AddRoute(route_id_, this);
}
ImageTransportHelper::~ImageTransportHelper() {
manager_->RemoveRoute(route_id_);
}
bool ImageTransportHelper::Initialize() {
gpu::gles2::GLES2Decoder* decoder = Decoder();
if (!decoder)
return false;
decoder->SetResizeCallback(
base::Bind(&ImageTransportHelper::Resize, base::Unretained(this)));
return true;
}
void ImageTransportHelper::Destroy() {
}
bool ImageTransportHelper::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ImageTransportHelper, message)
IPC_MESSAGE_HANDLER(AcceleratedSurfaceMsg_BuffersSwappedACK,
OnBuffersSwappedACK)
IPC_MESSAGE_HANDLER(AcceleratedSurfaceMsg_PostSubBufferACK,
OnPostSubBufferACK)
IPC_MESSAGE_HANDLER(AcceleratedSurfaceMsg_NewACK,
OnNewSurfaceACK)
IPC_MESSAGE_HANDLER(AcceleratedSurfaceMsg_ResizeViewACK, OnResizeViewACK);
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void ImageTransportHelper::SendAcceleratedSurfaceRelease(
GpuHostMsg_AcceleratedSurfaceRelease_Params params) {
params.surface_id = stub_->surface_id();
params.route_id = route_id_;
manager_->Send(new GpuHostMsg_AcceleratedSurfaceRelease(params));
}
void ImageTransportHelper::SendAcceleratedSurfaceNew(
GpuHostMsg_AcceleratedSurfaceNew_Params params) {
params.surface_id = stub_->surface_id();
params.route_id = route_id_;
#if defined(OS_MACOSX)
params.window = handle_;
#endif
manager_->Send(new GpuHostMsg_AcceleratedSurfaceNew(params));
}
void ImageTransportHelper::SendAcceleratedSurfaceBuffersSwapped(
GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params params) {
params.surface_id = stub_->surface_id();
params.route_id = route_id_;
#if defined(OS_MACOSX)
params.window = handle_;
#endif
manager_->Send(new GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params));
}
void ImageTransportHelper::SendAcceleratedSurfacePostSubBuffer(
GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params params) {
params.surface_id = stub_->surface_id();
params.route_id = route_id_;
#if defined(OS_MACOSX)
params.window = handle_;
#endif
manager_->Send(new GpuHostMsg_AcceleratedSurfacePostSubBuffer(params));
}
void ImageTransportHelper::SendResizeView(const gfx::Size& size) {
manager_->Send(new GpuHostMsg_ResizeView(stub_->surface_id(),
route_id_,
size));
}
void ImageTransportHelper::SetScheduled(bool is_scheduled) {
gpu::GpuScheduler* scheduler = Scheduler();
if (!scheduler)
return;
if (is_scheduled) {
TRACE_EVENT_ASYNC_BEGIN0("gpu", "Descheduled", this);
} else {
TRACE_EVENT_ASYNC_END0("gpu", "Descheduled", this);
}
scheduler->SetScheduled(is_scheduled);
}
void ImageTransportHelper::DeferToFence(base::Closure task) {
gpu::GpuScheduler* scheduler = Scheduler();
DCHECK(scheduler);
scheduler->DeferToFence(task);
}
void ImageTransportHelper::OnBuffersSwappedACK() {
surface_->OnBuffersSwappedACK();
}
void ImageTransportHelper::OnPostSubBufferACK() {
surface_->OnPostSubBufferACK();
}
void ImageTransportHelper::OnNewSurfaceACK(
uint64 surface_handle,
TransportDIB::Handle shm_handle) {
surface_->OnNewSurfaceACK(surface_handle, shm_handle);
}
void ImageTransportHelper::OnResizeViewACK() {
surface_->OnResizeViewACK();
}
void ImageTransportHelper::Resize(gfx::Size size) {
// On windows, the surface is recreated and, in case the newly allocated
// surface happens to have the same address, it should be invalidated on the
// decoder so that future calls to MakeCurrent do not early out on the
// assumption that neither the context or surface have actually changed.
#if defined(OS_WIN)
Decoder()->ReleaseCurrent();
#endif
surface_->OnResize(size);
#if defined(OS_WIN)
Decoder()->MakeCurrent();
SetSwapInterval();
#endif
}
void ImageTransportHelper::SetSwapInterval() {
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableGpuVsync))
Decoder()->GetGLContext()->SetSwapInterval(0);
else
Decoder()->GetGLContext()->SetSwapInterval(1);
}
bool ImageTransportHelper::MakeCurrent() {
gpu::gles2::GLES2Decoder* decoder = Decoder();
if (!decoder)
return false;
return decoder->MakeCurrent();
}
void ImageTransportHelper::Suspend() {
manager_->Send(new GpuHostMsg_AcceleratedSurfaceSuspend(stub_->surface_id()));
}
gpu::GpuScheduler* ImageTransportHelper::Scheduler() {
if (!stub_.get())
return NULL;
return stub_->scheduler();
}
gpu::gles2::GLES2Decoder* ImageTransportHelper::Decoder() {
if (!stub_.get())
return NULL;
return stub_->decoder();
}
PassThroughImageTransportSurface::PassThroughImageTransportSurface(
GpuChannelManager* manager,
GpuCommandBufferStub* stub,
gfx::GLSurface* surface,
bool transport)
: GLSurfaceAdapter(surface),
transport_(transport),
did_set_swap_interval_(false) {
helper_.reset(new ImageTransportHelper(this,
manager,
stub,
gfx::kNullPluginWindow));
}
PassThroughImageTransportSurface::~PassThroughImageTransportSurface() {
}
bool PassThroughImageTransportSurface::Initialize() {
// The surface is assumed to have already been initialized.
return helper_->Initialize();
}
void PassThroughImageTransportSurface::Destroy() {
helper_->Destroy();
GLSurfaceAdapter::Destroy();
}
void PassThroughImageTransportSurface::OnNewSurfaceACK(
uint64 surface_handle, TransportDIB::Handle shm_handle) {
}
bool PassThroughImageTransportSurface::SwapBuffers() {
bool result = gfx::GLSurfaceAdapter::SwapBuffers();
if (transport_) {
// Round trip to the browser UI thread, for throttling, by sending a dummy
// SwapBuffers message.
GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params params;
params.surface_handle = 0;
#if defined(OS_WIN)
params.size = GetSize();
#endif
helper_->SendAcceleratedSurfaceBuffersSwapped(params);
helper_->SetScheduled(false);
}
return result;
}
bool PassThroughImageTransportSurface::PostSubBuffer(
int x, int y, int width, int height) {
bool result = gfx::GLSurfaceAdapter::PostSubBuffer(x, y, width, height);
if (transport_) {
// Round trip to the browser UI thread, for throttling, by sending a dummy
// PostSubBuffer message.
GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params params;
params.surface_handle = 0;
params.x = x;
params.y = y;
params.width = width;
params.height = height;
helper_->SendAcceleratedSurfacePostSubBuffer(params);
helper_->SetScheduled(false);
}
return result;
}
bool PassThroughImageTransportSurface::OnMakeCurrent(gfx::GLContext* context) {
if (!did_set_swap_interval_) {
helper_->SetSwapInterval();
did_set_swap_interval_ = true;
}
return true;
}
void PassThroughImageTransportSurface::OnBuffersSwappedACK() {
DCHECK(transport_);
helper_->SetScheduled(true);
}
void PassThroughImageTransportSurface::OnPostSubBufferACK() {
DCHECK(transport_);
helper_->SetScheduled(true);
}
void PassThroughImageTransportSurface::OnResizeViewACK() {
DCHECK(transport_);
Resize(new_size_);
helper_->SetScheduled(true);
}
void PassThroughImageTransportSurface::OnResize(gfx::Size size) {
new_size_ = size;
if (transport_) {
helper_->SendResizeView(size);
helper_->SetScheduled(false);
} else {
Resize(new_size_);
}
}
#endif // defined(ENABLE_GPU)
<commit_msg>Fix ordering of descheduled async events<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.
#if defined(ENABLE_GPU)
#include "content/common/gpu/image_transport_surface.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/debug/trace_event.h"
#include "content/common/gpu/gpu_channel.h"
#include "content/common/gpu/gpu_channel_manager.h"
#include "content/common/gpu/gpu_command_buffer_stub.h"
#include "content/common/gpu/gpu_messages.h"
#include "gpu/command_buffer/service/gpu_scheduler.h"
#include "ui/gfx/gl/gl_switches.h"
ImageTransportSurface::ImageTransportSurface() {
}
ImageTransportSurface::~ImageTransportSurface() {
}
void ImageTransportSurface::GetRegionsToCopy(
const gfx::Rect& previous_damage_rect,
const gfx::Rect& new_damage_rect,
std::vector<gfx::Rect>* regions) {
gfx::Rect intersection = previous_damage_rect.Intersect(new_damage_rect);
if (intersection.IsEmpty()) {
regions->push_back(previous_damage_rect);
return;
}
// Top (above the intersection).
regions->push_back(gfx::Rect(previous_damage_rect.x(),
previous_damage_rect.y(),
previous_damage_rect.width(),
intersection.y() - previous_damage_rect.y()));
// Left (of the intersection).
regions->push_back(gfx::Rect(previous_damage_rect.x(),
intersection.y(),
intersection.x() - previous_damage_rect.x(),
intersection.height()));
// Right (of the intersection).
regions->push_back(gfx::Rect(intersection.right(),
intersection.y(),
previous_damage_rect.right() - intersection.right(),
intersection.height()));
// Bottom (below the intersection).
regions->push_back(gfx::Rect(previous_damage_rect.x(),
intersection.bottom(),
previous_damage_rect.width(),
previous_damage_rect.bottom() - intersection.bottom()));
}
ImageTransportHelper::ImageTransportHelper(ImageTransportSurface* surface,
GpuChannelManager* manager,
GpuCommandBufferStub* stub,
gfx::PluginWindowHandle handle)
: surface_(surface),
manager_(manager),
stub_(stub->AsWeakPtr()),
handle_(handle) {
route_id_ = manager_->GenerateRouteID();
manager_->AddRoute(route_id_, this);
}
ImageTransportHelper::~ImageTransportHelper() {
manager_->RemoveRoute(route_id_);
}
bool ImageTransportHelper::Initialize() {
gpu::gles2::GLES2Decoder* decoder = Decoder();
if (!decoder)
return false;
decoder->SetResizeCallback(
base::Bind(&ImageTransportHelper::Resize, base::Unretained(this)));
return true;
}
void ImageTransportHelper::Destroy() {
}
bool ImageTransportHelper::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ImageTransportHelper, message)
IPC_MESSAGE_HANDLER(AcceleratedSurfaceMsg_BuffersSwappedACK,
OnBuffersSwappedACK)
IPC_MESSAGE_HANDLER(AcceleratedSurfaceMsg_PostSubBufferACK,
OnPostSubBufferACK)
IPC_MESSAGE_HANDLER(AcceleratedSurfaceMsg_NewACK,
OnNewSurfaceACK)
IPC_MESSAGE_HANDLER(AcceleratedSurfaceMsg_ResizeViewACK, OnResizeViewACK);
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void ImageTransportHelper::SendAcceleratedSurfaceRelease(
GpuHostMsg_AcceleratedSurfaceRelease_Params params) {
params.surface_id = stub_->surface_id();
params.route_id = route_id_;
manager_->Send(new GpuHostMsg_AcceleratedSurfaceRelease(params));
}
void ImageTransportHelper::SendAcceleratedSurfaceNew(
GpuHostMsg_AcceleratedSurfaceNew_Params params) {
params.surface_id = stub_->surface_id();
params.route_id = route_id_;
#if defined(OS_MACOSX)
params.window = handle_;
#endif
manager_->Send(new GpuHostMsg_AcceleratedSurfaceNew(params));
}
void ImageTransportHelper::SendAcceleratedSurfaceBuffersSwapped(
GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params params) {
params.surface_id = stub_->surface_id();
params.route_id = route_id_;
#if defined(OS_MACOSX)
params.window = handle_;
#endif
manager_->Send(new GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params));
}
void ImageTransportHelper::SendAcceleratedSurfacePostSubBuffer(
GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params params) {
params.surface_id = stub_->surface_id();
params.route_id = route_id_;
#if defined(OS_MACOSX)
params.window = handle_;
#endif
manager_->Send(new GpuHostMsg_AcceleratedSurfacePostSubBuffer(params));
}
void ImageTransportHelper::SendResizeView(const gfx::Size& size) {
manager_->Send(new GpuHostMsg_ResizeView(stub_->surface_id(),
route_id_,
size));
}
void ImageTransportHelper::SetScheduled(bool is_scheduled) {
gpu::GpuScheduler* scheduler = Scheduler();
if (!scheduler)
return;
if (is_scheduled) {
TRACE_EVENT_ASYNC_END0("gpu", "Descheduled", this);
} else {
TRACE_EVENT_ASYNC_BEGIN0("gpu", "Descheduled", this);
}
scheduler->SetScheduled(is_scheduled);
}
void ImageTransportHelper::DeferToFence(base::Closure task) {
gpu::GpuScheduler* scheduler = Scheduler();
DCHECK(scheduler);
scheduler->DeferToFence(task);
}
void ImageTransportHelper::OnBuffersSwappedACK() {
surface_->OnBuffersSwappedACK();
}
void ImageTransportHelper::OnPostSubBufferACK() {
surface_->OnPostSubBufferACK();
}
void ImageTransportHelper::OnNewSurfaceACK(
uint64 surface_handle,
TransportDIB::Handle shm_handle) {
surface_->OnNewSurfaceACK(surface_handle, shm_handle);
}
void ImageTransportHelper::OnResizeViewACK() {
surface_->OnResizeViewACK();
}
void ImageTransportHelper::Resize(gfx::Size size) {
// On windows, the surface is recreated and, in case the newly allocated
// surface happens to have the same address, it should be invalidated on the
// decoder so that future calls to MakeCurrent do not early out on the
// assumption that neither the context or surface have actually changed.
#if defined(OS_WIN)
Decoder()->ReleaseCurrent();
#endif
surface_->OnResize(size);
#if defined(OS_WIN)
Decoder()->MakeCurrent();
SetSwapInterval();
#endif
}
void ImageTransportHelper::SetSwapInterval() {
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableGpuVsync))
Decoder()->GetGLContext()->SetSwapInterval(0);
else
Decoder()->GetGLContext()->SetSwapInterval(1);
}
bool ImageTransportHelper::MakeCurrent() {
gpu::gles2::GLES2Decoder* decoder = Decoder();
if (!decoder)
return false;
return decoder->MakeCurrent();
}
void ImageTransportHelper::Suspend() {
manager_->Send(new GpuHostMsg_AcceleratedSurfaceSuspend(stub_->surface_id()));
}
gpu::GpuScheduler* ImageTransportHelper::Scheduler() {
if (!stub_.get())
return NULL;
return stub_->scheduler();
}
gpu::gles2::GLES2Decoder* ImageTransportHelper::Decoder() {
if (!stub_.get())
return NULL;
return stub_->decoder();
}
PassThroughImageTransportSurface::PassThroughImageTransportSurface(
GpuChannelManager* manager,
GpuCommandBufferStub* stub,
gfx::GLSurface* surface,
bool transport)
: GLSurfaceAdapter(surface),
transport_(transport),
did_set_swap_interval_(false) {
helper_.reset(new ImageTransportHelper(this,
manager,
stub,
gfx::kNullPluginWindow));
}
PassThroughImageTransportSurface::~PassThroughImageTransportSurface() {
}
bool PassThroughImageTransportSurface::Initialize() {
// The surface is assumed to have already been initialized.
return helper_->Initialize();
}
void PassThroughImageTransportSurface::Destroy() {
helper_->Destroy();
GLSurfaceAdapter::Destroy();
}
void PassThroughImageTransportSurface::OnNewSurfaceACK(
uint64 surface_handle, TransportDIB::Handle shm_handle) {
}
bool PassThroughImageTransportSurface::SwapBuffers() {
bool result = gfx::GLSurfaceAdapter::SwapBuffers();
if (transport_) {
// Round trip to the browser UI thread, for throttling, by sending a dummy
// SwapBuffers message.
GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params params;
params.surface_handle = 0;
#if defined(OS_WIN)
params.size = GetSize();
#endif
helper_->SendAcceleratedSurfaceBuffersSwapped(params);
helper_->SetScheduled(false);
}
return result;
}
bool PassThroughImageTransportSurface::PostSubBuffer(
int x, int y, int width, int height) {
bool result = gfx::GLSurfaceAdapter::PostSubBuffer(x, y, width, height);
if (transport_) {
// Round trip to the browser UI thread, for throttling, by sending a dummy
// PostSubBuffer message.
GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params params;
params.surface_handle = 0;
params.x = x;
params.y = y;
params.width = width;
params.height = height;
helper_->SendAcceleratedSurfacePostSubBuffer(params);
helper_->SetScheduled(false);
}
return result;
}
bool PassThroughImageTransportSurface::OnMakeCurrent(gfx::GLContext* context) {
if (!did_set_swap_interval_) {
helper_->SetSwapInterval();
did_set_swap_interval_ = true;
}
return true;
}
void PassThroughImageTransportSurface::OnBuffersSwappedACK() {
DCHECK(transport_);
helper_->SetScheduled(true);
}
void PassThroughImageTransportSurface::OnPostSubBufferACK() {
DCHECK(transport_);
helper_->SetScheduled(true);
}
void PassThroughImageTransportSurface::OnResizeViewACK() {
DCHECK(transport_);
Resize(new_size_);
helper_->SetScheduled(true);
}
void PassThroughImageTransportSurface::OnResize(gfx::Size size) {
new_size_ = size;
if (transport_) {
helper_->SendResizeView(size);
helper_->SetScheduled(false);
} else {
Resize(new_size_);
}
}
#endif // defined(ENABLE_GPU)
<|endoftext|> |
<commit_before>#ifndef __ARCH_IO_NETWORK_HPP__
#define __ARCH_IO_NETWORK_HPP__
#include <vector>
#include "utils.hpp"
#include <boost/scoped_ptr.hpp>
#include "arch/runtime/event_queue.hpp"
#include "arch/io/io_utils.hpp"
#include "arch/address.hpp"
#include "concurrency/cond_var.hpp"
#include "concurrency/queue/unlimited_fifo.hpp"
#include "concurrency/semaphore.hpp"
#include "concurrency/coro_pool.hpp"
#include "perfmon_types.hpp"
#include "arch/io/event_watcher.hpp"
#include <boost/iterator/iterator_facade.hpp>
#include <stdexcept>
#include <stdarg.h>
#include <unistd.h>
#include <sstream>
class side_coro_handler_t;
/* linux_tcp_conn_t provides a disgusting wrapper around a TCP network connection. */
class linux_tcp_conn_t :
public home_thread_mixin_t,
private linux_event_callback_t {
public:
friend class linux_nascent_tcp_conn_t;
struct connect_failed_exc_t : public std::exception {
const char *what() const throw () {
return "Could not make connection";
}
~connect_failed_exc_t() throw () { }
};
/* TODO: One of these forms should be replaced by the other. */
linux_tcp_conn_t(const char *host, int port);
linux_tcp_conn_t(const ip_address_t &host, int port);
/* Reading */
struct read_closed_exc_t : public std::exception {
const char *what() const throw () {
return "Network connection read end closed";
}
};
/* If you know beforehand how many bytes you want to read, use read() with a byte buffer.
Returns when the buffer is full, or throws read_closed_exc_t. */
void read(void *buf, size_t size);
// If you don't know how many bytes you want to read, but still
// masochistically want to handle buffering yourself. Makes at
// most one call to ::read(), reads some data or throws
// read_closed_exc_t. read_some() is guaranteed to return at least
// one byte of data unless it throws read_closed_exc_t.
size_t read_some(void *buf, size_t size);
// If you don't know how many bytes you want to read, use peek()
// and then, if you're satisfied, pop what you've read, or if
// you're unsatisfied, read_more_buffered() and then try again.
// Note that you should always call peek() before calling
// read_more_buffered(), because there might be leftover data in
// the peek buffer that might be enough for you.
const_charslice peek() const;
//you can also peek with a specific size (this is really just convenient
//for some things and can in some cases avoid an unneeded copy
const_charslice peek(size_t size);
void pop(size_t len);
//pop to the position the iterator has been incremented to
class iterator;
void pop(iterator &);
void read_more_buffered();
/* Call shutdown_read() to close the half of the pipe that goes from the peer to us. If there
is an outstanding read() or peek_until() operation, it will throw read_closed_exc_t. */
void shutdown_read();
/* Returns false if the half of the pipe that goes from the peer to us has been closed. */
bool is_read_open();
/* Writing */
struct write_closed_exc_t : public std::exception {
const char *what() const throw () {
return "Network connection write end closed";
}
};
/* write() writes 'size' bytes from 'buf' to the socket and blocks until it is done. Throws
write_closed_exc_t if the write end of the pipe is closed before we can finish. */
void write(const void *buf, size_t size);
/* write_buffered() is like write(), but it might not send the data until flush_buffer*() or
write() is called. Internally, it bundles together the buffered writes; this may improve
performance. */
void write_buffered(const void *buf, size_t size);
void vwritef(const char *format, va_list args) {
char buffer[1000];
size_t bytes = vsnprintf(buffer, sizeof(buffer), format, args);
rassert(bytes < sizeof(buffer));
write(buffer, bytes);
}
void writef(const char *format, ...)
__attribute__ ((format (printf, 2, 3))) {
va_list args;
va_start(args, format);
vwritef(format, args);
va_end(args);
}
void flush_buffer(); // Blocks until flush is done
void flush_buffer_eventually(); // Blocks only if the queue is backed up
/* Call shutdown_write() to close the half of the pipe that goes from us to the peer. If there
is a write currently happening, it will get write_closed_exc_t. */
void shutdown_write();
/* Returns false if the half of the pipe that goes from us to the peer has been closed. */
bool is_write_open();
/* Put a `perfmon_rate_monitor_t` here if you want to record stats on how fast data is being
transmitted over the network. */
perfmon_rate_monitor_t *write_perfmon;
/* Note that is_read_open() and is_write_open() must both be false1 before the socket is
destroyed. */
~linux_tcp_conn_t();
public:
/* iterator always you to handle the stream of data off the
* socket with iterators, the iterator handles all of the buffering itself. The
* impetus for this class comes from wanting to use network connection's with
* Boost's spirit parser */
class iterator
: public boost::iterator_facade<iterator, const char, boost::forward_traversal_tag>
{
friend class linux_tcp_conn_t;
private:
linux_tcp_conn_t *source;
bool end;
size_t pos;
private:
int compare(iterator const& other) const;
private:
// boost iterator interface
void increment();
bool equal(iterator const& other);
const char &dereference();
public:
iterator();
iterator(linux_tcp_conn_t *, size_t);
private:
iterator(linux_tcp_conn_t *, bool); // <--- constructs and end iterator use the below method for better readability;
public:
static iterator make_end_iterator(linux_tcp_conn_t *);
iterator(const iterator&);
~iterator();
char operator*();
void operator++();
void operator++(int);
bool operator==(const iterator&);
bool operator!=(const iterator&);
bool operator<(const iterator&);
};
public:
iterator begin();
iterator end();
private:
explicit linux_tcp_conn_t(fd_t sock); // Used by tcp_listener_t
/* Note that this only gets called to handle error-events. Read and write
events are handled through the linux_event_watcher_t. */
void on_event(int events);
void on_shutdown_read();
void on_shutdown_write();
scoped_fd_t sock;
/* Object that we use to watch for events. It's NULL when we are not registered on any
thread, and otherwise is an object that's valid for the current thread. */
linux_event_watcher_t *event_watcher;
/* True if there is a pending read or write */
bool read_in_progress, write_in_progress;
/* These are pulsed if and only if the read/write end of the connection has been closed. */
cond_t read_closed, write_closed;
/* Holds data that we read from the socket but hasn't been consumed yet */
std::vector<char> read_buffer;
/* Reads up to the given number of bytes, but not necessarily that many. Simple wrapper around
::read(). Returns the number of bytes read or throws read_closed_exc_t. Bypasses read_buffer. */
size_t read_internal(void *buffer, size_t size);
/* Buffer we are currently filling up with data that we want to write. When it reaches a
certain size, we push it onto `write_queue`. */
std::vector<char> write_buffer;
/* Schedules old write buffer's contents to be flushed and swaps in a fresh write buffer.
Blocks until it can acquire the `write_queue_limiter` semaphore, but doesn't wait for
data to be completely written. */
void internal_flush_write_buffer();
/* Used to queue up buffers to write. The functions in `write_queue` will all be
`boost::bind()`s of the `perform_write()` function below. */
unlimited_fifo_queue_t<boost::function<void()> > write_queue;
/* This semaphore prevents the write queue from getting arbitrarily big. */
semaphore_t write_queue_limiter;
/* Used to actually perform the writes. Only has one coroutine in it. */
coro_pool_t write_coro_pool;
/* Used to actually perform a write. If the write end of the connection is open, then writes
`size` bytes from `buffer` to the socket. */
void perform_write(const void *buffer, size_t size);
};
class linux_nascent_tcp_conn_t {
public:
~linux_nascent_tcp_conn_t();
// Must get called exactly once during lifetime of this object.
// Call it on the thread you'll use the connection on.
void ennervate(boost::scoped_ptr<linux_tcp_conn_t>& tcp_conn);
private:
friend class linux_tcp_listener_t;
explicit linux_nascent_tcp_conn_t(fd_t fd);
private:
fd_t fd_;
DISABLE_COPYING(linux_nascent_tcp_conn_t);
};
/* The linux_tcp_listener_t is used to listen on a network port for incoming
connections. Create a linux_tcp_listener_t with some port and then call set_callback();
the provided callback will be called in a new coroutine every time something connects. */
class linux_tcp_listener_t : public linux_event_callback_t {
public:
linux_tcp_listener_t(
int port,
boost::function<void(boost::scoped_ptr<linux_nascent_tcp_conn_t>&)> callback
);
~linux_tcp_listener_t();
// The constructor can throw this exception
struct address_in_use_exc_t :
public std::exception
{
address_in_use_exc_t(const char* hostname, int port) throw () {
std::stringstream stream;
stream << "The address at " << hostname << ":" << port << " is already in use";
info.assign(stream.str());
}
~address_in_use_exc_t() throw () { };
const char *what() const throw () {
return info.c_str();
}
private:
std::string info;
};
private:
// The socket to listen for connections on
scoped_fd_t sock;
// Sentry representing our registration with event loop
linux_event_watcher_t event_watcher;
// The callback to call when we get a connection
boost::function<void(boost::scoped_ptr<linux_nascent_tcp_conn_t>&)> callback;
/* accept_loop() runs in a separate coroutine. It repeatedly tries to accept
new connections; when accept() blocks, then it waits for events from the
event loop. When accept_loop_handler's destructor is called, accept_loop_handler
stops accept_loop() by pulsing the signal. */
boost::scoped_ptr<side_coro_handler_t> accept_loop_handler;
void accept_loop(signal_t *);
void handle(fd_t sock);
/* event_watcher sends any error conditions to here */
void on_event(int events);
bool log_next_error;
};
#endif // __ARCH_IO_NETWORK_HPP__
<commit_msg>changing exception to use strprintf instead of std::stringstream<commit_after>#ifndef __ARCH_IO_NETWORK_HPP__
#define __ARCH_IO_NETWORK_HPP__
#include <vector>
#include "utils.hpp"
#include <boost/scoped_ptr.hpp>
#include "arch/runtime/event_queue.hpp"
#include "arch/io/io_utils.hpp"
#include "arch/address.hpp"
#include "concurrency/cond_var.hpp"
#include "concurrency/queue/unlimited_fifo.hpp"
#include "concurrency/semaphore.hpp"
#include "concurrency/coro_pool.hpp"
#include "perfmon_types.hpp"
#include "arch/io/event_watcher.hpp"
#include <boost/iterator/iterator_facade.hpp>
#include <stdexcept>
#include <stdarg.h>
#include <unistd.h>
#include <sstream>
class side_coro_handler_t;
/* linux_tcp_conn_t provides a disgusting wrapper around a TCP network connection. */
class linux_tcp_conn_t :
public home_thread_mixin_t,
private linux_event_callback_t {
public:
friend class linux_nascent_tcp_conn_t;
struct connect_failed_exc_t : public std::exception {
const char *what() const throw () {
return "Could not make connection";
}
~connect_failed_exc_t() throw () { }
};
/* TODO: One of these forms should be replaced by the other. */
linux_tcp_conn_t(const char *host, int port);
linux_tcp_conn_t(const ip_address_t &host, int port);
/* Reading */
struct read_closed_exc_t : public std::exception {
const char *what() const throw () {
return "Network connection read end closed";
}
};
/* If you know beforehand how many bytes you want to read, use read() with a byte buffer.
Returns when the buffer is full, or throws read_closed_exc_t. */
void read(void *buf, size_t size);
// If you don't know how many bytes you want to read, but still
// masochistically want to handle buffering yourself. Makes at
// most one call to ::read(), reads some data or throws
// read_closed_exc_t. read_some() is guaranteed to return at least
// one byte of data unless it throws read_closed_exc_t.
size_t read_some(void *buf, size_t size);
// If you don't know how many bytes you want to read, use peek()
// and then, if you're satisfied, pop what you've read, or if
// you're unsatisfied, read_more_buffered() and then try again.
// Note that you should always call peek() before calling
// read_more_buffered(), because there might be leftover data in
// the peek buffer that might be enough for you.
const_charslice peek() const;
//you can also peek with a specific size (this is really just convenient
//for some things and can in some cases avoid an unneeded copy
const_charslice peek(size_t size);
void pop(size_t len);
//pop to the position the iterator has been incremented to
class iterator;
void pop(iterator &);
void read_more_buffered();
/* Call shutdown_read() to close the half of the pipe that goes from the peer to us. If there
is an outstanding read() or peek_until() operation, it will throw read_closed_exc_t. */
void shutdown_read();
/* Returns false if the half of the pipe that goes from the peer to us has been closed. */
bool is_read_open();
/* Writing */
struct write_closed_exc_t : public std::exception {
const char *what() const throw () {
return "Network connection write end closed";
}
};
/* write() writes 'size' bytes from 'buf' to the socket and blocks until it is done. Throws
write_closed_exc_t if the write end of the pipe is closed before we can finish. */
void write(const void *buf, size_t size);
/* write_buffered() is like write(), but it might not send the data until flush_buffer*() or
write() is called. Internally, it bundles together the buffered writes; this may improve
performance. */
void write_buffered(const void *buf, size_t size);
void vwritef(const char *format, va_list args) {
char buffer[1000];
size_t bytes = vsnprintf(buffer, sizeof(buffer), format, args);
rassert(bytes < sizeof(buffer));
write(buffer, bytes);
}
void writef(const char *format, ...)
__attribute__ ((format (printf, 2, 3))) {
va_list args;
va_start(args, format);
vwritef(format, args);
va_end(args);
}
void flush_buffer(); // Blocks until flush is done
void flush_buffer_eventually(); // Blocks only if the queue is backed up
/* Call shutdown_write() to close the half of the pipe that goes from us to the peer. If there
is a write currently happening, it will get write_closed_exc_t. */
void shutdown_write();
/* Returns false if the half of the pipe that goes from us to the peer has been closed. */
bool is_write_open();
/* Put a `perfmon_rate_monitor_t` here if you want to record stats on how fast data is being
transmitted over the network. */
perfmon_rate_monitor_t *write_perfmon;
/* Note that is_read_open() and is_write_open() must both be false1 before the socket is
destroyed. */
~linux_tcp_conn_t();
public:
/* iterator always you to handle the stream of data off the
* socket with iterators, the iterator handles all of the buffering itself. The
* impetus for this class comes from wanting to use network connection's with
* Boost's spirit parser */
class iterator
: public boost::iterator_facade<iterator, const char, boost::forward_traversal_tag>
{
friend class linux_tcp_conn_t;
private:
linux_tcp_conn_t *source;
bool end;
size_t pos;
private:
int compare(iterator const& other) const;
private:
// boost iterator interface
void increment();
bool equal(iterator const& other);
const char &dereference();
public:
iterator();
iterator(linux_tcp_conn_t *, size_t);
private:
iterator(linux_tcp_conn_t *, bool); // <--- constructs and end iterator use the below method for better readability;
public:
static iterator make_end_iterator(linux_tcp_conn_t *);
iterator(const iterator&);
~iterator();
char operator*();
void operator++();
void operator++(int);
bool operator==(const iterator&);
bool operator!=(const iterator&);
bool operator<(const iterator&);
};
public:
iterator begin();
iterator end();
private:
explicit linux_tcp_conn_t(fd_t sock); // Used by tcp_listener_t
/* Note that this only gets called to handle error-events. Read and write
events are handled through the linux_event_watcher_t. */
void on_event(int events);
void on_shutdown_read();
void on_shutdown_write();
scoped_fd_t sock;
/* Object that we use to watch for events. It's NULL when we are not registered on any
thread, and otherwise is an object that's valid for the current thread. */
linux_event_watcher_t *event_watcher;
/* True if there is a pending read or write */
bool read_in_progress, write_in_progress;
/* These are pulsed if and only if the read/write end of the connection has been closed. */
cond_t read_closed, write_closed;
/* Holds data that we read from the socket but hasn't been consumed yet */
std::vector<char> read_buffer;
/* Reads up to the given number of bytes, but not necessarily that many. Simple wrapper around
::read(). Returns the number of bytes read or throws read_closed_exc_t. Bypasses read_buffer. */
size_t read_internal(void *buffer, size_t size);
/* Buffer we are currently filling up with data that we want to write. When it reaches a
certain size, we push it onto `write_queue`. */
std::vector<char> write_buffer;
/* Schedules old write buffer's contents to be flushed and swaps in a fresh write buffer.
Blocks until it can acquire the `write_queue_limiter` semaphore, but doesn't wait for
data to be completely written. */
void internal_flush_write_buffer();
/* Used to queue up buffers to write. The functions in `write_queue` will all be
`boost::bind()`s of the `perform_write()` function below. */
unlimited_fifo_queue_t<boost::function<void()> > write_queue;
/* This semaphore prevents the write queue from getting arbitrarily big. */
semaphore_t write_queue_limiter;
/* Used to actually perform the writes. Only has one coroutine in it. */
coro_pool_t write_coro_pool;
/* Used to actually perform a write. If the write end of the connection is open, then writes
`size` bytes from `buffer` to the socket. */
void perform_write(const void *buffer, size_t size);
};
class linux_nascent_tcp_conn_t {
public:
~linux_nascent_tcp_conn_t();
// Must get called exactly once during lifetime of this object.
// Call it on the thread you'll use the connection on.
void ennervate(boost::scoped_ptr<linux_tcp_conn_t>& tcp_conn);
private:
friend class linux_tcp_listener_t;
explicit linux_nascent_tcp_conn_t(fd_t fd);
private:
fd_t fd_;
DISABLE_COPYING(linux_nascent_tcp_conn_t);
};
/* The linux_tcp_listener_t is used to listen on a network port for incoming
connections. Create a linux_tcp_listener_t with some port and then call set_callback();
the provided callback will be called in a new coroutine every time something connects. */
class linux_tcp_listener_t : public linux_event_callback_t {
public:
linux_tcp_listener_t(
int port,
boost::function<void(boost::scoped_ptr<linux_nascent_tcp_conn_t>&)> callback
);
~linux_tcp_listener_t();
// The constructor can throw this exception
struct address_in_use_exc_t :
public std::exception
{
address_in_use_exc_t(const char* hostname, int port) throw () :
info(strprintf("The address at %s:%d is already in use", hostname, port)) { };
~address_in_use_exc_t() throw () { };
const char *what() const throw () {
return info.c_str();
}
private:
std::string info;
};
private:
// The socket to listen for connections on
scoped_fd_t sock;
// Sentry representing our registration with event loop
linux_event_watcher_t event_watcher;
// The callback to call when we get a connection
boost::function<void(boost::scoped_ptr<linux_nascent_tcp_conn_t>&)> callback;
/* accept_loop() runs in a separate coroutine. It repeatedly tries to accept
new connections; when accept() blocks, then it waits for events from the
event loop. When accept_loop_handler's destructor is called, accept_loop_handler
stops accept_loop() by pulsing the signal. */
boost::scoped_ptr<side_coro_handler_t> accept_loop_handler;
void accept_loop(signal_t *);
void handle(fd_t sock);
/* event_watcher sends any error conditions to here */
void on_event(int events);
bool log_next_error;
};
#endif // __ARCH_IO_NETWORK_HPP__
<|endoftext|> |
<commit_before>// Copyright 2015 Nikita Chudinov
#include "argument_parser.h"
#include <cstring>
#include <getopt.h>
#include <unistd.h>
#include <iostream>
#include <string>
ArgumentParser::ArgumentParser(int argc, char *argv[]) {
HELP_MESSAGE =
R"(General options:
-h, --help produce this help message
-s, --store scan and store file metadata
-c, --check[=FILE] check all files metadata (or one file, if provided)
--path_list=FILE use provided config file (default: "./path_list.json")
--start start daemon)";
const char *option_string = "sc::h?";
int index;
struct option long_options[] = {
{"help", no_argument, NULL, 'h'},
{"store", no_argument, NULL, 's'},
{"check", optional_argument, NULL, 'c'},
{"path_list", required_argument, NULL, 0},
{"start", no_argument, NULL, 0},
{"kill", no_argument, NULL, 0},
{NULL, 0, 0, 0}
};
bool help = false;
bool store = false;
bool check = false;
bool start = false;
bool kill = false;
std::string path_list_file = "path_list.json";
std::string check_file = "";
int option = getopt_long(argc, argv, option_string, long_options, &index);
while (option != -1) {
switch (option) {
case 's':
store = true;
break;
case 'c':
check = true;
if (optarg != NULL) {
check_file = optarg;
}
break;
case 'h':
help = true;
break;
case 0:
if (strcmp(long_options[index].name, "path_list") == 0) {
path_list_file = optarg;
} else if (strcmp(long_options[index].name, "start") == 0) {
start = true;
} else if (strcmp(long_options[index].name, "kill") == 0) {
kill = true;
}
break;
default:
break;
}
option = getopt_long(argc, argv, option_string, long_options, &index);
}
// fill object
if (store) {
mode = STORE;
}
if (check) {
mode = CHECK;
}
if (help) {
mode = HELP;
}
if (start) {
mode = START;
}
if (kill) {
mode = KILL;
}
this->path_list_file = path_list_file;
this->check_file = check_file;
}
std::string ArgumentParser::GetPathListFile() {
return path_list_file;
}
ArgumentParser::Mode ArgumentParser::GetMode() {
return mode;
}
void ArgumentParser::PrintHelpMessage() {
std::cout << HELP_MESSAGE << std::endl;
}
<commit_msg>Add --kill to help message<commit_after>// Copyright 2015 Nikita Chudinov
#include "argument_parser.h"
#include <cstring>
#include <getopt.h>
#include <unistd.h>
#include <iostream>
#include <string>
ArgumentParser::ArgumentParser(int argc, char *argv[]) {
HELP_MESSAGE =
R"(General options:
-h, --help produce this help message
-s, --store scan and store file metadata
-c, --check[=FILE] check all files metadata (or one file, if provided)
--path_list=FILE use provided config file (default: "./path_list.json")
--start start daemon
--kill kills daemon)";
const char *option_string = "sc::h?";
int index;
struct option long_options[] = {
{"help", no_argument, NULL, 'h'},
{"store", no_argument, NULL, 's'},
{"check", optional_argument, NULL, 'c'},
{"path_list", required_argument, NULL, 0},
{"start", no_argument, NULL, 0},
{"kill", no_argument, NULL, 0},
{NULL, 0, 0, 0}
};
bool help = false;
bool store = false;
bool check = false;
bool start = false;
bool kill = false;
std::string path_list_file = "path_list.json";
std::string check_file = "";
int option = getopt_long(argc, argv, option_string, long_options, &index);
while (option != -1) {
switch (option) {
case 's':
store = true;
break;
case 'c':
check = true;
if (optarg != NULL) {
check_file = optarg;
}
break;
case 'h':
help = true;
break;
case 0:
if (strcmp(long_options[index].name, "path_list") == 0) {
path_list_file = optarg;
} else if (strcmp(long_options[index].name, "start") == 0) {
start = true;
} else if (strcmp(long_options[index].name, "kill") == 0) {
kill = true;
}
break;
default:
break;
}
option = getopt_long(argc, argv, option_string, long_options, &index);
}
// fill object
if (store) {
mode = STORE;
}
if (check) {
mode = CHECK;
}
if (help) {
mode = HELP;
}
if (start) {
mode = START;
}
if (kill) {
mode = KILL;
}
this->path_list_file = path_list_file;
this->check_file = check_file;
}
std::string ArgumentParser::GetPathListFile() {
return path_list_file;
}
ArgumentParser::Mode ArgumentParser::GetMode() {
return mode;
}
void ArgumentParser::PrintHelpMessage() {
std::cout << HELP_MESSAGE << std::endl;
}
<|endoftext|> |
<commit_before>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
//
// spdlog usage example
//
//
#define SPDLOG_TRACE_ON
#define SPDLOG_DEBUG_ON
#include "spdlog/sinks/daily_file_sink.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include <iostream>
#include <memory>
void basic_example();
void rotating_example();
void daily_example();
void async_example();
void user_defined_example();
void err_handler_example();
void syslog_example();
namespace spd = spdlog;
int main(int, char *[])
{
try
{
auto console = spdlog::stdout_color_mt("console");
console->info("Welcome to spdlog!");
console->error("Some error message with arg: {}", 1);
// Formatting examples
console->warn("Easy padding in numbers like {:08d}", 12);
console->critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
console->info("Support for floats {:03.2f}", 1.23456);
console->info("Positional args are {1} {0}..", "too", "supported");
console->info("{:<30}", "left aligned");
spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name)");
// Runtime log levels
spd::set_level(spd::level::info); // Set global log level to info
console->debug("This message should not be displayed!");
console->set_level(spd::level::trace); // Set specific logger's log level
console->debug("This message should be displayed..");
// Customize msg format for all loggers
spd::set_pattern("[%H:%M:%S %z] [%^---%L---%$] [thread %t] %v");
console->info("This an info message with custom format");
// Compile time log levels
// define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON
SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);
// various file loggers
basic_example();
rotating_example();
daily_example();
// async logging using a backing thread pool
async_example();
// user defined types logging by implementing operator<<
user_defined_example();
// custom error handler
err_handler_example();
// Apply a function on all registered loggers
spd::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });
// Release and close all loggers
spdlog::drop_all();
}
// Exceptions will only be thrown upon failed logger or sink construction (not during logging)
catch (const spd::spdlog_ex &ex)
{
std::cout << "Log init failed: " << ex.what() << std::endl;
return 1;
}
}
#include "spdlog/sinks/basic_file_sink.h"
void basic_example()
{
// Create basic file logger (not rotated)
auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic-log.txt");
}
#include "spdlog/sinks/rotating_file_sink.h"
void rotating_example()
{
// Create a file rotating logger with 5mb size max and 3 rotated files
auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
}
#include "spdlog/sinks/daily_file_sink.h"
void daily_example()
{
// Create a daily logger - a new file is created every day on 2:30am
auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
}
#include "spdlog/async.h"
void async_example()
{
// default thread pool settings can be modified *before* creating the async logger:
// spdlog::init_thread_pool(32768, 1); // queue with max 32k items 1 backing thread.
// spdlog::init_thread_pool(32768, 4); // queue with max 32k items 4 backing threads.
auto async_file = spd::basic_logger_mt<spdlog::async_factory>("async_file_logger", "logs/async_log.txt");
// alternatively:
// auto async_file = spd::create_async<spd::sinks::basic_file_sink_mt>("async_file_logger", "logs/async_log.txt");
for (int i = 0; i < 100; ++i)
{
async_file->info("Async message #{}", i + 1);
}
}
// user defined types logging by implementing operator<<
#include "spdlog/fmt/ostr.h" // must be included
struct my_type
{
int i;
template<typename OStream>
friend OStream &operator<<(OStream &os, const my_type &c)
{
return os << "[my_type i=" << c.i << "]";
}
};
void user_defined_example()
{
spd::get("console")->info("user defined type: {}", my_type{14});
}
//
// custom error handler
//
void err_handler_example()
{
// can be set globaly or per logger(logger->set_error_handler(..))
spdlog::set_error_handler([](const std::string &msg) { spd::get("console")->error("*******my err handler: {}", msg); });
spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
// spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
}
// syslog example (linux/osx/freebsd)
#ifndef _WIN32
#include "spdlog/sinks/syslog_sink.h"
void syslog_example()
{
std::string ident = "spdlog-example";
auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
syslog_logger->warn("This is warning that will end up in syslog.");
}
#endif
// Android example
#if defined(__ANDROID__)
#incude "spdlog/sinks/android_sink.h"
void android_example()
{
std::string tag = "spdlog-android";
auto android_logger = spd::android_logger("android", tag);
android_logger->critical("Use \"adb shell logcat\" to view this message.");
}
#endif
<commit_msg>updated example<commit_after>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
//
// spdlog usage example
//
//
#include <iostream>
void stdout_example();
void basic_example();
void rotating_example();
void daily_example();
void async_example();
void user_defined_example();
void err_handler_example();
void syslog_example();
#include "spdlog/spdlog.h"
int main(int, char *[])
{
try
{
// console logging example
stdout_example();
// various file loggers
basic_example();
rotating_example();
daily_example();
// async logging using a backing thread pool
async_example();
// user defined types logging by implementing operator<<
user_defined_example();
// custom error handler
err_handler_example();
// apply some function on all registered loggers
spdlog::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });
// Release and close all loggers
spdlog::drop_all();
}
// Exceptions will only be thrown upon failed logger or sink construction (not during logging)
catch (const spdlog::spdlog_ex &ex)
{
std::cout << "Log init failed: " << ex.what() << std::endl;
return 1;
}
}
#include "spdlog/sinks/stdout_color_sinks.h" // or "/sinks/stdout_sinks.h" if no colors needed
void stdout_example()
{
// create color multi threaded logger
auto console = spdlog::stdout_color_mt("console");
console->info("Welcome to spdlog!");
console->error("Some error message with arg: {}", 1);
auto err_logger = spdlog::stderr_color_mt("error_logger");
err_logger ->error("Some error message");
// Formatting examples
console->warn("Easy padding in numbers like {:08d}", 12);
console->critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
console->info("Support for floats {:03.2f}", 1.23456);
console->info("Positional args are {1} {0}..", "too", "supported");
console->info("{:<30}", "left aligned");
spdlog::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name)");
// Runtime log levels
spdlog::set_level(spdlog::level::info); // Set global log level to info
console->debug("This message should not be displayed!");
console->set_level(spdlog::level::trace); // Set specific logger's log level
console->debug("This message should be displayed..");
// Customize msg format for all loggers
spdlog::set_pattern("[%H:%M:%S %z] [%^---%L---%$] [thread %t] %v");
console->info("This an info message with custom format");
// Compile time log levels
// define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON
SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);
}
#include "spdlog/sinks/basic_file_sink.h"
void basic_example()
{
// Create basic file logger (not rotated)
auto my_logger = spdlog::basic_logger_mt("basic_logger", "logs/basic-log.txt");
}
#include "spdlog/sinks/rotating_file_sink.h"
void rotating_example()
{
// Create a file rotating logger with 5mb size max and 3 rotated files
auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
}
#include "spdlog/sinks/daily_file_sink.h"
void daily_example()
{
// Create a daily logger - a new file is created every day on 2:30am
auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
}
#include "spdlog/async.h"
void async_example()
{
// default thread pool settings can be modified *before* creating the async logger:
// spdlog::init_thread_pool(32768, 1); // queue with max 32k items 1 backing thread.
auto async_file = spdlog::basic_logger_mt<spdlog::async_factory>("async_file_logger", "logs/async_log.txt");
// alternatively:
// auto async_file = spdlog::create_async<spdlog::sinks::basic_file_sink_mt>("async_file_logger", "logs/async_log.txt");
for (int i = 1; i < 101; ++i)
{
async_file->info("Async message #{}", i);
}
}
// user defined types logging by implementing operator<<
#include "spdlog/fmt/ostr.h" // must be included
struct my_type
{
int i;
template<typename OStream>
friend OStream &operator<<(OStream &os, const my_type &c)
{
return os << "[my_type i=" << c.i << "]";
}
};
void user_defined_example()
{
spdlog::get("console")->info("user defined type: {}", my_type{14});
}
//
// custom error handler
//
void err_handler_example()
{
// can be set globally or per logger(logger->set_error_handler(..))
spdlog::set_error_handler([](const std::string &msg) { spdlog::get("console")->error("*** LOGGER ERROR ***: {}", msg); });
spdlog::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
}
// syslog example (linux/osx/freebsd)
#ifndef _WIN32
#include "spdlog/sinks/syslog_sink.h"
void syslog_example()
{
std::string ident = "spdlog-example";
auto syslog_logger = spdlog::syslog_logger("syslog", ident, LOG_PID);
syslog_logger->warn("This is warning that will end up in syslog.");
}
#endif
// Android example
#if defined(__ANDROID__)
#incude "spdlog/sinks/android_sink.h"
void android_example()
{
std::string tag = "spdlog-android";
auto android_logger = spdlog::android_logger("android", tag);
android_logger->critical("Use \"adb shell logcat\" to view this message.");
}
#endif
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 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.
#ifndef SERVER_CONNECTION_HPP
#define SERVER_CONNECTION_HPP
#include <net/tcp/connection.hpp>
#include <rtc>
#include "request.hpp"
#include "response.hpp"
namespace server {
class Server;
class Connection;
using Connection_ptr = std::shared_ptr<Connection>;
class Connection {
private:
const static size_t BUFSIZE = 1460;
using Connection_ptr = net::tcp::Connection_ptr;
using buffer_t = net::tcp::buffer_t;
using OnData = net::tcp::Connection::ReadCallback;
using Disconnect = net::tcp::Connection::Disconnect;
using OnDisconnect = net::tcp::Connection::DisconnectCallback;
using OnClose = net::tcp::Connection::CloseCallback;
using OnError = net::tcp::Connection::ErrorCallback;
using TCPException = net::tcp::TCPException;
using OnPacketDropped = net::tcp::Connection::PacketDroppedCallback;
using Packet_ptr = net::tcp::Packet_ptr;
using OnConnection = std::function<void()>;
public:
Connection(Server&, Connection_ptr, size_t idx);
Request_ptr get_request() noexcept
{ return request_; }
Response_ptr get_response()
{ return response_; }
void close();
inline std::string to_string() const
{ return "Connection:[" + conn_->remote().to_string() + "]"; }
static void on_connection(OnConnection cb)
{ on_connection_ = cb; }
RTC::timestamp_t idle_since() const
{ return idle_since_; }
void close_tcp()
{
if(conn_->is_closing() == false)
conn_->close();
}
void timeout();
~Connection();
private:
Server& server_;
Connection_ptr conn_;
Request_ptr request_;
Response_ptr response_;
size_t idx_;
RTC::timestamp_t idle_since_;
static size_t PAYLOAD_LIMIT;
static OnConnection on_connection_;
void on_data(buffer_t, size_t);
void on_disconnect(Connection_ptr, Disconnect);
void on_error(TCPException);
void on_packet_dropped(Packet_ptr, std::string);
void update_idle()
{ idle_since_ = RTC::now(); }
}; // < server::Connection
}; // < server
#endif
<commit_msg>connection: Changed Connection::get_response signature<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 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.
#ifndef SERVER_CONNECTION_HPP
#define SERVER_CONNECTION_HPP
#include <net/tcp/connection.hpp>
#include <rtc>
#include "request.hpp"
#include "response.hpp"
namespace server {
class Server;
class Connection;
using Connection_ptr = std::shared_ptr<Connection>;
class Connection {
private:
const static size_t BUFSIZE = 1460;
using Connection_ptr = net::tcp::Connection_ptr;
using buffer_t = net::tcp::buffer_t;
using OnData = net::tcp::Connection::ReadCallback;
using Disconnect = net::tcp::Connection::Disconnect;
using OnDisconnect = net::tcp::Connection::DisconnectCallback;
using OnClose = net::tcp::Connection::CloseCallback;
using OnError = net::tcp::Connection::ErrorCallback;
using TCPException = net::tcp::TCPException;
using OnPacketDropped = net::tcp::Connection::PacketDroppedCallback;
using Packet_ptr = net::tcp::Packet_ptr;
using OnConnection = std::function<void()>;
public:
Connection(Server&, Connection_ptr, size_t idx);
Request_ptr get_request() noexcept
{ return request_; }
Response_ptr get_response() noexcept
{ return response_; }
void close();
inline std::string to_string() const
{ return "Connection:[" + conn_->remote().to_string() + "]"; }
static void on_connection(OnConnection cb)
{ on_connection_ = cb; }
RTC::timestamp_t idle_since() const
{ return idle_since_; }
void close_tcp()
{
if(conn_->is_closing() == false)
conn_->close();
}
void timeout();
~Connection();
private:
Server& server_;
Connection_ptr conn_;
Request_ptr request_;
Response_ptr response_;
size_t idx_;
RTC::timestamp_t idle_since_;
static size_t PAYLOAD_LIMIT;
static OnConnection on_connection_;
void on_data(buffer_t, size_t);
void on_disconnect(Connection_ptr, Disconnect);
void on_error(TCPException);
void on_packet_dropped(Packet_ptr, std::string);
void update_idle()
{ idle_since_ = RTC::now(); }
}; // < server::Connection
}; // < server
#endif
<|endoftext|> |
<commit_before>/*************************************************************************/
/* spdlog - an extremely fast and easy to use c++11 logging library. */
/* Copyright (c) 2014 Gabi Melman. */
/* */
/* 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. */
/*************************************************************************/
//
// spdlog usage example
//
#include <iostream>
#include "spdlog/spdlog.h"
int maina(int, char* [])
{
namespace spd = spdlog;
try
{
std::string filename = "logs/spdlog_example";
// Set log level to all loggers to DEBUG and above
spd::set_level(spd::level::DEBUG);
//Create console, multithreaded logger
auto console = spd::stdout_logger_mt("console");
console->info("Welcome to spdlog!") ;
console->info("An info message example", "...", 1, 2, 3.5);
console->info() << "Streams are supported too " << std::setw(5) << std::setfill('0') << 1;
//Create a file rotating logger with 5mb size max and 3 rotated files
auto file_logger = spd::rotating_logger_mt("file_logger", filename, 1024 * 1024 * 5, 3);
file_logger->info("Log file message number", 1);
for (int i = 0; i < 100; ++i)
{
file_logger->info(i, "in hex is", "0x") << std::hex << std::uppercase << i;
}
spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***");
file_logger->info("This is another message with custom format");
spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");
SPDLOG_TRACE(file_logger, "This is a trace message (only #ifdef _DEBUG)", 123);
}
catch (const spd::spdlog_ex& ex)
{
std::cout << "Log failed: " << ex.what() << std::endl;
}
return 0;
}
<commit_msg>example typo<commit_after>/*************************************************************************/
/* spdlog - an extremely fast and easy to use c++11 logging library. */
/* Copyright (c) 2014 Gabi Melman. */
/* */
/* 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. */
/*************************************************************************/
//
// spdlog usage example
//
#include <iostream>
#include "spdlog/spdlog.h"
int main(int, char* [])
{
namespace spd = spdlog;
try
{
std::string filename = "logs/spdlog_example";
// Set log level to all loggers to DEBUG and above
spd::set_level(spd::level::DEBUG);
//Create console, multithreaded logger
auto console = spd::stdout_logger_mt("console");
console->info("Welcome to spdlog!") ;
console->info("An info message example", "...", 1, 2, 3.5);
console->info() << "Streams are supported too " << std::setw(5) << std::setfill('0') << 1;
//Create a file rotating logger with 5mb size max and 3 rotated files
auto file_logger = spd::rotating_logger_mt("file_logger", filename, 1024 * 1024 * 5, 3);
file_logger->info("Log file message number", 1);
for (int i = 0; i < 100; ++i)
{
file_logger->info(i, "in hex is", "0x") << std::hex << std::uppercase << i;
}
spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***");
file_logger->info("This is another message with custom format");
spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");
SPDLOG_TRACE(file_logger, "This is a trace message (only #ifdef _DEBUG)", 123);
}
catch (const spd::spdlog_ex& ex)
{
std::cout << "Log failed: " << ex.what() << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
// SPDX-License-Identifier: MIT
// Copyright (c) 2019 Daniil Goncharov <neargye@gmail.com>.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <iostream>
#include <magic_enum.hpp>
enum class Color : int { RED = -10, BLUE = 0, GREEN = 10 };
int main() {
// Enum variable to string name.
Color c1 = Color::RED;
auto c1_name = magic_enum::enum_name(c1);
std::cout << c1_name << std::endl; // RED
// String enum name sequence.
constexpr auto color_names = magic_enum::enum_names<Color>();
std::cout << "Color names:";
for (auto n : color_names) {
std::cout << " " << n;
}
std::cout << std::endl;
// Color names: RED BLUE GREEN
// String name to enum value.
auto c2 = magic_enum::enum_cast<Color>("BLUE");
if (c2.has_value() && c2.value() == Color::BLUE) {
std::cout << "BLUE = " << static_cast<int>(c2.value()) << std::endl; // BLUE = 0
}
// Integer value to enum value.
auto c3 = magic_enum::enum_cast<Color>(10);
if (c3.has_value() && c3.value() == Color::GREEN) {
std::cout << "GREEN = " << magic_enum::enum_integer(c3.value()) << std::endl; // GREEN = 10
}
// Enum value to integer value.
auto color_integer = magic_enum::enum_integer(Color::RED);
if (color_integer == static_cast<std::underlying_type_t<Color>>(Color::RED)) {
std::cout << "RED = " << color_integer << std::endl; // RED = -10
}
using namespace magic_enum::ostream_operators; // out-of-the-box ostream operator for enums.
// ostream operator for enum.
std::cout << "Color: " << c1 << " " << c2 << " " << c3 << std::endl; // Color: RED BLUE GREEN
// Number of enum values.
std::cout << "Color enum size: " << magic_enum::enum_count<Color>() << std::endl; // Color enum size: 3
// Indexed access to enum value.
std::cout << "Color[0] = " << magic_enum::enum_value<Color>(0) << std::endl; // Color[0] = RED
// Enum value sequence.
constexpr auto colors = magic_enum::enum_values<Color>();
std::cout << "Colors sequence:";
for (Color c : colors) {
std::cout << " " << c; // ostream operator for enum.
}
std::cout << std::endl;
// Color sequence: RED BLUE GREEN
enum class Flags { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3 };
using namespace magic_enum::bitwise_operators; // out-of-the-box bitwise operators for enums.
Flags flags = Flags::A | Flags::B & ~Flags::C;
std::cout << magic_enum::enum_integer(flags) << std::endl;
enum color { red, green, blue };
// Checks whether type is an Unscoped enumeration.
static_assert(magic_enum::is_unscoped_enum_v<color>);
static_assert(!magic_enum::is_unscoped_enum_v<Color>);
static_assert(!magic_enum::is_unscoped_enum_v<Flags>);
// Checks whether type is an Scoped enumeration.
static_assert(!magic_enum::is_scoped_enum_v<color>);
static_assert(magic_enum::is_scoped_enum_v<Color>);
static_assert(magic_enum::is_scoped_enum_v<Flags>);
// Checks whether type is an Fixed enumeration.
static_assert(!magic_enum::is_fixed_enum_v<color>);
static_assert(magic_enum::is_fixed_enum_v<Color>);
static_assert(magic_enum::is_fixed_enum_v<Flags>);
// Enum pair (value enum, string enum name) sequence.
constexpr auto color_entries = magic_enum::enum_entries<Color>();
std::cout << "Colors entries:";
for (auto& e : color_entries) {
std::cout << " " << e.second << " = " << static_cast<int>(e.first);
}
std::cout << std::endl;
// Color entries: RED = -10 BLUE = 0 GREEN = 10
return 0;
}
<commit_msg>update example<commit_after>// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
// SPDX-License-Identifier: MIT
// Copyright (c) 2019 Daniil Goncharov <neargye@gmail.com>.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <iostream>
#include <magic_enum.hpp>
enum class Color : int { RED = -10, BLUE = 0, GREEN = 10 };
int main() {
// Enum variable to string name.
Color c1 = Color::RED;
auto c1_name = magic_enum::enum_name(c1);
std::cout << c1_name << std::endl; // RED
// String enum name sequence.
constexpr auto color_names = magic_enum::enum_names<Color>();
std::cout << "Color names:";
for (auto n : color_names) {
std::cout << " " << n;
}
std::cout << std::endl;
// Color names: RED BLUE GREEN
// String name to enum value.
auto c2 = magic_enum::enum_cast<Color>("BLUE");
if (c2.has_value() && c2.value() == Color::BLUE) {
std::cout << "BLUE = " << static_cast<int>(c2.value()) << std::endl; // BLUE = 0
}
// Integer value to enum value.
auto c3 = magic_enum::enum_cast<Color>(10);
if (c3.has_value() && c3.value() == Color::GREEN) {
std::cout << "GREEN = " << magic_enum::enum_integer(c3.value()) << std::endl; // GREEN = 10
}
// Enum value to integer value.
auto color_integer = magic_enum::enum_integer(Color::RED);
if (color_integer == static_cast<std::underlying_type_t<Color>>(Color::RED)) {
std::cout << "RED = " << color_integer << std::endl; // RED = -10
}
using namespace magic_enum::ostream_operators; // out-of-the-box ostream operator for enums.
// ostream operator for enum.
std::cout << "Color: " << c1 << " " << c2 << " " << c3 << std::endl; // Color: RED BLUE GREEN
// Number of enum values.
std::cout << "Color enum size: " << magic_enum::enum_count<Color>() << std::endl; // Color enum size: 3
// Indexed access to enum value.
std::cout << "Color[0] = " << magic_enum::enum_value<Color>(0) << std::endl; // Color[0] = RED
// Enum value sequence.
constexpr auto colors = magic_enum::enum_values<Color>();
std::cout << "Colors sequence:";
for (Color c : colors) {
std::cout << " " << c; // ostream operator for enum.
}
std::cout << std::endl;
// Color sequence: RED BLUE GREEN
enum class Flags { A = 1 << 0, B = 1 << 1, C = 1 << 2, D = 1 << 3 };
using namespace magic_enum::bitwise_operators; // out-of-the-box bitwise operators for enums.
// Support operators: ~, |, &, ^, |=, &=, ^=.
Flags flags = Flags::A & ~Flags::C;
std::cout << flags << std::endl;
enum color { red, green, blue };
// Checks whether type is an Unscoped enumeration.
static_assert(magic_enum::is_unscoped_enum_v<color>);
static_assert(!magic_enum::is_unscoped_enum_v<Color>);
static_assert(!magic_enum::is_unscoped_enum_v<Flags>);
// Checks whether type is an Scoped enumeration.
static_assert(!magic_enum::is_scoped_enum_v<color>);
static_assert(magic_enum::is_scoped_enum_v<Color>);
static_assert(magic_enum::is_scoped_enum_v<Flags>);
// Checks whether type is an Fixed enumeration.
static_assert(!magic_enum::is_fixed_enum_v<color>);
static_assert(magic_enum::is_fixed_enum_v<Color>);
static_assert(magic_enum::is_fixed_enum_v<Flags>);
// Enum pair (value enum, string enum name) sequence.
constexpr auto color_entries = magic_enum::enum_entries<Color>();
std::cout << "Colors entries:";
for (auto& e : color_entries) {
std::cout << " " << e.second << " = " << static_cast<int>(e.first);
}
std::cout << std::endl;
// Color entries: RED = -10 BLUE = 0 GREEN = 10
return 0;
}
<|endoftext|> |
<commit_before>#include "config.h"
#include "vm.hpp"
#include "immix_marker.hpp"
#include "builtin/class.hpp"
#include "builtin/thread.hpp"
#include "configuration.hpp"
#include "gc/gc.hpp"
#include "gc/immix.hpp"
#include "ontology.hpp"
#include "dtrace/dtrace.h"
#include "instruments/timing.hpp"
namespace rubinius {
Object* immix_marker_tramp(STATE) {
state->memory()->immix_marker()->perform(state);
return cNil;
}
ImmixMarker::ImmixMarker(STATE, ImmixGC* immix)
: AuxiliaryThread()
, shared_(state->shared())
, self_(NULL)
, immix_(immix)
, data_(NULL)
, paused_(false)
, exit_(false)
, thread_(state)
{
shared_.auxiliary_threads()->register_thread(this);
state->memory()->set_immix_marker(this);
run_lock_.init();
run_cond_.init();
pause_cond_.init();
start_thread(state);
}
ImmixMarker::~ImmixMarker() {
shared_.auxiliary_threads()->unregister_thread(this);
}
void ImmixMarker::start_thread(STATE) {
SYNC(state);
if(self_) return;
utilities::thread::Mutex::LockGuard lg(run_lock_);
self_ = state->shared().new_vm();
paused_ = false;
exit_ = false;
thread_.set(Thread::create(state, self_, G(thread), immix_marker_tramp, false, true));
run(state);
}
void ImmixMarker::stop_thread(STATE) {
SYNC(state);
if(!self_) return;
pthread_t os = self_->os_thread();
{
utilities::thread::Mutex::LockGuard lg(run_lock_);
// Thread might have already been stopped
exit_ = true;
run_cond_.signal();
}
void* return_value;
pthread_join(os, &return_value);
self_ = NULL;
}
void ImmixMarker::shutdown(STATE) {
stop_thread(state);
}
void ImmixMarker::before_exec(STATE) {
stop_thread(state);
}
void ImmixMarker::after_exec(STATE) {
start_thread(state);
}
void ImmixMarker::before_fork(STATE) {
utilities::thread::Mutex::LockGuard lg(run_lock_);
while(!paused_ && self_->run_state() == ManagedThread::eRunning) {
pause_cond_.wait(run_lock_);
}
}
void ImmixMarker::after_fork_parent(STATE) {
utilities::thread::Mutex::LockGuard lg(run_lock_);
run_cond_.signal();
}
void ImmixMarker::after_fork_child(STATE) {
run_lock_.init();
run_cond_.init();
pause_cond_.init();
if(self_) {
VM::discard(state, self_);
self_ = NULL;
}
if(data_) {
delete data_;
data_ = NULL;
}
start_thread(state);
}
void ImmixMarker::concurrent_mark(GCData* data) {
utilities::thread::Mutex::LockGuard lg(run_lock_);
paused_ = false;
data_ = data;
run_cond_.signal();
}
void ImmixMarker::wait_for_marker(STATE) {
utilities::thread::Mutex::LockGuard lg(run_lock_);
GCTokenImpl gct;
while(!paused_) {
state->gc_independent(gct, state->vm()->saved_call_frame());
pause_cond_.wait(run_lock_);
state->gc_dependent(gct, state->vm()->saved_call_frame());
}
}
void ImmixMarker::run(STATE) {
int error = thread_.get()->fork_attached(state);
if(error) rubinius::bug("Unable to immix marker thread");
}
void ImmixMarker::perform(STATE) {
GCTokenImpl gct;
const char* thread_name = "rbx.immix";
self_->set_name(thread_name);
RUBINIUS_THREAD_START(thread_name, state->vm()->thread_id(), 1);
state->vm()->thread->hard_unlock(state, gct, 0);
while(!exit_) {
if(data_) {
{
timer::Running<1000000> timer(state->memory()->gc_stats.total_full_concurrent_collection_time,
state->memory()->gc_stats.last_full_concurrent_collection_time);
// Allow for a young stop the world GC to occur
// every bunch of marks. 100 is a fairly arbitrary
// number, based mostly on the fact it didn't cause
// big increases in young gc times because of long
// stop the world wait times.
while(immix_->process_mark_stack(100)) {
state->gc_independent(gct, 0);
state->gc_dependent(gct, 0);
}
}
atomic::integer initial_stop = state->memory()->gc_stats.last_full_stop_collection_time;
{
timer::Running<1000000> timer(state->memory()->gc_stats.total_full_stop_collection_time,
state->memory()->gc_stats.last_full_stop_collection_time);
// Finish and pause
while(!state->stop_the_world()) {
state->checkpoint(gct, 0);
}
state->memory()->collect_mature_finish(state, data_);
state->memory()->clear_mature_mark_in_progress();
}
state->memory()->gc_stats.last_full_stop_collection_time.add(initial_stop.value);
state->memory()->print_mature_stats(state, data_);
delete data_;
data_ = NULL;
state->restart_world();
}
utilities::thread::Mutex::LockGuard lg(run_lock_);
if(exit_) break;
state->gc_independent(gct, 0);
paused_ = true;
pause_cond_.signal();
run_cond_.wait(run_lock_);
state->gc_dependent(gct, 0);
}
state->memory()->clear_mature_mark_in_progress();
RUBINIUS_THREAD_STOP(thread_name, state->vm()->thread_id(), 1);
}
}
<commit_msg>Fix deadlock when forking when immix thread is active<commit_after>#include "config.h"
#include "vm.hpp"
#include "immix_marker.hpp"
#include "builtin/class.hpp"
#include "builtin/thread.hpp"
#include "configuration.hpp"
#include "gc/gc.hpp"
#include "gc/immix.hpp"
#include "ontology.hpp"
#include "dtrace/dtrace.h"
#include "instruments/timing.hpp"
namespace rubinius {
Object* immix_marker_tramp(STATE) {
state->memory()->immix_marker()->perform(state);
return cNil;
}
ImmixMarker::ImmixMarker(STATE, ImmixGC* immix)
: AuxiliaryThread()
, shared_(state->shared())
, self_(NULL)
, immix_(immix)
, data_(NULL)
, paused_(false)
, exit_(false)
, thread_(state)
{
shared_.auxiliary_threads()->register_thread(this);
state->memory()->set_immix_marker(this);
run_lock_.init();
run_cond_.init();
pause_cond_.init();
start_thread(state);
}
ImmixMarker::~ImmixMarker() {
shared_.auxiliary_threads()->unregister_thread(this);
}
void ImmixMarker::start_thread(STATE) {
SYNC(state);
if(self_) return;
utilities::thread::Mutex::LockGuard lg(run_lock_);
self_ = state->shared().new_vm();
paused_ = false;
exit_ = false;
thread_.set(Thread::create(state, self_, G(thread), immix_marker_tramp, false, true));
run(state);
}
void ImmixMarker::stop_thread(STATE) {
SYNC(state);
if(!self_) return;
pthread_t os = self_->os_thread();
{
utilities::thread::Mutex::LockGuard lg(run_lock_);
// Thread might have already been stopped
exit_ = true;
run_cond_.signal();
}
void* return_value;
pthread_join(os, &return_value);
self_ = NULL;
}
void ImmixMarker::shutdown(STATE) {
stop_thread(state);
}
void ImmixMarker::before_exec(STATE) {
stop_thread(state);
}
void ImmixMarker::after_exec(STATE) {
start_thread(state);
}
void ImmixMarker::before_fork(STATE) {
utilities::thread::Mutex::LockGuard lg(run_lock_);
while(!paused_ && self_->run_state() == ManagedThread::eRunning) {
pause_cond_.wait(run_lock_);
}
}
void ImmixMarker::after_fork_parent(STATE) {
utilities::thread::Mutex::LockGuard lg(run_lock_);
run_cond_.signal();
}
void ImmixMarker::after_fork_child(STATE) {
run_lock_.init();
run_cond_.init();
pause_cond_.init();
if(self_) {
VM::discard(state, self_);
self_ = NULL;
}
if(data_) {
delete data_;
data_ = NULL;
}
start_thread(state);
}
void ImmixMarker::concurrent_mark(GCData* data) {
utilities::thread::Mutex::LockGuard lg(run_lock_);
paused_ = false;
data_ = data;
run_cond_.signal();
}
void ImmixMarker::wait_for_marker(STATE) {
utilities::thread::Mutex::LockGuard lg(run_lock_);
GCTokenImpl gct;
while(!paused_) {
state->gc_independent(gct, state->vm()->saved_call_frame());
pause_cond_.wait(run_lock_);
state->gc_dependent(gct, state->vm()->saved_call_frame());
}
}
void ImmixMarker::run(STATE) {
int error = thread_.get()->fork_attached(state);
if(error) rubinius::bug("Unable to immix marker thread");
}
void ImmixMarker::perform(STATE) {
GCTokenImpl gct;
const char* thread_name = "rbx.immix";
self_->set_name(thread_name);
RUBINIUS_THREAD_START(thread_name, state->vm()->thread_id(), 1);
state->vm()->thread->hard_unlock(state, gct, 0);
while(!exit_) {
if(data_) {
{
timer::Running<1000000> timer(state->memory()->gc_stats.total_full_concurrent_collection_time,
state->memory()->gc_stats.last_full_concurrent_collection_time);
// Allow for a young stop the world GC to occur
// every bunch of marks. 100 is a fairly arbitrary
// number, based mostly on the fact it didn't cause
// big increases in young gc times because of long
// stop the world wait times.
while(immix_->process_mark_stack(100)) {
state->gc_independent(gct, 0);
state->gc_dependent(gct, 0);
}
}
atomic::integer initial_stop = state->memory()->gc_stats.last_full_stop_collection_time;
{
timer::Running<1000000> timer(state->memory()->gc_stats.total_full_stop_collection_time,
state->memory()->gc_stats.last_full_stop_collection_time);
// Finish and pause
while(!state->stop_the_world()) {
state->checkpoint(gct, 0);
}
state->memory()->collect_mature_finish(state, data_);
state->memory()->clear_mature_mark_in_progress();
}
state->memory()->gc_stats.last_full_stop_collection_time.add(initial_stop.value);
state->memory()->print_mature_stats(state, data_);
delete data_;
data_ = NULL;
state->restart_world();
}
{
utilities::thread::Mutex::LockGuard lg(run_lock_);
if(exit_) break;
state->gc_independent(gct, 0);
paused_ = true;
pause_cond_.signal();
run_cond_.wait(run_lock_);
}
state->gc_dependent(gct, 0);
}
state->memory()->clear_mature_mark_in_progress();
RUBINIUS_THREAD_STOP(thread_name, state->vm()->thread_id(), 1);
}
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <typeinfo>
#include <cxxabi.h>
#include <boost/scoped_array.hpp>
#include <concrete/context.hpp>
#include <concrete/exception.hpp>
#include <concrete/execute.hpp>
#include <concrete/objects/code.hpp>
using namespace concrete;
static CodeObject load_example_code()
{
std::ifstream stream;
stream.exceptions(std::ios::failbit | std::ios::badbit);
stream.open(EXAMPLE_BYTECODE);
stream.seekg(0, std::ios::end);
auto size = stream.tellg();
stream.seekg(0, std::ios::beg);
boost::scoped_array<char> buf(new char[size]);
stream.read(buf.get(), size);
stream.close();
return CodeObject::Load(buf.get(), size);
}
template <typename T>
static std::string type_name(const T &object)
{
auto c_str = abi::__cxa_demangle(typeid (object).name(), 0, 0, 0);
std::string str = c_str;
std::free(c_str);
return str;
}
int main()
{
Context context;
ContextScope scope(context);
try {
Executor executor(load_example_code());
while (executor.execute())
;
} catch (const Exception &e) {
std::cerr << type_name(e) << ": " << e.what() << "\n";
return 1;
}
return 0;
}
<commit_msg>example: namespace<commit_after>#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <typeinfo>
#include <cxxabi.h>
#include <boost/scoped_array.hpp>
#include <concrete/context.hpp>
#include <concrete/exception.hpp>
#include <concrete/execute.hpp>
#include <concrete/objects/code.hpp>
using namespace concrete;
namespace example {
static CodeObject load_code()
{
std::ifstream stream;
stream.exceptions(std::ios::failbit | std::ios::badbit);
stream.open(EXAMPLE_BYTECODE);
stream.seekg(0, std::ios::end);
auto size = stream.tellg();
stream.seekg(0, std::ios::beg);
boost::scoped_array<char> buf(new char[size]);
stream.read(buf.get(), size);
stream.close();
return CodeObject::Load(buf.get(), size);
}
template <typename T>
static std::string type_name(const T &object)
{
auto c_str = abi::__cxa_demangle(typeid (object).name(), 0, 0, 0);
std::string str = c_str;
std::free(c_str);
return str;
}
static int main()
{
Context context;
ContextScope scope(context);
try {
Executor executor(load_code());
while (executor.execute())
;
} catch (const Exception &e) {
std::cerr << type_name(e) << ": " << e.what() << "\n";
return 1;
}
return 0;
}
} // namespace
int main()
{
return example::main();
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2014 Alexander Shafranov <shafranov@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <stdio.h>
#include <GL/glew.h>
#include <clew.h>
#ifdef _WIN32
#include <GL/wglew.h>
#endif
#include <GLFW/glfw3.h>
#include "corridormap/memory.h"
#include "corridormap/build.h"
#include "corridormap/render_gl.h"
struct glfw_context
{
bool ok;
glfw_context()
{
ok = (glfwInit() == GL_TRUE);
}
~glfw_context()
{
glfwTerminate();
}
};
struct glfw_window_context
{
GLFWwindow* window;
glfw_window_context(int width, int height, const char* title)
{
window = glfwCreateWindow(width, height, title, 0, 0);
}
~glfw_window_context()
{
glfwDestroyWindow(window);
}
};
namespace
{
const int screen_width = 720;
const int screen_height = 720;
// colors to use for diagram instead of indices.
unsigned colors[] =
{
0xffff0000, 0xff00ff00, 0xff0000ff, 0xffffff00, 0xffff00ff, 0xff00ffff, 0xff7f7f7f,
0xff800000, 0xff008000, 0xff000080, 0xff808000, 0xff800080, 0xff008080, 0xff808080,
0xffc00000, 0xff00c000, 0xff0000c0, 0xffc0c000, 0xffc000c0, 0xff00c0c0, 0xffc0c0c0,
0xff400000, 0xff004000, 0xff000040, 0xff404000, 0xff400040, 0xff004040, 0xff404040,
0xff200000, 0xff002000, 0xff000020, 0xff202000, 0xff200020, 0xff002020, 0xff202020,
0xff600000, 0xff006000, 0xff000060, 0xff606000, 0xff600060, 0xff006060, 0xff606060,
0xffa00000, 0xff00a000, 0xff0000a0, 0xffa0a000, 0xffa000a0, 0xff00a0a0, 0xffa0a0a0,
0xffe00000, 0xff00e000, 0xff0000e0, 0xffe0e000, 0xffe000e0, 0xff00e0e0, 0xffe0e0e0,
};
}
int main()
{
glfw_context glfw_ctx;
if (!glfw_ctx.ok)
{
fprintf(stderr, "failed to initialize GLFW context.\n");
return 1;
}
glfw_window_context glfw_window_ctx(screen_width, screen_height, "Voronoi");
GLFWwindow* window = glfw_window_ctx.window;
if (!window)
{
fprintf(stderr, "failed to create GLFW window.\n");
return 1;
}
glfwMakeContextCurrent(window);
glewInit();
const unsigned char* vendor = glGetString(GL_VENDOR);
const unsigned char* version = glGetString(GL_VERSION);
printf("opengl vendor=%s version=%s\n", vendor, version);
corridormap::memory_malloc mem;
float obstacle_verts_x[] = { 10.f, 50.f, 30.f, 70.f, 80.f, 90.f, 90.f, 80.f, 70.f, 60.f, 60.f, 10.f, 40.f, 40.f, 10.f, 50.f, 80.f, 70.f, };
float obstacle_verts_y[] = { 20.f, 20.f, 50.f, 20.f, 20.f, 30.f, 40.f, 50.f, 50.f, 40.f, 30.f, 70.f, 70.f, 90.f, 90.f, 70.f, 70.f, 80.f, };
int num_poly_verts[] = { 3, 8, 4, 3 };
corridormap::footprint obstacles;
obstacles.x = obstacle_verts_x;
obstacles.y = obstacle_verts_y;
obstacles.num_polys = 4;
obstacles.num_verts = sizeof(obstacle_verts_x)/sizeof(obstacle_verts_x[0]);
obstacles.num_poly_verts = num_poly_verts;
const float border = 10.f;
corridormap::bbox2 obstacle_bounds = corridormap::bounds(obstacles, border);
const float max_dist = corridormap::max_distance(obstacle_bounds);
const float max_error = 0.1f;
corridormap::distance_mesh mesh = corridormap::allocate_distance_mesh(&mem, obstacles, max_dist, max_error);
corridormap::build_distance_mesh(obstacles, obstacle_bounds, max_dist, max_error, mesh);
corridormap::set_segment_colors(mesh, colors, sizeof(colors)/sizeof(colors[0]));
corridormap::renderer_gl render_iface;
corridormap::renderer::parameters render_params;
render_params.render_target_width = screen_width;
render_params.render_target_height = screen_height;
render_params.min[0] = obstacle_bounds.min[0];
render_params.min[1] = obstacle_bounds.min[1];
render_params.max[0] = obstacle_bounds.max[0];
render_params.max[1] = obstacle_bounds.max[1];
render_params.far_plane = max_dist + 0.1f;
if (!render_iface.initialize(render_params, &mem))
{
fprintf(stderr, "failed to initialize render interface.\n");
render_iface.finalize();
return 1;
}
if (clewInit("OpenCL.dll") != CLEW_SUCCESS)
{
render_iface.finalize();
return 1;
}
render_iface.create_opencl_shared();
while (!glfwWindowShouldClose(window))
{
int width, height;
glfwGetFramebufferSize(window, &width, &height);
corridormap::render_distance_mesh(&render_iface, mesh);
glViewport(0, 0, width, height);
glClearColor(1.f, 1.f, 1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT);
render_iface.blit_frame_buffer(width, height);
glfwSwapBuffers(window);
glfwPollEvents();
}
render_iface.finalize();
corridormap::deallocate_distance_mesh(&mem, mesh);
return 0;
}
<commit_msg>moved clew initialization.<commit_after>//
// Copyright (c) 2014 Alexander Shafranov <shafranov@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <stdio.h>
#include <GL/glew.h>
#include <clew.h>
#ifdef _WIN32
#include <GL/wglew.h>
#endif
#include <GLFW/glfw3.h>
#include "corridormap/memory.h"
#include "corridormap/build.h"
#include "corridormap/render_gl.h"
struct glfw_context
{
bool ok;
glfw_context()
{
ok = (glfwInit() == GL_TRUE);
}
~glfw_context()
{
glfwTerminate();
}
};
struct glfw_window_context
{
GLFWwindow* window;
glfw_window_context(int width, int height, const char* title)
{
window = glfwCreateWindow(width, height, title, 0, 0);
}
~glfw_window_context()
{
glfwDestroyWindow(window);
}
};
namespace
{
const int screen_width = 720;
const int screen_height = 720;
// colors to use for diagram instead of indices.
unsigned colors[] =
{
0xffff0000, 0xff00ff00, 0xff0000ff, 0xffffff00, 0xffff00ff, 0xff00ffff, 0xff7f7f7f,
0xff800000, 0xff008000, 0xff000080, 0xff808000, 0xff800080, 0xff008080, 0xff808080,
0xffc00000, 0xff00c000, 0xff0000c0, 0xffc0c000, 0xffc000c0, 0xff00c0c0, 0xffc0c0c0,
0xff400000, 0xff004000, 0xff000040, 0xff404000, 0xff400040, 0xff004040, 0xff404040,
0xff200000, 0xff002000, 0xff000020, 0xff202000, 0xff200020, 0xff002020, 0xff202020,
0xff600000, 0xff006000, 0xff000060, 0xff606000, 0xff600060, 0xff006060, 0xff606060,
0xffa00000, 0xff00a000, 0xff0000a0, 0xffa0a000, 0xffa000a0, 0xff00a0a0, 0xffa0a0a0,
0xffe00000, 0xff00e000, 0xff0000e0, 0xffe0e000, 0xffe000e0, 0xff00e0e0, 0xffe0e0e0,
};
}
int main()
{
glfw_context glfw_ctx;
if (!glfw_ctx.ok)
{
fprintf(stderr, "failed to initialize GLFW context.\n");
return 1;
}
glfw_window_context glfw_window_ctx(screen_width, screen_height, "Voronoi");
GLFWwindow* window = glfw_window_ctx.window;
if (!window)
{
fprintf(stderr, "failed to create GLFW window.\n");
return 1;
}
glfwMakeContextCurrent(window);
glewInit();
if (clewInit("OpenCL.dll") != CLEW_SUCCESS)
{
return 1;
}
const unsigned char* vendor = glGetString(GL_VENDOR);
const unsigned char* version = glGetString(GL_VERSION);
printf("opengl vendor=%s version=%s\n", vendor, version);
corridormap::memory_malloc mem;
float obstacle_verts_x[] = { 10.f, 50.f, 30.f, 70.f, 80.f, 90.f, 90.f, 80.f, 70.f, 60.f, 60.f, 10.f, 40.f, 40.f, 10.f, 50.f, 80.f, 70.f, };
float obstacle_verts_y[] = { 20.f, 20.f, 50.f, 20.f, 20.f, 30.f, 40.f, 50.f, 50.f, 40.f, 30.f, 70.f, 70.f, 90.f, 90.f, 70.f, 70.f, 80.f, };
int num_poly_verts[] = { 3, 8, 4, 3 };
corridormap::footprint obstacles;
obstacles.x = obstacle_verts_x;
obstacles.y = obstacle_verts_y;
obstacles.num_polys = 4;
obstacles.num_verts = sizeof(obstacle_verts_x)/sizeof(obstacle_verts_x[0]);
obstacles.num_poly_verts = num_poly_verts;
const float border = 10.f;
corridormap::bbox2 obstacle_bounds = corridormap::bounds(obstacles, border);
const float max_dist = corridormap::max_distance(obstacle_bounds);
const float max_error = 0.1f;
corridormap::distance_mesh mesh = corridormap::allocate_distance_mesh(&mem, obstacles, max_dist, max_error);
corridormap::build_distance_mesh(obstacles, obstacle_bounds, max_dist, max_error, mesh);
corridormap::set_segment_colors(mesh, colors, sizeof(colors)/sizeof(colors[0]));
corridormap::renderer_gl render_iface;
corridormap::renderer::parameters render_params;
render_params.render_target_width = screen_width;
render_params.render_target_height = screen_height;
render_params.min[0] = obstacle_bounds.min[0];
render_params.min[1] = obstacle_bounds.min[1];
render_params.max[0] = obstacle_bounds.max[0];
render_params.max[1] = obstacle_bounds.max[1];
render_params.far_plane = max_dist + 0.1f;
if (!render_iface.initialize(render_params, &mem))
{
fprintf(stderr, "failed to initialize render interface.\n");
render_iface.finalize();
return 1;
}
render_iface.create_opencl_shared();
while (!glfwWindowShouldClose(window))
{
int width, height;
glfwGetFramebufferSize(window, &width, &height);
corridormap::render_distance_mesh(&render_iface, mesh);
glViewport(0, 0, width, height);
glClearColor(1.f, 1.f, 1.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT);
render_iface.blit_frame_buffer(width, height);
glfwSwapBuffers(window);
glfwPollEvents();
}
render_iface.finalize();
corridormap::deallocate_distance_mesh(&mem, mesh);
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2008-2016 the MRtrix3 contributors
*
* 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/
*
* MRtrix 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.
*
* For more details, see www.mrtrix.org
*
*/
#include "command.h"
#include "image.h"
#include "algo/loop.h"
#include "phase_encoding.h"
#include "progressbar.h"
#include "dwi/gradient.h"
using namespace MR;
using namespace App;
void usage () {
AUTHOR = "J-Donald Tournier (jdtournier@gmail.com)";
DESCRIPTION
+ "concatenate several images into one";
ARGUMENTS
+ Argument ("image1", "the first input image.")
.type_image_in()
+ Argument ("image2", "additional input image(s).")
.type_image_in()
.allow_multiple()
+ Argument ("output", "the output image.")
.type_image_out ();
OPTIONS
+ Option ("axis",
"specify axis along which concatenation should be performed. By default, "
"the program will use the last non-singleton, non-spatial axis of any of "
"the input images - in other words axis 3 or whichever axis (greater than 3) "
"of the input images has size greater than one.")
+ Argument ("axis").type_integer (0)
+ DataType::options();
}
typedef float value_type;
void run () {
int axis = get_option_value ("axis", -1);
int num_images = argument.size()-1;
std::vector<Header> in (num_images);
in[0] = Header::open (argument[0]);
int ndims = 0;
int last_dim;
for (int i = 1; i < num_images; i++) {
in[i] = Header::open (argument[i]);
for (last_dim = in[i].ndim()-1; in[i].size (last_dim) <= 1 && last_dim >= 0; last_dim--);
if (last_dim > ndims)
ndims = last_dim;
}
if (axis < 0) axis = std::max (3, ndims);
++ndims;
for (int i = 0; i < ndims; i++)
if (i != axis)
for (int n = 0; n < num_images; n++)
if (in[0].size (i) != in[n].size (i))
throw Exception ("dimensions of input images do not match");
if (axis >= ndims) ndims = axis+1;
Header header_out (in[0]);
header_out.ndim() = ndims;
for (size_t i = 0; i < header_out.ndim(); i++) {
if (header_out.size (i) <= 1) {
for (int n = 0; n < num_images; n++) {
if (in[n].ndim() > i) {
header_out.size(i) = in[n].size (i);
header_out.spacing(i) = in[n].spacing (i);
break;
}
}
}
}
{
size_t axis_dim = 0;
for (int n = 0; n < num_images; n++) {
if (in[n].datatype().is_complex())
header_out.datatype() = DataType::CFloat32;
axis_dim += in[n].ndim() > size_t (axis) ? (in[n].size (axis) > 1 ? in[n].size (axis) : 1) : 1;
}
header_out.size (axis) = axis_dim;
}
header_out.datatype() = DataType::from_command_line (header_out.datatype());
if (axis > 2) {
// concatenate DW schemes
ssize_t nrows = 0, ncols = 0;
std::vector<Eigen::MatrixXd> input_grads;
for (int n = 0; n < num_images; ++n) {
auto grad = DWI::get_DW_scheme (in[n]);
if (grad.rows() == 0 || grad.cols() < 4) {
nrows = 0;
break;
}
if (!ncols) {
ncols = grad.cols();
} else if (grad.cols() != ncols) {
nrows = 0;
break;
}
nrows += grad.rows();
input_grads.push_back (std::move (grad));
}
if (nrows) {
Eigen::MatrixXd grad_out (nrows, 4);
int row = 0;
for (int n = 0; n < num_images; ++n) {
for (ssize_t i = 0; i < input_grads[n].rows(); ++i, ++row)
grad_out.row(row) = input_grads[n].row(i);
}
DWI::set_DW_scheme (header_out, grad_out);
} else {
header_out.keyval().erase ("dw_scheme");
}
// concatenate PE schemes
nrows = 0; ncols = 0;
std::vector<Eigen::MatrixXd> input_schemes;
for (int n = 0; n != num_images; ++n) {
auto scheme = PhaseEncoding::parse_scheme (in[n]);
if (!scheme.rows()) {
nrows = 0;
break;
}
if (!ncols) {
ncols = scheme.cols();
} else if (scheme.cols() != ncols) {
nrows = 0;
break;
}
nrows += scheme.rows();
input_schemes.push_back (std::move (scheme));
}
Eigen::MatrixXd scheme_out;
if (nrows) {
scheme_out.resize (nrows, ncols);
size_t row = 0;
for (int n = 0; n != num_images; ++n) {
for (ssize_t i = 0; i != input_grads[n].rows(); ++i, ++row)
scheme_out.row(row) = input_grads[n].row(i);
}
}
PhaseEncoding::set_scheme (header_out, scheme_out);
}
auto image_out = Image<value_type>::create (argument[num_images], header_out);
int axis_offset = 0;
for (int i = 0; i < num_images; i++) {
auto image_in = in[i].get_image<value_type>();
auto copy_func = [&axis, &axis_offset](decltype(image_in)& in, decltype(image_out)& out)
{
out.index (axis) = axis < int(in.ndim()) ? in.index (axis) + axis_offset : axis_offset;
out.value() = in.value();
};
ThreadedLoop ("concatenating \"" + image_in.name() + "\"...", image_in, 0, std::min<size_t> (image_in.ndim(), image_out.ndim()))
.run (copy_func, image_in, image_out);
if (axis < int(image_in.ndim()))
axis_offset += image_in.size (axis);
else {
++axis_offset;
image_out.index (axis) = axis_offset;
}
}
}
<commit_msg>mrcat: Fix concatenation of phase encoding schemes<commit_after>/*
* Copyright (c) 2008-2016 the MRtrix3 contributors
*
* 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/
*
* MRtrix 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.
*
* For more details, see www.mrtrix.org
*
*/
#include "command.h"
#include "image.h"
#include "algo/loop.h"
#include "phase_encoding.h"
#include "progressbar.h"
#include "dwi/gradient.h"
using namespace MR;
using namespace App;
void usage () {
AUTHOR = "J-Donald Tournier (jdtournier@gmail.com)";
DESCRIPTION
+ "concatenate several images into one";
ARGUMENTS
+ Argument ("image1", "the first input image.")
.type_image_in()
+ Argument ("image2", "additional input image(s).")
.type_image_in()
.allow_multiple()
+ Argument ("output", "the output image.")
.type_image_out ();
OPTIONS
+ Option ("axis",
"specify axis along which concatenation should be performed. By default, "
"the program will use the last non-singleton, non-spatial axis of any of "
"the input images - in other words axis 3 or whichever axis (greater than 3) "
"of the input images has size greater than one.")
+ Argument ("axis").type_integer (0)
+ DataType::options();
}
typedef float value_type;
void run () {
int axis = get_option_value ("axis", -1);
int num_images = argument.size()-1;
std::vector<Header> in (num_images);
in[0] = Header::open (argument[0]);
int ndims = 0;
int last_dim;
for (int i = 1; i < num_images; i++) {
in[i] = Header::open (argument[i]);
for (last_dim = in[i].ndim()-1; in[i].size (last_dim) <= 1 && last_dim >= 0; last_dim--);
if (last_dim > ndims)
ndims = last_dim;
}
if (axis < 0) axis = std::max (3, ndims);
++ndims;
for (int i = 0; i < ndims; i++)
if (i != axis)
for (int n = 0; n < num_images; n++)
if (in[0].size (i) != in[n].size (i))
throw Exception ("dimensions of input images do not match");
if (axis >= ndims) ndims = axis+1;
Header header_out (in[0]);
header_out.ndim() = ndims;
for (size_t i = 0; i < header_out.ndim(); i++) {
if (header_out.size (i) <= 1) {
for (int n = 0; n < num_images; n++) {
if (in[n].ndim() > i) {
header_out.size(i) = in[n].size (i);
header_out.spacing(i) = in[n].spacing (i);
break;
}
}
}
}
{
size_t axis_dim = 0;
for (int n = 0; n < num_images; n++) {
if (in[n].datatype().is_complex())
header_out.datatype() = DataType::CFloat32;
axis_dim += in[n].ndim() > size_t (axis) ? (in[n].size (axis) > 1 ? in[n].size (axis) : 1) : 1;
}
header_out.size (axis) = axis_dim;
}
header_out.datatype() = DataType::from_command_line (header_out.datatype());
if (axis > 2) {
// concatenate DW schemes
ssize_t nrows = 0, ncols = 0;
std::vector<Eigen::MatrixXd> input_grads;
for (int n = 0; n < num_images; ++n) {
auto grad = DWI::get_DW_scheme (in[n]);
if (grad.rows() == 0 || grad.cols() < 4) {
nrows = 0;
break;
}
if (!ncols) {
ncols = grad.cols();
} else if (grad.cols() != ncols) {
nrows = 0;
break;
}
nrows += grad.rows();
input_grads.push_back (std::move (grad));
}
if (nrows) {
Eigen::MatrixXd grad_out (nrows, 4);
int row = 0;
for (int n = 0; n < num_images; ++n) {
for (ssize_t i = 0; i < input_grads[n].rows(); ++i, ++row)
grad_out.row(row) = input_grads[n].row(i);
}
DWI::set_DW_scheme (header_out, grad_out);
} else {
header_out.keyval().erase ("dw_scheme");
}
// concatenate PE schemes
nrows = 0; ncols = 0;
std::vector<Eigen::MatrixXd> input_schemes;
for (int n = 0; n != num_images; ++n) {
auto scheme = PhaseEncoding::parse_scheme (in[n]);
if (!scheme.rows()) {
nrows = 0;
break;
}
if (!ncols) {
ncols = scheme.cols();
} else if (scheme.cols() != ncols) {
nrows = 0;
break;
}
nrows += scheme.rows();
input_schemes.push_back (std::move (scheme));
}
Eigen::MatrixXd scheme_out;
if (nrows) {
scheme_out.resize (nrows, ncols);
size_t row = 0;
for (int n = 0; n != num_images; ++n) {
for (ssize_t i = 0; i != input_schemes[n].rows(); ++i, ++row)
scheme_out.row(row) = input_schemes[n].row(i);
}
}
PhaseEncoding::set_scheme (header_out, scheme_out);
}
auto image_out = Image<value_type>::create (argument[num_images], header_out);
int axis_offset = 0;
for (int i = 0; i < num_images; i++) {
auto image_in = in[i].get_image<value_type>();
auto copy_func = [&axis, &axis_offset](decltype(image_in)& in, decltype(image_out)& out)
{
out.index (axis) = axis < int(in.ndim()) ? in.index (axis) + axis_offset : axis_offset;
out.value() = in.value();
};
ThreadedLoop ("concatenating \"" + image_in.name() + "\"...", image_in, 0, std::min<size_t> (image_in.ndim(), image_out.ndim()))
.run (copy_func, image_in, image_out);
if (axis < int(image_in.ndim()))
axis_offset += image_in.size (axis);
else {
++axis_offset;
image_out.index (axis) = axis_offset;
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2006 Zack Rusin <zack@kde.org>
* Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
*
* 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 COMPUTER, 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 COMPUTER, 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 "ChromeClientQt.h"
#include "Frame.h"
#include "FrameLoadRequest.h"
#include "FrameLoader.h"
#include "FrameLoaderClientQt.h"
#include "FrameView.h"
#include "HitTestResult.h"
#include "NotImplemented.h"
#include "WindowFeatures.h"
#include "qwebpage.h"
#include "qwebpage_p.h"
#include "qwebframe_p.h"
#include <qtooltip.h>
namespace WebCore
{
ChromeClientQt::ChromeClientQt(QWebPage* webPage)
: m_webPage(webPage)
{
toolBarsVisible = statusBarVisible = menuBarVisible = true;
}
ChromeClientQt::~ChromeClientQt()
{
}
void ChromeClientQt::setWindowRect(const FloatRect& rect)
{
if (!m_webPage)
return;
emit m_webPage->geometryChangeRequested(QRect(qRound(rect.x()), qRound(rect.y()),
qRound(rect.width()), qRound(rect.height())));
}
FloatRect ChromeClientQt::windowRect()
{
if (!m_webPage)
return FloatRect();
QWidget* view = m_webPage->view();
if (!view)
return FloatRect();
return IntRect(view->topLevelWidget()->geometry());
}
FloatRect ChromeClientQt::pageRect()
{
if (!m_webPage)
return FloatRect();
return FloatRect(QRectF(QPointF(0,0), m_webPage->viewportSize()));
}
float ChromeClientQt::scaleFactor()
{
notImplemented();
return 1;
}
void ChromeClientQt::focus()
{
if (!m_webPage)
return;
QWidget* view = m_webPage->view();
if (!view)
return;
view->setFocus();
}
void ChromeClientQt::unfocus()
{
if (!m_webPage)
return;
QWidget* view = m_webPage->view();
if (!view)
return;
view->clearFocus();
}
bool ChromeClientQt::canTakeFocus(FocusDirection)
{
// This is called when cycling through links/focusable objects and we
// reach the last focusable object. Then we want to claim that we can
// take the focus to avoid wrapping.
return true;
}
void ChromeClientQt::takeFocus(FocusDirection)
{
// don't do anything. This is only called when cycling to links/focusable objects,
// which in turn is called from focusNextPrevChild. We let focusNextPrevChild
// call QWidget::focusNextPrevChild accordingly, so there is no need to do anything
// here.
}
Page* ChromeClientQt::createWindow(Frame*, const FrameLoadRequest& request, const WindowFeatures& features)
{
QWebPage *newPage = m_webPage->createWindow(features.dialog ? QWebPage::WebModalDialog : QWebPage::WebBrowserWindow);
if (!newPage)
return 0;
newPage->mainFrame()->load(request.resourceRequest().url());
return newPage->d->page;
}
void ChromeClientQt::show()
{
if (!m_webPage)
return;
QWidget* view = m_webPage->view();
if (!view)
return;
view->topLevelWidget()->show();
}
bool ChromeClientQt::canRunModal()
{
notImplemented();
return false;
}
void ChromeClientQt::runModal()
{
notImplemented();
}
void ChromeClientQt::setToolbarsVisible(bool visible)
{
toolBarsVisible = visible;
emit m_webPage->toolBarVisibilityChangeRequested(visible);
}
bool ChromeClientQt::toolbarsVisible()
{
return toolBarsVisible;
}
void ChromeClientQt::setStatusbarVisible(bool visible)
{
emit m_webPage->statusBarVisibilityChangeRequested(visible);
statusBarVisible = visible;
}
bool ChromeClientQt::statusbarVisible()
{
return statusBarVisible;
return false;
}
void ChromeClientQt::setScrollbarsVisible(bool)
{
notImplemented();
}
bool ChromeClientQt::scrollbarsVisible()
{
notImplemented();
return true;
}
void ChromeClientQt::setMenubarVisible(bool visible)
{
menuBarVisible = visible;
emit m_webPage->menuBarVisibilityChangeRequested(visible);
}
bool ChromeClientQt::menubarVisible()
{
return menuBarVisible;
}
void ChromeClientQt::setResizable(bool)
{
notImplemented();
}
void ChromeClientQt::addMessageToConsole(const String& message, unsigned int lineNumber,
const String& sourceID)
{
QString x = message;
QString y = sourceID;
m_webPage->javaScriptConsoleMessage(x, lineNumber, y);
}
void ChromeClientQt::chromeDestroyed()
{
delete this;
}
bool ChromeClientQt::canRunBeforeUnloadConfirmPanel()
{
return true;
}
bool ChromeClientQt::runBeforeUnloadConfirmPanel(const String& message, Frame* frame)
{
return runJavaScriptConfirm(frame, message);
}
void ChromeClientQt::closeWindowSoon()
{
m_webPage->mainFrame()->d->frame->loader()->stopAllLoaders();
emit m_webPage->windowCloseRequested();
}
void ChromeClientQt::runJavaScriptAlert(Frame* f, const String& msg)
{
QString x = msg;
FrameLoaderClientQt *fl = static_cast<FrameLoaderClientQt*>(f->loader()->client());
m_webPage->javaScriptAlert(fl->webFrame(), x);
}
bool ChromeClientQt::runJavaScriptConfirm(Frame* f, const String& msg)
{
QString x = msg;
FrameLoaderClientQt *fl = static_cast<FrameLoaderClientQt*>(f->loader()->client());
return m_webPage->javaScriptConfirm(fl->webFrame(), x);
}
bool ChromeClientQt::runJavaScriptPrompt(Frame* f, const String& message, const String& defaultValue, String& result)
{
QString x = result;
FrameLoaderClientQt *fl = static_cast<FrameLoaderClientQt*>(f->loader()->client());
bool rc = m_webPage->javaScriptPrompt(fl->webFrame(), (QString)message, (QString)defaultValue, &x);
result = x;
return rc;
}
void ChromeClientQt::setStatusbarText(const String& msg)
{
QString x = msg;
emit m_webPage->statusBarMessage(x);
}
bool ChromeClientQt::shouldInterruptJavaScript()
{
notImplemented();
return false;
}
bool ChromeClientQt::tabsToLinks() const
{
return m_webPage->settings()->testAttribute(QWebSettings::LinksIncludedInFocusChain);
}
IntRect ChromeClientQt::windowResizerRect() const
{
return IntRect();
}
void ChromeClientQt::repaint(const IntRect& windowRect, bool contentChanged, bool immediate, bool repaintContentOnly)
{
// No double buffer, so only update the QWidget if content changed.
if (contentChanged) {
QWidget* view = m_webPage->view();
if (view) {
QRect rect(windowRect);
rect = rect.intersected(QRect(QPoint(0, 0), m_webPage->viewportSize()));
if (!windowRect.isEmpty())
view->update(windowRect);
} else
emit m_webPage->repaintRequested(windowRect);
}
// FIXME: There is no "immediate" support for window painting. This should be done always whenever the flag
// is set.
}
void ChromeClientQt::scroll(const IntSize& delta, const IntRect& scrollViewRect, const IntRect&)
{
QWidget* view = m_webPage->view();
if (view)
view->scroll(delta.width(), delta.height(), scrollViewRect);
else
emit m_webPage->scrollRequested(delta.width(), delta.height(), scrollViewRect);
}
IntRect ChromeClientQt::windowToScreen(const IntRect& rect) const
{
notImplemented();
return rect;
}
IntPoint ChromeClientQt::screenToWindow(const IntPoint& point) const
{
notImplemented();
return point;
}
PlatformWidget WebChromeClient::platformWindow() const
{
return m_webPage->view();
}
void ChromeClientQt::mouseDidMoveOverElement(const HitTestResult& result, unsigned modifierFlags)
{
if (result.absoluteLinkURL() != lastHoverURL
|| result.title() != lastHoverTitle
|| result.textContent() != lastHoverContent) {
lastHoverURL = result.absoluteLinkURL();
lastHoverTitle = result.title();
lastHoverContent = result.textContent();
emit m_webPage->linkHovered(lastHoverURL.prettyURL(),
lastHoverTitle, lastHoverContent);
}
}
void ChromeClientQt::setToolTip(const String &tip)
{
#ifndef QT_NO_TOOLTIP
QWidget* view = m_webPage->view();
if (!view)
return;
if (tip.isEmpty()) {
view->setToolTip(QString());
QToolTip::hideText();
} else {
QString dtip = QLatin1String("<p>") + tip + QLatin1String("</p>");
view->setToolTip(dtip);
}
#else
Q_UNUSED(tip);
#endif
}
void ChromeClientQt::print(Frame *frame)
{
emit m_webPage->printRequested(QWebFramePrivate::kit(frame));
}
void ChromeClientQt::exceededDatabaseQuota(Frame*, const String&)
{
notImplemented();
}
}
<commit_msg>Fix Qt bustage.<commit_after>/*
* Copyright (C) 2006 Zack Rusin <zack@kde.org>
* Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
*
* 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 COMPUTER, 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 COMPUTER, 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 "ChromeClientQt.h"
#include "Frame.h"
#include "FrameLoadRequest.h"
#include "FrameLoader.h"
#include "FrameLoaderClientQt.h"
#include "FrameView.h"
#include "HitTestResult.h"
#include "NotImplemented.h"
#include "WindowFeatures.h"
#include "qwebpage.h"
#include "qwebpage_p.h"
#include "qwebframe_p.h"
#include <qtooltip.h>
namespace WebCore
{
ChromeClientQt::ChromeClientQt(QWebPage* webPage)
: m_webPage(webPage)
{
toolBarsVisible = statusBarVisible = menuBarVisible = true;
}
ChromeClientQt::~ChromeClientQt()
{
}
void ChromeClientQt::setWindowRect(const FloatRect& rect)
{
if (!m_webPage)
return;
emit m_webPage->geometryChangeRequested(QRect(qRound(rect.x()), qRound(rect.y()),
qRound(rect.width()), qRound(rect.height())));
}
FloatRect ChromeClientQt::windowRect()
{
if (!m_webPage)
return FloatRect();
QWidget* view = m_webPage->view();
if (!view)
return FloatRect();
return IntRect(view->topLevelWidget()->geometry());
}
FloatRect ChromeClientQt::pageRect()
{
if (!m_webPage)
return FloatRect();
return FloatRect(QRectF(QPointF(0,0), m_webPage->viewportSize()));
}
float ChromeClientQt::scaleFactor()
{
notImplemented();
return 1;
}
void ChromeClientQt::focus()
{
if (!m_webPage)
return;
QWidget* view = m_webPage->view();
if (!view)
return;
view->setFocus();
}
void ChromeClientQt::unfocus()
{
if (!m_webPage)
return;
QWidget* view = m_webPage->view();
if (!view)
return;
view->clearFocus();
}
bool ChromeClientQt::canTakeFocus(FocusDirection)
{
// This is called when cycling through links/focusable objects and we
// reach the last focusable object. Then we want to claim that we can
// take the focus to avoid wrapping.
return true;
}
void ChromeClientQt::takeFocus(FocusDirection)
{
// don't do anything. This is only called when cycling to links/focusable objects,
// which in turn is called from focusNextPrevChild. We let focusNextPrevChild
// call QWidget::focusNextPrevChild accordingly, so there is no need to do anything
// here.
}
Page* ChromeClientQt::createWindow(Frame*, const FrameLoadRequest& request, const WindowFeatures& features)
{
QWebPage *newPage = m_webPage->createWindow(features.dialog ? QWebPage::WebModalDialog : QWebPage::WebBrowserWindow);
if (!newPage)
return 0;
newPage->mainFrame()->load(request.resourceRequest().url());
return newPage->d->page;
}
void ChromeClientQt::show()
{
if (!m_webPage)
return;
QWidget* view = m_webPage->view();
if (!view)
return;
view->topLevelWidget()->show();
}
bool ChromeClientQt::canRunModal()
{
notImplemented();
return false;
}
void ChromeClientQt::runModal()
{
notImplemented();
}
void ChromeClientQt::setToolbarsVisible(bool visible)
{
toolBarsVisible = visible;
emit m_webPage->toolBarVisibilityChangeRequested(visible);
}
bool ChromeClientQt::toolbarsVisible()
{
return toolBarsVisible;
}
void ChromeClientQt::setStatusbarVisible(bool visible)
{
emit m_webPage->statusBarVisibilityChangeRequested(visible);
statusBarVisible = visible;
}
bool ChromeClientQt::statusbarVisible()
{
return statusBarVisible;
return false;
}
void ChromeClientQt::setScrollbarsVisible(bool)
{
notImplemented();
}
bool ChromeClientQt::scrollbarsVisible()
{
notImplemented();
return true;
}
void ChromeClientQt::setMenubarVisible(bool visible)
{
menuBarVisible = visible;
emit m_webPage->menuBarVisibilityChangeRequested(visible);
}
bool ChromeClientQt::menubarVisible()
{
return menuBarVisible;
}
void ChromeClientQt::setResizable(bool)
{
notImplemented();
}
void ChromeClientQt::addMessageToConsole(const String& message, unsigned int lineNumber,
const String& sourceID)
{
QString x = message;
QString y = sourceID;
m_webPage->javaScriptConsoleMessage(x, lineNumber, y);
}
void ChromeClientQt::chromeDestroyed()
{
delete this;
}
bool ChromeClientQt::canRunBeforeUnloadConfirmPanel()
{
return true;
}
bool ChromeClientQt::runBeforeUnloadConfirmPanel(const String& message, Frame* frame)
{
return runJavaScriptConfirm(frame, message);
}
void ChromeClientQt::closeWindowSoon()
{
m_webPage->mainFrame()->d->frame->loader()->stopAllLoaders();
emit m_webPage->windowCloseRequested();
}
void ChromeClientQt::runJavaScriptAlert(Frame* f, const String& msg)
{
QString x = msg;
FrameLoaderClientQt *fl = static_cast<FrameLoaderClientQt*>(f->loader()->client());
m_webPage->javaScriptAlert(fl->webFrame(), x);
}
bool ChromeClientQt::runJavaScriptConfirm(Frame* f, const String& msg)
{
QString x = msg;
FrameLoaderClientQt *fl = static_cast<FrameLoaderClientQt*>(f->loader()->client());
return m_webPage->javaScriptConfirm(fl->webFrame(), x);
}
bool ChromeClientQt::runJavaScriptPrompt(Frame* f, const String& message, const String& defaultValue, String& result)
{
QString x = result;
FrameLoaderClientQt *fl = static_cast<FrameLoaderClientQt*>(f->loader()->client());
bool rc = m_webPage->javaScriptPrompt(fl->webFrame(), (QString)message, (QString)defaultValue, &x);
result = x;
return rc;
}
void ChromeClientQt::setStatusbarText(const String& msg)
{
QString x = msg;
emit m_webPage->statusBarMessage(x);
}
bool ChromeClientQt::shouldInterruptJavaScript()
{
notImplemented();
return false;
}
bool ChromeClientQt::tabsToLinks() const
{
return m_webPage->settings()->testAttribute(QWebSettings::LinksIncludedInFocusChain);
}
IntRect ChromeClientQt::windowResizerRect() const
{
return IntRect();
}
void ChromeClientQt::repaint(const IntRect& windowRect, bool contentChanged, bool immediate, bool repaintContentOnly)
{
// No double buffer, so only update the QWidget if content changed.
if (contentChanged) {
QWidget* view = m_webPage->view();
if (view) {
QRect rect(windowRect);
rect = rect.intersected(QRect(QPoint(0, 0), m_webPage->viewportSize()));
if (!windowRect.isEmpty())
view->update(windowRect);
} else
emit m_webPage->repaintRequested(windowRect);
}
// FIXME: There is no "immediate" support for window painting. This should be done always whenever the flag
// is set.
}
void ChromeClientQt::scroll(const IntSize& delta, const IntRect& scrollViewRect, const IntRect&)
{
QWidget* view = m_webPage->view();
if (view)
view->scroll(delta.width(), delta.height(), scrollViewRect);
else
emit m_webPage->scrollRequested(delta.width(), delta.height(), scrollViewRect);
}
IntRect ChromeClientQt::windowToScreen(const IntRect& rect) const
{
notImplemented();
return rect;
}
IntPoint ChromeClientQt::screenToWindow(const IntPoint& point) const
{
notImplemented();
return point;
}
PlatformWidget ChromeClientQt::platformWindow() const
{
return m_webPage->view();
}
void ChromeClientQt::mouseDidMoveOverElement(const HitTestResult& result, unsigned modifierFlags)
{
if (result.absoluteLinkURL() != lastHoverURL
|| result.title() != lastHoverTitle
|| result.textContent() != lastHoverContent) {
lastHoverURL = result.absoluteLinkURL();
lastHoverTitle = result.title();
lastHoverContent = result.textContent();
emit m_webPage->linkHovered(lastHoverURL.prettyURL(),
lastHoverTitle, lastHoverContent);
}
}
void ChromeClientQt::setToolTip(const String &tip)
{
#ifndef QT_NO_TOOLTIP
QWidget* view = m_webPage->view();
if (!view)
return;
if (tip.isEmpty()) {
view->setToolTip(QString());
QToolTip::hideText();
} else {
QString dtip = QLatin1String("<p>") + tip + QLatin1String("</p>");
view->setToolTip(dtip);
}
#else
Q_UNUSED(tip);
#endif
}
void ChromeClientQt::print(Frame *frame)
{
emit m_webPage->printRequested(QWebFramePrivate::kit(frame));
}
void ChromeClientQt::exceededDatabaseQuota(Frame*, const String&)
{
notImplemented();
}
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2013 Slawomir Cygan <slawomir.cygan@gmail.com>
*
* 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 "gl-auxcontext.h"
#include "gl-state.h"
#include "display.h"
#include "native-surface.h"
#include "pointers.h"
#include <sstream>
namespace dglState {
GLAuxContextSession::GLAuxContextSession(GLAuxContext* ctx) : m_ctx(ctx) {
m_ctx->doRefCurrent();
}
GLAuxContextSession::~GLAuxContextSession() { m_ctx->doUnrefCurrent(); }
GLAuxContextSurface::GLAuxContextSurface(const DGLDisplayState* display,
opaque_id_t pixfmt)
: m_DisplayId(display->getId()), m_Id(0) {
EGLint attributes[] = {EGL_HEIGHT, 1, EGL_WIDTH, 1, EGL_NONE};
m_Id = (opaque_id_t)DIRECT_CALL_CHK(eglCreatePbufferSurface)(
(EGLDisplay)m_DisplayId, (EGLConfig)pixfmt, attributes);
if (!m_Id) {
throw std::runtime_error("Cannot allocate axualiary pbuffer surface");
}
}
GLAuxContextSurface::~GLAuxContextSurface() {
if (m_Id) {
DIRECT_CALL_CHK(eglDestroySurface)((EGLDisplay)m_DisplayId,
(EGLSurface)m_Id);
}
}
opaque_id_t GLAuxContextSurface::getId() const { return m_Id; }
GLAuxContext::GLAuxContext(const GLContext* origCtx)
: queries(this),
m_Id(0),
m_PixelFormat(0),
m_Parrent(origCtx),
m_MakeCurrentRef(0) {
if (m_Parrent->getDisplay()->getType() != DGLDisplayState::Type::EGL) {
throw std::runtime_error("auxaliary contexts implemented only for EGL");
}
std::vector<EGLint> eglAttributes(
m_Parrent->getContextCreationData().getAttribs().size());
for (size_t i = 0;
i < m_Parrent->getContextCreationData().getAttribs().size(); i++) {
eglAttributes[i] =
(EGLint)m_Parrent->getContextCreationData().getAttribs()[i];
}
eglAttributes.push_back(EGL_NONE);
m_PixelFormat = choosePixelFormat(
m_Parrent->getContextCreationData().getPixelFormat(),
m_Parrent->getDisplay()->getId());
switch (origCtx->getContextCreationData().getEntryPoint()) {
case eglCreateContext_Call:
m_Id = (opaque_id_t)DIRECT_CALL_CHK(eglCreateContext)(
(EGLDisplay)m_Parrent->getDisplay()->getId(),
(EGLConfig)m_PixelFormat, (EGLContext)m_Parrent->getId(),
&eglAttributes[0]);
break;
}
if (!m_Id) {
throw std::runtime_error("Cannot allocate auxaliary context");
}
}
GLAuxContext::~GLAuxContext() {
while (m_MakeCurrentRef) {
doUnrefCurrent();
}
if (m_Id) {
DIRECT_CALL_CHK(eglDestroyContext)(
(EGLDisplay)m_Parrent->getDisplay()->getId(), (EGLContext)m_Id);
}
}
GLAuxContextSession GLAuxContext::makeCurrent() {
return GLAuxContextSession(this);
}
void GLAuxContext::doRefCurrent() {
if (!m_MakeCurrentRef) {
if (!m_AuxSurface) {
m_AuxSurface = std::make_shared<GLAuxContextSurface>(
m_Parrent->getDisplay(), m_PixelFormat);
}
EGLBoolean status = DIRECT_CALL_CHK(eglMakeCurrent)(
(EGLDisplay)m_Parrent->getDisplay()->getId(),
(EGLSurface)m_AuxSurface->getId(),
(EGLSurface)m_AuxSurface->getId(), (EGLContext)m_Id);
if (!status) {
throw std::runtime_error("Cannot switch to auxaliary context.");
}
queries.setupInitialState();
}
m_MakeCurrentRef++;
}
void GLAuxContext::doUnrefCurrent() {
if (m_MakeCurrentRef) {
m_MakeCurrentRef--;
}
if (!m_MakeCurrentRef) {
EGLBoolean status = DIRECT_CALL_CHK(eglMakeCurrent)(
(EGLDisplay)m_Parrent->getDisplay()->getId(),
(EGLSurface)m_Parrent->getNativeDrawSurface()->getId(),
(EGLSurface)m_Parrent->getNativeReadSurface()->getId(),
(EGLContext)m_Parrent->getId());
if (!status) {
throw std::runtime_error(
"Cannot switch back from auxaliary context.");
}
}
}
opaque_id_t GLAuxContext::choosePixelFormat(opaque_id_t preferred,
opaque_id_t displayId) {
EGLDisplay eglDpy = (EGLDisplay)displayId;
EGLConfig preferredConfig = (EGLConfig)preferred;
EGLint supportedSurfType = 0;
EGLBoolean status = EGL_TRUE;
status &= DIRECT_CALL_CHK(eglGetConfigAttrib)(
eglDpy, preferredConfig, EGL_SURFACE_TYPE, &supportedSurfType);
if (!status) {
throw std::runtime_error("Cannot query EGLConfig associated with ctx");
}
EGLConfig ret;
if (supportedSurfType & EGL_PBUFFER_BIT) {
ret = preferredConfig;
} else {
EGLint renderableType = 0;
if (m_Parrent->getVersion().check(GLContextVersion::Type::DT)) {
renderableType = EGL_OPENGL_BIT;
} else if (m_Parrent->getVersion().check(GLContextVersion::Type::ES,
3)) {
renderableType = EGL_OPENGL_ES3_BIT_KHR;
} else if (m_Parrent->getVersion().check(GLContextVersion::Type::ES,
2)) {
renderableType = EGL_OPENGL_ES2_BIT;
} else if (m_Parrent->getVersion().check(GLContextVersion::Type::ES,
1)) {
renderableType = EGL_OPENGL_ES_BIT;
}
EGLint attributes[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
EGL_RENDERABLE_TYPE, renderableType,
EGL_NONE};
EGLint numConfigs = 0;
status &= DIRECT_CALL_CHK(eglChooseConfig)(eglDpy, attributes, &ret, 1,
&numConfigs);
if ((status != EGL_TRUE) || numConfigs < 1) {
throw std::runtime_error(
"Cannot choose EGLConfig capable of driving auxaliary "
"context");
}
}
return (opaque_id_t)ret;
}
GLAuxContext::GLQueries::GLQueries(GLAuxContext* ctx)
: m_InitialState(false), m_AuxCtx(ctx) {}
void GLAuxContext::GLQueries::setupInitialState() {
if (m_InitialState) return DIRECT_CALL_CHK(glGenFramebuffers)(1, &fbo);
DIRECT_CALL_CHK(glBindFramebuffer)(GL_FRAMEBUFFER, fbo);
DIRECT_CALL_CHK(glGenRenderbuffers)(1, &rbo);
DIRECT_CALL_CHK(glBindRenderbuffer)(GL_RENDERBUFFER, rbo);
DIRECT_CALL_CHK(glFramebufferRenderbuffer)(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo);
if (m_AuxCtx->m_Parrent->getVersion().check(GLContextVersion::Type::ES,
3) ||
m_AuxCtx->m_Parrent->getVersion().check(GLContextVersion::Type::DT,
3)) {
DIRECT_CALL_CHK(glGenVertexArrays)(1, &vao);
DIRECT_CALL_CHK(glBindVertexArray)(vao);
}
DIRECT_CALL_CHK(glGenBuffers)(1, &vbo);
DIRECT_CALL_CHK(glBindBuffer)(GL_ARRAY_BUFFER, vbo);
GLfloat triangleStrip[] = {-1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f,
0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
1.0f, -1.0f, 0.0f, 1.0f};
DIRECT_CALL_CHK(glBufferData)(GL_ARRAY_BUFFER, sizeof(triangleStrip),
triangleStrip, GL_STATIC_DRAW);
DIRECT_CALL_CHK(glVertexAttribPointer)(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);
DIRECT_CALL_CHK(glEnableVertexAttribArray)(0);
vshobj = DIRECT_CALL_CHK(glCreateShader)(GL_VERTEX_SHADER);
const char* vsh =
"attribute vec4 inPos;\n"
"varying vec2 texPos;\n"
"void main() {\n"
" gl_Position = inPos;\n"
" texPos = inPos.xy * 0.5 + 0.5;\n"
"}\n";
DIRECT_CALL_CHK(glShaderSource)(vshobj, 1, &vsh, NULL);
DIRECT_CALL_CHK(glCompileShader)(vshobj);
GLint status = 0;
DIRECT_CALL_CHK(glGetShaderiv)(vshobj, GL_COMPILE_STATUS, &status);
if (!status) {
char log[1000];
DIRECT_CALL_CHK(glGetShaderInfoLog)(vshobj, 1000, NULL, log);
throw std::runtime_error(std::string("Cannot compile vertex shader") +
log);
}
if (DIRECT_CALL_CHK(glGetError)() != GL_NO_ERROR) {
throw std::runtime_error("Got GL error on auxiliary context");
}
m_InitialState = true;
}
void GLAuxContext::GLQueries::auxDrawTexture(GLuint name, GLenum target,
GLint level,
GLenum textureBaseFormat,
GLenum renderableFormat, int width,
int height) {
if (!m_AuxCtx->m_Parrent->getVersion().check(GLContextVersion::Type::ES,
2)) {
throw std::runtime_error(
"GLAuxContext::GLQueries::auxGetTexImage not implemented for "
"this "
"context version");
}
if (!DIRECT_CALL_CHK(glIsTexture)(name)) {
throw std::runtime_error(
"Texture object not found in auxaliary context");
}
DIRECT_CALL_CHK(glBindTexture)(target, name);
DIRECT_CALL_CHK(glRenderbufferStorage)(GL_RENDERBUFFER, renderableFormat, width,
height);
GLuint program = getTextureShaderProgram(target, textureBaseFormat);
DIRECT_CALL_CHK(glUseProgram)(program);
DIRECT_CALL_CHK(glUniform1f)(
DIRECT_CALL_CHK(glGetUniformLocation)(program, "level"),
static_cast<GLfloat>(level));
DIRECT_CALL_CHK(glDrawArrays)(GL_TRIANGLE_STRIP, 0, 4);
}
GLuint GLAuxContext::GLQueries::getTextureShaderProgram(
GLenum target, GLenum textureBaseFormat) {
std::string suffix, pos;
if (textureBaseFormat != GL_RGBA && textureBaseFormat != GL_RGB &&
textureBaseFormat != GL_RG && textureBaseFormat != GL_RED) {
throw std::runtime_error(
"GLAuxContext::GLQueries::getTextureShaderProgram: format "
"unsupported");
}
switch (target) {
case GL_TEXTURE_1D:
suffix = "1D";
pos = "texPos.x";
break;
case GL_TEXTURE_2D:
suffix = "2D";
pos = "vec2(texPos.xy)";
break;
case GL_TEXTURE_RECTANGLE:
suffix = "Rect";
pos = "vec2(texPos.xy)";
break;
case GL_TEXTURE_1D_ARRAY:
suffix = "1DArray";
pos = "vec2(texPos.xy)";
break;
// case GL_TEXTURE_CUBE_MAP:
// suffix = "Cube";
// pos =
// break;
default:
throw std::runtime_error(
"cannot generate program for this texture target");
}
bool glsl300 = m_AuxCtx->m_Parrent->getVersion().check(
GLContextVersion::Type::ES, 3);
std::ostringstream fsh;
if (glsl300) {
fsh << "#version 300 es\n"
<< "out vec4 oColor\n;"
<< "varying vec2 texPos;\n";
}
fsh << "#ifdef GL_FRAGMENT_PRECISION_HIGH\n"
<< "precision highp float; \n"
<< "#else \n"
<< "precision mediump float; \n"
<< "#endif \n"
"uniform sampler" << suffix << " s;\n"
"uniform float level;\n"
<< "varying vec2 texPos;\n";
fsh << "void main() {\n";
if (glsl300) {
fsh << " oColor = textureLod(s, ";
} else {
fsh << " gl_FragColor = texture" << suffix << "(s, ";
}
fsh << pos;
if (glsl300) {
fsh << ", level";
}
fsh << ");\n"
<< "}\n";
auto i = programs.find(fsh.str());
if (i != programs.end()) {
return i->second;
} else {
GLuint program = DIRECT_CALL_CHK(glCreateProgram)();
DIRECT_CALL_CHK(glAttachShader)(program, vshobj);
GLuint fShader = DIRECT_CALL_CHK(glCreateShader)(GL_FRAGMENT_SHADER);
DIRECT_CALL_CHK(glAttachShader)(program, fShader);
DIRECT_CALL_CHK(glDeleteShader)(fShader);
std::string fshStr = fsh.str();
const char* csrc[] = {fshStr.c_str()};
DIRECT_CALL_CHK(glShaderSource)(fShader, 1, csrc, NULL);
DIRECT_CALL_CHK(glCompileShader)(fShader);
GLint status = 0;
DIRECT_CALL_CHK(glGetShaderiv)(fShader, GL_COMPILE_STATUS, &status);
if (!status) {
char log[1000];
DIRECT_CALL_CHK(glGetShaderInfoLog)(fShader, 1000, NULL, log);
throw std::runtime_error(
std::string("Cannot compile fragment shader:") + log);
}
DIRECT_CALL_CHK(glLinkProgram)(program);
DIRECT_CALL_CHK(glGetProgramiv)(program, GL_LINK_STATUS, &status);
if (status != GL_TRUE) {
char log[10000];
DIRECT_CALL_CHK(glGetProgramInfoLog)(program, 10000, NULL, log);
DIRECT_CALL_CHK(glDeleteProgram)(program);
throw std::runtime_error(std::string("cannot link program: ") +
log);
} else {
programs[fshStr] = program;
return program;
}
}
}
} // namespace dglState<commit_msg>aux context: fix two bugs. switch from aux ctx upon error, add misssing semicolon near glGenFB();<commit_after>/* Copyright (C) 2013 Slawomir Cygan <slawomir.cygan@gmail.com>
*
* 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 "gl-auxcontext.h"
#include "gl-state.h"
#include "display.h"
#include "native-surface.h"
#include "pointers.h"
#include <sstream>
namespace dglState {
GLAuxContextSession::GLAuxContextSession(GLAuxContext* ctx) : m_ctx(ctx) {
m_ctx->doRefCurrent();
m_ctx->queries.setupInitialState();
}
GLAuxContextSession::~GLAuxContextSession() { m_ctx->doUnrefCurrent(); }
GLAuxContextSurface::GLAuxContextSurface(const DGLDisplayState* display,
opaque_id_t pixfmt)
: m_DisplayId(display->getId()), m_Id(0) {
EGLint attributes[] = {EGL_HEIGHT, 1, EGL_WIDTH, 1, EGL_NONE};
m_Id = (opaque_id_t)DIRECT_CALL_CHK(eglCreatePbufferSurface)(
(EGLDisplay)m_DisplayId, (EGLConfig)pixfmt, attributes);
if (!m_Id) {
throw std::runtime_error("Cannot allocate axualiary pbuffer surface");
}
}
GLAuxContextSurface::~GLAuxContextSurface() {
if (m_Id) {
DIRECT_CALL_CHK(eglDestroySurface)((EGLDisplay)m_DisplayId,
(EGLSurface)m_Id);
}
}
opaque_id_t GLAuxContextSurface::getId() const { return m_Id; }
GLAuxContext::GLAuxContext(const GLContext* origCtx)
: queries(this),
m_Id(0),
m_PixelFormat(0),
m_Parrent(origCtx),
m_MakeCurrentRef(0) {
if (m_Parrent->getDisplay()->getType() != DGLDisplayState::Type::EGL) {
throw std::runtime_error("auxaliary contexts implemented only for EGL");
}
std::vector<EGLint> eglAttributes(
m_Parrent->getContextCreationData().getAttribs().size());
for (size_t i = 0;
i < m_Parrent->getContextCreationData().getAttribs().size(); i++) {
eglAttributes[i] =
(EGLint)m_Parrent->getContextCreationData().getAttribs()[i];
}
eglAttributes.push_back(EGL_NONE);
m_PixelFormat = choosePixelFormat(
m_Parrent->getContextCreationData().getPixelFormat(),
m_Parrent->getDisplay()->getId());
switch (origCtx->getContextCreationData().getEntryPoint()) {
case eglCreateContext_Call:
m_Id = (opaque_id_t)DIRECT_CALL_CHK(eglCreateContext)(
(EGLDisplay)m_Parrent->getDisplay()->getId(),
(EGLConfig)m_PixelFormat, (EGLContext)m_Parrent->getId(),
&eglAttributes[0]);
break;
}
if (!m_Id) {
throw std::runtime_error("Cannot allocate auxaliary context");
}
}
GLAuxContext::~GLAuxContext() {
while (m_MakeCurrentRef) {
doUnrefCurrent();
}
if (m_Id) {
DIRECT_CALL_CHK(eglDestroyContext)(
(EGLDisplay)m_Parrent->getDisplay()->getId(), (EGLContext)m_Id);
}
}
GLAuxContextSession GLAuxContext::makeCurrent() {
return GLAuxContextSession(this);
}
void GLAuxContext::doRefCurrent() {
if (!m_MakeCurrentRef) {
if (!m_AuxSurface) {
m_AuxSurface = std::make_shared<GLAuxContextSurface>(
m_Parrent->getDisplay(), m_PixelFormat);
}
EGLBoolean status = DIRECT_CALL_CHK(eglMakeCurrent)(
(EGLDisplay)m_Parrent->getDisplay()->getId(),
(EGLSurface)m_AuxSurface->getId(),
(EGLSurface)m_AuxSurface->getId(), (EGLContext)m_Id);
if (!status) {
throw std::runtime_error("Cannot switch to auxaliary context.");
}
}
m_MakeCurrentRef++;
}
void GLAuxContext::doUnrefCurrent() {
if (m_MakeCurrentRef) {
m_MakeCurrentRef--;
}
if (!m_MakeCurrentRef) {
EGLBoolean status = DIRECT_CALL_CHK(eglMakeCurrent)(
(EGLDisplay)m_Parrent->getDisplay()->getId(),
(EGLSurface)m_Parrent->getNativeDrawSurface()->getId(),
(EGLSurface)m_Parrent->getNativeReadSurface()->getId(),
(EGLContext)m_Parrent->getId());
if (!status) {
throw std::runtime_error(
"Cannot switch back from auxaliary context.");
}
}
}
opaque_id_t GLAuxContext::choosePixelFormat(opaque_id_t preferred,
opaque_id_t displayId) {
EGLDisplay eglDpy = (EGLDisplay)displayId;
EGLConfig preferredConfig = (EGLConfig)preferred;
EGLint supportedSurfType = 0;
EGLBoolean status = EGL_TRUE;
status &= DIRECT_CALL_CHK(eglGetConfigAttrib)(
eglDpy, preferredConfig, EGL_SURFACE_TYPE, &supportedSurfType);
if (!status) {
throw std::runtime_error("Cannot query EGLConfig associated with ctx");
}
EGLConfig ret;
if (supportedSurfType & EGL_PBUFFER_BIT) {
ret = preferredConfig;
} else {
EGLint renderableType = 0;
if (m_Parrent->getVersion().check(GLContextVersion::Type::DT)) {
renderableType = EGL_OPENGL_BIT;
} else if (m_Parrent->getVersion().check(GLContextVersion::Type::ES,
3)) {
renderableType = EGL_OPENGL_ES3_BIT_KHR;
} else if (m_Parrent->getVersion().check(GLContextVersion::Type::ES,
2)) {
renderableType = EGL_OPENGL_ES2_BIT;
} else if (m_Parrent->getVersion().check(GLContextVersion::Type::ES,
1)) {
renderableType = EGL_OPENGL_ES_BIT;
}
EGLint attributes[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
EGL_RENDERABLE_TYPE, renderableType,
EGL_NONE};
EGLint numConfigs = 0;
status &= DIRECT_CALL_CHK(eglChooseConfig)(eglDpy, attributes, &ret, 1,
&numConfigs);
if ((status != EGL_TRUE) || numConfigs < 1) {
throw std::runtime_error(
"Cannot choose EGLConfig capable of driving auxaliary "
"context");
}
}
return (opaque_id_t)ret;
}
GLAuxContext::GLQueries::GLQueries(GLAuxContext* ctx)
: m_InitialState(false), m_AuxCtx(ctx) {}
void GLAuxContext::GLQueries::setupInitialState() {
if (m_InitialState) return;
DIRECT_CALL_CHK(glGenFramebuffers)(1, &fbo);
DIRECT_CALL_CHK(glBindFramebuffer)(GL_FRAMEBUFFER, fbo);
DIRECT_CALL_CHK(glGenRenderbuffers)(1, &rbo);
DIRECT_CALL_CHK(glBindRenderbuffer)(GL_RENDERBUFFER, rbo);
DIRECT_CALL_CHK(glFramebufferRenderbuffer)(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo);
if (m_AuxCtx->m_Parrent->getVersion().check(GLContextVersion::Type::ES,
3) ||
m_AuxCtx->m_Parrent->getVersion().check(GLContextVersion::Type::DT,
3)) {
DIRECT_CALL_CHK(glGenVertexArrays)(1, &vao);
DIRECT_CALL_CHK(glBindVertexArray)(vao);
}
DIRECT_CALL_CHK(glGenBuffers)(1, &vbo);
DIRECT_CALL_CHK(glBindBuffer)(GL_ARRAY_BUFFER, vbo);
GLfloat triangleStrip[] = {-1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f,
0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
1.0f, -1.0f, 0.0f, 1.0f};
DIRECT_CALL_CHK(glBufferData)(GL_ARRAY_BUFFER, sizeof(triangleStrip),
triangleStrip, GL_STATIC_DRAW);
DIRECT_CALL_CHK(glVertexAttribPointer)(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);
DIRECT_CALL_CHK(glEnableVertexAttribArray)(0);
vshobj = DIRECT_CALL_CHK(glCreateShader)(GL_VERTEX_SHADER);
const char* vsh =
"attribute vec4 inPos;\n"
"varying vec2 texPos;\n"
"void main() {\n"
" gl_Position = inPos;\n"
" texPos = inPos.xy * 0.5 + 0.5;\n"
"}\n";
DIRECT_CALL_CHK(glShaderSource)(vshobj, 1, &vsh, NULL);
DIRECT_CALL_CHK(glCompileShader)(vshobj);
GLint status = 0;
DIRECT_CALL_CHK(glGetShaderiv)(vshobj, GL_COMPILE_STATUS, &status);
if (!status) {
char log[1000];
DIRECT_CALL_CHK(glGetShaderInfoLog)(vshobj, 1000, NULL, log);
throw std::runtime_error(std::string("Cannot compile vertex shader") +
log);
}
if (DIRECT_CALL_CHK(glGetError)() != GL_NO_ERROR) {
throw std::runtime_error("Got GL error on auxiliary context");
}
m_InitialState = true;
}
void GLAuxContext::GLQueries::auxDrawTexture(GLuint name, GLenum target,
GLint level,
GLenum textureBaseFormat,
GLenum renderableFormat, int width,
int height) {
if (!m_AuxCtx->m_Parrent->getVersion().check(GLContextVersion::Type::ES,
2)) {
throw std::runtime_error(
"GLAuxContext::GLQueries::auxGetTexImage not implemented for "
"this "
"context version");
}
if (!DIRECT_CALL_CHK(glIsTexture)(name)) {
throw std::runtime_error(
"Texture object not found in auxaliary context");
}
DIRECT_CALL_CHK(glBindTexture)(target, name);
DIRECT_CALL_CHK(glRenderbufferStorage)(GL_RENDERBUFFER, renderableFormat, width,
height);
GLuint program = getTextureShaderProgram(target, textureBaseFormat);
DIRECT_CALL_CHK(glUseProgram)(program);
DIRECT_CALL_CHK(glUniform1f)(
DIRECT_CALL_CHK(glGetUniformLocation)(program, "level"),
static_cast<GLfloat>(level));
DIRECT_CALL_CHK(glDrawArrays)(GL_TRIANGLE_STRIP, 0, 4);
}
GLuint GLAuxContext::GLQueries::getTextureShaderProgram(
GLenum target, GLenum textureBaseFormat) {
std::string suffix, pos;
if (textureBaseFormat != GL_RGBA && textureBaseFormat != GL_RGB &&
textureBaseFormat != GL_RG && textureBaseFormat != GL_RED) {
throw std::runtime_error(
"GLAuxContext::GLQueries::getTextureShaderProgram: format "
"unsupported");
}
switch (target) {
case GL_TEXTURE_1D:
suffix = "1D";
pos = "texPos.x";
break;
case GL_TEXTURE_2D:
suffix = "2D";
pos = "vec2(texPos.xy)";
break;
case GL_TEXTURE_RECTANGLE:
suffix = "Rect";
pos = "vec2(texPos.xy)";
break;
case GL_TEXTURE_1D_ARRAY:
suffix = "1DArray";
pos = "vec2(texPos.xy)";
break;
// case GL_TEXTURE_CUBE_MAP:
// suffix = "Cube";
// pos =
// break;
default:
throw std::runtime_error(
"cannot generate program for this texture target");
}
bool glsl300 = m_AuxCtx->m_Parrent->getVersion().check(
GLContextVersion::Type::ES, 3);
std::ostringstream fsh;
if (glsl300) {
fsh << "#version 300 es\n"
<< "out vec4 oColor\n;"
<< "varying vec2 texPos;\n";
}
fsh << "#ifdef GL_FRAGMENT_PRECISION_HIGH\n"
<< "precision highp float; \n"
<< "#else \n"
<< "precision mediump float; \n"
<< "#endif \n"
"uniform sampler" << suffix << " s;\n"
"uniform float level;\n"
<< "varying vec2 texPos;\n";
fsh << "void main() {\n";
if (glsl300) {
fsh << " oColor = textureLod(s, ";
} else {
fsh << " gl_FragColor = texture" << suffix << "(s, ";
}
fsh << pos;
if (glsl300) {
fsh << ", level";
}
fsh << ");\n"
<< "}\n";
auto i = programs.find(fsh.str());
if (i != programs.end()) {
return i->second;
} else {
GLuint program = DIRECT_CALL_CHK(glCreateProgram)();
DIRECT_CALL_CHK(glAttachShader)(program, vshobj);
GLuint fShader = DIRECT_CALL_CHK(glCreateShader)(GL_FRAGMENT_SHADER);
DIRECT_CALL_CHK(glAttachShader)(program, fShader);
DIRECT_CALL_CHK(glDeleteShader)(fShader);
std::string fshStr = fsh.str();
const char* csrc[] = {fshStr.c_str()};
DIRECT_CALL_CHK(glShaderSource)(fShader, 1, csrc, NULL);
DIRECT_CALL_CHK(glCompileShader)(fShader);
GLint status = 0;
DIRECT_CALL_CHK(glGetShaderiv)(fShader, GL_COMPILE_STATUS, &status);
if (!status) {
char log[1000];
DIRECT_CALL_CHK(glGetShaderInfoLog)(fShader, 1000, NULL, log);
throw std::runtime_error(
std::string("Cannot compile fragment shader:") + log);
}
DIRECT_CALL_CHK(glLinkProgram)(program);
DIRECT_CALL_CHK(glGetProgramiv)(program, GL_LINK_STATUS, &status);
if (status != GL_TRUE) {
char log[10000];
DIRECT_CALL_CHK(glGetProgramInfoLog)(program, 10000, NULL, log);
DIRECT_CALL_CHK(glDeleteProgram)(program);
throw std::runtime_error(std::string("cannot link program: ") +
log);
} else {
programs[fshStr] = program;
return program;
}
}
}
} // namespace dglState<|endoftext|> |
<commit_before>#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<stdlib.h>
int DeltaS =10; //ͼϸ̶ 1Ϊһһ 2Ϊһ0.5
#define RXlong 20
#define RYlong 20
IMAGE Rimg;
int checklock=0;
//ͼеÿһС
typedef struct Position {
int no;
int x;
int y;
int Used;
}Position;
typedef Position* Map;
//ͼλ
Map TestMap;
int NumOfTestMap = 50; //ͼг˿
int TestMapPos = NumOfTestMap * DeltaS;
int CustNum = 10;
int LineNum = 5;
//ͼ
//void CreateTestMap() {
//
// TestMap = (Position*)malloc(TestMapPos *sizeof(Position));
// int NowX = 0;
// int NowY = 0;
// int reverse = 0;
//
// for (int i = 0; i < 5*(10*DeltaS);i++) {
// TestMap[i].x = NowX;
// TestMap[i].y = NowY;
// TestMap[i].no = i;
// TestMap[i].Used = 0;
//
//
// if ((i+1) % (10*DeltaS) == 0) {
// NowY += RYlong;
// reverse = !reverse;
// continue;
// }
//
// if (reverse) {
// NowX -= RXlong / DeltaS;
// }
// else {
// NowX += RXlong / DeltaS;
// }
//
// }
//
//}
void CreateTestMap() {
TestMap = (Position*)malloc(TestMapPos * sizeof(Position));
int NowX = 200;
int NowY = 0;
int mode = 1;
int reverse=1;
for (int i = 0; i < 5 * (CustNum * DeltaS); i++) {
TestMap[i].x = NowX;
TestMap[i].y = NowY;
TestMap[i].no = i;
TestMap[i].Used = 0;
if ( (i+DeltaS) % (CustNum * DeltaS) == 0) {
mode = 0;
}
else if (i % (CustNum*DeltaS) == 0) {
mode =reverse;
reverse = -reverse;
}
switch(mode){
case -1: NowX -= RXlong / DeltaS; break;
case 0: NowY += RYlong / DeltaS; break;
case 1:NowX += RXlong / DeltaS; break;
}
}
}
Position checklast;
Map CheckMap;
void CreateCheckMap() {
CheckMap = (Position*)malloc(10*DeltaS * sizeof(Position));
int NowX = 0;
int NowY = 0;
for (int i = 0; i < 10*DeltaS; i++) {
CheckMap[i].x = NowX;
CheckMap[i].y = NowY;
CheckMap[i].no = i;
CheckMap[i].Used = 0;
NowX += RXlong / DeltaS;
}
checklast = CheckMap[10 * DeltaS -1];
}
//ƶ
void MoveRun(Position* New, Position* Old) {
setcolor(WHITE);
fillellipse(Old->x, Old->y, Old->x + RXlong, Old->y + RYlong);
putimage(New->x, New->y, &Rimg);
Old->Used = 0;
New->Used = 1;
}
//ŵͼ
void Move(Map map,Position checklast) {
int NumOfPos = TestMapPos;
int go=0; //ܲƶ
//ͷ
if (checklock)
MoveRun(&checklast, &map[0]);
for (int i = 0; i < NumOfPos; i++) {
if (map[i].Used) {
if (go) {
MoveRun(&map[i - 1], &map[i]); //+ܶ
}
else {
i += DeltaS-1; //ˣܶȥ¸
go = 0;
}
}
else {
go = 1; //û 칥
}
}
}
void EnterMap(Map map) {
int NumOfPos = TestMapPos;
int last = NumOfPos - DeltaS ; //Ǹ
//ص
for (int i = last - DeltaS + 1; i < last; i++) {
if (map[i].Used)
return;
}
putimage(map[last].x, map[last].y, &Rimg);
map[last].Used = 1;
}
int main() {
initgraph(1500, 800);
loadimage(&Rimg, _T("˿.jpg"), RXlong, RYlong);
setbkcolor(WHITE);
cleardevice();
CreateTestMap();
CreateCheckMap();
//MOUSEMSG m;
char c;
while (1) {
Move(TestMap,checklast);
if (kbhit()) {
c=getch();
if (c == 'l')
checklock = !checklock;
else
EnterMap(TestMap);
}
Sleep(50);
}
if (getch());
}
<commit_msg>新增 安检口+缓冲区map 以及状态转换<commit_after>#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<stdlib.h>
int checklock = 0;//------lockðǷ˴
#define SleepTime 50
int DeltaS =1; //----------------------Сϸ̶ һ˿ɷΪС
#define RXlong 20
#define RYlong 20
IMAGE Rimg;
//ͼеÿһС
typedef struct Position {
//int CheckNo;
int x;
int y;
int Used;
}Position;
typedef Position* Map;
//----------------------------------------------------------------------------------------------Ŷӻmap
//extern int MaxCustSingleLine;// ȴ˿
//extern int MaxLines;// λMaxLinesֱ
int MaxCustSingleLine = 10;
int MaxLines = 5;
int SingleLinePos = MaxCustSingleLine * DeltaS; //ÿеλ
Map LineMap;
void CreateLineMap() {
LineMap = (Position*)malloc( SingleLinePos * MaxLines * sizeof(Position));
if (LineMap==NULL) {
exit(1);
}
int NowX = 160; //--------------------ϽX
int NowY = 40; //--------------------ϽY
int mode = 1;
int reverse=1;
for (int i = 0; i < 5 * SingleLinePos; i++) {
//ֵ
LineMap[i].x = NowX;
LineMap[i].y = NowY;
//LineMap[i].CheckNo = i;
LineMap[i].Used = 0;
//ıģʽ
if ( (i+DeltaS) % SingleLinePos == 0) { //
mode = 0;
}
else if (i % SingleLinePos == 0) { //ֱ
mode =reverse;
reverse = -reverse;
}
//λñ仯
switch(mode){
case -1: NowY -= RYlong / DeltaS; break; //
case 0: NowX += RXlong / DeltaS; break; //
case 1:NowY += RYlong / DeltaS; break; //
}
}//end of for
}
//Ŷӻmap^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//-----------------------------------------------------------------------------------------------map
//extern int NumOfWin;
int NumOfWin = 10;
Map* CheckMap;
int* last;
//extern CXlong;
//extern int MaxCustCheck;
int CXlong = 300;
int MaxCustCheck = 5;
#define MinStep 12
void CreateSingleCheckMap(int no) {
CheckMap[no] = (Position*)malloc((MinStep+no)*DeltaS * sizeof(Position));//--------------
int NowX = - (RXlong / DeltaS);//-------------------------
int NowY = 40+no*RYlong;//-----------------------
int i=0;
//setcolor(BLACK);
//rectangle(NowX+RXlong, NowY + RYlong, NowX + RXlong + RXlong, NowY + RYlong + RYlong);
//
for (int j = 0; j < (MaxCustCheck+2)*DeltaS; i++,j++) {
NowX += RXlong / DeltaS;
CheckMap[no][i].x = NowX;
CheckMap[no][i].y = NowY;
//CheckMap[no][i].CheckNo = i;
CheckMap[no][i].Used = 0;
}
//putimage(NowX,NowY, &Rimg);
//
for (int j = 0; j < (2+no)*DeltaS; i++, j++) {
NowY -= RYlong / DeltaS;
CheckMap[no][i].x = NowX;
CheckMap[no][i].y = NowY;
//CheckMap[no][i].CheckNo = i;
CheckMap[no][i].Used = 0;
}
//putimage(NowX, NowY, &Rimg);
//
for (int j = 0; j < 2 * DeltaS; i++, j++) {
NowX += RXlong / DeltaS;
CheckMap[no][i].x = NowX;
CheckMap[no][i].y = NowY;
//CheckMap[no][i].CheckNo = i;
CheckMap[no][i].Used = 0;
}
//putimage(NowX, NowY, &Rimg);
//
for (int j = 0; j < DeltaS; i++, j++) {
NowY += RXlong / DeltaS;
CheckMap[no][i].x = NowX;
CheckMap[no][i].y = NowY;
//CheckMap[no][i].CheckNo = i;
CheckMap[no][i].Used = 0;
}
//putimage(NowX, NowY, &Rimg);
last[no] = i-1;
}
void CreateCheckMap() {
CheckMap = (Map*)malloc(NumOfWin * sizeof(Map));
last = (int*)malloc(NumOfWin * sizeof(int));
for (int i = 0; i < NumOfWin; i++) {
CreateSingleCheckMap(i);
}
}
//map^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//------------------------------------------------------------------------------------------------------GoGOGO
//ƶ
void MoveRun(Position* New, Position* Old) {
setcolor(WHITE);
fillellipse(Old->x, Old->y, Old->x + RXlong, Old->y + RYlong);
putimage(New->x, New->y, &Rimg);
Old->Used = 0;
New->Used = 1;
}
//ƶ
void Move(Map map,int NumOfPos) {
//int NumOfPos = SingleLinePos;
int go=0; //ܲƶ
for (int i = 0; i < NumOfPos; i++) {
if (map[i].Used) {
if (go) {
MoveRun(&map[i - 1], &map[i]); //ܶ !
}
else {
i += DeltaS-1; //˲ܶ Ѿ ȥ¸
go = 0;
}
}
else {
go = 1; //û 칥
}
}
}
//GoGoGo^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//--------------------------------------------------------------------------------------------------------ͼ״̬ת
//
void EnterMap(Map map,int NumOfPos) {
//int NumOfPos = LineMapPos;
int last = NumOfPos - DeltaS ; //Ǹ
//жϻص
for (int i = last - DeltaS + 1; i < last; i++) {
if (map[i].Used)
return;
}
putimage(map[last].x, map[last].y, &Rimg);
map[last].Used = 1;
}
//ȥ
void EnCheck(int no) {
//ͷ ܲ
if (checklock && LineMap[0].Used) { //δ & ͷ
MoveRun(&CheckMap[no][last[no]], &LineMap[0]); //
LineMap[0].Used = 0;
CheckMap[no][last[no]].Used = 1;
}
}
void DeCheck(int no) {
CheckMap[no][0].Used = 0;
}
//ͼ״̬ת^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
int main() {
initgraph(1200, 600);
loadimage(&Rimg, _T("˿.jpg"), RXlong, RYlong);
setbkcolor(WHITE);
cleardevice();
CreateLineMap();
CreateCheckMap();
char c;
while (1) {
for (int i = 0; i < NumOfWin; i++) {
Move(CheckMap[i], (MinStep+i) * DeltaS);//ڶ
}
//EnCheck(0); //ͷ
Move(LineMap, SingleLinePos*MaxLines);//
if (kbhit()) {
c=getch();
if(c=='l')
checklock = !checklock;
else if (c <= '9'&&c >= '0') {
c = c - '0';
EnCheck(c);
}
else
EnterMap(LineMap, SingleLinePos*MaxLines);
}
Sleep(SleepTime);
}
if (getch());
}
<|endoftext|> |
<commit_before>#include "main.h"
#include "../ciphers/Eigen/Dense"
using namespace Eigen;
/* example constructor, sets some options */
HillAtt::HillAtt()
{
// declare options, keep options as uppercase
vector<string> temp;
temp.push_back("INPUTFILE");
temp.push_back("OUTPUTFILE");
temp.push_back("PLAINTEXT");
temp.push_back("CIPHERTEXT");
temp.push_back("MATRIX_ROWS");
temp.push_back("MATRIX_COLUMNS");
set_opts(temp);
// set default values, option must exist or error will printed
set_opt_value("OUTPUTFILE", "broken.txt");
set_opt_value("INPUTFILE", "encrypted.txt");
set_opt_value("MATRIX_ROWS", "2");
set_opt_value("MATRIX_COLUMNS", "2");
set_opt_value("PLAINTEXT", "upto");
set_opt_value("CIPHERTEXT", "RERZ");
}
/* I am overriding the default module function
* for displaying the description text
*/
void HillAtt::disp_desc()
{
cout << "Module: attacks/HillAtt\n\tUses known plaintext and cipher text to try to crack the key. \n\tBoth the plaintext must be invertible and have a modulus of 26,\n\t all of this is checked in the program.\n\tInput text should be lowercase, symbols are ignored.\n\tCipher text is all uppercase.\n\tPlease define the following required options:\n\t\tPLAINTEXT\tfound in original file\n\t\tCIPHERTEXT\tuppercase corresponds to plaintext" << endl;
disp_opts();
cout << endl;
}
/* overrides the virtual function from Module
* this is where the real meaty stuff happens
*/
int HillAtt::run()
{
ifstream in;
ofstream out;
string ibuff, obuff;
// perform error checking on options first
if (options["INPUTFILE"].empty()) {
cout << "[-] Please specify an input file" << endl;
return 1;
}
if (options["OUTPUTFILE"].empty()) {
cout << "[-] Please specify an output file" << endl;
return 2;
}
if (options["PLAINTEXT"].empty()) {
cout << "[-] Please specify known plaintext" << endl;
return 3;
}
string tkey = options["PLAINTEXT"];
if (options["CIPHERTEXT"].empty()) {
cout << "[-] Please specify corresponding ciphertext" << endl;
return 4;
}
string ckey = options["CIPHERTEXT"];
if(options["MATRIX_ROWS"].empty() || options["MATRIX_COLUMNS"].empty())
{
cout << "[-] Please specify matrix dimensions" << endl;
return 5;
}
cout << "[*] Opening input file: " << options["INPUTFILE"] << endl;
in.open(options["INPUTFILE"]);
if (!in.good()) {
cout << "[-] Input file error" << endl;
return 6;
}
cout << "[*] Opening output file: " << options["OUTPUTFILE"] << endl;
out.open(options["OUTPUTFILE"]);
cout << "Attacking hill cipher!" << endl;
//int rows = stoi(options["MATRIX_ROWS"]);
int columns = stoi(options["MATRIX_COLUMNS"]);
vector < vector<int>> vec;
if(attack(tkey,ckey, vec)==9)
{
return 9;
}
string passbuff = "";
while (getline(in, ibuff)) {
passbuff += ibuff;
decrypt(passbuff,obuff,vec);
out << obuff << endl;
}
if(passbuff.length() > 0)//add random character if not a multiple
{
for(int i = passbuff.length(); i < columns;i++)
{
passbuff+="x";
}
out << obuff << endl;
}
cout << endl;
in.close();
out.close();
return 0;
}
/* implementation of cipher
* made static so anyone can use, helpful for attacks
* input string must be lowercase
* output string will be uppercase
*/
int HillAtt::attack(string& ptext, string&ctext, vector <vector<int>> &vec)
{
MatrixXf a(2,2);
MatrixXf k(2,2);
a(0,0) = ptext[0]-97;
a(1,0) = ptext[1]-97;
a(0,1) = ptext[2]-97;
a(1,1) = ptext[3]-97;
k(0,0) = tolower(ctext[0])-97;
k(1,0) = tolower(ctext[1])-97;
k(0,1) = tolower(ctext[2])-97;
k(1,1) = tolower(ctext[3])-97;
int y = rint(a.determinant());
if(y==0)
{
cout << "Plaintext provided not invertible" << endl;
return 9;
}
a = a.inverse();
int z =y;
int m = 26;
y = fmod(y,m);
if(y < 0)
{
y = y+m;
}
int x;
int inv = 1;
for(x = 1; x < m; x++) {
if(fmod((y*x),m) == 1)
{
inv = 0;
break;
}
}
if(inv ==1)
{
cout << "could not apply modulus 26" << endl;
return 9;
}
for(int i = 0; i < a.rows(); i++)
{
for(int j = 0; j <a.cols();j++)
{
int m=26;
a(i,j) = a(i,j)*z;
a(i,j) *=x;
int temp = fmod(a(i,j),m);
if(temp < 0)
{
temp = temp+m;
}
a(i,j) = temp;
}
}
k = k*a;
for(int i = 0; i < k.rows(); i++)
{
vector<int> row;
for(int j = 0; j <k.cols();j++)
{
int m=26;
int temp = fmod(k(i,j),m);
if(temp < 0)
{
temp = temp+m;
}
k(i,j) = temp;
row.push_back(k(i,j));
}
vec.push_back(row);
}
cout << "The key found is:" << endl;
cout << k << endl;
return 0;
}
void HillAtt::decrypt(string& in, string& out, vector <vector<int>>& vec)
{
out.clear();
const char *ti = in.c_str();
vector<int> text;
int writeout = 0;
for (unsigned int i = 0; i < in.size(); i++) {
char c;
MatrixXf a(vec.size(),vec[0].size());
for(unsigned int r = 0 ; r < vec.size();r++)
{
for(unsigned int c = 0; c <vec[0].size();c++)
{
a(r,c) = vec[r][c];
}
}
int y = a.determinant();
if(y == 0)
{
cout << "The key is not invertible, can't decrypt" << endl;
return;
}
a= a.inverse();
int m = 26;
int z =y;
y %= m;
int x;
for(x = 1; x < m; x++) {
if((y*x) % m == 1)
{
break;
}
}
for(int l = 0; l < a.rows();l++)
{
for(int k = 0; k < a.cols(); k++)
{
a(l,k) = a(l,k)*z;
a(l,k) *=x;
int temp = fmod(a(l,k),m);
if(temp < 0)
{
temp = temp+m;
}
a(l,k) = temp;
}
}
//cout << a << endl;
c = toupper(ti[i]);
if (isalpha(c)) {
text.push_back( ((int) c) - 65);
writeout++;
}
if(writeout>0 && (writeout)%vec[0].size()==0)
{
int sum = 0;
for(unsigned int r =0; r < a.rows();r++)
{
for(unsigned int c = 0; c < a.cols();c++)
{
sum +=a(r,c)*text[c];
}
sum%=26;
out += tolower(sum+65);
sum = 0;
writeout = 0;
}
text.clear();
}
//}
}
in = "";
if(text.size() > 0)
{
//if(!decrypt)
// {
for(unsigned int i = 0; i < text.size();i++)
{
in+=text[i]+97;
}
//}
}
}
<commit_msg>readded hillatt<commit_after>#include "main.h"
#include "../ciphers/Eigen/Dense"
using namespace Eigen;
/* example constructor, sets some options */
HillAtt::HillAtt()
{
// declare options, keep options as uppercase
vector<string> temp;
temp.push_back("INPUTFILE");
temp.push_back("OUTPUTFILE");
temp.push_back("PLAINTEXT");
temp.push_back("CIPHERTEXT");
temp.push_back("MATRIX_ROWS");
temp.push_back("MATRIX_COLUMNS");
set_opts(temp);
// set default values, option must exist or error will printed
set_opt_value("OUTPUTFILE", "broken.txt");
set_opt_value("INPUTFILE", "encrypted.txt");
set_opt_value("MATRIX_ROWS", "2");
set_opt_value("MATRIX_COLUMNS", "2");
set_opt_value("PLAINTEXT", "upto");
set_opt_value("CIPHERTEXT", "RERZ");
}
/* I am overriding the default module function
* for displaying the description text
*/
void HillAtt::disp_desc()
{
cout << "Module: attacks/HillAtt\n\tUses known plaintext and cipher text to try to crack the key. \n\tBoth the plaintext must be invertible and have a modulus of 26,\n\t all of this is checked in the program.\n\tInput text should be lowercase, symbols are ignored.\n\tCipher text is all uppercase.\n\tPlease define the following required options:\n\t\tPLAINTEXT\tfound in original file\n\t\tCIPHERTEXT\tuppercase corresponds to plaintext" << endl;
disp_opts();
cout << endl;
}
/* overrides the virtual function from Module
* this is where the real meaty stuff happens
*/
int HillAtt::run()
{
ifstream in;
ofstream out;
string ibuff, obuff;
// perform error checking on options first
if (options["INPUTFILE"].empty()) {
cout << "[-] Please specify an input file" << endl;
return 1;
}
if (options["OUTPUTFILE"].empty()) {
cout << "[-] Please specify an output file" << endl;
return 2;
}
if (options["PLAINTEXT"].empty()) {
cout << "[-] Please specify known plaintext" << endl;
return 3;
}
string tkey = options["PLAINTEXT"];
if (options["CIPHERTEXT"].empty()) {
cout << "[-] Please specify corresponding ciphertext" << endl;
return 4;
}
string ckey = options["CIPHERTEXT"];
if(options["MATRIX_ROWS"].empty() || options["MATRIX_COLUMNS"].empty())
{
cout << "[-] Please specify matrix dimensions" << endl;
return 5;
}
cout << "[*] Opening input file: " << options["INPUTFILE"] << endl;
in.open(options["INPUTFILE"]);
if (!in.good()) {
cout << "[-] Input file error" << endl;
return 6;
}
cout << "[*] Opening output file: " << options["OUTPUTFILE"] << endl;
out.open(options["OUTPUTFILE"]);
cout << "Attacking hill cipher!" << endl;
//int rows = stoi(options["MATRIX_ROWS"]);
int columns = stoi(options["MATRIX_COLUMNS"]);
vector < vector<int>> vec;
if(attack(tkey,ckey, vec)==9)
{
return 9;
}
string passbuff = "";
while (getline(in, ibuff)) {
passbuff += ibuff;
decrypt(passbuff,obuff,vec);
out << obuff << endl;
}
if(passbuff.length() > 0)//add random character if not a multiple
{
for(int i = passbuff.length(); i < columns;i++)
{
passbuff+="x";
}
out << obuff << endl;
}
cout << endl;
in.close();
out.close();
return 0;
}
/* implementation of cipher
* made static so anyone can use, helpful for attacks
* input string must be lowercase
* output string will be uppercase
*/
int HillAtt::attack(string& ptext, string&ctext, vector <vector<int>> &vec)
{
MatrixXf a(2,2);
MatrixXf k(2,2);
a(0,0) = ptext[0]-97;
a(1,0) = ptext[1]-97;
a(0,1) = ptext[2]-97;
a(1,1) = ptext[3]-97;
k(0,0) = tolower(ctext[0])-97;
k(1,0) = tolower(ctext[1])-97;
k(0,1) = tolower(ctext[2])-97;
k(1,1) = tolower(ctext[3])-97;
int y = rint(a.determinant());
if(y==0)
{
cout << "Plaintext provided not invertible" << endl;
return 9;
}
a = a.inverse();
int z =y;
int m = 26;
y = fmod(y,m);
if(y < 0)
{
y = y+m;
}
int x;
int inv = 1;
for(x = 1; x < m; x++) {
if(fmod((y*x),m) == 1)
{
inv = 0;
break;
}
}
if(inv ==1)
{
cout << "could not apply modulus 26" << endl;
return 9;
}
for(int i = 0; i < a.rows(); i++)
{
for(int j = 0; j <a.cols();j++)
{
int m=26;
a(i,j) = a(i,j)*z;
a(i,j) *=x;
int temp = fmod(a(i,j),m);
if(temp < 0)
{
temp = temp+m;
}
a(i,j) = temp;
}
}
k = k*a;
for(int i = 0; i < k.rows(); i++)
{
vector<int> row;
for(int j = 0; j <k.cols();j++)
{
int m=26;
int temp = fmod(k(i,j),m);
if(temp < 0)
{
temp = temp+m;
}
k(i,j) = temp;
row.push_back(k(i,j));
}
vec.push_back(row);
}
cout << "The key found is:" << endl;
cout << k << endl;
return 0;
}
void HillAtt::decrypt(string& in, string& out, vector <vector<int>>& vec)
{
out.clear();
const char *ti = in.c_str();
vector<int> text;
int writeout = 0;
for (unsigned int i = 0; i < in.size(); i++) {
char c;
MatrixXf a(vec.size(),vec[0].size());
for(unsigned int r = 0 ; r < vec.size();r++)
{
for(unsigned int c = 0; c <vec[0].size();c++)
{
a(r,c) = vec[r][c];
}
}
int y = a.determinant();
if(y == 0)
{
cout << "The key is not invertible, can't decrypt" << endl;
return;
}
a= a.inverse();
int m = 26;
int z =y;
y %= m;
int x;
for(x = 1; x < m; x++) {
if((y*x) % m == 1)
{
break;
}
}
for(int l = 0; l < a.rows();l++)
{
for(int k = 0; k < a.cols(); k++)
{
a(l,k) = a(l,k)*z;
a(l,k) *=x;
int temp = fmod(a(l,k),m);
if(temp < 0)
{
temp = temp+m;
}
a(l,k) = temp;
}
}
c = toupper(ti[i]);
if (isalpha(c)) {
text.push_back( ((int) c) - 65);
writeout++;
}
if(writeout>0 && (writeout)%vec[0].size()==0)
{
int sum = 0;
for(unsigned int r =0; r < a.rows();r++)
{
for(unsigned int c = 0; c < a.cols();c++)
{
sum +=a(r,c)*text[c];
}
sum%=26;
out += tolower(sum+65);
sum = 0;
writeout = 0;
}
text.clear();
}
//}
}
in = "";
if(text.size() > 0)
{
for(unsigned int i = 0; i < text.size();i++)
{
in+=text[i]+97;
}
}
}
<|endoftext|> |
<commit_before>// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2009 Sage Weil <sage@newdream.net>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "AuthTypes.h"
#include "CryptoTools.h"
#include "openssl/evp.h"
#include "openssl/aes.h"
#define CEPH_CRYPTO_STUPID 0x0
#define CEPH_CRYPTO_AES 0x1
class CryptoStupid : public CryptoHandler {
public:
CryptoStupid() {}
~CryptoStupid() {}
bool encrypt(EntitySecret& secret, bufferlist& in, bufferlist& out);
bool decrypt(EntitySecret& secret, bufferlist& in, bufferlist& out);
};
bool CryptoStupid::encrypt(EntitySecret& secret, bufferlist& in, bufferlist& out)
{
bufferlist sec_bl = secret.get_secret();
const char *sec = sec_bl.c_str();
int sec_len = sec_bl.length();
int in_len = in.length();
bufferptr outptr(in_len);
out.append(outptr);
const char *inbuf = in.c_str();
char *outbuf = outptr.c_str();
for (int i=0; i<in_len; i++) {
outbuf[i] = inbuf[i] ^ sec[i % sec_len];
}
return true;
}
bool CryptoStupid::decrypt(EntitySecret& secret, bufferlist& in, bufferlist& out)
{
return encrypt(secret, in, out);
}
#define AES_KEY_LEN AES_BLOCK_SIZE
class CryptoAES : public CryptoHandler {
public:
CryptoAES() {}
~CryptoAES() {}
bool encrypt(EntitySecret& secret, bufferlist& in, bufferlist& out);
bool decrypt(EntitySecret& secret, bufferlist& in, bufferlist& out);
};
static const unsigned char *aes_iv = (const unsigned char *)"cephsageyudagreg";
bool CryptoAES::encrypt(EntitySecret& secret, bufferlist& in, bufferlist& out)
{
bufferlist sec_bl = secret.get_secret();
const unsigned char *key = (const unsigned char *)sec_bl.c_str();
int in_len = in.length();
const unsigned char *in_buf = (const unsigned char *)in.c_str();
int outlen = (in_len + AES_BLOCK_SIZE) & ~(AES_BLOCK_SIZE -1);
int tmplen;
unsigned char outbuf[outlen];
if (sec_bl.length() < AES_KEY_LEN) {
derr(0) << "key is too short" << dendl;
return false;
}
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, aes_iv);
if(!EVP_EncryptUpdate(&ctx, outbuf, &outlen, in_buf, in.length())) {
derr(0) << "EVP_EncryptUpdate error" << dendl;
return false;
}
if(!EVP_EncryptFinal_ex(&ctx, outbuf + outlen, &tmplen)) {
derr(0) << "EVP_EncryptFinal error" << dendl;
return false;
}
out.append((const char *)outbuf, outlen);
return true;
}
bool CryptoAES::decrypt(EntitySecret& secret, bufferlist& in, bufferlist& out)
{
bufferlist sec_bl = secret.get_secret();
const unsigned char *key = (const unsigned char *)sec_bl.c_str();
int in_len = in.length();
int dec_len = 0;
int last_dec_len = 0;
unsigned char dec_data[in_len];
bool result = false;
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_CIPHER_CTX_init(ctx);
int res = EVP_DecryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, aes_iv);
if (res == 1) {
res = EVP_DecryptUpdate(ctx, dec_data,
&dec_len, (const unsigned char *)in.c_str(), in_len);
if (res == 1) {
EVP_DecryptFinal_ex(ctx,
dec_data + dec_len,
&last_dec_len);
dec_len += last_dec_len;
out.append((const char *)dec_data, dec_len);
result = true;
} else {
dout(0) << "EVP_DecryptUpdate error" << dendl;
}
} else {
dout(0) << "EVP_DecryptInit_ex error" << dendl;
}
EVP_CIPHER_CTX_free(ctx);
EVP_cleanup();
return result;
}
static CryptoStupid crypto_stupid;
static CryptoAES crypto_aes;
CryptoHandler *CryptoManager::get_crypto(int type)
{
switch (type) {
case CEPH_CRYPTO_STUPID:
return &crypto_stupid;
case CEPH_CRYPTO_AES:
return &crypto_aes;
default:
return NULL;
}
}
CryptoManager ceph_crypto_mgr;
<commit_msg>auth: fix aes encryption<commit_after>// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2009 Sage Weil <sage@newdream.net>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "AuthTypes.h"
#include "CryptoTools.h"
#include "openssl/evp.h"
#include "openssl/aes.h"
#define CEPH_CRYPTO_STUPID 0x0
#define CEPH_CRYPTO_AES 0x1
class CryptoStupid : public CryptoHandler {
public:
CryptoStupid() {}
~CryptoStupid() {}
bool encrypt(EntitySecret& secret, bufferlist& in, bufferlist& out);
bool decrypt(EntitySecret& secret, bufferlist& in, bufferlist& out);
};
bool CryptoStupid::encrypt(EntitySecret& secret, bufferlist& in, bufferlist& out)
{
bufferlist sec_bl = secret.get_secret();
const char *sec = sec_bl.c_str();
int sec_len = sec_bl.length();
int in_len = in.length();
bufferptr outptr(in_len);
out.append(outptr);
const char *inbuf = in.c_str();
char *outbuf = outptr.c_str();
for (int i=0; i<in_len; i++) {
outbuf[i] = inbuf[i] ^ sec[i % sec_len];
}
return true;
}
bool CryptoStupid::decrypt(EntitySecret& secret, bufferlist& in, bufferlist& out)
{
return encrypt(secret, in, out);
}
#define AES_KEY_LEN AES_BLOCK_SIZE
class CryptoAES : public CryptoHandler {
public:
CryptoAES() {}
~CryptoAES() {}
bool encrypt(EntitySecret& secret, bufferlist& in, bufferlist& out);
bool decrypt(EntitySecret& secret, bufferlist& in, bufferlist& out);
};
static const unsigned char *aes_iv = (const unsigned char *)"cephsageyudagreg";
bool CryptoAES::encrypt(EntitySecret& secret, bufferlist& in, bufferlist& out)
{
bufferlist sec_bl = secret.get_secret();
const unsigned char *key = (const unsigned char *)sec_bl.c_str();
int in_len = in.length();
const unsigned char *in_buf = (const unsigned char *)in.c_str();
int outlen = (in_len + AES_BLOCK_SIZE) & ~(AES_BLOCK_SIZE -1);
int tmplen;
#define OUT_BUF_EXTRA 128
unsigned char outbuf[outlen + OUT_BUF_EXTRA];
if (sec_bl.length() < AES_KEY_LEN) {
derr(0) << "key is too short" << dendl;
return false;
}
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, aes_iv);
if(!EVP_EncryptUpdate(&ctx, outbuf, &outlen, in_buf, in.length())) {
derr(0) << "EVP_EncryptUpdate error" << dendl;
return false;
}
if(!EVP_EncryptFinal_ex(&ctx, outbuf + outlen, &tmplen)) {
derr(0) << "EVP_EncryptFinal error" << dendl;
return false;
}
out.append((const char *)outbuf, outlen + tmplen);
return true;
}
bool CryptoAES::decrypt(EntitySecret& secret, bufferlist& in, bufferlist& out)
{
bufferlist sec_bl = secret.get_secret();
const unsigned char *key = (const unsigned char *)sec_bl.c_str();
int in_len = in.length();
int dec_len = 0;
int last_dec_len = 0;
unsigned char dec_data[in_len];
bool result = false;
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_CIPHER_CTX_init(ctx);
int res = EVP_DecryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, aes_iv);
if (res == 1) {
res = EVP_DecryptUpdate(ctx, dec_data,
&dec_len, (const unsigned char *)in.c_str(), in_len);
if (res == 1) {
EVP_DecryptFinal_ex(ctx,
dec_data + dec_len,
&last_dec_len);
dec_len += last_dec_len;
out.append((const char *)dec_data, dec_len);
result = true;
} else {
dout(0) << "EVP_DecryptUpdate error" << dendl;
}
} else {
dout(0) << "EVP_DecryptInit_ex error" << dendl;
}
EVP_CIPHER_CTX_free(ctx);
EVP_cleanup();
return result;
}
static CryptoStupid crypto_stupid;
static CryptoAES crypto_aes;
CryptoHandler *CryptoManager::get_crypto(int type)
{
switch (type) {
case CEPH_CRYPTO_STUPID:
return &crypto_stupid;
case CEPH_CRYPTO_AES:
return &crypto_aes;
default:
return NULL;
}
}
CryptoManager ceph_crypto_mgr;
<|endoftext|> |
<commit_before>/*
* This code was taken directly from the OpenSceneGraph
*/
//#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ossim/base/ossimNotifyContext.h>
#include <ossim/base/ossimTimer.h>
ossimTimer* ossimTimer::m_instance = 0;
// follows are the constructors of the Timer class, once version
// for each OS combination. The order is WIN32, FreeBSD, Linux, IRIX,
// and the rest of the world.
//
// all the rest of the timer methods are implemented within the header.
ossimTimer* ossimTimer::instance()
{
if(!m_instance)
{
m_instance = new ossimTimer;
}
return m_instance;
}
// ---
// From: http://msdn.microsoft.com/en-us/library/b0084kay.aspx
// Defined for applications for Win32 and Win64. Always defined.
// ---
#if defined(_WIN32)
#include <sys/types.h>
#include <fcntl.h>
#include <windows.h>
#include <winbase.h>
ossimTimer::ossimTimer()
{
LARGE_INTEGER frequency;
if(QueryPerformanceFrequency(&frequency))
{
m_secsPerTick = 1.0/(double)frequency.QuadPart;
}
else
{
m_secsPerTick = 1.0;
ossimNotify(ossimNotifyLevel_NOTICE)<<"Error: ossimTimer::ossimTimer() unable to use QueryPerformanceFrequency, "<<std::endl;
ossimNotify(ossimNotifyLevel_NOTICE)<<"timing code will be wrong, Windows error code: "<<GetLastError()<<std::endl;
}
setStartTick();
}
ossimTimer::Timer_t ossimTimer::tick() const
{
LARGE_INTEGER qpc;
if (QueryPerformanceCounter(&qpc))
{
return qpc.QuadPart;
}
else
{
ossimNotify(ossimNotifyLevel_NOTICE)<<"Error: ossimTimer::ossimTimer() unable to use QueryPerformanceCounter, "<<std::endl;
ossimNotify(ossimNotifyLevel_NOTICE)<<"timing code will be wrong, Windows error code: "<<GetLastError()<<std::endl;
return 0;
}
}
#else
#include <sys/time.h>
ossimTimer::ossimTimer( )
{
m_secsPerTick = (1.0 / (double) 1000000);
setStartTick();
}
ossimTimer::Timer_t ossimTimer::tick() const
{
struct timeval tv;
gettimeofday(&tv, NULL);
return ((ossimTimer::Timer_t)tv.tv_sec)*1000000+(ossimTimer::Timer_t)tv.tv_usec;
}
#endif
<commit_msg>Updated the timer code to the latest OSG implementation<commit_after>/*
* This code was taken directly from the OpenSceneGraph
*/
//#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ossim/base/ossimNotifyContext.h>
#include <ossim/base/ossimTimer.h>
ossimTimer* ossimTimer::m_instance = 0;
// follows are the constructors of the Timer class, once version
// for each OS combination. The order is WIN32, FreeBSD, Linux, IRIX,
// and the rest of the world.
//
// all the rest of the timer methods are implemented within the header.
ossimTimer* ossimTimer::instance()
{
if(!m_instance)
{
m_instance = new ossimTimer;
}
return m_instance;
}
// ---
// From: http://msdn.microsoft.com/en-us/library/b0084kay.aspx
// Defined for applications for Win32 and Win64. Always defined.
// ---
#if defined(_WIN32)
#include <sys/types.h>
#include <fcntl.h>
#include <windows.h>
#include <winbase.h>
ossimTimer::ossimTimer()
{
LARGE_INTEGER frequency;
if(QueryPerformanceFrequency(&frequency))
{
m_secsPerTick = 1.0/(double)frequency.QuadPart;
}
else
{
m_secsPerTick = 1.0;
ossimNotify(ossimNotifyLevel_NOTICE)<<"Error: ossimTimer::ossimTimer() unable to use QueryPerformanceFrequency, "<<std::endl;
ossimNotify(ossimNotifyLevel_NOTICE)<<"timing code will be wrong, Windows error code: "<<GetLastError()<<std::endl;
}
setStartTick();
}
ossimTimer::Timer_t ossimTimer::tick() const
{
LARGE_INTEGER qpc;
if (QueryPerformanceCounter(&qpc))
{
return qpc.QuadPart;
}
else
{
ossimNotify(ossimNotifyLevel_NOTICE)<<"Error: ossimTimer::ossimTimer() unable to use QueryPerformanceCounter, "<<std::endl;
ossimNotify(ossimNotifyLevel_NOTICE)<<"timing code will be wrong, Windows error code: "<<GetLastError()<<std::endl;
return 0;
}
}
#else
#include <unistd.h>
ossimTimer::ossimTimer( )
{
m_secsPerTick = (1.0 / (double) 1000000);
setStartTick();
}
#if defined(_POSIX_TIMERS) && ( _POSIX_TIMERS > 0 ) && defined(_POSIX_MONOTONIC_CLOCK)
#include <time.h>
ossimTimer::Timer_t ossimTimer::tick() const
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ((ossimTimer::Timer_t)ts.tv_sec)*1000000+(ossimTimer::Timer_t)ts.tv_nsec/1000;
}
#else
#include <sys/time.h>
ossimTimer::Timer_t ossimTimer::tick() const
{
struct timeval tv;
gettimeofday(&tv, NULL);
return ((ossimTimer::Timer_t)tv.tv_sec)*1000000+(ossimTimer::Timer_t)tv.tv_usec;
}
#endif
// ossimTimer::Timer_t ossimTimer::tick() const
// {
// struct timeval tv;
// gettimeofday(&tv, NULL);
// return ((ossimTimer::Timer_t)tv.tv_sec)*1000000+(ossimTimer::Timer_t)tv.tv_usec;
// }
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2009 Haiku, Inc.
* Distributed under the terms of the MIT License.
*
* Authors:
* Ankur Sethi (get.me.ankur@gmail.com)
*/
#include "Indexer.h"
#include "support.h"
#include <Directory.h>
#include <Entry.h>
#include <FindDirectory.h>
#include <NodeInfo.h>
#include <NodeMonitor.h>
#include <Path.h>
using namespace lucene::document ;
Indexer :: Indexer()
: BApplication("application/x-vnd.Haiku-BeaconDaemon"),
fIndexWriterList(1)
{
BMessage settings('sett') ;
if (load_settings(&settings) == B_OK)
LoadSettings(&settings) ;
}
void
Indexer ::ReadyToRun()
{
fQueryFeeder = new Feeder() ;
fQueryFeeder->StartWatching() ;
BVolume *volume ;
BList *volumeList = fQueryFeeder->GetVolumeList() ;
for (int i = 0 ; (volume = (BVolume*)volumeList->ItemAt(i)) != NULL ; i++)
InitIndex(volume) ;
UpdateIndex() ;
}
void
Indexer :: MessageReceived(BMessage *message)
{
index_writer_ref *ref = NULL ;
dev_t device ;
switch (message->what) {
case BEACON_UPDATE_INDEX :
UpdateIndex() ;
break ;
case BEACON_THREAD_DONE :
message->FindInt32("device", &device) ;
ref = FindIndexWriterRef(device) ;
acquire_sem(ref->sem) ;
break ;
case B_NODE_MONITOR :
HandleDeviceUpdate(message) ;
break ;
default :
BApplication :: MessageReceived(message) ;
}
}
bool
Indexer :: QuitRequested()
{
BMessage settings('sett') ;
fQueryFeeder->SaveSettings(&settings) ;
SaveSettings(&settings) ;
save_settings(&settings) ;
fQueryFeeder->PostMessage(B_QUIT_REQUESTED) ;
index_writer_ref *ref ;
status_t exitValue ;
for (int i = 0 ; (ref = (index_writer_ref*)fIndexWriterList.ItemAt(i))
!= NULL ; i++) {
delete_sem(ref->sem) ;
wait_for_thread(ref->thread, &exitValue) ;
ref->indexWriter->optimize() ;
ref->indexWriter->close() ;
}
return true ;
}
void
Indexer :: SaveSettings(BMessage *settings)
{
}
void
Indexer :: LoadSettings(BMessage *settings)
{
}
void
Indexer :: UpdateIndex()
{
entry_ref* iter_ref = new entry_ref ;
dev_t device = -1 ;
index_writer_ref *ref = NULL ;
while (fQueryFeeder->GetNextRef(iter_ref) == B_OK) {
if (ref == NULL || ref->device != iter_ref->device)
ref = FindIndexWriterRef(iter_ref->device) ;
if (ref != NULL && TranslatorAvailable(iter_ref))
ref->entryList->AddItem(iter_ref) ;
}
for (int i = 0 ; (ref = (index_writer_ref*)fIndexWriterList.ItemAt(i))
!= NULL ; i++) {
release_sem(ref->sem) ;
resume_thread(ref->thread) ;
}
}
void
Indexer :: InitIndex(BVolume *volume)
{
// TODO: handle errors.
index_writer_ref *ref = new index_writer_ref ;
char volume_name[B_FILE_NAME_LENGTH] ;
BDirectory dir ;
ref->device = volume->Device() ;
volume->GetRootDirectory(&dir) ;
ref->indexWriter = OpenIndex(&dir) ;
ref->entryList = new BList(10) ;
volume->GetName(volume_name) ;
ref->sem = create_sem(1, volume_name) ;
acquire_sem(ref->sem) ;
ref->thread = spawn_thread(add_document, volume_name, B_NORMAL_PRIORITY,
(void*)ref) ;
fIndexWriterList.AddItem((void*)ref) ;
}
IndexWriter*
Indexer :: OpenIndex(BDirectory *dir)
{
// TODO: handle errors.
IndexWriter *indexWriter = NULL ;
BPath path(dir) ;
path.Append("index") ;
if(create_directory(path.Path(), 0777) != B_OK)
return NULL ;
try {
if (IndexReader::indexExists(path.Path()))
indexWriter = new IndexWriter(path.Path(), &fStandardAnalyzer,
false) ;
else
indexWriter = new IndexWriter(path.Path(), &fStandardAnalyzer,
true) ;
} catch (CLuceneError) {
// Index is unreadable. Delete it and call OpenIndex() again.
BEntry entry ;
BDirectory indexDirectory(path.Path()) ;
while (indexDirectory.GetNextEntry(&entry, false) == B_OK)
entry.Remove() ;
indexWriter = OpenIndex(dir) ;
}
return indexWriter ;
}
bool
Indexer :: TranslatorAvailable(entry_ref *ref)
{
// For now, just return true if the file is a plain text file.
// Will change in the future when we have more translators.
BNode node(ref) ;
BNodeInfo nodeInfo(&node) ;
char MIMEString[B_MIME_TYPE_LENGTH] ;
nodeInfo.GetType(MIMEString) ;
if (!strcmp(MIMEString, "text/plain"))
return true ;
return false ;
}
void
Indexer :: HandleDeviceUpdate(BMessage *message)
{
int32 opcode ;
dev_t device ;
BVolume volume ;
message->FindInt32("opcode", &opcode) ;
switch (opcode) {
case B_DEVICE_MOUNTED :
message->FindInt32("new device", &device) ;
volume.SetTo(device) ;
InitIndex(&volume) ;
break ;
case B_DEVICE_UNMOUNTED :
message->FindInt32("device", &device) ;
volume.SetTo(device) ;
CloseIndex(&volume) ;
break ;
}
}
void
Indexer :: CloseIndex(BVolume *volume)
{
// Just removes the index_writer_ref from fIndexWriterList for now.
// This means unmounting or unplugging the USB will cause the index
// to become corrupted. TODO.
index_writer_ref *ref ;
for (int i = 0 ; (ref = (index_writer_ref*)fIndexWriterList.ItemAt(i)) != NULL
; i++) {
if (ref->device == volume->Device()) {
fIndexWriterList.RemoveItem(i) ;
delete ref ;
break ;
}
}
}
index_writer_ref*
Indexer :: FindIndexWriterRef(dev_t device)
{
index_writer_ref *iter_ref ;
for (int i = 0 ; (iter_ref = (index_writer_ref*)fIndexWriterList.ItemAt(i))
!= NULL ; i++) {
if (iter_ref->device == device)
return iter_ref ;
}
return NULL ;
}
int32 add_document(void *data)
{
index_writer_ref *ref = (index_writer_ref*)data ;
BList *entryList = ref->entryList ;
entry_ref *iter_ref ;
BMessage doneMessage(BEACON_THREAD_DONE) ;
doneMessage.AddInt32("device", ref->device) ;
BPath path ;
IndexWriter *indexWriter = ref->indexWriter ;
FileReader *fileReader ;
Document *doc ;
// Get path to the index directory on this particular
// volume.
BVolume volume(ref->device) ;
BDirectory dir ;
volume.GetRootDirectory(&dir) ;
path.SetTo(&dir) ;
path.Append("index") ;
dir.SetTo(path.Path()) ;
while (acquire_sem(ref->sem) >= B_NO_ERROR) {
for (int i = 0 ; (iter_ref = (entry_ref*)entryList->ItemAt(i)) != NULL
; i++) {
path.SetTo(iter_ref) ;
if (dir.Contains(path.Path()))
continue ;
fileReader = new FileReader(path.Path(), "ASCII") ;
doc = new Document ;
doc->add(*(new Field("contents", fileReader,
Field::STORE_NO | Field::INDEX_TOKENIZED))) ;
doc->add(*(new Field ("path", path.Path(),
Field::STORE_YES | Field::INDEX_UNTOKENIZED))) ;
indexWriter->addDocument(doc) ;
}
entryList->MakeEmpty() ;
be_app->PostMessage(&doneMessage) ;
release_sem(ref->sem) ;
suspend_thread(find_thread(NULL)) ;
}
return B_OK ;
}
<commit_msg>* Small, overlooked change in Indexer::CloseIndex(). Oops.<commit_after>/*
* Copyright 2009 Haiku, Inc.
* Distributed under the terms of the MIT License.
*
* Authors:
* Ankur Sethi (get.me.ankur@gmail.com)
*/
#include "Indexer.h"
#include "support.h"
#include <Directory.h>
#include <Entry.h>
#include <FindDirectory.h>
#include <NodeInfo.h>
#include <NodeMonitor.h>
#include <Path.h>
using namespace lucene::document ;
Indexer :: Indexer()
: BApplication("application/x-vnd.Haiku-BeaconDaemon"),
fIndexWriterList(1)
{
BMessage settings('sett') ;
if (load_settings(&settings) == B_OK)
LoadSettings(&settings) ;
}
void
Indexer ::ReadyToRun()
{
fQueryFeeder = new Feeder() ;
fQueryFeeder->StartWatching() ;
BVolume *volume ;
BList *volumeList = fQueryFeeder->GetVolumeList() ;
for (int i = 0 ; (volume = (BVolume*)volumeList->ItemAt(i)) != NULL ; i++)
InitIndex(volume) ;
UpdateIndex() ;
}
void
Indexer :: MessageReceived(BMessage *message)
{
index_writer_ref *ref = NULL ;
dev_t device ;
switch (message->what) {
case BEACON_UPDATE_INDEX :
UpdateIndex() ;
break ;
case BEACON_THREAD_DONE :
message->FindInt32("device", &device) ;
ref = FindIndexWriterRef(device) ;
acquire_sem(ref->sem) ;
break ;
case B_NODE_MONITOR :
HandleDeviceUpdate(message) ;
break ;
default :
BApplication :: MessageReceived(message) ;
}
}
bool
Indexer :: QuitRequested()
{
BMessage settings('sett') ;
fQueryFeeder->SaveSettings(&settings) ;
SaveSettings(&settings) ;
save_settings(&settings) ;
fQueryFeeder->PostMessage(B_QUIT_REQUESTED) ;
index_writer_ref *ref ;
status_t exitValue ;
for (int i = 0 ; (ref = (index_writer_ref*)fIndexWriterList.ItemAt(i))
!= NULL ; i++) {
delete_sem(ref->sem) ;
wait_for_thread(ref->thread, &exitValue) ;
ref->indexWriter->optimize() ;
ref->indexWriter->close() ;
}
return true ;
}
void
Indexer :: SaveSettings(BMessage *settings)
{
}
void
Indexer :: LoadSettings(BMessage *settings)
{
}
void
Indexer :: UpdateIndex()
{
entry_ref* iter_ref = new entry_ref ;
dev_t device = -1 ;
index_writer_ref *ref = NULL ;
while (fQueryFeeder->GetNextRef(iter_ref) == B_OK) {
if (ref == NULL || ref->device != iter_ref->device)
ref = FindIndexWriterRef(iter_ref->device) ;
if (ref != NULL && TranslatorAvailable(iter_ref))
ref->entryList->AddItem(iter_ref) ;
}
for (int i = 0 ; (ref = (index_writer_ref*)fIndexWriterList.ItemAt(i))
!= NULL ; i++) {
release_sem(ref->sem) ;
resume_thread(ref->thread) ;
}
}
void
Indexer :: InitIndex(BVolume *volume)
{
// TODO: handle errors.
index_writer_ref *ref = new index_writer_ref ;
char volume_name[B_FILE_NAME_LENGTH] ;
BDirectory dir ;
ref->device = volume->Device() ;
volume->GetRootDirectory(&dir) ;
ref->indexWriter = OpenIndex(&dir) ;
ref->entryList = new BList(10) ;
volume->GetName(volume_name) ;
ref->sem = create_sem(1, volume_name) ;
acquire_sem(ref->sem) ;
ref->thread = spawn_thread(add_document, volume_name, B_NORMAL_PRIORITY,
(void*)ref) ;
fIndexWriterList.AddItem((void*)ref) ;
}
IndexWriter*
Indexer :: OpenIndex(BDirectory *dir)
{
// TODO: handle errors.
IndexWriter *indexWriter = NULL ;
BPath path(dir) ;
path.Append("index") ;
if(create_directory(path.Path(), 0777) != B_OK)
return NULL ;
try {
if (IndexReader::indexExists(path.Path()))
indexWriter = new IndexWriter(path.Path(), &fStandardAnalyzer,
false) ;
else
indexWriter = new IndexWriter(path.Path(), &fStandardAnalyzer,
true) ;
} catch (CLuceneError) {
// Index is unreadable. Delete it and call OpenIndex() again.
BEntry entry ;
BDirectory indexDirectory(path.Path()) ;
while (indexDirectory.GetNextEntry(&entry, false) == B_OK)
entry.Remove() ;
indexWriter = OpenIndex(dir) ;
}
return indexWriter ;
}
bool
Indexer :: TranslatorAvailable(entry_ref *ref)
{
// For now, just return true if the file is a plain text file.
// Will change in the future when we have more translators.
BNode node(ref) ;
BNodeInfo nodeInfo(&node) ;
char MIMEString[B_MIME_TYPE_LENGTH] ;
nodeInfo.GetType(MIMEString) ;
if (!strcmp(MIMEString, "text/plain"))
return true ;
return false ;
}
void
Indexer :: HandleDeviceUpdate(BMessage *message)
{
int32 opcode ;
dev_t device ;
BVolume volume ;
message->FindInt32("opcode", &opcode) ;
switch (opcode) {
case B_DEVICE_MOUNTED :
message->FindInt32("new device", &device) ;
volume.SetTo(device) ;
InitIndex(&volume) ;
break ;
case B_DEVICE_UNMOUNTED :
message->FindInt32("device", &device) ;
volume.SetTo(device) ;
CloseIndex(&volume) ;
break ;
}
}
void
Indexer :: CloseIndex(BVolume *volume)
{
// Just removes the index_writer_ref from fIndexWriterList for now.
// This means unmounting or unplugging the USB will cause the index
// to become corrupted. TODO.
index_writer_ref *ref ;
for (int i = 0 ; (ref = (index_writer_ref*)fIndexWriterList.ItemAt(i)) != NULL
; i++) {
if (ref->device == volume->Device()) {
fIndexWriterList.RemoveItem(i) ;
kill_thread(ref->thread) ;
delete_sem(ref->sem) ;
delete ref ;
break ;
}
}
}
index_writer_ref*
Indexer :: FindIndexWriterRef(dev_t device)
{
index_writer_ref *iter_ref ;
for (int i = 0 ; (iter_ref = (index_writer_ref*)fIndexWriterList.ItemAt(i))
!= NULL ; i++) {
if (iter_ref->device == device)
return iter_ref ;
}
return NULL ;
}
int32 add_document(void *data)
{
index_writer_ref *ref = (index_writer_ref*)data ;
BList *entryList = ref->entryList ;
entry_ref *iter_ref ;
BMessage doneMessage(BEACON_THREAD_DONE) ;
doneMessage.AddInt32("device", ref->device) ;
BPath path ;
IndexWriter *indexWriter = ref->indexWriter ;
FileReader *fileReader ;
Document *doc ;
// Get path to the index directory on this particular
// volume.
BVolume volume(ref->device) ;
BDirectory dir ;
volume.GetRootDirectory(&dir) ;
path.SetTo(&dir) ;
path.Append("index") ;
dir.SetTo(path.Path()) ;
while (acquire_sem(ref->sem) >= B_NO_ERROR) {
for (int i = 0 ; (iter_ref = (entry_ref*)entryList->ItemAt(i)) != NULL
; i++) {
path.SetTo(iter_ref) ;
if (dir.Contains(path.Path()))
continue ;
fileReader = new FileReader(path.Path(), "ASCII") ;
doc = new Document ;
doc->add(*(new Field("contents", fileReader,
Field::STORE_NO | Field::INDEX_TOKENIZED))) ;
doc->add(*(new Field ("path", path.Path(),
Field::STORE_YES | Field::INDEX_UNTOKENIZED))) ;
indexWriter->addDocument(doc) ;
}
entryList->MakeEmpty() ;
be_app->PostMessage(&doneMessage) ;
release_sem(ref->sem) ;
suspend_thread(find_thread(NULL)) ;
}
return B_OK ;
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
/* interface header */
#include "CustomCone.h"
/* system headers */
#include <math.h>
#include <sstream>
#include <vector>
/* common implementation headers */
#include "ConeObstacle.h"
#include "PhysicsDriver.h"
#include "StateDatabase.h"
#include "ObstacleMgr.h"
/* bzfs implementation headers */
#include "ParseMaterial.h"
const char* CustomCone::sideNames[MaterialCount] = {
"edge",
"bottom",
"startside",
"endside"
};
CustomCone::CustomCone(bool pyramid)
{
// default to a (radius=10, height=10) cylinder
divisions = 16;
size[0] = size[1] = size[2] = 10.0f;
texsize[0] = texsize[1] = -8.0f;
angle = 360.0f;
phydrv = -1;
useNormals = true;
smoothBounce = false;
// setup the default textures
materials[Edge].setTexture("boxwall");
materials[Bottom].setTexture("roof");
materials[StartFace].setTexture("wall");
materials[EndFace].setTexture("wall");
pyramidStyle = pyramid;
if (pyramidStyle) {
flipz = false;
divisions = 4;
useNormals = false;
size[0] = size[1] = BZDB.eval(StateDatabase::BZDB_PYRBASE);
size[2] = BZDB.eval(StateDatabase::BZDB_PYRHEIGHT);
materials[Edge].setTexture("pyrwall");
materials[Bottom].setTexture("pyrwall");
materials[StartFace].setTexture("pyrwall");
materials[EndFace].setTexture("pyrwall");
}
return;
}
CustomCone::~CustomCone()
{
return;
}
bool CustomCone::read(const char *cmd, std::istream& input)
{
bool materror;
if (strcasecmp(cmd, "divisions") == 0) {
if (!(input >> divisions)) {
return false;
}
}
else if (strcasecmp(cmd, "angle") == 0) {
if (!(input >> angle)) {
return false;
}
}
else if (strcasecmp(cmd, "texsize") == 0) {
if (!(input >> texsize[0] >> texsize[1])) {
return false;
}
}
else if (strcasecmp(cmd, "phydrv") == 0) {
std::string drvname;
if (!(input >> drvname)) {
std::cout << "missing Physics Driver parameter" << std::endl;
return false;
}
phydrv = PHYDRVMGR.findDriver(drvname);
if ((phydrv == -1) && (drvname != "-1")) {
std::cout << "couldn't find PhysicsDriver: " << drvname << std::endl;
}
}
else if (strcasecmp(cmd, "smoothbounce") == 0) {
smoothBounce = true;
}
else if (strcasecmp(cmd, "flatshading") == 0) {
useNormals = false;
}
else if (parseMaterials(cmd, input, materials, MaterialCount, materror)) {
if (materror) {
return false;
}
}
else if (parseMaterialsByName(cmd, input, materials, sideNames,
MaterialCount, materror)) {
if (materror) {
return false;
}
}
else if (pyramidStyle && (strcasecmp(cmd, "flipz") == 0)) {
flipz = true;
}
else {
return WorldFileObstacle::read(cmd, input);
}
return true;
}
void CustomCone::writeToGroupDef(GroupDefinition *groupdef) const
{
int i;
const BzMaterial* mats[MaterialCount];
for (i = 0; i < MaterialCount; i++) {
mats[i] = MATERIALMGR.addMaterial(&materials[i]);
}
ConeObstacle* cone;
if (!pyramidStyle) {
cone = new ConeObstacle(transform, pos, size, rotation, angle,
texsize, useNormals, divisions, mats, phydrv,
smoothBounce, driveThrough, shootThrough);
} else {
const float zAxis[3] = {0.0f, 0.0f, 1.0f};
const float origin[3] = {0.0f, 0.0f, 0.0f};
MeshTransform xform;
if (flipz) {
const float flipScale[3] = {1.0f, -1.0f, -1.0f};
const float flipShift[3] = {0.0f, 0.0f, size[2]};
xform.addScale(flipScale);
xform.addShift(flipShift);
}
xform.addSpin((float)(rotation * (180.0 / M_PI)), zAxis);
xform.addShift(pos);
xform.append(transform);
float newSize[3];
newSize[0] = (float)(size[0] * M_SQRT2);
newSize[1] = (float)(size[1] * M_SQRT2);
newSize[2] = size[2];
cone = new ConeObstacle(xform, origin, newSize, (float)(M_PI * 0.25), angle,
texsize, useNormals, divisions, mats, phydrv,
smoothBounce, driveThrough, shootThrough);
}
if (cone->isValid()) {
groupdef->addObstacle(cone);
} else {
delete cone;
}
return;
}
// Local variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>touchup for meshpyr<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
/* interface header */
#include "CustomCone.h"
/* system headers */
#include <math.h>
#include <sstream>
#include <vector>
/* common implementation headers */
#include "ConeObstacle.h"
#include "PhysicsDriver.h"
#include "StateDatabase.h"
#include "ObstacleMgr.h"
/* bzfs implementation headers */
#include "ParseMaterial.h"
const char* CustomCone::sideNames[MaterialCount] = {
"edge",
"bottom",
"startside",
"endside"
};
CustomCone::CustomCone(bool pyramid)
{
// default to a (radius=10, height=10) cylinder
divisions = 16;
size[0] = size[1] = size[2] = 10.0f;
texsize[0] = texsize[1] = -8.0f;
angle = 360.0f;
phydrv = -1;
useNormals = true;
smoothBounce = false;
// setup the default textures
materials[Edge].setTexture("boxwall");
materials[Bottom].setTexture("roof");
materials[StartFace].setTexture("wall");
materials[EndFace].setTexture("wall");
pyramidStyle = pyramid;
if (pyramidStyle) {
flipz = false;
divisions = 4;
useNormals = false;
size[0] = size[1] = BZDB.eval(StateDatabase::BZDB_PYRBASE);
size[2] = BZDB.eval(StateDatabase::BZDB_PYRHEIGHT);
materials[Edge].setTexture("pyrwall");
materials[Bottom].setTexture("pyrwall");
materials[StartFace].setTexture("pyrwall");
materials[EndFace].setTexture("pyrwall");
}
return;
}
CustomCone::~CustomCone()
{
return;
}
bool CustomCone::read(const char *cmd, std::istream& input)
{
bool materror;
if (strcasecmp(cmd, "divisions") == 0) {
if (!(input >> divisions)) {
return false;
}
}
else if (strcasecmp(cmd, "angle") == 0) {
if (!(input >> angle)) {
return false;
}
}
else if (strcasecmp(cmd, "texsize") == 0) {
if (!(input >> texsize[0] >> texsize[1])) {
return false;
}
}
else if (strcasecmp(cmd, "phydrv") == 0) {
std::string drvname;
if (!(input >> drvname)) {
std::cout << "missing Physics Driver parameter" << std::endl;
return false;
}
phydrv = PHYDRVMGR.findDriver(drvname);
if ((phydrv == -1) && (drvname != "-1")) {
std::cout << "couldn't find PhysicsDriver: " << drvname << std::endl;
}
}
else if (strcasecmp(cmd, "smoothbounce") == 0) {
smoothBounce = true;
}
else if (strcasecmp(cmd, "flatshading") == 0) {
useNormals = false;
}
else if (parseMaterials(cmd, input, materials, MaterialCount, materror)) {
if (materror) {
return false;
}
}
else if (parseMaterialsByName(cmd, input, materials, sideNames,
MaterialCount, materror)) {
if (materror) {
return false;
}
}
else if (pyramidStyle && (strcasecmp(cmd, "flipz") == 0)) {
flipz = true;
}
else {
return WorldFileObstacle::read(cmd, input);
}
return true;
}
void CustomCone::writeToGroupDef(GroupDefinition *groupdef) const
{
int i;
const BzMaterial* mats[MaterialCount];
for (i = 0; i < MaterialCount; i++) {
mats[i] = MATERIALMGR.addMaterial(&materials[i]);
}
ConeObstacle* cone;
if (!pyramidStyle) {
cone = new ConeObstacle(transform, pos, size, rotation, angle,
texsize, useNormals, divisions, mats, phydrv,
smoothBounce, driveThrough, shootThrough);
} else {
const float zAxis[3] = {0.0f, 0.0f, 1.0f};
const float origin[3] = {0.0f, 0.0f, 0.0f};
MeshTransform xform;
if (flipz || (size[2] < 0.0f)) {
const float flipScale[3] = {1.0f, 1.0f, -1.0f};
const float flipShift[3] = {0.0f, 0.0f, -size[2]};
xform.addScale(flipScale);
xform.addShift(flipShift);
}
xform.addSpin((float)(rotation * (180.0 / M_PI)), zAxis);
xform.addShift(pos);
xform.append(transform);
float newSize[3];
newSize[0] = (float)(size[0] * M_SQRT2);
newSize[1] = (float)(size[1] * M_SQRT2);
newSize[2] = fabsf(size[2]);
cone = new ConeObstacle(xform, origin, newSize, (float)(M_PI * 0.25), angle,
texsize, useNormals, divisions, mats, phydrv,
smoothBounce, driveThrough, shootThrough);
}
if (cone->isValid()) {
groupdef->addObstacle(cone);
} else {
delete cone;
}
return;
}
// Local variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>#ifndef VISION_EDGEPOINT_HPP_
#define VISION_EDGEPOINT_HPP_
#include <cctag/geometry/Point.hpp>
#include <cctag/utils/Defines.hpp>
#include <cstddef>
#include <sys/types.h>
#include <cmath>
#include <iosfwd>
namespace cctag
{
class Label;
class EdgePoint : public cctag::Point2d<Eigen::Vector3i>
{
public:
EdgePoint()
: Point2d(0, 0)
, _grad(0.f,0.f)
, _normGrad( 0.f )
, _before( NULL )
, _after( NULL )
, _processed( 0 )
, _processedIn( false )
, _isMax( -1 )
, _edgeLinked( -1 )
, _nSegmentOut(-1)
, _flowLength (0)
,_processedAux(false)
{}
EdgePoint( const EdgePoint& p )
: Point2d( p )
, _grad( p._grad )
, _normGrad ( p._normGrad )
, _before( p._before )
, _after( p._after )
, _processed( 0 )
, _processedIn( false )
, _isMax( -1 )
, _edgeLinked( -1 )
, _nSegmentOut(-1)
, _flowLength (0)
, _processedAux(false)
{}
EdgePoint( const int vx, const int vy, const float vdx, const float vdy )
: Point2d( vx, vy )
, _before( NULL )
, _after( NULL )
, _processed( 0 )
, _processedIn( false )
, _isMax( -1 )
, _edgeLinked( -1 )
, _nSegmentOut(-1)
, _flowLength (0)
, _processedAux(false)
, _grad(0.f,0.f)
, _normGrad(0.f)
{
_grad << vdx , vdy;
_normGrad = std::sqrt( vdx * vdx + vdy * vdy );
}
Eigen::Vector2f gradient() const
{
return _grad;
}
float dX() const
{
return _grad(0);
}
float dY() const
{
return _grad(1);
}
float normGradient() const
{
return _normGrad ;
}
friend std::ostream& operator<<( std::ostream& os, const EdgePoint& eP );
std::vector<EdgePoint*> _voters;
EdgePoint* _before;
EdgePoint* _after;
size_t _processed;
bool _processedIn;
ssize_t _isMax;
ssize_t _edgeLinked;
ssize_t _nSegmentOut; // std::size_t _nSegmentOut;
float _flowLength;
bool _processedAux;
private:
Eigen::Vector2f _grad;
float _normGrad;
};
inline bool receivedMoreVoteThan(const EdgePoint * const p1, const EdgePoint * const p2)
{
return (p1->_isMax > p2->_isMax);
}
} // namespace cctag
#endif
<commit_msg>For CUDA: noop default constructor.<commit_after>#ifndef VISION_EDGEPOINT_HPP_
#define VISION_EDGEPOINT_HPP_
#include <cctag/geometry/Point.hpp>
#include <cctag/utils/Defines.hpp>
#include <cstddef>
#include <sys/types.h>
#include <cmath>
#include <iosfwd>
namespace cctag
{
class Label;
class EdgePoint : public cctag::Point2d<Eigen::Vector3i>
{
public:
#ifdef WITH_CUDA
EdgePoint() = default; // don't want to do any work in this in cuda part where it's constructed
#else
EdgePoint()
: Point2d(0, 0)
, _grad(0.f,0.f)
, _normGrad( 0.f )
, _before( NULL )
, _after( NULL )
, _processed( 0 )
, _processedIn( false )
, _isMax( -1 )
, _edgeLinked( -1 )
, _nSegmentOut(-1)
, _flowLength (0)
,_processedAux(false)
{}
#endif
EdgePoint( const EdgePoint& p )
: Point2d( p )
, _grad( p._grad )
, _normGrad ( p._normGrad )
, _before( p._before )
, _after( p._after )
, _processed( 0 )
, _processedIn( false )
, _isMax( -1 )
, _edgeLinked( -1 )
, _nSegmentOut(-1)
, _flowLength (0)
, _processedAux(false)
{}
EdgePoint( const int vx, const int vy, const float vdx, const float vdy )
: Point2d( vx, vy )
, _before( NULL )
, _after( NULL )
, _processed( 0 )
, _processedIn( false )
, _isMax( -1 )
, _edgeLinked( -1 )
, _nSegmentOut(-1)
, _flowLength (0)
, _processedAux(false)
, _grad(0.f,0.f)
, _normGrad(0.f)
{
_grad << vdx , vdy;
_normGrad = std::sqrt( vdx * vdx + vdy * vdy );
}
Eigen::Vector2f gradient() const
{
return _grad;
}
float dX() const
{
return _grad(0);
}
float dY() const
{
return _grad(1);
}
float normGradient() const
{
return _normGrad ;
}
friend std::ostream& operator<<( std::ostream& os, const EdgePoint& eP );
std::vector<EdgePoint*> _voters;
EdgePoint* _before;
EdgePoint* _after;
size_t _processed;
bool _processedIn;
ssize_t _isMax;
ssize_t _edgeLinked;
ssize_t _nSegmentOut; // std::size_t _nSegmentOut;
float _flowLength;
bool _processedAux;
private:
Eigen::Vector2f _grad;
float _normGrad;
};
inline bool receivedMoreVoteThan(const EdgePoint * const p1, const EdgePoint * const p2)
{
return (p1->_isMax > p2->_isMax);
}
} // namespace cctag
#endif
<|endoftext|> |
<commit_before>#include "cnn/dglstm.h"
#include <string>
#include <cassert>
#include <vector>
#include <iostream>
#include "cnn/nodes.h"
using namespace std;
using namespace cnn::expr;
namespace cnn {
enum { X2I, H2I, C2I, BI, X2F, H2F, C2F, BF, X2O, H2O, C2O, BO, X2C, H2C, BC, X2K, C2K, Q2K, BK, STAB, X2K0 };
DGLSTMBuilder::DGLSTMBuilder(unsigned ilayers,
unsigned input_dim,
unsigned hidden_dim,
Model* model)
{
layers = ilayers;
Parameters * p_x2k, *p_c2k, *p_q2k, *p_bk, *p_x2k0;
long layer_input_dim = input_dim;
input_dims = vector<unsigned>(layers, layer_input_dim);
p_x2k0 = model->add_parameters({ long(hidden_dim), long(layer_input_dim) });
for (unsigned i = 0; i < layers; ++i) {
input_dims[i] = layer_input_dim;
// i
Parameters* p_x2i = model->add_parameters({ long(hidden_dim), layer_input_dim });
Parameters* p_h2i = model->add_parameters({ long(hidden_dim), long(hidden_dim) });
Parameters* p_c2i = model->add_parameters({ long(hidden_dim), long(hidden_dim) });
Parameters* p_bi = model->add_parameters({ long(hidden_dim) });
// f
Parameters* p_x2f = model->add_parameters({ long(hidden_dim), layer_input_dim });
Parameters* p_h2f = model->add_parameters({ long(hidden_dim), long(hidden_dim) });
Parameters* p_c2f = model->add_parameters({ long(hidden_dim), long(hidden_dim) });
Parameters* p_bf = model->add_parameters({ long(hidden_dim) });
// o
Parameters* p_x2o = model->add_parameters({ long(hidden_dim), layer_input_dim });
Parameters* p_h2o = model->add_parameters({ long(hidden_dim), long(hidden_dim) });
Parameters* p_c2o = model->add_parameters({ long(hidden_dim), long(hidden_dim) });
Parameters* p_bo = model->add_parameters({ long(hidden_dim) });
// c
Parameters* p_x2c = model->add_parameters({ long(hidden_dim), layer_input_dim });
Parameters* p_h2c = model->add_parameters({ long(hidden_dim), long(hidden_dim) });
Parameters* p_bc = model->add_parameters({ long(hidden_dim) });
p_x2k = model->add_parameters({ long(hidden_dim), long(layer_input_dim) });
p_c2k = model->add_parameters({ long(hidden_dim) });
p_bk = model->add_parameters({ long(hidden_dim) });
p_q2k = model->add_parameters({ long(hidden_dim) });
layer_input_dim = hidden_dim; // output (hidden) from 1st layer is input to next
Parameters * p_stab = model->add_parameters({ 1 });
p_stab->reset_to_zero();
vector<Parameters*> ps;
if (i == 0)
ps = { p_x2i, p_h2i, p_c2i, p_bi, p_x2f, p_h2f, p_c2f, p_bf, p_x2o, p_h2o, p_c2o, p_bo, p_x2c, p_h2c, p_bc, p_x2k, p_c2k, p_q2k, p_bk, p_stab, p_x2k0 };
else
ps = { p_x2i, p_h2i, p_c2i, p_bi, p_x2f, p_h2f, p_c2f, p_bf, p_x2o, p_h2o, p_c2o, p_bo, p_x2c, p_h2c, p_bc, p_x2k, p_c2k, p_q2k, p_bk, p_stab };
params.push_back(ps);
} // layers
}
void DGLSTMBuilder::new_graph_impl(ComputationGraph& cg){
param_vars.clear();
for (unsigned i = 0; i < layers; ++i){
auto& p = params[i];
//i
Expression i_x2i = parameter(cg,p[X2I]);
Expression i_h2i = parameter(cg,p[H2I]);
Expression i_c2i = parameter(cg,p[C2I]);
Expression i_bi = parameter(cg,p[BI]);
//f
Expression i_x2f = parameter(cg, p[X2F]);
Expression i_h2f = parameter(cg, p[H2F]);
Expression i_c2f = parameter(cg, p[C2F]);
Expression i_bf = parameter(cg, p[BF]);
//o
Expression i_x2o = parameter(cg,p[X2O]);
Expression i_h2o = parameter(cg,p[H2O]);
Expression i_c2o = parameter(cg,p[C2O]);
Expression i_bo = parameter(cg,p[BO]);
//c
Expression i_x2c = parameter(cg,p[X2C]);
Expression i_h2c = parameter(cg,p[H2C]);
Expression i_bc = parameter(cg,p[BC]);
vector<Expression> vars;
//k
Expression i_x2k = parameter(cg, p[X2K]);
Expression i_q2k = parameter(cg, p[Q2K]);
Expression i_c2k = parameter(cg, p[C2K]);
Expression i_bk = parameter(cg, p[BK]);
Expression i_stab = parameter(cg, p[STAB]);
if (i == 0)
{
Expression i_x2k0 = parameter(cg, p[X2K0]);
vars = { i_x2i, i_h2i, i_c2i, i_bi, i_x2f, i_h2f, i_c2f, i_bf, i_x2o, i_h2o, i_c2o, i_bo, i_x2c, i_h2c, i_bc, i_x2k, i_c2k, i_q2k, i_bk, i_stab, i_x2k0 };
}
else
vars = { i_x2i, i_h2i, i_c2i, i_bi, i_x2f, i_h2f, i_c2f, i_bf, i_x2o, i_h2o, i_c2o, i_bo, i_x2c, i_h2c, i_bc, i_x2k, i_c2k, i_q2k, i_bk, i_stab };
param_vars.push_back(vars);
}
}
// layout: 0..layers = c
// layers+1..2*layers = h
void DGLSTMBuilder::start_new_sequence_impl(const vector<Expression>& hinit) {
h.clear();
c.clear();
if (hinit.size() > 0) {
assert(layers*2 == hinit.size());
h0.resize(layers);
c0.resize(layers);
for (unsigned i = 0; i < layers; ++i) {
c0[i] = hinit[i];
h0[i] = hinit[i + layers];
}
has_initial_state = true;
} else {
has_initial_state = false;
}
set_data_in_parallel(data_in_parallel());
}
void DGLSTMBuilder::set_data_in_parallel(int n)
{
RNNBuilder::set_data_in_parallel(n);
biases.clear();
for (unsigned i = 0; i < layers; ++i) {
const vector<Expression>& vars = param_vars[i];
Expression bimb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BI]));
Expression bfmb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BF]));
Expression bcmb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BC]));
Expression bomb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BO]));
Expression bkmb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BK]));
Expression mc2kmb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[C2K]));
Expression mq2kmb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[Q2K]));
Expression i_stabilizer = exp(vars[STAB]);
Expression i_stab = concatenate(vector<Expression>(input_dims[i], i_stabilizer)); /// self stabilizer
vector<Expression> b = { bimb, bfmb, bcmb, bomb, bkmb, mc2kmb, mq2kmb, i_stab };
biases.push_back(b);
}
}
Expression DGLSTMBuilder::add_input_impl(int prev, const Expression& x) {
h.push_back(vector<Expression>(layers));
c.push_back(vector<Expression>(layers));
vector<Expression>& ht = h.back();
vector<Expression>& ct = c.back();
Expression lower_layer_c = x; /// at layer 0, no lower memory but observation
Expression in = x;
Expression in_stb;
int nutt = data_in_parallel();
for (unsigned i = 0; i < layers; ++i) {
const vector<Expression>& vars = param_vars[i];
Expression i_stabilizer = biases[i][7];
Expression i_v_stab = concatenate_cols(vector<Expression>(nutt, i_stabilizer));
in_stb = cwise_multiply(i_v_stab, in);
Expression i_h_tm1, i_c_tm1;
bool has_prev_state = (prev >= 0 || has_initial_state);
if (prev < 0) {
if (has_initial_state) {
// intial value for h and c at timestep 0 in layer i
// defaults to zero matrix input if not set in add_parameter_edges
i_h_tm1 = h0[i];
i_c_tm1 = c0[i];
}
} else { // t > 0
i_h_tm1 = h[prev][i];
i_c_tm1 = c[prev][i];
}
// input
Expression i_ait;
Expression bimb = biases[i][0];
if (has_prev_state)
i_ait = affine_transform({ bimb, vars[X2I], in_stb, vars[H2I], i_h_tm1, vars[C2I], i_c_tm1 });
else
i_ait = affine_transform({ bimb, vars[X2I], in_stb });
Expression i_it = logistic(i_ait);
// forget
// input
Expression i_aft;
Expression bfmb = biases[i][1];
if (has_prev_state)
i_ait = affine_transform({ bfmb, vars[X2F], in_stb, vars[H2F], i_h_tm1, vars[C2F], i_c_tm1 });
else
i_ait = affine_transform({ bfmb, vars[X2F], in_stb });
Expression i_ft = logistic(i_ait);
// write memory cell
Expression bcmb = biases[i][2];
Expression i_awt;
if (has_prev_state)
i_awt = affine_transform({ bcmb, vars[X2C], in_stb, vars[H2C], i_h_tm1 });
else
i_awt = affine_transform({ bcmb, vars[X2C], in_stb });
Expression i_wt = tanh(i_awt);
// output
Expression i_before_add_with_lower_linearly;
if (has_prev_state) {
Expression i_nwt = cwise_multiply(i_it,i_wt);
Expression i_crt = cwise_multiply(i_ft,i_c_tm1);
i_before_add_with_lower_linearly = i_crt + i_nwt;
} else {
i_before_add_with_lower_linearly = cwise_multiply(i_it, i_wt);
}
/// add lower layer memory cell
Expression i_k_t;
Expression bkmb = biases[i][4];
Expression i_k_lowerc = bkmb;
if (i > 0)
{
Expression mc2kmb = biases[i][5];
i_k_lowerc = i_k_lowerc + cwise_multiply(mc2kmb, lower_layer_c);
}
if (has_prev_state)
{
Expression q2kmb = biases[i][6];
i_k_t = logistic(i_k_lowerc + vars[X2K] * in_stb + cwise_multiply(q2kmb, i_c_tm1));
}
else
i_k_t = logistic(i_k_lowerc + vars[X2K] * in_stb);
ct[i] = i_before_add_with_lower_linearly + cwise_multiply(i_k_t, (i == 0) ? vars[X2K0] * lower_layer_c : lower_layer_c);
Expression i_aot;
Expression bomb = biases[i][3];
if (has_prev_state)
i_aot = affine_transform({bomb, vars[X2O], in_stb, vars[H2O], i_h_tm1, vars[C2O], ct[i]});
else
i_aot = affine_transform({ bomb, vars[X2O], in_stb });
Expression i_ot = logistic(i_aot);
Expression ph_t = tanh(ct[i]);
in = ht[i] = cwise_multiply(i_ot,ph_t);
lower_layer_c = ct[i];
}
return ht.back();
}
void DGLSTMBuilder::copy(const RNNBuilder & rnn) {
const DGLSTMBuilder & rnn_lstm = (const DGLSTMBuilder&)rnn;
assert(params.size() == rnn_lstm.params.size());
for(size_t i = 0; i < params.size(); ++i)
for(size_t j = 0; j < params[i].size(); ++j)
params[i][j]->copy(*rnn_lstm.params[i][j]);
}
} // namespace cnn
<commit_msg>fix bug in dglstm<commit_after>#include "cnn/dglstm.h"
#include <string>
#include <cassert>
#include <vector>
#include <iostream>
#include "cnn/nodes.h"
using namespace std;
using namespace cnn::expr;
namespace cnn {
enum { X2I, H2I, C2I, BI, X2F, H2F, C2F, BF, X2O, H2O, C2O, BO, X2C, H2C, BC, X2K, C2K, Q2K, BK, STAB, X2K0 };
DGLSTMBuilder::DGLSTMBuilder(unsigned ilayers,
unsigned input_dim,
unsigned hidden_dim,
Model* model)
{
layers = ilayers;
Parameters * p_x2k, *p_c2k, *p_q2k, *p_bk, *p_x2k0;
long layer_input_dim = input_dim;
input_dims = vector<unsigned>(layers, layer_input_dim);
p_x2k0 = model->add_parameters({ long(hidden_dim), long(layer_input_dim) });
for (unsigned i = 0; i < layers; ++i) {
input_dims[i] = layer_input_dim;
// i
Parameters* p_x2i = model->add_parameters({ long(hidden_dim), layer_input_dim });
Parameters* p_h2i = model->add_parameters({ long(hidden_dim), long(hidden_dim) });
Parameters* p_c2i = model->add_parameters({ long(hidden_dim), long(hidden_dim) });
Parameters* p_bi = model->add_parameters({ long(hidden_dim) });
// f
Parameters* p_x2f = model->add_parameters({ long(hidden_dim), layer_input_dim });
Parameters* p_h2f = model->add_parameters({ long(hidden_dim), long(hidden_dim) });
Parameters* p_c2f = model->add_parameters({ long(hidden_dim), long(hidden_dim) });
Parameters* p_bf = model->add_parameters({ long(hidden_dim) });
// o
Parameters* p_x2o = model->add_parameters({ long(hidden_dim), layer_input_dim });
Parameters* p_h2o = model->add_parameters({ long(hidden_dim), long(hidden_dim) });
Parameters* p_c2o = model->add_parameters({ long(hidden_dim), long(hidden_dim) });
Parameters* p_bo = model->add_parameters({ long(hidden_dim) });
// c
Parameters* p_x2c = model->add_parameters({ long(hidden_dim), layer_input_dim });
Parameters* p_h2c = model->add_parameters({ long(hidden_dim), long(hidden_dim) });
Parameters* p_bc = model->add_parameters({ long(hidden_dim) });
p_x2k = model->add_parameters({ long(hidden_dim), long(layer_input_dim) });
p_c2k = model->add_parameters({ long(hidden_dim) });
p_bk = model->add_parameters({ long(hidden_dim) });
p_q2k = model->add_parameters({ long(hidden_dim) });
layer_input_dim = hidden_dim; // output (hidden) from 1st layer is input to next
Parameters * p_stab = model->add_parameters({ 1 });
p_stab->reset_to_zero();
vector<Parameters*> ps;
if (i == 0)
ps = { p_x2i, p_h2i, p_c2i, p_bi, p_x2f, p_h2f, p_c2f, p_bf, p_x2o, p_h2o, p_c2o, p_bo, p_x2c, p_h2c, p_bc, p_x2k, p_c2k, p_q2k, p_bk, p_stab, p_x2k0 };
else
ps = { p_x2i, p_h2i, p_c2i, p_bi, p_x2f, p_h2f, p_c2f, p_bf, p_x2o, p_h2o, p_c2o, p_bo, p_x2c, p_h2c, p_bc, p_x2k, p_c2k, p_q2k, p_bk, p_stab };
params.push_back(ps);
} // layers
}
void DGLSTMBuilder::new_graph_impl(ComputationGraph& cg){
param_vars.clear();
for (unsigned i = 0; i < layers; ++i){
auto& p = params[i];
//i
Expression i_x2i = parameter(cg,p[X2I]);
Expression i_h2i = parameter(cg,p[H2I]);
Expression i_c2i = parameter(cg,p[C2I]);
Expression i_bi = parameter(cg,p[BI]);
//f
Expression i_x2f = parameter(cg, p[X2F]);
Expression i_h2f = parameter(cg, p[H2F]);
Expression i_c2f = parameter(cg, p[C2F]);
Expression i_bf = parameter(cg, p[BF]);
//o
Expression i_x2o = parameter(cg,p[X2O]);
Expression i_h2o = parameter(cg,p[H2O]);
Expression i_c2o = parameter(cg,p[C2O]);
Expression i_bo = parameter(cg,p[BO]);
//c
Expression i_x2c = parameter(cg,p[X2C]);
Expression i_h2c = parameter(cg,p[H2C]);
Expression i_bc = parameter(cg,p[BC]);
vector<Expression> vars;
//k
Expression i_x2k = parameter(cg, p[X2K]);
Expression i_q2k = parameter(cg, p[Q2K]);
Expression i_c2k = parameter(cg, p[C2K]);
Expression i_bk = parameter(cg, p[BK]);
Expression i_stab = parameter(cg, p[STAB]);
if (i == 0)
{
Expression i_x2k0 = parameter(cg, p[X2K0]);
vars = { i_x2i, i_h2i, i_c2i, i_bi, i_x2f, i_h2f, i_c2f, i_bf, i_x2o, i_h2o, i_c2o, i_bo, i_x2c, i_h2c, i_bc, i_x2k, i_c2k, i_q2k, i_bk, i_stab, i_x2k0 };
}
else
vars = { i_x2i, i_h2i, i_c2i, i_bi, i_x2f, i_h2f, i_c2f, i_bf, i_x2o, i_h2o, i_c2o, i_bo, i_x2c, i_h2c, i_bc, i_x2k, i_c2k, i_q2k, i_bk, i_stab };
param_vars.push_back(vars);
}
}
// layout: 0..layers = c
// layers+1..2*layers = h
void DGLSTMBuilder::start_new_sequence_impl(const vector<Expression>& hinit) {
h.clear();
c.clear();
if (hinit.size() > 0) {
assert(layers*2 == hinit.size());
h0.resize(layers);
c0.resize(layers);
for (unsigned i = 0; i < layers; ++i) {
c0[i] = hinit[i];
h0[i] = hinit[i + layers];
}
has_initial_state = true;
} else {
has_initial_state = false;
}
set_data_in_parallel(data_in_parallel());
}
void DGLSTMBuilder::set_data_in_parallel(int n)
{
RNNBuilder::set_data_in_parallel(n);
biases.clear();
for (unsigned i = 0; i < layers; ++i) {
const vector<Expression>& vars = param_vars[i];
Expression bimb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BI]));
Expression bfmb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BF]));
Expression bcmb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BC]));
Expression bomb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BO]));
Expression bkmb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[BK]));
Expression mc2kmb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[C2K]));
Expression mq2kmb = concatenate_cols(vector<Expression>(data_in_parallel(), vars[Q2K]));
Expression i_stabilizer = exp(vars[STAB]);
Expression i_stab = concatenate(vector<Expression>(input_dims[i], i_stabilizer)); /// self stabilizer
vector<Expression> b = { bimb, bfmb, bcmb, bomb, bkmb, mc2kmb, mq2kmb, i_stab };
biases.push_back(b);
}
}
Expression DGLSTMBuilder::add_input_impl(int prev, const Expression& x) {
h.push_back(vector<Expression>(layers));
c.push_back(vector<Expression>(layers));
vector<Expression>& ht = h.back();
vector<Expression>& ct = c.back();
Expression lower_layer_c = x; /// at layer 0, no lower memory but observation
Expression in = x;
Expression in_stb;
int nutt = data_in_parallel();
for (unsigned i = 0; i < layers; ++i) {
const vector<Expression>& vars = param_vars[i];
Expression i_stabilizer = biases[i][7];
Expression i_v_stab = concatenate_cols(vector<Expression>(nutt, i_stabilizer));
in_stb = cwise_multiply(i_v_stab, in);
Expression i_h_tm1, i_c_tm1;
bool has_prev_state = (prev >= 0 || has_initial_state);
if (prev < 0) {
if (has_initial_state) {
// intial value for h and c at timestep 0 in layer i
// defaults to zero matrix input if not set in add_parameter_edges
i_h_tm1 = h0[i];
i_c_tm1 = c0[i];
}
} else { // t > 0
i_h_tm1 = h[prev][i];
i_c_tm1 = c[prev][i];
}
// input
Expression i_ait;
Expression bimb = biases[i][0];
if (has_prev_state)
i_ait = affine_transform({ bimb, vars[X2I], in_stb, vars[H2I], i_h_tm1, vars[C2I], i_c_tm1 });
else
i_ait = affine_transform({ bimb, vars[X2I], in_stb });
Expression i_it = logistic(i_ait);
// forget
// input
Expression i_aft;
Expression bfmb = biases[i][1];
if (has_prev_state)
i_aft = affine_transform({ bfmb, vars[X2F], in_stb, vars[H2F], i_h_tm1, vars[C2F], i_c_tm1 });
else
i_aft = affine_transform({ bfmb, vars[X2F], in_stb });
Expression i_ft = logistic(i_aft);
// write memory cell
Expression bcmb = biases[i][2];
Expression i_awt;
if (has_prev_state)
i_awt = affine_transform({ bcmb, vars[X2C], in_stb, vars[H2C], i_h_tm1 });
else
i_awt = affine_transform({ bcmb, vars[X2C], in_stb });
Expression i_wt = tanh(i_awt);
// output
Expression i_before_add_with_lower_linearly;
if (has_prev_state) {
Expression i_nwt = cwise_multiply(i_it,i_wt);
Expression i_crt = cwise_multiply(i_ft,i_c_tm1);
i_before_add_with_lower_linearly = i_crt + i_nwt;
} else {
i_before_add_with_lower_linearly = cwise_multiply(i_it, i_wt);
}
/// add lower layer memory cell
Expression i_k_t;
Expression bkmb = biases[i][4];
Expression i_k_lowerc = bkmb;
if (i > 0)
{
Expression mc2kmb = biases[i][5];
i_k_lowerc = i_k_lowerc + cwise_multiply(mc2kmb, lower_layer_c);
}
if (has_prev_state)
{
Expression q2kmb = biases[i][6];
i_k_t = logistic(i_k_lowerc + vars[X2K] * in_stb + cwise_multiply(q2kmb, i_c_tm1));
}
else
i_k_t = logistic(i_k_lowerc + vars[X2K] * in_stb);
ct[i] = i_before_add_with_lower_linearly + cwise_multiply(i_k_t, (i == 0) ? vars[X2K0] * lower_layer_c : lower_layer_c);
Expression i_aot;
Expression bomb = biases[i][3];
if (has_prev_state)
i_aot = affine_transform({bomb, vars[X2O], in_stb, vars[H2O], i_h_tm1, vars[C2O], ct[i]});
else
i_aot = affine_transform({ bomb, vars[X2O], in_stb });
Expression i_ot = logistic(i_aot);
Expression ph_t = tanh(ct[i]);
in = ht[i] = cwise_multiply(i_ot,ph_t);
lower_layer_c = ct[i];
}
return ht.back();
}
void DGLSTMBuilder::copy(const RNNBuilder & rnn) {
const DGLSTMBuilder & rnn_lstm = (const DGLSTMBuilder&)rnn;
assert(params.size() == rnn_lstm.params.size());
for(size_t i = 0; i < params.size(); ++i)
for(size_t j = 0; j < params[i].size(); ++j)
params[i][j]->copy(*rnn_lstm.params[i][j]);
}
} // namespace cnn
<|endoftext|> |
<commit_before>/* This file is part of qjson
*
* Copyright (C) 2009 Till Adam <adam@kde.org>
* Copyright (C) 2009 Flavio Castelli <flavio@castelli.name>
* Copyright (C) 2013 BMW Car IT GmbH
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "serializer.h"
#include <QtCore/QDataStream>
#include <QtCore/QStringList>
#include <QtCore/QVariant>
#include <QtCore/QMetaObject>
#include <QtCore/QMetaProperty>
#include <QtCore/QMap>
#include <QtCore/QMetaEnum>
#include <QtCore/QMutex>
#include <iostream>
using namespace QJson;
QMutex* Serializer::enumIdsMutex = new QMutex();
QMap<int, QMetaEnum>* Serializer::enumIds = new QMap<int,QMetaEnum>();
class Serializer::SerializerPrivate {
};
Serializer::Serializer() : d( new SerializerPrivate ) {
}
Serializer::~Serializer() {
delete d;
}
void Serializer::registerEnum( int typeId, const QMetaEnum& meta )
{
QMutexLocker locker(enumIdsMutex);
if (!enumIds->contains(typeId)) {
enumIds->insert(typeId, meta);
}
}
void Serializer::serialize( const QVariant& v, QIODevice* io, bool* ok )
{
Q_ASSERT( io );
if (!io->isOpen()) {
if (!io->open(QIODevice::WriteOnly)) {
if ( ok != 0 )
*ok = false;
qCritical ("Error opening device");
return;
}
}
if (!io->isWritable()) {
if (ok != 0)
*ok = false;
qCritical ("Device is not readable");
io->close();
return;
}
const QByteArray str = serialize( v );
if ( !str.isNull() ) {
QDataStream stream( io );
stream << str;
} else {
if ( ok )
*ok = false;
}
}
// Delimits special characters in a string and surrounds the string in quotes
// Returns a QByteArray in UTF-8 format
static QByteArray sanitizeString( const QString& str )
{
QByteArray ret;
const QChar *data = str.constData();
// Add the first quote
ret.append('"');
// Delimit special characters
int length = str.length();
for (int i = 0; i < length; i++) {
char ch = data[i].toLatin1();
switch(ch) {
case '\\' :
case '\"' :
case '\b' :
case '\f' :
case '\n' :
case '\r' :
case '\t' :
ret.append('\\');
ret.append(ch);
break;
default:
ret.append(QString(data[i]).toUtf8());
}
}
// Add the final quote
ret.append('"');
return ret;
}
// Delimits special characters in a byte array and surrounds the string in quotes
// Returns a QByteArray in UTF-8 format
static QByteArray sanitizeByteArray( const QByteArray& array )
{
QByteArray ret;
const char *data = array.constData();
// Add the first quote
ret.append('"');
// Delimit special characters
int length = array.length();
for (int i = 0; i < length; i++) {
char ch = data[i];
switch(ch) {
case '\\' :
case '\"' :
case '\b' :
case '\f' :
case '\n' :
case '\r' :
case '\t' :
ret.append('\\');
ret.append(ch);
break;
default:
ret.append(ch);
}
}
// Add the final quote
ret.append('"');
return ret;
}
QByteArray Serializer::serialize( const QVariant &v )
{
QByteArray str;
bool error = false;
if ( ! v.isValid() ) { // invalid or null?
str = "null";
} else if ( v.type() == QVariant::List ) { // variant is a list?
const QVariantList list = v.toList();
str = "[";
bool first = true;
Q_FOREACH( const QVariant& v, list )
{
QByteArray serializedValue = serialize( v );
if ( serializedValue.isNull() ) {
error = true;
break;
}
if (!first) {
str.append(",");
} else {
first = false;
}
str.append(serializedValue);
}
str.append("]");
} else if ( v.type() == QVariant::Map ) { // variant is a map?
const QVariantMap vmap = v.toMap();
QMapIterator<QString, QVariant> it( vmap );
str = "{";
bool first = true;
while ( it.hasNext() ) {
it.next();
QByteArray serializedValue = serialize( it.value() );
if ( serializedValue.isNull() ) {
error = true;
break;
}
if (!first) {
str.append(",");
} else {
first = false;
}
str.append(sanitizeString(it.key()));
str.append(":");
str.append(serializedValue);
}
str.append("}");
} else if ( v.type() == QVariant::String ) { // a string
str = sanitizeString( v.toString() );
} else if ( v.type() == QVariant::ByteArray ) { // a byte array?
str = sanitizeByteArray( v.toByteArray() );
} else if ( v.type() == QVariant::Double ) { // a double?
str = QByteArray::number( v.toDouble(), 'g', 15 );
if( ! str.contains( "." ) && ! str.contains( "e" ) ) {
str += ".0";
}
} else if ( v.type() == QVariant::Bool ) { // boolean value?
str = ( v.toBool() ? "true" : "false" );
// remember the current state of GCC diagnostics
#pragma GCC diagnostic push
// disable GCC enum-compare warning:
// Although v.type() is declared as returning QVariant::Type, the return value
// should be interpreted as QMetaType::Type (cf. http://qt-project.org/doc/qt-5/qvariant.html#type).
#pragma GCC diagnostic ignored "-Wenum-compare"
} else if ( v.type() == QMetaType::UChar // quint8, unsigned char
|| v.type() == QMetaType::UShort // quint16, unsigned short
|| v.type() == QMetaType::UInt // quint32, unsigned int
|| v.type() == QMetaType::ULong
|| v.type() == QMetaType::ULongLong // quint64, unsigned long long
) {
// restore previous state of GCC diagnostics
#pragma GCC diagnostic pop
str = QByteArray::number( v.value<qulonglong>() );
// remember the current state of GCC diagnostics
#pragma GCC diagnostic push
// disable GCC enum-compare warning:
// Although v.type() is declared as returning QVariant::Type, the return value
// should be interpreted as QMetaType::Type (cf. http://qt-project.org/doc/qt-5/qvariant.html#type).
#pragma GCC diagnostic ignored "-Wenum-compare"
} else if ( v.type() == QMetaType::SChar // qint8, (signed) char
|| v.type() == QMetaType::Char
|| v.type() == QMetaType::Short // qint16, (signed) short
|| v.type() == QMetaType::Int // qint32, (signed) int
|| v.type() == QMetaType::Long
|| v.type() == QMetaType::LongLong // qint64, (signed) long long
) {
// restore previous state of GCC diagnostics
#pragma GCC diagnostic pop
str = QByteArray::number( v.value<qlonglong>() );
} else if (v.type() == QVariant::UserType) {
int typeId = v.userType();
// Does the variant contain a user defined enum?
if (enumIds->contains(typeId)) {
// enum
QMetaEnum metaEnum = enumIds->value(typeId);
// Convert the enum value to a key
const int *pvalue = static_cast<const int *>(v.constData());
QString key = QLatin1String(metaEnum.valueToKey(*pvalue));
str = sanitizeString(key);
} else {
// QObject
//If this point is reached, we know it came from a QObject of some sort
const QObject *obj = static_cast<const QObject*>(v.constData());
QVariantMap result;
const QMetaObject *metaobject = obj->metaObject();
QVariant typeNameVariant(turnMetaObjectIntoTypename(metaobject));
result[QString::fromLatin1("_typeName")] = typeNameVariant;
int count = metaobject->propertyCount();
for (int i = 0; i < count; ++i) {
QMetaProperty metaproperty = metaobject->property(i);
const char *name = metaproperty.name();
// const char *typeName = metaproperty.typeName();
if (!metaproperty.isReadable() || !strcmp(name, "objectName")) {
continue;
}
QVariant value = obj->property(name);
result[QLatin1String(name)] = value;
// The line below sometimes fails with VisualStudio, see Joynr-1121
// std::cerr << "name: " << name << ", type: " << value.typeName() << std::endl;
// if (!strcmp(typeName, "QVariant")){// && value.type() == QVariant::UserType){
// const QObject *obj2 = static_cast<const QObject*>(value.constData());
// const QMetaObject *metaobject2 = obj2->metaObject();
// QVariant typeNameVariant(QString(metaobject2->className()));
// std::cout << metaobject2->className() << std::endl;
// result[QLatin1String(name)+ QLatin1String("_typeName")] = typeNameVariant;
// }
}
str = serialize( result );
}
} else if ( v.canConvert<QString>() ){ // Last chance: can value be converted to string?
// this will catch QDate, QDateTime, QUrl, ...
str = sanitizeString( v.toString() );
//TODO: catch other values like QImage, QRect, ...
} else {
// unable to serialize QVariant
// TODO: error handling
error = true;
}
if ( !error )
return str;
else
return QByteArray();
}
QString Serializer::turnMetaObjectIntoTypename(const QMetaObject* metaObject){
static QString dot = QString::fromLatin1(".");
static QString doubleColon = QString::fromLatin1("::");
QString fullClassName = QString::fromLatin1(metaObject->className());
return fullClassName.replace(doubleColon, dot);
}
<commit_msg>Changed the delimiting of control characters.<commit_after>/* This file is part of qjson
*
* Copyright (C) 2009 Till Adam <adam@kde.org>
* Copyright (C) 2009 Flavio Castelli <flavio@castelli.name>
* Copyright (C) 2013 BMW Car IT GmbH
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "serializer.h"
#include <QtCore/QDataStream>
#include <QtCore/QStringList>
#include <QtCore/QVariant>
#include <QtCore/QMetaObject>
#include <QtCore/QMetaProperty>
#include <QtCore/QMap>
#include <QtCore/QMetaEnum>
#include <QtCore/QMutex>
#include <iostream>
using namespace QJson;
QMutex* Serializer::enumIdsMutex = new QMutex();
QMap<int, QMetaEnum>* Serializer::enumIds = new QMap<int,QMetaEnum>();
class Serializer::SerializerPrivate {
};
Serializer::Serializer() : d( new SerializerPrivate ) {
}
Serializer::~Serializer() {
delete d;
}
void Serializer::registerEnum( int typeId, const QMetaEnum& meta )
{
QMutexLocker locker(enumIdsMutex);
if (!enumIds->contains(typeId)) {
enumIds->insert(typeId, meta);
}
}
void Serializer::serialize( const QVariant& v, QIODevice* io, bool* ok )
{
Q_ASSERT( io );
if (!io->isOpen()) {
if (!io->open(QIODevice::WriteOnly)) {
if ( ok != 0 )
*ok = false;
qCritical ("Error opening device");
return;
}
}
if (!io->isWritable()) {
if (ok != 0)
*ok = false;
qCritical ("Device is not readable");
io->close();
return;
}
const QByteArray str = serialize( v );
if ( !str.isNull() ) {
QDataStream stream( io );
stream << str;
} else {
if ( ok )
*ok = false;
}
}
// Delimits special characters in a string and surrounds the string in quotes
// Returns a QByteArray in UTF-8 format
static QByteArray sanitizeString( const QString& str )
{
QByteArray ret;
const QChar *data = str.constData();
// Add the first quote
ret.append('"');
// Delimit special characters
int length = str.length();
for (int i = 0; i < length; i++) {
char ch = data[i].toLatin1();
switch(ch) {
case '\b' :
ret.append("\\b");
break;
case '\f' :
ret.append("\\f");
break;
case '\n' :
ret.append("\\n");
break;
case '\r' :
ret.append("\\r");
break;
case '\t' :
ret.append("\\t");
break;
case '\\' :
case '\"' :
ret.append('\\');
ret.append(ch);
break;
default:
ret.append(QString(data[i]).toUtf8());
}
}
// Add the final quote
ret.append('"');
return ret;
}
// Delimits special characters in a byte array and surrounds the string in quotes
// Returns a QByteArray in UTF-8 format
static QByteArray sanitizeByteArray( const QByteArray& array )
{
QByteArray ret;
const char *data = array.constData();
// Add the first quote
ret.append('"');
// Delimit special characters
int length = array.length();
for (int i = 0; i < length; i++) {
char ch = data[i];
switch(ch) {
case '\b' :
ret.append("\\b");
break;
case '\f' :
ret.append("\\f");
break;
case '\n' :
ret.append("\\n");
break;
case '\r' :
ret.append("\\r");
break;
case '\t' :
ret.append("\\t");
break;
case '\\' :
case '\"' :
ret.append('\\');
ret.append(ch);
break;
default:
ret.append(ch);
}
}
// Add the final quote
ret.append('"');
return ret;
}
QByteArray Serializer::serialize( const QVariant &v )
{
QByteArray str;
bool error = false;
if ( ! v.isValid() ) { // invalid or null?
str = "null";
} else if ( v.type() == QVariant::List ) { // variant is a list?
const QVariantList list = v.toList();
str = "[";
bool first = true;
Q_FOREACH( const QVariant& v, list )
{
QByteArray serializedValue = serialize( v );
if ( serializedValue.isNull() ) {
error = true;
break;
}
if (!first) {
str.append(",");
} else {
first = false;
}
str.append(serializedValue);
}
str.append("]");
} else if ( v.type() == QVariant::Map ) { // variant is a map?
const QVariantMap vmap = v.toMap();
QMapIterator<QString, QVariant> it( vmap );
str = "{";
bool first = true;
while ( it.hasNext() ) {
it.next();
QByteArray serializedValue = serialize( it.value() );
if ( serializedValue.isNull() ) {
error = true;
break;
}
if (!first) {
str.append(",");
} else {
first = false;
}
str.append(sanitizeString(it.key()));
str.append(":");
str.append(serializedValue);
}
str.append("}");
} else if ( v.type() == QVariant::String ) { // a string
str = sanitizeString( v.toString() );
} else if ( v.type() == QVariant::ByteArray ) { // a byte array?
str = sanitizeByteArray( v.toByteArray() );
} else if ( v.type() == QVariant::Double ) { // a double?
str = QByteArray::number( v.toDouble(), 'g', 15 );
if( ! str.contains( "." ) && ! str.contains( "e" ) ) {
str += ".0";
}
} else if ( v.type() == QVariant::Bool ) { // boolean value?
str = ( v.toBool() ? "true" : "false" );
// remember the current state of GCC diagnostics
#pragma GCC diagnostic push
// disable GCC enum-compare warning:
// Although v.type() is declared as returning QVariant::Type, the return value
// should be interpreted as QMetaType::Type (cf. http://qt-project.org/doc/qt-5/qvariant.html#type).
#pragma GCC diagnostic ignored "-Wenum-compare"
} else if ( v.type() == QMetaType::UChar // quint8, unsigned char
|| v.type() == QMetaType::UShort // quint16, unsigned short
|| v.type() == QMetaType::UInt // quint32, unsigned int
|| v.type() == QMetaType::ULong
|| v.type() == QMetaType::ULongLong // quint64, unsigned long long
) {
// restore previous state of GCC diagnostics
#pragma GCC diagnostic pop
str = QByteArray::number( v.value<qulonglong>() );
// remember the current state of GCC diagnostics
#pragma GCC diagnostic push
// disable GCC enum-compare warning:
// Although v.type() is declared as returning QVariant::Type, the return value
// should be interpreted as QMetaType::Type (cf. http://qt-project.org/doc/qt-5/qvariant.html#type).
#pragma GCC diagnostic ignored "-Wenum-compare"
} else if ( v.type() == QMetaType::SChar // qint8, (signed) char
|| v.type() == QMetaType::Char
|| v.type() == QMetaType::Short // qint16, (signed) short
|| v.type() == QMetaType::Int // qint32, (signed) int
|| v.type() == QMetaType::Long
|| v.type() == QMetaType::LongLong // qint64, (signed) long long
) {
// restore previous state of GCC diagnostics
#pragma GCC diagnostic pop
str = QByteArray::number( v.value<qlonglong>() );
} else if (v.type() == QVariant::UserType) {
int typeId = v.userType();
// Does the variant contain a user defined enum?
if (enumIds->contains(typeId)) {
// enum
QMetaEnum metaEnum = enumIds->value(typeId);
// Convert the enum value to a key
const int *pvalue = static_cast<const int *>(v.constData());
QString key = QLatin1String(metaEnum.valueToKey(*pvalue));
str = sanitizeString(key);
} else {
// QObject
//If this point is reached, we know it came from a QObject of some sort
const QObject *obj = static_cast<const QObject*>(v.constData());
QVariantMap result;
const QMetaObject *metaobject = obj->metaObject();
QVariant typeNameVariant(turnMetaObjectIntoTypename(metaobject));
result[QString::fromLatin1("_typeName")] = typeNameVariant;
int count = metaobject->propertyCount();
for (int i = 0; i < count; ++i) {
QMetaProperty metaproperty = metaobject->property(i);
const char *name = metaproperty.name();
// const char *typeName = metaproperty.typeName();
if (!metaproperty.isReadable() || !strcmp(name, "objectName")) {
continue;
}
QVariant value = obj->property(name);
result[QLatin1String(name)] = value;
// The line below sometimes fails with VisualStudio, see Joynr-1121
// std::cerr << "name: " << name << ", type: " << value.typeName() << std::endl;
// if (!strcmp(typeName, "QVariant")){// && value.type() == QVariant::UserType){
// const QObject *obj2 = static_cast<const QObject*>(value.constData());
// const QMetaObject *metaobject2 = obj2->metaObject();
// QVariant typeNameVariant(QString(metaobject2->className()));
// std::cout << metaobject2->className() << std::endl;
// result[QLatin1String(name)+ QLatin1String("_typeName")] = typeNameVariant;
// }
}
str = serialize( result );
}
} else if ( v.canConvert<QString>() ){ // Last chance: can value be converted to string?
// this will catch QDate, QDateTime, QUrl, ...
str = sanitizeString( v.toString() );
//TODO: catch other values like QImage, QRect, ...
} else {
// unable to serialize QVariant
// TODO: error handling
error = true;
}
if ( !error )
return str;
else
return QByteArray();
}
QString Serializer::turnMetaObjectIntoTypename(const QMetaObject* metaObject){
static QString dot = QString::fromLatin1(".");
static QString doubleColon = QString::fromLatin1("::");
QString fullClassName = QString::fromLatin1(metaObject->className());
return fullClassName.replace(doubleColon, dot);
}
<|endoftext|> |
<commit_before>#ifndef __CALLBACK_PARAMETER_HPP_INCLUDED
#define __CALLBACK_PARAMETER_HPP_INCLUDED
#include "cpp/ylikuutio/common/any_value.hpp"
#include "callback_object.hpp"
// Include standard headers
#include <string> // std::string
namespace model
{
class World;
}
namespace callback_system
{
class CallbackParameter;
}
namespace callback_system
{
class CallbackParameter
{
public:
// constructor.
CallbackParameter(std::string name, AnyValue any_value, bool is_reference, callback_system::CallbackObject* callback_object);
// destructor.
~CallbackParameter();
friend class CallbackObject;
private:
void bind_to_parent();
std::string name;
AnyValue any_value;
bool is_reference; // if true, the value is read from the hashmap. if false, then the value is read from the union.
};
class BoolCallbackParameter : CallbackParameter
{
public:
// constructor.
BoolCallbackParameter();
};
}
#endif
<commit_msg>`uint32_t childID`.<commit_after>#ifndef __CALLBACK_PARAMETER_HPP_INCLUDED
#define __CALLBACK_PARAMETER_HPP_INCLUDED
#include "cpp/ylikuutio/common/any_value.hpp"
#include "callback_object.hpp"
// Include standard headers
#include <string> // std::string
namespace model
{
class World;
}
namespace callback_system
{
class CallbackParameter;
}
namespace callback_system
{
class CallbackParameter
{
public:
// constructor.
CallbackParameter(std::string name, AnyValue any_value, bool is_reference, callback_system::CallbackObject* callback_object);
// destructor.
~CallbackParameter();
friend class CallbackObject;
private:
void bind_to_parent();
uint32_t childID; // callback parameter ID, returned by `callback_system::CallbackObject->get_callback_parameterID()`.
std::string name;
AnyValue any_value;
bool is_reference; // if true, the value is read from the hashmap. if false, then the value is read from the union.
};
class BoolCallbackParameter : CallbackParameter
{
public:
// constructor.
BoolCallbackParameter();
};
}
#endif
<|endoftext|> |
<commit_before>// Copyright 2016 Tom Barthel-Steer
// http://www.tomsteer.net
//
// 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 "sacneffectengine.h"
#include <QTimer>
#include <QThread>
#include <QPainter>
#include <QFont>
#include "fontdata.h"
#include <QDateTime>
#include <QEventLoop>
void GetCharacterCoord(unsigned char ch, int *x, int *y)
{
*y = ch / 32;
*x = ch % 32;
}
sACNEffectEngine::sACNEffectEngine() : QObject(NULL),
m_sender(Q_NULLPTR),
m_mode(FxManual),
m_dateStyle(dsEU),
m_start(0),
m_end(0),
m_index(0),
m_index_chase(0),
m_data(0),
m_manualLevel(0),
m_renderedImage(QImage(32, 16, QImage::Format_Grayscale8)),
m_image(Q_NULLPTR)
{
qRegisterMetaType<sACNEffectEngine::FxMode>("sACNEffectEngine::FxMode");
qRegisterMetaType<sACNEffectEngine::DateStyle>("sACNEffectEngine::DateStyle");
m_timer = new QTimer(this);
m_timer->setInterval(1000);
connect(m_timer, SIGNAL(timeout()), this, SLOT(timerTick()));
m_thread = new QThread();
moveToThread(m_thread);
connect(m_thread, &QThread::finished, this, &QObject::deleteLater);
m_thread->start();
}
sACNEffectEngine::~sACNEffectEngine()
{
// Stop thread
m_thread->quit();
}
void sACNEffectEngine::setSender(sACNSentUniverse *sender)
{
m_sender = sender;
}
void sACNEffectEngine::setMode(sACNEffectEngine::FxMode mode)
{
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"setMode", Q_ARG(sACNEffectEngine::FxMode, mode));
else
m_mode = mode;
clear();
}
void sACNEffectEngine::start()
{
// Make this method thread-safe
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"start");
else
m_timer->start();
}
void sACNEffectEngine::pause()
{
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"pause");
else
m_timer->stop();
}
void sACNEffectEngine::clear()
{
QMetaObject::invokeMethod(
m_sender,"setLevelRange",
Q_ARG(quint16, MIN_DMX_ADDRESS - 1),
Q_ARG(quint16, MAX_DMX_ADDRESS - 1),
Q_ARG(quint8, 0));
}
void sACNEffectEngine::setStartAddress(quint16 start)
{
// Make this method thread-safe
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"setStartAddress", Q_ARG(quint16, start));
else
{
// Set unused values to 0
if(start > m_start)
{
QMetaObject::invokeMethod(m_sender, "setLevelRange", Q_ARG(quint16, 0),
Q_ARG(quint16, start),
Q_ARG(quint8, 0));
}
m_start = start;
if(m_start > m_end)
std::swap(m_start, m_end);
qDebug() << "Start " << m_start << " End " << m_end;
}
}
void sACNEffectEngine::setEndAddress(quint16 end)
{
// Make this method thread-safe
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"setEndAddress", Q_ARG(quint16, end));
else
{
// Set unused values to 0
if(end < m_end)
{
QMetaObject::invokeMethod(m_sender, "setLevelRange", Q_ARG(quint16, end),
Q_ARG(quint16, MAX_DMX_ADDRESS-1),
Q_ARG(quint8, 0));
}
m_end = end;
if(m_end < m_start)
std::swap(m_start, m_end);
qDebug() << "Start " << m_start << " End " << m_end;
}
}
void sACNEffectEngine::setRange(quint16 start, quint16 end)
{
// Make this method thread-safe
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"setRange", Q_ARG(quint16, start), Q_ARG(quint16, end));
else
{
if(end < start)
std::swap(start, end);
// Set unused values to 0
if(start > m_start)
{
QMetaObject::invokeMethod(m_sender, "setLevelRange", Q_ARG(quint16, 0),
Q_ARG(quint16, start),
Q_ARG(quint8, 0));
}
m_start = start;
if(end < m_end)
{
QMetaObject::invokeMethod(m_sender, "setLevelRange", Q_ARG(quint16, end),
Q_ARG(quint16, MAX_DMX_ADDRESS-1),
Q_ARG(quint8, 0));
}
m_end = end;
qDebug() << "Range start " << m_start << " End " << m_end;
}
}
void sACNEffectEngine::renderText(QString text)
{
if(m_image)
delete m_image;
m_imageWidth = 8 * text.length();
int img_size = 16 * m_imageWidth;
m_image = new quint8[img_size];
memset(m_image, 0, img_size);
renderText(text, 4, true);
}
void sACNEffectEngine::renderText(QString top, QString bottom)
{
if(m_image)
delete m_image;
m_imageWidth = 32;
int img_size = 16 * m_imageWidth;
m_image = new quint8[img_size];
memset(m_image, 0, img_size);
renderText(top, 1, false);
renderText(bottom, 9, false);
}
void sACNEffectEngine::renderText(QString text, int yStart, bool big)
{
Q_ASSERT(m_image);
int char_width = big ? 8 : 4;
int char_height = big ? 8 : 5;
int width = char_width * text.length();
int height = 16;
int img_size = width * height;
for (int i = 0 ; i < text.length() ; i++)
{
unsigned char c = text.at(i).toLatin1();
unsigned char *character_font;
if(big)
character_font = vincent_data[c];
else
character_font = minifont_data[c];
int base_x = 0 + i * char_width;
int base_y = yStart;
for (int y = 0 ; y < char_height ; y++)
{
char character_scanline = character_font[y];
for (int x = 0 ; x < char_width ; x++)
{
int raw_pixel = (1 << (8 - 1 - x)) & character_scanline;
bool pixel = raw_pixel > 0 ? true : false;
int pixel_index = (base_x + x) + (base_y + y)*width;
if(pixel == true && pixel_index < img_size) {
m_image[pixel_index] = 255;
}
}
}
}
m_renderedImage = QImage(m_image, width, height, QImage::Format_Grayscale8);
emit textImageChanged(QPixmap::fromImage(m_renderedImage.scaledToHeight(100)));
}
void sACNEffectEngine::setText(QString text)
{
// Make this method thread-safe
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"setText", Q_ARG(QString, text));
else
{
m_text = text;
renderText(text);
}
}
void sACNEffectEngine::setDateStyle(sACNEffectEngine::DateStyle style)
{
// Make this method thread-safe
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"setDateStyle", Q_ARG(sACNEffectEngine::DateStyle, style));
else
m_dateStyle = style;
}
void sACNEffectEngine::setRate(qreal hz)
{
// Make this method thread-safe
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"setRate", Q_ARG(qreal, hz));
else
{
m_rate = hz;
int msTime = 1000 / hz;
m_timer->setInterval(msTime);
}
}
void sACNEffectEngine::timerTick()
{
m_index++;
char line[32];
switch(m_mode)
{
case FxRamp:
m_data++;
QMetaObject::invokeMethod(m_sender, "setLevelRange",
Q_ARG(quint16, m_start),
Q_ARG(quint16, m_end),
Q_ARG(quint8, m_data));
emit fxLevelChange(m_data);
break;
case FxSinewave:
if(m_index >= sizeof(sinetable))
m_index = 0;
m_data = sinetable[m_index];
QMetaObject::invokeMethod(m_sender, "setLevelRange",
Q_ARG(quint16, m_start),
Q_ARG(quint16, m_end),
Q_ARG(quint8, m_data));
emit fxLevelChange(m_data);
break;
case FxChaseSnap:
QMetaObject::invokeMethod(m_sender, "setLevelRange",
Q_ARG(quint16, m_start),
Q_ARG(quint16, m_end),
Q_ARG(quint8, 0));
QMetaObject::invokeMethod(m_sender, "setLevel",
Q_ARG(quint16, m_index_chase),
Q_ARG(quint8, m_manualLevel));
if (m_index_chase < m_start)
m_index_chase = m_start;
if(++m_index_chase > m_end)
m_index_chase = m_start;
break;
case FxChaseRamp:
if(m_index > std::numeric_limits<typeof(m_data)>::max())
{
m_index = std::numeric_limits<typeof(m_data)>::min();
if (++m_index_chase > m_end )
m_index_chase = m_start;
}
if (m_index_chase < m_start)
m_index_chase = m_start;
m_data = m_index;
QMetaObject::invokeMethod(m_sender, "setLevelRange",
Q_ARG(quint16, m_start),
Q_ARG(quint16, m_end),
Q_ARG(quint8, 0));
QMetaObject::invokeMethod(m_sender, "setLevel",
Q_ARG(quint16, m_index_chase),
Q_ARG(quint8, m_data));
emit fxLevelChange(m_data);
break;
case FxChaseSine:
if(m_index > sizeof(sinetable))
{
m_index = 0;
if (++m_index_chase > m_end )
m_index_chase = m_start;
}
if (m_index_chase < m_start)
m_index_chase = m_start;
m_data = sinetable[m_index];
QMetaObject::invokeMethod(m_sender, "setLevelRange",
Q_ARG(quint16, m_start),
Q_ARG(quint16, m_end),
Q_ARG(quint8, 0));
QMetaObject::invokeMethod(m_sender, "setLevel",
Q_ARG(quint16, m_index_chase),
Q_ARG(quint8, m_data));
emit fxLevelChange(m_data);
break;
case FxManual:
QMetaObject::invokeMethod(m_sender, "setLevelRange",
Q_ARG(quint16, m_start),
Q_ARG(quint16, m_end),
Q_ARG(quint8, m_manualLevel));
break;
case FxText:
if(m_image)
{
if(m_index > m_imageWidth) m_index=0;
for(int i=0; i<16; i++)
{
// Rolling window on to the image
quint8 *scanline = m_image + (i*m_imageWidth);
memset(line, 0, 32);
for(int j=0; j<32; j++)
{
if(m_imageWidth>0) // Protect against empty text
line[j] = scanline[(m_index + j) % m_imageWidth ];
}
m_sender->setLevel((quint8*)&line, 32, i*32);
}
}
break;
case FxDate:
if(m_dateStyle==dsEU)
renderText(QDateTime::currentDateTime().toString("hh:mm:ss"),
QDateTime::currentDateTime().toString("dd/MM/yy"));
else
renderText(QDateTime::currentDateTime().toString("hh:mm:ss"),
QDateTime::currentDateTime().toString("MM/dd/yy"));
for(int i=0; i<16; i++)
{
quint8 *scanline = m_image + (i*32);
m_sender->setLevel(scanline, 32, i*32);
}
break;
case FxVerticalBar:
if(m_index > 31)
m_index = 0;
QMetaObject::invokeMethod(m_sender, "setVerticalBar",
Q_ARG(quint16, m_index),
Q_ARG(quint8, 255));
break;
case FxHorizontalBar:
if(m_index > 15)
m_index = 0;
QMetaObject::invokeMethod(m_sender, "setHorizontalBar",
Q_ARG(quint16, m_index),
Q_ARG(quint8, 255));
break;
}
}
void sACNEffectEngine::setManualLevel(int level)
{
m_manualLevel = level;
if (m_mode == FxManual) {
QMetaObject::invokeMethod(m_sender, "setLevelRange",
Q_ARG(quint16, m_start),
Q_ARG(quint16, m_end),
Q_ARG(quint8, m_manualLevel));
}
}
<commit_msg>Make compatible with non-GCC<commit_after>// Copyright 2016 Tom Barthel-Steer
// http://www.tomsteer.net
//
// 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 "sacneffectengine.h"
#include <QTimer>
#include <QThread>
#include <QPainter>
#include <QFont>
#include "fontdata.h"
#include <QDateTime>
#include <QEventLoop>
void GetCharacterCoord(unsigned char ch, int *x, int *y)
{
*y = ch / 32;
*x = ch % 32;
}
sACNEffectEngine::sACNEffectEngine() : QObject(NULL),
m_sender(Q_NULLPTR),
m_mode(FxManual),
m_dateStyle(dsEU),
m_start(0),
m_end(0),
m_index(0),
m_index_chase(0),
m_data(0),
m_manualLevel(0),
m_renderedImage(QImage(32, 16, QImage::Format_Grayscale8)),
m_image(Q_NULLPTR)
{
qRegisterMetaType<sACNEffectEngine::FxMode>("sACNEffectEngine::FxMode");
qRegisterMetaType<sACNEffectEngine::DateStyle>("sACNEffectEngine::DateStyle");
m_timer = new QTimer(this);
m_timer->setInterval(1000);
connect(m_timer, SIGNAL(timeout()), this, SLOT(timerTick()));
m_thread = new QThread();
moveToThread(m_thread);
connect(m_thread, &QThread::finished, this, &QObject::deleteLater);
m_thread->start();
}
sACNEffectEngine::~sACNEffectEngine()
{
// Stop thread
m_thread->quit();
}
void sACNEffectEngine::setSender(sACNSentUniverse *sender)
{
m_sender = sender;
}
void sACNEffectEngine::setMode(sACNEffectEngine::FxMode mode)
{
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"setMode", Q_ARG(sACNEffectEngine::FxMode, mode));
else
m_mode = mode;
clear();
}
void sACNEffectEngine::start()
{
// Make this method thread-safe
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"start");
else
m_timer->start();
}
void sACNEffectEngine::pause()
{
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"pause");
else
m_timer->stop();
}
void sACNEffectEngine::clear()
{
QMetaObject::invokeMethod(
m_sender,"setLevelRange",
Q_ARG(quint16, MIN_DMX_ADDRESS - 1),
Q_ARG(quint16, MAX_DMX_ADDRESS - 1),
Q_ARG(quint8, 0));
}
void sACNEffectEngine::setStartAddress(quint16 start)
{
// Make this method thread-safe
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"setStartAddress", Q_ARG(quint16, start));
else
{
// Set unused values to 0
if(start > m_start)
{
QMetaObject::invokeMethod(m_sender, "setLevelRange", Q_ARG(quint16, 0),
Q_ARG(quint16, start),
Q_ARG(quint8, 0));
}
m_start = start;
if(m_start > m_end)
std::swap(m_start, m_end);
qDebug() << "Start " << m_start << " End " << m_end;
}
}
void sACNEffectEngine::setEndAddress(quint16 end)
{
// Make this method thread-safe
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"setEndAddress", Q_ARG(quint16, end));
else
{
// Set unused values to 0
if(end < m_end)
{
QMetaObject::invokeMethod(m_sender, "setLevelRange", Q_ARG(quint16, end),
Q_ARG(quint16, MAX_DMX_ADDRESS-1),
Q_ARG(quint8, 0));
}
m_end = end;
if(m_end < m_start)
std::swap(m_start, m_end);
qDebug() << "Start " << m_start << " End " << m_end;
}
}
void sACNEffectEngine::setRange(quint16 start, quint16 end)
{
// Make this method thread-safe
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"setRange", Q_ARG(quint16, start), Q_ARG(quint16, end));
else
{
if(end < start)
std::swap(start, end);
// Set unused values to 0
if(start > m_start)
{
QMetaObject::invokeMethod(m_sender, "setLevelRange", Q_ARG(quint16, 0),
Q_ARG(quint16, start),
Q_ARG(quint8, 0));
}
m_start = start;
if(end < m_end)
{
QMetaObject::invokeMethod(m_sender, "setLevelRange", Q_ARG(quint16, end),
Q_ARG(quint16, MAX_DMX_ADDRESS-1),
Q_ARG(quint8, 0));
}
m_end = end;
qDebug() << "Range start " << m_start << " End " << m_end;
}
}
void sACNEffectEngine::renderText(QString text)
{
if(m_image)
delete m_image;
m_imageWidth = 8 * text.length();
int img_size = 16 * m_imageWidth;
m_image = new quint8[img_size];
memset(m_image, 0, img_size);
renderText(text, 4, true);
}
void sACNEffectEngine::renderText(QString top, QString bottom)
{
if(m_image)
delete m_image;
m_imageWidth = 32;
int img_size = 16 * m_imageWidth;
m_image = new quint8[img_size];
memset(m_image, 0, img_size);
renderText(top, 1, false);
renderText(bottom, 9, false);
}
void sACNEffectEngine::renderText(QString text, int yStart, bool big)
{
Q_ASSERT(m_image);
int char_width = big ? 8 : 4;
int char_height = big ? 8 : 5;
int width = char_width * text.length();
int height = 16;
int img_size = width * height;
for (int i = 0 ; i < text.length() ; i++)
{
unsigned char c = text.at(i).toLatin1();
unsigned char *character_font;
if(big)
character_font = vincent_data[c];
else
character_font = minifont_data[c];
int base_x = 0 + i * char_width;
int base_y = yStart;
for (int y = 0 ; y < char_height ; y++)
{
char character_scanline = character_font[y];
for (int x = 0 ; x < char_width ; x++)
{
int raw_pixel = (1 << (8 - 1 - x)) & character_scanline;
bool pixel = raw_pixel > 0 ? true : false;
int pixel_index = (base_x + x) + (base_y + y)*width;
if(pixel == true && pixel_index < img_size) {
m_image[pixel_index] = 255;
}
}
}
}
m_renderedImage = QImage(m_image, width, height, QImage::Format_Grayscale8);
emit textImageChanged(QPixmap::fromImage(m_renderedImage.scaledToHeight(100)));
}
void sACNEffectEngine::setText(QString text)
{
// Make this method thread-safe
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"setText", Q_ARG(QString, text));
else
{
m_text = text;
renderText(text);
}
}
void sACNEffectEngine::setDateStyle(sACNEffectEngine::DateStyle style)
{
// Make this method thread-safe
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"setDateStyle", Q_ARG(sACNEffectEngine::DateStyle, style));
else
m_dateStyle = style;
}
void sACNEffectEngine::setRate(qreal hz)
{
// Make this method thread-safe
if(QThread::currentThread()!=this->thread())
QMetaObject::invokeMethod(
this,"setRate", Q_ARG(qreal, hz));
else
{
m_rate = hz;
int msTime = 1000 / hz;
m_timer->setInterval(msTime);
}
}
void sACNEffectEngine::timerTick()
{
m_index++;
char line[32];
switch(m_mode)
{
case FxRamp:
m_data++;
QMetaObject::invokeMethod(m_sender, "setLevelRange",
Q_ARG(quint16, m_start),
Q_ARG(quint16, m_end),
Q_ARG(quint8, m_data));
emit fxLevelChange(m_data);
break;
case FxSinewave:
if(m_index >= sizeof(sinetable))
m_index = 0;
m_data = sinetable[m_index];
QMetaObject::invokeMethod(m_sender, "setLevelRange",
Q_ARG(quint16, m_start),
Q_ARG(quint16, m_end),
Q_ARG(quint8, m_data));
emit fxLevelChange(m_data);
break;
case FxChaseSnap:
QMetaObject::invokeMethod(m_sender, "setLevelRange",
Q_ARG(quint16, m_start),
Q_ARG(quint16, m_end),
Q_ARG(quint8, 0));
QMetaObject::invokeMethod(m_sender, "setLevel",
Q_ARG(quint16, m_index_chase),
Q_ARG(quint8, m_manualLevel));
if (m_index_chase < m_start)
m_index_chase = m_start;
if(++m_index_chase > m_end)
m_index_chase = m_start;
break;
case FxChaseRamp:
if(m_index > std::numeric_limits<decltype(m_data)>::max())
{
m_index = std::numeric_limits<decltype(m_data)>::min();
if (++m_index_chase > m_end )
m_index_chase = m_start;
}
if (m_index_chase < m_start)
m_index_chase = m_start;
m_data = m_index;
QMetaObject::invokeMethod(m_sender, "setLevelRange",
Q_ARG(quint16, m_start),
Q_ARG(quint16, m_end),
Q_ARG(quint8, 0));
QMetaObject::invokeMethod(m_sender, "setLevel",
Q_ARG(quint16, m_index_chase),
Q_ARG(quint8, m_data));
emit fxLevelChange(m_data);
break;
case FxChaseSine:
if(m_index > sizeof(sinetable))
{
m_index = 0;
if (++m_index_chase > m_end )
m_index_chase = m_start;
}
if (m_index_chase < m_start)
m_index_chase = m_start;
m_data = sinetable[m_index];
QMetaObject::invokeMethod(m_sender, "setLevelRange",
Q_ARG(quint16, m_start),
Q_ARG(quint16, m_end),
Q_ARG(quint8, 0));
QMetaObject::invokeMethod(m_sender, "setLevel",
Q_ARG(quint16, m_index_chase),
Q_ARG(quint8, m_data));
emit fxLevelChange(m_data);
break;
case FxManual:
QMetaObject::invokeMethod(m_sender, "setLevelRange",
Q_ARG(quint16, m_start),
Q_ARG(quint16, m_end),
Q_ARG(quint8, m_manualLevel));
break;
case FxText:
if(m_image)
{
if(m_index > m_imageWidth) m_index=0;
for(int i=0; i<16; i++)
{
// Rolling window on to the image
quint8 *scanline = m_image + (i*m_imageWidth);
memset(line, 0, 32);
for(int j=0; j<32; j++)
{
if(m_imageWidth>0) // Protect against empty text
line[j] = scanline[(m_index + j) % m_imageWidth ];
}
m_sender->setLevel((quint8*)&line, 32, i*32);
}
}
break;
case FxDate:
if(m_dateStyle==dsEU)
renderText(QDateTime::currentDateTime().toString("hh:mm:ss"),
QDateTime::currentDateTime().toString("dd/MM/yy"));
else
renderText(QDateTime::currentDateTime().toString("hh:mm:ss"),
QDateTime::currentDateTime().toString("MM/dd/yy"));
for(int i=0; i<16; i++)
{
quint8 *scanline = m_image + (i*32);
m_sender->setLevel(scanline, 32, i*32);
}
break;
case FxVerticalBar:
if(m_index > 31)
m_index = 0;
QMetaObject::invokeMethod(m_sender, "setVerticalBar",
Q_ARG(quint16, m_index),
Q_ARG(quint8, 255));
break;
case FxHorizontalBar:
if(m_index > 15)
m_index = 0;
QMetaObject::invokeMethod(m_sender, "setHorizontalBar",
Q_ARG(quint16, m_index),
Q_ARG(quint8, 255));
break;
}
}
void sACNEffectEngine::setManualLevel(int level)
{
m_manualLevel = level;
if (m_mode == FxManual) {
QMetaObject::invokeMethod(m_sender, "setLevelRange",
Q_ARG(quint16, m_start),
Q_ARG(quint16, m_end),
Q_ARG(quint8, m_manualLevel));
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: implbitmapcanvas.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 08:25:37 $
*
* 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 _COM_SUN_STAR_RENDERING_XCANVAS_HPP__
#include <com/sun/star/rendering/XCanvas.hpp>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XBITMAPCANVAS_HPP__
#include <com/sun/star/rendering/XBitmapCanvas.hpp>
#endif
#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif
#ifndef _BGFX_TOOLS_CANVASTOOLS_HXX
#include <basegfx/tools/canvastools.hxx>
#endif
#include <implbitmapcanvas.hxx>
using namespace ::com::sun::star;
namespace cppcanvas
{
namespace internal
{
ImplBitmapCanvas::ImplBitmapCanvas( const uno::Reference< rendering::XBitmapCanvas >& rCanvas ) :
ImplCanvas( uno::Reference< rendering::XCanvas >(rCanvas,
uno::UNO_QUERY) ),
mxBitmapCanvas( rCanvas ),
mxBitmap( rCanvas,
uno::UNO_QUERY )
{
OSL_ENSURE( mxBitmapCanvas.is(), "ImplBitmapCanvas::ImplBitmapCanvas(): Invalid canvas" );
OSL_ENSURE( mxBitmap.is(), "ImplBitmapCanvas::ImplBitmapCanvas(): Invalid bitmap" );
}
ImplBitmapCanvas::~ImplBitmapCanvas()
{
}
::basegfx::B2ISize ImplBitmapCanvas::getSize() const
{
OSL_ENSURE( mxBitmap.is(), "ImplBitmapCanvas::getSize(): Invalid canvas" );
return ::basegfx::unotools::b2ISizeFromIntegerSize2D( mxBitmap->getSize() );
}
CanvasSharedPtr ImplBitmapCanvas::clone() const
{
return BitmapCanvasSharedPtr( new ImplBitmapCanvas( *this ) );
}
}
}
<commit_msg>INTEGRATION: CWS canvas02 (1.5.8); FILE MERGED 2005/10/09 09:18:28 thb 1.5.8.2: RESYNC: (1.5-1.6); FILE MERGED 2005/08/19 11:08:34 thb 1.5.8.1: #i53538# Changed clip setting to use basegfx polygon (cppcanvas::PolyPolygon contains reference back to canvas); changed direct access to base class member to getter method, thus, providing the actual XCanvas clip polygon lazily.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: implbitmapcanvas.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2005-11-02 13:43:02 $
*
* 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 _COM_SUN_STAR_RENDERING_XCANVAS_HPP__
#include <com/sun/star/rendering/XCanvas.hpp>
#endif
#ifndef _COM_SUN_STAR_RENDERING_XBITMAPCANVAS_HPP__
#include <com/sun/star/rendering/XBitmapCanvas.hpp>
#endif
#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif
#ifndef _BGFX_POLYGON_B2DPOLYPOLYGON_HXX
#include <basegfx/polygon/b2dpolypolygon.hxx>
#endif
#ifndef _BGFX_TOOLS_CANVASTOOLS_HXX
#include <basegfx/tools/canvastools.hxx>
#endif
#include <implbitmapcanvas.hxx>
using namespace ::com::sun::star;
namespace cppcanvas
{
namespace internal
{
ImplBitmapCanvas::ImplBitmapCanvas( const uno::Reference< rendering::XBitmapCanvas >& rCanvas ) :
ImplCanvas( uno::Reference< rendering::XCanvas >(rCanvas,
uno::UNO_QUERY) ),
mxBitmapCanvas( rCanvas ),
mxBitmap( rCanvas,
uno::UNO_QUERY )
{
OSL_ENSURE( mxBitmapCanvas.is(), "ImplBitmapCanvas::ImplBitmapCanvas(): Invalid canvas" );
OSL_ENSURE( mxBitmap.is(), "ImplBitmapCanvas::ImplBitmapCanvas(): Invalid bitmap" );
}
ImplBitmapCanvas::~ImplBitmapCanvas()
{
}
::basegfx::B2ISize ImplBitmapCanvas::getSize() const
{
OSL_ENSURE( mxBitmap.is(), "ImplBitmapCanvas::getSize(): Invalid canvas" );
return ::basegfx::unotools::b2ISizeFromIntegerSize2D( mxBitmap->getSize() );
}
CanvasSharedPtr ImplBitmapCanvas::clone() const
{
return BitmapCanvasSharedPtr( new ImplBitmapCanvas( *this ) );
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012, Steinwurf ApS
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Steinwurf ApS 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 Steinwurf ApS 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 "file_input_stream.hpp"
#include "error.hpp"
#include <fstream>
#include <cassert>
namespace sak
{
file_input_stream::file_input_stream()
: m_filesize(0)
{
}
file_input_stream::file_input_stream(const std::string& filename)
: m_filesize(0)
{
open(filename);
}
void file_input_stream::open(const std::string& filename)
{
assert(!m_file.is_open());
boost::system::error_code ec;
open(filename, ec);
// If an error throw
std::cout << "before throw" << std::endl;
if(ec)
{
boost::system::system_error e(ec);
std::cout << "right before throw" << std::endl;
throw e;
}
// error::throw_error(ec);
}
void file_input_stream::open(const std::string& filename,
boost::system::error_code& ec)
{
assert(!m_file.is_open());
m_file.open(filename.c_str(),
std::ios::in | std::ios::binary);
if (!m_file.is_open())
{
ec = error::make_error_code(error::failed_open_file);
return;
}
m_file.seekg(0, std::ios::end);
assert(m_file);
// We cannot use the read_position function here due to a
// problem on the iOS platform described in the read_position
// function.
auto pos = m_file.tellg();
assert(pos >= 0);
m_filesize = (uint32_t) pos;
m_file.seekg(0, std::ios::beg);
assert(m_file);
}
void file_input_stream::close()
{
assert(m_file.is_open());
m_file.close();
}
void file_input_stream::seek(uint32_t pos)
{
assert(m_file.is_open());
m_file.seekg(pos, std::ios::beg);
assert(m_file);
}
uint32_t file_input_stream::read_position()
{
assert(m_file.is_open());
// Work around for problem on iOS where tellg returned -1 when
// reading the last byte. However the EOF flag was correctly
// set. So here we check for EOF if true we set the
// read_position = m_file_size
if(m_file.eof())
{
return m_filesize;
}
else
{
std::streamoff pos = m_file.tellg();
assert(pos >= 0);
return static_cast<uint32_t>(pos);
}
}
void file_input_stream::read(uint8_t* buffer, uint32_t bytes)
{
assert(m_file.is_open());
m_file.read(reinterpret_cast<char*>(buffer), bytes);
assert(bytes == static_cast<uint32_t>(m_file.gcount()));
}
uint32_t file_input_stream::bytes_available()
{
assert(m_file.is_open());
uint32_t pos = read_position();
assert(pos <= m_filesize);
return m_filesize - pos;
}
uint32_t file_input_stream::size()
{
assert(m_file.is_open());
return m_filesize;
}
}
<commit_msg>Fix unix line endings<commit_after>// Copyright (c) 2012, Steinwurf ApS
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Steinwurf ApS 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 Steinwurf ApS 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 "file_input_stream.hpp"
#include "error.hpp"
#include <fstream>
#include <cassert>
namespace sak
{
file_input_stream::file_input_stream()
: m_filesize(0)
{
}
file_input_stream::file_input_stream(const std::string& filename)
: m_filesize(0)
{
open(filename);
}
void file_input_stream::open(const std::string& filename)
{
assert(!m_file.is_open());
boost::system::error_code ec;
open(filename, ec);
// If an error throw
std::cout << "before throw" << std::endl;
if(ec)
{
boost::system::system_error e(ec);
std::cout << "right before throw" << std::endl;
throw e;
}
// error::throw_error(ec);
}
void file_input_stream::open(const std::string& filename,
boost::system::error_code& ec)
{
assert(!m_file.is_open());
m_file.open(filename.c_str(),
std::ios::in | std::ios::binary);
if (!m_file.is_open())
{
ec = error::make_error_code(error::failed_open_file);
return;
}
m_file.seekg(0, std::ios::end);
assert(m_file);
// We cannot use the read_position function here due to a
// problem on the iOS platform described in the read_position
// function.
auto pos = m_file.tellg();
assert(pos >= 0);
m_filesize = (uint32_t) pos;
m_file.seekg(0, std::ios::beg);
assert(m_file);
}
void file_input_stream::close()
{
assert(m_file.is_open());
m_file.close();
}
void file_input_stream::seek(uint32_t pos)
{
assert(m_file.is_open());
m_file.seekg(pos, std::ios::beg);
assert(m_file);
}
uint32_t file_input_stream::read_position()
{
assert(m_file.is_open());
// Work around for problem on iOS where tellg returned -1 when
// reading the last byte. However the EOF flag was correctly
// set. So here we check for EOF if true we set the
// read_position = m_file_size
if(m_file.eof())
{
return m_filesize;
}
else
{
std::streamoff pos = m_file.tellg();
assert(pos >= 0);
return static_cast<uint32_t>(pos);
}
}
void file_input_stream::read(uint8_t* buffer, uint32_t bytes)
{
assert(m_file.is_open());
m_file.read(reinterpret_cast<char*>(buffer), bytes);
assert(bytes == static_cast<uint32_t>(m_file.gcount()));
}
uint32_t file_input_stream::bytes_available()
{
assert(m_file.is_open());
uint32_t pos = read_position();
assert(pos <= m_filesize);
return m_filesize - pos;
}
uint32_t file_input_stream::size()
{
assert(m_file.is_open());
return m_filesize;
}
}
<|endoftext|> |
<commit_before> /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: accembedded.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-16 20:34:38 $
*
* 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_sw.hxx"
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _FLYFRM_HXX
#include <flyfrm.hxx>
#endif
#ifndef _ACCEMBEDDED_HXX
#include "accembedded.hxx"
#endif
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::accessibility;
using namespace ::rtl;
const sal_Char sServiceName[] = "com.sun.star.text.AccessibleTextEmbeddedObject";
const sal_Char sImplementationName[] = "com.sun.star.comp.Writer.SwAccessibleEmbeddedObject";
SwAccessibleEmbeddedObject::SwAccessibleEmbeddedObject(
SwAccessibleMap *pMap,
const SwFlyFrm *pFlyFrm ) :
SwAccessibleNoTextFrame( pMap, AccessibleRole::EMBEDDED_OBJECT, pFlyFrm )
{
}
SwAccessibleEmbeddedObject::~SwAccessibleEmbeddedObject()
{
}
OUString SAL_CALL SwAccessibleEmbeddedObject::getImplementationName()
throw( RuntimeException )
{
return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationName));
}
sal_Bool SAL_CALL SwAccessibleEmbeddedObject::supportsService(
const ::rtl::OUString& sTestServiceName)
throw (::com::sun::star::uno::RuntimeException)
{
return sTestServiceName.equalsAsciiL( sServiceName,
sizeof(sServiceName)-1 ) ||
sTestServiceName.equalsAsciiL( sAccessibleServiceName,
sizeof(sAccessibleServiceName)-1 );
}
Sequence< OUString > SAL_CALL SwAccessibleEmbeddedObject::getSupportedServiceNames()
throw( ::com::sun::star::uno::RuntimeException )
{
Sequence< OUString > aRet(2);
OUString* pArray = aRet.getArray();
pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceName) );
pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );
return aRet;
}
Sequence< sal_Int8 > SAL_CALL SwAccessibleEmbeddedObject::getImplementationId()
throw(RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
static Sequence< sal_Int8 > aId( 16 );
static sal_Bool bInit = sal_False;
if(!bInit)
{
rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );
bInit = sal_True;
}
return aId;
}
<commit_msg>INTEGRATION: CWS swwarnings (1.8.222); FILE MERGED 2007/04/11 07:02:38 tl 1.8.222.2: #i69287# warning-free code 2007/03/08 15:18:39 od 1.8.222.1: #i69287# warning free code<commit_after> /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: accembedded.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2007-09-27 08:19:47 $
*
* 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_sw.hxx"
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _FLYFRM_HXX
#include <flyfrm.hxx>
#endif
#ifndef _ACCEMBEDDED_HXX
#include "accembedded.hxx"
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::accessibility;
using namespace ::rtl;
const sal_Char sServiceName[] = "com.sun.star.text.AccessibleTextEmbeddedObject";
const sal_Char sImplementationName[] = "com.sun.star.comp.Writer.SwAccessibleEmbeddedObject";
SwAccessibleEmbeddedObject::SwAccessibleEmbeddedObject(
SwAccessibleMap* pInitMap,
const SwFlyFrm* pFlyFrm ) :
SwAccessibleNoTextFrame( pInitMap, AccessibleRole::EMBEDDED_OBJECT, pFlyFrm )
{
}
SwAccessibleEmbeddedObject::~SwAccessibleEmbeddedObject()
{
}
OUString SAL_CALL SwAccessibleEmbeddedObject::getImplementationName()
throw( uno::RuntimeException )
{
return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationName));
}
sal_Bool SAL_CALL SwAccessibleEmbeddedObject::supportsService(
const ::rtl::OUString& sTestServiceName)
throw (uno::RuntimeException)
{
return sTestServiceName.equalsAsciiL( sServiceName,
sizeof(sServiceName)-1 ) ||
sTestServiceName.equalsAsciiL( sAccessibleServiceName,
sizeof(sAccessibleServiceName)-1 );
}
uno::Sequence< OUString > SAL_CALL SwAccessibleEmbeddedObject::getSupportedServiceNames()
throw( uno::RuntimeException )
{
uno::Sequence< OUString > aRet(2);
OUString* pArray = aRet.getArray();
pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceName) );
pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );
return aRet;
}
uno::Sequence< sal_Int8 > SAL_CALL SwAccessibleEmbeddedObject::getImplementationId()
throw(uno::RuntimeException)
{
vos::OGuard aGuard(Application::GetSolarMutex());
static uno::Sequence< sal_Int8 > aId( 16 );
static sal_Bool bInit = sal_False;
if(!bInit)
{
rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );
bInit = sal_True;
}
return aId;
}
<|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 "net/base/ip_endpoint.h"
#include "base/logging.h"
#if defined(OS_WIN)
#include <winsock2.h>
#elif defined(OS_POSIX)
#include <netinet/in.h>
#endif
namespace net {
const size_t kIPv4AddressSize = 4;
const size_t kIPv6AddressSize = 16;
IPEndPoint::IPEndPoint() : port_(0) {}
IPEndPoint::IPEndPoint(const IPAddressNumber& address, int port)
: address_(address),
port_(port) {}
IPEndPoint::IPEndPoint(const IPEndPoint& endpoint) {
address_ = endpoint.address_;
port_ = endpoint.port_;
}
bool IPEndPoint::ToSockaddr(struct sockaddr* address,
size_t* address_length) const {
DCHECK(address);
DCHECK(address_length);
switch (address_.size()) {
case kIPv4AddressSize: {
if (*address_length < sizeof(struct sockaddr_in))
return false;
*address_length = sizeof(struct sockaddr_in);
struct sockaddr_in* addr = reinterpret_cast<struct sockaddr_in*>(address);
memset(addr, 0, sizeof(struct sockaddr_in));
addr->sin_family = AF_INET;
addr->sin_port = htons(port_);
memcpy(&addr->sin_addr, &address_[0], kIPv4AddressSize);
break;
}
case kIPv6AddressSize: {
if (*address_length < sizeof(struct sockaddr_in6))
return false;
*address_length = sizeof(struct sockaddr_in6);
struct sockaddr_in6* addr6 =
reinterpret_cast<struct sockaddr_in6*>(address);
memset(addr6, 0, sizeof(struct sockaddr_in6));
addr6->sin6_family = AF_INET6;
addr6->sin6_port = htons(port_);
memcpy(&addr6->sin6_addr, &address_[0], kIPv6AddressSize);
break;
}
default: {
NOTREACHED() << "Bad IP address";
break;
}
}
return true;
}
bool IPEndPoint::FromSockAddr(const struct sockaddr* address,
size_t address_length) {
DCHECK(address);
switch (address->sa_family) {
case AF_INET: {
const struct sockaddr_in* addr =
reinterpret_cast<const struct sockaddr_in*>(address);
port_ = ntohs(addr->sin_port);
const char* bytes = reinterpret_cast<const char*>(&addr->sin_addr);
address_.assign(&bytes[0], &bytes[kIPv4AddressSize]);
break;
}
case AF_INET6: {
const struct sockaddr_in6* addr =
reinterpret_cast<const struct sockaddr_in6*>(address);
port_ = ntohs(addr->sin6_port);
const char* bytes = reinterpret_cast<const char*>(&addr->sin6_addr);
address_.assign(&bytes[0], &bytes[kIPv6AddressSize]);
break;
}
default: {
NOTREACHED() << "Bad IP address";
break;
}
}
return true;
}
bool IPEndPoint::operator<(const IPEndPoint& that) const {
return address_ < that.address_ || port_ < that.port_;
}
bool IPEndPoint::operator==(const IPEndPoint& that) const {
return address_ == that.address_ && port_ == that.port_;
}
} // namespace net
<commit_msg>More build errors from on-they-fly-emergency clang patching.<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 "net/base/ip_endpoint.h"
#include "base/logging.h"
#if defined(OS_WIN)
#include <winsock2.h>
#elif defined(OS_POSIX)
#include <netinet/in.h>
#endif
namespace net {
const size_t kIPv4AddressSize = 4;
const size_t kIPv6AddressSize = 16;
IPEndPoint::IPEndPoint() : port_(0) {}
IPEndPoint::~IPEndPoint() {}
IPEndPoint::IPEndPoint(const IPAddressNumber& address, int port)
: address_(address),
port_(port) {}
IPEndPoint::IPEndPoint(const IPEndPoint& endpoint) {
address_ = endpoint.address_;
port_ = endpoint.port_;
}
bool IPEndPoint::ToSockaddr(struct sockaddr* address,
size_t* address_length) const {
DCHECK(address);
DCHECK(address_length);
switch (address_.size()) {
case kIPv4AddressSize: {
if (*address_length < sizeof(struct sockaddr_in))
return false;
*address_length = sizeof(struct sockaddr_in);
struct sockaddr_in* addr = reinterpret_cast<struct sockaddr_in*>(address);
memset(addr, 0, sizeof(struct sockaddr_in));
addr->sin_family = AF_INET;
addr->sin_port = htons(port_);
memcpy(&addr->sin_addr, &address_[0], kIPv4AddressSize);
break;
}
case kIPv6AddressSize: {
if (*address_length < sizeof(struct sockaddr_in6))
return false;
*address_length = sizeof(struct sockaddr_in6);
struct sockaddr_in6* addr6 =
reinterpret_cast<struct sockaddr_in6*>(address);
memset(addr6, 0, sizeof(struct sockaddr_in6));
addr6->sin6_family = AF_INET6;
addr6->sin6_port = htons(port_);
memcpy(&addr6->sin6_addr, &address_[0], kIPv6AddressSize);
break;
}
default: {
NOTREACHED() << "Bad IP address";
break;
}
}
return true;
}
bool IPEndPoint::FromSockAddr(const struct sockaddr* address,
size_t address_length) {
DCHECK(address);
switch (address->sa_family) {
case AF_INET: {
const struct sockaddr_in* addr =
reinterpret_cast<const struct sockaddr_in*>(address);
port_ = ntohs(addr->sin_port);
const char* bytes = reinterpret_cast<const char*>(&addr->sin_addr);
address_.assign(&bytes[0], &bytes[kIPv4AddressSize]);
break;
}
case AF_INET6: {
const struct sockaddr_in6* addr =
reinterpret_cast<const struct sockaddr_in6*>(address);
port_ = ntohs(addr->sin6_port);
const char* bytes = reinterpret_cast<const char*>(&addr->sin6_addr);
address_.assign(&bytes[0], &bytes[kIPv6AddressSize]);
break;
}
default: {
NOTREACHED() << "Bad IP address";
break;
}
}
return true;
}
bool IPEndPoint::operator<(const IPEndPoint& that) const {
return address_ < that.address_ || port_ < that.port_;
}
bool IPEndPoint::operator==(const IPEndPoint& that) const {
return address_ == that.address_ && port_ == that.port_;
}
} // namespace net
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/test/test_server.h"
#include <algorithm>
#include <string>
#include <vector>
#include "build/build_config.h"
#if defined(OS_MACOSX)
#include "net/base/x509_certificate.h"
#endif
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/leak_annotations.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "googleurl/src/gurl.h"
#include "net/base/cert_test_util.h"
#include "net/base/host_port_pair.h"
#include "net/base/host_resolver.h"
#include "net/base/test_completion_callback.h"
#include "net/socket/tcp_client_socket.h"
#include "net/test/python_utils.h"
#include "testing/platform_test.h"
namespace {
// Number of connection attempts for tests.
const int kServerConnectionAttempts = 10;
// Connection timeout in milliseconds for tests.
const int kServerConnectionTimeoutMs = 1000;
const char kTestServerShardFlag[] = "test-server-shard";
int GetPortBase(net::TestServer::Type type) {
switch (type) {
case net::TestServer::TYPE_FTP:
return 3117;
case net::TestServer::TYPE_HTTP:
return 1337;
case net::TestServer::TYPE_HTTPS:
case net::TestServer::TYPE_HTTPS_CLIENT_AUTH:
case net::TestServer::TYPE_HTTPS_EXPIRED_CERTIFICATE:
return 9443;
case net::TestServer::TYPE_HTTPS_MISMATCHED_HOSTNAME:
return 9666;
default:
NOTREACHED();
}
return -1;
}
int GetPort(net::TestServer::Type type) {
int port = GetPortBase(type);
if (CommandLine::ForCurrentProcess()->HasSwitch(kTestServerShardFlag)) {
std::string shard_str(CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
kTestServerShardFlag));
int shard = -1;
if (base::StringToInt(shard_str, &shard)) {
port += shard;
} else {
LOG(FATAL) << "Got invalid " << kTestServerShardFlag << " flag value. "
<< "An integer is expected.";
}
}
return port;
}
std::string GetHostname(net::TestServer::Type type) {
if (type == net::TestServer::TYPE_HTTPS_MISMATCHED_HOSTNAME) {
// Return a different hostname string that resolves to the same hostname.
return "localhost";
}
return "127.0.0.1";
}
} // namespace
namespace net {
#if defined(OS_MACOSX)
void SetMacTestCertificate(X509Certificate* cert);
#endif
TestServer::TestServer(Type type, const FilePath& document_root)
: host_port_pair_(GetHostname(type), GetPort(type)),
process_handle_(base::kNullProcessHandle),
type_(type) {
FilePath src_dir;
PathService::Get(base::DIR_SOURCE_ROOT, &src_dir);
document_root_ = src_dir.Append(document_root);
certificates_dir_ = src_dir.Append(FILE_PATH_LITERAL("net"))
.Append(FILE_PATH_LITERAL("data"))
.Append(FILE_PATH_LITERAL("ssl"))
.Append(FILE_PATH_LITERAL("certificates"));
}
TestServer::~TestServer() {
#if defined(OS_MACOSX)
SetMacTestCertificate(NULL);
#endif
Stop();
}
bool TestServer::Start() {
if (GetScheme() == "https") {
if (!LoadTestRootCert())
return false;
if (!CheckCATrusted())
return false;
}
// Get path to python server script
FilePath testserver_path;
if (!PathService::Get(base::DIR_SOURCE_ROOT, &testserver_path)) {
LOG(ERROR) << "Failed to get DIR_SOURCE_ROOT";
return false;
}
testserver_path = testserver_path
.Append(FILE_PATH_LITERAL("net"))
.Append(FILE_PATH_LITERAL("tools"))
.Append(FILE_PATH_LITERAL("testserver"))
.Append(FILE_PATH_LITERAL("testserver.py"));
if (!SetPythonPath())
return false;
if (!LaunchPython(testserver_path))
return false;
if (!WaitToStart()) {
Stop();
return false;
}
return true;
}
bool TestServer::Stop() {
if (!process_handle_)
return true;
// First check if the process has already terminated.
bool ret = base::WaitForSingleProcess(process_handle_, 0);
if (!ret)
ret = base::KillProcess(process_handle_, 1, true);
if (ret) {
base::CloseProcessHandle(process_handle_);
process_handle_ = base::kNullProcessHandle;
} else {
LOG(INFO) << "Kill failed?";
}
return ret;
}
bool TestServer::WaitToFinish(int timeout_ms) {
if (!process_handle_)
return true;
bool ret = base::WaitForSingleProcess(process_handle_, timeout_ms);
if (ret) {
base::CloseProcessHandle(process_handle_);
process_handle_ = base::kNullProcessHandle;
} else {
LOG(ERROR) << "Timed out.";
}
return ret;
}
std::string TestServer::GetScheme() const {
switch (type_) {
case TYPE_FTP:
return "ftp";
case TYPE_HTTP:
return "http";
case TYPE_HTTPS:
case TYPE_HTTPS_CLIENT_AUTH:
case TYPE_HTTPS_MISMATCHED_HOSTNAME:
case TYPE_HTTPS_EXPIRED_CERTIFICATE:
return "https";
default:
NOTREACHED();
}
return std::string();
}
bool TestServer::GetAddressList(AddressList* address_list) const {
DCHECK(address_list);
scoped_refptr<HostResolver> resolver(
CreateSystemHostResolver(HostResolver::kDefaultParallelism, NULL));
HostResolver::RequestInfo info(host_port_pair_);
int rv = resolver->Resolve(info, address_list, NULL, NULL, BoundNetLog());
if (rv != net::OK) {
LOG(ERROR) << "Failed to resolve hostname: " << host_port_pair_.host();
return false;
}
return true;
}
GURL TestServer::GetURL(const std::string& path) {
return GURL(GetScheme() + "://" + host_port_pair_.ToString() +
"/" + path);
}
GURL TestServer::GetURLWithUser(const std::string& path,
const std::string& user) {
return GURL(GetScheme() + "://" + user + "@" +
host_port_pair_.ToString() +
"/" + path);
}
GURL TestServer::GetURLWithUserAndPassword(const std::string& path,
const std::string& user,
const std::string& password) {
return GURL(GetScheme() + "://" + user + ":" + password +
"@" + host_port_pair_.ToString() +
"/" + path);
}
bool TestServer::SetPythonPath() {
FilePath third_party_dir;
if (!PathService::Get(base::DIR_SOURCE_ROOT, &third_party_dir)) {
LOG(ERROR) << "Failed to get DIR_SOURCE_ROOT";
return false;
}
third_party_dir = third_party_dir.Append(FILE_PATH_LITERAL("third_party"));
AppendToPythonPath(third_party_dir.Append(FILE_PATH_LITERAL("tlslite")));
AppendToPythonPath(third_party_dir.Append(FILE_PATH_LITERAL("pyftpdlib")));
// Locate the Python code generated by the protocol buffers compiler.
FilePath generated_code_dir;
if (!PathService::Get(base::DIR_EXE, &generated_code_dir)) {
LOG(ERROR) << "Failed to get DIR_EXE";
return false;
}
generated_code_dir = generated_code_dir.Append(FILE_PATH_LITERAL("pyproto"));
AppendToPythonPath(generated_code_dir);
AppendToPythonPath(generated_code_dir.Append(FILE_PATH_LITERAL("sync_pb")));
return true;
}
FilePath TestServer::GetRootCertificatePath() {
return certificates_dir_.AppendASCII("root_ca_cert.crt");
}
bool TestServer::LoadTestRootCert() {
#if defined(USE_NSS)
if (cert_)
return true;
// TODO(dkegel): figure out how to get this to only happen once?
// This currently leaks a little memory.
// TODO(dkegel): fix the leak and remove the entry in
// tools/valgrind/memcheck/suppressions.txt
ANNOTATE_SCOPED_MEMORY_LEAK; // Tell heap checker about the leak.
cert_ = LoadTemporaryRootCert(GetRootCertificatePath());
return (cert_ != NULL);
#elif defined(OS_MACOSX)
X509Certificate* cert = LoadTemporaryRootCert(GetRootCertificatePath());
if (!cert)
return false;
SetMacTestCertificate(cert);
return true;
#else
return true;
#endif
}
FilePath TestServer::GetCertificatePath() {
switch (type_) {
case TYPE_FTP:
case TYPE_HTTP:
return FilePath();
case TYPE_HTTPS:
case TYPE_HTTPS_CLIENT_AUTH:
case TYPE_HTTPS_MISMATCHED_HOSTNAME:
return certificates_dir_.AppendASCII("ok_cert.pem");
case TYPE_HTTPS_EXPIRED_CERTIFICATE:
return certificates_dir_.AppendASCII("expired_cert.pem");
default:
NOTREACHED();
}
return FilePath();
}
} // namespace net
<commit_msg>GTTF: Use different port number for all types of TestServer.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/test/test_server.h"
#include <algorithm>
#include <string>
#include <vector>
#include "build/build_config.h"
#if defined(OS_MACOSX)
#include "net/base/x509_certificate.h"
#endif
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/leak_annotations.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "googleurl/src/gurl.h"
#include "net/base/cert_test_util.h"
#include "net/base/host_port_pair.h"
#include "net/base/host_resolver.h"
#include "net/base/test_completion_callback.h"
#include "net/socket/tcp_client_socket.h"
#include "net/test/python_utils.h"
#include "testing/platform_test.h"
namespace {
// Number of connection attempts for tests.
const int kServerConnectionAttempts = 10;
// Connection timeout in milliseconds for tests.
const int kServerConnectionTimeoutMs = 1000;
const char kTestServerShardFlag[] = "test-server-shard";
int GetPortBase(net::TestServer::Type type) {
switch (type) {
case net::TestServer::TYPE_FTP:
return 3117;
case net::TestServer::TYPE_HTTP:
return 1337;
case net::TestServer::TYPE_HTTPS:
return 9443;
case net::TestServer::TYPE_HTTPS_CLIENT_AUTH:
return 9543;
case net::TestServer::TYPE_HTTPS_EXPIRED_CERTIFICATE:
// TODO(phajdan.jr): Some tests rely on this hardcoded value.
// Some uses of this are actually in .html/.js files.
return 9666;
case net::TestServer::TYPE_HTTPS_MISMATCHED_HOSTNAME:
return 9643;
default:
NOTREACHED();
}
return -1;
}
int GetPort(net::TestServer::Type type) {
int port = GetPortBase(type);
if (CommandLine::ForCurrentProcess()->HasSwitch(kTestServerShardFlag)) {
std::string shard_str(CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
kTestServerShardFlag));
int shard = -1;
if (base::StringToInt(shard_str, &shard)) {
port += shard;
} else {
LOG(FATAL) << "Got invalid " << kTestServerShardFlag << " flag value. "
<< "An integer is expected.";
}
}
return port;
}
std::string GetHostname(net::TestServer::Type type) {
if (type == net::TestServer::TYPE_HTTPS_MISMATCHED_HOSTNAME) {
// Return a different hostname string that resolves to the same hostname.
return "localhost";
}
return "127.0.0.1";
}
} // namespace
namespace net {
#if defined(OS_MACOSX)
void SetMacTestCertificate(X509Certificate* cert);
#endif
TestServer::TestServer(Type type, const FilePath& document_root)
: host_port_pair_(GetHostname(type), GetPort(type)),
process_handle_(base::kNullProcessHandle),
type_(type) {
FilePath src_dir;
PathService::Get(base::DIR_SOURCE_ROOT, &src_dir);
document_root_ = src_dir.Append(document_root);
certificates_dir_ = src_dir.Append(FILE_PATH_LITERAL("net"))
.Append(FILE_PATH_LITERAL("data"))
.Append(FILE_PATH_LITERAL("ssl"))
.Append(FILE_PATH_LITERAL("certificates"));
}
TestServer::~TestServer() {
#if defined(OS_MACOSX)
SetMacTestCertificate(NULL);
#endif
Stop();
}
bool TestServer::Start() {
if (GetScheme() == "https") {
if (!LoadTestRootCert())
return false;
if (!CheckCATrusted())
return false;
}
// Get path to python server script
FilePath testserver_path;
if (!PathService::Get(base::DIR_SOURCE_ROOT, &testserver_path)) {
LOG(ERROR) << "Failed to get DIR_SOURCE_ROOT";
return false;
}
testserver_path = testserver_path
.Append(FILE_PATH_LITERAL("net"))
.Append(FILE_PATH_LITERAL("tools"))
.Append(FILE_PATH_LITERAL("testserver"))
.Append(FILE_PATH_LITERAL("testserver.py"));
if (!SetPythonPath())
return false;
if (!LaunchPython(testserver_path))
return false;
if (!WaitToStart()) {
Stop();
return false;
}
return true;
}
bool TestServer::Stop() {
if (!process_handle_)
return true;
// First check if the process has already terminated.
bool ret = base::WaitForSingleProcess(process_handle_, 0);
if (!ret)
ret = base::KillProcess(process_handle_, 1, true);
if (ret) {
base::CloseProcessHandle(process_handle_);
process_handle_ = base::kNullProcessHandle;
} else {
LOG(INFO) << "Kill failed?";
}
return ret;
}
bool TestServer::WaitToFinish(int timeout_ms) {
if (!process_handle_)
return true;
bool ret = base::WaitForSingleProcess(process_handle_, timeout_ms);
if (ret) {
base::CloseProcessHandle(process_handle_);
process_handle_ = base::kNullProcessHandle;
} else {
LOG(ERROR) << "Timed out.";
}
return ret;
}
std::string TestServer::GetScheme() const {
switch (type_) {
case TYPE_FTP:
return "ftp";
case TYPE_HTTP:
return "http";
case TYPE_HTTPS:
case TYPE_HTTPS_CLIENT_AUTH:
case TYPE_HTTPS_MISMATCHED_HOSTNAME:
case TYPE_HTTPS_EXPIRED_CERTIFICATE:
return "https";
default:
NOTREACHED();
}
return std::string();
}
bool TestServer::GetAddressList(AddressList* address_list) const {
DCHECK(address_list);
scoped_refptr<HostResolver> resolver(
CreateSystemHostResolver(HostResolver::kDefaultParallelism, NULL));
HostResolver::RequestInfo info(host_port_pair_);
int rv = resolver->Resolve(info, address_list, NULL, NULL, BoundNetLog());
if (rv != net::OK) {
LOG(ERROR) << "Failed to resolve hostname: " << host_port_pair_.host();
return false;
}
return true;
}
GURL TestServer::GetURL(const std::string& path) {
return GURL(GetScheme() + "://" + host_port_pair_.ToString() +
"/" + path);
}
GURL TestServer::GetURLWithUser(const std::string& path,
const std::string& user) {
return GURL(GetScheme() + "://" + user + "@" +
host_port_pair_.ToString() +
"/" + path);
}
GURL TestServer::GetURLWithUserAndPassword(const std::string& path,
const std::string& user,
const std::string& password) {
return GURL(GetScheme() + "://" + user + ":" + password +
"@" + host_port_pair_.ToString() +
"/" + path);
}
bool TestServer::SetPythonPath() {
FilePath third_party_dir;
if (!PathService::Get(base::DIR_SOURCE_ROOT, &third_party_dir)) {
LOG(ERROR) << "Failed to get DIR_SOURCE_ROOT";
return false;
}
third_party_dir = third_party_dir.Append(FILE_PATH_LITERAL("third_party"));
AppendToPythonPath(third_party_dir.Append(FILE_PATH_LITERAL("tlslite")));
AppendToPythonPath(third_party_dir.Append(FILE_PATH_LITERAL("pyftpdlib")));
// Locate the Python code generated by the protocol buffers compiler.
FilePath generated_code_dir;
if (!PathService::Get(base::DIR_EXE, &generated_code_dir)) {
LOG(ERROR) << "Failed to get DIR_EXE";
return false;
}
generated_code_dir = generated_code_dir.Append(FILE_PATH_LITERAL("pyproto"));
AppendToPythonPath(generated_code_dir);
AppendToPythonPath(generated_code_dir.Append(FILE_PATH_LITERAL("sync_pb")));
return true;
}
FilePath TestServer::GetRootCertificatePath() {
return certificates_dir_.AppendASCII("root_ca_cert.crt");
}
bool TestServer::LoadTestRootCert() {
#if defined(USE_NSS)
if (cert_)
return true;
// TODO(dkegel): figure out how to get this to only happen once?
// This currently leaks a little memory.
// TODO(dkegel): fix the leak and remove the entry in
// tools/valgrind/memcheck/suppressions.txt
ANNOTATE_SCOPED_MEMORY_LEAK; // Tell heap checker about the leak.
cert_ = LoadTemporaryRootCert(GetRootCertificatePath());
return (cert_ != NULL);
#elif defined(OS_MACOSX)
X509Certificate* cert = LoadTemporaryRootCert(GetRootCertificatePath());
if (!cert)
return false;
SetMacTestCertificate(cert);
return true;
#else
return true;
#endif
}
FilePath TestServer::GetCertificatePath() {
switch (type_) {
case TYPE_FTP:
case TYPE_HTTP:
return FilePath();
case TYPE_HTTPS:
case TYPE_HTTPS_CLIENT_AUTH:
case TYPE_HTTPS_MISMATCHED_HOSTNAME:
return certificates_dir_.AppendASCII("ok_cert.pem");
case TYPE_HTTPS_EXPIRED_CERTIFICATE:
return certificates_dir_.AppendASCII("expired_cert.pem");
default:
NOTREACHED();
}
return FilePath();
}
} // namespace net
<|endoftext|> |
<commit_before>#include <elevator/sessionmanager.h>
#include <elevator/serialization.h>
#include <elevator/restartwrapper.h>
namespace elevator {
using namespace serialization;
const udp::Address commSend{ udp::IPv4Address::any, udp::Port{ 64032 } };
const udp::Address commRcv{ udp::IPv4Address::any, udp::Port{ 64033 } };
const udp::Address commBroadcast{ udp::IPv4Address::broadcast, udp::Port{ 64033 } };
struct Initial {
Initial() = default;
Initial( std::tuple<> ) { };
std::tuple<> tuple() const { return std::tuple<>(); }
static TypeSignature type() {
return TypeSignature::InitialPacket;
}
};
struct Ready {
Ready() = default;
Ready( std::tuple<> ) { };
std::tuple<> tuple() const { return std::tuple<>(); }
static TypeSignature type() {
return TypeSignature::ElevatorReady;
}
};
struct RecoveryState {
RecoveryState() = default;
explicit RecoveryState( ElevatorState state ) : state( state ) { }
RecoveryState( std::tuple< ElevatorState > t )
: RecoveryState( std::get< 0 >( t ) )
{ }
static TypeSignature type() { return TypeSignature::RecoveryState; }
std::tuple< ElevatorState > tuple() const { return std::make_tuple( state ); }
ElevatorState state;
};
SessionManager::SessionManager( GlobalState &glo ) : _state( glo ),
_sendSock{ commSend, true }, _recvSock{ commRcv, true }
{ }
void SessionManager::_initSender( std::atomic< int > *initPhase ) {
udp::Socket _sendSock{ commSend, true };
_sendSock.enableBroadcast();
while( *initPhase < 2 ) {
udp::Packet pack;
switch ( *initPhase ) {
case 0: {
pack = Serializer::toPacket( Initial() );
break; }
case 1: {
pack = Serializer::toPacket( Ready() );
break; }
}
pack.address() = commBroadcast;
bool sent = _sendSock.sendPacket( pack );
assert( sent, "send failed" );
std::this_thread::sleep_for( std::chrono::milliseconds( 500 ) );
}
}
void SessionManager::_initListener( std::atomic< int > *initPhase, int count ) {
udp::Socket _recvSock{ commRcv, true };
std::set< udp::IPv4Address > barrier;
while ( *initPhase < 2 ) {
udp::Packet pack = _recvSock.recvPacketWithTimeout( 300 );
if ( pack.size() != 0 ) {
switch ( Serializer::packetType( pack ) ) {
case TypeSignature::InitialPacket: {
_peers.insert( pack.address().ip() );
break; }
case TypeSignature::ElevatorReady: {
_peers.insert( pack.address().ip() ); // it might still be that we dont know
barrier.insert( pack.address().ip() );
break; }
case TypeSignature::RecoveryState: {
_needRecovery = true;
auto maybeRecovered = Serializer::fromPacket< RecoveryState >( pack );
assert( !maybeRecovered.isNothing(), "error deserializing Recovery" );
RecoveryState recovered = maybeRecovered.value();
_state.update( recovered.state );
break; }
default:
std::cerr << "Unknown packet received on service channel" << std::endl;
}
if ( int( barrier.size() ) == count )
*initPhase = 2;
else if ( int( _peers.size() ) == count )
*initPhase = 1;
}
}
}
void SessionManager::connect( int count ) {
// first continue sending Initial messages untill we have count peers
std::atomic< int > initPhase{ 0 };
std::thread findPeers( &SessionManager::_initSender, this, &initPhase );
_initListener( &initPhase, count );
findPeers.join();
auto localAddrs = udp::IPv4Address::getMachineAddresses();
int i = 0;
// the set is sorted (guaranteed by C++) and therefore same on all elevators
for ( auto addr : _peers ) {
if ( localAddrs.find( addr ) != localAddrs.end() ) {
_id = i;
break;
}
++i;
}
assert_leq( 0, _id, "Could not assing ID" );
std::cout << "detected id " << _id << std::endl;
// if RecoveryState is received use it for initialization, save it
// and save recovery flag
// when we have count peers start sending Ready message untill we have
// count peers in ready set
// if Ready is received add to ready set
// now start monitoring thread
_thr = std::thread( restartWrapper( &SessionManager::_loop ), this );
}
void SessionManager::_loop() {
udp::Socket _recvSock{ commRcv, true };
while ( true ) {
udp::Packet pack = _recvSock.recvPacketWithTimeout( 300 );
if ( pack.size() != 0 && Serializer::packetType( pack ) == TypeSignature::InitialPacket ) {
int i = 0;
bool found = false;
for ( auto addr : _peers ) {
if ( addr == pack.address().ip() ) {
found = true;
break;
}
++i;
}
if ( !found ) {
/* NOTE: we can't add unknown elevator, it would change IDs and make
* mess in recovery mechanisms */
std::cerr << "WARNING: Attempt to socialization from unknown IP "
<< pack.address().ip() << ". It will be ignored." << std::endl;
continue;
}
std::cerr << "NOTICE: Sending recovery to elevator " << i << ", ("
<< pack.address().ip() << ")" << std::endl;
udp::Packet recovery = Serializer::toPacket( RecoveryState( _state.get( i ) ) );
recovery.address() = pack.address();
_sendSock.sendPacket( recovery );
}
}
}
}
<commit_msg>sessionmanager: Fix linking error.<commit_after>#include <elevator/sessionmanager.h>
#include <elevator/serialization.h>
#include <elevator/restartwrapper.h>
namespace elevator {
using namespace serialization;
const udp::Address SessionManager::commSend{ udp::IPv4Address::any, udp::Port{ 64032 } };
const udp::Address SessionManager::commRcv{ udp::IPv4Address::any, udp::Port{ 64033 } };
const udp::Address SessionManager::commBroadcast{ udp::IPv4Address::broadcast, udp::Port{ 64033 } };
struct Initial {
Initial() = default;
Initial( std::tuple<> ) { };
std::tuple<> tuple() const { return std::tuple<>(); }
static TypeSignature type() {
return TypeSignature::InitialPacket;
}
};
struct Ready {
Ready() = default;
Ready( std::tuple<> ) { };
std::tuple<> tuple() const { return std::tuple<>(); }
static TypeSignature type() {
return TypeSignature::ElevatorReady;
}
};
struct RecoveryState {
RecoveryState() = default;
explicit RecoveryState( ElevatorState state ) : state( state ) { }
RecoveryState( std::tuple< ElevatorState > t )
: RecoveryState( std::get< 0 >( t ) )
{ }
static TypeSignature type() { return TypeSignature::RecoveryState; }
std::tuple< ElevatorState > tuple() const { return std::make_tuple( state ); }
ElevatorState state;
};
SessionManager::SessionManager( GlobalState &glo ) : _state( glo ),
_sendSock{ commSend, true }, _recvSock{ commRcv, true }
{ }
void SessionManager::_initSender( std::atomic< int > *initPhase ) {
udp::Socket _sendSock{ commSend, true };
_sendSock.enableBroadcast();
while( *initPhase < 2 ) {
udp::Packet pack;
switch ( *initPhase ) {
case 0: {
pack = Serializer::toPacket( Initial() );
break; }
case 1: {
pack = Serializer::toPacket( Ready() );
break; }
}
pack.address() = commBroadcast;
bool sent = _sendSock.sendPacket( pack );
assert( sent, "send failed" );
std::this_thread::sleep_for( std::chrono::milliseconds( 500 ) );
}
}
void SessionManager::_initListener( std::atomic< int > *initPhase, int count ) {
udp::Socket _recvSock{ commRcv, true };
std::set< udp::IPv4Address > barrier;
while ( *initPhase < 2 ) {
udp::Packet pack = _recvSock.recvPacketWithTimeout( 300 );
if ( pack.size() != 0 ) {
switch ( Serializer::packetType( pack ) ) {
case TypeSignature::InitialPacket: {
_peers.insert( pack.address().ip() );
break; }
case TypeSignature::ElevatorReady: {
_peers.insert( pack.address().ip() ); // it might still be that we dont know
barrier.insert( pack.address().ip() );
break; }
case TypeSignature::RecoveryState: {
_needRecovery = true;
auto maybeRecovered = Serializer::fromPacket< RecoveryState >( pack );
assert( !maybeRecovered.isNothing(), "error deserializing Recovery" );
RecoveryState recovered = maybeRecovered.value();
_state.update( recovered.state );
break; }
default:
std::cerr << "Unknown packet received on service channel" << std::endl;
}
if ( int( barrier.size() ) == count )
*initPhase = 2;
else if ( int( _peers.size() ) == count )
*initPhase = 1;
}
}
}
void SessionManager::connect( int count ) {
// first continue sending Initial messages untill we have count peers
std::atomic< int > initPhase{ 0 };
std::thread findPeers( &SessionManager::_initSender, this, &initPhase );
_initListener( &initPhase, count );
findPeers.join();
auto localAddrs = udp::IPv4Address::getMachineAddresses();
int i = 0;
// the set is sorted (guaranteed by C++) and therefore same on all elevators
for ( auto addr : _peers ) {
if ( localAddrs.find( addr ) != localAddrs.end() ) {
_id = i;
break;
}
++i;
}
assert_leq( 0, _id, "Could not assing ID" );
std::cout << "detected id " << _id << std::endl;
// if RecoveryState is received use it for initialization, save it
// and save recovery flag
// when we have count peers start sending Ready message untill we have
// count peers in ready set
// if Ready is received add to ready set
// now start monitoring thread
_thr = std::thread( restartWrapper( &SessionManager::_loop ), this );
}
void SessionManager::_loop() {
udp::Socket _recvSock{ commRcv, true };
while ( true ) {
udp::Packet pack = _recvSock.recvPacketWithTimeout( 300 );
if ( pack.size() != 0 && Serializer::packetType( pack ) == TypeSignature::InitialPacket ) {
int i = 0;
bool found = false;
for ( auto addr : _peers ) {
if ( addr == pack.address().ip() ) {
found = true;
break;
}
++i;
}
if ( !found ) {
/* NOTE: we can't add unknown elevator, it would change IDs and make
* mess in recovery mechanisms */
std::cerr << "WARNING: Attempt to socialization from unknown IP "
<< pack.address().ip() << ". It will be ignored." << std::endl;
continue;
}
std::cerr << "NOTICE: Sending recovery to elevator " << i << ", ("
<< pack.address().ip() << ")" << std::endl;
udp::Packet recovery = Serializer::toPacket( RecoveryState( _state.get( i ) ) );
recovery.address() = pack.address();
_sendSock.sendPacket( recovery );
}
}
}
}
<|endoftext|> |
<commit_before>// Copyright (C) 2014 David Helkowski
// License GNU AGPLv3
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<libgen.h>
// Text to print before every hexidecimal byte representation
#define HEX_PREFIX '~'
// Characters to show normally instead of in hex
#define OK_CHARACTERS " {}\"'=-()<>,./_![]:&;?"
// Comment this out to disable acceptance of alpha-numeric characters
#define ALPHA_NUM
// Minimum number of sequential acceptable character needed to show text instead of hex
#define MIN_SEQUENCE 3
void phex( unsigned char let );
unsigned char let_okay( unsigned char let );
unsigned char accept[ 256 ];
int main( int argc, char *argv[] ) {
FILE *data_handle = 0;
bool showhelp = 0;
if( argc < 2 ) {
if( isatty( STDIN_FILENO ) ) {
showhelp = 1;
}
else {
fprintf(stderr, "Reading input from redirection\n" );
data_handle = stdin;
}
}
if( argc > 1 ) {
if( !strncmp( argv[1], "--help", 6 ) ) showhelp = 1;
fprintf(stderr, "Using file '%s' for input\n", argv[1] );
data_handle = fopen( argv[1], "r" );
if( !data_handle ) {
fprintf(stderr, "File does not exist\n" );
return 1;
}
}
if( showhelp ) {
char *base = basename( argv[0] );
printf("=== Text Hack ===\nTakes input data and outputs specific characters as regular text and hex for other characters.\n\n");
printf("Characters configured to be output normally:\n");
#ifdef ALPHA_NUM
printf(" Alphanumerics\n" );
#endif
printf(" %s\n\n", OK_CHARACTERS );
printf("Usage:\n %s [filename]\n %s < filename\n", base, base );
return 0;
}
if( !data_handle ) {
return 1;
}
#define STACK_SIZE MIN_SEQUENCE + 1
unsigned char stack[ STACK_SIZE ];
memset( stack, 0, STACK_SIZE );
// accept is a global
memset( accept, 0, 256 );
unsigned char accept_these[] = OK_CHARACTERS;
for( int i=0; i < sizeof( accept_these); i++ ) {
unsigned char let = accept_these[ i ];
accept[ let ] = 1;
}
unsigned char ok_cnt = 0;
int stack_fill = 0; // how much of the stack is filled
bool stack_full = 0;
while( 1 ) {
unsigned char let = fgetc( data_handle );
if( feof( data_handle ) ) break;
if( !stack_full ) {
stack_fill++;
if( stack_fill == MIN_SEQUENCE ) {
stack_full = 1;
}
}
// shift out the lowest char
unsigned char n_ago = stack[ 0 ];
for( int i=0;i<(MIN_SEQUENCE-1);i++ ) {
stack[ i ] = stack[ i + 1 ];
}
// push the new character onto the stack and pop the last one
stack[ MIN_SEQUENCE - 1 ] = let;
unsigned char num_ok = 0;
if( let_okay( n_ago ) ) {
num_ok++;
for( int i=0;i<=(MIN_SEQUENCE-1);i++ ) {
if( let_okay( stack[ i ] ) ) num_ok++;
else i=100;
}
}
else {
ok_cnt = 0;
}
if( ( num_ok + ok_cnt ) >= MIN_SEQUENCE ) {
putchar( n_ago );
ok_cnt++;
}
else {
phex( n_ago );
ok_cnt = 0;
}
}
for( int i=0;i<stack_fill;i++ ) {
putchar( stack[ i ] );
}
fclose( data_handle );
}
unsigned char let_okay( unsigned char let ) {
unsigned char ok = 0;
if( accept[ let ] ) ok = 1;
#ifdef ALPHA_NUM
if( let >= 'a' && let <= 'z' ) ok = 1;
if( let >= 'A' && let <= 'Z' ) ok = 1;
if( let >= '0' && let <= '9' ) ok = 1;
#endif
return ok;
}
void phex( unsigned char let ) {
printf( "%c%02X", HEX_PREFIX, let );
}<commit_msg>Inline contents of phex function since it is just 1 line. Update copyright year.<commit_after>// Copyright (C) 2018 David Helkowski
// License GNU AGPLv3
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<libgen.h>
// Text to print before every hexidecimal byte representation
#define HEX_PREFIX '~'
// Characters to show normally instead of in hex
#define OK_CHARACTERS " {}\"'=-()<>,./_![]:&;?"
// Comment this out to disable acceptance of alpha-numeric characters
#define ALPHA_NUM
// Minimum number of sequential acceptable character needed to show text instead of hex
#define MIN_SEQUENCE 3
unsigned char let_okay( unsigned char let );
unsigned char accept[ 256 ];
int main( int argc, char *argv[] ) {
FILE *data_handle = 0;
bool showhelp = 0;
if( argc < 2 ) {
if( isatty( STDIN_FILENO ) ) {
showhelp = 1;
}
else {
fprintf(stderr, "Reading input from redirection\n" );
data_handle = stdin;
}
}
if( argc > 1 ) {
if( !strncmp( argv[1], "--help", 6 ) ) showhelp = 1;
fprintf(stderr, "Using file '%s' for input\n", argv[1] );
data_handle = fopen( argv[1], "r" );
if( !data_handle ) {
fprintf(stderr, "File does not exist\n" );
return 1;
}
}
if( showhelp ) {
char *base = basename( argv[0] );
printf("=== Text Hack ===\nTakes input data and outputs specific characters as regular text and hex for other characters.\n\n");
printf("Characters configured to be output normally:\n");
#ifdef ALPHA_NUM
printf(" Alphanumerics\n" );
#endif
printf(" %s\n\n", OK_CHARACTERS );
printf("Usage:\n %s [filename]\n %s < filename\n", base, base );
return 0;
}
if( !data_handle ) {
return 1;
}
#define STACK_SIZE MIN_SEQUENCE + 1
unsigned char stack[ STACK_SIZE ];
memset( stack, 0, STACK_SIZE );
// accept is a global
memset( accept, 0, 256 );
unsigned char accept_these[] = OK_CHARACTERS;
for( int i=0; i < sizeof( accept_these); i++ ) {
unsigned char let = accept_these[ i ];
accept[ let ] = 1;
}
unsigned char ok_cnt = 0;
int stack_fill = 0; // how much of the stack is filled
bool stack_full = 0;
while( 1 ) {
unsigned char let = fgetc( data_handle );
if( feof( data_handle ) ) break;
if( !stack_full ) {
stack_fill++;
if( stack_fill == MIN_SEQUENCE ) {
stack_full = 1;
}
}
// shift out the lowest char
unsigned char n_ago = stack[ 0 ];
for( int i=0;i<(MIN_SEQUENCE-1);i++ ) {
stack[ i ] = stack[ i + 1 ];
}
// push the new character onto the stack and pop the last one
stack[ MIN_SEQUENCE - 1 ] = let;
unsigned char num_ok = 0;
if( let_okay( n_ago ) ) {
num_ok++;
for( int i=0;i<=(MIN_SEQUENCE-1);i++ ) {
if( let_okay( stack[ i ] ) ) num_ok++;
else i=100;
}
}
else {
ok_cnt = 0;
}
if( ( num_ok + ok_cnt ) >= MIN_SEQUENCE ) {
putchar( n_ago );
ok_cnt++;
}
else {
printf( "%c%02X", HEX_PREFIX, n_ago );
ok_cnt = 0;
}
}
for( int i=0;i<stack_fill;i++ ) {
putchar( stack[ i ] );
}
fclose( data_handle );
}
unsigned char let_okay( unsigned char let ) {
unsigned char ok = 0;
if( accept[ let ] ) ok = 1;
#ifdef ALPHA_NUM
if( let >= 'a' && let <= 'z' ) ok = 1;
if( let >= 'A' && let <= 'Z' ) ok = 1;
if( let >= '0' && let <= '9' ) ok = 1;
#endif
return ok;
}<|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkConfig.h"
#include "mitkPicHelper.h"
#include "mitkSlicedGeometry3D.h"
#include "mitkPlaneGeometry.h"
#ifdef HAVE_IPDICOM
#include "ipDicom/ipDicom.h"
#endif /* HAVE_IPDICOM */
bool mitk::PicHelper::GetSpacing(const ipPicDescriptor* aPic, Vector3D & spacing)
{
ipPicDescriptor* pic = const_cast<ipPicDescriptor*>(aPic);
ipPicTSV_t *tsv;
tsv = ipPicQueryTag( pic, "REAL PIXEL SIZE" );
if(tsv==NULL)
tsv = ipPicQueryTag( pic, "PIXEL SIZE" );
if(tsv)
{
if((tsv->dim*tsv->n[0]>=3) && (tsv->type==ipPicFloat))
{
if(tsv->bpe==32)
{
FillVector3D(spacing,((ipFloat4_t*)tsv->value)[0], ((ipFloat4_t*)tsv->value)[1],((ipFloat4_t*)tsv->value)[2]);
return true;
}
else
if(tsv->bpe==64)
{
FillVector3D(spacing,((ipFloat8_t*)tsv->value)[0], ((ipFloat8_t*)tsv->value)[1],((ipFloat8_t*)tsv->value)[2]);
return true;
}
}
}
#ifdef HAVE_IPDICOM
else
{
tsv = ipPicQueryTag( pic, "SOURCE HEADER" );
if( tsv )
{
void *data;
ipUInt4_t len;
ipFloat8_t spacing_z = 0;
ipFloat8_t thickness = 1;
ipFloat8_t fx = 1;
ipFloat8_t fy = 1;
bool ok=false;
if( dicomFindElement( (unsigned char *) tsv->value, 0x0018, 0x0088, &data, &len ) )
{
ok=true;
sscanf( (char *) data, "%lf", &spacing_z );
// itkGenericOutputMacro( "spacing: " << spacing_z << " mm");
}
if( dicomFindElement( (unsigned char *) tsv->value, 0x0018, 0x0050, &data, &len ) )
{
ok=true;
sscanf( (char *) data, "%lf", &thickness );
// itkGenericOutputMacro( "thickness: " << thickness << " mm");
if( thickness == 0 )
thickness = 1;
}
if( dicomFindElement( (unsigned char *) tsv->value, 0x0028, 0x0030, &data, &len )
&& len>0 && ((char *)data)[0] )
{
sscanf( (char *) data, "%lf\\%lf", &fy, &fx ); // row / column value
// itkGenericOutputMacro( "fx, fy: " << fx << "/" << fy << " mm");
}
else
ok=false;
if(ok)
FillVector3D(spacing, fx, fy,( spacing_z > 0 ? spacing_z : thickness));
return ok;
}
}
#endif /* HAVE_IPDICOM */
if(spacing[0]<=0 || spacing[1]<=0 || spacing[2]<=0)
{
itkGenericOutputMacro(<< "illegal spacing by pic tag: " << spacing << ". Setting spacing to (1,1,1).");
spacing.Fill(1);
}
return false;
}
bool mitk::PicHelper::SetSpacing(const ipPicDescriptor* aPic, SlicedGeometry3D* slicedgeometry)
{
ipPicDescriptor* pic = const_cast<ipPicDescriptor*>(aPic);
Vector3D spacing(slicedgeometry->GetSpacing());
ipPicTSV_t *tsv;
if ( (tsv = ipPicQueryTag( pic, "REAL PIXEL SIZES" )) != NULL)
{
int count = tsv->n[1];
float* value = (float*) tsv->value;
mitk::Vector3D pixelSize;
spacing.Fill(0);
for ( int s=0; s < count; s++ )
{
pixelSize[0] = (ScalarType) *value++;
pixelSize[1] = (ScalarType) *value++;
pixelSize[2] = (ScalarType) *value++;
spacing += pixelSize;
}
spacing *= 1.0f/count;
slicedgeometry->SetSpacing(spacing);
itkGenericOutputMacro(<< "the slices are inhomogeneous" );
}
else
if(GetSpacing(pic, spacing))
{
slicedgeometry->SetSpacing(spacing);
return true;
}
return false;
}
void mitk::PicHelper::InitializeEvenlySpaced(const ipPicDescriptor* pic, unsigned int slices, SlicedGeometry3D* slicedgeometry)
{
assert(pic!=NULL);
assert(slicedgeometry!=NULL);
mitk::PlaneGeometry::Pointer planegeometry=mitk::PlaneGeometry::New();
ipPicTSV_t *geometryTag;
if ( (geometryTag = ipPicQueryTag( const_cast<ipPicDescriptor*>(pic), "ISG" )) != NULL)
{
mitk::Point3D origin;
mitk::Vector3D rightVector;
mitk::Vector3D downVector;
mitk::Vector3D spacing;
mitk::vtk2itk(((float*)geometryTag->value+0), origin);
mitk::vtk2itk(((float*)geometryTag->value+3), rightVector);
mitk::vtk2itk(((float*)geometryTag->value+6), downVector);
mitk::vtk2itk(((float*)geometryTag->value+9), spacing);
mitk::PlaneGeometry::Pointer planegeometry = PlaneGeometry::New();
planegeometry->InitializeStandardPlane(pic->n[0], pic->n[1], rightVector, downVector, &spacing);
planegeometry->SetOrigin(origin);
slicedgeometry->InitializeEvenlySpaced(planegeometry, slices);
}
else
{
Vector3D spacing;
spacing.Fill(1);
GetSpacing(pic, spacing);
planegeometry->InitializeStandardPlane(pic->n[0], pic->n[1], spacing);
slicedgeometry->InitializeEvenlySpaced(planegeometry, spacing[2], slices);
}
if(pic->dim>=4)
{
TimeBounds timebounds;
timebounds[0] = 0.0;
timebounds[1] = 1.0;
slicedgeometry->SetTimeBounds(timebounds);
}
}
bool mitk::PicHelper::SetGeometry2D(const ipPicDescriptor* aPic, int s, SlicedGeometry3D* slicedgeometry)
{
ipPicDescriptor* pic = const_cast<ipPicDescriptor*>(aPic);
if((pic!=NULL) && (slicedgeometry->IsValidSlice(s)))
{
//construct standard view
mitk::Point3D origin;
mitk::Vector3D rightDV, bottomDV;
ipPicTSV_t *tsv;
if ( (tsv = ipPicQueryTag( pic, "REAL PIXEL SIZES" )) != NULL)
{
unsigned int count = (unsigned int) tsv->n[1];
float* value = (float*) tsv->value;
mitk::Vector3D pixelSize;
ScalarType zPosition = 0.0f;
if(s >= 0)
{
if(count < (unsigned int) s)
return false;
count = s;
}
else
{
if(count < slicedgeometry->GetSlices())
return false;
count = slicedgeometry->GetSlices();
}
unsigned int slice;
for (slice=0; slice < count; ++slice )
{
pixelSize[0] = (ScalarType) *value++;
pixelSize[1] = (ScalarType) *value++;
pixelSize[2] = (ScalarType) *value++;
zPosition += pixelSize[2] / 2.0f; // first half slice thickness
if((s==-1) || (slice== (unsigned int) s))
{
Vector3D spacing;
spacing = pixelSize;
FillVector3D(origin, 0, 0, zPosition);
FillVector3D(rightDV, pic->n[0], 0, 0);
FillVector3D(bottomDV, 0, pic->n[1], 0);
mitk::PlaneGeometry::Pointer planegeometry=mitk::PlaneGeometry::New();
planegeometry->InitializeStandardPlane(pic->n[0], pic->n[1], rightDV.Get_vnl_vector(), bottomDV.Get_vnl_vector(), &spacing);
planegeometry->SetOrigin(origin);
slicedgeometry->SetGeometry2D(planegeometry, s);
}
zPosition += pixelSize[2] / 2.0f; // second half slice thickness
}
}
else
{
FillVector3D(origin,0,0,s); slicedgeometry->IndexToWorld(origin, origin);
FillVector3D(rightDV,pic->n[0],0,0);
FillVector3D(bottomDV,0,pic->n[1],0);
mitk::PlaneGeometry::Pointer planegeometry=mitk::PlaneGeometry::New();
planegeometry->InitializeStandardPlane(pic->n[0], pic->n[1], rightDV.Get_vnl_vector(), bottomDV.Get_vnl_vector(), &slicedgeometry->GetSpacing());
planegeometry->SetOrigin(origin);
slicedgeometry->SetGeometry2D(planegeometry, s);
}
return true;
}
return false;
}
<commit_msg>ENH: try to use tag "PIXEL SPACING" to access z-spacing in cases where there is only a "PIXEL SIZE" tag<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkConfig.h"
#include "mitkPicHelper.h"
#include "mitkSlicedGeometry3D.h"
#include "mitkPlaneGeometry.h"
#ifdef HAVE_IPDICOM
#include "ipDicom/ipDicom.h"
#endif /* HAVE_IPDICOM */
bool mitk::PicHelper::GetSpacing(const ipPicDescriptor* aPic, Vector3D & spacing)
{
ipPicDescriptor* pic = const_cast<ipPicDescriptor*>(aPic);
ipPicTSV_t *tsv;
bool pixelSize = false;
tsv = ipPicQueryTag( pic, "REAL PIXEL SIZE" );
if(tsv==NULL)
{
tsv = ipPicQueryTag( pic, "PIXEL SIZE" );
pixelSize = true;
}
if(tsv)
{
bool tagFound = false;
if((tsv->dim*tsv->n[0]>=3) && (tsv->type==ipPicFloat))
{
if(tsv->bpe==32)
{
FillVector3D(spacing,((ipFloat4_t*)tsv->value)[0], ((ipFloat4_t*)tsv->value)[1],((ipFloat4_t*)tsv->value)[2]);
tagFound = true;
}
else
if(tsv->bpe==64)
{
FillVector3D(spacing,((ipFloat8_t*)tsv->value)[0], ((ipFloat8_t*)tsv->value)[1],((ipFloat8_t*)tsv->value)[2]);
tagFound = true;
}
}
if(tagFound && pixelSize)
{
tsv = ipPicQueryTag( pic, "PIXEL SPACING" );
if(tsv)
{
mitk::ScalarType zSpacing = 0;
if((tsv->dim*tsv->n[0]>=3) && (tsv->type==ipPicFloat))
{
if(tsv->bpe==32)
{
zSpacing = ((ipFloat4_t*)tsv->value)[2];
}
else
if(tsv->bpe==64)
{
zSpacing = ((ipFloat8_t*)tsv->value)[2];
}
if(zSpacing != 0)
{
spacing[2] = zSpacing;
}
}
}
}
if(tagFound) return true;
}
#ifdef HAVE_IPDICOM
tsv = ipPicQueryTag( pic, "SOURCE HEADER" );
if( tsv )
{
void *data;
ipUInt4_t len;
ipFloat8_t spacing_z = 0;
ipFloat8_t thickness = 1;
ipFloat8_t fx = 1;
ipFloat8_t fy = 1;
bool ok=false;
if( dicomFindElement( (unsigned char *) tsv->value, 0x0018, 0x0088, &data, &len ) )
{
ok=true;
sscanf( (char *) data, "%lf", &spacing_z );
// itkGenericOutputMacro( "spacing: " << spacing_z << " mm");
}
if( dicomFindElement( (unsigned char *) tsv->value, 0x0018, 0x0050, &data, &len ) )
{
ok=true;
sscanf( (char *) data, "%lf", &thickness );
// itkGenericOutputMacro( "thickness: " << thickness << " mm");
if( thickness == 0 )
thickness = 1;
}
if( dicomFindElement( (unsigned char *) tsv->value, 0x0028, 0x0030, &data, &len )
&& len>0 && ((char *)data)[0] )
{
sscanf( (char *) data, "%lf\\%lf", &fy, &fx ); // row / column value
// itkGenericOutputMacro( "fx, fy: " << fx << "/" << fy << " mm");
}
else
ok=false;
if(ok)
FillVector3D(spacing, fx, fy,( spacing_z > 0 ? spacing_z : thickness));
return ok;
}
#endif /* HAVE_IPDICOM */
if(spacing[0]<=0 || spacing[1]<=0 || spacing[2]<=0)
{
itkGenericOutputMacro(<< "illegal spacing by pic tag: " << spacing << ". Setting spacing to (1,1,1).");
spacing.Fill(1);
}
return false;
}
bool mitk::PicHelper::SetSpacing(const ipPicDescriptor* aPic, SlicedGeometry3D* slicedgeometry)
{
ipPicDescriptor* pic = const_cast<ipPicDescriptor*>(aPic);
Vector3D spacing(slicedgeometry->GetSpacing());
ipPicTSV_t *tsv;
if ( (tsv = ipPicQueryTag( pic, "REAL PIXEL SIZES" )) != NULL)
{
int count = tsv->n[1];
float* value = (float*) tsv->value;
mitk::Vector3D pixelSize;
spacing.Fill(0);
for ( int s=0; s < count; s++ )
{
pixelSize[0] = (ScalarType) *value++;
pixelSize[1] = (ScalarType) *value++;
pixelSize[2] = (ScalarType) *value++;
spacing += pixelSize;
}
spacing *= 1.0f/count;
slicedgeometry->SetSpacing(spacing);
itkGenericOutputMacro(<< "the slices are inhomogeneous" );
}
else
if(GetSpacing(pic, spacing))
{
slicedgeometry->SetSpacing(spacing);
return true;
}
return false;
}
void mitk::PicHelper::InitializeEvenlySpaced(const ipPicDescriptor* pic, unsigned int slices, SlicedGeometry3D* slicedgeometry)
{
assert(pic!=NULL);
assert(slicedgeometry!=NULL);
mitk::PlaneGeometry::Pointer planegeometry=mitk::PlaneGeometry::New();
ipPicTSV_t *geometryTag;
if ( (geometryTag = ipPicQueryTag( const_cast<ipPicDescriptor*>(pic), "ISG" )) != NULL)
{
mitk::Point3D origin;
mitk::Vector3D rightVector;
mitk::Vector3D downVector;
mitk::Vector3D spacing;
mitk::vtk2itk(((float*)geometryTag->value+0), origin);
mitk::vtk2itk(((float*)geometryTag->value+3), rightVector);
mitk::vtk2itk(((float*)geometryTag->value+6), downVector);
mitk::vtk2itk(((float*)geometryTag->value+9), spacing);
mitk::PlaneGeometry::Pointer planegeometry = PlaneGeometry::New();
planegeometry->InitializeStandardPlane(pic->n[0], pic->n[1], rightVector, downVector, &spacing);
planegeometry->SetOrigin(origin);
slicedgeometry->InitializeEvenlySpaced(planegeometry, slices);
}
else
{
Vector3D spacing;
spacing.Fill(1);
GetSpacing(pic, spacing);
planegeometry->InitializeStandardPlane(pic->n[0], pic->n[1], spacing);
slicedgeometry->InitializeEvenlySpaced(planegeometry, spacing[2], slices);
}
if(pic->dim>=4)
{
TimeBounds timebounds;
timebounds[0] = 0.0;
timebounds[1] = 1.0;
slicedgeometry->SetTimeBounds(timebounds);
}
}
bool mitk::PicHelper::SetGeometry2D(const ipPicDescriptor* aPic, int s, SlicedGeometry3D* slicedgeometry)
{
ipPicDescriptor* pic = const_cast<ipPicDescriptor*>(aPic);
if((pic!=NULL) && (slicedgeometry->IsValidSlice(s)))
{
//construct standard view
mitk::Point3D origin;
mitk::Vector3D rightDV, bottomDV;
ipPicTSV_t *tsv;
if ( (tsv = ipPicQueryTag( pic, "REAL PIXEL SIZES" )) != NULL)
{
unsigned int count = (unsigned int) tsv->n[1];
float* value = (float*) tsv->value;
mitk::Vector3D pixelSize;
ScalarType zPosition = 0.0f;
if(s >= 0)
{
if(count < (unsigned int) s)
return false;
count = s;
}
else
{
if(count < slicedgeometry->GetSlices())
return false;
count = slicedgeometry->GetSlices();
}
unsigned int slice;
for (slice=0; slice < count; ++slice )
{
pixelSize[0] = (ScalarType) *value++;
pixelSize[1] = (ScalarType) *value++;
pixelSize[2] = (ScalarType) *value++;
zPosition += pixelSize[2] / 2.0f; // first half slice thickness
if((s==-1) || (slice== (unsigned int) s))
{
Vector3D spacing;
spacing = pixelSize;
FillVector3D(origin, 0, 0, zPosition);
FillVector3D(rightDV, pic->n[0], 0, 0);
FillVector3D(bottomDV, 0, pic->n[1], 0);
mitk::PlaneGeometry::Pointer planegeometry=mitk::PlaneGeometry::New();
planegeometry->InitializeStandardPlane(pic->n[0], pic->n[1], rightDV.Get_vnl_vector(), bottomDV.Get_vnl_vector(), &spacing);
planegeometry->SetOrigin(origin);
slicedgeometry->SetGeometry2D(planegeometry, s);
}
zPosition += pixelSize[2] / 2.0f; // second half slice thickness
}
}
else
{
FillVector3D(origin,0,0,s); slicedgeometry->IndexToWorld(origin, origin);
FillVector3D(rightDV,pic->n[0],0,0);
FillVector3D(bottomDV,0,pic->n[1],0);
mitk::PlaneGeometry::Pointer planegeometry=mitk::PlaneGeometry::New();
planegeometry->InitializeStandardPlane(pic->n[0], pic->n[1], rightDV.Get_vnl_vector(), bottomDV.Get_vnl_vector(), &slicedgeometry->GetSpacing());
planegeometry->SetOrigin(origin);
slicedgeometry->SetGeometry2D(planegeometry, s);
}
return true;
}
return false;
}
<|endoftext|> |
<commit_before>#include "EventMapper.h"
//XML Event
//##ModelId=3E788FC000E5
const std::string mitk::EventMapper::STYLE = "STYLE";
//##ModelId=3E788FC0025C
const std::string mitk::EventMapper::NAME = "NAME";
//##ModelId=3E788FC002AA
const std::string mitk::EventMapper::ID = "ID";
//##ModelId=3E77572901E9
const std::string mitk::EventMapper::TYPE = "TYPE";
//##ModelId=3E7757290256
const std::string mitk::EventMapper::BUTTON = "BUTTON";
//##ModelId=3E8B08FA01AA
const std::string mitk::EventMapper::BUTTONSTATE = "BUTTONSTATE";
//##ModelId=3E77572902C4
const std::string mitk::EventMapper::KEY = "KEY";
//##ModelId=3E7757290341
//const std::string mitk::EventMapper::ISTRUE = "TRUE";
//##ModelId=3E77572903AE
//const std::string mitk::EventMapper::ISFALSE = "FALSE";
//##ModelId=3E5B349600CB
void mitk::EventMapper::SetStateMachine(StateMachine* stateMachine)
{
m_StateMachine = stateMachine;
}
//##ModelId=3E5B34CF0041
bool mitk::EventMapper::MapEvent(Event* event)
{
if (m_StateMachine == NULL)
return false;
int i;
for (i = 0;
(i < ((int)(m_EventDescriptions.size()))) ||
!(m_EventDescriptions.at(i) == *event);
i++){}
if (!(m_EventDescriptions.at(i) == *event))//searched entry not found
return false;
m_StateEvent.Set( (m_EventDescriptions.at(i)).GetId(), event );
m_StateMachine->HandleEvent(&m_StateEvent);
return true;
}
//##ModelId=3E5B35140072
bool mitk::EventMapper::LoadBehavior(std::string fileName)
{
if ( fileName.empty() )
return false;
QFile xmlFile( fileName.c_str() );
if ( !xmlFile.exists() )
return false;
QXmlInputSource source( &xmlFile );
QXmlSimpleReader reader;
mitk::EventMapper* eventMapper = new EventMapper();
reader.setContentHandler( eventMapper );
reader.parse( source );
delete eventMapper;
return true;
}
//##ModelId=3E788FC00308
bool mitk::EventMapper::startElement( const QString&, const QString&, const QString& qName, const QXmlAttributes& atts )
{
qName.ascii(); //for debuging
if( qName == "events")
{
m_StyleName = atts.value( STYLE.c_str() ).latin1();
}
else if ( qName == "event")
{
//neuen Eintrag in der m_EventDescriptions
EventDescription tempEventDescr( atts.value( NAME.c_str() ).latin1(),
atts.value( ID.c_str() ).toInt(),
atts.value( TYPE.c_str() ).toInt(),
atts.value( BUTTON.c_str() ).toInt(),
atts.value( BUTTONSTATE.c_str() ).toInt(),
atts.value( KEY.c_str() ).toInt() );
m_EventDescriptions.push_back(tempEventDescr);
}
return true;
}
//##ModelId=3E7B20EE01F5
std::string mitk::EventMapper::GetStyleName()
{
return m_StyleName;
}
<commit_msg>no message<commit_after>#include "EventMapper.h"
//XML Event
//##ModelId=3E788FC000E5
const std::string mitk::EventMapper::STYLE = "STYLE";
//##ModelId=3E788FC0025C
const std::string mitk::EventMapper::NAME = "NAME";
//##ModelId=3E788FC002AA
const std::string mitk::EventMapper::ID = "ID";
//##ModelId=3E77572901E9
const std::string mitk::EventMapper::TYPE = "TYPE";
//##ModelId=3E7757290256
const std::string mitk::EventMapper::BUTTON = "BUTTON";
//##ModelId=3E8B08FA01AA
const std::string mitk::EventMapper::BUTTONSTATE = "BUTTONSTATE";
//##ModelId=3E77572902C4
const std::string mitk::EventMapper::KEY = "KEY";
//##ModelId=3E7757290341
//const std::string mitk::EventMapper::ISTRUE = "TRUE";
//##ModelId=3E77572903AE
//const std::string mitk::EventMapper::ISFALSE = "FALSE";
//##ModelId=3E5B349600CB
void mitk::EventMapper::SetStateMachine(StateMachine* stateMachine)
{
m_StateMachine = stateMachine;
}
//##ModelId=3E5B34CF0041
bool mitk::EventMapper::MapEvent(Event* event)
{
if (m_StateMachine == NULL)
return false;
int i;
for (i = 0;
(i < ((int)(m_EventDescriptions.size()))) ||
!(m_EventDescriptions[i] == *event);//insecure[] but .at(i) is not supported before std.vers 3.0
i++){}
if (!(m_EventDescriptions[i] == *event))//insecure
//searched entry not found
return false;
m_StateEvent.Set( (m_EventDescriptions.at(i)).GetId(), event );
m_StateMachine->HandleEvent(&m_StateEvent);
return true;
}
//##ModelId=3E5B35140072
bool mitk::EventMapper::LoadBehavior(std::string fileName)
{
if ( fileName.empty() )
return false;
QFile xmlFile( fileName.c_str() );
if ( !xmlFile.exists() )
return false;
QXmlInputSource source( &xmlFile );
QXmlSimpleReader reader;
mitk::EventMapper* eventMapper = new EventMapper();
reader.setContentHandler( eventMapper );
reader.parse( source );
delete eventMapper;
return true;
}
//##ModelId=3E788FC00308
bool mitk::EventMapper::startElement( const QString&, const QString&, const QString& qName, const QXmlAttributes& atts )
{
qName.ascii(); //for debuging
if( qName == "events")
{
m_StyleName = atts.value( STYLE.c_str() ).latin1();
}
else if ( qName == "event")
{
//neuen Eintrag in der m_EventDescriptions
EventDescription tempEventDescr( atts.value( NAME.c_str() ).latin1(),
atts.value( ID.c_str() ).toInt(),
atts.value( TYPE.c_str() ).toInt(),
atts.value( BUTTON.c_str() ).toInt(),
atts.value( BUTTONSTATE.c_str() ).toInt(),
atts.value( KEY.c_str() ).toInt() );
m_EventDescriptions.push_back(tempEventDescr);
}
return true;
}
//##ModelId=3E7B20EE01F5
std::string mitk::EventMapper::GetStyleName()
{
return m_StyleName;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: frmselimpl.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: ihi $ $Date: 2007-06-06 14:07:34 $
*
* 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 SVX_FRMSELIMPL_HXX
#define SVX_FRMSELIMPL_HXX
#ifndef _SV_VIRDEV_HXX
#include <vcl/virdev.hxx>
#endif
#ifndef _SV_IMAGE_HXX
#include <vcl/image.hxx>
#endif
#ifndef SVX_FRMSEL_HXX
#include "frmsel.hxx"
#endif
#ifndef SVX_FRAMELINKARRAY_HXX
#include "framelinkarray.hxx"
#endif
#ifndef SVX_BORDERLINE_HXX
#include "borderline.hxx"
#endif
namespace svx {
namespace a11y { class AccFrameSelector; }
// ============================================================================
class FrameBorder
{
public:
explicit FrameBorder( FrameBorderType eType );
inline FrameBorderType GetType() const { return meType; }
inline bool IsEnabled() const { return mbEnabled; }
void Enable( FrameSelFlags nFlags );
inline FrameBorderState GetState() const { return meState; }
void SetState( FrameBorderState eState );
inline bool IsSelected() const { return mbSelected; }
inline void Select( bool bSelect ) { mbSelected = bSelect; }
const SvxBorderLine& GetCoreStyle() const { return maCoreStyle; }
void SetCoreStyle( const SvxBorderLine* pStyle );
inline void SetUIColor( const Color& rColor ) {maUIStyle.SetColor( rColor ); }
inline const frame::Style& GetUIStyle() const { return maUIStyle; }
inline void ClearFocusArea() { maFocusArea.Clear(); }
void AddFocusPolygon( const Polygon& rFocus );
void MergeFocusToPolyPolygon( PolyPolygon& rPPoly ) const;
inline void ClearClickArea() { maClickArea.Clear(); }
void AddClickRect( const Rectangle& rRect );
bool ContainsClickPoint( const Point& rPos ) const;
void MergeClickAreaToPolyPolygon( PolyPolygon& rPPoly ) const;
Rectangle GetClickBoundRect() const;
void SetKeyboardNeighbors(
FrameBorderType eLeft, FrameBorderType eRight,
FrameBorderType eTop, FrameBorderType eBottom );
FrameBorderType GetKeyboardNeighbor( USHORT nKeyCode ) const;
private:
const FrameBorderType meType; /// Frame border type (position in control).
FrameBorderState meState; /// Frame border state (on/off/don't care).
SvxBorderLine maCoreStyle; /// Core style from application.
frame::Style maUIStyle; /// Internal style to draw lines.
FrameBorderType meKeyLeft; /// Left neighbor for keyboard control.
FrameBorderType meKeyRight; /// Right neighbor for keyboard control.
FrameBorderType meKeyTop; /// Upper neighbor for keyboard control.
FrameBorderType meKeyBottom; /// Lower neighbor for keyboard control.
PolyPolygon maFocusArea; /// Focus drawing areas.
PolyPolygon maClickArea; /// Mouse click areas.
bool mbEnabled; /// true = Border enabled in control.
bool mbSelected; /// true = Border selected in control.
};
// ============================================================================
typedef std::vector< FrameBorder* > FrameBorderPtrVec;
struct FrameSelectorImpl : public Resource
{
typedef ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible > XAccessibleRef;
typedef std::vector< a11y::AccFrameSelector* > AccessibleImplVec;
typedef std::vector< XAccessibleRef > XAccessibleRefVec;
FrameSelector& mrFrameSel; /// The control itself.
VirtualDevice maVirDev; /// For all buffered drawing operations.
ImageList maILArrows; /// Arrows in current system colors.
Color maBackCol; /// Background color.
Color maArrowCol; /// Selection arrow color.
Color maMarkCol; /// Selection marker color.
Color maHCLineCol; /// High contrast line color.
Point maVirDevPos; /// Position of virtual device in the control.
Point maMousePos; /// Last mouse pointer position.
FrameBorder maLeft; /// All data of left frame border.
FrameBorder maRight; /// All data of right frame border.
FrameBorder maTop; /// All data of top frame border.
FrameBorder maBottom; /// All data of bottom frame border.
FrameBorder maHor; /// All data of inner horizontal frame border.
FrameBorder maVer; /// All data of inner vertical frame border.
FrameBorder maTLBR; /// All data of top-left to bottom-right frame border.
FrameBorder maBLTR; /// All data of bottom-left to top-right frame border.
SvxBorderLine maCurrStyle; /// Current style and color for new borders.
frame::Array maArray; /// Frame link array to draw an array of frame borders.
FrameSelFlags mnFlags; /// Flags for enabled frame borders.
FrameBorderPtrVec maAllBorders; /// Pointers to all frame borders.
FrameBorderPtrVec maEnabBorders; /// Pointers to enables frame borders.
Link maSelectHdl; /// Selection handler.
long mnCtrlSize; /// Size of the control (always square).
long mnArrowSize; /// Size of an arrow image.
long mnLine1; /// Middle of left/top frame borders.
long mnLine2; /// Middle of inner frame borders.
long mnLine3; /// Middle of right/bottom frame borders.
long mnFocusOffs; /// Offset from frame border middle to draw focus.
bool mbHor; /// true = Inner horizontal frame border enabled.
bool mbVer; /// true = Inner vertical frame border enabled.
bool mbTLBR; /// true = Top-left to bottom-right frame border enabled.
bool mbBLTR; /// true = Bottom-left to top-right frame border enabled.
bool mbFullRepaint; /// Used for repainting (false = only copy virtual device).
bool mbAutoSelect; /// true = Auto select a frame border, if focus reaches control.
bool mbClicked; /// true = The control has been clicked at least one time.
bool mbHCMode; /// true = High contrast mode.
a11y::AccFrameSelector* mpAccess; /// Pointer to accessibility object of the control.
XAccessibleRef mxAccess; /// Reference to accessibility object of the control.
AccessibleImplVec maChildVec; /// Pointers to accessibility objects for frame borders.
XAccessibleRefVec mxChildVec; /// References to accessibility objects for frame borders.
explicit FrameSelectorImpl( FrameSelector& rFrameSel );
~FrameSelectorImpl();
// initialization ---------------------------------------------------------
/** Initializes the control, enables/disables frame borders according to flags. */
void Initialize( FrameSelFlags nFlags );
/** Fills all color members from current style settings. */
void InitColors();
/** Creates the image list with selection arrows regarding current style settings. */
void InitArrowImageList();
/** Initializes global coordinates. */
void InitGlobalGeometry();
/** Initializes coordinates of all frame borders. */
void InitBorderGeometry();
/** Initializes click areas of all enabled frame borders. */
void InitClickAreas();
/** Draws the entire control into the internal virtual device. */
void InitVirtualDevice();
// frame border access ----------------------------------------------------
/** Returns the object representing the specified frame border. */
const FrameBorder& GetBorder( FrameBorderType eBorder ) const;
/** Returns the object representing the specified frame border (write access). */
FrameBorder& GetBorderAccess( FrameBorderType eBorder );
// drawing ----------------------------------------------------------------
/** Draws the background of the entire control (the gray areas between borders). */
void DrawBackground();
/** Draws selection arrows for the specified frame border. */
void DrawArrows( const FrameBorder& rBorder );
/** Draws arrows in current selection state for all enabled frame borders. */
void DrawAllArrows();
/** Returns the color that has to be used to draw a frame border. */
Color GetDrawLineColor( const Color& rColor ) const;
/** Draws all frame borders. */
void DrawAllFrameBorders();
/** Draws all contents of the control. */
void DrawVirtualDevice();
/** Copies contents of the virtual device to the control. */
void CopyVirDevToControl();
/** Draws tracking rectangles for all selected frame borders. */
void DrawAllTrackingRects();
/** Converts a mouse position to the virtual device position. */
Point GetDevPosFromMousePos( const Point& rMousePos ) const;
/** Invalidates the control.
@param bFullRepaint true = Full repaint; false = update selection only. */
void DoInvalidate( bool bFullRepaint );
// frame border state and style -------------------------------------------
/** Sets the state of the specified frame border. */
void SetBorderState( FrameBorder& rBorder, FrameBorderState eState );
/** Sets the core style of the specified frame border, or hides the frame border, if pStyle is 0. */
void SetBorderCoreStyle( FrameBorder& rBorder, const SvxBorderLine* pStyle );
/** Sets the color of the specified frame border. */
void SetBorderColor( FrameBorder& rBorder, const Color& rColor );
/** Changes the state of a frame border after a control event (mouse/keyboard). */
void ToggleBorderState( FrameBorder& rBorder );
// frame border selection -------------------------------------------------
/** Selects a frame border and schedules redraw. */
void SelectBorder( FrameBorder& rBorder, bool bSelect );
/** Grabs focus without auto-selection of a frame border, if no border selected. */
void SilentGrabFocus();
/** Returns true, if all selected frame borders are equal (or if nothing is selected). */
bool SelectedBordersEqual() const;
};
// ============================================================================
/** Dummy predicate for frame border iterators to use all borders in a container. */
struct FrameBorderDummy_Pred
{
inline bool operator()( const FrameBorder* ) const { return true; }
};
/** Predicate for frame border iterators to use only visible borders in a container. */
struct FrameBorderVisible_Pred
{
inline bool operator()( const FrameBorder* pBorder ) const { return pBorder->GetState() == FRAMESTATE_SHOW; }
};
/** Predicate for frame border iterators to use only selected borders in a container. */
struct FrameBorderSelected_Pred
{
inline bool operator()( const FrameBorder* pBorder ) const { return pBorder->IsSelected(); }
};
/** Template class for all types of frame border iterators. */
template< typename Cont, typename Iter, typename Pred >
class FrameBorderIterBase
{
public:
typedef Cont container_type;
typedef Iter iterator_type;
typedef Pred predicate_type;
typedef typename Cont::value_type value_type;
typedef FrameBorderIterBase< Cont, Iter, Pred > this_type;
explicit FrameBorderIterBase( container_type& rCont );
inline bool Is() const { return maIt != maEnd; }
this_type& operator++();
inline value_type operator*() const { return *maIt; }
private:
iterator_type maIt;
iterator_type maEnd;
predicate_type maPred;
};
/** Iterator for constant svx::FrameBorder containers, iterates over all borders. */
typedef FrameBorderIterBase< const FrameBorderPtrVec, FrameBorderPtrVec::const_iterator, FrameBorderDummy_Pred >
FrameBorderCIter;
/** Iterator for mutable svx::FrameBorder containers, iterates over all borders. */
typedef FrameBorderIterBase< FrameBorderPtrVec, FrameBorderPtrVec::iterator, FrameBorderDummy_Pred >
FrameBorderIter;
/** Iterator for constant svx::FrameBorder containers, iterates over visible borders. */
typedef FrameBorderIterBase< const FrameBorderPtrVec, FrameBorderPtrVec::const_iterator, FrameBorderVisible_Pred >
VisFrameBorderCIter;
/** Iterator for mutable svx::FrameBorder containers, iterates over visible borders. */
typedef FrameBorderIterBase< FrameBorderPtrVec, FrameBorderPtrVec::iterator, FrameBorderVisible_Pred >
VisFrameBorderIter;
/** Iterator for constant svx::FrameBorder containers, iterates over selected borders. */
typedef FrameBorderIterBase< const FrameBorderPtrVec, FrameBorderPtrVec::const_iterator, FrameBorderSelected_Pred >
SelFrameBorderCIter;
/** Iterator for mutable svx::FrameBorder containers, iterates over selected borders. */
typedef FrameBorderIterBase< FrameBorderPtrVec, FrameBorderPtrVec::iterator, FrameBorderSelected_Pred >
SelFrameBorderIter;
// ============================================================================
} // namespace svx
#endif
<commit_msg>INTEGRATION: CWS vgbugs07 (1.3.876); FILE MERGED 2007/06/04 13:27:03 vg 1.3.876.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: frmselimpl.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2007-06-27 18:23:50 $
*
* 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 SVX_FRMSELIMPL_HXX
#define SVX_FRMSELIMPL_HXX
#ifndef _SV_VIRDEV_HXX
#include <vcl/virdev.hxx>
#endif
#ifndef _SV_IMAGE_HXX
#include <vcl/image.hxx>
#endif
#ifndef SVX_FRMSEL_HXX
#include <svx/frmsel.hxx>
#endif
#ifndef SVX_FRAMELINKARRAY_HXX
#include <svx/framelinkarray.hxx>
#endif
#ifndef SVX_BORDERLINE_HXX
#include <svx/borderline.hxx>
#endif
namespace svx {
namespace a11y { class AccFrameSelector; }
// ============================================================================
class FrameBorder
{
public:
explicit FrameBorder( FrameBorderType eType );
inline FrameBorderType GetType() const { return meType; }
inline bool IsEnabled() const { return mbEnabled; }
void Enable( FrameSelFlags nFlags );
inline FrameBorderState GetState() const { return meState; }
void SetState( FrameBorderState eState );
inline bool IsSelected() const { return mbSelected; }
inline void Select( bool bSelect ) { mbSelected = bSelect; }
const SvxBorderLine& GetCoreStyle() const { return maCoreStyle; }
void SetCoreStyle( const SvxBorderLine* pStyle );
inline void SetUIColor( const Color& rColor ) {maUIStyle.SetColor( rColor ); }
inline const frame::Style& GetUIStyle() const { return maUIStyle; }
inline void ClearFocusArea() { maFocusArea.Clear(); }
void AddFocusPolygon( const Polygon& rFocus );
void MergeFocusToPolyPolygon( PolyPolygon& rPPoly ) const;
inline void ClearClickArea() { maClickArea.Clear(); }
void AddClickRect( const Rectangle& rRect );
bool ContainsClickPoint( const Point& rPos ) const;
void MergeClickAreaToPolyPolygon( PolyPolygon& rPPoly ) const;
Rectangle GetClickBoundRect() const;
void SetKeyboardNeighbors(
FrameBorderType eLeft, FrameBorderType eRight,
FrameBorderType eTop, FrameBorderType eBottom );
FrameBorderType GetKeyboardNeighbor( USHORT nKeyCode ) const;
private:
const FrameBorderType meType; /// Frame border type (position in control).
FrameBorderState meState; /// Frame border state (on/off/don't care).
SvxBorderLine maCoreStyle; /// Core style from application.
frame::Style maUIStyle; /// Internal style to draw lines.
FrameBorderType meKeyLeft; /// Left neighbor for keyboard control.
FrameBorderType meKeyRight; /// Right neighbor for keyboard control.
FrameBorderType meKeyTop; /// Upper neighbor for keyboard control.
FrameBorderType meKeyBottom; /// Lower neighbor for keyboard control.
PolyPolygon maFocusArea; /// Focus drawing areas.
PolyPolygon maClickArea; /// Mouse click areas.
bool mbEnabled; /// true = Border enabled in control.
bool mbSelected; /// true = Border selected in control.
};
// ============================================================================
typedef std::vector< FrameBorder* > FrameBorderPtrVec;
struct FrameSelectorImpl : public Resource
{
typedef ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible > XAccessibleRef;
typedef std::vector< a11y::AccFrameSelector* > AccessibleImplVec;
typedef std::vector< XAccessibleRef > XAccessibleRefVec;
FrameSelector& mrFrameSel; /// The control itself.
VirtualDevice maVirDev; /// For all buffered drawing operations.
ImageList maILArrows; /// Arrows in current system colors.
Color maBackCol; /// Background color.
Color maArrowCol; /// Selection arrow color.
Color maMarkCol; /// Selection marker color.
Color maHCLineCol; /// High contrast line color.
Point maVirDevPos; /// Position of virtual device in the control.
Point maMousePos; /// Last mouse pointer position.
FrameBorder maLeft; /// All data of left frame border.
FrameBorder maRight; /// All data of right frame border.
FrameBorder maTop; /// All data of top frame border.
FrameBorder maBottom; /// All data of bottom frame border.
FrameBorder maHor; /// All data of inner horizontal frame border.
FrameBorder maVer; /// All data of inner vertical frame border.
FrameBorder maTLBR; /// All data of top-left to bottom-right frame border.
FrameBorder maBLTR; /// All data of bottom-left to top-right frame border.
SvxBorderLine maCurrStyle; /// Current style and color for new borders.
frame::Array maArray; /// Frame link array to draw an array of frame borders.
FrameSelFlags mnFlags; /// Flags for enabled frame borders.
FrameBorderPtrVec maAllBorders; /// Pointers to all frame borders.
FrameBorderPtrVec maEnabBorders; /// Pointers to enables frame borders.
Link maSelectHdl; /// Selection handler.
long mnCtrlSize; /// Size of the control (always square).
long mnArrowSize; /// Size of an arrow image.
long mnLine1; /// Middle of left/top frame borders.
long mnLine2; /// Middle of inner frame borders.
long mnLine3; /// Middle of right/bottom frame borders.
long mnFocusOffs; /// Offset from frame border middle to draw focus.
bool mbHor; /// true = Inner horizontal frame border enabled.
bool mbVer; /// true = Inner vertical frame border enabled.
bool mbTLBR; /// true = Top-left to bottom-right frame border enabled.
bool mbBLTR; /// true = Bottom-left to top-right frame border enabled.
bool mbFullRepaint; /// Used for repainting (false = only copy virtual device).
bool mbAutoSelect; /// true = Auto select a frame border, if focus reaches control.
bool mbClicked; /// true = The control has been clicked at least one time.
bool mbHCMode; /// true = High contrast mode.
a11y::AccFrameSelector* mpAccess; /// Pointer to accessibility object of the control.
XAccessibleRef mxAccess; /// Reference to accessibility object of the control.
AccessibleImplVec maChildVec; /// Pointers to accessibility objects for frame borders.
XAccessibleRefVec mxChildVec; /// References to accessibility objects for frame borders.
explicit FrameSelectorImpl( FrameSelector& rFrameSel );
~FrameSelectorImpl();
// initialization ---------------------------------------------------------
/** Initializes the control, enables/disables frame borders according to flags. */
void Initialize( FrameSelFlags nFlags );
/** Fills all color members from current style settings. */
void InitColors();
/** Creates the image list with selection arrows regarding current style settings. */
void InitArrowImageList();
/** Initializes global coordinates. */
void InitGlobalGeometry();
/** Initializes coordinates of all frame borders. */
void InitBorderGeometry();
/** Initializes click areas of all enabled frame borders. */
void InitClickAreas();
/** Draws the entire control into the internal virtual device. */
void InitVirtualDevice();
// frame border access ----------------------------------------------------
/** Returns the object representing the specified frame border. */
const FrameBorder& GetBorder( FrameBorderType eBorder ) const;
/** Returns the object representing the specified frame border (write access). */
FrameBorder& GetBorderAccess( FrameBorderType eBorder );
// drawing ----------------------------------------------------------------
/** Draws the background of the entire control (the gray areas between borders). */
void DrawBackground();
/** Draws selection arrows for the specified frame border. */
void DrawArrows( const FrameBorder& rBorder );
/** Draws arrows in current selection state for all enabled frame borders. */
void DrawAllArrows();
/** Returns the color that has to be used to draw a frame border. */
Color GetDrawLineColor( const Color& rColor ) const;
/** Draws all frame borders. */
void DrawAllFrameBorders();
/** Draws all contents of the control. */
void DrawVirtualDevice();
/** Copies contents of the virtual device to the control. */
void CopyVirDevToControl();
/** Draws tracking rectangles for all selected frame borders. */
void DrawAllTrackingRects();
/** Converts a mouse position to the virtual device position. */
Point GetDevPosFromMousePos( const Point& rMousePos ) const;
/** Invalidates the control.
@param bFullRepaint true = Full repaint; false = update selection only. */
void DoInvalidate( bool bFullRepaint );
// frame border state and style -------------------------------------------
/** Sets the state of the specified frame border. */
void SetBorderState( FrameBorder& rBorder, FrameBorderState eState );
/** Sets the core style of the specified frame border, or hides the frame border, if pStyle is 0. */
void SetBorderCoreStyle( FrameBorder& rBorder, const SvxBorderLine* pStyle );
/** Sets the color of the specified frame border. */
void SetBorderColor( FrameBorder& rBorder, const Color& rColor );
/** Changes the state of a frame border after a control event (mouse/keyboard). */
void ToggleBorderState( FrameBorder& rBorder );
// frame border selection -------------------------------------------------
/** Selects a frame border and schedules redraw. */
void SelectBorder( FrameBorder& rBorder, bool bSelect );
/** Grabs focus without auto-selection of a frame border, if no border selected. */
void SilentGrabFocus();
/** Returns true, if all selected frame borders are equal (or if nothing is selected). */
bool SelectedBordersEqual() const;
};
// ============================================================================
/** Dummy predicate for frame border iterators to use all borders in a container. */
struct FrameBorderDummy_Pred
{
inline bool operator()( const FrameBorder* ) const { return true; }
};
/** Predicate for frame border iterators to use only visible borders in a container. */
struct FrameBorderVisible_Pred
{
inline bool operator()( const FrameBorder* pBorder ) const { return pBorder->GetState() == FRAMESTATE_SHOW; }
};
/** Predicate for frame border iterators to use only selected borders in a container. */
struct FrameBorderSelected_Pred
{
inline bool operator()( const FrameBorder* pBorder ) const { return pBorder->IsSelected(); }
};
/** Template class for all types of frame border iterators. */
template< typename Cont, typename Iter, typename Pred >
class FrameBorderIterBase
{
public:
typedef Cont container_type;
typedef Iter iterator_type;
typedef Pred predicate_type;
typedef typename Cont::value_type value_type;
typedef FrameBorderIterBase< Cont, Iter, Pred > this_type;
explicit FrameBorderIterBase( container_type& rCont );
inline bool Is() const { return maIt != maEnd; }
this_type& operator++();
inline value_type operator*() const { return *maIt; }
private:
iterator_type maIt;
iterator_type maEnd;
predicate_type maPred;
};
/** Iterator for constant svx::FrameBorder containers, iterates over all borders. */
typedef FrameBorderIterBase< const FrameBorderPtrVec, FrameBorderPtrVec::const_iterator, FrameBorderDummy_Pred >
FrameBorderCIter;
/** Iterator for mutable svx::FrameBorder containers, iterates over all borders. */
typedef FrameBorderIterBase< FrameBorderPtrVec, FrameBorderPtrVec::iterator, FrameBorderDummy_Pred >
FrameBorderIter;
/** Iterator for constant svx::FrameBorder containers, iterates over visible borders. */
typedef FrameBorderIterBase< const FrameBorderPtrVec, FrameBorderPtrVec::const_iterator, FrameBorderVisible_Pred >
VisFrameBorderCIter;
/** Iterator for mutable svx::FrameBorder containers, iterates over visible borders. */
typedef FrameBorderIterBase< FrameBorderPtrVec, FrameBorderPtrVec::iterator, FrameBorderVisible_Pred >
VisFrameBorderIter;
/** Iterator for constant svx::FrameBorder containers, iterates over selected borders. */
typedef FrameBorderIterBase< const FrameBorderPtrVec, FrameBorderPtrVec::const_iterator, FrameBorderSelected_Pred >
SelFrameBorderCIter;
/** Iterator for mutable svx::FrameBorder containers, iterates over selected borders. */
typedef FrameBorderIterBase< FrameBorderPtrVec, FrameBorderPtrVec::iterator, FrameBorderSelected_Pred >
SelFrameBorderIter;
// ============================================================================
} // namespace svx
#endif
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _ROMENU_HXX
#define _ROMENU_HXX
#include <vcl/graph.hxx>
#include <tools/list.hxx>
#include <vcl/menu.hxx>
#include <svl/stritem.hxx>
class SwView;
class SfxDispatcher;
class SvxBrushItem;
class ImageMap;
class INetImage;
class SwReadOnlyPopup : public PopupMenu
{
SwView &rView;
const SvxBrushItem *pItem;
const Point &rDocPos;
Graphic aGraphic;
String sURL,
sTargetFrameName,
sDescription,
sGrfName;
std::vector<String> aThemeList;
BOOL bGrfToGalleryAsLnk;
ImageMap* pImageMap;
INetImage* pTargetURL;
void Check( USHORT nMID, USHORT nSID, SfxDispatcher &rDis );
String SaveGraphic( USHORT nId );
using PopupMenu::Execute;
public:
SwReadOnlyPopup( const Point &rDPos, SwView &rV );
~SwReadOnlyPopup();
void Execute( Window* pWin, const Point &rPPos );
void Execute( Window* pWin, USHORT nId );
};
void GetPreferedExtension( String &rExt, const Graphic &rGrf );
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove include <tools/list.hxx><commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _ROMENU_HXX
#define _ROMENU_HXX
#include <vcl/graph.hxx>
#include <vcl/menu.hxx>
#include <svl/stritem.hxx>
class SwView;
class SfxDispatcher;
class SvxBrushItem;
class ImageMap;
class INetImage;
class SwReadOnlyPopup : public PopupMenu
{
SwView &rView;
const SvxBrushItem *pItem;
const Point &rDocPos;
Graphic aGraphic;
String sURL,
sTargetFrameName,
sDescription,
sGrfName;
std::vector<String> aThemeList;
BOOL bGrfToGalleryAsLnk;
ImageMap* pImageMap;
INetImage* pTargetURL;
void Check( USHORT nMID, USHORT nSID, SfxDispatcher &rDis );
String SaveGraphic( USHORT nId );
using PopupMenu::Execute;
public:
SwReadOnlyPopup( const Point &rDPos, SwView &rV );
~SwReadOnlyPopup();
void Execute( Window* pWin, const Point &rPPos );
void Execute( Window* pWin, USHORT nId );
};
void GetPreferedExtension( String &rExt, const Graphic &rGrf );
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: beziersh.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 17:14:38 $
*
* 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 _SWBEZIERSH_HXX
#define _SWBEZIERSH_HXX
#include "basesh.hxx"
class SwBezierShell: public SwBaseShell
{
public:
SFX_DECL_INTERFACE(SW_BEZIERSHELL);
TYPEINFO();
SwBezierShell(SwView &rView);
void GetState(SfxItemSet &);
void Execute(SfxRequest &);
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.1462); FILE MERGED 2005/09/05 13:44:57 rt 1.1.1.1.1462.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: beziersh.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-09 09:00:14 $
*
* 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 _SWBEZIERSH_HXX
#define _SWBEZIERSH_HXX
#include "basesh.hxx"
class SwBezierShell: public SwBaseShell
{
public:
SFX_DECL_INTERFACE(SW_BEZIERSHELL);
TYPEINFO();
SwBezierShell(SwView &rView);
void GetState(SfxItemSet &);
void Execute(SfxRequest &);
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: bookmark.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2004-08-12 13:03:40 $
*
* 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 _BOOKMARK_HXX
#define _BOOKMARK_HXX
#ifndef _SVX_STDDLG_HXX //autogen
#include <svx/stddlg.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#include "swlbox.hxx" // SwComboBox
class SwWrtShell;
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
class BookmarkCombo : public SwComboBox
{
USHORT GetFirstSelEntryPos() const;
USHORT GetNextSelEntryPos(USHORT nPos) const;
USHORT GetSelEntryPos(USHORT nPos) const;
virtual long PreNotify(NotifyEvent& rNEvt);
public:
BookmarkCombo( Window* pWin, const ResId& rResId );
USHORT GetSelectEntryCount() const;
USHORT GetSelectEntryPos( USHORT nSelIndex = 0 ) const;
static const String aForbiddenChars;
};
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
class SwInsertBookmarkDlg: public SvxStandardDialog
{
BookmarkCombo aBookmarkBox;
FixedLine aBookmarkFl;
OKButton aOkBtn;
CancelButton aCancelBtn;
PushButton aDeleteBtn;
String sRemoveWarning;
SwWrtShell &rSh;
SfxRequest& rReq;
DECL_LINK( ModifyHdl, BookmarkCombo * );
DECL_LINK( DeleteHdl, Button * );
virtual void Apply();
public:
SwInsertBookmarkDlg( Window *pParent, SwWrtShell &rSh, SfxRequest& rReq );
~SwInsertBookmarkDlg();
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.600); FILE MERGED 2005/09/05 13:44:57 rt 1.4.600.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bookmark.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 09:01:33 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _BOOKMARK_HXX
#define _BOOKMARK_HXX
#ifndef _SVX_STDDLG_HXX //autogen
#include <svx/stddlg.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#include "swlbox.hxx" // SwComboBox
class SwWrtShell;
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
class BookmarkCombo : public SwComboBox
{
USHORT GetFirstSelEntryPos() const;
USHORT GetNextSelEntryPos(USHORT nPos) const;
USHORT GetSelEntryPos(USHORT nPos) const;
virtual long PreNotify(NotifyEvent& rNEvt);
public:
BookmarkCombo( Window* pWin, const ResId& rResId );
USHORT GetSelectEntryCount() const;
USHORT GetSelectEntryPos( USHORT nSelIndex = 0 ) const;
static const String aForbiddenChars;
};
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
class SwInsertBookmarkDlg: public SvxStandardDialog
{
BookmarkCombo aBookmarkBox;
FixedLine aBookmarkFl;
OKButton aOkBtn;
CancelButton aCancelBtn;
PushButton aDeleteBtn;
String sRemoveWarning;
SwWrtShell &rSh;
SfxRequest& rReq;
DECL_LINK( ModifyHdl, BookmarkCombo * );
DECL_LINK( DeleteHdl, Button * );
virtual void Apply();
public:
SwInsertBookmarkDlg( Window *pParent, SwWrtShell &rSh, SfxRequest& rReq );
~SwInsertBookmarkDlg();
};
#endif
<|endoftext|> |
<commit_before>//=============================================================================
//File Name: RollingAverage.cpp
//Description: Creates queue of values and returns the average of the latest
// values added to it
//Author: FRC Team 3512, Spartatroniks
//=============================================================================
#include "RollingAverage.hpp"
RollingAverage::RollingAverage( unsigned int size ) :
m_size( 0 ) ,
m_maxSize( size ) {
m_values = new std::atomic<float>[m_maxSize];
pthread_mutex_init( &m_dataMutex , NULL );
}
RollingAverage::~RollingAverage() {
delete[] m_values;
pthread_mutex_destroy( &m_dataMutex );
}
void RollingAverage::addValue( float value ) {
m_protectArray.startWriting();
/* Advance to next slot. If the next slot is past the end of the array, set
* index to the beginning
*/
m_index = (m_index + 1) % m_maxSize;
m_protectArray.stopWriting();
/* Other assignments are atomic and don't negatively affect getAverage() */
// Set oldest value to new value
m_values[m_index] = value;
if ( m_size < m_maxSize ) {
m_size++;
}
}
void RollingAverage::setSize( unsigned int newSize ) {
std::atomic<float>* tempVals = new std::atomic<float>[newSize];
unsigned int oldPos = m_index;
unsigned int count = 0;
while ( count < newSize ) {
if ( oldPos < 0 ) {
oldPos = m_size - 1;
}
tempVals[count] = m_values[oldPos].load();
oldPos--;
count++;
}
// Every operation before here was only reading
m_protectArray.startWriting();
m_maxSize = newSize;
m_size = count;
m_index = 0;
// Swap buffers, then delete the old one
m_values.exchange( tempVals );
delete[] tempVals;
m_protectArray.stopWriting();
}
float RollingAverage::getAverage() {
float sum = 0;
m_protectArray.startReading();
// Store values from atomic variables
unsigned int index = m_index;
unsigned int size = m_size;
unsigned int maxSize = m_maxSize;
for ( unsigned int count = 0 ; count < size ; count++ ) {
sum += m_values[(index + count) % maxSize];
}
m_protectArray.stopReading();
// Prevent divide by zero
if ( size != 0 ) {
return sum / size;
}
else {
return 0.f;
}
}
<commit_msg>Fixed compile error by renaming uses of RWProtect::startWriting() to RWProtect::startWrite(), among other member function renames<commit_after>//=============================================================================
//File Name: RollingAverage.cpp
//Description: Creates queue of values and returns the average of the latest
// values added to it
//Author: FRC Team 3512, Spartatroniks
//=============================================================================
#include "RollingAverage.hpp"
RollingAverage::RollingAverage( unsigned int size ) :
m_size( 0 ) ,
m_maxSize( size ) {
m_values = new std::atomic<float>[m_maxSize];
pthread_mutex_init( &m_dataMutex , NULL );
}
RollingAverage::~RollingAverage() {
delete[] m_values;
pthread_mutex_destroy( &m_dataMutex );
}
void RollingAverage::addValue( float value ) {
m_protectArray.startWrite();
/* Advance to next slot. If the next slot is past the end of the array, set
* index to the beginning
*/
m_index = (m_index + 1) % m_maxSize;
m_protectArray.stopWrite();
/* Other assignments are atomic and don't negatively affect getAverage() */
// Set oldest value to new value
m_values[m_index] = value;
if ( m_size < m_maxSize ) {
m_size++;
}
}
void RollingAverage::setSize( unsigned int newSize ) {
std::atomic<float>* tempVals = new std::atomic<float>[newSize];
unsigned int oldPos = m_index;
unsigned int count = 0;
while ( count < newSize ) {
if ( oldPos < 0 ) {
oldPos = m_size - 1;
}
tempVals[count] = m_values[oldPos].load();
oldPos--;
count++;
}
// Every operation before here was only reading
m_protectArray.startWrite();
m_maxSize = newSize;
m_size = count;
m_index = 0;
// Swap buffers, then delete the old one
m_values.exchange( tempVals );
delete[] tempVals;
m_protectArray.stopWrite();
}
float RollingAverage::getAverage() {
float sum = 0;
m_protectArray.startRead();
// Store values from atomic variables
unsigned int index = m_index;
unsigned int size = m_size;
unsigned int maxSize = m_maxSize;
for ( unsigned int count = 0 ; count < size ; count++ ) {
sum += m_values[(index + count) % maxSize];
}
m_protectArray.stopRead();
// Prevent divide by zero
if ( size != 0 ) {
return sum / size;
}
else {
return 0.f;
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.