<commit_before>#include <vtkSmoothPolyDataFilter.h>
#include <vtkSmartPointer.h>
#include <vtkPolyData.h>
#include <vtkPolyDataReader.h>
#include <vtkPolyDataWriter.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkXMLPolyDataWriter.h>
#include <vtkFloatArray.h>
#include <vtkPointData.h>
#include <vtkCell.h>
#include <vtkCellData.h>
#include <vtkCellArray.h>
#include <iostream>
#include <cstring>
#include <string>
#include <string.h>
#include "processing.h"

#include <itkImage.h>
#include <itkImageFileReader.h>
#include "itkImageToVTKImageFilter.h"

#include <vtkImageWriter.h>
#include <itkPoint.h>
#include <itkLinearInterpolateImageFunction.h>

#include <vtkCellArray.h>
#include <vtkDoubleArray.h>

#include <vtkPointData.h>

#include <vtkPolyLine.h>

processing::processing( int visuAttribute )
{
    visualize = visuAttribute ;
}

std::string processing::ExtensionofFile( std::string filename )
{
    std::string extension ;
    extension = filename.substr( filename.find_last_of(".")+1,filename.size()-filename.find_last_of( "." ) + 1 ) ;
    return extension ;
}

void processing::FindAllData( vtkSmartPointer< vtkPolyData > polydata )
{
    polydata->GetLines()->InitTraversal() ;
    std::cout << "Normals: " << polydata->GetPointData()->GetNormals() << std::endl ;
    vtkIdType numberOfPointArrays = polydata->GetPointData()->GetNumberOfArrays() ;
    std::cout << "Lines: " << polydata->GetNumberOfLines() << std::endl ;
    vtkSmartPointer< vtkIdList > idList = vtkSmartPointer< vtkIdList >::New() ;
    std::cout << "Cells: " << polydata->GetNumberOfCells() << std::endl ;
    std::cout << "Points: " << polydata->GetNumberOfPoints() << std::endl ;
    std::cout << "Polys: " << polydata->GetNumberOfPolys() << std::endl ;
    std::cout << "Strips: " << polydata->GetNumberOfStrips() << std::endl ;
    std::cout << "Verts: " << polydata->GetNumberOfVerts() << std::endl ;
    int i=1;
    while( polydata->GetLines()->GetNextCell( idList ) )
    {
        std::cout<< "Line " << i << ": " << idList->GetNumberOfIds() << " points" <<std::endl ;
        i++;
        for( vtkIdType pointId = 0 ; pointId < idList->GetNumberOfIds() ; pointId++ )
        {
            /*std::cout <<idList->GetId( pointId ) << " " ;*/
        }
    }
}
template <class T>
vtkSmartPointer< vtkPolyData > processing::readFiberFile( T reader , std::string fiberFile )
{
    vtkSmartPointer< vtkPolyData > PolyData ;
    reader->SetFileName( fiberFile.c_str() ) ;
    PolyData=reader->GetOutput() ;
    reader->Update() ;
    return PolyData ;
}

void processing::writeFiberFile( vtkSmartPointer< vtkPolyData > PolyData , std::string outputFileName )
{
    vtkSmartPointer< vtkPolyDataWriter > writer = vtkSmartPointer< vtkPolyDataWriter >::New() ;
    writer->SetInputData( PolyData ) ;
    //writer->SetDataModeToBinary() ;
    writer->SetFileName( outputFileName.c_str() ) ;
    writer->Update() ;
}

vtkSmartPointer< vtkPolyData > processing::ApplyMaskToFiber( vtkSmartPointer< vtkPolyData > PolyData , std::string maskFileName )
{
    typedef itk::Image< int , 3 > ImageType ;
    typedef itk::ImageFileReader< ImageType > ReaderType ;
    ReaderType::Pointer readerMask = ReaderType::New() ;
    readerMask->SetFileName( maskFileName ) ;
    readerMask->Update() ;
    ImageType::Pointer maskImage = ImageType::New() ;
    maskImage = readerMask->GetOutput() ;
    typedef itk::Index< 3 > IndexType ;
    ImageType::IndexType index ;
    typedef itk::LinearInterpolateImageFunction< ImageType , double > InterpolationType ;
    InterpolationType::Pointer interp = InterpolationType::New() ;
    interp->SetInputImage( maskImage ) ;
    itk::Point< double , 3 > p ;
    const int nfib = PolyData->GetNumberOfCells() ;
    std::cout<< nfib <<std::endl;
    // Inserting an array corresponding to the % of the fiber which is not inside the mask
    vtkSmartPointer< vtkDoubleArray > fiberData = vtkSmartPointer< vtkDoubleArray >::New() ;
    vtkSmartPointer< vtkDoubleArray > pointData = vtkSmartPointer< vtkDoubleArray >::New() ;
    for( int i = 0 ; i < nfib ; ++i )
    {
        float badPixel = 0.0f ;
        std::cout << " FIBER NUMBER " << i << std::endl ;
        vtkSmartPointer< vtkCell > fiber = PolyData->GetCell( i ) ;
        vtkSmartPointer< vtkPoints > fiberPoints = fiber->GetPoints() ;
        for( int j = 0 ; j < fiberPoints->GetNumberOfPoints() ; ++j )
        {
            double* coordinates = fiberPoints->GetPoint( j ) ;
            /* Flip the coordinates */
            coordinates[0] = - coordinates[0] ;
            coordinates[1] = - coordinates[1] ;
            p[0] = coordinates[0] ;
            p[1] = coordinates[1] ;
            p[2] = coordinates[2] ;
            maskImage->TransformPhysicalPointToIndex( p , index ) ;
            //Checks if the index is inside the image boundaries
            if( !interp->IsInsideBuffer( index ) )
            {
                std::cout << "Index out of bounds" << std::endl ;
            }
            else
            {
            }
            ImageType::PixelType pixel = maskImage->GetPixel( index ) ;
            if(pixel == 255)
            {

                badPixel = badPixel +1.0f ;
                pointData->SetNumberOfComponents( 1 ) ;
                pointData->SetName( "InsideMask" ) ;
                pointData->InsertNextValue( 255 ) ;
            }
            else
            {
                pointData->InsertNextValue( 0 ) ;
            }
        }
        std::cout << "Pixels out of mask = " << badPixel << std::endl ;
        fiberData->SetNumberOfComponents( nfib ) ;
        fiberData->SetName( "UnwantedFiber" ) ;
        fiberData->InsertNextValue( badPixel/fiberPoints->GetNumberOfPoints()*100 ) ;

        // Reading the data inserted
        std::cout<< "% of the fiber outside of the mask = " << badPixel/fiberPoints->GetNumberOfPoints()*100 << "%" <<std::endl ;
    }
    PolyData->GetPointData()->AddArray( pointData ) ;
    PolyData->GetCellData()->AddArray( fiberData ) ;
    return PolyData ;
}

vtkSmartPointer< vtkPolyData > processing::AddPointData( vtkSmartPointer< vtkPolyData > PolyData )
{
    const int nfib = PolyData->GetNumberOfCells() ;
    vtkSmartPointer< vtkDoubleArray > pointData = vtkSmartPointer< vtkDoubleArray >::New() ;
    for( int i = 0 ; i < nfib ; ++i )
    {
        vtkSmartPointer< vtkCell > fiber = PolyData->GetCell( i ) ;
        vtkSmartPointer< vtkPoints > fiberPoints = fiber->GetPoints() ;
        for( int j = 0 ; j < fiberPoints->GetNumberOfPoints() ; ++j )
        {
            pointData->SetNumberOfComponents( PolyData->GetNumberOfPoints() ) ;
            pointData->SetName( "InsideMask" ) ;
            pointData->InsertNextValue( 0 ) ;
        }

    }
    PolyData->GetPointData()->AddArray( pointData ) ;
    return PolyData;
}

vtkSmartPointer< vtkPolyData > processing::CleanFiber( vtkSmartPointer< vtkPolyData > PolyData , float threshold )
{
    vtkSmartPointer< vtkPolyData > NewPolyData = vtkSmartPointer< vtkPolyData >::New() ;
    //vtkSmartPointer<vtkFloatArray> NewTensors=vtkSmartPointer<vtkFloatArray>::New();
    vtkSmartPointer<vtkPoints> NewPoints = vtkSmartPointer<vtkPoints>::New() ;
    vtkSmartPointer<vtkCellArray> NewLines = vtkSmartPointer<vtkCellArray>::New() ;
    vtkPoints* Points = PolyData->GetPoints() ;
    vtkCellArray* Lines = PolyData->GetLines() ;
    vtkIdType* Ids ;
    vtkIdType NumberOfPoints ;
    int NewId = 0 ;
    vtkSmartPointer< vtkDoubleArray > fiberReadArray = vtkSmartPointer< vtkDoubleArray >::New() ;
    fiberReadArray = vtkDoubleArray::SafeDownCast( PolyData->GetCellData()->GetArray("UnwantedFiber") ) ;
    Lines->InitTraversal() ;
    for( int i = 0 ; Lines->GetNextCell( NumberOfPoints , Ids ) ; i++ )
    {
        std::cout<<"coucou";
        vtkSmartPointer< vtkPolyLine > NewLine = vtkSmartPointer< vtkPolyLine >::New() ;
        NewLine->GetPointIds()->SetNumberOfIds( NumberOfPoints ) ;
        std::cout << " FIBER NUMBER " << i << std::endl ;
        std::cout << fiberReadArray->GetValue( i ) <<"%"<<std::endl ;
        if( fiberReadArray->GetValue( i ) <= threshold )
        {
            for( int j = 0 ; j < NumberOfPoints ; j ++ )
            {
                NewPoints->InsertNextPoint( Points->GetPoint( Ids[j] ) ) ;
                NewLine->GetPointIds()->SetId( j , NewId ) ;
                NewId++ ;
            }
            NewLines->InsertNextCell( NewLine ) ;
       }
        else
        {
            std::cout << "Deleted" <<std::endl ;
        }
    }
    NewPolyData->SetPoints( NewPoints ) ;
    NewPolyData->SetLines( NewLines ) ;
    return NewPolyData ;
}

vtkSmartPointer< vtkPolyData > processing::CreateVisuFiber( vtkSmartPointer< vtkPolyData > PolyData )
{
    vtkSmartPointer< vtkPolyData > NewPolyData = vtkSmartPointer< vtkPolyData >::New() ;
    vtkSmartPointer<vtkPoints> NewPoints = vtkSmartPointer<vtkPoints>::New() ;
    vtkSmartPointer<vtkCellArray> NewLines = vtkSmartPointer<vtkCellArray>::New() ;
    vtkSmartPointer< vtkDoubleArray > pointData = vtkSmartPointer< vtkDoubleArray >::New() ;
    vtkPoints* Points = PolyData->GetPoints() ;
    vtkCellArray* Lines = PolyData->GetLines() ;
    vtkIdType* Ids ;
    vtkIdType NumberOfPoints ;
    int NewId = 0 ;
    Lines->InitTraversal() ;
    const int nfib = PolyData->GetNumberOfCells() ;
    for( int i = 0 ; Lines->GetNextCell( NumberOfPoints , Ids ) ; i++ )
    {
        vtkSmartPointer< vtkPolyLine > NewLine = vtkSmartPointer< vtkPolyLine >::New() ;
        NewLine->GetPointIds()->SetNumberOfIds( NumberOfPoints ) ;
        for( int j = 0 ; j < NumberOfPoints ; j ++ )
        {
            NewPoints->InsertNextPoint( Points->GetPoint( Ids[j] ) ) ;
            NewLine->GetPointIds()->SetId( j , NewId ) ;
            NewId++ ;
        }
        NewLines->InsertNextCell( NewLine ) ;
    }
    NewPolyData->SetPoints( NewPoints ) ;
    NewPolyData->SetLines( NewLines ) ;
    NewPolyData->GetPointData()->AddArray( PolyData->GetPointData()->GetAbstractArray( 1 ) ) ;
    return NewPolyData ;

}

int processing::processing_main(std::string& inputFileName ,
                                std::string& outputFileName ,
                                std::string& maskFileName ,
                                float threshold )
{
    typedef itk::Image< int , 3 > ImageType ;
    typedef itk::ImageFileReader< ImageType > ReaderType ;
    vtkSmartPointer< vtkPolyData > fiberPolyData ;
    vtkSmartPointer< vtkPolyData > cleanedFiberPolyData ;
    std::string extension = ExtensionofFile( inputFileName ) ;
    if( extension.rfind("vtk") != std::string::npos )
    {
        vtkSmartPointer< vtkPolyDataReader > fiberPolyDataReader = vtkSmartPointer< vtkPolyDataReader >::New() ;
        fiberPolyData = readFiberFile( fiberPolyDataReader, inputFileName ) ;
    }
    else if( extension.rfind("vtp") != std::string::npos )
    {
        vtkSmartPointer<vtkXMLPolyDataReader> fiberPolyDataReader = vtkSmartPointer< vtkXMLPolyDataReader >::New() ;
        fiberPolyData = readFiberFile( fiberPolyDataReader, inputFileName ) ;
    }
    else
    {
        std::cout << "File could not be read" << std::endl ;
        return 1 ;
    }
    FindAllData( fiberPolyData ) ;
    fiberPolyData = ApplyMaskToFiber( fiberPolyData , maskFileName ) ;
    cleanedFiberPolyData = CleanFiber(fiberPolyData , threshold ) ;
    cleanedFiberPolyData = AddPointData( cleanedFiberPolyData ) ;
    vtkSmartPointer< vtkPolyData > visuFiber = vtkSmartPointer< vtkPolyData >::New() ;
    if( visualize )
    {
        visuFiber = CreateVisuFiber( fiberPolyData ) ;
    }
    writeFiberFile( visuFiber , "visuFiber.vtk") ;
    writeFiberFile( fiberPolyData , outputFileName ) ;
    writeFiberFile( cleanedFiberPolyData , "cleanedFiber.vtk" ) ;
    return 0 ;
}
<commit_msg>BUG: cleanedFiber and visuFiber now both visualizable.<commit_after>#include <vtkSmoothPolyDataFilter.h>
#include <vtkSmartPointer.h>
#include <vtkPolyData.h>
#include <vtkPolyDataReader.h>
#include <vtkPolyDataWriter.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkXMLPolyDataWriter.h>
#include <vtkFloatArray.h>
#include <vtkPointData.h>
#include <vtkCell.h>
#include <vtkCellData.h>
#include <vtkCellArray.h>
#include <iostream>
#include <cstring>
#include <string>
#include <string.h>
#include "processing.h"

#include <itkImage.h>
#include <itkImageFileReader.h>
#include "itkImageToVTKImageFilter.h"

#include <vtkImageWriter.h>
#include <itkPoint.h>
#include <itkLinearInterpolateImageFunction.h>

#include <vtkCellArray.h>
#include <vtkDoubleArray.h>

#include <vtkPointData.h>

#include <vtkPolyLine.h>

processing::processing( int visuAttribute )
{
    visualize = visuAttribute ;
}

std::string processing::ExtensionofFile( std::string filename )
{
    std::string extension ;
    extension = filename.substr( filename.find_last_of(".")+1,filename.size()-filename.find_last_of( "." ) + 1 ) ;
    return extension ;
}

void processing::FindAllData( vtkSmartPointer< vtkPolyData > polydata )
{
    polydata->GetLines()->InitTraversal() ;
    std::cout << "Normals: " << polydata->GetPointData()->GetNormals() << std::endl ;
    vtkIdType numberOfPointArrays = polydata->GetPointData()->GetNumberOfArrays() ;
    std::cout << "Lines: " << polydata->GetNumberOfLines() << std::endl ;
    vtkSmartPointer< vtkIdList > idList = vtkSmartPointer< vtkIdList >::New() ;
    std::cout << "Cells: " << polydata->GetNumberOfCells() << std::endl ;
    std::cout << "Points: " << polydata->GetNumberOfPoints() << std::endl ;
    std::cout << "Polys: " << polydata->GetNumberOfPolys() << std::endl ;
    std::cout << "Strips: " << polydata->GetNumberOfStrips() << std::endl ;
    std::cout << "Verts: " << polydata->GetNumberOfVerts() << std::endl ;
    int i=1;
    while( polydata->GetLines()->GetNextCell( idList ) )
    {
        std::cout<< "Line " << i << ": " << idList->GetNumberOfIds() << " points" <<std::endl ;
        i++;
        for( vtkIdType pointId = 0 ; pointId < idList->GetNumberOfIds() ; pointId++ )
        {
            /*std::cout <<idList->GetId( pointId ) << " " ;*/
        }
    }
}
template <class T>
vtkSmartPointer< vtkPolyData > processing::readFiberFile( T reader , std::string fiberFile )
{
    vtkSmartPointer< vtkPolyData > PolyData ;
    reader->SetFileName( fiberFile.c_str() ) ;
    PolyData=reader->GetOutput() ;
    reader->Update() ;
    return PolyData ;
}

void processing::writeFiberFile( vtkSmartPointer< vtkPolyData > PolyData , std::string outputFileName )
{
    vtkSmartPointer< vtkPolyDataWriter > writer = vtkSmartPointer< vtkPolyDataWriter >::New() ;
    writer->SetInputData( PolyData ) ;
    //writer->SetDataModeToBinary() ;
    writer->SetFileName( outputFileName.c_str() ) ;
    writer->Update() ;
}

vtkSmartPointer< vtkPolyData > processing::ApplyMaskToFiber( vtkSmartPointer< vtkPolyData > PolyData , std::string maskFileName )
{
    typedef itk::Image< int , 3 > ImageType ;
    typedef itk::ImageFileReader< ImageType > ReaderType ;
    ReaderType::Pointer readerMask = ReaderType::New() ;
    readerMask->SetFileName( maskFileName ) ;
    readerMask->Update() ;
    ImageType::Pointer maskImage = ImageType::New() ;
    maskImage = readerMask->GetOutput() ;
    typedef itk::Index< 3 > IndexType ;
    ImageType::IndexType index ;
    typedef itk::LinearInterpolateImageFunction< ImageType , double > InterpolationType ;
    InterpolationType::Pointer interp = InterpolationType::New() ;
    interp->SetInputImage( maskImage ) ;
    itk::Point< double , 3 > p ;
    const int nfib = PolyData->GetNumberOfCells() ;
    std::cout<< nfib <<std::endl;
    // Inserting an array corresponding to the % of the fiber which is not inside the mask
    vtkSmartPointer< vtkDoubleArray > fiberData = vtkSmartPointer< vtkDoubleArray >::New() ;
    vtkSmartPointer< vtkDoubleArray > pointData = vtkSmartPointer< vtkDoubleArray >::New() ;
    for( int i = 0 ; i < nfib ; ++i )
    {
        float badPixel = 0.0f ;
        std::cout << " FIBER NUMBER " << i << std::endl ;
        vtkSmartPointer< vtkCell > fiber = PolyData->GetCell( i ) ;
        vtkSmartPointer< vtkPoints > fiberPoints = fiber->GetPoints() ;
        for( int j = 0 ; j < fiberPoints->GetNumberOfPoints() ; ++j )
        {
            double* coordinates = fiberPoints->GetPoint( j ) ;
            /* Flip the coordinates */
            coordinates[0] = - coordinates[0] ;
            coordinates[1] = - coordinates[1] ;
            p[0] = coordinates[0] ;
            p[1] = coordinates[1] ;
            p[2] = coordinates[2] ;
            maskImage->TransformPhysicalPointToIndex( p , index ) ;
            //Checks if the index is inside the image boundaries
            if( !interp->IsInsideBuffer( index ) )
            {
                std::cout << "Index out of bounds" << std::endl ;
            }
            else
            {
            }
            ImageType::PixelType pixel = maskImage->GetPixel( index ) ;
            if(pixel == 255)
            {

                badPixel = badPixel +1.0f ;
                pointData->SetNumberOfComponents( 1 ) ;
                pointData->SetName( "InsideMask" ) ;
                pointData->InsertNextValue( 255 ) ;
            }
            else
            {
                pointData->InsertNextValue( 0 ) ;
            }
        }
        std::cout << "Pixels out of mask = " << badPixel << std::endl ;
        fiberData->SetNumberOfComponents( nfib ) ;
        fiberData->SetName( "UnwantedFiber" ) ;
        fiberData->InsertNextValue( badPixel/fiberPoints->GetNumberOfPoints()*100 ) ;

        // Reading the data inserted
        std::cout<< "% of the fiber outside of the mask = " << badPixel/fiberPoints->GetNumberOfPoints()*100 << "%" <<std::endl ;
    }
    PolyData->GetPointData()->AddArray( pointData ) ;
    PolyData->GetCellData()->AddArray( fiberData ) ;
    return PolyData ;
}

vtkSmartPointer< vtkPolyData > processing::AddPointData( vtkSmartPointer< vtkPolyData > PolyData )
{
    const int nfib = PolyData->GetNumberOfCells() ;
    vtkSmartPointer< vtkDoubleArray > pointData = vtkSmartPointer< vtkDoubleArray >::New() ;
    for( int i = 0 ; i < nfib ; ++i )
    {
        vtkSmartPointer< vtkCell > fiber = PolyData->GetCell( i ) ;
        vtkSmartPointer< vtkPoints > fiberPoints = fiber->GetPoints() ;
        for( int j = 0 ; j < fiberPoints->GetNumberOfPoints() ; ++j )
        {
            pointData->SetNumberOfComponents( 1 ) ;
            pointData->SetName( "InsideMask" ) ;
            pointData->InsertNextValue( 0 ) ;
        }

    }
    PolyData->GetPointData()->AddArray( pointData ) ;
    return PolyData;
}

vtkSmartPointer< vtkPolyData > processing::CleanFiber( vtkSmartPointer< vtkPolyData > PolyData , float threshold )
{
    vtkSmartPointer< vtkPolyData > NewPolyData = vtkSmartPointer< vtkPolyData >::New() ;
    //vtkSmartPointer<vtkFloatArray> NewTensors=vtkSmartPointer<vtkFloatArray>::New();
    vtkSmartPointer<vtkPoints> NewPoints = vtkSmartPointer<vtkPoints>::New() ;
    vtkSmartPointer<vtkCellArray> NewLines = vtkSmartPointer<vtkCellArray>::New() ;
    vtkPoints* Points = PolyData->GetPoints() ;
    vtkCellArray* Lines = PolyData->GetLines() ;
    vtkIdType* Ids ;
    vtkIdType NumberOfPoints ;
    int NewId = 0 ;
    vtkSmartPointer< vtkDoubleArray > fiberReadArray = vtkSmartPointer< vtkDoubleArray >::New() ;
    fiberReadArray = vtkDoubleArray::SafeDownCast( PolyData->GetCellData()->GetArray("UnwantedFiber") ) ;
    Lines->InitTraversal() ;
    for( int i = 0 ; Lines->GetNextCell( NumberOfPoints , Ids ) ; i++ )
    {
        vtkSmartPointer< vtkPolyLine > NewLine = vtkSmartPointer< vtkPolyLine >::New() ;
        NewLine->GetPointIds()->SetNumberOfIds( NumberOfPoints ) ;
        std::cout << " FIBER NUMBER " << i << std::endl ;
        std::cout << fiberReadArray->GetValue( i ) <<"%"<<std::endl ;
        if( fiberReadArray->GetValue( i ) <= threshold )
        {
            for( int j = 0 ; j < NumberOfPoints ; j ++ )
            {
                NewPoints->InsertNextPoint( Points->GetPoint( Ids[j] ) ) ;
                NewLine->GetPointIds()->SetId( j , NewId ) ;
                NewId++ ;
            }
            NewLines->InsertNextCell( NewLine ) ;
       }
        else
        {
            std::cout << "Deleted" <<std::endl ;
        }
    }
    NewPolyData->SetPoints( NewPoints ) ;
    NewPolyData->SetLines( NewLines ) ;
    return NewPolyData ;
}

vtkSmartPointer< vtkPolyData > processing::CreateVisuFiber( vtkSmartPointer< vtkPolyData > PolyData )
{
    vtkSmartPointer< vtkPolyData > NewPolyData = vtkSmartPointer< vtkPolyData >::New() ;
    vtkSmartPointer<vtkPoints> NewPoints = vtkSmartPointer<vtkPoints>::New() ;
    vtkSmartPointer<vtkCellArray> NewLines = vtkSmartPointer<vtkCellArray>::New() ;
    vtkSmartPointer< vtkDoubleArray > pointData = vtkSmartPointer< vtkDoubleArray >::New() ;
    vtkPoints* Points = PolyData->GetPoints() ;
    vtkCellArray* Lines = PolyData->GetLines() ;
    vtkIdType* Ids ;
    vtkIdType NumberOfPoints ;
    int NewId = 0 ;
    Lines->InitTraversal() ;
    const int nfib = PolyData->GetNumberOfCells() ;
    for( int i = 0 ; Lines->GetNextCell( NumberOfPoints , Ids ) ; i++ )
    {
        vtkSmartPointer< vtkPolyLine > NewLine = vtkSmartPointer< vtkPolyLine >::New() ;
        NewLine->GetPointIds()->SetNumberOfIds( NumberOfPoints ) ;
        for( int j = 0 ; j < NumberOfPoints ; j ++ )
        {
            NewPoints->InsertNextPoint( Points->GetPoint( Ids[j] ) ) ;
            NewLine->GetPointIds()->SetId( j , NewId ) ;
            NewId++ ;
        }
        NewLines->InsertNextCell( NewLine ) ;
    }
    NewPolyData->SetPoints( NewPoints ) ;
    NewPolyData->SetLines( NewLines ) ;
    NewPolyData->GetPointData()->AddArray( PolyData->GetPointData()->GetAbstractArray( 1 ) ) ;
    return NewPolyData ;

}

int processing::processing_main(std::string& inputFileName ,
                                std::string& outputFileName ,
                                std::string& maskFileName ,
                                float threshold )
{
    typedef itk::Image< int , 3 > ImageType ;
    typedef itk::ImageFileReader< ImageType > ReaderType ;
    vtkSmartPointer< vtkPolyData > fiberPolyData ;
    vtkSmartPointer< vtkPolyData > cleanedFiberPolyData ;
    std::string extension = ExtensionofFile( inputFileName ) ;
    if( extension.rfind("vtk") != std::string::npos )
    {
        vtkSmartPointer< vtkPolyDataReader > fiberPolyDataReader = vtkSmartPointer< vtkPolyDataReader >::New() ;
        fiberPolyData = readFiberFile( fiberPolyDataReader, inputFileName ) ;
    }
    else if( extension.rfind("vtp") != std::string::npos )
    {
        vtkSmartPointer<vtkXMLPolyDataReader> fiberPolyDataReader = vtkSmartPointer< vtkXMLPolyDataReader >::New() ;
        fiberPolyData = readFiberFile( fiberPolyDataReader, inputFileName ) ;
    }
    else
    {
        std::cout << "File could not be read" << std::endl ;
        return 1 ;
    }
    FindAllData( fiberPolyData ) ;
    fiberPolyData = ApplyMaskToFiber( fiberPolyData , maskFileName ) ;
    cleanedFiberPolyData = CleanFiber(fiberPolyData , threshold ) ;
    cleanedFiberPolyData = AddPointData( cleanedFiberPolyData ) ;
    vtkSmartPointer< vtkPolyData > visuFiber = vtkSmartPointer< vtkPolyData >::New() ;
    if( visualize )
    {
        visuFiber = CreateVisuFiber( fiberPolyData ) ;
    }
    writeFiberFile( visuFiber , "visuFiber.vtk") ;
    writeFiberFile( fiberPolyData , outputFileName ) ;
    writeFiberFile( cleanedFiberPolyData , "cleanedFiber.vtk" ) ;
    return 0 ;
}
<|endoftext|>


<commit_before>// Filename: mutexDebug.cxx
// Created by:  drose (13Feb06)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001 - 2004, Disney Enterprises, Inc.  All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license.  You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://etc.cmu.edu/panda3d/docs/license/ .
//
// To contact the maintainers of this program write to
// panda3d-general@lists.sourceforge.net .
//
////////////////////////////////////////////////////////////////////

#include "mutexDebug.h"
#include "thread.h"
#include "config_pipeline.h"

#ifdef DEBUG_THREADS

MutexImpl *MutexDebug::_global_lock;

////////////////////////////////////////////////////////////////////
//     Function: MutexDebug::Constructor
//       Access: Protected
//  Description:
////////////////////////////////////////////////////////////////////
MutexDebug::
MutexDebug(const string &name, bool allow_recursion) :
  _name(name),
  _allow_recursion(allow_recursion),
  _locking_thread(NULL),
  _lock_count(0),
  _cvar_impl(*get_global_lock())
{
}

////////////////////////////////////////////////////////////////////
//     Function: MutexDebug::Destructor
//       Access: Protected, Virtual
//  Description:
////////////////////////////////////////////////////////////////////
MutexDebug::
~MutexDebug() {
  nassertv(_locking_thread == NULL && _lock_count == 0);

  // Put a distinctive, bogus lock count in upon destruction, so we'll
  // be more likely to notice a floating pointer.
  _lock_count = -100;
}

////////////////////////////////////////////////////////////////////
//     Function: MutexDebug::output
//       Access: Public, Virtual
//  Description: This method is declared virtual in MutexDebug, but
//               non-virtual in MutexDirect.
////////////////////////////////////////////////////////////////////
void MutexDebug::
output(ostream &out) const {
  if (_allow_recursion) {
    out << "ReMutex " << _name << " " << (void *)this;
  } else {
    out << "Mutex " << _name << " " << (void *)this;
  }
}

////////////////////////////////////////////////////////////////////
//     Function: MutexDebug::do_lock
//       Access: Private
//  Description: The private implementation of lock() assumes that
//               _lock_impl is held.
////////////////////////////////////////////////////////////////////
void MutexDebug::
do_lock() {
  // If this assertion is triggered, you tried to lock a
  // recently-destructed mutex.
  nassertv(_lock_count != -100);

  Thread *this_thread = Thread::get_current_thread();

  if (_locking_thread == (Thread *)NULL) {
    // The mutex is not already locked by anyone.  Lock it.
    _locking_thread = this_thread;
    ++_lock_count;
    nassertv(_lock_count == 1);

  } else if (_locking_thread == this_thread) {
    // The mutex is already locked by this thread.  Increment the lock
    // count.
    nassertv(_lock_count >= 0);
    if (!_allow_recursion && _lock_count == 0) {
      ostringstream ostr;
      ostr << *_locking_thread << " attempted to re-lock non-reentrant "
           << *this;
      nassert_raise(ostr.str());
      return;
    }
    ++_lock_count;

  } else {
    // The mutex is locked by some other thread.

    // Check for deadlock.
    MutexDebug *next_mutex = this;
    while (next_mutex != NULL) {
      if (next_mutex->_locking_thread == this_thread) {
        // Whoops, the thread is blocked on me!  Deadlock!
        report_deadlock(this_thread);
        nassert_raise("Deadlock");

        _global_lock->release();
        return;
      }
      Thread *next_thread = next_mutex->_locking_thread;
      if (next_thread == NULL) {
        // Looks like this mutex isn't actually locked, which means
        // the last thread isn't really blocked--it just hasn't woken
        // up yet to discover that.  In any case, no deadlock.
        break;
      }

      // The last thread is blocked on this "next thread"'s mutex, but
      // what mutex is the next thread blocked on?
      next_mutex = next_thread->_blocked_on_mutex;
    }

    // OK, no deadlock detected.  Carry on.
    this_thread->_blocked_on_mutex = this;

    // Go to sleep on the condition variable until it's unlocked.

    if (thread_cat.is_spam()) {
      thread_cat.spam()
        << *this_thread << " blocking on " << *this << " (held by "
        << *_locking_thread << ")\n";
    }
    while (_locking_thread != (Thread *)NULL) {
      _cvar_impl.wait();
    }

    if (thread_cat.is_spam()) {
      thread_cat.spam()
        << *this_thread << " awake on " << *this << "\n";
    }

    this_thread->_blocked_on_mutex = NULL;

    _locking_thread = this_thread;
    ++_lock_count;
    nassertv(_lock_count == 1);
  }
}

////////////////////////////////////////////////////////////////////
//     Function: MutexDebug::do_release
//       Access: Private
//  Description: The private implementation of lock() assumes that
//               _lock_impl is held.
////////////////////////////////////////////////////////////////////
void MutexDebug::
do_release() {
  // If this assertion is triggered, you tried to release a
  // recently-destructed mutex.
  nassertv(_lock_count != -100);

  Thread *this_thread = Thread::get_current_thread();

  if (_locking_thread != this_thread) {
    ostringstream ostr;
    ostr << *this_thread << " attempted to release "
         << *this << " which it does not own";
    nassert_raise(ostr.str());
    _global_lock->release();
    return;
  }

  nassertv(_lock_count > 0);

  --_lock_count;
  if (_lock_count == 0) {
    // That was the last lock held by this thread.  Release the lock.
    _locking_thread = (Thread *)NULL;
    _cvar_impl.signal();
  }
}

////////////////////////////////////////////////////////////////////
//     Function: MutexDebug::do_debug_is_locked
//       Access: Private
//  Description: The private implementation of debug_is_locked()
//               assumes that _lock_impl is held.
////////////////////////////////////////////////////////////////////
bool MutexDebug::
do_debug_is_locked() const {
  return (_locking_thread == Thread::get_current_thread());
}

////////////////////////////////////////////////////////////////////
//     Function: MutexDebug::report_deadlock
//       Access: Private
//  Description: Reports a detected deadlock situation.  _lock_impl
//               should be already held.
////////////////////////////////////////////////////////////////////
void MutexDebug::
report_deadlock(Thread *this_thread) {
  thread_cat.error()
    << "\n\n"
    << "****************************************************************\n"
    << "*****                 Deadlock detected!                   *****\n"
    << "****************************************************************\n"
    << "\n";

  thread_cat.error()
    << *this_thread << " attempted to lock " << *this
    << " which is held by " << *_locking_thread << "\n";

  MutexDebug *next_mutex = this;
  Thread *next_thread = next_mutex->_locking_thread;
  next_mutex = next_thread->_blocked_on_mutex;
  while (next_mutex != NULL) {
    thread_cat.error()
      << *next_thread << " is blocked waiting on "
      << *next_mutex << " which is held by "
      << *next_mutex->_locking_thread << "\n";
    next_thread = next_mutex->_locking_thread;
    next_mutex = next_thread->_blocked_on_mutex;
  }

  thread_cat.error()
    << "Deadlock!\n";
}

#endif  //  DEBUG_THREADS
<commit_msg>fix double-lock detection<commit_after>// Filename: mutexDebug.cxx
// Created by:  drose (13Feb06)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001 - 2004, Disney Enterprises, Inc.  All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license.  You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://etc.cmu.edu/panda3d/docs/license/ .
//
// To contact the maintainers of this program write to
// panda3d-general@lists.sourceforge.net .
//
////////////////////////////////////////////////////////////////////

#include "mutexDebug.h"
#include "thread.h"
#include "config_pipeline.h"

#ifdef DEBUG_THREADS

MutexImpl *MutexDebug::_global_lock;

////////////////////////////////////////////////////////////////////
//     Function: MutexDebug::Constructor
//       Access: Protected
//  Description:
////////////////////////////////////////////////////////////////////
MutexDebug::
MutexDebug(const string &name, bool allow_recursion) :
  _name(name),
  _allow_recursion(allow_recursion),
  _locking_thread(NULL),
  _lock_count(0),
  _cvar_impl(*get_global_lock())
{
}

////////////////////////////////////////////////////////////////////
//     Function: MutexDebug::Destructor
//       Access: Protected, Virtual
//  Description:
////////////////////////////////////////////////////////////////////
MutexDebug::
~MutexDebug() {
  nassertv(_locking_thread == NULL && _lock_count == 0);

  // Put a distinctive, bogus lock count in upon destruction, so we'll
  // be more likely to notice a floating pointer.
  _lock_count = -100;
}

////////////////////////////////////////////////////////////////////
//     Function: MutexDebug::output
//       Access: Public, Virtual
//  Description: This method is declared virtual in MutexDebug, but
//               non-virtual in MutexDirect.
////////////////////////////////////////////////////////////////////
void MutexDebug::
output(ostream &out) const {
  if (_allow_recursion) {
    out << "ReMutex " << _name << " " << (void *)this;
  } else {
    out << "Mutex " << _name << " " << (void *)this;
  }
}

////////////////////////////////////////////////////////////////////
//     Function: MutexDebug::do_lock
//       Access: Private
//  Description: The private implementation of lock() assumes that
//               _lock_impl is held.
////////////////////////////////////////////////////////////////////
void MutexDebug::
do_lock() {
  // If this assertion is triggered, you tried to lock a
  // recently-destructed mutex.
  nassertv(_lock_count != -100);

  Thread *this_thread = Thread::get_current_thread();

  if (_locking_thread == (Thread *)NULL) {
    // The mutex is not already locked by anyone.  Lock it.
    _locking_thread = this_thread;
    ++_lock_count;
    nassertv(_lock_count == 1);

  } else if (_locking_thread == this_thread) {
    // The mutex is already locked by this thread.  Increment the lock
    // count.
    nassertv(_lock_count > 0);
    if (!_allow_recursion) {
      ostringstream ostr;
      ostr << *_locking_thread << " attempted to double-lock non-reentrant "
           << *this;
      nassert_raise(ostr.str());
    }
    ++_lock_count;

  } else {
    // The mutex is locked by some other thread.

    // Check for deadlock.
    MutexDebug *next_mutex = this;
    while (next_mutex != NULL) {
      if (next_mutex->_locking_thread == this_thread) {
        // Whoops, the thread is blocked on me!  Deadlock!
        report_deadlock(this_thread);
        nassert_raise("Deadlock");

        _global_lock->release();
        return;
      }
      Thread *next_thread = next_mutex->_locking_thread;
      if (next_thread == NULL) {
        // Looks like this mutex isn't actually locked, which means
        // the last thread isn't really blocked--it just hasn't woken
        // up yet to discover that.  In any case, no deadlock.
        break;
      }

      // The last thread is blocked on this "next thread"'s mutex, but
      // what mutex is the next thread blocked on?
      next_mutex = next_thread->_blocked_on_mutex;
    }

    // OK, no deadlock detected.  Carry on.
    this_thread->_blocked_on_mutex = this;

    // Go to sleep on the condition variable until it's unlocked.

    if (thread_cat.is_spam()) {
      thread_cat.spam()
        << *this_thread << " blocking on " << *this << " (held by "
        << *_locking_thread << ")\n";
    }
    while (_locking_thread != (Thread *)NULL) {
      _cvar_impl.wait();
    }

    if (thread_cat.is_spam()) {
      thread_cat.spam()
        << *this_thread << " awake on " << *this << "\n";
    }

    this_thread->_blocked_on_mutex = NULL;

    _locking_thread = this_thread;
    ++_lock_count;
    nassertv(_lock_count == 1);
  }
}

////////////////////////////////////////////////////////////////////
//     Function: MutexDebug::do_release
//       Access: Private
//  Description: The private implementation of lock() assumes that
//               _lock_impl is held.
////////////////////////////////////////////////////////////////////
void MutexDebug::
do_release() {
  // If this assertion is triggered, you tried to release a
  // recently-destructed mutex.
  nassertv(_lock_count != -100);

  Thread *this_thread = Thread::get_current_thread();

  if (_locking_thread != this_thread) {
    ostringstream ostr;
    ostr << *this_thread << " attempted to release "
         << *this << " which it does not own";
    nassert_raise(ostr.str());
    _global_lock->release();
    return;
  }

  nassertv(_lock_count > 0);

  --_lock_count;
  if (_lock_count == 0) {
    // That was the last lock held by this thread.  Release the lock.
    _locking_thread = (Thread *)NULL;
    _cvar_impl.signal();
  }
}

////////////////////////////////////////////////////////////////////
//     Function: MutexDebug::do_debug_is_locked
//       Access: Private
//  Description: The private implementation of debug_is_locked()
//               assumes that _lock_impl is held.
////////////////////////////////////////////////////////////////////
bool MutexDebug::
do_debug_is_locked() const {
  return (_locking_thread == Thread::get_current_thread());
}

////////////////////////////////////////////////////////////////////
//     Function: MutexDebug::report_deadlock
//       Access: Private
//  Description: Reports a detected deadlock situation.  _lock_impl
//               should be already held.
////////////////////////////////////////////////////////////////////
void MutexDebug::
report_deadlock(Thread *this_thread) {
  thread_cat.error()
    << "\n\n"
    << "****************************************************************\n"
    << "*****                 Deadlock detected!                   *****\n"
    << "****************************************************************\n"
    << "\n";

  thread_cat.error()
    << *this_thread << " attempted to lock " << *this
    << " which is held by " << *_locking_thread << "\n";

  MutexDebug *next_mutex = this;
  Thread *next_thread = next_mutex->_locking_thread;
  next_mutex = next_thread->_blocked_on_mutex;
  while (next_mutex != NULL) {
    thread_cat.error()
      << *next_thread << " is blocked waiting on "
      << *next_mutex << " which is held by "
      << *next_mutex->_locking_thread << "\n";
    next_thread = next_mutex->_locking_thread;
    next_mutex = next_thread->_blocked_on_mutex;
  }

  thread_cat.error()
    << "Deadlock!\n";
}

#endif  //  DEBUG_THREADS
<|endoftext|>


<commit_before>#include "prog_solver.h"

#include "OsiSolverInterface.hpp"

#include "prog_translator.h"
#include "greedy_solver.h"
#include "solver_factory.h"

namespace cyclus {

void Report(OsiSolverInterface* iface) {
  std::cout << iface->getNumCols() << " total variables, "
            << iface->getNumIntegers() << " integer.\n";
  std::cout << iface->getNumRows() << " constraints\n";
}

ProgSolver::ProgSolver(std::string solver_t)
    : solver_t_(solver_t),
      tmax_(ProgSolver::KOptimizeDefaultTimeout),
      ExchangeSolver(false) {}

ProgSolver::ProgSolver(std::string solver_t, bool exclusive_orders)
    : solver_t_(solver_t),
      tmax_(ProgSolver::KOptimizeDefaultTimeout),
      ExchangeSolver(exclusive_orders) {}

ProgSolver::ProgSolver(std::string solver_t, double tmax)
    : solver_t_(solver_t),
      tmax_(tmax),
      ExchangeSolver(false) {}

ProgSolver::ProgSolver(std::string solver_t, double tmax, bool exclusive_orders)
    : solver_t_(solver_t),
      tmax_(tmax),
      ExchangeSolver(exclusive_orders) {}

ProgSolver::~ProgSolver() {}

double ProgSolver::SolveGraph() {
  SolverFactory sf(solver_t_, tmax_);
  OsiSolverInterface* iface = sf.get();
  try {
    // get greedy solution
    GreedySolver greedy(exclusive_orders_);
    double greedy_obj = greedy.Solve(graph_);
    graph_->ClearMatches();

    // translate graph to iface instance
    double pseudo_cost = PseudoCost(); // from ExchangeSolver API
    ProgTranslator xlator(graph_, iface, exclusive_orders_, pseudo_cost);
    xlator.ToProg();

    // set noise level
    CoinMessageHandler h;
    h.setLogLevel(0);
    if (verbose_) {
      Report(iface);
      h.setLogLevel(4);
    }
    iface->passInMessageHandler(&h);
    if (verbose_) {
      std::cout << "Solving problem, message handler has log level of "
                << iface->messageHandler()->logLevel() << "\n";
    }
    bool verbose = false; // turn this off, solveprog prints a lot

    // solve and back translate
    SolveProg(iface, greedy_obj, verbose);
    xlator.FromProg();
  } catch(...) {
    delete iface;
    throw;
  }
  double ret = iface->getObjValue();
  delete iface;
  return ret;
}

}  // namespace cyclus
<commit_msg>adding some debugging, I see errors in cycamore<commit_after>#include "prog_solver.h"

#include "OsiSolverInterface.hpp"

#include "prog_translator.h"
#include "greedy_solver.h"
#include "solver_factory.h"

namespace cyclus {

void Report(OsiSolverInterface* iface) {
  std::cout << iface->getNumCols() << " total variables, "
            << iface->getNumIntegers() << " integer.\n";
  std::cout << iface->getNumRows() << " constraints\n";
}

ProgSolver::ProgSolver(std::string solver_t)
    : solver_t_(solver_t),
      tmax_(ProgSolver::KOptimizeDefaultTimeout),
      ExchangeSolver(false) {}

ProgSolver::ProgSolver(std::string solver_t, bool exclusive_orders)
    : solver_t_(solver_t),
      tmax_(ProgSolver::KOptimizeDefaultTimeout),
      ExchangeSolver(exclusive_orders) {}

ProgSolver::ProgSolver(std::string solver_t, double tmax)
    : solver_t_(solver_t),
      tmax_(tmax),
      ExchangeSolver(false) {}

ProgSolver::ProgSolver(std::string solver_t, double tmax, bool exclusive_orders)
    : solver_t_(solver_t),
      tmax_(tmax),
      ExchangeSolver(exclusive_orders) {}

ProgSolver::~ProgSolver() {}

double ProgSolver::SolveGraph() {
  SolverFactory sf(solver_t_, tmax_);
  OsiSolverInterface* iface = sf.get();
  try {
    // get greedy solution
    GreedySolver greedy(exclusive_orders_);
    double greedy_obj = greedy.Solve(graph_);
    graph_->ClearMatches();

    // translate graph to iface instance
    double pseudo_cost = PseudoCost(); // from ExchangeSolver API
    ProgTranslator xlator(graph_, iface, exclusive_orders_, pseudo_cost);
    xlator.ToProg();

    // set noise level
    CoinMessageHandler h;
    h.setLogLevel(0);
    verbose_ = true;
    if (verbose_) {
      Report(iface);
      h.setLogLevel(4);
    }
    iface->passInMessageHandler(&h);
    if (verbose_) {
      std::cout << "Solving problem, message handler has log level of "
                << iface->messageHandler()->logLevel() << "\n";
    }
    //bool verbose = false; // turn this off, solveprog prints a lot
    bool verbose = true; // turn this on for logging

    // solve and back translate
    SolveProg(iface, greedy_obj, verbose);
    xlator.FromProg();
  } catch(...) {
    delete iface;
    throw;
  }
  double ret = iface->getObjValue();
  delete iface;
  return ret;
}

}  // namespace cyclus
<|endoftext|>


<commit_before>#include "pulseaudio.h"

#include <QDebug>
#include <QMetaEnum>

#include "card.h"
#include "client.h"
#include "sink.h"
#include "sinkinput.h"
#include "source.h"
#include "sourceoutput.h"

ClientModel::ClientModel(QObject *parent)
    : AbstractModel(&context()->clients(), parent)
{
}

int ClientModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    if (!context())
        return 0;
    return context()->clients().data().count();
}

QVariant ClientModel::data(const QModelIndex &index, int role) const
{
    Client *client = context()->clients().data().values().at(index.row());
    Q_ASSERT(client);
    switch(static_cast<ItemRole>(role)){
    case NameRole:
        return client->name();
    case PulseObjectRole:
        return QVariant::fromValue(client);
    }
    return QVariant();
}

SinkInputModel::SinkInputModel(QObject *parent)
    : AbstractModel(&context()->sinkInputs(), parent)
{
}

int SinkInputModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    if (!context())
        return 0;
    return context()->sinkInputs().data().count();
}

QVariant SinkInputModel::data(const QModelIndex &index, int role) const
{
    SinkInput *data = context()->sinkInputs().data().values().at(index.row());
    Q_ASSERT(data);

    // Try to resolve by enum value.
    switch ((ItemRole) role) {
    case IndexRole:
        return data->index();
    case PulseObjectRole:
        return QVariant::fromValue(data);
    }

    return QVariant();
}

QHash<int, QByteArray> AbstractModel::roleNames() const
{
    if (!m_roles.empty()) {
        qDebug() << "returning roles" << m_roles;
        return m_roles;
    }

    QHash<int, QByteArray> roles;

    QMetaEnum enumerator;
    for (int i = 0; i < metaObject()->enumeratorCount(); ++i) {
        if (metaObject()->enumerator(i).name() == QLatin1Literal("ItemRole")) {
            enumerator = metaObject()->enumerator(i);
            break;
        }
    }

    Q_ASSERT(enumerator.scope() == metaObject()->className());
    // No valid enum found, leaf probably doesn't implement ItemRole (correctly).
    Q_ASSERT(enumerator.isValid());

    for (int i = 0; i < enumerator.keyCount(); ++i) {
        // Clip the Role suffix and glue it in the hash.
        static int roleLength = strlen("Role");
        QByteArray key(enumerator.key(i));
        // Enum values must end in Role or the enum is crap
        Q_ASSERT(key.right(roleLength) == QByteArray("Role"));
        key.chop(roleLength);
        roles[enumerator.value(i)] = key;
    }

    qDebug() << roles;
    return roles;
}

SinkModel::SinkModel(QObject *parent)
    : AbstractModel(&context()->sinks(), parent)
{
    connect(&context()->sinks(), &SinkMap::added, this, &SinkModel::sinksChanged);
    connect(&context()->sinks(), &SinkMap::updated, this, &SinkModel::sinksChanged);
    connect(&context()->sinks(), &SinkMap::removed, this, &SinkModel::sinksChanged);

    emit sinksChanged();
}

#warning very naughty, used by main.qml to set volume on all sinks
QList<QObject *> SinkModel::sinks() const
{
    QList <QObject *> ret;
    if (!context())
        return ret;
    for (Sink *sink : context()->sinks().data().values()) {
        ret << sink;
    }
    return ret;
}

int SinkModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    if (!context())
        return 0;
    return context()->sinks().data().count();
}

QVariant SinkModel::data(const QModelIndex &index, int role) const
{
    qDebug() << IndexRole << role;
    Sink *sink = context()->sinks().data().values().at(index.row());
    Q_ASSERT(sink);
    switch(static_cast<ItemRole>(role)) {
    case IndexRole:
        return sink->index();
    case PulseObjectRole:
        return QVariant::fromValue(sink);
    }
    return QVariant();
}

void AbstractModel::onDataAdded(quint32 index)
{
    beginInsertRows(QModelIndex(), index, index);
    endInsertRows();
}

void AbstractModel::onDataUpdated(quint32 index)
{
    emit dataChanged(createIndex(index, 0), createIndex(index, 0));
}

void AbstractModel::onDataRemoved(quint32 index)
{
    beginRemoveRows(QModelIndex(), index, index);
    endRemoveRows();
}

AbstractModel::AbstractModel(const MapBaseQObject *map, QObject *parent)
    : QAbstractListModel(parent)
{
    connect(map, &MapBaseQObject::added, this, &AbstractModel::onDataAdded);
    connect(map, &MapBaseQObject::updated, this, &AbstractModel::onDataUpdated);
    connect(map, &MapBaseQObject::removed, this, &AbstractModel::onDataRemoved);
}

#warning probably should be called from constructor and it should get the mo passed

void AbstractModel::initRoleNames(const QMetaObject &qobjectMetaObject)
{
    QMetaEnum enumerator;
    for (int i = 0; i < metaObject()->enumeratorCount(); ++i) {
        if (metaObject()->enumerator(i).name() == QLatin1Literal("ItemRole")) {
            enumerator = metaObject()->enumerator(i);
            break;
        }
    }

    Q_ASSERT(enumerator.scope() == metaObject()->className());
    // No valid enum found, leaf probably doesn't implement ItemRole (correctly).
    Q_ASSERT(enumerator.isValid());

    for (int i = 0; i < enumerator.keyCount(); ++i) {
        // Clip the Role suffix and glue it in the hash.
        static int roleLength = strlen("Role");
        QByteArray key(enumerator.key(i));
        // Enum values must end in Role or the enum is crap
        Q_ASSERT(key.right(roleLength) == QByteArray("Role"));
        key.chop(roleLength);
        m_roles[enumerator.value(i)] = key;
    }

    int maxEnumValue = -1;
    for (auto it = m_roles.constBegin(); it != m_roles.constEnd(); ++it) {
        if (it.key() > maxEnumValue)
            maxEnumValue = it.key();
    }
    Q_ASSERT(maxEnumValue != -1);
    auto mo = qobjectMetaObject;
    for (int i = 0; i < mo.propertyCount(); ++i) {
        QString property(mo.property(i).name());
        property.replace(0, 1, property.at(0).toUpper());
        m_roles[++maxEnumValue] = property.toLatin1();
        m_objectProperties.insert(maxEnumValue, i);
    }
    qDebug() << m_roles;
}

ReverseFilterModel::ReverseFilterModel(QObject *parent)
    : QSortFilterProxyModel(parent)
{
    setDynamicSortFilter(true);
    setFilterKeyColumn(0);
}

void ReverseFilterModel::initialSort()
{
    QSortFilterProxyModel::sort(0, Qt::DescendingOrder);
}

SourceModel::SourceModel(QObject *parent)
    : AbstractModel(&context()->sources(), parent)
{
}

int SourceModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    if (!context())
        return 0;
    return context()->sources().data().count();
}

QVariant SourceModel::data(const QModelIndex &index, int role) const
{
    Source *source = context()->sources().data().values().at(index.row());
    Q_ASSERT(source);
    switch(static_cast<ItemRole>(role)) {
    case IndexRole:
        return source->index();
    case PulseObjectRole:
        return QVariant::fromValue(source);
    }
    return QVariant();
}

SourceOutputModel::SourceOutputModel(QObject *parent)
    : AbstractModel(&context()->sourceOutputs(), parent)
{
}

int SourceOutputModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    if (!context())
        return 0;
    return context()->sourceOutputs().data().count();
}

QVariant SourceOutputModel::data(const QModelIndex &index, int role) const
{
    SourceOutput *data =  context()->sourceOutputs().data().values().at(index.row());
    Q_ASSERT(data);
    switch ((ItemRole) role) {
    case IndexRole:
        return data->index();
    case PulseObjectRole:
        return QVariant::fromValue(data);
    }
    Q_ASSERT(false);
    return QVariant();
}

CardModel::CardModel(QObject *parent)
    : AbstractModel(&context()->cards(), parent)
{
}

int CardModel::rowCount(const QModelIndex &parent) const
{
    qDebug() << Q_FUNC_INFO << context() << (context() ? context()->cards().data().count() : 0);
    Q_UNUSED(parent);
    if (!context())
        return 0;
    return context()->cards().data().count();
}

QVariant CardModel::data(const QModelIndex &index, int role) const
{
    qDebug() << index<< role;
    Card *data =  context()->cards().data().values().at(index.row());
    Q_ASSERT(data);
    switch ((ItemRole) role) {
    case IndexRole:
        return data->index();
    case PulseObjectRole:
        return QVariant::fromValue(data);
    }
    Q_ASSERT(false);
    return QVariant();
}
<commit_msg>remove excessive debug from models<commit_after>#include "pulseaudio.h"

#include <QDebug>
#include <QMetaEnum>

#include "card.h"
#include "client.h"
#include "sink.h"
#include "sinkinput.h"
#include "source.h"
#include "sourceoutput.h"

ClientModel::ClientModel(QObject *parent)
    : AbstractModel(&context()->clients(), parent)
{
}

int ClientModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    if (!context())
        return 0;
    return context()->clients().data().count();
}

QVariant ClientModel::data(const QModelIndex &index, int role) const
{
    Client *data = context()->clients().data().values().at(index.row());
    Q_ASSERT(data);
    switch(static_cast<ItemRole>(role)){
    case NameRole:
        return data->name();
    case PulseObjectRole:
        return QVariant::fromValue(data);
    }
    return QVariant();
}

SinkInputModel::SinkInputModel(QObject *parent)
    : AbstractModel(&context()->sinkInputs(), parent)
{
}

int SinkInputModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    if (!context())
        return 0;
    return context()->sinkInputs().data().count();
}

QVariant SinkInputModel::data(const QModelIndex &index, int role) const
{
    SinkInput *data = context()->sinkInputs().data().values().at(index.row());
    Q_ASSERT(data);
    switch ((ItemRole) role) {
    case IndexRole:
        return data->index();
    case PulseObjectRole:
        return QVariant::fromValue(data);
    }
    return QVariant();
}

QHash<int, QByteArray> AbstractModel::roleNames() const
{
    if (!m_roles.empty()) {
        qDebug() << "returning roles" << m_roles;
        return m_roles;
    }

    QHash<int, QByteArray> roles;

    QMetaEnum enumerator;
    for (int i = 0; i < metaObject()->enumeratorCount(); ++i) {
        if (metaObject()->enumerator(i).name() == QLatin1Literal("ItemRole")) {
            enumerator = metaObject()->enumerator(i);
            break;
        }
    }

    Q_ASSERT(enumerator.scope() == metaObject()->className());
    // No valid enum found, leaf probably doesn't implement ItemRole (correctly).
    Q_ASSERT(enumerator.isValid());

    for (int i = 0; i < enumerator.keyCount(); ++i) {
        // Clip the Role suffix and glue it in the hash.
        static int roleLength = strlen("Role");
        QByteArray key(enumerator.key(i));
        // Enum values must end in Role or the enum is crap
        Q_ASSERT(key.right(roleLength) == QByteArray("Role"));
        key.chop(roleLength);
        roles[enumerator.value(i)] = key;
    }

    qDebug() << roles;
    return roles;
}

SinkModel::SinkModel(QObject *parent)
    : AbstractModel(&context()->sinks(), parent)
{
    connect(&context()->sinks(), &SinkMap::added, this, &SinkModel::sinksChanged);
    connect(&context()->sinks(), &SinkMap::updated, this, &SinkModel::sinksChanged);
    connect(&context()->sinks(), &SinkMap::removed, this, &SinkModel::sinksChanged);

    emit sinksChanged();
}

#warning very naughty, used by main.qml to set volume on all sinks
QList<QObject *> SinkModel::sinks() const
{
    QList <QObject *> ret;
    if (!context())
        return ret;
    for (Sink *sink : context()->sinks().data().values()) {
        ret << sink;
    }
    return ret;
}

int SinkModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    if (!context())
        return 0;
    return context()->sinks().data().count();
}

QVariant SinkModel::data(const QModelIndex &index, int role) const
{
    Sink *data = context()->sinks().data().values().at(index.row());
    Q_ASSERT(data);
    switch(static_cast<ItemRole>(role)) {
    case IndexRole:
        return data->index();
    case PulseObjectRole:
        return QVariant::fromValue(data);
    }
    return QVariant();
}

void AbstractModel::onDataAdded(quint32 index)
{
    beginInsertRows(QModelIndex(), index, index);
    endInsertRows();
}

void AbstractModel::onDataUpdated(quint32 index)
{
    emit dataChanged(createIndex(index, 0), createIndex(index, 0));
}

void AbstractModel::onDataRemoved(quint32 index)
{
    beginRemoveRows(QModelIndex(), index, index);
    endRemoveRows();
}

AbstractModel::AbstractModel(const MapBaseQObject *map, QObject *parent)
    : QAbstractListModel(parent)
{
    connect(map, &MapBaseQObject::added, this, &AbstractModel::onDataAdded);
    connect(map, &MapBaseQObject::updated, this, &AbstractModel::onDataUpdated);
    connect(map, &MapBaseQObject::removed, this, &AbstractModel::onDataRemoved);
}

#warning probably should be called from constructor and it should get the mo passed

void AbstractModel::initRoleNames(const QMetaObject &qobjectMetaObject)
{
    QMetaEnum enumerator;
    for (int i = 0; i < metaObject()->enumeratorCount(); ++i) {
        if (metaObject()->enumerator(i).name() == QLatin1Literal("ItemRole")) {
            enumerator = metaObject()->enumerator(i);
            break;
        }
    }

    Q_ASSERT(enumerator.scope() == metaObject()->className());
    // No valid enum found, leaf probably doesn't implement ItemRole (correctly).
    Q_ASSERT(enumerator.isValid());

    for (int i = 0; i < enumerator.keyCount(); ++i) {
        // Clip the Role suffix and glue it in the hash.
        static int roleLength = strlen("Role");
        QByteArray key(enumerator.key(i));
        // Enum values must end in Role or the enum is crap
        Q_ASSERT(key.right(roleLength) == QByteArray("Role"));
        key.chop(roleLength);
        m_roles[enumerator.value(i)] = key;
    }

    int maxEnumValue = -1;
    for (auto it = m_roles.constBegin(); it != m_roles.constEnd(); ++it) {
        if (it.key() > maxEnumValue)
            maxEnumValue = it.key();
    }
    Q_ASSERT(maxEnumValue != -1);
    auto mo = qobjectMetaObject;
    for (int i = 0; i < mo.propertyCount(); ++i) {
        QString property(mo.property(i).name());
        property.replace(0, 1, property.at(0).toUpper());
        m_roles[++maxEnumValue] = property.toLatin1();
        m_objectProperties.insert(maxEnumValue, i);
    }
    qDebug() << m_roles;
}

ReverseFilterModel::ReverseFilterModel(QObject *parent)
    : QSortFilterProxyModel(parent)
{
    setDynamicSortFilter(true);
    setFilterKeyColumn(0);
}

void ReverseFilterModel::initialSort()
{
    QSortFilterProxyModel::sort(0, Qt::DescendingOrder);
}

SourceModel::SourceModel(QObject *parent)
    : AbstractModel(&context()->sources(), parent)
{
}

int SourceModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    if (!context())
        return 0;
    return context()->sources().data().count();
}

QVariant SourceModel::data(const QModelIndex &index, int role) const
{
    Source *data = context()->sources().data().values().at(index.row());
    Q_ASSERT(data);
    switch(static_cast<ItemRole>(role)) {
    case IndexRole:
        return data->index();
    case PulseObjectRole:
        return QVariant::fromValue(data);
    }
    return QVariant();
}

SourceOutputModel::SourceOutputModel(QObject *parent)
    : AbstractModel(&context()->sourceOutputs(), parent)
{
}

int SourceOutputModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    if (!context())
        return 0;
    return context()->sourceOutputs().data().count();
}

QVariant SourceOutputModel::data(const QModelIndex &index, int role) const
{
    SourceOutput *data =  context()->sourceOutputs().data().values().at(index.row());
    Q_ASSERT(data);
    switch ((ItemRole) role) {
    case IndexRole:
        return data->index();
    case PulseObjectRole:
        return QVariant::fromValue(data);
    }
    Q_ASSERT(false);
    return QVariant();
}

CardModel::CardModel(QObject *parent)
    : AbstractModel(&context()->cards(), parent)
{
}

int CardModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    if (!context())
        return 0;
    return context()->cards().data().count();
}

QVariant CardModel::data(const QModelIndex &index, int role) const
{
    Card *data =  context()->cards().data().values().at(index.row());
    Q_ASSERT(data);
    switch ((ItemRole) role) {
    case IndexRole:
        return data->index();
    case PulseObjectRole:
        return QVariant::fromValue(data);
    }
    Q_ASSERT(false);
    return QVariant();
}
<|endoftext|>


<commit_before>#ifndef __se3_python_se3_hpp__
#define __se3_python_se3_hpp__

#include <eigenpy/exception.hpp>
#include <eigenpy/eigenpy.hpp>
#include "pinocchio/spatial/se3.hpp"

namespace eigenpy
{
  template<>
  struct UnalignedEquivalent<se3::SE3>
  {
    typedef se3::SE3Tpl<double,Eigen::DontAlign> type;
  };
} // namespace eigenpy

namespace se3
{
  namespace python
  {
    namespace bp = boost::python;

    template<typename SE3>
    struct SE3PythonVisitor
      : public boost::python::def_visitor< SE3PythonVisitor<SE3> >
    {
      typedef typename eigenpy::UnalignedEquivalent<SE3>::type SE3_fx;
      typedef typename SE3::Matrix3 Matrix3;
      typedef typename SE3::Matrix6 Matrix6;
      typedef typename SE3::Matrix4 Matrix4;
      typedef typename SE3::Vector6 Vector6;
      typedef typename SE3::Vector3 Vector3;

      typedef typename SE3_fx::Matrix3 Matrix3_fx;
      typedef typename SE3_fx::Matrix6 Matrix6_fx;
      typedef typename SE3_fx::Matrix4 Matrix4_fx;
      typedef typename SE3_fx::Vector6 Vector6_fx;
      typedef typename SE3_fx::Vector3 Vector3_fx;

    public:

      static PyObject* convert(SE3 const& m)
      {
	SE3_fx m_fx = m;
	return boost::python::incref(boost::python::object(m_fx).ptr());
      }

      template<class PyClass>
      void visit(PyClass& cl) const
      {
	cl
	  .def(bp::init<Matrix3_fx,Vector3_fx>
	       ((bp::arg("Rotation"),bp::arg("translation")),
		"Initialize from rotation and translation."))
	  .def(bp::init<int>
	       ((bp::arg("trivial arg (should be 1)")),
	   	"Init to identity."))

	  .add_property("rotation",&SE3PythonVisitor::getRotation,&SE3PythonVisitor::setRotation)
	  .add_property("translation",&SE3PythonVisitor::getTranslation,&SE3PythonVisitor::setTranslation)
	  .def("homogeneous",&SE3_fx::toHomogeneousMatrix)
	  .def("action",&SE3_fx::toActionMatrix)

	  .def("inverse", &SE3_fx::inverse)
	  .def("act_point", &SE3PythonVisitor::act_point)
	  .def("actInv_point", &SE3PythonVisitor::actInv_point)
	  .def("act_se3", &SE3PythonVisitor::act_se3)
	  .def("actInv_se3", &SE3PythonVisitor::actInv_se3)

	  .def("__str__",&SE3PythonVisitor::toString)
	  .def("__invert__",&SE3_fx::inverse)
	  .def(bp::self * bp::self)
	  .add_property("np",&SE3_fx::toActionMatrix)

	  .def("Identity",&SE3_fx::Identity)
	  .staticmethod("Identity")
	  .def("Random",&SE3_fx::Random)
	  .staticmethod("Random")
	  ;
	  }

      static Matrix3_fx getRotation( const SE3_fx & self ) { return self.rotation(); }
      static void setRotation( SE3_fx & self, const Matrix3_fx & R ) { self.rotation(R); }
      static Vector3_fx getTranslation( const SE3_fx & self ) { return self.translation(); }
      static void setTranslation( SE3_fx & self, const Vector3_fx & p ) { self.translation(p); }

      static Vector3_fx act_point( const SE3_fx & self, const Vector3_fx & pt ) { return self.act(pt); }
      static Vector3_fx actInv_point( const SE3_fx & self, const Vector3_fx & pt ) { return self.actInv(pt); }
      static SE3_fx act_se3( const SE3_fx & self, const SE3_fx & x ) { return self.act(x); }
      static SE3_fx actInv_se3( const SE3_fx & self, const SE3_fx & x ) { return self.actInv(x); }
      static std::string toString(const SE3_fx& m)
      {	  std::ostringstream s; s << m; return s.str();       }

      static void expose()
      {
	bp::class_<SE3_fx>("SE3",
			   "SE3 transformations, composing rotation and translation.\n\n"
			   "Supported operations ...",
			   bp::init<>())
	  .def(SE3PythonVisitor<SE3>())
	;

	bp::to_python_converter< SE3,SE3PythonVisitor<SE3> >();
    }

    };

  }} // namespace se3::python

#endif // ifndef __se3_python_se3_hpp__

<commit_msg>Python: changed SE3 rotation and translation into properties.<commit_after>#ifndef __se3_python_se3_hpp__
#define __se3_python_se3_hpp__

#include <eigenpy/exception.hpp>
#include <eigenpy/eigenpy.hpp>
#include "pinocchio/spatial/se3.hpp"

namespace eigenpy
{
  template<>
  struct UnalignedEquivalent<se3::SE3>
  {
    typedef se3::SE3Tpl<double,Eigen::DontAlign> type;
  };
} // namespace eigenpy

namespace se3
{
  namespace python
  {
    namespace bp = boost::python;

    template<typename SE3>
    struct SE3PythonVisitor
      : public boost::python::def_visitor< SE3PythonVisitor<SE3> >
    {
      typedef typename eigenpy::UnalignedEquivalent<SE3>::type SE3_fx;
      typedef typename SE3::Matrix3 Matrix3;
      typedef typename SE3::Matrix6 Matrix6;
      typedef typename SE3::Matrix4 Matrix4;
      typedef typename SE3::Vector6 Vector6;
      typedef typename SE3::Vector3 Vector3;

      typedef typename SE3_fx::Matrix3 Matrix3_fx;
      typedef typename SE3_fx::Matrix6 Matrix6_fx;
      typedef typename SE3_fx::Matrix4 Matrix4_fx;
      typedef typename SE3_fx::Vector6 Vector6_fx;
      typedef typename SE3_fx::Vector3 Vector3_fx;

    public:

      static PyObject* convert(SE3 const& m)
      {
	SE3_fx m_fx = m;
	return boost::python::incref(boost::python::object(m_fx).ptr());
      }

      template<class PyClass>
      void visit(PyClass& cl) const
      {
	cl
	  .def(bp::init<Matrix3_fx,Vector3_fx>
	       ((bp::arg("Rotation"),bp::arg("translation")),
		"Initialize from rotation and translation."))
	  .def(bp::init<int>
	       ((bp::arg("trivial arg (should be 1)")),
	   	"Init to identity."))

	  .add_property("rotation",&SE3PythonVisitor::getRotation,&SE3PythonVisitor::setRotation)
	  .add_property("translation",&SE3PythonVisitor::getTranslation,&SE3PythonVisitor::setTranslation)
	  .add_property("homogeneous",&SE3_fx::toHomogeneousMatrix)
	  .add_property("action",&SE3_fx::toActionMatrix)

	  .def("inverse", &SE3_fx::inverse)
	  .def("act_point", &SE3PythonVisitor::act_point)
	  .def("actInv_point", &SE3PythonVisitor::actInv_point)
	  .def("act_se3", &SE3PythonVisitor::act_se3)
	  .def("actInv_se3", &SE3PythonVisitor::actInv_se3)

	  .def("__str__",&SE3PythonVisitor::toString)
	  .def("__invert__",&SE3_fx::inverse)
	  .def(bp::self * bp::self)
	  .add_property("np",&SE3_fx::toActionMatrix)

	  .def("Identity",&SE3_fx::Identity)
	  .staticmethod("Identity")
	  .def("Random",&SE3_fx::Random)
	  .staticmethod("Random")
	  ;
	  }

      static Matrix3_fx getRotation( const SE3_fx & self ) { return self.rotation(); }
      static void setRotation( SE3_fx & self, const Matrix3_fx & R ) { self.rotation(R); }
      static Vector3_fx getTranslation( const SE3_fx & self ) { return self.translation(); }
      static void setTranslation( SE3_fx & self, const Vector3_fx & p ) { self.translation(p); }

      static Vector3_fx act_point( const SE3_fx & self, const Vector3_fx & pt ) { return self.act(pt); }
      static Vector3_fx actInv_point( const SE3_fx & self, const Vector3_fx & pt ) { return self.actInv(pt); }
      static SE3_fx act_se3( const SE3_fx & self, const SE3_fx & x ) { return self.act(x); }
      static SE3_fx actInv_se3( const SE3_fx & self, const SE3_fx & x ) { return self.actInv(x); }
      static std::string toString(const SE3_fx& m)
      {	  std::ostringstream s; s << m; return s.str();       }

      static void expose()
      {
	bp::class_<SE3_fx>("SE3",
			   "SE3 transformations, composing rotation and translation.\n\n"
			   "Supported operations ...",
			   bp::init<>())
	  .def(SE3PythonVisitor<SE3>())
	;

	bp::to_python_converter< SE3,SE3PythonVisitor<SE3> >();
    }

    };

  }} // namespace se3::python

#endif // ifndef __se3_python_se3_hpp__

<|endoftext|>


<commit_before>/*
 * W.J. van der Laan 2011-2012
 */

#include <QApplication>
#include <QTimer>

#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>

#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif

// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;

boost::thread_group threadGroup;
//Global reference to globalcom

#ifdef WIN32
static QAxObject *globalcom;
#endif

static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
    // Message from network thread
    if(guiref)
    {
        bool modal = (style & CClientUIInterface::MODAL);
        // in case of modal message, use blocking connection to wait for user to click OK
        QMetaObject::invokeMethod(guiref, "error",
                                   modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
                                   Q_ARG(QString, QString::fromStdString(caption)),
                                   Q_ARG(QString, QString::fromStdString(message)),
                                   Q_ARG(bool, modal));
    }
    else
    {
        printf("%s: %s\n", caption.c_str(), message.c_str());
        fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
    }
}

static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption)
{
    if(!guiref)
        return false;
    if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
        return true;
    bool payFee = false;

    QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
                               Q_ARG(qint64, nFeeRequired),
                               Q_ARG(bool*, &payFee));

    return payFee;
}

static bool ThreadSafeAskQuestion(std::string strCaption, std::string Body)
{
    if(!guiref) return false;
    bool result = false;
    QMetaObject::invokeMethod(guiref, "askQuestion", GUIUtil::blockingGUIThreadConnection(),
                               Q_ARG(std::string, strCaption), Q_ARG(std::string, Body),
                               Q_ARG(bool*, &result));
    return result;
}

static void ThreadSafeHandleURI(const std::string& strURI)
{
    if(!guiref)
        return;

    QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
                               Q_ARG(QString, QString::fromStdString(strURI)));
}

static void InitMessage(const std::string &message)
{
    if(splashref)
    {
        splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(232,186,63));
        QApplication::instance()->processEvents();
    }
}

static void QueueShutdown()
{
    QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}

/*
   Translate string to current locale using Qt.
 */
static std::string Translate(const char* psz)
{
    return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}

void timerfire()
{

}

/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
 */
static void handleRunawayException(std::exception *e)
{
    PrintExceptionContinue(e, "Runaway exception");
    QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. GridCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
    exit(1);
}

#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
    // Do this early as we don't want to bother initializing if we are just calling IPC
    ipcScanRelay(argc, argv);

#if QT_VERSION < 0x050000
    // Internal string conversion is all UTF-8
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
#endif

    Q_INIT_RESOURCE(bitcoin);
    QApplication app(argc, argv);
	//uint SEM_FAILCRITICALERRORS= 0x0001;
	//uint SEM_NOGPFAULTERRORBOX = 0x0002;
#ifdef WIN32
	SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
#endif

    // Install global event filter that makes sure that long tooltips can be word-wrapped
    app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));

    // Command-line options take precedence:
    ParseParameters(argc, argv);

    // ... then bitcoin.conf:
    if (!boost::filesystem::is_directory(GetDataDir(false)))
    {
        // This message can not be translated, as translation is not initialized yet
        // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
        QMessageBox::critical(0, "GridCoin",
                              QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
        return 1;
    }
    ReadConfigFile(mapArgs, mapMultiArgs);

    // Application identification (must be set before OptionsModel is initialized,
    // as it is used to locate QSettings)
    app.setOrganizationName("GridCoin");
    //XXX app.setOrganizationDomain("");
    if(GetBoolArg("-testnet")) // Separate UI settings for testnet
        app.setApplicationName("GridCoin-Qt-testnet");
    else
        app.setApplicationName("GridCoin-Qt");

    // ... then GUI settings:
    OptionsModel optionsModel;

    // Get desired locale (e.g. "de_DE") from command line or use system locale
    QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
    QString lang = lang_territory;
    // Convert to "de" only by truncating "_DE"
    lang.truncate(lang_territory.lastIndexOf('_'));

    QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
    // Load language files for configured locale:
    // - First load the translator for the base language, without territory
    // - Then load the more specific locale translator

    // Load e.g. qt_de.qm
    if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
        app.installTranslator(&qtTranslatorBase);

    // Load e.g. qt_de_DE.qm
    if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
        app.installTranslator(&qtTranslator);

    // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
    if (translatorBase.load(lang, ":/translations/"))
        app.installTranslator(&translatorBase);

    // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
    if (translator.load(lang_territory, ":/translations/"))
        app.installTranslator(&translator);

    // Subscribe to global signals from core
    uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
    uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
	uiInterface.ThreadSafeAskQuestion.connect(ThreadSafeAskQuestion);

    uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
    uiInterface.InitMessage.connect(InitMessage);
    uiInterface.QueueShutdown.connect(QueueShutdown);
    uiInterface.Translate.connect(Translate);

    // Show help message immediately after parsing command-line options (for "-lang") and setting locale,
    // but before showing splash screen.
    if (mapArgs.count("-?") || mapArgs.count("--help"))
    {
        GUIUtil::HelpMessageBox help;
        help.showOrPrint();
        return 1;
    }

    QSplashScreen splash(QPixmap(":/images/splash"), 0);
    if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
    {
        splash.show();
        splashref = &splash;
    }

    app.processEvents();

    app.setQuitOnLastWindowClosed(false);

    try
    {
        // Regenerate startup link, to fix links to old versions
        if (GUIUtil::GetStartOnSystemStartup())
            GUIUtil::SetStartOnSystemStartup(true);

        BitcoinGUI window;
        guiref = &window;

		QTimer *timer = new QTimer(guiref);
		printf("\r\nStarting Gridcoin\r\n");

		QObject::connect(timer, SIGNAL(timeout()), guiref, SLOT(timerfire()));

	    //Start globalcom

        if(AppInit2())
        {
            {
                // Put this in a block, so that the Model objects are cleaned up before
                // calling Shutdown().

                if (splashref)
                    splash.finish(&window);

                ClientModel clientModel(&optionsModel);
                WalletModel walletModel(pwalletMain, &optionsModel);

                window.setClientModel(&clientModel);
                window.setWalletModel(&walletModel);

                // If -min option passed, start window minimized.
                if(GetBoolArg("-min"))
                {
                    window.showMinimized();
                }
                else
                {
                    window.show();
                }
				timer->start(5000);

                // Place this here as guiref has to be defined if we don't want to lose URIs
                ipcInit(argc, argv);

                app.exec();

                window.hide();
                window.setClientModel(0);
                window.setWalletModel(0);
                guiref = 0;
            }
            // Shutdown the core and its threads, but don't exit Bitcoin-Qt here
            Shutdown(NULL);
        }
        else
        {
            return 1;
        }
    } catch (std::exception& e) {
        handleRunawayException(&e);
    } catch (...) {
        handleRunawayException(NULL);
    }
    return 0;
}
#endif // BITCOIN_QT_TEST
<commit_msg>Linux Build - 3.5.1.5 - Leisure<commit_after>/*
 * W.J. van der Laan 2011-2012
 */

#include <QApplication>
#include <QTimer>

#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "ui_interface.h"
#include "qtipcserver.h"
#include <QMessageBox>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>

#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif

// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static QSplashScreen *splashref;

boost::thread_group threadGroup;
//Global reference to globalcom

#ifdef WIN32
static QAxObject *globalcom;
#endif

static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
{
    // Message from network thread
    if(guiref)
    {
        bool modal = (style & CClientUIInterface::MODAL);
        // in case of modal message, use blocking connection to wait for user to click OK
        QMetaObject::invokeMethod(guiref, "error",
                                   modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
                                   Q_ARG(QString, QString::fromStdString(caption)),
                                   Q_ARG(QString, QString::fromStdString(message)),
                                   Q_ARG(bool, modal));
    }
    else
    {
        printf("%s: %s\n", caption.c_str(), message.c_str());
        fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
    }
}

static bool ThreadSafeAskFee(int64_t nFeeRequired, const std::string& strCaption)
{
    if(!guiref)
        return false;
    if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
        return true;
    bool payFee = false;

    QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
                               Q_ARG(qint64, nFeeRequired),
                               Q_ARG(bool*, &payFee));

    return payFee;
}

static bool ThreadSafeAskQuestion(std::string strCaption, std::string Body)
{
    if(!guiref) return false;
    bool result = false;
    QMetaObject::invokeMethod(guiref, "askQuestion", GUIUtil::blockingGUIThreadConnection(),
                               Q_ARG(std::string, strCaption), Q_ARG(std::string, Body),
                               Q_ARG(bool*, &result));
    return result;
}

static void ThreadSafeHandleURI(const std::string& strURI)
{
    if(!guiref)
        return;

    QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
                               Q_ARG(QString, QString::fromStdString(strURI)));
}

static void InitMessage(const std::string &message)
{
    if(splashref)
    {
        splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(232,186,63));
        QApplication::instance()->processEvents();
    }
}

static void QueueShutdown()
{
    QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}

/*
   Translate string to current locale using Qt.
 */
static std::string Translate(const char* psz)
{
    return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}

void timerfire()
{

}

/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
 */
static void handleRunawayException(std::exception *e)
{
    PrintExceptionContinue(e, "Runaway exception");
    QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. GridCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
    exit(1);
}

#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
    // Do this early as we don't want to bother initializing if we are just calling IPC
    ipcScanRelay(argc, argv);

#if QT_VERSION < 0x050000
    // Internal string conversion is all UTF-8
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
#endif

    Q_INIT_RESOURCE(bitcoin);
    QApplication app(argc, argv);
	//uint SEM_FAILCRITICALERRORS= 0x0001;
	//uint SEM_NOGPFAULTERRORBOX = 0x0002;
#if defined(WIN32) && defined(QT_GUI)
	SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
#endif

    // Install global event filter that makes sure that long tooltips can be word-wrapped
    app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));

    // Command-line options take precedence:
    ParseParameters(argc, argv);

    // ... then bitcoin.conf:
    if (!boost::filesystem::is_directory(GetDataDir(false)))
    {
        // This message can not be translated, as translation is not initialized yet
        // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
        QMessageBox::critical(0, "GridCoin",
                              QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
        return 1;
    }
    ReadConfigFile(mapArgs, mapMultiArgs);

    // Application identification (must be set before OptionsModel is initialized,
    // as it is used to locate QSettings)
    app.setOrganizationName("GridCoin");
    //XXX app.setOrganizationDomain("");
    if(GetBoolArg("-testnet")) // Separate UI settings for testnet
        app.setApplicationName("GridCoin-Qt-testnet");
    else
        app.setApplicationName("GridCoin-Qt");

    // ... then GUI settings:
    OptionsModel optionsModel;

    // Get desired locale (e.g. "de_DE") from command line or use system locale
    QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
    QString lang = lang_territory;
    // Convert to "de" only by truncating "_DE"
    lang.truncate(lang_territory.lastIndexOf('_'));

    QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
    // Load language files for configured locale:
    // - First load the translator for the base language, without territory
    // - Then load the more specific locale translator

    // Load e.g. qt_de.qm
    if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
        app.installTranslator(&qtTranslatorBase);

    // Load e.g. qt_de_DE.qm
    if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
        app.installTranslator(&qtTranslator);

    // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
    if (translatorBase.load(lang, ":/translations/"))
        app.installTranslator(&translatorBase);

    // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
    if (translator.load(lang_territory, ":/translations/"))
        app.installTranslator(&translator);

    // Subscribe to global signals from core
    uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
    uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
	uiInterface.ThreadSafeAskQuestion.connect(ThreadSafeAskQuestion);

    uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
    uiInterface.InitMessage.connect(InitMessage);
    uiInterface.QueueShutdown.connect(QueueShutdown);
    uiInterface.Translate.connect(Translate);

    // Show help message immediately after parsing command-line options (for "-lang") and setting locale,
    // but before showing splash screen.
    if (mapArgs.count("-?") || mapArgs.count("--help"))
    {
        GUIUtil::HelpMessageBox help;
        help.showOrPrint();
        return 1;
    }

    QSplashScreen splash(QPixmap(":/images/splash"), 0);
    if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
    {
        splash.show();
        splashref = &splash;
    }

    app.processEvents();

    app.setQuitOnLastWindowClosed(false);

    try
    {
        // Regenerate startup link, to fix links to old versions
        if (GUIUtil::GetStartOnSystemStartup())
            GUIUtil::SetStartOnSystemStartup(true);

        BitcoinGUI window;
        guiref = &window;

		QTimer *timer = new QTimer(guiref);
		printf("\r\nStarting Gridcoin\r\n");

		QObject::connect(timer, SIGNAL(timeout()), guiref, SLOT(timerfire()));

	    //Start globalcom

        if(AppInit2())
        {
            {
                // Put this in a block, so that the Model objects are cleaned up before
                // calling Shutdown().

                if (splashref)
                    splash.finish(&window);

                ClientModel clientModel(&optionsModel);
                WalletModel walletModel(pwalletMain, &optionsModel);

                window.setClientModel(&clientModel);
                window.setWalletModel(&walletModel);

                // If -min option passed, start window minimized.
                if(GetBoolArg("-min"))
                {
                    window.showMinimized();
                }
                else
                {
                    window.show();
                }
				timer->start(5000);

                // Place this here as guiref has to be defined if we don't want to lose URIs
                ipcInit(argc, argv);

                app.exec();

                window.hide();
                window.setClientModel(0);
                window.setWalletModel(0);
                guiref = 0;
            }
            // Shutdown the core and its threads, but don't exit Bitcoin-Qt here
            Shutdown(NULL);
        }
        else
        {
            return 1;
        }
    } catch (std::exception& e) {
        handleRunawayException(&e);
    } catch (...) {
        handleRunawayException(NULL);
    }
    return 0;
}
#endif // BITCOIN_QT_TEST
<|endoftext|>