<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkImageStatisticsCalculationThread.h"

//QT headers
#include <QMessageBox>
#include <QApplication>
#include <mitkImageMaskGenerator.h>
#include <mitkPlanarFigureMaskGenerator.h>
#include <mitkIgnorePixelMaskGenerator.h>

QmitkImageStatisticsCalculationThread::QmitkImageStatisticsCalculationThread():QThread(),
  m_StatisticsImage(nullptr), m_BinaryMask(nullptr), m_PlanarFigureMask(nullptr), m_TimeStep(0),
  m_IgnoreZeros(false), m_CalculationSuccessful(false), m_StatisticChanged(false), m_HistogramBinSize(10.0), m_UseDefaultNBins(true), m_nBinsForHistogramStatistics(100), m_prioritizeNBinsOverBinSize(true)
{
}

QmitkImageStatisticsCalculationThread::~QmitkImageStatisticsCalculationThread()
{
}

void QmitkImageStatisticsCalculationThread::Initialize( mitk::Image::Pointer image, mitk::Image::Pointer binaryImage, mitk::PlanarFigure::Pointer planarFig )
{
  // reset old values
  if( this->m_StatisticsImage.IsNotNull() )
    this->m_StatisticsImage = nullptr;

  if( this->m_BinaryMask.IsNotNull() )
    this->m_BinaryMask = nullptr;

  if( this->m_PlanarFigureMask.IsNotNull())
    this->m_PlanarFigureMask = nullptr;

  // set new values if passed in
  if(image.IsNotNull())
    this->m_StatisticsImage = image->Clone();
  if(binaryImage.IsNotNull())
    this->m_BinaryMask = binaryImage->Clone();
  if(planarFig.IsNotNull())
    this->m_PlanarFigureMask = planarFig->Clone();
}

void QmitkImageStatisticsCalculationThread::SetUseDefaultNBins(bool useDefault)
{
    m_UseDefaultNBins = useDefault;
}

void QmitkImageStatisticsCalculationThread::SetTimeStep( int times )
{
  this->m_TimeStep = times;
}

int QmitkImageStatisticsCalculationThread::GetTimeStep()
{
  return this->m_TimeStep;
}

std::vector<mitk::ImageStatisticsCalculator::StatisticsContainer::Pointer> QmitkImageStatisticsCalculationThread::GetStatisticsData()
{
  return this->m_StatisticsVector;
}

mitk::Image::Pointer QmitkImageStatisticsCalculationThread::GetStatisticsImage()
{
  return this->m_StatisticsImage;
}

void QmitkImageStatisticsCalculationThread::SetIgnoreZeroValueVoxel(bool _arg)
{
  this->m_IgnoreZeros = _arg;
}

bool QmitkImageStatisticsCalculationThread::GetIgnoreZeroValueVoxel()
{
  return this->m_IgnoreZeros;
}

void QmitkImageStatisticsCalculationThread::SetHistogramBinSize(double size)
{
  this->m_HistogramBinSize = size;
  this->m_prioritizeNBinsOverBinSize = false;
}

double QmitkImageStatisticsCalculationThread::GetHistogramBinSize() const
{
  return this->m_HistogramBinSize;
}

void QmitkImageStatisticsCalculationThread::SetHistogramNBins(double size)
{
  this->m_nBinsForHistogramStatistics = size;
  this->m_prioritizeNBinsOverBinSize = true;
}

double QmitkImageStatisticsCalculationThread::GetHistogramNBins() const
{
  return this->m_nBinsForHistogramStatistics;
}

std::string QmitkImageStatisticsCalculationThread::GetLastErrorMessage()
{
  return m_message;
}

QmitkImageStatisticsCalculationThread::HistogramType::Pointer
QmitkImageStatisticsCalculationThread::GetTimeStepHistogram(unsigned int t)
{
  if (t >= this->m_HistogramVector.size())
    return nullptr;

  return this->m_HistogramVector[t];
}

bool QmitkImageStatisticsCalculationThread::GetStatisticsChangedFlag()
{
  return m_StatisticChanged;
}

bool QmitkImageStatisticsCalculationThread::GetStatisticsUpdateSuccessFlag()
{
  return m_CalculationSuccessful;
}

void QmitkImageStatisticsCalculationThread::run()
{
  bool statisticCalculationSuccessful = true;
  mitk::ImageStatisticsCalculator::Pointer calculator = mitk::ImageStatisticsCalculator::New();

  if(this->m_StatisticsImage.IsNotNull())
  {
    calculator->SetInputImage(m_StatisticsImage);
  }
  else
  {
    statisticCalculationSuccessful = false;
  }

  // Bug 13416 : The ImageStatistics::SetImageMask() method can throw exceptions, i.e. when the dimensionality
  // of the masked and input image differ, we need to catch them and mark the calculation as failed
  // the same holds for the ::SetPlanarFigure()
  try
  {
    if(this->m_BinaryMask.IsNotNull())
    {
      mitk::ImageMaskGenerator::Pointer imgMask = mitk::ImageMaskGenerator::New();
      imgMask->SetImageMask(m_BinaryMask);
      calculator->SetMask(imgMask.GetPointer());
    }
    if(this->m_PlanarFigureMask.IsNotNull())
    {
      mitk::PlanarFigureMaskGenerator::Pointer pfMaskGen = mitk::PlanarFigureMaskGenerator::New();
      pfMaskGen->SetInputImage(m_StatisticsImage);
      pfMaskGen->SetPlanarFigure(m_PlanarFigureMask);
      calculator->SetMask(pfMaskGen.GetPointer());
    }
  }
  catch( const itk::ExceptionObject& e)
  {
    MITK_ERROR << "ITK Exception:" << e.what();
    statisticCalculationSuccessful = false;
  }
  catch( const mitk::Exception& e )
  {
    MITK_ERROR<< "MITK Exception: " << e.what();
    statisticCalculationSuccessful = false;
  }
  catch ( const std::runtime_error &e )
  {
    MITK_ERROR<< "Runtime Exception: " << e.what();
    statisticCalculationSuccessful = false;
  }
  catch ( const std::exception &e )
  {
    //m_message = "Failure: " + std::string(e.what());
    MITK_ERROR<< "Standard Exception: " << e.what();
    statisticCalculationSuccessful = false;
  }

  bool statisticChanged = false;

  if (this->m_IgnoreZeros)
  {
      mitk::IgnorePixelMaskGenerator::Pointer ignorePixelValueMaskGen = mitk::IgnorePixelMaskGenerator::New();
      ignorePixelValueMaskGen->SetIgnoredPixelValue(0);
      ignorePixelValueMaskGen->SetInputImage(m_StatisticsImage);
      calculator->SetSecondaryMask(ignorePixelValueMaskGen.GetPointer());
  }
  else
  {
      calculator->SetSecondaryMask(nullptr);
  }

  if (m_UseDefaultNBins)
  {
      calculator->SetNBinsForHistogramStatistics(100);
  }
  else
  {
      if (!m_prioritizeNBinsOverBinSize)
      {
          calculator->SetBinSizeForHistogramStatistics(m_HistogramBinSize);
      }
      else
      {
          calculator->SetNBinsForHistogramStatistics(100);
      }
  }

  //calculator->SetHistogramBinSize( m_HistogramBinSize );
  //calculator->SetUseDefaultBinSize( m_UseDefaultBinSize );

  for (unsigned int i = 0; i < m_StatisticsImage->GetTimeSteps(); i++)
  {
    try
    {
      calculator->GetStatistics(i);
    }
    catch ( mitk::Exception& e)
    {
      //m_message = e.GetDescription();
      MITK_ERROR<< "MITK Exception: " << e.what();
      statisticCalculationSuccessful = false;
    }
    catch ( const std::runtime_error &e )
    {
      //m_message = "Failure: " + std::string(e.what());
      MITK_ERROR<< "Runtime Exception: " << e.what();
      statisticCalculationSuccessful = false;
    }
    catch ( const std::exception &e )
    {
      //m_message = "Failure: " + std::string(e.what());
      MITK_ERROR<< "Standard Exception: " << e.what();
      statisticCalculationSuccessful = false;
    }
  }

  this->m_StatisticChanged = statisticChanged;
  this->m_CalculationSuccessful = statisticCalculationSuccessful;

  if(statisticCalculationSuccessful)
  {
    this->m_StatisticsVector.clear();
    this->m_HistogramVector.clear();

    for (unsigned int i = 0; i < m_StatisticsImage->GetTimeSteps(); i++)
    {
      this->m_StatisticsVector.push_back(calculator->GetStatistics(i));
      this->m_HistogramVector.push_back((HistogramType*)this->m_StatisticsVector[i]->GetHistogram());
    }
  }
}
<commit_msg>Fix warnings in measurementtoolbox plugin<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkImageStatisticsCalculationThread.h"

//QT headers
#include <QMessageBox>
#include <QApplication>
#include <mitkImageMaskGenerator.h>
#include <mitkPlanarFigureMaskGenerator.h>
#include <mitkIgnorePixelMaskGenerator.h>

QmitkImageStatisticsCalculationThread::QmitkImageStatisticsCalculationThread():QThread(),
  m_StatisticsImage(nullptr), m_BinaryMask(nullptr), m_PlanarFigureMask(nullptr), m_TimeStep(0),
  m_IgnoreZeros(false), m_CalculationSuccessful(false), m_StatisticChanged(false), m_HistogramBinSize(10.0), m_UseDefaultNBins(true), m_nBinsForHistogramStatistics(100), m_prioritizeNBinsOverBinSize(true)
{
}

QmitkImageStatisticsCalculationThread::~QmitkImageStatisticsCalculationThread()
{
}

void QmitkImageStatisticsCalculationThread::Initialize( mitk::Image::Pointer image, mitk::Image::Pointer binaryImage, mitk::PlanarFigure::Pointer planarFig )
{
  // reset old values
  if( this->m_StatisticsImage.IsNotNull() )
    this->m_StatisticsImage = nullptr;

  if( this->m_BinaryMask.IsNotNull() )
    this->m_BinaryMask = nullptr;

  if( this->m_PlanarFigureMask.IsNotNull())
    this->m_PlanarFigureMask = nullptr;

  // set new values if passed in
  if(image.IsNotNull())
    this->m_StatisticsImage = image->Clone();
  if(binaryImage.IsNotNull())
    this->m_BinaryMask = binaryImage->Clone();
  if(planarFig.IsNotNull())
    this->m_PlanarFigureMask = planarFig->Clone();
}

void QmitkImageStatisticsCalculationThread::SetUseDefaultNBins(bool useDefault)
{
    m_UseDefaultNBins = useDefault;
}

void QmitkImageStatisticsCalculationThread::SetTimeStep( int times )
{
  this->m_TimeStep = times;
}

int QmitkImageStatisticsCalculationThread::GetTimeStep()
{
  return this->m_TimeStep;
}

std::vector<mitk::ImageStatisticsCalculator::StatisticsContainer::Pointer> QmitkImageStatisticsCalculationThread::GetStatisticsData()
{
  return this->m_StatisticsVector;
}

mitk::Image::Pointer QmitkImageStatisticsCalculationThread::GetStatisticsImage()
{
  return this->m_StatisticsImage;
}

void QmitkImageStatisticsCalculationThread::SetIgnoreZeroValueVoxel(bool _arg)
{
  this->m_IgnoreZeros = _arg;
}

bool QmitkImageStatisticsCalculationThread::GetIgnoreZeroValueVoxel()
{
  return this->m_IgnoreZeros;
}

void QmitkImageStatisticsCalculationThread::SetHistogramBinSize(double size)
{
  this->m_HistogramBinSize = size;
  this->m_prioritizeNBinsOverBinSize = false;
}

double QmitkImageStatisticsCalculationThread::GetHistogramBinSize() const
{
  return this->m_HistogramBinSize;
}

void QmitkImageStatisticsCalculationThread::SetHistogramNBins(double size)
{
  this->m_nBinsForHistogramStatistics = size;
  this->m_prioritizeNBinsOverBinSize = true;
}

double QmitkImageStatisticsCalculationThread::GetHistogramNBins() const
{
  return this->m_nBinsForHistogramStatistics;
}

std::string QmitkImageStatisticsCalculationThread::GetLastErrorMessage()
{
  return m_message;
}

QmitkImageStatisticsCalculationThread::HistogramType::Pointer
QmitkImageStatisticsCalculationThread::GetTimeStepHistogram(unsigned int t)
{
  if (t >= this->m_HistogramVector.size())
    return nullptr;

  return this->m_HistogramVector[t];
}

bool QmitkImageStatisticsCalculationThread::GetStatisticsChangedFlag()
{
  return m_StatisticChanged;
}

bool QmitkImageStatisticsCalculationThread::GetStatisticsUpdateSuccessFlag()
{
  return m_CalculationSuccessful;
}

void QmitkImageStatisticsCalculationThread::run()
{
  bool statisticCalculationSuccessful = true;
  mitk::ImageStatisticsCalculator::Pointer calculator = mitk::ImageStatisticsCalculator::New();

  if(this->m_StatisticsImage.IsNotNull())
  {
    calculator->SetInputImage(m_StatisticsImage);
  }
  else
  {
    statisticCalculationSuccessful = false;
  }

  // Bug 13416 : The ImageStatistics::SetImageMask() method can throw exceptions, i.e. when the dimensionality
  // of the masked and input image differ, we need to catch them and mark the calculation as failed
  // the same holds for the ::SetPlanarFigure()
  try
  {
    if(this->m_BinaryMask.IsNotNull())
    {
      mitk::ImageMaskGenerator::Pointer imgMask = mitk::ImageMaskGenerator::New();
      imgMask->SetImageMask(m_BinaryMask);
      calculator->SetMask(imgMask.GetPointer());
    }
    if(this->m_PlanarFigureMask.IsNotNull())
    {
      mitk::PlanarFigureMaskGenerator::Pointer pfMaskGen = mitk::PlanarFigureMaskGenerator::New();
      pfMaskGen->SetInputImage(m_StatisticsImage);
      pfMaskGen->SetPlanarFigure(m_PlanarFigureMask);
      calculator->SetMask(pfMaskGen.GetPointer());
    }
  }
  catch (const mitk::Exception& e)
  {
    MITK_ERROR << "MITK Exception: " << e.what();
    statisticCalculationSuccessful = false;
  }
  catch( const itk::ExceptionObject& e)
  {
    MITK_ERROR << "ITK Exception:" << e.what();
    statisticCalculationSuccessful = false;
  }
  catch ( const std::runtime_error &e )
  {
    MITK_ERROR<< "Runtime Exception: " << e.what();
    statisticCalculationSuccessful = false;
  }
  catch ( const std::exception &e )
  {
    MITK_ERROR<< "Standard Exception: " << e.what();
    statisticCalculationSuccessful = false;
  }

  bool statisticChanged = false;

  if (this->m_IgnoreZeros)
  {
      mitk::IgnorePixelMaskGenerator::Pointer ignorePixelValueMaskGen = mitk::IgnorePixelMaskGenerator::New();
      ignorePixelValueMaskGen->SetIgnoredPixelValue(0);
      ignorePixelValueMaskGen->SetInputImage(m_StatisticsImage);
      calculator->SetSecondaryMask(ignorePixelValueMaskGen.GetPointer());
  }
  else
  {
      calculator->SetSecondaryMask(nullptr);
  }

  if (m_UseDefaultNBins)
  {
      calculator->SetNBinsForHistogramStatistics(100);
  }
  else
  {
      if (!m_prioritizeNBinsOverBinSize)
      {
          calculator->SetBinSizeForHistogramStatistics(m_HistogramBinSize);
      }
      else
      {
          calculator->SetNBinsForHistogramStatistics(100);
      }
  }

  //calculator->SetHistogramBinSize( m_HistogramBinSize );
  //calculator->SetUseDefaultBinSize( m_UseDefaultBinSize );

  for (unsigned int i = 0; i < m_StatisticsImage->GetTimeSteps(); i++)
  {
    try
    {
      calculator->GetStatistics(i);
    }
    catch ( mitk::Exception& e)
    {
      //m_message = e.GetDescription();
      MITK_ERROR<< "MITK Exception: " << e.what();
      statisticCalculationSuccessful = false;
    }
    catch ( const std::runtime_error &e )
    {
      //m_message = "Failure: " + std::string(e.what());
      MITK_ERROR<< "Runtime Exception: " << e.what();
      statisticCalculationSuccessful = false;
    }
    catch ( const std::exception &e )
    {
      //m_message = "Failure: " + std::string(e.what());
      MITK_ERROR<< "Standard Exception: " << e.what();
      statisticCalculationSuccessful = false;
    }
  }

  this->m_StatisticChanged = statisticChanged;
  this->m_CalculationSuccessful = statisticCalculationSuccessful;

  if(statisticCalculationSuccessful)
  {
    this->m_StatisticsVector.clear();
    this->m_HistogramVector.clear();

    for (unsigned int i = 0; i < m_StatisticsImage->GetTimeSteps(); i++)
    {
      this->m_StatisticsVector.push_back(calculator->GetStatistics(i));
      this->m_HistogramVector.push_back((HistogramType*)this->m_StatisticsVector[i]->GetHistogram());
    }
  }
}
<|endoftext|>


<commit_before>/*=========================================================================

  Programme :   OTB (ORFEO ToolBox)
  Auteurs   :   CS - C.Ruffel
  Language  :   C++
  Date      :   14 mars 2006
  Version   :
  Role      :   Test la classe du filtre de detection de lignes
  $Id$

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#define MAIN

#include "itkExceptionObject.h"
#include "itkImage.h"
#include "itkImageFileWriter.h"
#include <iostream>

#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbTupinEdgeDetector.h"

#include "itkLinearInterpolateImageFunction.h"

int otbTupinEdgeDetector( int argc, char* argv[] )
{
  try
    {
        const char * inputFilename  = argv[1];
        const char * outputFilename = argv[2];

        unsigned int  WidthLine((unsigned int)::atoi(argv[3]));
        unsigned int  LengthLine((unsigned int)::atoi(argv[4]));

        typedef unsigned char                                   InputPixelType;
        typedef double		   	                        OutputPixelType;
        const   unsigned int        	                        Dimension = 2;

        typedef itk::Image< InputPixelType,  Dimension >        InputImageType;
        typedef itk::Image< OutputPixelType, Dimension >        OutputImageType;

        typedef otb::ImageFileReader< InputImageType  >         ReaderType;
        typedef otb::ImageFileWriter< OutputImageType >         WriterType;

        typedef itk::LinearInterpolateImageFunction< InputImageType, double >	InterpolatorType;
        typedef otb::TupinEdgeDetector< InputImageType, OutputImageType, InterpolatorType >   FilterType;

        FilterType::Pointer filtreTupin = FilterType::New();

	filtreTupin->SetWidthLine( WidthLine );
	filtreTupin->SetLengthLine( LengthLine );

        ReaderType::Pointer reader = ReaderType::New();
        WriterType::Pointer writer = WriterType::New();

        reader->SetFileName( inputFilename  );
        writer->SetFileName( outputFilename );

        filtreTupin->SetInput( reader->GetOutput() );
        writer->SetInput( filtreTupin->GetOutput() );

        writer->Update();

    }
  catch( itk::ExceptionObject & err )
    {
    std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
    std::cout << err << std::endl;
    return EXIT_FAILURE;
    }
  catch( ... )
    {
    std::cout << "Exception levee inconnue !" << std::endl;
    return EXIT_FAILURE;
    }
  // Software Guide : EndCodeSnippet

//#endif
  return EXIT_SUCCESS;
}

<commit_msg>nomsg<commit_after>/*=========================================================================

  Programme :   OTB (ORFEO ToolBox)
  Auteurs   :   CS - C.Ruffel
  Language  :   C++
  Date      :   14 mars 2006
  Version   :
  Role      :   Test du filtre de detection de lignes
  $Id$

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#define MAIN

#include "itkExceptionObject.h"
#include "itkImage.h"
#include "itkImageFileWriter.h"
#include <iostream>

#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbTupinEdgeDetector.h"

#include "itkLinearInterpolateImageFunction.h"

int otbTupinEdgeDetector( int argc, char* argv[] )
{
  try
    {
        const char * inputFilename  = argv[1];
        const char * outputFilename = argv[2];

	// Width of the linear feature = 2*WidthLine+1
        unsigned int  WidthLine((unsigned int)::atoi(argv[3]));
        // Length of the linear feature = 2*LengthLine+1
        unsigned int  LengthLine((unsigned int)::atoi(argv[4]));

        typedef unsigned char                                   InputPixelType;
        typedef double		   	                        OutputPixelType;
        const   unsigned int        	                        Dimension = 2;

        typedef itk::Image< InputPixelType,  Dimension >        InputImageType;
        typedef itk::Image< OutputPixelType, Dimension >        OutputImageType;

        typedef otb::ImageFileReader< InputImageType  >         ReaderType;
        typedef otb::ImageFileWriter< OutputImageType >         WriterType;

        typedef itk::LinearInterpolateImageFunction< InputImageType, double >	InterpolatorType;
        typedef otb::TupinEdgeDetector< InputImageType, OutputImageType, InterpolatorType >   FilterType;

        FilterType::Pointer filtreTupin = FilterType::New();

	filtreTupin->SetWidthLine( WidthLine );
	filtreTupin->SetLengthLine( LengthLine );

        ReaderType::Pointer reader = ReaderType::New();
        WriterType::Pointer writer = WriterType::New();

        reader->SetFileName( inputFilename  );
        writer->SetFileName( outputFilename );

        filtreTupin->SetInput( reader->GetOutput() );
        writer->SetInput( filtreTupin->GetOutput() );

        writer->Update();

    }
  catch( itk::ExceptionObject & err )
    {
    std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
    std::cout << err << std::endl;
    return EXIT_FAILURE;
    }
  catch( ... )
    {
    std::cout << "Exception levee inconnue !" << std::endl;
    return EXIT_FAILURE;
    }
  // Software Guide : EndCodeSnippet

//#endif
  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>//
//  CodeGeneratorCPP.cpp
//  Protocol
//
//  Created by Wahid Tanner on 10/17/14.
//

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem/fstream.hpp>

#include "CodeGeneratorCPP.h"

using namespace std;
using namespace boost;
using namespace MuddledManaged;

const string Protocol::CodeGeneratorCPP::mHeaderFileExtension = ".protocol.h";
const string Protocol::CodeGeneratorCPP::mSourceFileExtension = ".protocol.cpp";
const string Protocol::CodeGeneratorCPP::mHeaderFileProlog =
"// This file was generated from the Protocol compiler.\n"
"// You should not edit this file directly.\n";
const string Protocol::CodeGeneratorCPP::mSourceFileProlog =
"// This file was generated from the Protocol compiler.\n"
"// You should not edit this file directly.\n";

Protocol::CodeGeneratorCPP::CodeGeneratorCPP ()
{ }

void Protocol::CodeGeneratorCPP::generateCode (const string & outputFolder, const ProtoModel & protoModel, const std::string & projectName) const
{
    filesystem::path outputPath(outputFolder);
    filesystem::path modelPath(protoModel.name());
    filesystem::path headerPath(outputPath / filesystem::change_extension(modelPath, mHeaderFileExtension));
    filesystem::path sourcePath(outputPath / filesystem::change_extension(modelPath, mSourceFileExtension));

    filesystem::create_directory(outputFolder);
    filesystem::ofstream headerFile(headerPath, ios::out | ios::trunc);
    CodeWriter headerFileWriter(headerFile);
    filesystem::ofstream sourceFile(sourcePath, ios::out | ios::trunc);
    CodeWriter sourceFileWriter(sourceFile);

    headerFileWriter.writeLine(mHeaderFileProlog);
    headerFileWriter.writeHeaderIncludeBlockOpening(headerIncludeBlockText(protoModel, projectName));

    writeStandardIncludFileNamesToHeader(headerFileWriter);
    writeIncludedProtoFileNamesToHeader(headerFileWriter, protoModel);

    writeProtoEnumsToHeader(headerFileWriter, protoModel);

    writeProtoMessagesToHeader(headerFileWriter, protoModel);

    headerFileWriter.writeHeaderIncludeBlockClosing();

    sourceFileWriter.writeLine(mSourceFileProlog);
}

string Protocol::CodeGeneratorCPP::headerIncludeBlockText (const ProtoModel & protoModel, const std::string & projectName) const
{
    string text = projectName;
    if (!text.empty())
    {
        text += "_";
    }

    filesystem::path modelPath(protoModel.namePascal());
    text += filesystem::basename(modelPath.filename());
    text += "_h";

    return text;
}

void Protocol::CodeGeneratorCPP::writeStandardIncludFileNamesToHeader (CodeWriter & headerFileWriter) const
{
    headerFileWriter.writeIncludeLibrary("cstdint");
    headerFileWriter.writeIncludeLibrary("string");
    headerFileWriter.writeBlankLine();
}

void Protocol::CodeGeneratorCPP::writeIncludedProtoFileNamesToHeader (CodeWriter & headerFileWriter, const ProtoModel & protoModel) const
{
    auto importedProtoBegin = protoModel.importedProtoNames()->cbegin();
    auto importedProtoEnd = protoModel.importedProtoNames()->cend();
    bool importsFound = false;
    while (importedProtoBegin != importedProtoEnd)
    {
        importsFound = true;
        filesystem::path protoPath(*importedProtoBegin);
        filesystem::path headerPath(filesystem::change_extension(protoPath, mHeaderFileExtension));
        headerFileWriter.writeIncludeProject(headerPath.string());
        ++importedProtoBegin;
    }
    if (importsFound)
    {
        headerFileWriter.writeBlankLine();
    }
}

void Protocol::CodeGeneratorCPP::writeProtoEnumsToHeader (CodeWriter & headerFileWriter, const ProtoModel & protoModel) const
{
    auto protoEnumBegin = protoModel.enums()->cbegin();
    auto protoEnumEnd = protoModel.enums()->cend();
    while (protoEnumBegin != protoEnumEnd)
    {
        auto enumModel = *protoEnumBegin;
        headerFileWriter.writeEnumOpening(enumModel->namePascal());

        auto enumValueBegin = enumModel->enumValues()->cbegin();
        auto enumValueEnd = enumModel->enumValues()->cend();
        bool firstEnumValue = true;
        while (enumValueBegin != enumValueEnd)
        {
            auto enumValueModel = *enumValueBegin;
            if (firstEnumValue)
            {
                headerFileWriter.writeEnumValueFirst(enumValueModel->name(), enumValueModel->value());
                firstEnumValue = false;
            }
            else
            {
                headerFileWriter.writeEnumValueSubsequent(enumValueModel->name(), enumValueModel->value());
            }
            ++enumValueBegin;
        }

        headerFileWriter.writeEnumClosing();
        ++protoEnumBegin;
    }
}

void Protocol::CodeGeneratorCPP::writeProtoMessagesToHeader (CodeWriter & headerFileWriter, const ProtoModel & protoModel) const
{
    auto protoMessageBegin = protoModel.messages()->cbegin();
    auto protoMessageEnd = protoModel.messages()->cend();
    while (protoMessageBegin != protoMessageEnd)
    {
        auto messageModel = *protoMessageBegin;

        writeMessageToHeader(headerFileWriter, protoModel, *messageModel, messageModel->namePascal());

        ++protoMessageBegin;
    }
}

void Protocol::CodeGeneratorCPP::writeMessageToHeader (CodeWriter & headerFileWriter,
                                                       const ProtoModel & protoModel,
                                                       const MessageModel & messageModel,
                                                       const std::string & className) const
{
    headerFileWriter.writeClassOpening(className);

    headerFileWriter.writeClassPublic();

    // Generate all the typedefs for nested classes first, then generate each class.
    bool subMessageFound = false;
    auto messageMessageBegin = messageModel.messages()->cbegin();
    auto messageMessageEnd = messageModel.messages()->cend();
    while (messageMessageBegin != messageMessageEnd)
    {
        subMessageFound = true;
        auto messageSubModel = *messageMessageBegin;

        string subClassName = className + messageSubModel->namePascal();
        headerFileWriter.writeTypedef(subClassName, messageSubModel->namePascal());

        ++messageMessageBegin;
    }
    if (subMessageFound)
    {
        headerFileWriter.writeBlankLine();
    }
    messageMessageBegin = messageModel.messages()->cbegin();
    messageMessageEnd = messageModel.messages()->cend();
    while (messageMessageBegin != messageMessageEnd)
    {
        auto messageSubModel = *messageMessageBegin;

        string subClassName = className + messageSubModel->namePascal();
        writeMessageToHeader(headerFileWriter, protoModel, *messageSubModel, subClassName);

        ++messageMessageBegin;
    }

    string methodName = className;
    headerFileWriter.writeClassMethodDeclaration(methodName);

    string methodReturn = "";
    string methodParameters = "const ";
    methodParameters += className + " & src";
    headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters);

    methodName = "~";
    methodName += className;
    headerFileWriter.writeClassMethodDeclaration(methodName);

    methodName = "operator =";
    methodReturn = className + " &";
    methodParameters = "const ";
    methodParameters += className + " & rhs";
    headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters);

    methodName = "swap";
    methodReturn = "void";
    methodParameters = className + " * other";
    headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters);

    auto messageFieldBegin = messageModel.fields()->cbegin();
    auto messageFieldEnd = messageModel.fields()->cend();
    while (messageFieldBegin != messageFieldEnd)
    {
        auto messageFieldModel = *messageFieldBegin;

        methodName = messageFieldModel->name();
        string fieldType = fullTypeName(protoModel, messageFieldModel->fieldType());
        methodReturn = fieldType;
        methodParameters = "";
        headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true);

        methodName = "set";
        methodName += messageFieldModel->namePascal();
        methodReturn = "void";
        methodParameters = fieldType + " value";
        headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters);

        methodName = "has";
        methodName += messageFieldModel->namePascal();
        methodReturn = "bool";
        methodParameters = "";
        headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true);

        methodName = "clear";
        methodName += messageFieldModel->namePascal();
        methodReturn = "void";
        methodParameters = "";
        headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters);

        ++messageFieldBegin;
    }

    headerFileWriter.writeClassPrivate();

    messageFieldBegin = messageModel.fields()->cbegin();
    messageFieldEnd = messageModel.fields()->cend();
    while (messageFieldBegin != messageFieldEnd)
    {
        auto messageFieldModel = *messageFieldBegin;

        string constantName = "m";
        constantName += messageFieldModel->namePascal() + "Index";
        string fieldType = "const unsigned int";
        headerFileWriter.writeClassFieldDeclaration(constantName, fieldType, to_string(messageFieldModel->index()), true);

        ++messageFieldBegin;
    }

    headerFileWriter.writeClassClosing();
}

string Protocol::CodeGeneratorCPP::fullTypeName (const ProtoModel & protoModel, const std::string & protoTypeName) const
{
    if (protoTypeName == "bool")
    {
        return "bool";
    }
    if (protoTypeName == "string")
    {
        return "std::string";
    }
    if (protoTypeName == "double")
    {
        return "double";
    }
    if (protoTypeName == "float")
    {
        return "float";
    }
    if (protoTypeName == "int32")
    {
        return "int32_t";
    }
    if (protoTypeName == "int64")
    {
        return "int64_t";
    }
    if (protoTypeName == "uint32")
    {
        return "uint32_t";
    }
    if (protoTypeName == "uint64")
    {
        return "uint64_t";
    }
    if (protoTypeName == "sint32")
    {
        return "int32_t";
    }
    if (protoTypeName == "sint64")
    {
        return "int64_t";
    }
    if (protoTypeName == "fixed32")
    {
        return "int32_t";
    }
    if (protoTypeName == "fixed64")
    {
        return "int64_t";
    }
    if (protoTypeName == "sfixed32")
    {
        return "int32_t";
    }
    if (protoTypeName == "sfixed64")
    {
        return "int64_t";
    }
    if (protoTypeName == "bytes")
    {
        return "std::string";
    }
    return "";
}
<commit_msg>Generated field methods now differ based on field category.<commit_after>//
//  CodeGeneratorCPP.cpp
//  Protocol
//
//  Created by Wahid Tanner on 10/17/14.
//

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem/fstream.hpp>

#include "CodeGeneratorCPP.h"

using namespace std;
using namespace boost;
using namespace MuddledManaged;

const string Protocol::CodeGeneratorCPP::mHeaderFileExtension = ".protocol.h";
const string Protocol::CodeGeneratorCPP::mSourceFileExtension = ".protocol.cpp";
const string Protocol::CodeGeneratorCPP::mHeaderFileProlog =
"// This file was generated from the Protocol compiler.\n"
"// You should not edit this file directly.\n";
const string Protocol::CodeGeneratorCPP::mSourceFileProlog =
"// This file was generated from the Protocol compiler.\n"
"// You should not edit this file directly.\n";

Protocol::CodeGeneratorCPP::CodeGeneratorCPP ()
{ }

void Protocol::CodeGeneratorCPP::generateCode (const string & outputFolder, const ProtoModel & protoModel, const std::string & projectName) const
{
    filesystem::path outputPath(outputFolder);
    filesystem::path modelPath(protoModel.name());
    filesystem::path headerPath(outputPath / filesystem::change_extension(modelPath, mHeaderFileExtension));
    filesystem::path sourcePath(outputPath / filesystem::change_extension(modelPath, mSourceFileExtension));

    filesystem::create_directory(outputFolder);
    filesystem::ofstream headerFile(headerPath, ios::out | ios::trunc);
    CodeWriter headerFileWriter(headerFile);
    filesystem::ofstream sourceFile(sourcePath, ios::out | ios::trunc);
    CodeWriter sourceFileWriter(sourceFile);

    headerFileWriter.writeLine(mHeaderFileProlog);
    headerFileWriter.writeHeaderIncludeBlockOpening(headerIncludeBlockText(protoModel, projectName));

    writeStandardIncludFileNamesToHeader(headerFileWriter);
    writeIncludedProtoFileNamesToHeader(headerFileWriter, protoModel);

    writeProtoEnumsToHeader(headerFileWriter, protoModel);

    writeProtoMessagesToHeader(headerFileWriter, protoModel);

    headerFileWriter.writeHeaderIncludeBlockClosing();

    sourceFileWriter.writeLine(mSourceFileProlog);
}

string Protocol::CodeGeneratorCPP::headerIncludeBlockText (const ProtoModel & protoModel, const std::string & projectName) const
{
    string text = projectName;
    if (!text.empty())
    {
        text += "_";
    }

    filesystem::path modelPath(protoModel.namePascal());
    text += filesystem::basename(modelPath.filename());
    text += "_h";

    return text;
}

void Protocol::CodeGeneratorCPP::writeStandardIncludFileNamesToHeader (CodeWriter & headerFileWriter) const
{
    headerFileWriter.writeIncludeLibrary("cstdint");
    headerFileWriter.writeIncludeLibrary("string");
    headerFileWriter.writeBlankLine();
}

void Protocol::CodeGeneratorCPP::writeIncludedProtoFileNamesToHeader (CodeWriter & headerFileWriter, const ProtoModel & protoModel) const
{
    auto importedProtoBegin = protoModel.importedProtoNames()->cbegin();
    auto importedProtoEnd = protoModel.importedProtoNames()->cend();
    bool importsFound = false;
    while (importedProtoBegin != importedProtoEnd)
    {
        importsFound = true;
        filesystem::path protoPath(*importedProtoBegin);
        filesystem::path headerPath(filesystem::change_extension(protoPath, mHeaderFileExtension));
        headerFileWriter.writeIncludeProject(headerPath.string());
        ++importedProtoBegin;
    }
    if (importsFound)
    {
        headerFileWriter.writeBlankLine();
    }
}

void Protocol::CodeGeneratorCPP::writeProtoEnumsToHeader (CodeWriter & headerFileWriter, const ProtoModel & protoModel) const
{
    auto protoEnumBegin = protoModel.enums()->cbegin();
    auto protoEnumEnd = protoModel.enums()->cend();
    while (protoEnumBegin != protoEnumEnd)
    {
        auto enumModel = *protoEnumBegin;
        headerFileWriter.writeEnumOpening(enumModel->namePascal());

        auto enumValueBegin = enumModel->enumValues()->cbegin();
        auto enumValueEnd = enumModel->enumValues()->cend();
        bool firstEnumValue = true;
        while (enumValueBegin != enumValueEnd)
        {
            auto enumValueModel = *enumValueBegin;
            if (firstEnumValue)
            {
                headerFileWriter.writeEnumValueFirst(enumValueModel->name(), enumValueModel->value());
                firstEnumValue = false;
            }
            else
            {
                headerFileWriter.writeEnumValueSubsequent(enumValueModel->name(), enumValueModel->value());
            }
            ++enumValueBegin;
        }

        headerFileWriter.writeEnumClosing();
        ++protoEnumBegin;
    }
}

void Protocol::CodeGeneratorCPP::writeProtoMessagesToHeader (CodeWriter & headerFileWriter, const ProtoModel & protoModel) const
{
    auto protoMessageBegin = protoModel.messages()->cbegin();
    auto protoMessageEnd = protoModel.messages()->cend();
    while (protoMessageBegin != protoMessageEnd)
    {
        auto messageModel = *protoMessageBegin;

        writeMessageToHeader(headerFileWriter, protoModel, *messageModel, messageModel->namePascal());

        ++protoMessageBegin;
    }
}

void Protocol::CodeGeneratorCPP::writeMessageToHeader (CodeWriter & headerFileWriter,
                                                       const ProtoModel & protoModel,
                                                       const MessageModel & messageModel,
                                                       const std::string & className) const
{
    headerFileWriter.writeClassOpening(className);

    headerFileWriter.writeClassPublic();

    // Generate all the typedefs for nested classes first, then generate each class.
    bool subMessageFound = false;
    auto messageMessageBegin = messageModel.messages()->cbegin();
    auto messageMessageEnd = messageModel.messages()->cend();
    while (messageMessageBegin != messageMessageEnd)
    {
        subMessageFound = true;
        auto messageSubModel = *messageMessageBegin;

        string subClassName = className + messageSubModel->namePascal();
        headerFileWriter.writeTypedef(subClassName, messageSubModel->namePascal());

        ++messageMessageBegin;
    }
    if (subMessageFound)
    {
        headerFileWriter.writeBlankLine();
    }
    messageMessageBegin = messageModel.messages()->cbegin();
    messageMessageEnd = messageModel.messages()->cend();
    while (messageMessageBegin != messageMessageEnd)
    {
        auto messageSubModel = *messageMessageBegin;

        string subClassName = className + messageSubModel->namePascal();
        writeMessageToHeader(headerFileWriter, protoModel, *messageSubModel, subClassName);

        ++messageMessageBegin;
    }

    string methodName = className;
    headerFileWriter.writeClassMethodDeclaration(methodName);

    string methodReturn = "";
    string methodParameters = "const ";
    methodParameters += className + " & src";
    headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters);

    methodName = "~";
    methodName += className;
    headerFileWriter.writeClassMethodDeclaration(methodName);

    methodName = "operator =";
    methodReturn = className + " &";
    methodParameters = "const ";
    methodParameters += className + " & rhs";
    headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters);

    methodName = "swap";
    methodReturn = "void";
    methodParameters = className + " * other";
    headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters);

    auto messageFieldBegin = messageModel.fields()->cbegin();
    auto messageFieldEnd = messageModel.fields()->cend();
    while (messageFieldBegin != messageFieldEnd)
    {
        auto messageFieldModel = *messageFieldBegin;
        switch (messageFieldModel->fieldCategory())
        {
            case MessageFieldModel::FieldCategory::numericType:
            case MessageFieldModel::FieldCategory::enumType:
            {
                methodName = messageFieldModel->name();
                string fieldType = fullTypeName(protoModel, messageFieldModel->fieldType());
                methodReturn = fieldType;
                methodParameters = "";
                headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true);

                methodName = "set";
                methodName += messageFieldModel->namePascal();
                methodReturn = "void";
                methodParameters = fieldType + " value";
                headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters);

                methodName = "has";
                methodName += messageFieldModel->namePascal();
                methodReturn = "bool";
                methodParameters = "";
                headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true);

                methodName = "clear";
                methodName += messageFieldModel->namePascal();
                methodReturn = "void";
                methodParameters = "";
                headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters);
                break;
            }

            case MessageFieldModel::FieldCategory::stringType:
            case MessageFieldModel::FieldCategory::bytesType:
            case MessageFieldModel::FieldCategory::messageType:
            {
                methodName = messageFieldModel->name();
                string fieldType = fullTypeName(protoModel, messageFieldModel->fieldType());
                methodReturn = "const ";
                methodReturn += fieldType + " &";
                methodParameters = "";
                headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true);

                methodName = "mutable";
                methodName += messageFieldModel->namePascal();
                methodReturn = fieldType + " *";
                methodParameters = "";
                headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters);

                methodName = "set";
                methodName += messageFieldModel->namePascal();
                methodReturn = "void";
                methodParameters = "const ";
                methodParameters += fieldType + " & value";
                headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters);

                methodName = "has";
                methodName += messageFieldModel->namePascal();
                methodReturn = "bool";
                methodParameters = "";
                headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters, true);

                methodName = "clear";
                methodName += messageFieldModel->namePascal();
                methodReturn = "void";
                methodParameters = "";
                headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters);

                methodName = "reset";
                methodName += messageFieldModel->namePascal();
                methodReturn = "void";
                methodParameters = fieldType + " * value";
                headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters);

                methodName = "release";
                methodName += messageFieldModel->namePascal();
                methodReturn = fieldType + " *";
                methodParameters = "";
                headerFileWriter.writeClassMethodDeclaration(methodName, methodReturn, methodParameters);
                break;
            }

            default:
                break;
        }

        ++messageFieldBegin;
    }

    headerFileWriter.writeClassPrivate();

    messageFieldBegin = messageModel.fields()->cbegin();
    messageFieldEnd = messageModel.fields()->cend();
    while (messageFieldBegin != messageFieldEnd)
    {
        auto messageFieldModel = *messageFieldBegin;

        string constantName = "m";
        constantName += messageFieldModel->namePascal() + "Index";
        string fieldType = "const unsigned int";
        headerFileWriter.writeClassFieldDeclaration(constantName, fieldType, to_string(messageFieldModel->index()), true);

        ++messageFieldBegin;
    }

    headerFileWriter.writeClassClosing();
}

string Protocol::CodeGeneratorCPP::fullTypeName (const ProtoModel & protoModel, const std::string & protoTypeName) const
{
    if (protoTypeName == "bool")
    {
        return "bool";
    }
    if (protoTypeName == "string")
    {
        return "std::string";
    }
    if (protoTypeName == "double")
    {
        return "double";
    }
    if (protoTypeName == "float")
    {
        return "float";
    }
    if (protoTypeName == "int32")
    {
        return "int32_t";
    }
    if (protoTypeName == "int64")
    {
        return "int64_t";
    }
    if (protoTypeName == "uint32")
    {
        return "uint32_t";
    }
    if (protoTypeName == "uint64")
    {
        return "uint64_t";
    }
    if (protoTypeName == "sint32")
    {
        return "int32_t";
    }
    if (protoTypeName == "sint64")
    {
        return "int64_t";
    }
    if (protoTypeName == "fixed32")
    {
        return "int32_t";
    }
    if (protoTypeName == "fixed64")
    {
        return "int64_t";
    }
    if (protoTypeName == "sfixed32")
    {
        return "int32_t";
    }
    if (protoTypeName == "sfixed64")
    {
        return "int64_t";
    }
    if (protoTypeName == "bytes")
    {
        return "std::string";
    }
    return "";
}
<|endoftext|>


<commit_before>// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "vm/globals.h"
#if defined(HOST_OS_FUCHSIA)

#include "vm/os.h"

#include <errno.h>
#include <fdio/util.h>
#include <zircon/process.h>
#include <zircon/syscalls.h>
#include <zircon/syscalls/object.h>
#include <zircon/types.h>

#include <fuchsia/cpp/time_zone.h>

#include "lib/app/cpp/environment_services.h"

#include "platform/assert.h"
#include "vm/zone.h"

namespace dart {

#ifndef PRODUCT

DEFINE_FLAG(bool,
            generate_perf_events_symbols,
            false,
            "Generate events symbols for profiling with perf");

#endif  // !PRODUCT

const char* OS::Name() {
  return "fuchsia";
}

intptr_t OS::ProcessId() {
  return static_cast<intptr_t>(getpid());
}

static zx_status_t GetLocalAndDstOffsetInSeconds(int64_t seconds_since_epoch,
                                                 int32_t* local_offset,
                                                 int32_t* dst_offset) {
  time_zone::TimezoneSyncPtr time_svc;
  component::ConnectToEnvironmentService(time_svc.NewRequest());
  if (!time_svc->GetTimezoneOffsetMinutes(seconds_since_epoch * 1000,
                                          local_offset, dst_offset))
    return ZX_ERR_UNAVAILABLE;
  *local_offset *= 60;
  *dst_offset *= 60;
  return ZX_OK;
}

const char* OS::GetTimeZoneName(int64_t seconds_since_epoch) {
  // TODO(abarth): Handle time zone changes.
  static const auto* tz_name = new std::string([] {
    time_zone::TimezoneSyncPtr time_svc;
    component::ConnectToEnvironmentService(time_svc.NewRequest());
    fidl::StringPtr result;
    time_svc->GetTimezoneId(&result);
    return *result;
  }());
  return tz_name->c_str();
}

int OS::GetTimeZoneOffsetInSeconds(int64_t seconds_since_epoch) {
  int32_t local_offset, dst_offset;
  zx_status_t status = GetLocalAndDstOffsetInSeconds(
      seconds_since_epoch, &local_offset, &dst_offset);
  return status == ZX_OK ? local_offset + dst_offset : 0;
}

int OS::GetLocalTimeZoneAdjustmentInSeconds() {
  int32_t local_offset, dst_offset;
  zx_status_t status = GetLocalAndDstOffsetInSeconds(
      zx_clock_get(ZX_CLOCK_UTC) / ZX_SEC(1), &local_offset, &dst_offset);
  return status == ZX_OK ? local_offset : 0;
}

int64_t OS::GetCurrentTimeMillis() {
  return GetCurrentTimeMicros() / 1000;
}

int64_t OS::GetCurrentTimeMicros() {
  return zx_clock_get(ZX_CLOCK_UTC) / kNanosecondsPerMicrosecond;
}

int64_t OS::GetCurrentMonotonicTicks() {
  return zx_clock_get(ZX_CLOCK_MONOTONIC);
}

int64_t OS::GetCurrentMonotonicFrequency() {
  return kNanosecondsPerSecond;
}

int64_t OS::GetCurrentMonotonicMicros() {
  int64_t ticks = GetCurrentMonotonicTicks();
  ASSERT(GetCurrentMonotonicFrequency() == kNanosecondsPerSecond);
  return ticks / kNanosecondsPerMicrosecond;
}

int64_t OS::GetCurrentThreadCPUMicros() {
  return zx_clock_get(ZX_CLOCK_THREAD) / kNanosecondsPerMicrosecond;
}

// TODO(5411554):  May need to hoist these architecture dependent code
// into a architecture specific file e.g: os_ia32_fuchsia.cc
intptr_t OS::ActivationFrameAlignment() {
#if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) ||                   \
    defined(TARGET_ARCH_ARM64)
  const int kMinimumAlignment = 16;
#elif defined(TARGET_ARCH_ARM) || defined(TARGET_ARCH_DBC)
  const int kMinimumAlignment = 8;
#else
#error Unsupported architecture.
#endif
  intptr_t alignment = kMinimumAlignment;
  // TODO(5411554): Allow overriding default stack alignment for
  // testing purposes.
  // Flags::DebugIsInt("stackalign", &alignment);
  ASSERT(Utils::IsPowerOfTwo(alignment));
  ASSERT(alignment >= kMinimumAlignment);
  return alignment;
}

intptr_t OS::PreferredCodeAlignment() {
#if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) ||                   \
    defined(TARGET_ARCH_ARM64) || defined(TARGET_ARCH_DBC)
  const int kMinimumAlignment = 32;
#elif defined(TARGET_ARCH_ARM)
  const int kMinimumAlignment = 16;
#else
#error Unsupported architecture.
#endif
  intptr_t alignment = kMinimumAlignment;
  // TODO(5411554): Allow overriding default code alignment for
  // testing purposes.
  // Flags::DebugIsInt("codealign", &alignment);
  ASSERT(Utils::IsPowerOfTwo(alignment));
  ASSERT(alignment >= kMinimumAlignment);
  ASSERT(alignment <= OS::kMaxPreferredCodeAlignment);
  return alignment;
}

int OS::NumberOfAvailableProcessors() {
  return sysconf(_SC_NPROCESSORS_CONF);
}

void OS::Sleep(int64_t millis) {
  SleepMicros(millis * kMicrosecondsPerMillisecond);
}

void OS::SleepMicros(int64_t micros) {
  zx_nanosleep(zx_deadline_after(micros * kNanosecondsPerMicrosecond));
}

void OS::DebugBreak() {
  UNIMPLEMENTED();
}

DART_NOINLINE uintptr_t OS::GetProgramCounter() {
  return reinterpret_cast<uintptr_t>(
      __builtin_extract_return_addr(__builtin_return_address(0)));
}

void OS::Print(const char* format, ...) {
  va_list args;
  va_start(args, format);
  VFPrint(stdout, format, args);
  va_end(args);
}

void OS::VFPrint(FILE* stream, const char* format, va_list args) {
  vfprintf(stream, format, args);
  fflush(stream);
}

char* OS::SCreate(Zone* zone, const char* format, ...) {
  va_list args;
  va_start(args, format);
  char* buffer = VSCreate(zone, format, args);
  va_end(args);
  return buffer;
}

char* OS::VSCreate(Zone* zone, const char* format, va_list args) {
  // Measure.
  va_list measure_args;
  va_copy(measure_args, args);
  intptr_t len = Utils::VSNPrint(NULL, 0, format, measure_args);
  va_end(measure_args);

  char* buffer;
  if (zone) {
    buffer = zone->Alloc<char>(len + 1);
  } else {
    buffer = reinterpret_cast<char*>(malloc(len + 1));
  }
  ASSERT(buffer != NULL);

  // Print.
  va_list print_args;
  va_copy(print_args, args);
  Utils::VSNPrint(buffer, len + 1, format, print_args);
  va_end(print_args);
  return buffer;
}

bool OS::StringToInt64(const char* str, int64_t* value) {
  ASSERT(str != NULL && strlen(str) > 0 && value != NULL);
  int32_t base = 10;
  char* endptr;
  int i = 0;
  if (str[0] == '-') {
    i = 1;
  }
  if ((str[i] == '0') && (str[i + 1] == 'x' || str[i + 1] == 'X') &&
      (str[i + 2] != '\0')) {
    base = 16;
  }
  errno = 0;
  if (FLAG_limit_ints_to_64_bits && (base == 16)) {
    // Unsigned 64-bit hexadecimal integer literals are allowed but
    // immediately interpreted as signed 64-bit integers.
    *value = static_cast<int64_t>(strtoull(str, &endptr, base));
  } else {
    *value = strtoll(str, &endptr, base);
  }
  return ((errno == 0) && (endptr != str) && (*endptr == 0));
}

void OS::RegisterCodeObservers() {
#ifndef PRODUCT
  if (FLAG_generate_perf_events_symbols) {
    UNIMPLEMENTED();
  }
#endif  // !PRODUCT
}

void OS::PrintErr(const char* format, ...) {
  va_list args;
  va_start(args, format);
  VFPrint(stderr, format, args);
  va_end(args);
}

void OS::InitOnce() {
  // TODO(5411554): For now we check that initonce is called only once,
  // Once there is more formal mechanism to call InitOnce we can move
  // this check there.
  static bool init_once_called = false;
  ASSERT(init_once_called == false);
  init_once_called = true;
}

void OS::Shutdown() {}

void OS::Abort() {
  abort();
}

void OS::Exit(int code) {
  UNIMPLEMENTED();
}

}  // namespace dart

#endif  // defined(HOST_OS_FUCHSIA)
<commit_msg>[fuchsia] Update FIDL include paths.<commit_after>// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "vm/globals.h"
#if defined(HOST_OS_FUCHSIA)

#include "vm/os.h"

#include <errno.h>
#include <fdio/util.h>
#include <zircon/process.h>
#include <zircon/syscalls.h>
#include <zircon/syscalls/object.h>
#include <zircon/types.h>

#include <time_zone/cpp/fidl.h>

#include "lib/app/cpp/environment_services.h"

#include "platform/assert.h"
#include "vm/zone.h"

namespace dart {

#ifndef PRODUCT

DEFINE_FLAG(bool,
            generate_perf_events_symbols,
            false,
            "Generate events symbols for profiling with perf");

#endif  // !PRODUCT

const char* OS::Name() {
  return "fuchsia";
}

intptr_t OS::ProcessId() {
  return static_cast<intptr_t>(getpid());
}

static zx_status_t GetLocalAndDstOffsetInSeconds(int64_t seconds_since_epoch,
                                                 int32_t* local_offset,
                                                 int32_t* dst_offset) {
  time_zone::TimezoneSyncPtr time_svc;
  component::ConnectToEnvironmentService(time_svc.NewRequest());
  if (!time_svc->GetTimezoneOffsetMinutes(seconds_since_epoch * 1000,
                                          local_offset, dst_offset))
    return ZX_ERR_UNAVAILABLE;
  *local_offset *= 60;
  *dst_offset *= 60;
  return ZX_OK;
}

const char* OS::GetTimeZoneName(int64_t seconds_since_epoch) {
  // TODO(abarth): Handle time zone changes.
  static const auto* tz_name = new std::string([] {
    time_zone::TimezoneSyncPtr time_svc;
    component::ConnectToEnvironmentService(time_svc.NewRequest());
    fidl::StringPtr result;
    time_svc->GetTimezoneId(&result);
    return *result;
  }());
  return tz_name->c_str();
}

int OS::GetTimeZoneOffsetInSeconds(int64_t seconds_since_epoch) {
  int32_t local_offset, dst_offset;
  zx_status_t status = GetLocalAndDstOffsetInSeconds(
      seconds_since_epoch, &local_offset, &dst_offset);
  return status == ZX_OK ? local_offset + dst_offset : 0;
}

int OS::GetLocalTimeZoneAdjustmentInSeconds() {
  int32_t local_offset, dst_offset;
  zx_status_t status = GetLocalAndDstOffsetInSeconds(
      zx_clock_get(ZX_CLOCK_UTC) / ZX_SEC(1), &local_offset, &dst_offset);
  return status == ZX_OK ? local_offset : 0;
}

int64_t OS::GetCurrentTimeMillis() {
  return GetCurrentTimeMicros() / 1000;
}

int64_t OS::GetCurrentTimeMicros() {
  return zx_clock_get(ZX_CLOCK_UTC) / kNanosecondsPerMicrosecond;
}

int64_t OS::GetCurrentMonotonicTicks() {
  return zx_clock_get(ZX_CLOCK_MONOTONIC);
}

int64_t OS::GetCurrentMonotonicFrequency() {
  return kNanosecondsPerSecond;
}

int64_t OS::GetCurrentMonotonicMicros() {
  int64_t ticks = GetCurrentMonotonicTicks();
  ASSERT(GetCurrentMonotonicFrequency() == kNanosecondsPerSecond);
  return ticks / kNanosecondsPerMicrosecond;
}

int64_t OS::GetCurrentThreadCPUMicros() {
  return zx_clock_get(ZX_CLOCK_THREAD) / kNanosecondsPerMicrosecond;
}

// TODO(5411554):  May need to hoist these architecture dependent code
// into a architecture specific file e.g: os_ia32_fuchsia.cc
intptr_t OS::ActivationFrameAlignment() {
#if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) ||                   \
    defined(TARGET_ARCH_ARM64)
  const int kMinimumAlignment = 16;
#elif defined(TARGET_ARCH_ARM) || defined(TARGET_ARCH_DBC)
  const int kMinimumAlignment = 8;
#else
#error Unsupported architecture.
#endif
  intptr_t alignment = kMinimumAlignment;
  // TODO(5411554): Allow overriding default stack alignment for
  // testing purposes.
  // Flags::DebugIsInt("stackalign", &alignment);
  ASSERT(Utils::IsPowerOfTwo(alignment));
  ASSERT(alignment >= kMinimumAlignment);
  return alignment;
}

intptr_t OS::PreferredCodeAlignment() {
#if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) ||                   \
    defined(TARGET_ARCH_ARM64) || defined(TARGET_ARCH_DBC)
  const int kMinimumAlignment = 32;
#elif defined(TARGET_ARCH_ARM)
  const int kMinimumAlignment = 16;
#else
#error Unsupported architecture.
#endif
  intptr_t alignment = kMinimumAlignment;
  // TODO(5411554): Allow overriding default code alignment for
  // testing purposes.
  // Flags::DebugIsInt("codealign", &alignment);
  ASSERT(Utils::IsPowerOfTwo(alignment));
  ASSERT(alignment >= kMinimumAlignment);
  ASSERT(alignment <= OS::kMaxPreferredCodeAlignment);
  return alignment;
}

int OS::NumberOfAvailableProcessors() {
  return sysconf(_SC_NPROCESSORS_CONF);
}

void OS::Sleep(int64_t millis) {
  SleepMicros(millis * kMicrosecondsPerMillisecond);
}

void OS::SleepMicros(int64_t micros) {
  zx_nanosleep(zx_deadline_after(micros * kNanosecondsPerMicrosecond));
}

void OS::DebugBreak() {
  UNIMPLEMENTED();
}

DART_NOINLINE uintptr_t OS::GetProgramCounter() {
  return reinterpret_cast<uintptr_t>(
      __builtin_extract_return_addr(__builtin_return_address(0)));
}

void OS::Print(const char* format, ...) {
  va_list args;
  va_start(args, format);
  VFPrint(stdout, format, args);
  va_end(args);
}

void OS::VFPrint(FILE* stream, const char* format, va_list args) {
  vfprintf(stream, format, args);
  fflush(stream);
}

char* OS::SCreate(Zone* zone, const char* format, ...) {
  va_list args;
  va_start(args, format);
  char* buffer = VSCreate(zone, format, args);
  va_end(args);
  return buffer;
}

char* OS::VSCreate(Zone* zone, const char* format, va_list args) {
  // Measure.
  va_list measure_args;
  va_copy(measure_args, args);
  intptr_t len = Utils::VSNPrint(NULL, 0, format, measure_args);
  va_end(measure_args);

  char* buffer;
  if (zone) {
    buffer = zone->Alloc<char>(len + 1);
  } else {
    buffer = reinterpret_cast<char*>(malloc(len + 1));
  }
  ASSERT(buffer != NULL);

  // Print.
  va_list print_args;
  va_copy(print_args, args);
  Utils::VSNPrint(buffer, len + 1, format, print_args);
  va_end(print_args);
  return buffer;
}

bool OS::StringToInt64(const char* str, int64_t* value) {
  ASSERT(str != NULL && strlen(str) > 0 && value != NULL);
  int32_t base = 10;
  char* endptr;
  int i = 0;
  if (str[0] == '-') {
    i = 1;
  }
  if ((str[i] == '0') && (str[i + 1] == 'x' || str[i + 1] == 'X') &&
      (str[i + 2] != '\0')) {
    base = 16;
  }
  errno = 0;
  if (FLAG_limit_ints_to_64_bits && (base == 16)) {
    // Unsigned 64-bit hexadecimal integer literals are allowed but
    // immediately interpreted as signed 64-bit integers.
    *value = static_cast<int64_t>(strtoull(str, &endptr, base));
  } else {
    *value = strtoll(str, &endptr, base);
  }
  return ((errno == 0) && (endptr != str) && (*endptr == 0));
}

void OS::RegisterCodeObservers() {
#ifndef PRODUCT
  if (FLAG_generate_perf_events_symbols) {
    UNIMPLEMENTED();
  }
#endif  // !PRODUCT
}

void OS::PrintErr(const char* format, ...) {
  va_list args;
  va_start(args, format);
  VFPrint(stderr, format, args);
  va_end(args);
}

void OS::InitOnce() {
  // TODO(5411554): For now we check that initonce is called only once,
  // Once there is more formal mechanism to call InitOnce we can move
  // this check there.
  static bool init_once_called = false;
  ASSERT(init_once_called == false);
  init_once_called = true;
}

void OS::Shutdown() {}

void OS::Abort() {
  abort();
}

void OS::Exit(int code) {
  UNIMPLEMENTED();
}

}  // namespace dart

#endif  // defined(HOST_OS_FUCHSIA)
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: implpolypolygon.cxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_cppcanvas.hxx"
#include <rtl/math.hxx>
#include <com/sun/star/rendering/PathJoinType.hpp>
#include <com/sun/star/rendering/PathCapType.hpp>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/tools/canvastools.hxx>

#include <implpolypolygon.hxx>
#include <tools.hxx>

using namespace ::com::sun::star;

namespace cppcanvas
{
    namespace internal
    {
        ImplPolyPolygon::ImplPolyPolygon( const CanvasSharedPtr& rParentCanvas,
                                          const uno::Reference< rendering::XPolyPolygon2D >& rPolyPoly ) :
            CanvasGraphicHelper( rParentCanvas ),
            mxPolyPoly( rPolyPoly ),
            maStrokeAttributes(1.0,
                               10.0,
                               uno::Sequence< double >(),
                               uno::Sequence< double >(),
                               rendering::PathCapType::ROUND,
                               rendering::PathCapType::ROUND,
                               rendering::PathJoinType::ROUND ),
            maFillColor(),
            maStrokeColor(),
            mbFillColorSet( false ),
            mbStrokeColorSet( false )
        {
            OSL_ENSURE( mxPolyPoly.is(), "PolyPolygonImpl::PolyPolygonImpl: no valid polygon" );
        }

        ImplPolyPolygon::~ImplPolyPolygon()
        {
        }

        void ImplPolyPolygon::addPolygon( const ::basegfx::B2DPolygon& rPoly )
        {
            OSL_ENSURE( mxPolyPoly.is(),
                        "ImplPolyPolygon::addPolygon(): Invalid polygon" );

            if( !mxPolyPoly.is() )
                return;

            uno::Reference< rendering::XGraphicDevice > xDevice( getGraphicDevice() );

            OSL_ENSURE( xDevice.is(),
                        "ImplPolyPolygon::addPolygon(): Invalid graphic device" );

            if( !xDevice.is() )
                return;

            mxPolyPoly->addPolyPolygon( geometry::RealPoint2D(0.0, 0.0),
                                        ::basegfx::unotools::xPolyPolygonFromB2DPolygon(
                                            xDevice,
                                            rPoly) );
        }

        void ImplPolyPolygon::addPolyPolygon( const ::basegfx::B2DPolyPolygon& rPoly )
        {
            OSL_ENSURE( mxPolyPoly.is(),
                        "ImplPolyPolygon::addPolyPolygon(): Invalid polygon" );

            if( !mxPolyPoly.is() )
                return;

            uno::Reference< rendering::XGraphicDevice > xDevice( getGraphicDevice() );

            OSL_ENSURE( xDevice.is(),
                        "ImplPolyPolygon::addPolyPolygon(): Invalid graphic device" );

            if( !xDevice.is() )
                return;

            mxPolyPoly->addPolyPolygon( geometry::RealPoint2D(0.0, 0.0),
                                        ::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon(
                                            xDevice,
                                            rPoly) );
        }

        void ImplPolyPolygon::setRGBAFillColor( Color::IntSRGBA aColor )
        {
            maFillColor = tools::intSRGBAToDoubleSequence( getGraphicDevice(),
                                                           aColor );
            mbFillColorSet = true;
        }

        void ImplPolyPolygon::setRGBALineColor( Color::IntSRGBA aColor )
        {
            maStrokeColor = tools::intSRGBAToDoubleSequence( getGraphicDevice(),
                                                             aColor );
            mbStrokeColorSet = true;
        }

        Color::IntSRGBA ImplPolyPolygon::getRGBAFillColor() const
        {
            return tools::doubleSequenceToIntSRGBA( getGraphicDevice(),
                                                    maFillColor );
        }

        Color::IntSRGBA ImplPolyPolygon::getRGBALineColor() const
        {
            return tools::doubleSequenceToIntSRGBA( getGraphicDevice(),
                                                    maStrokeColor );
        }

        void ImplPolyPolygon::setStrokeWidth( const double& rStrokeWidth )
        {
            maStrokeAttributes.StrokeWidth = rStrokeWidth;
        }

        double ImplPolyPolygon::getStrokeWidth() const
        {
            return maStrokeAttributes.StrokeWidth;
        }

        bool ImplPolyPolygon::draw() const
        {
            CanvasSharedPtr pCanvas( getCanvas() );

            OSL_ENSURE( pCanvas.get() != NULL &&
                        pCanvas->getUNOCanvas().is(),
                        "ImplBitmap::draw: invalid canvas" );

            if( pCanvas.get() == NULL ||
                !pCanvas->getUNOCanvas().is() )
                return false;

            if( mbFillColorSet )
            {
                rendering::RenderState aLocalState( getRenderState() );
                aLocalState.DeviceColor = maFillColor;

                pCanvas->getUNOCanvas()->fillPolyPolygon( mxPolyPoly,
                                                          pCanvas->getViewState(),
                                                          aLocalState );
            }

            if( mbStrokeColorSet )
            {
                rendering::RenderState aLocalState( getRenderState() );
                aLocalState.DeviceColor = maStrokeColor;

                if( ::rtl::math::approxEqual(maStrokeAttributes.StrokeWidth, 1.0) )
                    pCanvas->getUNOCanvas()->drawPolyPolygon( mxPolyPoly,
                                                              pCanvas->getViewState(),
                                                              aLocalState );
                else
                    pCanvas->getUNOCanvas()->strokePolyPolygon( mxPolyPoly,
                                                                pCanvas->getViewState(),
                                                                aLocalState,
                                                                maStrokeAttributes );
            }

            return true;
        }

        uno::Reference< rendering::XPolyPolygon2D > ImplPolyPolygon::getUNOPolyPolygon() const
        {
            return mxPolyPoly;
        }

    }
}
<commit_msg>INTEGRATION: CWS canvas05 (1.8.38); FILE MERGED 2008/04/21 07:50:51 thb 1.8.38.2: RESYNC: (1.8-1.9); FILE MERGED 2007/10/01 13:41:45 thb 1.8.38.1: #i79258# Merge from CWS picom<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: implpolypolygon.cxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_cppcanvas.hxx"

#include <rtl/math.hxx>

#include <com/sun/star/rendering/XCanvas.hpp>
#include <com/sun/star/rendering/PathJoinType.hpp>
#include <com/sun/star/rendering/PathCapType.hpp>

#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/tools/canvastools.hxx>

#include "implpolypolygon.hxx"
#include "tools.hxx"

using namespace ::com::sun::star;

namespace cppcanvas
{
    namespace internal
    {
        ImplPolyPolygon::ImplPolyPolygon( const CanvasSharedPtr& rParentCanvas,
                                          const uno::Reference< rendering::XPolyPolygon2D >& rPolyPoly ) :
            CanvasGraphicHelper( rParentCanvas ),
            mxPolyPoly( rPolyPoly ),
            maStrokeAttributes(1.0,
                               10.0,
                               uno::Sequence< double >(),
                               uno::Sequence< double >(),
                               rendering::PathCapType::ROUND,
                               rendering::PathCapType::ROUND,
                               rendering::PathJoinType::ROUND ),
            maFillColor(),
            maStrokeColor(),
            mbFillColorSet( false ),
            mbStrokeColorSet( false )
        {
            OSL_ENSURE( mxPolyPoly.is(), "PolyPolygonImpl::PolyPolygonImpl: no valid polygon" );
        }

        ImplPolyPolygon::~ImplPolyPolygon()
        {
        }

        void ImplPolyPolygon::addPolygon( const ::basegfx::B2DPolygon& rPoly )
        {
            OSL_ENSURE( mxPolyPoly.is(),
                        "ImplPolyPolygon::addPolygon(): Invalid polygon" );

            if( !mxPolyPoly.is() )
                return;

            uno::Reference< rendering::XGraphicDevice > xDevice( getGraphicDevice() );

            OSL_ENSURE( xDevice.is(),
                        "ImplPolyPolygon::addPolygon(): Invalid graphic device" );

            if( !xDevice.is() )
                return;

            mxPolyPoly->addPolyPolygon( geometry::RealPoint2D(0.0, 0.0),
                                        ::basegfx::unotools::xPolyPolygonFromB2DPolygon(
                                            xDevice,
                                            rPoly) );
        }

        void ImplPolyPolygon::addPolyPolygon( const ::basegfx::B2DPolyPolygon& rPoly )
        {
            OSL_ENSURE( mxPolyPoly.is(),
                        "ImplPolyPolygon::addPolyPolygon(): Invalid polygon" );

            if( !mxPolyPoly.is() )
                return;

            uno::Reference< rendering::XGraphicDevice > xDevice( getGraphicDevice() );

            OSL_ENSURE( xDevice.is(),
                        "ImplPolyPolygon::addPolyPolygon(): Invalid graphic device" );

            if( !xDevice.is() )
                return;

            mxPolyPoly->addPolyPolygon( geometry::RealPoint2D(0.0, 0.0),
                                        ::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon(
                                            xDevice,
                                            rPoly) );
        }

        void ImplPolyPolygon::setRGBAFillColor( Color::IntSRGBA aColor )
        {
            maFillColor = tools::intSRGBAToDoubleSequence( getGraphicDevice(),
                                                           aColor );
            mbFillColorSet = true;
        }

        void ImplPolyPolygon::setRGBALineColor( Color::IntSRGBA aColor )
        {
            maStrokeColor = tools::intSRGBAToDoubleSequence( getGraphicDevice(),
                                                             aColor );
            mbStrokeColorSet = true;
        }

        Color::IntSRGBA ImplPolyPolygon::getRGBAFillColor() const
        {
            return tools::doubleSequenceToIntSRGBA( getGraphicDevice(),
                                                    maFillColor );
        }

        Color::IntSRGBA ImplPolyPolygon::getRGBALineColor() const
        {
            return tools::doubleSequenceToIntSRGBA( getGraphicDevice(),
                                                    maStrokeColor );
        }

        void ImplPolyPolygon::setStrokeWidth( const double& rStrokeWidth )
        {
            maStrokeAttributes.StrokeWidth = rStrokeWidth;
        }

        double ImplPolyPolygon::getStrokeWidth() const
        {
            return maStrokeAttributes.StrokeWidth;
        }

        bool ImplPolyPolygon::draw() const
        {
            CanvasSharedPtr pCanvas( getCanvas() );

            OSL_ENSURE( pCanvas.get() != NULL &&
                        pCanvas->getUNOCanvas().is(),
                        "ImplBitmap::draw: invalid canvas" );

            if( pCanvas.get() == NULL ||
                !pCanvas->getUNOCanvas().is() )
                return false;

            if( mbFillColorSet )
            {
                rendering::RenderState aLocalState( getRenderState() );
                aLocalState.DeviceColor = maFillColor;

                pCanvas->getUNOCanvas()->fillPolyPolygon( mxPolyPoly,
                                                          pCanvas->getViewState(),
                                                          aLocalState );
            }

            if( mbStrokeColorSet )
            {
                rendering::RenderState aLocalState( getRenderState() );
                aLocalState.DeviceColor = maStrokeColor;

                if( ::rtl::math::approxEqual(maStrokeAttributes.StrokeWidth, 1.0) )
                    pCanvas->getUNOCanvas()->drawPolyPolygon( mxPolyPoly,
                                                              pCanvas->getViewState(),
                                                              aLocalState );
                else
                    pCanvas->getUNOCanvas()->strokePolyPolygon( mxPolyPoly,
                                                                pCanvas->getViewState(),
                                                                aLocalState,
                                                                maStrokeAttributes );
            }

            return true;
        }

        uno::Reference< rendering::XPolyPolygon2D > ImplPolyPolygon::getUNOPolyPolygon() const
        {
            return mxPolyPoly;
        }

    }
}
<|endoftext|>


<commit_before>/**
 ** \file libport/timer.hh
 ** \brief timer: Timing nested tasks.
 */

#ifndef LIBPORT_TIMER_HH
# define LIBPORT_TIMER_HH

# include <stack>
# include <map>
# include <string>
# include <iosfwd>

# include <boost/function.hpp>

# include <libport/export.hh>

namespace libport
{

  /// Timing nested tasks.
  class LIBPORT_API timer
  {
  public:
    timer();
    timer(const timer& rhs);
    ~timer();

    /// Start a sub timer for a named task.
    /// \param name a constant string which is the task's name
    void push(const std::string& name);

    /// Start a sub timer with an integer which refers to a string.
    /// \see push()
    /// \see name()
    void push(int i);

    /// Stop the named task. Take a const string as parameter
    /// that make sure that what is popped is indeed what is on top.
    void pop(const std::string& task_name);

    /// \see pop()
    /// \see pop(const std::string& name)
    void pop(const int i);

    /// Stop the current task's timer (the last task pushed).
    void pop();

    /// Write results.
    /// \param out an ostream which defaults to cerr.
    void dump(std::ostream& out);

    /// Write results when the timer is destroyed.
    /// \param out an ostream which defaults to cerr.
    void dump_on_destruction(std::ostream& out);

    /// the name function links an int and a constant string.
    void name(int, const std::string);

    /// the start function must be called at the beginning of the program
    /// to get the total time spend in the whole program.
    /// \see stop()
    void start();

    /// the stop function must be called at the end of the program.
    /// \see start()
    void stop();

    /// \brief Import timer.
    ///
    /// Import tasks defined in \a rhs. There must be not stacked task.
    /// Total execution time of \a rhs is ignored.
    timer& operator<<(const timer& rhs);

    /// Things to do when this timer is about to be destroyed.
    typedef boost::function0<void> callback_type;

    /// Register a new callback.
    void destruction_hook(const callback_type& c);

  private:
    class time_var;
    class time
    {
      friend class timer;
      friend class timer::time_var;
    public:
      time();
      time & operator +=(const time& rhs);

    private :
      long user;
      long sys;
      long wall;
    };

    class LIBPORT_API time_var
    {
    public:
      time_var();

      void start();
      void stop();

      bool is_zero();

      time begin;
      time elapsed;
      time first;
      time last;
      bool initial;
    };

    /// Format timing results.
    void timeinfo(long, long, std::ostream&);

    typedef std::map<const std::string, time_var*> task_map_type;

    /// Store differents tasks you benched.
    task_map_type tasksmap;

    /// tasks is a stack in which tasks are benched in order.
    std::stack<time_var*> tasks;

    /// Map for int and string couples (to call push(int))
    std::map<int, std::string> intmap;

    /// Total time spend in the program
    /// \see start()
    /// \see stop()
    time_var total;

    /// Things to do when this timer is about to be destroyed.
    typedef std::vector<callback_type> callbacks_type;
    callbacks_type destruction_callbacks_;

    /// Number of clocks ticks per second, set according to the system
    /// timing function used.
    static const long clocks_per_sec;
  };

} // namespace libport

# include <libport/timer.hxx>

#endif // !LIBPORT_TIMER_HH
<commit_msg>fix includes.<commit_after>/**
 ** \file libport/timer.hh
 ** \brief timer: Timing nested tasks.
 */

#ifndef LIBPORT_TIMER_HH
# define LIBPORT_TIMER_HH

# include <iosfwd>
# include <map>
# include <stack>
# include <string>
# include <vector>

# include <boost/function.hpp>

# include <libport/export.hh>

namespace libport
{

  /// Timing nested tasks.
  class LIBPORT_API timer
  {
  public:
    timer();
    timer(const timer& rhs);
    ~timer();

    /// Start a sub timer for a named task.
    /// \param name a constant string which is the task's name
    void push(const std::string& name);

    /// Start a sub timer with an integer which refers to a string.
    /// \see push()
    /// \see name()
    void push(int i);

    /// Stop the named task. Take a const string as parameter
    /// that make sure that what is popped is indeed what is on top.
    void pop(const std::string& task_name);

    /// \see pop()
    /// \see pop(const std::string& name)
    void pop(const int i);

    /// Stop the current task's timer (the last task pushed).
    void pop();

    /// Write results.
    /// \param out an ostream which defaults to cerr.
    void dump(std::ostream& out);

    /// Write results when the timer is destroyed.
    /// \param out an ostream which defaults to cerr.
    void dump_on_destruction(std::ostream& out);

    /// the name function links an int and a constant string.
    void name(int, const std::string);

    /// the start function must be called at the beginning of the program
    /// to get the total time spend in the whole program.
    /// \see stop()
    void start();

    /// the stop function must be called at the end of the program.
    /// \see start()
    void stop();

    /// \brief Import timer.
    ///
    /// Import tasks defined in \a rhs. There must be not stacked task.
    /// Total execution time of \a rhs is ignored.
    timer& operator<<(const timer& rhs);

    /// Things to do when this timer is about to be destroyed.
    typedef boost::function0<void> callback_type;

    /// Register a new callback.
    void destruction_hook(const callback_type& c);

  private:
    class time_var;
    class time
    {
      friend class timer;
      friend class timer::time_var;
    public:
      time();
      time & operator +=(const time& rhs);

    private :
      long user;
      long sys;
      long wall;
    };

    class LIBPORT_API time_var
    {
    public:
      time_var();

      void start();
      void stop();

      bool is_zero();

      time begin;
      time elapsed;
      time first;
      time last;
      bool initial;
    };

    /// Format timing results.
    void timeinfo(long, long, std::ostream&);

    typedef std::map<const std::string, time_var*> task_map_type;

    /// Store differents tasks you benched.
    task_map_type tasksmap;

    /// tasks is a stack in which tasks are benched in order.
    std::stack<time_var*> tasks;

    /// Map for int and string couples (to call push(int))
    std::map<int, std::string> intmap;

    /// Total time spend in the program
    /// \see start()
    /// \see stop()
    time_var total;

    /// Things to do when this timer is about to be destroyed.
    typedef std::vector<callback_type> callbacks_type;
    callbacks_type destruction_callbacks_;

    /// Number of clocks ticks per second, set according to the system
    /// timing function used.
    static const long clocks_per_sec;
  };

} // namespace libport

# include <libport/timer.hxx>

#endif // !LIBPORT_TIMER_HH
<|endoftext|>