<commit_before>/*
 *  mitkFiberBundleMapper2D.cpp
 *  mitk-all
 *
 *  Created by HAL9000 on 1/17/11.
 *  Copyright 2011 __MyCompanyName__. All rights reserved.
 *
 */

#include "mitkFiberBundleXMapper2D.h"
#include <mitkBaseRenderer.h>

#include <vtkActor.h>
#include <vtkPolyDataMapper.h>
#include <vtkPlane.h>
#include <vtkPolyData.h>
//#include <vtkPropAssembly.h>

//#include <vtkPainterPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkLookupTable.h>
#include <vtkPoints.h>
#include <vtkCamera.h>
#include <vtkPolyLine.h>
#include <vtkRenderer.h>
#include <vtkCellArray.h>
#include <vtkMatrix4x4.h>

//#include <mitkGeometry3D.h>
#include <mitkPlaneGeometry.h>
#include <mitkSliceNavigationController.h>

#include <mitkShaderRepository.h>
#include <mitkShaderProperty.h>
#include <mitkStandardFileLocations.h>

#include <QCoreApplication>
#include <QFile>

mitk::FiberBundleXMapper2D::FiberBundleXMapper2D()
{
    m_lut = vtkLookupTable::New();
    m_lut->Build();

}

mitk::FiberBundleXMapper2D::~FiberBundleXMapper2D()
{
}

mitk::FiberBundleX* mitk::FiberBundleXMapper2D::GetInput()
{
    return dynamic_cast< mitk::FiberBundleX * > ( GetData() );
}

void mitk::FiberBundleXMapper2D::Update(mitk::BaseRenderer * renderer)
{

    if ( !this->IsVisible( renderer ) )
    {
        return;
    }

 MITK_INFO << "MapperFBX 2D  update: ";
    // Calculate time step of the input data for the specified renderer (integer value)
    // this method is implemented in mitkMapper
    this->CalculateTimeStep( renderer );

    //check if updates occured in the node or on the display
    FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
    const DataNode *node = this->GetDataNode();
    if ( (localStorage->m_LastUpdateTime < node->GetMTime())
         || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified?
         || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) )
    {
        //    MITK_INFO << "UPDATE NEEDED FOR _ " << renderer->GetName();
        this->GenerateDataForRenderer( renderer );
    }

    if ((localStorage->m_LastUpdateTime < renderer->GetDisplayGeometry()->GetMTime()) ) //was the display geometry modified? e.g. zooming, panning)
    {

        this->UpdateShaderParameter(renderer);

    }

}

void mitk::FiberBundleXMapper2D::UpdateShaderParameter(mitk::BaseRenderer * renderer)
{
    FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);

    //get information about current position of views
    mitk::SliceNavigationController::Pointer sliceContr = renderer->GetSliceNavigationController();
    mitk::PlaneGeometry::ConstPointer planeGeo = sliceContr->GetCurrentPlaneGeometry();

    //generate according cutting planes based on the view position
    float sliceN[3], planeOrigin[3];

    // since shader uses camera coordinates, transform origin and normal from worldcoordinates to cameracoordinates

    planeOrigin[0] = (float) planeGeo->GetOrigin()[0];
    planeOrigin[1] = (float) planeGeo->GetOrigin()[1];
    planeOrigin[2] = (float) planeGeo->GetOrigin()[2];

    sliceN[0] = planeGeo->GetNormal()[0];
    sliceN[1] = planeGeo->GetNormal()[1];
    sliceN[2] = planeGeo->GetNormal()[2];

    float tmp1 = planeOrigin[0] * sliceN[0];
    float tmp2 = planeOrigin[1] * sliceN[1];
    float tmp3 = planeOrigin[2] * sliceN[2];
    float d1 = tmp1 + tmp2 + tmp3; //attention, correct normalvector

    float plane1[4];
    plane1[0] = sliceN[0];
    plane1[1] = sliceN[1];
    plane1[2] = sliceN[2];
    plane1[3] = d1;

    float thickness = 2.0;
    if(!this->GetDataNode()->GetPropertyValue("Fiber2DSliceThickness",thickness))
        MITK_INFO << "FIBER2D SLICE THICKNESS PROPERTY ERROR";

    bool fiberfading = false;
    if(!this->GetDataNode()->GetPropertyValue("Fiber2DfadeEFX",fiberfading))
        MITK_INFO << "FIBER2D SLICE FADE EFX PROPERTY ERROR";

    int fiberfading_i = 1;
    if (!fiberfading)
        fiberfading_i = 0;

    // set Opacity
    float fiberOpacity;
    this->GetDataNode()->GetOpacity(fiberOpacity, NULL);

    localStorage->m_PointActor->GetProperty()->AddShaderVariable("slicingPlane",4, plane1);
    localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberThickness",1, &thickness);
    localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberFadingON",1,  &fiberfading_i);
    localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberOpacity", 1, &fiberOpacity);

}

// ALL RAW DATA FOR VISUALIZATION IS GENERATED HERE.
// vtkActors and Mappers are feeded here
void mitk::FiberBundleXMapper2D::GenerateDataForRenderer(mitk::BaseRenderer *renderer)
{

    //the handler of local storage gets feeded in this method with requested data for related renderwindow
    FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);

    //this procedure is depricated,
    //not needed after initializaton anymore
    mitk::DataNode* node = this->GetDataNode();
    if ( node == NULL )
    {
        MITK_INFO << "check DATANODE: ....[Fail] ";
        return;
    }
    ///////////////////////////////////

    ///THIS GET INPUT
    mitk::FiberBundleX* fbx = this->GetInput();

    localStorage->m_PointMapper->ScalarVisibilityOn();
    localStorage->m_PointMapper->SetScalarModeToUsePointFieldData();
    localStorage->m_PointMapper->SetLookupTable(m_lut);  //apply the properties after the slice was set
    localStorage->m_PointActor->GetProperty()->SetOpacity(0.999);

    // set color
    if (fbx->GetCurrentColorCoding() != NULL){
//        localStorage->m_PointMapper->SelectColorArray("");
        localStorage->m_PointMapper->SelectColorArray(fbx->GetCurrentColorCoding());
        MITK_DEBUG << "MapperFBX 2D: " << fbx->GetCurrentColorCoding();

        if(fbx->GetCurrentColorCoding() == fbx->COLORCODING_CUSTOM){
            float temprgb[3];
            this->GetDataNode()->GetColor( temprgb, NULL );
            double trgb[3] = { (double) temprgb[0], (double) temprgb[1], (double) temprgb[2] };
            localStorage->m_PointActor->GetProperty()->SetColor(trgb);
        }
    }

    localStorage->m_PointMapper->SetInput(fbx->GetFiberPolyData());
    localStorage->m_PointActor->SetMapper(localStorage->m_PointMapper);
    localStorage->m_PointActor->GetProperty()->ShadingOn();

    // Applying shading properties
    {
        mitk::ShaderRepository::GetGlobalShaderRepository()->ApplyProperties(this->GetDataNode(),localStorage->m_PointActor,renderer, localStorage->m_LastUpdateTime);
    }

    this->UpdateShaderParameter(renderer);

    // We have been modified => save this for next Update()
    localStorage->m_LastUpdateTime.Modified();

}

vtkProp* mitk::FiberBundleXMapper2D::GetVtkProp(mitk::BaseRenderer *renderer)
{

    //MITK_INFO << "FiberBundleMapper2D GetVtkProp(renderer)";
    this->Update(renderer);
    return m_LSH.GetLocalStorage(renderer)->m_PointActor;

}

void mitk::FiberBundleXMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{    //add shader to datano

    //####### load shader from file #########
    QString applicationDir = QCoreApplication::applicationDirPath();

    if (applicationDir.endsWith("bin"))
        applicationDir.append("/");
    else if (applicationDir.endsWith("MacOS"))
    {
        //on osx, check if path for installer or MITK development is needed
        applicationDir.append("/");
        QFile f( applicationDir+"FiberTrackingLUTBaryCoords.bin" );
        if( !f.exists() ) // if file does not exist, then look in MITK development build directory
            applicationDir.append("../../../");
    }else
        applicationDir.append("\\..\\");

    mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false );
    mitk::ShaderRepository::Pointer shaderRepository = mitk::ShaderRepository::GetGlobalShaderRepository();
    shaderRepository->LoadShader(mitk::StandardFileLocations::GetInstance()->FindFile("mitkShaderFiberClipping.xml"));

    //####################################################################
    node->SetProperty("shader",mitk::ShaderProperty::New("mitkShaderFiberClipping"));
    mitk::ShaderRepository::GetGlobalShaderRepository()->AddDefaultProperties(node,renderer,overwrite);

    //add other parameters to propertylist
    node->AddProperty( "Fiber2DSliceThickness", mitk::FloatProperty::New(2.0f), renderer, overwrite );
    node->AddProperty( "Fiber2DfadeEFX", mitk::BoolProperty::New(true), renderer, overwrite );

    Superclass::SetDefaultProperties(node, renderer, overwrite);
}

// following methods are essential, they actually call the GetVtkProp() method
// which returns the desired actors
void mitk::FiberBundleXMapper2D::MitkRenderOverlay(BaseRenderer* renderer)
{
    //   MITK_INFO << "FiberBundleMapper2D MitkRenderOVerlay(renderer)";
    if ( this->IsVisible(renderer)==false )
        return;

    if ( this->GetVtkProp(renderer)->GetVisibility() )
    {
        this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer());
    }
}

void mitk::FiberBundleXMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer)
{
    //  MITK_INFO << "FiberBundleMapper2D MitkRenderOpaqueGeometry(renderer)";
    if ( this->IsVisible( renderer )==false )
        return;

    if ( this->GetVtkProp(renderer)->GetVisibility() )
        this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() );
}
void mitk::FiberBundleXMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer)
{
    //  MITK_INFO << "FiberBundleMapper2D MitkRenderTranslucentGeometry(renderer)";
    if ( this->IsVisible(renderer)==false )
        return;

    //TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???
    if ( this->GetVtkProp(renderer)->GetVisibility() )
        this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer());

}
void mitk::FiberBundleXMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer)
{
    //  MITK_INFO << "FiberBundleMapper2D MitkRenderVolumentricGeometry(renderer)";
    if(IsVisible(renderer)==false)
        return;

    //TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???
    if ( GetVtkProp(renderer)->GetVisibility() )
        this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer());

}

mitk::FiberBundleXMapper2D::FBXLocalStorage::FBXLocalStorage()
{
    m_PointActor = vtkSmartPointer<vtkActor>::New();
    m_PointMapper = vtkSmartPointer<vtkPolyDataMapper>::New();

}
<commit_msg>Missed output in a separate branch<commit_after>/*
 *  mitkFiberBundleMapper2D.cpp
 *  mitk-all
 *
 *  Created by HAL9000 on 1/17/11.
 *  Copyright 2011 __MyCompanyName__. All rights reserved.
 *
 */

#include "mitkFiberBundleXMapper2D.h"
#include <mitkBaseRenderer.h>

#include <vtkActor.h>
#include <vtkPolyDataMapper.h>
#include <vtkPlane.h>
#include <vtkPolyData.h>
//#include <vtkPropAssembly.h>

//#include <vtkPainterPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkLookupTable.h>
#include <vtkPoints.h>
#include <vtkCamera.h>
#include <vtkPolyLine.h>
#include <vtkRenderer.h>
#include <vtkCellArray.h>
#include <vtkMatrix4x4.h>

//#include <mitkGeometry3D.h>
#include <mitkPlaneGeometry.h>
#include <mitkSliceNavigationController.h>

#include <mitkShaderRepository.h>
#include <mitkShaderProperty.h>
#include <mitkStandardFileLocations.h>

#include <QCoreApplication>
#include <QFile>

mitk::FiberBundleXMapper2D::FiberBundleXMapper2D()
{
    m_lut = vtkLookupTable::New();
    m_lut->Build();

}

mitk::FiberBundleXMapper2D::~FiberBundleXMapper2D()
{
}

mitk::FiberBundleX* mitk::FiberBundleXMapper2D::GetInput()
{
    return dynamic_cast< mitk::FiberBundleX * > ( GetData() );
}

void mitk::FiberBundleXMapper2D::Update(mitk::BaseRenderer * renderer)
{

    if ( !this->IsVisible( renderer ) )
    {
        return;
    }

 MITK_DEBUG << "MapperFBX 2D  update: ";
    // Calculate time step of the input data for the specified renderer (integer value)
    // this method is implemented in mitkMapper
    this->CalculateTimeStep( renderer );

    //check if updates occured in the node or on the display
    FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);
    const DataNode *node = this->GetDataNode();
    if ( (localStorage->m_LastUpdateTime < node->GetMTime())
         || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified?
         || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) )
    {
        //    MITK_INFO << "UPDATE NEEDED FOR _ " << renderer->GetName();
        this->GenerateDataForRenderer( renderer );
    }

    if ((localStorage->m_LastUpdateTime < renderer->GetDisplayGeometry()->GetMTime()) ) //was the display geometry modified? e.g. zooming, panning)
    {

        this->UpdateShaderParameter(renderer);

    }

}

void mitk::FiberBundleXMapper2D::UpdateShaderParameter(mitk::BaseRenderer * renderer)
{
    FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);

    //get information about current position of views
    mitk::SliceNavigationController::Pointer sliceContr = renderer->GetSliceNavigationController();
    mitk::PlaneGeometry::ConstPointer planeGeo = sliceContr->GetCurrentPlaneGeometry();

    //generate according cutting planes based on the view position
    float sliceN[3], planeOrigin[3];

    // since shader uses camera coordinates, transform origin and normal from worldcoordinates to cameracoordinates

    planeOrigin[0] = (float) planeGeo->GetOrigin()[0];
    planeOrigin[1] = (float) planeGeo->GetOrigin()[1];
    planeOrigin[2] = (float) planeGeo->GetOrigin()[2];

    sliceN[0] = planeGeo->GetNormal()[0];
    sliceN[1] = planeGeo->GetNormal()[1];
    sliceN[2] = planeGeo->GetNormal()[2];

    float tmp1 = planeOrigin[0] * sliceN[0];
    float tmp2 = planeOrigin[1] * sliceN[1];
    float tmp3 = planeOrigin[2] * sliceN[2];
    float d1 = tmp1 + tmp2 + tmp3; //attention, correct normalvector

    float plane1[4];
    plane1[0] = sliceN[0];
    plane1[1] = sliceN[1];
    plane1[2] = sliceN[2];
    plane1[3] = d1;

    float thickness = 2.0;
    if(!this->GetDataNode()->GetPropertyValue("Fiber2DSliceThickness",thickness))
        MITK_INFO << "FIBER2D SLICE THICKNESS PROPERTY ERROR";

    bool fiberfading = false;
    if(!this->GetDataNode()->GetPropertyValue("Fiber2DfadeEFX",fiberfading))
        MITK_INFO << "FIBER2D SLICE FADE EFX PROPERTY ERROR";

    int fiberfading_i = 1;
    if (!fiberfading)
        fiberfading_i = 0;

    // set Opacity
    float fiberOpacity;
    this->GetDataNode()->GetOpacity(fiberOpacity, NULL);

    localStorage->m_PointActor->GetProperty()->AddShaderVariable("slicingPlane",4, plane1);
    localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberThickness",1, &thickness);
    localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberFadingON",1,  &fiberfading_i);
    localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberOpacity", 1, &fiberOpacity);

}

// ALL RAW DATA FOR VISUALIZATION IS GENERATED HERE.
// vtkActors and Mappers are feeded here
void mitk::FiberBundleXMapper2D::GenerateDataForRenderer(mitk::BaseRenderer *renderer)
{

    //the handler of local storage gets feeded in this method with requested data for related renderwindow
    FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);

    //this procedure is depricated,
    //not needed after initializaton anymore
    mitk::DataNode* node = this->GetDataNode();
    if ( node == NULL )
    {
        MITK_INFO << "check DATANODE: ....[Fail] ";
        return;
    }
    ///////////////////////////////////

    ///THIS GET INPUT
    mitk::FiberBundleX* fbx = this->GetInput();

    localStorage->m_PointMapper->ScalarVisibilityOn();
    localStorage->m_PointMapper->SetScalarModeToUsePointFieldData();
    localStorage->m_PointMapper->SetLookupTable(m_lut);  //apply the properties after the slice was set
    localStorage->m_PointActor->GetProperty()->SetOpacity(0.999);

    // set color
    if (fbx->GetCurrentColorCoding() != NULL){
//        localStorage->m_PointMapper->SelectColorArray("");
        localStorage->m_PointMapper->SelectColorArray(fbx->GetCurrentColorCoding());
        MITK_DEBUG << "MapperFBX 2D: " << fbx->GetCurrentColorCoding();

        if(fbx->GetCurrentColorCoding() == fbx->COLORCODING_CUSTOM){
            float temprgb[3];
            this->GetDataNode()->GetColor( temprgb, NULL );
            double trgb[3] = { (double) temprgb[0], (double) temprgb[1], (double) temprgb[2] };
            localStorage->m_PointActor->GetProperty()->SetColor(trgb);
        }
    }

    localStorage->m_PointMapper->SetInput(fbx->GetFiberPolyData());
    localStorage->m_PointActor->SetMapper(localStorage->m_PointMapper);
    localStorage->m_PointActor->GetProperty()->ShadingOn();

    // Applying shading properties
    {
        mitk::ShaderRepository::GetGlobalShaderRepository()->ApplyProperties(this->GetDataNode(),localStorage->m_PointActor,renderer, localStorage->m_LastUpdateTime);
    }

    this->UpdateShaderParameter(renderer);

    // We have been modified => save this for next Update()
    localStorage->m_LastUpdateTime.Modified();

}

vtkProp* mitk::FiberBundleXMapper2D::GetVtkProp(mitk::BaseRenderer *renderer)
{

    //MITK_INFO << "FiberBundleMapper2D GetVtkProp(renderer)";
    this->Update(renderer);
    return m_LSH.GetLocalStorage(renderer)->m_PointActor;

}

void mitk::FiberBundleXMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite)
{    //add shader to datano

    //####### load shader from file #########
    QString applicationDir = QCoreApplication::applicationDirPath();

    if (applicationDir.endsWith("bin"))
        applicationDir.append("/");
    else if (applicationDir.endsWith("MacOS"))
    {
        //on osx, check if path for installer or MITK development is needed
        applicationDir.append("/");
        QFile f( applicationDir+"FiberTrackingLUTBaryCoords.bin" );
        if( !f.exists() ) // if file does not exist, then look in MITK development build directory
            applicationDir.append("../../../");
    }else
        applicationDir.append("\\..\\");

    mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false );
    mitk::ShaderRepository::Pointer shaderRepository = mitk::ShaderRepository::GetGlobalShaderRepository();
    shaderRepository->LoadShader(mitk::StandardFileLocations::GetInstance()->FindFile("mitkShaderFiberClipping.xml"));

    //####################################################################
    node->SetProperty("shader",mitk::ShaderProperty::New("mitkShaderFiberClipping"));
    mitk::ShaderRepository::GetGlobalShaderRepository()->AddDefaultProperties(node,renderer,overwrite);

    //add other parameters to propertylist
    node->AddProperty( "Fiber2DSliceThickness", mitk::FloatProperty::New(2.0f), renderer, overwrite );
    node->AddProperty( "Fiber2DfadeEFX", mitk::BoolProperty::New(true), renderer, overwrite );

    Superclass::SetDefaultProperties(node, renderer, overwrite);
}

// following methods are essential, they actually call the GetVtkProp() method
// which returns the desired actors
void mitk::FiberBundleXMapper2D::MitkRenderOverlay(BaseRenderer* renderer)
{
    //   MITK_INFO << "FiberBundleMapper2D MitkRenderOVerlay(renderer)";
    if ( this->IsVisible(renderer)==false )
        return;

    if ( this->GetVtkProp(renderer)->GetVisibility() )
    {
        this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer());
    }
}

void mitk::FiberBundleXMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer)
{
    //  MITK_INFO << "FiberBundleMapper2D MitkRenderOpaqueGeometry(renderer)";
    if ( this->IsVisible( renderer )==false )
        return;

    if ( this->GetVtkProp(renderer)->GetVisibility() )
        this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() );
}
void mitk::FiberBundleXMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer)
{
    //  MITK_INFO << "FiberBundleMapper2D MitkRenderTranslucentGeometry(renderer)";
    if ( this->IsVisible(renderer)==false )
        return;

    //TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???
    if ( this->GetVtkProp(renderer)->GetVisibility() )
        this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer());

}
void mitk::FiberBundleXMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer)
{
    //  MITK_INFO << "FiberBundleMapper2D MitkRenderVolumentricGeometry(renderer)";
    if(IsVisible(renderer)==false)
        return;

    //TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer???
    if ( GetVtkProp(renderer)->GetVisibility() )
        this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer());

}

mitk::FiberBundleXMapper2D::FBXLocalStorage::FBXLocalStorage()
{
    m_PointActor = vtkSmartPointer<vtkActor>::New();
    m_PointMapper = vtkSmartPointer<vtkPolyDataMapper>::New();

}
<|endoftext|>


<commit_before>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2014 Michael Fink
//
/// \file CmdlineApp.cpp Command line app
//

// includes
#include "stdafx.h"
#include "CmdlineApp.hpp"
#include "Exception.hpp"
#include "CameraException.hpp"
#include "AppCommand.hpp"
#include "AppOptions.hpp"
#include "Event.hpp"
#include "CameraScriptProcessor.hpp"
#include "Instance.hpp"
#include "SourceInfo.hpp"
#include "SourceDevice.hpp"
#include "RemoteReleaseControl.hpp"
#include "ShutterReleaseSettings.hpp"
#include "Filesystem.hpp"
#include "CrashReporter.hpp"
#include "..\version.h"
#include <thread>

CmdlineApp::CmdlineApp()
{
   _tprintf(_T("RemotePhotoTool Command-Line %s\n%s\n\n"),
      _T(VERSIONINFO_FILEVERSION_DISPLAYSTRING),
      _T(VERSIONINFO_COPYRIGHT));
}

void CmdlineApp::InitCrashReporter()
{
   CString cszFolder = App_GetAppDataFolder(appDataUserNonRoaming) + _T("\\RemotePhotoToolCmdline\\");

   if (!Directory_Exists(cszFolder))
      CreateDirectory(cszFolder, NULL);

   cszFolder += _T("crashdumps\\");

   if (!Directory_Exists(cszFolder))
      CreateDirectory(cszFolder, NULL);

   CrashReporter::Init(cszFolder);
}

void CmdlineApp::Run(int argc, TCHAR* argv[])
{
   // parse options
   AppOptions options(m_vecCommandList);
   options.Parse(argc, argv);

   if (m_vecCommandList.empty())
   {
      options.OutputHelp();
      return;
   }

   if (options.IsSelectedHelpOption())
      return;

   // run command list
   std::for_each(m_vecCommandList.begin(), m_vecCommandList.end(), [&](const AppCommand& cmd)
   {
      try
      {
         Exec(cmd);
      }
      catch(const CameraException& ex)
      {
         _tprintf(_T("CameraException was thrown: \"%s\"\n"), ex.Message().GetString());
      }
      catch(const Exception& ex)
      {
         _tprintf(_T("Exception was thrown: \"%s\"\n"), ex.Message().GetString());
      }
   });
}

void CmdlineApp::Exec(const AppCommand& cmd)
{
   switch (cmd.m_enCommand)
   {
   case AppCommand::showVersion: PrintVersionInfo(); break;
   case AppCommand::listDevices: ListDevices(); break;
   case AppCommand::openDevice:  OpenByName(cmd.m_cszData); break;
   case AppCommand::closeDevice:
      m_spSourceDevice.reset();
      m_spReleaseControl.reset();
      break;
   case AppCommand::deviceInfo: OutputDeviceInfo(); break;
   case AppCommand::deviceProperties: ListDeviceProperties(); break;
   case AppCommand::imageProperties: ListImageProperties(); break;
   case AppCommand::listenEvents: ListenToEvents(); break;
   case AppCommand::releaseShutter: ReleaseShutter(); break;
   case AppCommand::runScript: RunScript(cmd.m_cszData); break;
   default:
      ATLASSERT(false);
      break;
   }
}

void CmdlineApp::PrintVersionInfo()
{
   _tprintf(_T("CanonControl version info\n\n"));

   Instance inst = Instance::Get();

   CString cszVersionInfo = inst.Version();

   _tprintf(_T("%s\n"), cszVersionInfo.GetString());
}

void CmdlineApp::ListDevices()
{
   _tprintf(_T("Devices list\n"));

   Instance inst = Instance::Get();

   std::vector<std::shared_ptr<SourceInfo>> vecSourceDevices;
   inst.EnumerateDevices(vecSourceDevices);

   if (vecSourceDevices.empty())
   {
      _tprintf(_T("No device found.\n"));
   }
   else
   {
      for (size_t i=0,iMax=vecSourceDevices.size(); i<iMax; i++)
      {
         std::shared_ptr<SourceInfo> spSourceInfo = vecSourceDevices[i];
         _tprintf(_T("Device %lu: \"%s\"\n"), i+1, spSourceInfo->Name().GetString());
      }
   }

   _tprintf(_T("\n"));
}

void CmdlineApp::OpenByName(const CString& cszName)
{
   Instance inst = Instance::Get();

   std::vector<std::shared_ptr<SourceInfo>> vecSourceDevices;
   inst.EnumerateDevices(vecSourceDevices);

   int iPosOpen = cszName.Find(_T('{'));
   int iPosClose = cszName.Find(_T('}'), iPosOpen + 1);
   if (iPosOpen != -1 && iPosClose != -1)
   {
      CString cszIndex = cszName.Mid(iPosOpen + 1, iPosClose - iPosOpen - 1);

      size_t iIndex = _tcstoul(cszIndex, nullptr, 10);

      if (iIndex >= vecSourceDevices.size())
         throw Exception(_T("Invalid index for camera"), __FILE__, __LINE__);

      std::shared_ptr<SourceInfo> spSourceInfo = vecSourceDevices[iIndex];

      _tprintf(_T("Opening camera: %s\n"), spSourceInfo->Name().GetString());

      m_spSourceDevice = spSourceInfo->Open();
      return;
   }

   for (size_t i=0,iMax=vecSourceDevices.size(); i<iMax; i++)
   {
      std::shared_ptr<SourceInfo> spSourceInfo = vecSourceDevices[i];
      if (spSourceInfo->Name() == cszName)
      {
         _tprintf(_T("Opening camera: %s\n"), spSourceInfo->Name().GetString());

         m_spSourceDevice = spSourceInfo->Open();
         return;
      }
   }

   throw Exception(_T("Couldn't find camera model: ") + cszName, __FILE__, __LINE__);
}

void CmdlineApp::OutputDeviceInfo()
{
   _tprintf(_T("Device info about \"%s\"\n"), m_spSourceDevice->ModelName().GetString());
   _tprintf(_T("Serial number \"%s\"\n"), m_spSourceDevice->SerialNumber().GetString());

   // output capabilities
   _tprintf(_T("Device capabilities\n"));
   bool bCanRelease = m_spSourceDevice->GetDeviceCapability(SourceDevice::capRemoteReleaseControl);
   bool bCanUseViewfinder = m_spSourceDevice->GetDeviceCapability(SourceDevice::capRemoteViewfinder);

   _tprintf(_T("can release shutter: %s\n"), bCanRelease ? _T("yes") : _T("no"));
   _tprintf(_T("can use remote viewfinder: %s\n"), bCanUseViewfinder ? _T("yes") : _T("no"));
   _tprintf(_T("\n"));
}

void CmdlineApp::ListDeviceProperties()
{
   // output device properties
   _tprintf(_T("Device properties\n"));

   std::vector<unsigned int> vecProperties = m_spSourceDevice->EnumDeviceProperties();

   for (size_t i=0, iMax=vecProperties.size(); i<iMax; i++)
   {
      unsigned int uiPropertyId = vecProperties[i];
      DeviceProperty dp = m_spSourceDevice->GetDeviceProperty(uiPropertyId);

      _tprintf(_T("Property \"%s\" (%04x)%s: %s (%s)\n"),
         dp.Name().GetString(),
         uiPropertyId,
         dp.IsReadOnly() ? _T(" [read-only]") : _T(""),
         dp.Value().ToString().GetString(),
         dp.AsString().GetString());

      std::vector<Variant> vecValidValues = dp.ValidValues();
      for (size_t j=0, jMax=vecValidValues.size(); j<jMax; j++)
      {
         _tprintf(_T("   Valid value: %s (%s)\n"),
            vecValidValues[j].ToString().GetString(),
            dp.ValueAsString(vecValidValues[j]).GetString());
      }
   }
   _tprintf(_T("\n"));
}

void CmdlineApp::ListImageProperties()
{
   _tprintf(_T("List image properties\n"));

   EnsureReleaseControl();

   std::vector<unsigned int> vecImageProperties = m_spReleaseControl->EnumImageProperties();
   if (vecImageProperties.empty())
   {
      _tprintf(_T("no image properties found.\n"));
   }
   else
   for (size_t i=0,iMax=vecImageProperties.size(); i<iMax; i++)
   {
      unsigned int uiPropertyId = vecImageProperties[i];

      ImageProperty ip = m_spReleaseControl->GetImageProperty(uiPropertyId);

      _tprintf(_T("Image property \"%s\" (%04x)%s: %s (%s)\n"),
         ip.Name().GetString(),
         uiPropertyId,
         ip.IsReadOnly() ? _T(" [read-only]") : _T(""),
         ip.Value().ToString().GetString(),
         ip.AsString().GetString());

      std::vector<ImageProperty> vecValues;
      m_spReleaseControl->EnumImagePropertyValues(vecImageProperties[i], vecValues);

      for (size_t j=0, jMax=vecValues.size(); j<jMax; j++)
      {
         const ImageProperty& ip2 = vecValues[j];
         _tprintf(_T("   Valid value: %s (%s)\n"),
            ip2.Value().ToString().GetString(),
            ip.ValueAsString(ip2.Value()).GetString());
      }
   }
}

void CmdlineApp::ListenToEvents()
{
   _tprintf(_T("Listens for events from camera\n"));

   EnsureReleaseControl();

   int iPropertyEvent = m_spReleaseControl->AddPropertyEventHandler(
      [&](RemoteReleaseControl::T_enPropertyEvent enPropertyEvent, unsigned int uiValue)
   {
      ImageProperty prop = m_spReleaseControl->GetImageProperty(uiValue);

      _tprintf(_T("Property%s changed: Id=%04x Name=%s Value=%s\n"),
         enPropertyEvent == RemoteReleaseControl::propEventPropertyChanged ? _T("") : _T(" desc."),
         uiValue,
         prop.Name().GetString(),
         prop.AsString().GetString());
   });

   int iStateEvent = m_spReleaseControl->AddStateEventHandler(
      [&](RemoteReleaseControl::T_enStateEvent enStateEvent, unsigned int uiValue)
   {
      _tprintf(_T("State changed: State=%s Value=%u\n"),
         enStateEvent == RemoteReleaseControl::stateEventCameraShutdown ? _T("CameraShutdown") :
         enStateEvent == RemoteReleaseControl::stateEventRotationAngle ? _T("RotationAngle") :
         enStateEvent == RemoteReleaseControl::stateEventMemoryCardSlotOpen ? _T("MemoryCardSlotOpen") :
         enStateEvent == RemoteReleaseControl::stateEventReleaseError ? _T("ReleaseError") :
         enStateEvent == RemoteReleaseControl::stateEventBulbExposureTime ? _T("BulbExposureTime") :
         enStateEvent == RemoteReleaseControl::stateEventInternalError ? _T("InternalError") :
         _T("???"),
         uiValue);
   });

   _tprintf(_T("Press any key to exit listening for events...\n\n"));

   // wait for key and run OnIdle() in the meantime
   Event evtStop(true, false);
   std::thread idleThread([&evtStop]()
   {
      (void)fgetc(stdin);
      evtStop.Set();
   });

   while (!evtStop.Wait(10))
      Instance::OnIdle();

   idleThread.join();

   m_spReleaseControl->RemovePropertyEventHandler(iPropertyEvent);
   m_spReleaseControl->RemoveStateEventHandler(iStateEvent);
}

void CmdlineApp::EnsureReleaseControl()
{
   if (m_spReleaseControl != nullptr)
      return;

   if (m_spSourceDevice == nullptr)
      throw Exception(_T("Source device not opened."), __FILE__, __LINE__);

   _tprintf(_T("Starting Remote Release Control\n"));

   m_spReleaseControl = m_spSourceDevice->EnterReleaseControl();
}

void CmdlineApp::ReleaseShutter()
{
   _tprintf(_T("Release shutter\n"));

   EnsureReleaseControl();

   unsigned int uiNumAvailShot = m_spReleaseControl->NumAvailableShots();
   _tprintf(_T("Memory for %u images available\n"), uiNumAvailShot);

   Event evtPictureTaken(true, false);
   ShutterReleaseSettings settings(
      ShutterReleaseSettings::saveToHost,
      std::bind(&Event::Set, &evtPictureTaken));

   m_spReleaseControl->SetReleaseSettings(settings);

   m_spReleaseControl->Release();

   evtPictureTaken.Wait();
}

void CmdlineApp::RunScript(const CString& cszFilename)
{
   _tprintf(_T("Loading script: %s\n"), cszFilename.GetString());

   CameraScriptProcessor proc;

   proc.SetOutputDebugStringHandler(
      [&](const CString& cszText){
         _tprintf(_T("%s"), cszText.GetString());
   });

   proc.LoadScript(cszFilename);

   proc.Run();

   _tprintf(_T("Press any key to abort running script.\n\n"));

   (void)fgetc(stdin);

   proc.Stop();
}
<commit_msg>fixed cppcheck message, formatting size_t with wrong format specifier<commit_after>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2014 Michael Fink
//
/// \file CmdlineApp.cpp Command line app
//

// includes
#include "stdafx.h"
#include "CmdlineApp.hpp"
#include "Exception.hpp"
#include "CameraException.hpp"
#include "AppCommand.hpp"
#include "AppOptions.hpp"
#include "Event.hpp"
#include "CameraScriptProcessor.hpp"
#include "Instance.hpp"
#include "SourceInfo.hpp"
#include "SourceDevice.hpp"
#include "RemoteReleaseControl.hpp"
#include "ShutterReleaseSettings.hpp"
#include "Filesystem.hpp"
#include "CrashReporter.hpp"
#include "..\version.h"
#include <thread>

CmdlineApp::CmdlineApp()
{
   _tprintf(_T("RemotePhotoTool Command-Line %s\n%s\n\n"),
      _T(VERSIONINFO_FILEVERSION_DISPLAYSTRING),
      _T(VERSIONINFO_COPYRIGHT));
}

void CmdlineApp::InitCrashReporter()
{
   CString cszFolder = App_GetAppDataFolder(appDataUserNonRoaming) + _T("\\RemotePhotoToolCmdline\\");

   if (!Directory_Exists(cszFolder))
      CreateDirectory(cszFolder, NULL);

   cszFolder += _T("crashdumps\\");

   if (!Directory_Exists(cszFolder))
      CreateDirectory(cszFolder, NULL);

   CrashReporter::Init(cszFolder);
}

void CmdlineApp::Run(int argc, TCHAR* argv[])
{
   // parse options
   AppOptions options(m_vecCommandList);
   options.Parse(argc, argv);

   if (m_vecCommandList.empty())
   {
      options.OutputHelp();
      return;
   }

   if (options.IsSelectedHelpOption())
      return;

   // run command list
   std::for_each(m_vecCommandList.begin(), m_vecCommandList.end(), [&](const AppCommand& cmd)
   {
      try
      {
         Exec(cmd);
      }
      catch(const CameraException& ex)
      {
         _tprintf(_T("CameraException was thrown: \"%s\"\n"), ex.Message().GetString());
      }
      catch(const Exception& ex)
      {
         _tprintf(_T("Exception was thrown: \"%s\"\n"), ex.Message().GetString());
      }
   });
}

void CmdlineApp::Exec(const AppCommand& cmd)
{
   switch (cmd.m_enCommand)
   {
   case AppCommand::showVersion: PrintVersionInfo(); break;
   case AppCommand::listDevices: ListDevices(); break;
   case AppCommand::openDevice:  OpenByName(cmd.m_cszData); break;
   case AppCommand::closeDevice:
      m_spSourceDevice.reset();
      m_spReleaseControl.reset();
      break;
   case AppCommand::deviceInfo: OutputDeviceInfo(); break;
   case AppCommand::deviceProperties: ListDeviceProperties(); break;
   case AppCommand::imageProperties: ListImageProperties(); break;
   case AppCommand::listenEvents: ListenToEvents(); break;
   case AppCommand::releaseShutter: ReleaseShutter(); break;
   case AppCommand::runScript: RunScript(cmd.m_cszData); break;
   default:
      ATLASSERT(false);
      break;
   }
}

void CmdlineApp::PrintVersionInfo()
{
   _tprintf(_T("CanonControl version info\n\n"));

   Instance inst = Instance::Get();

   CString cszVersionInfo = inst.Version();

   _tprintf(_T("%s\n"), cszVersionInfo.GetString());
}

void CmdlineApp::ListDevices()
{
   _tprintf(_T("Devices list\n"));

   Instance inst = Instance::Get();

   std::vector<std::shared_ptr<SourceInfo>> vecSourceDevices;
   inst.EnumerateDevices(vecSourceDevices);

   if (vecSourceDevices.empty())
   {
      _tprintf(_T("No device found.\n"));
   }
   else
   {
      for (size_t i=0,iMax=vecSourceDevices.size(); i<iMax; i++)
      {
         std::shared_ptr<SourceInfo> spSourceInfo = vecSourceDevices[i];
         _tprintf(_T("Device %Iu: \"%s\"\n"), i+1, spSourceInfo->Name().GetString());
      }
   }

   _tprintf(_T("\n"));
}

void CmdlineApp::OpenByName(const CString& cszName)
{
   Instance inst = Instance::Get();

   std::vector<std::shared_ptr<SourceInfo>> vecSourceDevices;
   inst.EnumerateDevices(vecSourceDevices);

   int iPosOpen = cszName.Find(_T('{'));
   int iPosClose = cszName.Find(_T('}'), iPosOpen + 1);
   if (iPosOpen != -1 && iPosClose != -1)
   {
      CString cszIndex = cszName.Mid(iPosOpen + 1, iPosClose - iPosOpen - 1);

      size_t iIndex = _tcstoul(cszIndex, nullptr, 10);

      if (iIndex >= vecSourceDevices.size())
         throw Exception(_T("Invalid index for camera"), __FILE__, __LINE__);

      std::shared_ptr<SourceInfo> spSourceInfo = vecSourceDevices[iIndex];

      _tprintf(_T("Opening camera: %s\n"), spSourceInfo->Name().GetString());

      m_spSourceDevice = spSourceInfo->Open();
      return;
   }

   for (size_t i=0,iMax=vecSourceDevices.size(); i<iMax; i++)
   {
      std::shared_ptr<SourceInfo> spSourceInfo = vecSourceDevices[i];
      if (spSourceInfo->Name() == cszName)
      {
         _tprintf(_T("Opening camera: %s\n"), spSourceInfo->Name().GetString());

         m_spSourceDevice = spSourceInfo->Open();
         return;
      }
   }

   throw Exception(_T("Couldn't find camera model: ") + cszName, __FILE__, __LINE__);
}

void CmdlineApp::OutputDeviceInfo()
{
   _tprintf(_T("Device info about \"%s\"\n"), m_spSourceDevice->ModelName().GetString());
   _tprintf(_T("Serial number \"%s\"\n"), m_spSourceDevice->SerialNumber().GetString());

   // output capabilities
   _tprintf(_T("Device capabilities\n"));
   bool bCanRelease = m_spSourceDevice->GetDeviceCapability(SourceDevice::capRemoteReleaseControl);
   bool bCanUseViewfinder = m_spSourceDevice->GetDeviceCapability(SourceDevice::capRemoteViewfinder);

   _tprintf(_T("can release shutter: %s\n"), bCanRelease ? _T("yes") : _T("no"));
   _tprintf(_T("can use remote viewfinder: %s\n"), bCanUseViewfinder ? _T("yes") : _T("no"));
   _tprintf(_T("\n"));
}

void CmdlineApp::ListDeviceProperties()
{
   // output device properties
   _tprintf(_T("Device properties\n"));

   std::vector<unsigned int> vecProperties = m_spSourceDevice->EnumDeviceProperties();

   for (size_t i=0, iMax=vecProperties.size(); i<iMax; i++)
   {
      unsigned int uiPropertyId = vecProperties[i];
      DeviceProperty dp = m_spSourceDevice->GetDeviceProperty(uiPropertyId);

      _tprintf(_T("Property \"%s\" (%04x)%s: %s (%s)\n"),
         dp.Name().GetString(),
         uiPropertyId,
         dp.IsReadOnly() ? _T(" [read-only]") : _T(""),
         dp.Value().ToString().GetString(),
         dp.AsString().GetString());

      std::vector<Variant> vecValidValues = dp.ValidValues();
      for (size_t j=0, jMax=vecValidValues.size(); j<jMax; j++)
      {
         _tprintf(_T("   Valid value: %s (%s)\n"),
            vecValidValues[j].ToString().GetString(),
            dp.ValueAsString(vecValidValues[j]).GetString());
      }
   }
   _tprintf(_T("\n"));
}

void CmdlineApp::ListImageProperties()
{
   _tprintf(_T("List image properties\n"));

   EnsureReleaseControl();

   std::vector<unsigned int> vecImageProperties = m_spReleaseControl->EnumImageProperties();
   if (vecImageProperties.empty())
   {
      _tprintf(_T("no image properties found.\n"));
   }
   else
   for (size_t i=0,iMax=vecImageProperties.size(); i<iMax; i++)
   {
      unsigned int uiPropertyId = vecImageProperties[i];

      ImageProperty ip = m_spReleaseControl->GetImageProperty(uiPropertyId);

      _tprintf(_T("Image property \"%s\" (%04x)%s: %s (%s)\n"),
         ip.Name().GetString(),
         uiPropertyId,
         ip.IsReadOnly() ? _T(" [read-only]") : _T(""),
         ip.Value().ToString().GetString(),
         ip.AsString().GetString());

      std::vector<ImageProperty> vecValues;
      m_spReleaseControl->EnumImagePropertyValues(vecImageProperties[i], vecValues);

      for (size_t j=0, jMax=vecValues.size(); j<jMax; j++)
      {
         const ImageProperty& ip2 = vecValues[j];
         _tprintf(_T("   Valid value: %s (%s)\n"),
            ip2.Value().ToString().GetString(),
            ip.ValueAsString(ip2.Value()).GetString());
      }
   }
}

void CmdlineApp::ListenToEvents()
{
   _tprintf(_T("Listens for events from camera\n"));

   EnsureReleaseControl();

   int iPropertyEvent = m_spReleaseControl->AddPropertyEventHandler(
      [&](RemoteReleaseControl::T_enPropertyEvent enPropertyEvent, unsigned int uiValue)
   {
      ImageProperty prop = m_spReleaseControl->GetImageProperty(uiValue);

      _tprintf(_T("Property%s changed: Id=%04x Name=%s Value=%s\n"),
         enPropertyEvent == RemoteReleaseControl::propEventPropertyChanged ? _T("") : _T(" desc."),
         uiValue,
         prop.Name().GetString(),
         prop.AsString().GetString());
   });

   int iStateEvent = m_spReleaseControl->AddStateEventHandler(
      [&](RemoteReleaseControl::T_enStateEvent enStateEvent, unsigned int uiValue)
   {
      _tprintf(_T("State changed: State=%s Value=%u\n"),
         enStateEvent == RemoteReleaseControl::stateEventCameraShutdown ? _T("CameraShutdown") :
         enStateEvent == RemoteReleaseControl::stateEventRotationAngle ? _T("RotationAngle") :
         enStateEvent == RemoteReleaseControl::stateEventMemoryCardSlotOpen ? _T("MemoryCardSlotOpen") :
         enStateEvent == RemoteReleaseControl::stateEventReleaseError ? _T("ReleaseError") :
         enStateEvent == RemoteReleaseControl::stateEventBulbExposureTime ? _T("BulbExposureTime") :
         enStateEvent == RemoteReleaseControl::stateEventInternalError ? _T("InternalError") :
         _T("???"),
         uiValue);
   });

   _tprintf(_T("Press any key to exit listening for events...\n\n"));

   // wait for key and run OnIdle() in the meantime
   Event evtStop(true, false);
   std::thread idleThread([&evtStop]()
   {
      (void)fgetc(stdin);
      evtStop.Set();
   });

   while (!evtStop.Wait(10))
      Instance::OnIdle();

   idleThread.join();

   m_spReleaseControl->RemovePropertyEventHandler(iPropertyEvent);
   m_spReleaseControl->RemoveStateEventHandler(iStateEvent);
}

void CmdlineApp::EnsureReleaseControl()
{
   if (m_spReleaseControl != nullptr)
      return;

   if (m_spSourceDevice == nullptr)
      throw Exception(_T("Source device not opened."), __FILE__, __LINE__);

   _tprintf(_T("Starting Remote Release Control\n"));

   m_spReleaseControl = m_spSourceDevice->EnterReleaseControl();
}

void CmdlineApp::ReleaseShutter()
{
   _tprintf(_T("Release shutter\n"));

   EnsureReleaseControl();

   unsigned int uiNumAvailShot = m_spReleaseControl->NumAvailableShots();
   _tprintf(_T("Memory for %u images available\n"), uiNumAvailShot);

   Event evtPictureTaken(true, false);
   ShutterReleaseSettings settings(
      ShutterReleaseSettings::saveToHost,
      std::bind(&Event::Set, &evtPictureTaken));

   m_spReleaseControl->SetReleaseSettings(settings);

   m_spReleaseControl->Release();

   evtPictureTaken.Wait();
}

void CmdlineApp::RunScript(const CString& cszFilename)
{
   _tprintf(_T("Loading script: %s\n"), cszFilename.GetString());

   CameraScriptProcessor proc;

   proc.SetOutputDebugStringHandler(
      [&](const CString& cszText){
         _tprintf(_T("%s"), cszText.GetString());
   });

   proc.LoadScript(cszFilename);

   proc.Run();

   _tprintf(_T("Press any key to abort running script.\n\n"));

   (void)fgetc(stdin);

   proc.Stop();
}
<|endoftext|>


<commit_before><commit_msg>Fix BMC 21651 - [REG] New tab on wrench menu is not working when bookmark manager or download manager is open<commit_after><|endoftext|>


<commit_before><commit_msg>Looks like the fix I did last time did work. According to the flakiness dashboard this hasn't failed since the day I checked in the fix (Jan 26th).<commit_after><|endoftext|>


<commit_before><commit_msg>Disable test while investigating. TBR=amit<commit_after><|endoftext|>


<commit_before>
#include <gtest/gtest.h>
#include <Unittests/unittests_common.hh>

namespace {

class OpenMeshReadWriteSTL : public OpenMeshBase {

    protected:

        // This function is called before each test is run
        virtual void SetUp() {

            // Do some initial stuff with the member data here...
        }

        // This function is called after all tests are through
        virtual void TearDown() {

            // Do some final stuff with the member data here...
        }

    // Member already defined in OpenMeshBase
    //Mesh mesh_;
};

/*
 * ====================================================================
 * Define tests below
 * ====================================================================
 */

/*
 * Just load a simple mesh file in stla format and count whether
 * the right number of entities has been loaded.
 */
TEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLFile) {

    mesh_.clear();

    bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.stl");

    EXPECT_TRUE(ok);

    EXPECT_EQ(7526u  , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
    EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
    EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";
}

/*
 * Just load a simple mesh file in stla format and count whether
 * the right number of entities has been loaded. Also check facet normals.
 */
TEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLFileWithNormals) {

    mesh_.clear();
    mesh_.request_face_normals();

    OpenMesh::IO::Options opt;
    opt += OpenMesh::IO::Options::FaceNormal;

    bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.stl", opt);

    EXPECT_TRUE(ok);

    EXPECT_TRUE(opt.face_has_normal());
    EXPECT_FALSE(opt.vertex_has_normal());

    EXPECT_NEAR(-0.038545f, mesh_.normal(mesh_.face_handle(0))[0], 0.0001 ) << "Wrong face normal at face 0 component 0";
    EXPECT_NEAR(-0.004330f, mesh_.normal(mesh_.face_handle(0))[1], 0.0001 ) << "Wrong face normal at face 0 component 1";
    EXPECT_NEAR(0.999247f, mesh_.normal(mesh_.face_handle(0))[2], 0.0001 ) << "Wrong face normal at face 0 component 2";

    EXPECT_EQ(7526u  , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
    EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
    EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";

    mesh_.release_face_normals();
}

/*
 * Just load a simple mesh file in stlb format and count whether
 * the right number of entities has been loaded.
 */
TEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLBinaryFile) {

    mesh_.clear();

    bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1Binary.stl");

    EXPECT_TRUE(ok);

    EXPECT_EQ(7526u  , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
    EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
    EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";
}

/*
 * Just load a simple mesh file in stlb format and count whether
 * the right number of entities has been loaded. Also check facet normals.
 */
TEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLBinaryFileWithNormals) {

    mesh_.clear();
    mesh_.request_face_normals();

    OpenMesh::IO::Options opt;
    opt += OpenMesh::IO::Options::FaceNormal;
    opt += OpenMesh::IO::Options::Binary;

    bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1Binary.stl", opt);

    EXPECT_TRUE(ok);

    EXPECT_TRUE(opt.is_binary());
    EXPECT_TRUE(opt.face_has_normal());
    EXPECT_FALSE(opt.vertex_has_normal());

    EXPECT_NEAR(-0.038545f, mesh_.normal(mesh_.face_handle(0))[0], 0.0001 ) << "Wrong face normal at face 0 component 0";
    EXPECT_NEAR(-0.004330f, mesh_.normal(mesh_.face_handle(0))[1], 0.0001 ) << "Wrong face normal at face 0 component 1";
    EXPECT_NEAR(0.999247f, mesh_.normal(mesh_.face_handle(0))[2], 0.0001 ) << "Wrong face normal at face 0 component 2";

    EXPECT_EQ(7526u  , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
    EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
    EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";

    mesh_.release_face_normals();
}

}
<commit_msg>add write unittest for binary files<commit_after>
#include <gtest/gtest.h>
#include <Unittests/unittests_common.hh>

namespace {

class OpenMeshReadWriteSTL : public OpenMeshBase {

    protected:

        // This function is called before each test is run
        virtual void SetUp() {

            // Do some initial stuff with the member data here...
        }

        // This function is called after all tests are through
        virtual void TearDown() {

            // Do some final stuff with the member data here...
        }

    // Member already defined in OpenMeshBase
    //Mesh mesh_;
};

/*
 * ====================================================================
 * Define tests below
 * ====================================================================
 */

/*
 * Just load a simple mesh file in stla format and count whether
 * the right number of entities has been loaded.
 */
TEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLFile) {

    mesh_.clear();

    bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.stl");

    EXPECT_TRUE(ok);

    EXPECT_EQ(7526u  , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
    EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
    EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";
}

/*
 * Just load a simple mesh file in stla format and count whether
 * the right number of entities has been loaded. Also check facet normals.
 */
TEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLFileWithNormals) {

    mesh_.clear();
    mesh_.request_face_normals();

    OpenMesh::IO::Options opt;
    opt += OpenMesh::IO::Options::FaceNormal;

    bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.stl", opt);

    EXPECT_TRUE(ok);

    EXPECT_TRUE(opt.face_has_normal());
    EXPECT_FALSE(opt.vertex_has_normal());

    EXPECT_NEAR(-0.038545f, mesh_.normal(mesh_.face_handle(0))[0], 0.0001 ) << "Wrong face normal at face 0 component 0";
    EXPECT_NEAR(-0.004330f, mesh_.normal(mesh_.face_handle(0))[1], 0.0001 ) << "Wrong face normal at face 0 component 1";
    EXPECT_NEAR(0.999247f, mesh_.normal(mesh_.face_handle(0))[2], 0.0001 ) << "Wrong face normal at face 0 component 2";

    EXPECT_EQ(7526u  , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
    EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
    EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";

    mesh_.release_face_normals();
}

/*
 * Just load a simple mesh file in stlb format and count whether
 * the right number of entities has been loaded.
 */
TEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLBinaryFile) {

    mesh_.clear();

    bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1Binary.stl");

    EXPECT_TRUE(ok);

    EXPECT_EQ(7526u  , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
    EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
    EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";
}

/*
 * Just load a simple mesh file in stlb format and count whether
 * the right number of entities has been loaded. Also check facet normals.
 */
TEST_F(OpenMeshReadWriteSTL, LoadSimpleSTLBinaryFileWithNormals) {

    mesh_.clear();
    mesh_.request_face_normals();

    OpenMesh::IO::Options opt;
    opt += OpenMesh::IO::Options::FaceNormal;
    opt += OpenMesh::IO::Options::Binary;

    bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1Binary.stl", opt);

    EXPECT_TRUE(ok);

    EXPECT_TRUE(opt.is_binary());
    EXPECT_TRUE(opt.face_has_normal());
    EXPECT_FALSE(opt.vertex_has_normal());

    EXPECT_NEAR(-0.038545f, mesh_.normal(mesh_.face_handle(0))[0], 0.0001 ) << "Wrong face normal at face 0 component 0";
    EXPECT_NEAR(-0.004330f, mesh_.normal(mesh_.face_handle(0))[1], 0.0001 ) << "Wrong face normal at face 0 component 1";
    EXPECT_NEAR(0.999247f, mesh_.normal(mesh_.face_handle(0))[2], 0.0001 ) << "Wrong face normal at face 0 component 2";

    EXPECT_EQ(7526u  , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
    EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
    EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";

    mesh_.release_face_normals();
}

/*
 * Read and Write stl binary file
 */
TEST_F(OpenMeshReadWriteSTL, ReadWriteSimpleSTLBinaryFile) {

    mesh_.clear();

    OpenMesh::IO::Options opt;
    opt += OpenMesh::IO::Options::Binary;

    bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1Binary.stl");

    EXPECT_TRUE(ok);

    const char* filename = "cube1Binary_openmeshWriteTestFile.stl";

    ok = OpenMesh::IO::write_mesh(mesh_, filename, opt);

    EXPECT_TRUE(ok);

    ok = OpenMesh::IO::read_mesh(mesh_, filename, opt);

    EXPECT_TRUE(ok);

    EXPECT_EQ(7526u  , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
    EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
    EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";

    remove(filename);
}

/*
 * Just load a simple mesh file in stlb format and count whether
 * the right number of entities has been loaded. Also check facet normals.
 */
TEST_F(OpenMeshReadWriteSTL, ReadWriteSimpleSTLBinaryFileWithNormals) {

    mesh_.clear();
    mesh_.request_face_normals();

    OpenMesh::IO::Options opt;
    opt += OpenMesh::IO::Options::FaceNormal;
    opt += OpenMesh::IO::Options::Binary;

    bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1Binary.stl", opt);

    EXPECT_TRUE(ok);

    const char* filename = "cube1BinaryNormal_openmeshWriteTestFile.stl";

    ok = OpenMesh::IO::write_mesh(mesh_, filename, opt);

    EXPECT_TRUE(ok);

    ok = OpenMesh::IO::read_mesh(mesh_, filename, opt);

    EXPECT_TRUE(ok);

    EXPECT_TRUE(opt.is_binary());
    EXPECT_TRUE(opt.face_has_normal());
    EXPECT_FALSE(opt.vertex_has_normal());

    EXPECT_NEAR(-0.038545f, mesh_.normal(mesh_.face_handle(0))[0], 0.0001 ) << "Wrong face normal at face 0 component 0";
    EXPECT_NEAR(-0.004330f, mesh_.normal(mesh_.face_handle(0))[1], 0.0001 ) << "Wrong face normal at face 0 component 1";
    EXPECT_NEAR(0.999247f, mesh_.normal(mesh_.face_handle(0))[2], 0.0001 ) << "Wrong face normal at face 0 component 2";

    EXPECT_EQ(7526u  , mesh_.n_vertices()) << "The number of loaded vertices is not correct!";
    EXPECT_EQ(22572u , mesh_.n_edges()) << "The number of loaded edges is not correct!";
    EXPECT_EQ(15048u , mesh_.n_faces()) << "The number of loaded faces is not correct!";

    mesh_.release_face_normals();
    remove(filename);
}

}
<|endoftext|>


<commit_before><commit_msg>nit: spacing<commit_after><|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkShiftScaleLabelMapFilterTest1.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

  Portions of this code are covered under the VTK copyright.
  See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

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

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSimpleFilterWatcher.h"

#include "itkLabelObject.h"
#include "itkLabelMap.h"
#include "itkLabelImageToLabelMapFilter.h"
#include "itkShiftScaleLabelMapFilter.h"
#include "itkLabelMapToLabelImageFilter.h"

#include "itkTestingMacros.h"

int itkShiftScaleLabelMapFilterTest1(int argc, char * argv[])
{

  if( argc != 6 )
    {
    std::cerr << "usage: " << argv[0] << " input output shift scale change_bg" << std::endl;
    return EXIT_FAILURE;
    }

  const unsigned int dim = 2;

  typedef itk::Image< unsigned char, dim > ImageType;

  typedef itk::LabelObject< unsigned char, dim > LabelObjectType;
  typedef itk::LabelMap< LabelObjectType >       LabelMapType;

  typedef itk::ImageFileReader< ImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );

  typedef itk::LabelImageToLabelMapFilter< ImageType, LabelMapType> I2LType;
  I2LType::Pointer i2l = I2LType::New();
  i2l->SetInput( reader->GetOutput() );

  typedef itk::ShiftScaleLabelMapFilter< LabelMapType > ChangeType;
  ChangeType::Pointer change = ChangeType::New();
  change->SetInput( i2l->GetOutput() );
  change->SetShift( atof(argv[3]) );
  change->SetScale( atof(argv[4]) );
  change->SetChangeBackgroundValue( atoi(argv[5]) );
  itk::SimpleFilterWatcher watcher6(change, "filter");

  typedef itk::LabelMapToLabelImageFilter< LabelMapType, ImageType> L2IType;
  L2IType::Pointer l2i = L2IType::New();
  l2i->SetInput( change->GetOutput() );

  typedef itk::ImageFileWriter< ImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetInput( l2i->GetOutput() );
  writer->SetFileName( argv[2] );
  writer->UseCompressionOn();

  TRY_EXPECT_NO_EXCEPTION( writer->Update() );

  return EXIT_SUCCESS;
}
<commit_msg>BUG: Clarified use of ChangeBackgroundValue as a boolean.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkShiftScaleLabelMapFilterTest1.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

  Portions of this code are covered under the VTK copyright.
  See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

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

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSimpleFilterWatcher.h"

#include "itkLabelObject.h"
#include "itkLabelMap.h"
#include "itkLabelImageToLabelMapFilter.h"
#include "itkShiftScaleLabelMapFilter.h"
#include "itkLabelMapToLabelImageFilter.h"

#include "itkTestingMacros.h"

int itkShiftScaleLabelMapFilterTest1(int argc, char * argv[])
{

  if( argc != 6 )
    {
    std::cerr << "usage: " << argv[0] << " input output shift scale change_bg" << std::endl;
    return EXIT_FAILURE;
    }

  const unsigned int dim = 2;

  typedef itk::Image< unsigned char, dim > ImageType;

  typedef itk::LabelObject< unsigned char, dim > LabelObjectType;
  typedef itk::LabelMap< LabelObjectType >       LabelMapType;

  typedef itk::ImageFileReader< ImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );

  typedef itk::LabelImageToLabelMapFilter< ImageType, LabelMapType> I2LType;
  I2LType::Pointer i2l = I2LType::New();
  i2l->SetInput( reader->GetOutput() );

  typedef itk::ShiftScaleLabelMapFilter< LabelMapType > ChangeType;
  ChangeType::Pointer change = ChangeType::New();
  change->SetInput( i2l->GetOutput() );
  change->SetShift( atof(argv[3]) );
  change->SetScale( atof(argv[4]) );
  bool changeBackground = atoi(argv[5]);
  change->SetChangeBackgroundValue( changeBackground );
  itk::SimpleFilterWatcher watcher6(change, "filter");

  typedef itk::LabelMapToLabelImageFilter< LabelMapType, ImageType> L2IType;
  L2IType::Pointer l2i = L2IType::New();
  l2i->SetInput( change->GetOutput() );

  typedef itk::ImageFileWriter< ImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetInput( l2i->GetOutput() );
  writer->SetFileName( argv[2] );
  writer->UseCompressionOn();

  TRY_EXPECT_NO_EXCEPTION( writer->Update() );

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before><commit_msg>Revert -r47806 which had negative consequences (failing to handle properly #ifdef at the beginning of an unnamed script and making it much harder to update roottest to work around missing feature in cling)<commit_after><|endoftext|>


<commit_before>/*
 * itkVectorImageRepresenterTest.cpp
 *
 *  Created on: May 3, 2012
 *      Author: luethi
 */

#include "itkVectorImageRepresenter.h"
#include "genericRepresenterTest.hxx"

typedef itk::Image< itk::Vector<float, 2> ,2 > VectorImageType;
typedef itk::VectorImageRepresenter<float, 2, 2> RepresenterType;

typedef GenericRepresenterTest<RepresenterType> RepresenterTestType;

VectorImageType::Pointer loadVectorImage(const std::string& filename) {
	itk::ImageFileReader<VectorImageType>::Pointer reader = itk::ImageFileReader<VectorImageType>::New();
	reader->SetFileName(filename);
	reader->Update();
	VectorImageType::Pointer img = reader->GetOutput();
	img->DisconnectPipeline();
	return img;
}

int main(int argc, char** argv) {
	if (argc < 2) {
		std::cout << "Usage: " << argv[0] << " datadir" << std::endl;
		exit(EXIT_FAILURE);
	}
	std::string datadir = std::string(argv[1]);

	const std::string referenceFilename = datadir + "/hand_dfs/df-hand-1.vtk";
	const std::string testDatasetFilename = datadir + "/hand_dfs/df-hand-2.vtk";

	RepresenterType::Pointer representer = RepresenterType::New();
	VectorImageType::Pointer reference = loadVectorImage(referenceFilename);
	representer->SetReference(reference);

	// choose a test dataset, a point and its associate pixel value

	VectorImageType::Pointer testDataset = loadVectorImage(testDatasetFilename);
	VectorImageType::IndexType idx;
	idx.Fill(0);
	VectorImageType::PointType testPt;
	testDataset->TransformIndexToPhysicalPoint(idx, testPt);
	VectorImageType::PixelType testValue = testDataset->GetPixel(idx);

	RepresenterTestType representerTest(representer, testDataset, std::make_pair(testPt, testValue));

	if (representerTest.runAllTests() == true) {
		return EXIT_SUCCESS;
	}
	else {
		return EXIT_FAILURE;
	}

}

<commit_msg>fixed bug: testPoint must be taken from reference and not from testData<commit_after>/*
 * itkVectorImageRepresenterTest.cpp
 *
 *  Created on: May 3, 2012
 *      Author: luethi
 */

#include "itkVectorImageRepresenter.h"
#include "genericRepresenterTest.hxx"

typedef itk::Image< itk::Vector<float, 2> ,2 > VectorImageType;
typedef itk::VectorImageRepresenter<float, 2, 2> RepresenterType;

typedef GenericRepresenterTest<RepresenterType> RepresenterTestType;

VectorImageType::Pointer loadVectorImage(const std::string& filename) {
	itk::ImageFileReader<VectorImageType>::Pointer reader = itk::ImageFileReader<VectorImageType>::New();
	reader->SetFileName(filename);
	reader->Update();
	VectorImageType::Pointer img = reader->GetOutput();
	img->DisconnectPipeline();
	return img;
}

int main(int argc, char** argv) {
	if (argc < 2) {
		std::cout << "Usage: " << argv[0] << " datadir" << std::endl;
		exit(EXIT_FAILURE);
	}
	std::string datadir = std::string(argv[1]);

	const std::string referenceFilename = datadir + "/hand_dfs/df-hand-1.vtk";
	const std::string testDatasetFilename = datadir + "/hand_dfs/df-hand-2.vtk";

	RepresenterType::Pointer representer = RepresenterType::New();
	VectorImageType::Pointer reference = loadVectorImage(referenceFilename);
	representer->SetReference(reference);

	// choose a test dataset, a point and its associate pixel value

	VectorImageType::Pointer testDataset = loadVectorImage(testDatasetFilename);
	VectorImageType::IndexType idx;
	idx.Fill(0);
	VectorImageType::PointType testPt;
	reference->TransformIndexToPhysicalPoint(idx, testPt);
	VectorImageType::PixelType testValue = testDataset->GetPixel(idx);

	RepresenterTestType representerTest(representer, testDataset, std::make_pair(testPt, testValue));

	if (representerTest.runAllTests() == true) {
		return EXIT_SUCCESS;
	}
	else {
		return EXIT_FAILURE;
	}

}

<|endoftext|>


<commit_before>#include "decafs_barista.h"

int main (int argc, char *argv[]) {
  barista_core_init (argc, argv);
  printf ("Barista is initialized.\n");
  printf ("\tstripe_size: %d\n\tchunk_size: %d\n\n", get_stripe_size(),
           get_chunk_size());

  int port = 0;
  if (argc >= MIN_ARGS) {
    port = atoi(argv[PORT]);
    printf("got port: %d\n", port);
  } else {
    fprintf(stderr, "port number not specified\n");
    exit(-1);
  }

  BaristaServer *barista_server = BaristaServer::init(port);
  barista_server->run();

  /* TEST CODE */
  /*struct ip_address ip;
  struct client default_client = {ip, 1, 1};
  int count, fd = open_file ("new_file.txt", O_RDWR, default_client);
  char buf[] = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100";
  char *read_buf = (char *)malloc (1000);
  memset (read_buf, '\0', 1000);
  printf ("\n\n ------------------------------FIRST WRITE------------------------------\n");
  count = write_file (fd, buf, strlen (buf), default_client);
  printf ("(\n(BARISTA) wrote %d bytes.\n", count);

  close_file (fd, default_client);
  fd = open_file ("new_file.txt", O_RDONLY, default_client);

  printf ("\n\n ------------------------------FIRST READ--------------------------------\n");
  count = read_file (fd, read_buf, strlen (buf), default_client);
  printf ("\n(BARISTA) Read %d bytes.\n", count);
  printf ("(BARISTA) Buf is:\n%s\n", read_buf);

  close_file (fd, default_client);
  fd = open_file ("new_file.txt", O_RDWR | O_APPEND, default_client);

  printf ("\n\n ------------------------------SECOND WRITE------------------------------\n");
  write_file (fd, buf, strlen (buf), default_client);

  close_file (fd, default_client);
  fd = open_file ("new_file.txt", O_RDONLY, default_client);

  printf ("\n\n ------------------------------SECOND READ--------------------------------\n");
  count = read_file (fd, read_buf, 2*strlen (buf), default_client);
  printf ("\n(BARISTA) Read %d bytes.\n", count);
  printf ("(BARISTA) Buf is:\n%s\n", read_buf);*/
  return 0;
}

<commit_msg>added logging to decafs_barista main<commit_after>#include "decafs_barista.h"

int main (int argc, char *argv[]) {

  printf("DecafsBarista: initializing barista_core\n");
  barista_core_init (argc, argv);
  printf ("Barista is initialized.\n");
  printf ("\tstripe_size: %d\n\tchunk_size: %d\n\n", get_stripe_size(),
           get_chunk_size());
  printf("DecafsBarista: barista_core initialized\n");

  int port = 0;
  if (argc >= MIN_ARGS) {
    port = atoi(argv[PORT]);
    printf("got port: %d\n", port);
  } else {
    fprintf(stderr, "port number not specified\n");
    exit(-1);
  }

  printf("DecafsBarista: initializing BaristaServer\n");
  BaristaServer *barista_server = BaristaServer::init(port);
  printf("DecafsBarista: BaristaServer initialized, running BaristaServer\n");
  barista_server->run();

  return 0;
}

<|endoftext|>


<commit_before><commit_msg>Export ShapeRec symbols<commit_after><|endoftext|>


<commit_before>#include "HPACK.h"
#include "gtest/gtest.h"
#include <string.h>

TEST(encode_intTest, NormalTest) {
    uint8_t dst[10];
    uint8_t expect[][5] = {
        {0x01, 0x00},
        {0x0f, 0x01},
        //{0x1f, 0xa1, 0x8d, 0xb7, 0x01},
    };
    uint64_t len = encode_int(dst, 1, 1);
    EXPECT_EQ(2, len);
    EXPECT_TRUE(0 == std::memcmp(dst, expect[0], len));
    len = encode_int(dst, 16, 4);
    EXPECT_EQ(2, len);
    EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));
    /*
      len = encode_int(dst, 3000000, 5);
      EXPECT_EQ(5, len);
      EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));
    */
}

TEST(decode_intTest, NormalTest) {
    uint32_t dst = 0;
    uint8_t data[][5] = {
        {0x01, 0x00},
        {0x0f, 0x01},
    };
    EXPECT_EQ(1, decode_int(data[0], 1));
    EXPECT_EQ(16, decode_int(data[1], 4));
}

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<commit_msg>implement json parser<commit_after>#include "HPACK.h"
#include "hpack_table.h"
#include "gtest/gtest.h"
#include <string.h>
#include "picojson/picojson.h"
#include <fstream>
#include <iostream>
#include <iterator>

TEST(encode_intTest, NormalTest) {
    uint8_t dst[10];
    uint8_t expect[][5] = {
        {0x01, 0x00},
        {0x0f, 0x01},
        //{0x1f, 0xa1, 0x8d, 0xb7, 0x01},
    };
    uint64_t len = encode_int(dst, 1, 1);
    EXPECT_EQ(2, len);
    EXPECT_TRUE(0 == std::memcmp(dst, expect[0], len));
    len = encode_int(dst, 16, 4);
    EXPECT_EQ(2, len);
    EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));
    /*
      len = encode_int(dst, 3000000, 5);
      EXPECT_EQ(5, len);
      EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));
    */
}

TEST(decode_intTest, NormalTest) {
    uint32_t dst = 0;
    uint8_t data[][5] = {
        {0x01, 0x00},
        {0x0f, 0x01},
    };
    EXPECT_EQ(1, decode_int(data[0], 1));
    EXPECT_EQ(16, decode_int(data[1], 4));
}

TEST(encodeTest, NormalTest) {
    std::ifstream ifs("hpack-test-case/haskell-http2-naive/story_00.json");
    if (ifs.fail()) {
        std::cerr  << "fail to open" << std::endl;
    }
    std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());

    picojson::value v;
    std::string err = picojson::parse(v, str);
    if (! err.empty()) {
        std::cerr << err << std::endl;
    }

    picojson::object obj = v.get<picojson::object>();
    picojson::array arr = obj["cases"].get<picojson::array>();
    picojson::array::iterator it_seqno;
    for (it_seqno = arr.begin(); it_seqno != arr.end(); it_seqno++) {
        picojson::object obj_in = it_seqno->get<picojson::object>();
        std::string wire = obj_in["wire"].to_str();
        picojson::array json_headers = obj_in["headers"].get<picojson::array>();
        picojson::array::iterator it_headers;
        std::vector<header> ans_headers;

        for (it_headers = json_headers.begin(); it_headers != json_headers.end(); it_headers++) {
            picojson::object content = it_headers->get<picojson::object>();
            picojson::object::iterator it = content.begin();
            ans_headers.push_back(header(it->first, it->second.to_str()));
        }
        Table* table = new Table();
        uint8_t dst[2000];
        int64_t len = hpack_encode(dst, ans_headers, false, false, false, table, -1);
        //EXPECT_TRUE(0 == std::memcmp(dst, wire, len));
    }
}

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<|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 "mitkRenderWindow.h"
#include "mitkVtkRenderWindow.h"
#include "mitkOpenGLRenderer.h"
#include <assert.h>

std::set<mitk::RenderWindow*> mitk::RenderWindow::instances;

mitk::RenderWindow::RenderWindow(const char *name, mitk::BaseRenderer* renderer)
  : m_MitkVtkRenderWindow(NULL), m_Name(name), m_Renderer(renderer)
{
  instances.insert(this);
  m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();
}

mitk::RenderWindow::~RenderWindow()
{
  instances.erase(this);
  m_Renderer = NULL;
  m_MitkVtkRenderWindow->Delete(); //xxx
}

void mitk::RenderWindow::MakeCurrent()
{
  m_MitkVtkRenderWindow->MakeCurrent();
};

void mitk::RenderWindow::SwapBuffers()
{
  m_MitkVtkRenderWindow->Frame();
};

bool mitk::RenderWindow::IsSharing () const
{
  return false;
}

void mitk::RenderWindow::Update()
{
  m_MitkVtkRenderWindow->MakeCurrent();
  m_MitkVtkRenderWindow->Render();
}

void mitk::RenderWindow::Repaint()
{
  m_MitkVtkRenderWindow->MakeCurrent();
  m_MitkVtkRenderWindow->Render();
}

void mitk::RenderWindow::SetSize(int w, int h)
{
  m_MitkVtkRenderWindow->SetSize(w,h);
}

void mitk::RenderWindow::InitRenderer()
{
  if(m_Renderer.IsNull())
    m_Renderer = mitk::OpenGLRenderer::New();

  m_MitkVtkRenderWindow->SetMitkRenderer(m_Renderer);

  m_Renderer->InitRenderer(this);

  int * size = m_MitkVtkRenderWindow->GetSize();
  if((size[0]>10) && (size[1]>10))
    m_Renderer->InitSize(size[0], size[1]);
}

void mitk::RenderWindow::SetWindowId(void * id)
{
  m_MitkVtkRenderWindow->SetWindowId( id );
}

void mitk::RenderWindow::SetVtkRenderWindow(VtkRenderWindow* renWin)
{
  if (renWin != NULL)
  {
    m_MitkVtkRenderWindow = renWin;
    InitRenderer();
  }
}

<commit_msg>FIX: accept NULL as name<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 "mitkRenderWindow.h"
#include "mitkVtkRenderWindow.h"
#include "mitkOpenGLRenderer.h"
#include <assert.h>

std::set<mitk::RenderWindow*> mitk::RenderWindow::instances;

mitk::RenderWindow::RenderWindow(const char *name, mitk::BaseRenderer* renderer)
  : m_MitkVtkRenderWindow(NULL), m_Renderer(renderer)
{
  if(name == NULL)
    m_Name = "renderwindow";
  else
    m_Name = name;
  instances.insert(this);
  m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();
}

mitk::RenderWindow::~RenderWindow()
{
  instances.erase(this);
  m_Renderer = NULL;
  m_MitkVtkRenderWindow->Delete(); //xxx
}

void mitk::RenderWindow::MakeCurrent()
{
  m_MitkVtkRenderWindow->MakeCurrent();
};

void mitk::RenderWindow::SwapBuffers()
{
  m_MitkVtkRenderWindow->Frame();
};

bool mitk::RenderWindow::IsSharing () const
{
  return false;
}

void mitk::RenderWindow::Update()
{
  m_MitkVtkRenderWindow->MakeCurrent();
  m_MitkVtkRenderWindow->Render();
}

void mitk::RenderWindow::Repaint()
{
  m_MitkVtkRenderWindow->MakeCurrent();
  m_MitkVtkRenderWindow->Render();
}

void mitk::RenderWindow::SetSize(int w, int h)
{
  m_MitkVtkRenderWindow->SetSize(w,h);
}

void mitk::RenderWindow::InitRenderer()
{
  if(m_Renderer.IsNull())
    m_Renderer = mitk::OpenGLRenderer::New();

  m_MitkVtkRenderWindow->SetMitkRenderer(m_Renderer);

  m_Renderer->InitRenderer(this);

  int * size = m_MitkVtkRenderWindow->GetSize();
  if((size[0]>10) && (size[1]>10))
    m_Renderer->InitSize(size[0], size[1]);
}

void mitk::RenderWindow::SetWindowId(void * id)
{
  m_MitkVtkRenderWindow->SetWindowId( id );
}

void mitk::RenderWindow::SetVtkRenderWindow(VtkRenderWindow* renWin)
{
  if (renWin != NULL)
  {
    m_MitkVtkRenderWindow = renWin;
    InitRenderer();
  }
}

<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "localplaingdbadapter.h"

#include "gdbengine.h"
#include "procinterrupt.h"
#include "debuggerstringutils.h"

#include <utils/qtcassert.h>

#include <QtCore/QFileInfo>
#include <QtCore/QProcess>
#include <QtGui/QMessageBox>

namespace Debugger {
namespace Internal {

///////////////////////////////////////////////////////////////////////
//
// PlainGdbAdapter
//
///////////////////////////////////////////////////////////////////////

LocalPlainGdbAdapter::LocalPlainGdbAdapter(GdbEngine *engine, QObject *parent)
    : AbstractPlainGdbAdapter(engine, parent)
{
    // Output
    connect(&m_outputCollector, SIGNAL(byteDelivery(QByteArray)),
        engine, SLOT(readDebugeeOutput(QByteArray)));
}

AbstractGdbAdapter::DumperHandling LocalPlainGdbAdapter::dumperHandling() const
{
    // LD_PRELOAD fails for System-Qt on Mac.
#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
    return DumperLoadedByGdb;
#else
    return DumperLoadedByGdbPreload;
#endif
}

void LocalPlainGdbAdapter::startAdapter()
{
    QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
    showMessage(_("TRYING TO START ADAPTER"));

    QStringList gdbArgs;

    if (!m_outputCollector.listen()) {
        m_engine->handleAdapterStartFailed(tr("Cannot set up communication with child process: %1")
                .arg(m_outputCollector.errorString()), QString());
        return;
    }
    gdbArgs.append(_("--tty=") + m_outputCollector.serverName());

    if (!startParameters().workingDirectory.isEmpty())
        m_gdbProc.setWorkingDirectory(startParameters().workingDirectory);
    if (!startParameters().environment.isEmpty())
        m_gdbProc.setEnvironment(startParameters().environment);

    if (!m_engine->startGdb(gdbArgs)) {
        m_outputCollector.shutdown();
        return;
    }

    checkForReleaseBuild();
    m_engine->handleAdapterStarted();
}

void LocalPlainGdbAdapter::setupInferior()
{
    AbstractPlainGdbAdapter::setupInferior();
}

void LocalPlainGdbAdapter::runEngine()
{
    AbstractPlainGdbAdapter::runEngine();
}

void LocalPlainGdbAdapter::shutdownInferior()
{
    m_engine->defaultInferiorShutdown("kill");
}

void LocalPlainGdbAdapter::shutdownAdapter()
{
    showMessage(_("PLAIN ADAPTER SHUTDOWN %1").arg(state()));
    m_outputCollector.shutdown();
    m_engine->notifyAdapterShutdownOk();
}

void LocalPlainGdbAdapter::checkForReleaseBuild()
{
    // Quick check for a "release" build
    QProcess proc;
    QStringList args;
    args.append(_("-h"));
    args.append(_("-j"));
    args.append(_(".debug_info"));
    args.append(startParameters().executable);
    proc.start(_("objdump"), args);
    proc.closeWriteChannel();
    QTC_ASSERT(proc.waitForStarted(), qDebug() << "UNABLE TO RUN OBJDUMP");
    proc.waitForFinished();
    QByteArray ba = proc.readAllStandardOutput();
    // This should yield something like
    // "debuggertest:     file format elf32-i386\n\n"
    // "Sections:\nIdx Name          Size      VMA       LMA       File off  Algn\n"
    // "30 .debug_info   00087d36  00000000  00000000  0006bbd5  2**0\n"
    // " CONTENTS, READONLY, DEBUGGING"
    if (ba.contains("Sections:") && !ba.contains(".debug_info")) {
        m_engine->showMessageBox(QMessageBox::Information, "Warning",
           tr("This does not seem to be a \"Debug\" build.\n"
              "Setting breakpoints by file name and line number may fail."));
    }
}

void LocalPlainGdbAdapter::interruptInferior()
{
    const qint64 attachedPID = m_engine->inferiorPid();
    if (attachedPID <= 0) {
        showMessage(_("TRYING TO INTERRUPT INFERIOR BEFORE PID WAS OBTAINED"));
        return;
    }

    if (!interruptProcess(attachedPID)) {
        showMessage(_("CANNOT INTERRUPT %1").arg(attachedPID));
        m_engine->notifyInferiorStopFailed();
    }
}

QByteArray LocalPlainGdbAdapter::execFilePath() const
{
    return QFileInfo(startParameters().executable)
            .absoluteFilePath().toLocal8Bit();
}

bool LocalPlainGdbAdapter::infoTargetNecessary() const
{
#ifdef Q_OS_LINUX
    return true;
#else
    return false;
#endif
}

QByteArray LocalPlainGdbAdapter::toLocalEncoding(const QString &s) const
{
    return s.toLocal8Bit();
}

QString LocalPlainGdbAdapter::fromLocalEncoding(const QByteArray &b) const
{
    return QString::fromLocal8Bit(b);
}

} // namespace Internal
} // namespace Debugger
<commit_msg>debugger: skip "release build" check if objdump could not be started<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "localplaingdbadapter.h"

#include "gdbengine.h"
#include "procinterrupt.h"
#include "debuggerstringutils.h"

#include <utils/qtcassert.h>

#include <QtCore/QFileInfo>
#include <QtCore/QProcess>
#include <QtGui/QMessageBox>

namespace Debugger {
namespace Internal {

///////////////////////////////////////////////////////////////////////
//
// PlainGdbAdapter
//
///////////////////////////////////////////////////////////////////////

LocalPlainGdbAdapter::LocalPlainGdbAdapter(GdbEngine *engine, QObject *parent)
    : AbstractPlainGdbAdapter(engine, parent)
{
    // Output
    connect(&m_outputCollector, SIGNAL(byteDelivery(QByteArray)),
        engine, SLOT(readDebugeeOutput(QByteArray)));
}

AbstractGdbAdapter::DumperHandling LocalPlainGdbAdapter::dumperHandling() const
{
    // LD_PRELOAD fails for System-Qt on Mac.
#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
    return DumperLoadedByGdb;
#else
    return DumperLoadedByGdbPreload;
#endif
}

void LocalPlainGdbAdapter::startAdapter()
{
    QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
    showMessage(_("TRYING TO START ADAPTER"));

    QStringList gdbArgs;

    if (!m_outputCollector.listen()) {
        m_engine->handleAdapterStartFailed(tr("Cannot set up communication with child process: %1")
                .arg(m_outputCollector.errorString()), QString());
        return;
    }
    gdbArgs.append(_("--tty=") + m_outputCollector.serverName());

    if (!startParameters().workingDirectory.isEmpty())
        m_gdbProc.setWorkingDirectory(startParameters().workingDirectory);
    if (!startParameters().environment.isEmpty())
        m_gdbProc.setEnvironment(startParameters().environment);

    if (!m_engine->startGdb(gdbArgs)) {
        m_outputCollector.shutdown();
        return;
    }

    checkForReleaseBuild();
    m_engine->handleAdapterStarted();
}

void LocalPlainGdbAdapter::setupInferior()
{
    AbstractPlainGdbAdapter::setupInferior();
}

void LocalPlainGdbAdapter::runEngine()
{
    AbstractPlainGdbAdapter::runEngine();
}

void LocalPlainGdbAdapter::shutdownInferior()
{
    m_engine->defaultInferiorShutdown("kill");
}

void LocalPlainGdbAdapter::shutdownAdapter()
{
    showMessage(_("PLAIN ADAPTER SHUTDOWN %1").arg(state()));
    m_outputCollector.shutdown();
    m_engine->notifyAdapterShutdownOk();
}

void LocalPlainGdbAdapter::checkForReleaseBuild()
{
    // Quick check for a "release" build
    QProcess proc;
    QStringList args;
    args.append(_("-h"));
    args.append(_("-j"));
    args.append(_(".debug_info"));
    args.append(startParameters().executable);
    proc.start(_("objdump"), args);
    proc.closeWriteChannel();
    if (!proc.waitForStarted()) {
        showMessage(_("OBJDUMP PROCESS COULD NOT BE STARTED. "
            "RELEASE BUILD CHECK WILL FAIL"));
        return;
    }
    proc.waitForFinished();
    QByteArray ba = proc.readAllStandardOutput();
    // This should yield something like
    // "debuggertest:     file format elf32-i386\n\n"
    // "Sections:\nIdx Name          Size      VMA       LMA       File off  Algn\n"
    // "30 .debug_info   00087d36  00000000  00000000  0006bbd5  2**0\n"
    // " CONTENTS, READONLY, DEBUGGING"
    if (ba.contains("Sections:") && !ba.contains(".debug_info")) {
        m_engine->showMessageBox(QMessageBox::Information, "Warning",
           tr("This does not seem to be a \"Debug\" build.\n"
              "Setting breakpoints by file name and line number may fail."));
    }
}

void LocalPlainGdbAdapter::interruptInferior()
{
    const qint64 attachedPID = m_engine->inferiorPid();
    if (attachedPID <= 0) {
        showMessage(_("TRYING TO INTERRUPT INFERIOR BEFORE PID WAS OBTAINED"));
        return;
    }

    if (!interruptProcess(attachedPID)) {
        showMessage(_("CANNOT INTERRUPT %1").arg(attachedPID));
        m_engine->notifyInferiorStopFailed();
    }
}

QByteArray LocalPlainGdbAdapter::execFilePath() const
{
    return QFileInfo(startParameters().executable)
            .absoluteFilePath().toLocal8Bit();
}

bool LocalPlainGdbAdapter::infoTargetNecessary() const
{
#ifdef Q_OS_LINUX
    return true;
#else
    return false;
#endif
}

QByteArray LocalPlainGdbAdapter::toLocalEncoding(const QString &s) const
{
    return s.toLocal8Bit();
}

QString LocalPlainGdbAdapter::fromLocalEncoding(const QByteArray &b) const
{
    return QString::fromLocal8Bit(b);
}

} // namespace Internal
} // namespace Debugger
<|endoftext|>


<commit_before>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "multiplication_process.h"

#include <vistk/pipeline_types/port_types.h>

#include <vistk/pipeline/config.h>
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>

#include <algorithm>

namespace vistk
{

class multiplication_process::priv
{
  public:
    typedef uint32_t number_t;

    priv();
    ~priv();

    edge_ref_t input_edge_factor1;
    edge_ref_t input_edge_factor2;
    edge_group_t output_edges;

    port_info_t factor1_port_info;
    port_info_t factor2_port_info;
    port_info_t output_port_info;

    static port_t const INPUT_FACTOR1_PORT_NAME;
    static port_t const INPUT_FACTOR2_PORT_NAME;
    static port_t const OUTPUT_PORT_NAME;
};

process::port_t const multiplication_process::priv::INPUT_FACTOR1_PORT_NAME = process::port_t("factor1");
process::port_t const multiplication_process::priv::INPUT_FACTOR2_PORT_NAME = process::port_t("factor2");
process::port_t const multiplication_process::priv::OUTPUT_PORT_NAME = process::port_t("product");

multiplication_process
::multiplication_process(config_t const& config)
  : process(config)
{
  d = boost::shared_ptr<priv>(new priv);
}

multiplication_process
::~multiplication_process()
{
}

void
multiplication_process
::_step()
{
  datum_t dat;
  stamp_t st;

  edge_group_t input_edges;

  input_edges.push_back(d->input_edge_factor1);
  input_edges.push_back(d->input_edge_factor2);

  bool const colored = same_colored_edges(input_edges);
  bool const syncd = syncd_edges(input_edges);

  if (!colored)
  {
    st = heartbeat_stamp();

    dat = datum::error_datum("The input edges are not colored the same.");
  }
  else if (!syncd)
  {
    st = heartbeat_stamp();

    dat = datum::error_datum("The input edges are not synchronized.");
  }
  else
  {
    edge_datum_t const factor1_dat = grab_from_edge_ref(d->input_edge_factor1);
    edge_datum_t const factor2_dat = grab_from_edge_ref(d->input_edge_factor2);

    edge_data_t input_dats;

    input_dats.push_back(factor1_dat);
    input_dats.push_back(factor2_dat);

    st = factor1_dat.get<1>();

    datum::datum_type_t const max_type = max_status(input_dats);

    switch (max_type)
    {
      case datum::DATUM_DATA:
      {
        priv::number_t const factor1 = factor1_dat.get<0>()->get_datum<priv::number_t>();
        priv::number_t const factor2 = factor2_dat.get<0>()->get_datum<priv::number_t>();

        priv::number_t const product = factor1 * factor2;

        dat = datum::new_datum(product);
        break;
      }
      case datum::DATUM_EMPTY:
        dat = datum::empty_datum();
        break;
      case datum::DATUM_COMPLETE:
        mark_as_complete();
        dat = datum::complete_datum();
        break;
      case datum::DATUM_ERROR:
        dat = datum::error_datum("Error on the input edges.");
        break;
      case datum::DATUM_INVALID:
      default:
        dat = datum::error_datum("Unrecognized datum type.");
        break;
    }
  }

  edge_datum_t const edat = edge_datum_t(dat, st);

  push_to_edges(d->output_edges, edat);

  process::_step();
}

void
multiplication_process
::_connect_input_port(port_t const& port, edge_t edge)
{
  if (port == priv::INPUT_FACTOR1_PORT_NAME)
  {
    if (d->input_edge_factor1.use_count())
    {
      throw port_reconnect_exception(name(), port);
    }

    d->input_edge_factor1 = edge_ref_t(edge);

    return;
  }
  if (port == priv::INPUT_FACTOR2_PORT_NAME)
  {
    if (d->input_edge_factor2.use_count())
    {
      throw port_reconnect_exception(name(), port);
    }

    d->input_edge_factor2 = edge_ref_t(edge);

    return;
  }

  process::_connect_input_port(port, edge);
}

process::port_info_t
multiplication_process
::_input_port_info(port_t const& port) const
{
  if (port == priv::INPUT_FACTOR1_PORT_NAME)
  {
    return d->factor1_port_info;
  }
  if (port == priv::INPUT_FACTOR2_PORT_NAME)
  {
    return d->factor2_port_info;
  }

  return process::_input_port_info(port);
}

void
multiplication_process
::_connect_output_port(port_t const& port, edge_t edge)
{
  if (port == priv::OUTPUT_PORT_NAME)
  {
    d->output_edges.push_back(edge_ref_t(edge));

    return;
  }

  process::_connect_output_port(port, edge);
}

process::port_info_t
multiplication_process
::_output_port_info(port_t const& port) const
{
  if (port == priv::OUTPUT_PORT_NAME)
  {
    return d->output_port_info;
  }

  return process::_output_port_info(port);
}

process::ports_t
multiplication_process
::_input_ports() const
{
  ports_t ports;

  ports.push_back(priv::INPUT_FACTOR1_PORT_NAME);
  ports.push_back(priv::INPUT_FACTOR2_PORT_NAME);

  return ports;
}

process::ports_t
multiplication_process
::_output_ports() const
{
  ports_t ports;

  ports.push_back(priv::OUTPUT_PORT_NAME);

  return ports;
}

multiplication_process::priv
::priv()
{
  port_flags_t required;

  required.insert(flag_required);

  factor1_port_info = port_info_t(new port_info(
    port_types::t_integer,
    required,
    port_description_t("The first factor to multiply.")));
  factor2_port_info = port_info_t(new port_info(
    port_types::t_integer,
    required,
    port_description_t("The second factor to multiply.")));
  output_port_info = port_info_t(new port_info(
    port_types::t_integer,
    required,
    port_description_t("Where the product will be available.")));
}

multiplication_process::priv
::~priv()
{
}

}
<commit_msg>Collect all input edges as received<commit_after>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "multiplication_process.h"

#include <vistk/pipeline_types/port_types.h>

#include <vistk/pipeline/config.h>
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>

#include <algorithm>

namespace vistk
{

class multiplication_process::priv
{
  public:
    typedef uint32_t number_t;

    priv();
    ~priv();

    edge_ref_t input_edge_factor1;
    edge_ref_t input_edge_factor2;

    edge_group_t input_edges;
    edge_group_t output_edges;

    port_info_t factor1_port_info;
    port_info_t factor2_port_info;
    port_info_t output_port_info;

    static port_t const INPUT_FACTOR1_PORT_NAME;
    static port_t const INPUT_FACTOR2_PORT_NAME;
    static port_t const OUTPUT_PORT_NAME;
};

process::port_t const multiplication_process::priv::INPUT_FACTOR1_PORT_NAME = process::port_t("factor1");
process::port_t const multiplication_process::priv::INPUT_FACTOR2_PORT_NAME = process::port_t("factor2");
process::port_t const multiplication_process::priv::OUTPUT_PORT_NAME = process::port_t("product");

multiplication_process
::multiplication_process(config_t const& config)
  : process(config)
{
  d = boost::shared_ptr<priv>(new priv);
}

multiplication_process
::~multiplication_process()
{
}

void
multiplication_process
::_step()
{
  datum_t dat;
  stamp_t st;

  bool const colored = same_colored_edges(d->input_edges);
  bool const syncd = syncd_edges(d->input_edges);

  if (!colored)
  {
    st = heartbeat_stamp();

    dat = datum::error_datum("The input edges are not colored the same.");
  }
  else if (!syncd)
  {
    st = heartbeat_stamp();

    dat = datum::error_datum("The input edges are not synchronized.");
  }
  else
  {
    edge_datum_t const factor1_dat = grab_from_edge_ref(d->input_edge_factor1);
    edge_datum_t const factor2_dat = grab_from_edge_ref(d->input_edge_factor2);

    edge_data_t input_dats;

    input_dats.push_back(factor1_dat);
    input_dats.push_back(factor2_dat);

    st = factor1_dat.get<1>();

    datum::datum_type_t const max_type = max_status(input_dats);

    switch (max_type)
    {
      case datum::DATUM_DATA:
      {
        priv::number_t const factor1 = factor1_dat.get<0>()->get_datum<priv::number_t>();
        priv::number_t const factor2 = factor2_dat.get<0>()->get_datum<priv::number_t>();

        priv::number_t const product = factor1 * factor2;

        dat = datum::new_datum(product);
        break;
      }
      case datum::DATUM_EMPTY:
        dat = datum::empty_datum();
        break;
      case datum::DATUM_COMPLETE:
        mark_as_complete();
        dat = datum::complete_datum();
        break;
      case datum::DATUM_ERROR:
        dat = datum::error_datum("Error on the input edges.");
        break;
      case datum::DATUM_INVALID:
      default:
        dat = datum::error_datum("Unrecognized datum type.");
        break;
    }
  }

  edge_datum_t const edat = edge_datum_t(dat, st);

  push_to_edges(d->output_edges, edat);

  process::_step();
}

void
multiplication_process
::_connect_input_port(port_t const& port, edge_t edge)
{
  if (port == priv::INPUT_FACTOR1_PORT_NAME)
  {
    if (d->input_edge_factor1.use_count())
    {
      throw port_reconnect_exception(name(), port);
    }

    d->input_edge_factor1 = edge_ref_t(edge);
    d->input_edges.push_back(d->input_edge_factor1);

    return;
  }
  if (port == priv::INPUT_FACTOR2_PORT_NAME)
  {
    if (d->input_edge_factor2.use_count())
    {
      throw port_reconnect_exception(name(), port);
    }

    d->input_edge_factor2 = edge_ref_t(edge);
    d->input_edges.push_back(d->input_edge_factor2);

    return;
  }

  process::_connect_input_port(port, edge);
}

process::port_info_t
multiplication_process
::_input_port_info(port_t const& port) const
{
  if (port == priv::INPUT_FACTOR1_PORT_NAME)
  {
    return d->factor1_port_info;
  }
  if (port == priv::INPUT_FACTOR2_PORT_NAME)
  {
    return d->factor2_port_info;
  }

  return process::_input_port_info(port);
}

void
multiplication_process
::_connect_output_port(port_t const& port, edge_t edge)
{
  if (port == priv::OUTPUT_PORT_NAME)
  {
    d->output_edges.push_back(edge_ref_t(edge));

    return;
  }

  process::_connect_output_port(port, edge);
}

process::port_info_t
multiplication_process
::_output_port_info(port_t const& port) const
{
  if (port == priv::OUTPUT_PORT_NAME)
  {
    return d->output_port_info;
  }

  return process::_output_port_info(port);
}

process::ports_t
multiplication_process
::_input_ports() const
{
  ports_t ports;

  ports.push_back(priv::INPUT_FACTOR1_PORT_NAME);
  ports.push_back(priv::INPUT_FACTOR2_PORT_NAME);

  return ports;
}

process::ports_t
multiplication_process
::_output_ports() const
{
  ports_t ports;

  ports.push_back(priv::OUTPUT_PORT_NAME);

  return ports;
}

multiplication_process::priv
::priv()
{
  port_flags_t required;

  required.insert(flag_required);

  factor1_port_info = port_info_t(new port_info(
    port_types::t_integer,
    required,
    port_description_t("The first factor to multiply.")));
  factor2_port_info = port_info_t(new port_info(
    port_types::t_integer,
    required,
    port_description_t("The second factor to multiply.")));
  output_port_info = port_info_t(new port_info(
    port_types::t_integer,
    required,
    port_description_t("Where the product will be available.")));
}

multiplication_process::priv
::~priv()
{
}

}
<|endoftext|>