<commit_before>#pragma once

#include <vector>
#include <ostream>
#include <istream>
#include <fstream>

struct VabHeader
{
    VabHeader( std::istream& aStream )
    {
        Read( aStream );
    }

    void Read( std::istream& aStream )
    {
        aStream.read( reinterpret_cast< char* > ( &iForm ), sizeof( iForm ) );
        aStream.read( reinterpret_cast< char* > ( &iVersion ), sizeof( iVersion ) );
        aStream.read( reinterpret_cast< char* > ( &iId ), sizeof( iId ) );
        aStream.read( reinterpret_cast< char* > ( &iFileSize ), sizeof( iFileSize ) );
        aStream.read( reinterpret_cast< char* > ( &iReserved0 ), sizeof( iReserved0 ) );
        aStream.read( reinterpret_cast< char* > ( &iNumProgs ), sizeof( iNumProgs ) );
        aStream.read( reinterpret_cast< char* > ( &iNumTones ), sizeof( iNumTones ) );
        aStream.read( reinterpret_cast< char* > ( &iNumVags ), sizeof( iNumVags ) );
        aStream.read( reinterpret_cast< char* > ( &iMasterVol ), sizeof( iMasterVol ) );
        aStream.read( reinterpret_cast< char* > ( &iMasterPan ), sizeof( iMasterPan ) );
        aStream.read( reinterpret_cast< char* > ( &iAttr1 ), sizeof( iAttr1 ) );
        aStream.read( reinterpret_cast< char* > ( &iAttr2 ), sizeof( iAttr2 ) );
        aStream.read( reinterpret_cast< char* > ( &iReserved1 ), sizeof( iReserved1 ) );
    }

    unsigned int iForm;				// Always "VABp"
    unsigned int iVersion;			// Header version
    unsigned int iId;				// Bank Id
    unsigned int iFileSize;			// File size
    unsigned short int iReserved0;  // Not used
    unsigned short int iNumProgs;
    unsigned short int iNumTones;
    unsigned short int iNumVags;
    unsigned char iMasterVol;
    unsigned char iMasterPan;
    unsigned char iAttr1;
    unsigned char iAttr2;
    unsigned int iReserved1;
};

//  program (instrument) level for example  "piano", "drum", "guitar" and "effect sound".
struct VagAtr;
struct ProgAtr
{
    ProgAtr( std::istream& aStream )
    {
        Read( aStream );
    }

    void Read( std::istream& aStream )
    {
        aStream.read( reinterpret_cast< char* > ( &iNumTones ), sizeof( iNumTones ) );
        aStream.read( reinterpret_cast< char* > ( &iVol ), sizeof( iVol ) );
        aStream.read( reinterpret_cast< char* > ( &iPriority ), sizeof( iPriority ) );
        aStream.read( reinterpret_cast< char* > ( &iMode ), sizeof( iMode ) );
        aStream.read( reinterpret_cast< char* > ( &iPan ), sizeof( iPan ) );
        aStream.read( reinterpret_cast< char* > ( &iReserved0 ), sizeof( iReserved0 ) );
        aStream.read( reinterpret_cast< char* > ( &iAttr ), sizeof( iAttr ) );
        aStream.read( reinterpret_cast< char* > ( &iReserved1 ), sizeof( iReserved1 ) );
        aStream.read( reinterpret_cast< char* > ( &iReserved2 ), sizeof( iReserved2 ) );
    }

    unsigned char iNumTones; // Number of valid entries in iTones
    unsigned char iVol;
    unsigned char iPriority;
    unsigned char iMode;
    unsigned char iPan;
    unsigned char iReserved0;
    unsigned short int iAttr;
    unsigned int iReserved1;
    unsigned int iReserved2;

    std::vector< VagAtr* > iTones;
};

// vag/tone/waves that are linked to an instrument
struct VagAtr
{
    VagAtr( std::istream& aStream )
    {
        Read( aStream );
    }

    void Read( std::istream& aStream )
    {
        aStream.read( reinterpret_cast< char* > ( &iPriority ), sizeof( iPriority ) );
        aStream.read( reinterpret_cast< char* > ( &iMode ), sizeof( iMode ) );
        aStream.read( reinterpret_cast< char* > ( &iVol ), sizeof( iVol ) );
        aStream.read( reinterpret_cast< char* > ( &iPan ), sizeof( iPan ) );
        aStream.read( reinterpret_cast< char* > ( &iCenter ), sizeof( iCenter ) );
        aStream.read( reinterpret_cast< char* > ( &iShift ), sizeof( iShift ) );
        aStream.read( reinterpret_cast< char* > ( &iMin ), sizeof( iMin ) );
        aStream.read( reinterpret_cast< char* > ( &iMax ), sizeof( iMax ) );
        aStream.read( reinterpret_cast< char* > ( &iVibW ), sizeof( iVibW ) );
        aStream.read( reinterpret_cast< char* > ( &iVibT ), sizeof( iVibT ) );
        aStream.read( reinterpret_cast< char* > ( &iPorW ), sizeof( iPorW ) );
        aStream.read( reinterpret_cast< char* > ( &iPorT ), sizeof( iPorT ) );
        aStream.read( reinterpret_cast< char* > ( &iPitchBendMin ), sizeof( iPitchBendMin ) );
        aStream.read( reinterpret_cast< char* > ( &iPitchBendMax ), sizeof( iPitchBendMax ) );
        aStream.read( reinterpret_cast< char* > ( &iReserved1 ), sizeof( iReserved1 ) );
        aStream.read( reinterpret_cast< char* > ( &iReserved2 ), sizeof( iReserved2 ) );
        aStream.read( reinterpret_cast< char* > ( &iAdsr1 ), sizeof( iAdsr1 ) );
        aStream.read( reinterpret_cast< char* > ( &iAdsr2 ), sizeof( iAdsr2 ) );
        aStream.read( reinterpret_cast< char* > ( &iProg ), sizeof( iProg ) );
        aStream.read( reinterpret_cast< char* > ( &iVag ), sizeof( iVag ) );
        aStream.read( reinterpret_cast< char* > ( &iReserved[0] ), sizeof( iReserved ) );
    }

    unsigned char iPriority;
    unsigned char iMode;
    unsigned char iVol;
    unsigned char iPan;
    unsigned char iCenter;
    unsigned char iShift;
    unsigned char iMin;
    unsigned char iMax;
    unsigned char iVibW;
    unsigned char iVibT;
    unsigned char iPorW;
    unsigned char iPorT;
    unsigned char iPitchBendMin;
    unsigned char iPitchBendMax;
    unsigned char iReserved1;
    unsigned char iReserved2;
    unsigned short int iAdsr1;
    unsigned short int iAdsr2;
    short int iProg; // Which progAttr we live in?
    short int iVag;  // Sound index in the VB
    short int iReserved[4];
};

// AE VAB header points into sounds.dat!

// A record in the VB!! file not the VH!!
struct AEVh
{
    AEVh( std::istream& aStream )
    {
        Read( aStream );
    }

    void Read( std::istream& aStream )
    {
        aStream.read( reinterpret_cast< char* > ( &iLengthOrDuration ), sizeof( iLengthOrDuration ) );
        aStream.read( reinterpret_cast< char* > ( &iUnusedByEngine ), sizeof( iUnusedByEngine ) );
        aStream.read( reinterpret_cast< char* > ( &iFileOffset ), sizeof( iFileOffset ) );
    }

    unsigned int iLengthOrDuration;
    unsigned int iUnusedByEngine; // khz, 44100, or 8000 seen? aka bit rate then?
    unsigned int iFileOffset;
};

struct AoVag
{
    unsigned int iSize;
    unsigned int iSampleRate;
    std::vector< unsigned char > iSampleData;
};

class Vab
{
public:
    Vab();
    Vab( std::string aVhFile, std::string aVbFile );
    void LoadVbFile( std::string aFileName );
    void ReadVb( std::istream& aStream );
    void LoadVhFile( std::string aFileName );
    void ReadVh( std::istream& aStream );

public:
    VabHeader* iHeader;  // File header
    std::vector< ProgAtr* > iProgs; // Always 128 of these - must be what the midi data is indexing into?
    std::vector< VagAtr* > iTones;	// always 16 * num progs? Also called a tone??
    // VAG Data body / (VB 254 VAG data) ("Samples" in AE?)
    // 512bytes /2 = 256 samps max
    std::vector< AEVh* > iOffs;

    std::vector< AoVag* > iAoVags;

    std::ifstream iSoundsDat;

    // What about AO? Seems the same as sounds.dat but in each VB file
};
<commit_msg>Update vab.hpp<commit_after>#pragma once

#include <vector>
#include <ostream>
#include <istream>
#include <fstream>

struct VabHeader
{
    VabHeader( std::istream& aStream )
    {
        Read( aStream );
    }

    void Read( std::istream& aStream )
    {
        aStream.read( reinterpret_cast< char* > ( &iForm ), sizeof( iForm ) );
        aStream.read( reinterpret_cast< char* > ( &iVersion ), sizeof( iVersion ) );
        aStream.read( reinterpret_cast< char* > ( &iId ), sizeof( iId ) );
        aStream.read( reinterpret_cast< char* > ( &iFileSize ), sizeof( iFileSize ) );
        aStream.read( reinterpret_cast< char* > ( &iReserved0 ), sizeof( iReserved0 ) );
        aStream.read( reinterpret_cast< char* > ( &iNumProgs ), sizeof( iNumProgs ) );
        aStream.read( reinterpret_cast< char* > ( &iNumTones ), sizeof( iNumTones ) );
        aStream.read( reinterpret_cast< char* > ( &iNumVags ), sizeof( iNumVags ) );
        aStream.read( reinterpret_cast< char* > ( &iMasterVol ), sizeof( iMasterVol ) );
        aStream.read( reinterpret_cast< char* > ( &iMasterPan ), sizeof( iMasterPan ) );
        aStream.read( reinterpret_cast< char* > ( &iAttr1 ), sizeof( iAttr1 ) );
        aStream.read( reinterpret_cast< char* > ( &iAttr2 ), sizeof( iAttr2 ) );
        aStream.read( reinterpret_cast< char* > ( &iReserved1 ), sizeof( iReserved1 ) );
    }

    unsigned int iForm;				// Always "VABp"
    unsigned int iVersion;			// Header version
    unsigned int iId;				// Bank Id
    unsigned int iFileSize;			// File size
    unsigned short int iReserved0;  // Not used
    unsigned short int iNumProgs;
    unsigned short int iNumTones;
    unsigned short int iNumVags;
    unsigned char iMasterVol;
    unsigned char iMasterPan;
    unsigned char iAttr1;
    unsigned char iAttr2;
    unsigned int iReserved1;
};

//  program (instrument) level for example  "piano", "drum", "guitar" and "effect sound".
struct VagAtr;
struct ProgAtr
{
    ProgAtr( std::istream& aStream )
    {
        Read( aStream );
    }

    void Read( std::istream& aStream )
    {
        aStream.read( reinterpret_cast< char* > ( &iNumTones ), sizeof( iNumTones ) );
        aStream.read( reinterpret_cast< char* > ( &iVol ), sizeof( iVol ) );
        aStream.read( reinterpret_cast< char* > ( &iPriority ), sizeof( iPriority ) );
        aStream.read( reinterpret_cast< char* > ( &iMode ), sizeof( iMode ) );
        aStream.read( reinterpret_cast< char* > ( &iPan ), sizeof( iPan ) );
        aStream.read( reinterpret_cast< char* > ( &iReserved0 ), sizeof( iReserved0 ) );
        aStream.read( reinterpret_cast< char* > ( &iAttr ), sizeof( iAttr ) );
        aStream.read( reinterpret_cast< char* > ( &iReserved1 ), sizeof( iReserved1 ) );
        aStream.read( reinterpret_cast< char* > ( &iReserved2 ), sizeof( iReserved2 ) );
    }

    unsigned char iNumTones; // Number of valid entries in iTones
    unsigned char iVol;
    unsigned char iPriority;
    unsigned char iMode;
    unsigned char iPan;
    unsigned char iReserved0;
    unsigned short int iAttr;
    unsigned int iReserved1;
    unsigned int iReserved2;

    std::vector< VagAtr* > iTones;
};

// vag/tone/waves that are linked to an instrument
struct VagAtr
{
    VagAtr( std::istream& aStream )
    {
        Read( aStream );
    }

    void Read( std::istream& aStream )
    {
        aStream.read( reinterpret_cast< char* > ( &iPriority ), sizeof( iPriority ) );
        aStream.read( reinterpret_cast< char* > ( &iMode ), sizeof( iMode ) );
        aStream.read( reinterpret_cast< char* > ( &iVol ), sizeof( iVol ) );
        aStream.read( reinterpret_cast< char* > ( &iPan ), sizeof( iPan ) );
        aStream.read( reinterpret_cast< char* > ( &iCenter ), sizeof( iCenter ) );
        aStream.read( reinterpret_cast< char* > ( &iShift ), sizeof( iShift ) );
        aStream.read( reinterpret_cast< char* > ( &iMin ), sizeof( iMin ) );
        aStream.read( reinterpret_cast< char* > ( &iMax ), sizeof( iMax ) );
        aStream.read( reinterpret_cast< char* > ( &iVibW ), sizeof( iVibW ) );
        aStream.read( reinterpret_cast< char* > ( &iVibT ), sizeof( iVibT ) );
        aStream.read( reinterpret_cast< char* > ( &iPorW ), sizeof( iPorW ) );
        aStream.read( reinterpret_cast< char* > ( &iPorT ), sizeof( iPorT ) );
        aStream.read( reinterpret_cast< char* > ( &iPitchBendMin ), sizeof( iPitchBendMin ) );
        aStream.read( reinterpret_cast< char* > ( &iPitchBendMax ), sizeof( iPitchBendMax ) );
        aStream.read( reinterpret_cast< char* > ( &iReserved1 ), sizeof( iReserved1 ) );
        aStream.read( reinterpret_cast< char* > ( &iReserved2 ), sizeof( iReserved2 ) );
        aStream.read( reinterpret_cast< char* > ( &iAdsr1 ), sizeof( iAdsr1 ) );
        aStream.read( reinterpret_cast< char* > ( &iAdsr2 ), sizeof( iAdsr2 ) );
        aStream.read( reinterpret_cast< char* > ( &iProg ), sizeof( iProg ) );
        aStream.read( reinterpret_cast< char* > ( &iVag ), sizeof( iVag ) );
        aStream.read( reinterpret_cast< char* > ( &iReserved[0] ), sizeof( iReserved ) );
    }

    unsigned char iPriority;

    // 0 = normal, 4 = reverb
    unsigned char iMode;

    // volume 0-127
    unsigned char iVol;

    // panning 0-127
    unsigned char iPan;

    // "Default" note
    unsigned char iCenter;
    unsigned char iShift;

    // Key range which this waveform maps to
    unsigned char iMin;
    unsigned char iMax;

    // Maybe these are not used?
    unsigned char iVibW;
    unsigned char iVibT;
    unsigned char iPorW;
    unsigned char iPorT;

    // Min/max pitch values
    unsigned char iPitchBendMin;
    unsigned char iPitchBendMax;

    // Not used
    unsigned char iReserved1;
    unsigned char iReserved2;

    // adsr1
    // 0-127 attack rate (byte)
    // 0-15 decay rate (nibble)
    // 0-127 sustain rate (byte)

    // adsr2
    // 0-31 release rate (6bits)
    // 0-15 sustain rate (nibble)
    // 1+0.5+1+0.6+0.5=3.6 bytes
    unsigned short int iAdsr1;
    unsigned short int iAdsr2;

    short int iProg; // Which progAttr we live in?
    short int iVag;  // Sound index in the VB
    short int iReserved[4];
};

// AE VAB header points into sounds.dat!

// A record in the VB!! file not the VH!!
struct AEVh
{
    AEVh( std::istream& aStream )
    {
        Read( aStream );
    }

    void Read( std::istream& aStream )
    {
        aStream.read( reinterpret_cast< char* > ( &iLengthOrDuration ), sizeof( iLengthOrDuration ) );
        aStream.read( reinterpret_cast< char* > ( &iUnusedByEngine ), sizeof( iUnusedByEngine ) );
        aStream.read( reinterpret_cast< char* > ( &iFileOffset ), sizeof( iFileOffset ) );
    }

    unsigned int iLengthOrDuration;
    unsigned int iUnusedByEngine; // khz, 44100, or 8000 seen? aka bit rate then?
    unsigned int iFileOffset;
};

struct AoVag
{
    unsigned int iSize;
    unsigned int iSampleRate;
    std::vector< unsigned char > iSampleData;
};

class Vab
{
public:
    Vab();
    Vab( std::string aVhFile, std::string aVbFile );
    void LoadVbFile( std::string aFileName );
    void ReadVb( std::istream& aStream );
    void LoadVhFile( std::string aFileName );
    void ReadVh( std::istream& aStream );

public:
    VabHeader* iHeader;  // File header
    std::vector< ProgAtr* > iProgs; // Always 128 of these - must be what the midi data is indexing into?
    std::vector< VagAtr* > iTones;	// always 16 * num progs? Also called a tone??
    // VAG Data body / (VB 254 VAG data) ("Samples" in AE?)
    // 512bytes /2 = 256 samps max
    std::vector< AEVh* > iOffs;

    std::vector< AoVag* > iAoVags;

    std::ifstream iSoundsDat;

    // What about AO? Seems the same as sounds.dat but in each VB file
};
<|endoftext|>


<commit_before>#include <iostream>
#include <stack>

int main()
{
	std::stack<int> s;
	int val = 0;
	while(std::cin >> val)
		s.push(val);
	std::cout << "popping..." << std::endl;
	while(!s.empty())
	{
		// val = s.pop();
		std::cout << s.top() << std::endl;
		s.pop();
	}
}<commit_msg>Stack STL test<commit_after>#include <iostream>
#include <stack>

int main()
{
	std::stack<int> s;
	int val = 0;
	while(std::cin >> val)
		s.push(val);
	std::cout << "popping..." << std::endl;
	while(!s.empty())
	{
		std::cout << s.top() << std::endl;
		s.pop();
	}
}<|endoftext|>


<commit_before>/*
 *  qiaffine.cpp
 *
 *  Copyright (c) 2015 Tobias Wood.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 */

#include <iostream>

#include "itkImage.h"
#include "itkVersor.h"
#include "itkVersorRigid3DTransform.h"
#include "itkCenteredAffineTransform.h"
#include "itkTransformFileWriter.h"
#include "itkPermuteAxesImageFilter.h"
#include "itkFlipImageFilter.h"

#include "QI/Util.h"
#include "QI/IO.h"
#include "QI/Args.h"

using namespace std;

/*
 * Declare arguments here so they are available to pipeline
 */
args::ArgumentParser parser("Applies simple affine transformations to images by manipulating the header\n"
    "transforms. If an output file is not specified, the input file will be\n"
    "overwritten.\n"
    "http://github.com/spinicist/QUIT");

args::Positional<std::string> source_path(parser, "SOURCE", "Source file");
args::Positional<std::string> dest_path(parser, "DEST", "Destination file");

args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"});
args::Flag     verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"});
args::Flag     center(parser, "CENTER", "Set the origin to the center of the image", {'c', "center"});
args::ValueFlag<std::string> tfm_path(parser, "TFM", "Write out the transformation to a file", {'t', "tfm"});
args::ValueFlag<double> scale(parser, "SCALE", "Scale by a constant", {'s', "scale"});
args::ValueFlag<double> offX(parser, "OFF_X", "Translate origin in X direction", {"offX"});
args::ValueFlag<double> offY(parser, "OFF_Y", "Translate origin in Y direction", {"offY"});
args::ValueFlag<double> offZ(parser, "OFF_Z", "Translate origin in Z direction", {"offZ"});
args::ValueFlag<double> rotX(parser, "ROT_X", "Rotate about X-axis by angle (degrees)", {"rotX"});
args::ValueFlag<double> rotY(parser, "ROT_Y", "Rotate about Y-axis by angle (degrees)", {"rotY"});
args::ValueFlag<double> rotZ(parser, "ROT_Z", "Rotate about Z-axis by angle (degrees)", {"rotZ"});
args::ValueFlag<std::string> permute(parser, "PERMUTE", "Permute axes, e.g. 2,0,1. Negative values mean flip as well", {"permute"});
args::ValueFlag<std::string> flip(parser, "FLIP", "Flip an axis, e.g. 0,1,0. Occurs AFTER any permutation.", {"flip"});

template<typename TImage>
int Pipeline() {
    auto image = QI::ReadImage<TImage>(QI::CheckPos(source_path));

    // Permute if required
    if (permute) {
        auto permute_filter = itk::PermuteAxesImageFilter<TImage>::New();
        itk::FixedArray<unsigned int, TImage::ImageDimension> permute_order;
        std::istringstream iss(permute.Get());
        std::string el;
        for (int i = 0; i < 3; i++) {
            std::getline(iss, el, ',');
            permute_order[i] = std::stoi(el);
        }
        for (int i = 3; i < TImage::ImageDimension; i++) {
            permute_order[i] = i;
        }
        if (!iss)
            QI_FAIL("Failed to read permutation order: " << permute.Get());

        permute_filter->SetInput(image);
        permute_filter->SetOrder(permute_order);
        permute_filter->Update();
        image = permute_filter->GetOutput();
        image->DisconnectPipeline();
    }

    // Flip if required
    if (flip) {
        auto flip_filter = itk::FlipImageFilter<TImage>::New();
        itk::FixedArray<bool, TImage::ImageDimension> flip_axes; // Save this
        std::istringstream iss(flip.Get());
        std::string el;
        for (int i = 0; i < 3; i++) {
            std::getline(iss, el, ',');
            flip_axes[i] = (std::stoi(el) > 0);
        }
        for (int i = 3; i < TImage::ImageDimension; i++) {
            flip_axes[i] = false;
        }
        if (!iss)
            QI_FAIL("Failed to read flip: " << flip.Get());
        if (verbose) std::cout << "Flipping: " << flip_axes << std::endl;
        flip_filter->SetInput(image);
        flip_filter->SetFlipAxes(flip_axes);
        flip_filter->SetFlipAboutOrigin(false);
        flip_filter->Update();
        image = flip_filter->GetOutput();
        image->DisconnectPipeline();
    }

    typename TImage::DirectionType fullDir = image->GetDirection();
    typename TImage::SpacingType fullSpacing = image->GetSpacing();
    typename TImage::PointType fullOrigin = image->GetOrigin();
    typename TImage::SizeType fullSize = image->GetLargestPossibleRegion().GetSize();
    QI::VolumeF::DirectionType direction;
    QI::VolumeF::SpacingType spacing;

    typedef itk::CenteredAffineTransform<double, 3> TAffine;
    TAffine::OutputVectorType origin;
    QI::VolumeF::SizeType size;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            direction[i][j] = fullDir[i][j];
        }
        origin[i] = fullOrigin[i];
        spacing[i] = fullSpacing[i];
        size[i] = fullSize[i];
    }

    auto img_tfm = TAffine::New();
    img_tfm->SetMatrix(direction);
    img_tfm->Scale(spacing);
    img_tfm->Translate(origin);
    if (verbose) std::cout << "Start transform:\n" << img_tfm->GetMatrix() << std::endl;
    auto tfm = TAffine::New();
    if (scale) {
        if (verbose) cout << "Scaling by factor " << scale.Get() << endl;
        tfm->Scale(scale.Get());
    }
    if (rotX != 0.0) {
        if (verbose) cout << "Rotating image by " << rotX.Get() << " around X axis." << endl;
        tfm->Rotate(1,2,rotX.Get() * M_PI / 180.0);
    }
    if (rotY != 0.0) {
        if (verbose) cout << "Rotating image by " << rotY.Get() << " around X axis." << endl;
        tfm->Rotate(2,0,rotY.Get() * M_PI / 180.0);
    }
    if (rotZ != 0.0) {
        if (verbose) cout << "Rotating image by " << rotZ.Get() << " around X axis." << endl;
        tfm->Rotate(0,1,rotZ.Get() * M_PI / 180.0);
    }
    itk::Versor<double>::VectorType offset; offset.Fill(0);
    if (center) {
        for (int i = 0; i < 3; i++) {
            offset[i] = origin[i]-spacing[i]*size[i] / 2;
        }
        if (verbose) std::cout << "Centering image" << std::endl;
        tfm->Translate(-offset);
    } else if (offX || offY || offZ) {
        offset[0] = offX.Get();
        offset[1] = offY.Get();
        offset[2] = offZ.Get();
        if (verbose) std::cout << "Translating by: " << offset << std::endl;
        tfm->Translate(-offset);
    }

    if (tfm_path) { // Output the transform file
        auto writer = itk::TransformFileWriterTemplate<double>::New();
        writer->SetInput(tfm);
        writer->SetFileName(tfm_path.Get());
        writer->Update();
    }

    img_tfm->Compose(tfm);
    itk::CenteredAffineTransform<double, 3>::MatrixType fmat = img_tfm->GetMatrix();
    if (verbose) std::cout << "Final transform:\n" << fmat << std::endl;
    for (int i = 0; i < 3; i++) {
        fullOrigin[i] = img_tfm->GetOffset()[i];
    }
    for (int j = 0; j < 3; j++) {
        double scale = 0.;
        for (int i = 0; i < 3; i++) {
            scale += fmat[i][j]*fmat[i][j];
        }
        scale = sqrt(scale);

        fullSpacing[j] = scale;
        for (int i = 0; i < 3; i++) {
            fullDir[i][j] = fmat[i][j] / scale;
        }
    }
    image->SetDirection(fullDir);
    image->SetOrigin(fullOrigin);
    image->SetSpacing(fullSpacing);

    // Write out the edited file
    if (dest_path) {
        QI::WriteImage(image, dest_path.Get());
    } else {
        QI::WriteImage(image, source_path.Get());
    }
    return EXIT_SUCCESS;
}

int main(int argc, char **argv) {
    QI::ParseArgs(parser, argc, argv);
    if (verbose) std::cout << "Reading header for: " << QI::CheckPos(source_path) << std::endl;
    auto header = itk::ImageIOFactory::CreateImageIO(QI::CheckPos(source_path).c_str(), itk::ImageIOFactory::ReadMode);
    header->SetFileName(source_path.Get());
    header->ReadImageInformation();
    auto dims  = header->GetNumberOfDimensions();
    auto dtype = header->GetComponentType();
    if (verbose) std::cout << "Datatype is " << header->GetComponentTypeAsString( dtype ) << std::endl;

    #define DIM_SWITCH( TYPE ) \
        switch (dims) { \
            case 3: return Pipeline<itk::Image< TYPE , 3 >>(); \
            case 4: return Pipeline<itk::Image< TYPE , 4 >>(); \
            default: QI_FAIL("Unsupported dimension: " << dims); return EXIT_FAILURE; \
        }

    switch (dtype) {
        case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: QI_FAIL("Unknown component type in image " << source_path);
        case itk::ImageIOBase::UCHAR:  DIM_SWITCH( unsigned char ); break;
        case itk::ImageIOBase::CHAR:   DIM_SWITCH( char ); break;
        case itk::ImageIOBase::USHORT: DIM_SWITCH( unsigned short ); break;
        case itk::ImageIOBase::SHORT:  DIM_SWITCH( short ); break;
        case itk::ImageIOBase::UINT:   DIM_SWITCH( unsigned int ); break;
        case itk::ImageIOBase::INT:    DIM_SWITCH( int ); break;
        case itk::ImageIOBase::ULONG:  DIM_SWITCH( unsigned long ); break;
        case itk::ImageIOBase::LONG:   DIM_SWITCH( long ); break;
        case itk::ImageIOBase::FLOAT:  DIM_SWITCH( float ); break;
        case itk::ImageIOBase::DOUBLE: DIM_SWITCH( double ); break;
    }
}
<commit_msg>ENH: Added CoG centering<commit_after>/*
 *  qiaffine.cpp
 *
 *  Copyright (c) 2015 Tobias Wood.
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 */

#include <iostream>

#include "itkImage.h"
#include "itkVersor.h"
#include "itkVersorRigid3DTransform.h"
#include "itkCenteredAffineTransform.h"
#include "itkTransformFileWriter.h"
#include "itkPermuteAxesImageFilter.h"
#include "itkFlipImageFilter.h"
#include "itkImageMomentsCalculator.h"

#include "QI/Util.h"
#include "QI/IO.h"
#include "QI/Args.h"

using namespace std;

/*
 * Declare arguments here so they are available to pipeline
 */
args::ArgumentParser parser("Applies simple affine transformations to images by manipulating the header\n"
    "transforms. If an output file is not specified, the input file will be\n"
    "overwritten.\n"
    "http://github.com/spinicist/QUIT");

args::Positional<std::string> source_path(parser, "SOURCE", "Source file");
args::Positional<std::string> dest_path(parser, "DEST", "Destination file");

args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"});
args::Flag     verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"});
args::ValueFlag<std::string> center(parser, "CENTER", "Set the origin to geometric center (geo) or (cog)", {'c', "center"});
args::ValueFlag<std::string> tfm_path(parser, "TFM", "Write out the transformation to a file", {'t', "tfm"});
args::ValueFlag<double> scale(parser, "SCALE", "Scale by a constant", {'s', "scale"});
args::ValueFlag<double> offX(parser, "OFF_X", "Translate origin in X direction", {"offX"});
args::ValueFlag<double> offY(parser, "OFF_Y", "Translate origin in Y direction", {"offY"});
args::ValueFlag<double> offZ(parser, "OFF_Z", "Translate origin in Z direction", {"offZ"});
args::ValueFlag<double> rotX(parser, "ROT_X", "Rotate about X-axis by angle (degrees)", {"rotX"});
args::ValueFlag<double> rotY(parser, "ROT_Y", "Rotate about Y-axis by angle (degrees)", {"rotY"});
args::ValueFlag<double> rotZ(parser, "ROT_Z", "Rotate about Z-axis by angle (degrees)", {"rotZ"});
args::ValueFlag<std::string> permute(parser, "PERMUTE", "Permute axes, e.g. 2,0,1. Negative values mean flip as well", {"permute"});
args::ValueFlag<std::string> flip(parser, "FLIP", "Flip an axis, e.g. 0,1,0. Occurs AFTER any permutation.", {"flip"});

template<typename TImage>
int Pipeline() {
    auto image = QI::ReadImage<TImage>(QI::CheckPos(source_path));

    // Permute if required
    if (permute) {
        auto permute_filter = itk::PermuteAxesImageFilter<TImage>::New();
        itk::FixedArray<unsigned int, TImage::ImageDimension> permute_order;
        std::istringstream iss(permute.Get());
        std::string el;
        for (int i = 0; i < 3; i++) {
            std::getline(iss, el, ',');
            permute_order[i] = std::stoi(el);
        }
        for (int i = 3; i < TImage::ImageDimension; i++) {
            permute_order[i] = i;
        }
        if (!iss)
            QI_FAIL("Failed to read permutation order: " << permute.Get());

        permute_filter->SetInput(image);
        permute_filter->SetOrder(permute_order);
        permute_filter->Update();
        image = permute_filter->GetOutput();
        image->DisconnectPipeline();
    }

    // Flip if required
    if (flip) {
        auto flip_filter = itk::FlipImageFilter<TImage>::New();
        itk::FixedArray<bool, TImage::ImageDimension> flip_axes; // Save this
        std::istringstream iss(flip.Get());
        std::string el;
        for (int i = 0; i < 3; i++) {
            std::getline(iss, el, ',');
            flip_axes[i] = (std::stoi(el) > 0);
        }
        for (int i = 3; i < TImage::ImageDimension; i++) {
            flip_axes[i] = false;
        }
        if (!iss)
            QI_FAIL("Failed to read flip: " << flip.Get());
        if (verbose) std::cout << "Flipping: " << flip_axes << std::endl;
        flip_filter->SetInput(image);
        flip_filter->SetFlipAxes(flip_axes);
        flip_filter->SetFlipAboutOrigin(false);
        flip_filter->Update();
        image = flip_filter->GetOutput();
        image->DisconnectPipeline();
    }

    typename TImage::DirectionType fullDir = image->GetDirection();
    typename TImage::SpacingType fullSpacing = image->GetSpacing();
    typename TImage::PointType fullOrigin = image->GetOrigin();
    typename TImage::SizeType fullSize = image->GetLargestPossibleRegion().GetSize();
    QI::VolumeF::DirectionType direction;
    QI::VolumeF::SpacingType spacing;

    typedef itk::CenteredAffineTransform<double, 3> TAffine;
    TAffine::OutputVectorType origin;
    QI::VolumeF::SizeType size;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            direction[i][j] = fullDir[i][j];
        }
        origin[i] = fullOrigin[i];
        spacing[i] = fullSpacing[i];
        size[i] = fullSize[i];
    }

    auto img_tfm = TAffine::New();
    img_tfm->SetMatrix(direction);
    img_tfm->Scale(spacing);
    img_tfm->Translate(origin);
    if (verbose) std::cout << "Start transform:\n" << img_tfm->GetMatrix() << std::endl;
    auto tfm = TAffine::New();
    if (scale) {
        if (verbose) cout << "Scaling by factor " << scale.Get() << endl;
        tfm->Scale(scale.Get());
    }
    if (rotX != 0.0) {
        if (verbose) cout << "Rotating image by " << rotX.Get() << " around X axis." << endl;
        tfm->Rotate(1,2,rotX.Get() * M_PI / 180.0);
    }
    if (rotY != 0.0) {
        if (verbose) cout << "Rotating image by " << rotY.Get() << " around X axis." << endl;
        tfm->Rotate(2,0,rotY.Get() * M_PI / 180.0);
    }
    if (rotZ != 0.0) {
        if (verbose) cout << "Rotating image by " << rotZ.Get() << " around X axis." << endl;
        tfm->Rotate(0,1,rotZ.Get() * M_PI / 180.0);
    }
    itk::Versor<double>::VectorType offset; offset.Fill(0);
    if (center) {
        if (center.Get() == "geo") {
            if (verbose) std::cout << "Setting geometric center" << std::endl;
            for (int i = 0; i < 3; i++) {
                offset[i] = origin[i]-spacing[i]*size[i] / 2;
            }
        } else if (center.Get() == "cog") {
            if (verbose) std::cout << "Setting center to center of gravity" << std::endl;
            auto moments = itk::ImageMomentsCalculator<TImage>::New();
            moments->SetImage(image);
            moments->Compute();
            // ITK seems to put a negative sign on the CoG
            for (int i = 0; i < 3; i++) {
                offset[i] = moments->GetCenterOfGravity()[i];
            }
        }
        std::cout << "Translation will be: " << offset << std::endl;
        tfm->Translate(-offset);
    } else if (offX || offY || offZ) {
        offset[0] = offX.Get();
        offset[1] = offY.Get();
        offset[2] = offZ.Get();
        if (verbose) std::cout << "Translating by: " << offset << std::endl;
        tfm->Translate(-offset);
    }

    if (tfm_path) { // Output the transform file
        auto writer = itk::TransformFileWriterTemplate<double>::New();
        writer->SetInput(tfm);
        writer->SetFileName(tfm_path.Get());
        writer->Update();
    }

    img_tfm->Compose(tfm);
    itk::CenteredAffineTransform<double, 3>::MatrixType fmat = img_tfm->GetMatrix();
    if (verbose) std::cout << "Final transform:\n" << fmat << std::endl;
    for (int i = 0; i < 3; i++) {
        fullOrigin[i] = img_tfm->GetOffset()[i];
    }
    for (int j = 0; j < 3; j++) {
        double scale = 0.;
        for (int i = 0; i < 3; i++) {
            scale += fmat[i][j]*fmat[i][j];
        }
        scale = sqrt(scale);

        fullSpacing[j] = scale;
        for (int i = 0; i < 3; i++) {
            fullDir[i][j] = fmat[i][j] / scale;
        }
    }
    image->SetDirection(fullDir);
    image->SetOrigin(fullOrigin);
    image->SetSpacing(fullSpacing);

    // Write out the edited file
    if (dest_path) {
        if (verbose) std::cout << "Writing: " << dest_path.Get() << std::endl;
        QI::WriteImage(image, dest_path.Get());
    } else {
        if (verbose) std::cout << "Writing: " << source_path.Get() << std::endl;
        QI::WriteImage(image, source_path.Get());
    }
    return EXIT_SUCCESS;
}

int main(int argc, char **argv) {
    QI::ParseArgs(parser, argc, argv);
    if (verbose) std::cout << "Reading header for: " << QI::CheckPos(source_path) << std::endl;
    auto header = itk::ImageIOFactory::CreateImageIO(QI::CheckPos(source_path).c_str(), itk::ImageIOFactory::ReadMode);
    header->SetFileName(source_path.Get());
    header->ReadImageInformation();
    auto dims  = header->GetNumberOfDimensions();
    auto dtype = header->GetComponentType();
    if (verbose) std::cout << "Datatype is " << header->GetComponentTypeAsString( dtype ) << std::endl;

    #define DIM_SWITCH( TYPE ) \
        switch (dims) { \
            case 3: return Pipeline<itk::Image< TYPE , 3 >>(); \
            case 4: return Pipeline<itk::Image< TYPE , 4 >>(); \
            default: QI_FAIL("Unsupported dimension: " << dims); return EXIT_FAILURE; \
        }

    switch (dtype) {
        case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: QI_FAIL("Unknown component type in image " << source_path);
        case itk::ImageIOBase::UCHAR:  DIM_SWITCH( unsigned char ); break;
        case itk::ImageIOBase::CHAR:   DIM_SWITCH( char ); break;
        case itk::ImageIOBase::USHORT: DIM_SWITCH( unsigned short ); break;
        case itk::ImageIOBase::SHORT:  DIM_SWITCH( short ); break;
        case itk::ImageIOBase::UINT:   DIM_SWITCH( unsigned int ); break;
        case itk::ImageIOBase::INT:    DIM_SWITCH( int ); break;
        case itk::ImageIOBase::ULONG:  DIM_SWITCH( unsigned long ); break;
        case itk::ImageIOBase::LONG:   DIM_SWITCH( long ); break;
        case itk::ImageIOBase::FLOAT:  DIM_SWITCH( float ); break;
        case itk::ImageIOBase::DOUBLE: DIM_SWITCH( double ); break;
    }
}
<|endoftext|>


<commit_before>
#include <sstream>
#include <random>
#include <functional>

#include <layout/form_layout.h>
#include <layout/box_layout.h>
#include <layout/grid_layout.h>
#include <layout/tree_layout.h>
#include <gui/application.h>
#include <gui/cocoa_style.h>

namespace {

////////////////////////////////////////

void build_form_layout( const std::shared_ptr<gui::window> &win )
{
	gui::builder builder( win );
	auto layout = builder.new_layout<layout::form_layout>( layout::direction::RIGHT );
	layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
	layout->set_spacing( 12.0, 12.0 );

	auto row = layout->new_row();
	builder.make_label( row.first, "Hello World" );
	builder.make_button( row.second, "Press Me" );

	row = layout->new_row();
	builder.make_label( row.first, "Goodbye World" );
	builder.make_button( row.second, "Me Too" );
}

void build_box_layout( const std::shared_ptr<gui::window> &win )
{
	gui::builder builder( win );
	auto layout = builder.new_layout<layout::box_layout>( layout::direction::DOWN );
	layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
	layout->set_spacing( 12.0, 12.0 );

	builder.make_label( layout->new_area(), "Hello World" );
	builder.make_button( layout->new_area(), "Press Me" );

	builder.make_label( layout->new_area(), "Goodbye World" );
	builder.make_button( layout->new_area(), "Me Too" );
}

void build_grid_layout( const std::shared_ptr<gui::window> &win )
{
	gui::builder builder( win );
	auto layout = builder.new_layout<layout::grid_layout>();
	layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
	layout->set_spacing( 12.0, 12.0 );

	for ( size_t i = 0; i < 5; ++i )
		layout->new_column( 1.0 );

	int count = 0;
	for ( size_t i = 0; i < 5; ++i )
	{
		auto cols = layout->new_row();
		for ( auto a: cols )
		{
			std::stringstream tmp;
			tmp << ++count;
			builder.make_label( a, tmp.str() );
		}
	}
}

void build_tree_layout( const std::shared_ptr<gui::window> &win )
{
	gui::builder builder( win );
	auto layout = builder.new_layout<layout::tree_layout>( 24.0 );
	layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
	layout->set_spacing( 12.0 );

	std::random_device rd;
	std::default_random_engine rand( rd() );
	std::uniform_int_distribution<int> uniform_dist( 1, 6 );

	std::function<void(std::shared_ptr<layout::tree_layout>,int)> make_tree =
		[&]( std::shared_ptr<layout::tree_layout> l, int level )
		{
			int count = uniform_dist( rand );
			for ( int i = 0; i < count; ++i )
			{
				std::stringstream tmp;
				tmp << char( 'A' + i );
				builder.make_label( l->new_area( 0.0 ), tmp.str() );
				if ( level < 2 )
					make_tree( l->new_branch( 0.0 ), level + 1 );
			}
		};

	make_tree( layout, 0 );
}

////////////////////////////////////////

int safemain( int argc, char **argv )
{
	auto app = std::make_shared<gui::application>();
	app->push();
	app->set_style( std::make_shared<gui::cocoa_style>() );

	auto win1 = app->new_window();
	build_form_layout( win1 );
	win1->show();

	auto win2 = app->new_window();
	build_box_layout( win2 );
	win2->show();

	auto win3 = app->new_window();
	build_grid_layout( win3 );
	win3->show();

	auto win4 = app->new_window();
	build_tree_layout( win4 );
	win4->show();

	int code = app->run();
	app->pop();
	return code;
}

////////////////////////////////////////

}

////////////////////////////////////////

int main( int argc, char *argv[] )
{
	int ret = -1;
	try
	{
		ret = safemain( argc, argv );
	}
	catch ( std::exception &e )
	{
		print_exception( std::cerr, e );
	}
	return ret;
}

////////////////////////////////////////

<commit_msg>Added button test.<commit_after>
#include <sstream>
#include <random>
#include <functional>

#include <layout/form_layout.h>
#include <layout/box_layout.h>
#include <layout/grid_layout.h>
#include <layout/tree_layout.h>
#include <gui/application.h>
#include <gui/cocoa_style.h>

namespace {

////////////////////////////////////////

void build_form_layout( const std::shared_ptr<gui::window> &win )
{
	gui::builder builder( win );
	auto layout = builder.new_layout<layout::form_layout>( layout::direction::RIGHT );
	layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
	layout->set_spacing( 12.0, 12.0 );

	auto row = layout->new_row();
	builder.make_label( row.first, "Hello World" );
	builder.make_button( row.second, "Press Me" );

	row = layout->new_row();
	builder.make_label( row.first, "Goodbye World" );
	builder.make_button( row.second, "Me Too" );
}

void build_box_layout( const std::shared_ptr<gui::window> &win )
{
	gui::builder builder( win );
	auto layout = builder.new_layout<layout::box_layout>( layout::direction::DOWN );
	layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
	layout->set_spacing( 12.0, 12.0 );

	builder.make_label( layout->new_area(), "Hello World" );
	builder.make_button( layout->new_area(), "Press Me" );

	builder.make_label( layout->new_area(), "Goodbye World" );
	builder.make_button( layout->new_area(), "Me Too" );
}

void build_grid_layout( const std::shared_ptr<gui::window> &win )
{
	gui::builder builder( win );
	auto layout = builder.new_layout<layout::grid_layout>();
	layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
	layout->set_spacing( 12.0, 12.0 );

	for ( size_t i = 0; i < 5; ++i )
		layout->new_column( 1.0 );

	int count = 0;
	for ( size_t i = 0; i < 5; ++i )
	{
		auto cols = layout->new_row();
		for ( auto a: cols )
		{
			std::stringstream tmp;
			tmp << ++count;
			builder.make_label( a, tmp.str() );
		}
	}
}

void build_tree_layout( const std::shared_ptr<gui::window> &win )
{
	gui::builder builder( win );
	auto layout = builder.new_layout<layout::tree_layout>( 24.0 );
	layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
	layout->set_spacing( 12.0 );

	std::random_device rd;
	std::default_random_engine rand( rd() );
	std::uniform_int_distribution<int> uniform_dist( 1, 6 );

	std::function<void(std::shared_ptr<layout::tree_layout>,int)> make_tree =
		[&]( std::shared_ptr<layout::tree_layout> l, int level )
		{
			int count = uniform_dist( rand );
			for ( int i = 0; i < count; ++i )
			{
				std::stringstream tmp;
				tmp << char( 'A' + i );
				builder.make_label( l->new_area( 0.0 ), tmp.str() );
				if ( level < 2 )
					make_tree( l->new_branch( 0.0 ), level + 1 );
			}
		};

	make_tree( layout, 0 );
}

////////////////////////////////////////

void build_button( const std::shared_ptr<gui::window> &win )
{
	gui::builder builder( win );
	auto layout = builder.new_layout<layout::box_layout>( layout::direction::DOWN );
	layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
	layout->set_spacing( 12.0, 12.0 );

	auto area = layout->new_area();
	builder.make_button( area, "Button" );
}

////////////////////////////////////////

int safemain( int argc, char **argv )
{
	auto app = std::make_shared<gui::application>();
	app->push();
	app->set_style( std::make_shared<gui::cocoa_style>() );

//	auto win1 = app->new_window();
//	build_form_layout( win1 );
//	win1->show();

//	auto win2 = app->new_window();
//	build_box_layout( win2 );
//	win2->show();

//	auto win3 = app->new_window();
//	build_grid_layout( win3 );
//	win3->show();

//	auto win4 = app->new_window();
//	build_tree_layout( win4 );
//	win4->show();

	auto win5 = app->new_window();
	build_button( win5 );
	win5->show();

	int code = app->run();
	app->pop();
	return code;
}

////////////////////////////////////////

}

////////////////////////////////////////

int main( int argc, char *argv[] )
{
	int ret = -1;
	try
	{
		ret = safemain( argc, argv );
	}
	catch ( std::exception &e )
	{
		print_exception( std::cerr, e );
	}
	return ret;
}

////////////////////////////////////////

<|endoftext|>


<commit_before>#include <iostream>

int main(int, char**){
#ifdef __AVX__
	std::cout << "AVX available\n";
#else
	std::cout << "No AVX\n";
#endif
	return 0;
}

<commit_msg>tossing the test_avx file<commit_after><|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief v8 client connection
///
/// @file
///
/// DISCLAIMER
///
/// Copyright by triAGENS GmbH - All rights reserved.
///
/// The Programs (which include both the software and documentation)
/// contain proprietary information of triAGENS GmbH; they are
/// provided under a license agreement containing restrictions on use and
/// disclosure and are also protected by copyright, patent and other
/// intellectual and industrial property laws. Reverse engineering,
/// disassembly or decompilation of the Programs, except to the extent
/// required to obtain interoperability with other independently created
/// software or as specified by law, is prohibited.
///
/// The Programs are not intended for use in any nuclear, aviation, mass
/// transit, medical, or other inherently dangerous applications. It shall
/// be the licensee's responsibility to take all appropriate fail-safe,
/// backup, redundancy, and other measures to ensure the safe use of such
/// applications if the Programs are used for such purposes, and triAGENS
/// GmbH disclaims liability for any damages caused by such use of
/// the Programs.
///
/// This software is the confidential and proprietary information of
/// triAGENS GmbH. You shall not disclose such confidential and
/// proprietary information and shall use it only in accordance with the
/// terms of the license agreement you entered into with triAGENS GmbH.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
/// @author Copyright 2008-2011, triagens GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "V8ClientConnection.h"

#include <sstream>

#include "Basics/StringUtils.h"

#include "Variant/VariantArray.h"
#include "Variant/VariantString.h"

#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"

#include "json.h"
#include "V8/v8-conv.h"

using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace std;

namespace triagens {
  namespace v8client {

    ////////////////////////////////////////////////////////////////////////////////
    /// constructor and destructor
    ////////////////////////////////////////////////////////////////////////////////

    V8ClientConnection::V8ClientConnection (const std::string& hostname,
            int port,
            double requestTimeout,
            size_t retries,
            double connectionTimeout) : _client(0), _httpResult(0) {

      _connected = false;
      _lastHttpReturnCode = 0;
      _lastErrorMessage = "";
      _client = new SimpleHttpClient(hostname, port, requestTimeout, retries, connectionTimeout);

      // connect to server and get version number
      map<string, string> headerFields;
      SimpleHttpResult* result = _client->request(SimpleHttpClient::GET, "/version", 0, 0, headerFields);

      if (!result->isComplete()) {
        // save error message
        _lastErrorMessage = _client->getErrorMessage();
        _lastHttpReturnCode = 500;
      }
      else {
        _lastHttpReturnCode = result->getHttpReturnCode();
        if (result->getHttpReturnCode() == SimpleHttpResult::HTTP_STATUS_OK) {

          triagens::basics::VariantArray* json = result->getBodyAsVariantArray();
          if (json) {
            triagens::basics::VariantString* vs = json->lookupString("server");
            if (vs && vs->getValue() == "arango") {
              // connected to arango server
              _connected = true;
              vs = json->lookupString("version");
              if (vs) {
                _version = vs->getValue();
              }
            }
            delete json;
          }
        }
      }

      delete result;
    }

    V8ClientConnection::~V8ClientConnection () {
      if (_httpResult) {
        delete _httpResult;
      }

      if (_client) {
        delete _client;
      }
    }

    v8::Handle<v8::Value> V8ClientConnection::getData (std::string const& location, map<string, string> const& headerFields) {
      return requestData(SimpleHttpClient::GET, location, "", headerFields);
    }

    v8::Handle<v8::Value> V8ClientConnection::deleteData (std::string const& location, map<string, string> const& headerFields) {
      return requestData(SimpleHttpClient::DELETE, location, "", headerFields);
    }

    v8::Handle<v8::Value> V8ClientConnection::headData (std::string const& location, map<string, string> const& headerFields) {
      return requestData(SimpleHttpClient::HEAD, location, "", headerFields);
    }

    v8::Handle<v8::Value> V8ClientConnection::postData (std::string const& location, std::string const& body, map<string, string> const& headerFields) {
      return requestData(SimpleHttpClient::POST, location, body, headerFields);
    }

    v8::Handle<v8::Value> V8ClientConnection::putData (std::string const& location, std::string const& body, map<string, string> const& headerFields) {
      return requestData(SimpleHttpClient::PUT, location, body, headerFields);
    }

    const std::string& V8ClientConnection::getHostname () {
      return _client->getHostname();
    }

    int V8ClientConnection::getPort () {
      return _client->getPort();
    }

    v8::Handle<v8::Value> V8ClientConnection::requestData (int method, string const& location, string const& body, map<string, string> const& headerFields) {
      _lastErrorMessage = "";
      _lastHttpReturnCode = 0;

      if (_httpResult) {
        delete _httpResult;
      }

      if (body.empty()) {
        _httpResult = _client->request(method, location, 0, 0, headerFields);
      }
      else {
        _httpResult = _client->request(method, location, body.c_str(), body.length(), headerFields);
      }

      if (!_httpResult->isComplete()) {
        // not complete
        _lastErrorMessage = _client->getErrorMessage();

        if (_lastErrorMessage == "") {
          _lastErrorMessage = "Unknown error";
        }

        _lastHttpReturnCode = SimpleHttpResult::HTTP_STATUS_SERVER_ERROR;

        v8::Handle<v8::Object> result = v8::Object::New();
        result->Set(v8::String::New("error"), v8::Boolean::New(true));
        result->Set(v8::String::New("code"), v8::Integer::New(SimpleHttpResult::HTTP_STATUS_SERVER_ERROR));

        int errorNumber = 0;
        switch (_httpResult->getResultType()) {
          case (SimpleHttpResult::COULD_NOT_CONNECT) :
            errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_CONNECT;
            break;

          case (SimpleHttpResult::READ_ERROR) :
            errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_READ;
            break;

          case (SimpleHttpResult::WRITE_ERROR) :
            errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_WRITE;
            break;

          default:
            errorNumber = TRI_SIMPLE_CLIENT_UNKNOWN_ERROR;
        }

        result->Set(v8::String::New("errorNum"), v8::Integer::New(errorNumber));
        result->Set(v8::String::New("errorMessage"), v8::String::New(_lastErrorMessage.c_str(), _lastErrorMessage.length()));
        return result;
      }
      else {
        // complete
        _lastHttpReturnCode = _httpResult->getHttpReturnCode();

        // got a body
        if (_httpResult->getBody().str().length() > 0) {
          string contentType = _httpResult->getContentType(true);

          if (contentType == "application/json") {
            TRI_json_t* js = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, _httpResult->getBody().str().c_str());

            if (js != NULL) {
              // return v8 object
              v8::Handle<v8::Value> result = TRI_ObjectJson(js);
              TRI_FreeJson(TRI_UNKNOWN_MEM_ZONE, js);
              return result;
            }
          }

          // return body as string
          v8::Handle<v8::String> result = v8::String::New(_httpResult->getBody().str().c_str(), _httpResult->getBody().str().length());
          return result;
        }
        else {
          // no body
          // this should not happen
          v8::Handle<v8::Object> result;
          result->Set(v8::String::New("error"), v8::Boolean::New(false));
          result->Set(v8::String::New("code"), v8::Integer::New(_httpResult->getHttpReturnCode()));
          return result;
        }
      }
    }

  }
}
<commit_msg>fixed version path<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief v8 client connection
///
/// @file
///
/// DISCLAIMER
///
/// Copyright by triAGENS GmbH - All rights reserved.
///
/// The Programs (which include both the software and documentation)
/// contain proprietary information of triAGENS GmbH; they are
/// provided under a license agreement containing restrictions on use and
/// disclosure and are also protected by copyright, patent and other
/// intellectual and industrial property laws. Reverse engineering,
/// disassembly or decompilation of the Programs, except to the extent
/// required to obtain interoperability with other independently created
/// software or as specified by law, is prohibited.
///
/// The Programs are not intended for use in any nuclear, aviation, mass
/// transit, medical, or other inherently dangerous applications. It shall
/// be the licensee's responsibility to take all appropriate fail-safe,
/// backup, redundancy, and other measures to ensure the safe use of such
/// applications if the Programs are used for such purposes, and triAGENS
/// GmbH disclaims liability for any damages caused by such use of
/// the Programs.
///
/// This software is the confidential and proprietary information of
/// triAGENS GmbH. You shall not disclose such confidential and
/// proprietary information and shall use it only in accordance with the
/// terms of the license agreement you entered into with triAGENS GmbH.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
/// @author Copyright 2008-2011, triagens GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "V8ClientConnection.h"

#include <sstream>

#include "Basics/StringUtils.h"

#include "Variant/VariantArray.h"
#include "Variant/VariantString.h"

#include "SimpleHttpClient/SimpleHttpClient.h"
#include "SimpleHttpClient/SimpleHttpResult.h"

#include "json.h"
#include "V8/v8-conv.h"

using namespace triagens::basics;
using namespace triagens::httpclient;
using namespace std;

namespace triagens {
  namespace v8client {

    ////////////////////////////////////////////////////////////////////////////////
    /// constructor and destructor
    ////////////////////////////////////////////////////////////////////////////////

    V8ClientConnection::V8ClientConnection (const std::string& hostname,
            int port,
            double requestTimeout,
            size_t retries,
            double connectionTimeout) : _client(0), _httpResult(0) {

      _connected = false;
      _lastHttpReturnCode = 0;
      _lastErrorMessage = "";
      _client = new SimpleHttpClient(hostname, port, requestTimeout, retries, connectionTimeout);

      // connect to server and get version number
      map<string, string> headerFields;
      SimpleHttpResult* result = _client->request(SimpleHttpClient::GET, "/_admin/version", 0, 0, headerFields);

      if (!result->isComplete()) {
        // save error message
        _lastErrorMessage = _client->getErrorMessage();
        _lastHttpReturnCode = 500;
      }
      else {
        _lastHttpReturnCode = result->getHttpReturnCode();
        if (result->getHttpReturnCode() == SimpleHttpResult::HTTP_STATUS_OK) {

          triagens::basics::VariantArray* json = result->getBodyAsVariantArray();
          if (json) {
            triagens::basics::VariantString* vs = json->lookupString("server");
            if (vs && vs->getValue() == "arango") {
              // connected to arango server
              _connected = true;
              vs = json->lookupString("version");
              if (vs) {
                _version = vs->getValue();
              }
            }
            delete json;
          }
        }
      }

      delete result;
    }

    V8ClientConnection::~V8ClientConnection () {
      if (_httpResult) {
        delete _httpResult;
      }

      if (_client) {
        delete _client;
      }
    }

    v8::Handle<v8::Value> V8ClientConnection::getData (std::string const& location, map<string, string> const& headerFields) {
      return requestData(SimpleHttpClient::GET, location, "", headerFields);
    }

    v8::Handle<v8::Value> V8ClientConnection::deleteData (std::string const& location, map<string, string> const& headerFields) {
      return requestData(SimpleHttpClient::DELETE, location, "", headerFields);
    }

    v8::Handle<v8::Value> V8ClientConnection::headData (std::string const& location, map<string, string> const& headerFields) {
      return requestData(SimpleHttpClient::HEAD, location, "", headerFields);
    }

    v8::Handle<v8::Value> V8ClientConnection::postData (std::string const& location, std::string const& body, map<string, string> const& headerFields) {
      return requestData(SimpleHttpClient::POST, location, body, headerFields);
    }

    v8::Handle<v8::Value> V8ClientConnection::putData (std::string const& location, std::string const& body, map<string, string> const& headerFields) {
      return requestData(SimpleHttpClient::PUT, location, body, headerFields);
    }

    const std::string& V8ClientConnection::getHostname () {
      return _client->getHostname();
    }

    int V8ClientConnection::getPort () {
      return _client->getPort();
    }

    v8::Handle<v8::Value> V8ClientConnection::requestData (int method, string const& location, string const& body, map<string, string> const& headerFields) {
      _lastErrorMessage = "";
      _lastHttpReturnCode = 0;

      if (_httpResult) {
        delete _httpResult;
      }

      if (body.empty()) {
        _httpResult = _client->request(method, location, 0, 0, headerFields);
      }
      else {
        _httpResult = _client->request(method, location, body.c_str(), body.length(), headerFields);
      }

      if (!_httpResult->isComplete()) {
        // not complete
        _lastErrorMessage = _client->getErrorMessage();

        if (_lastErrorMessage == "") {
          _lastErrorMessage = "Unknown error";
        }

        _lastHttpReturnCode = SimpleHttpResult::HTTP_STATUS_SERVER_ERROR;

        v8::Handle<v8::Object> result = v8::Object::New();
        result->Set(v8::String::New("error"), v8::Boolean::New(true));
        result->Set(v8::String::New("code"), v8::Integer::New(SimpleHttpResult::HTTP_STATUS_SERVER_ERROR));

        int errorNumber = 0;
        switch (_httpResult->getResultType()) {
          case (SimpleHttpResult::COULD_NOT_CONNECT) :
            errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_CONNECT;
            break;

          case (SimpleHttpResult::READ_ERROR) :
            errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_READ;
            break;

          case (SimpleHttpResult::WRITE_ERROR) :
            errorNumber = TRI_SIMPLE_CLIENT_COULD_NOT_WRITE;
            break;

          default:
            errorNumber = TRI_SIMPLE_CLIENT_UNKNOWN_ERROR;
        }

        result->Set(v8::String::New("errorNum"), v8::Integer::New(errorNumber));
        result->Set(v8::String::New("errorMessage"), v8::String::New(_lastErrorMessage.c_str(), _lastErrorMessage.length()));
        return result;
      }
      else {
        // complete
        _lastHttpReturnCode = _httpResult->getHttpReturnCode();

        // got a body
        if (_httpResult->getBody().str().length() > 0) {
          string contentType = _httpResult->getContentType(true);

          if (contentType == "application/json") {
            TRI_json_t* js = TRI_JsonString(TRI_UNKNOWN_MEM_ZONE, _httpResult->getBody().str().c_str());

            if (js != NULL) {
              // return v8 object
              v8::Handle<v8::Value> result = TRI_ObjectJson(js);
              TRI_FreeJson(TRI_UNKNOWN_MEM_ZONE, js);
              return result;
            }
          }

          // return body as string
          v8::Handle<v8::String> result = v8::String::New(_httpResult->getBody().str().c_str(), _httpResult->getBody().str().length());
          return result;
        }
        else {
          // no body
          // this should not happen
          v8::Handle<v8::Object> result;
          result->Set(v8::String::New("error"), v8::Boolean::New(false));
          result->Set(v8::String::New("code"), v8::Integer::New(_httpResult->getHttpReturnCode()));
          return result;
        }
      }
    }

  }
}
<|endoftext|>


<commit_before>#include "SuffixTree\SuffixTreeBuilder.h"
#include <iostream>
#include <string>
#include <cassert>
#include <ctime>
using namespace std;

int main()
{
    unsigned int length = 100000;
    char* source = new char[length + 1];
    for (unsigned int i = 0; i < length; i++)
    {
        source[i] = rand() % 26 + 'A';
    }
    source[length] = 0;
    string s = source;
    clock_t s_time = clock();
    SuffixTreeBuilder builder(s);
    SuffixTree suffixTree;
    builder.BuildSuffixTree(&suffixTree);
    clock_t e_time = clock();
    cout << e_time - s_time << endl;
    // cout << suffixTree.Show(s, &builder) << endl;
    return 0;
}
<commit_msg>Fix build error on OSX<commit_after>#include "SuffixTree/SuffixTreeBuilder.h"
#include <iostream>
#include <string>
#include <cassert>
#include <ctime>
using namespace std;

int main()
{
    unsigned int length = 100000;
    char* source = new char[length + 1];
    for (unsigned int i = 0; i < length; i++)
    {
        source[i] = rand() % 26 + 'A';
    }
    source[length] = 0;
    string s = source;
    clock_t s_time = clock();
    SuffixTreeBuilder builder(s);
    SuffixTree suffixTree;
    builder.BuildSuffixTree(&suffixTree);
    clock_t e_time = clock();
    cout << e_time - s_time << endl;
    // cout << suffixTree.Show(s, &builder) << endl;
    return 0;
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
//#include <strstream.h>
#include <sstream>
#else
#include <iostream>
//#include <strstream>
#include <sstream>
#endif

#include <stdio.h>

#if !defined(XALAN_NO_NAMESPACES)
	using std::cerr;
	using std::cout;
	using std::cin;
	using std::endl;
//	using std::ostrstream;
	using std::ostringstream;
#endif

// XERCES HEADERS...
//	Most are included by HarnessInit.hpp
#include <parsers/DOMParser.hpp>

// XALAN HEADERS...
//	Most are included by FileUtility.hpp
#include <XalanTransformer/XercesDOMWrapperParsedSource.hpp>

// HARNESS HEADERS...
#include <Harness/XMLFileReporter.hpp>
#include <Harness/FileUtility.hpp>
#include <Harness/HarnessInit.hpp>

#if defined(XALAN_NO_NAMESPACES)
	typedef map<XalanDOMString, XalanDOMString, less<XalanDOMString> >	Hashtable;
#else
	typedef std::map<XalanDOMString, XalanDOMString>  Hashtable;
#endif

// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

FileUtility		h;

void
setHelp()
{
	h.args.help << endl
		 << "conf dir [-category -out -gold -source (XST | XPL | DOM)]"
		 << endl
		 << endl
		 << "dir		(base directory for testcases)"
		 << endl
		 << "-sub dir	(specific directory)"
		 << endl
		 << "-out dir	(base directory for output)"
		 << endl
		 << "-gold dir	(base directory for gold files)"
		 << endl
		 << "-src type	(parsed source; XalanSourceTree(d), XercesParserLiasion, XercesDOM)"
		 << endl;
}

static const char* const 	excludeStylesheets[] =
{
	"output22.xsl",		// Excluded because it outputs EBCDIC
	0
};

inline bool
checkForExclusion(const XalanDOMString&		currentFile)
{
	for (size_t i = 0; excludeStylesheets[i] != 0; ++i)
	{
		if (equals(currentFile, excludeStylesheets[i]))
		{
			return true;
		}
	}

	return false;
}

void
parseWithTransformer(int sourceType, XalanTransformer &xalan, const XSLTInputSource &xmlInput,
					 const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget &output,
					 XMLFileReporter &logFile)
{
	const XalanParsedSource* parsedSource = 0;

	// Parse the XML source accordingly.
	//
	if (sourceType != 0 )
	{
		xalan.parseSource(xmlInput, parsedSource, true);
		h.data.xmlFormat = XalanDOMString("XercesParserLiasion");
	}
	else
	{
		xalan.parseSource(xmlInput, parsedSource, false);
		h.data.xmlFormat = XalanDOMString("XalanSourceTree");
	}

	// If the source was parsed correctly then perform the transform else report the failure.
	//
	if (parsedSource == 0)
	{
		// Report the failure and be sure to increment fail count.
		//
		cout << "ParseWTransformer - Failed to PARSE source document for " << h.data.testOrFile << endl;
		++h.data.fail;
		logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to PARSE source document."));
	}
	else
	{
		xalan.transform(*parsedSource, styleSheet, output);
		xalan.destroyParsedSource(parsedSource);
	}
}

void
parseWithXerces(XalanTransformer &xalan, const XSLTInputSource &xmlInput,
				const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget &output,
				XMLFileReporter &logFile)
{

	h.data.xmlFormat = XalanDOMString("Xerces_DOM");

	DOMParser  theParser;
	theParser.setToCreateXMLDeclTypeNode(false);
	theParser.setDoValidation(true);
	theParser.setDoNamespaces(true);

	theParser.parse(xmlInput);
	DOM_Document theDOM = theParser.getDocument();

	theDOM.normalize();

	XercesDOMSupport	theDOMSupport;
	XercesParserLiaison theParserLiaison(theDOMSupport);

	try
	{
		const XercesDOMWrapperParsedSource	parsedSource(
					theDOM,
					theParserLiaison,
					theDOMSupport,
					XalanDOMString(xmlInput.getSystemId()));

		xalan.transform(parsedSource, styleSheet, output);
	}
	catch(...)
	{
		// Report the failure and be sure to increment fail count.
		//
		cout << "parseWXerces - Failed to PARSE source document for " << h.data.testOrFile << endl;
		++h.data.fail;
		logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to PARSE source document."));
	}
}

int
main(int			argc,
	 const char*	argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

	// Set the program help string,  then get the command line parameters.
	//
	setHelp();

	if (h.getParams(argc, argv, "CONF-RESULTS") == true)
	{
		// Call the static initializers for xerces and xalan, and create a transformer
		//
		HarnessInit xmlPlatformUtils;
		XalanTransformer::initialize();
		XalanTransformer xalan;

		// Get drive designation for final analysis and generate Unique name for results log.
		//
		const XalanDOMString  drive(h.getDrive());			// This is used to get stylesheet for final analysis
		const XalanDOMString  resultFilePrefix("conf");		// This & UniqRunid used for log file name.
		const XalanDOMString  UniqRunid = h.generateUniqRunid();
		const XalanDOMString  resultsFile(drive + h.args.output + resultFilePrefix + UniqRunid + XMLSuffix);

		// Open results log, and do some initialization of result data.
		//
		XMLFileReporter	logFile(resultsFile);
		logFile.logTestFileInit("Conformance Testing:");
		h.data.xmlFormat = XalanDOMString("NotSet");

		// Get the list of Directories that are below conf and iterate through them
		//
		bool foundDir = false;		// Flag indicates directory found. Used in conjunction with -sub cmd-line arg.
		const FileNameVectorType	dirs = h.getDirectoryNames(h.args.base);

		for(FileNameVectorType::size_type	j = 0; j < dirs.size(); ++j)
		{
			// Skip all but the specified directory if the -sub cmd-line option was used.
			//
			const XalanDOMString currentDir(dirs[j]);
			if (length(h.args.sub) > 0 && !equals(currentDir, h.args.sub))
			{
				continue;
			}

			// Check that output directory is there.
			//
			const XalanDOMString  theOutputDir = h.args.output + currentDir;
			h.checkAndCreateDir(theOutputDir);

			// Indicate that directory was processed and get test files from the directory
			//
			foundDir = true;
			const FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, true);

			// Log directory in results log and process it's files.
			//
			logFile.logTestCaseInit(currentDir);
			for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
			{
				Hashtable attrs;
				const XalanDOMString currentFile(files[i]);
				if (checkForExclusion(currentFile))
					continue;

				h.data.testOrFile = currentFile;
				const XalanDOMString  theXSLFile = h.args.base + currentDir + pathSep + currentFile;

				// Check and see if the .xml file exists. If not skip this .xsl file and continue.
				bool fileStatus = true;
				const XalanDOMString  theXMLFile = h.generateFileName(theXSLFile, "xml", &fileStatus);
				if (!fileStatus)
					continue;

				h.data.xmlFileURL = theXMLFile;
				h.data.xslFileURL = theXSLFile;

				XalanDOMString  theGoldFile = h.args.gold + currentDir + pathSep + currentFile;
				theGoldFile = h.generateFileName(theGoldFile, "out");

				const XalanDOMString  outbase =  h.args.output + currentDir + pathSep + currentFile;
				const XalanDOMString  theOutputFile = h.generateFileName(outbase, "out");

				const XSLTInputSource	xslInputSource(c_wstr(theXSLFile));
				const XSLTInputSource	xmlInputSource(c_wstr(theXMLFile));
				const XSLTResultTarget	resultFile(theOutputFile);

				// Parsing(compile) the XSL stylesheet and report the results..
				//
				const XalanCompiledStylesheet*	compiledSS = 0;
				xalan.compileStylesheet(xslInputSource, compiledSS);
				if (compiledSS == 0 )
				{
					// Report the failure and be sure to increment fail count.
					//
					cout << "Failed to PARSE stylesheet for " << currentFile << endl;
					h.data.fail += 1;
					logFile.logErrorResult(currentFile, XalanDOMString("Failed to PARSE stylesheet."));
					continue;
				}

				// Parse the Source XML based on input parameters, and then perform transform.
				//
				switch (h.args.source)
				{
					case 0:
					case 1:
						parseWithTransformer(h.args.source, xalan, xmlInputSource, compiledSS, resultFile, logFile);
						break;

					case 2:
						parseWithXerces(xalan, xmlInputSource, compiledSS, resultFile, logFile);
						break;
				}

				// Check and report results...  Then delete compiled stylesheet.
				//
				h.checkResults(theOutputFile, theGoldFile, logFile);
				xalan.destroyStylesheet(compiledSS);
			}

			logFile.logTestCaseClose("Done", "Pass");
		}

		// Check to see if -sub cmd-line directory was processed correctly.
		//
		if (!foundDir)
		{
			cout << "Specified test directory: \"" << c_str(TranscodeToLocalCodePage(h.args.sub)) << "\" not found" << endl;
		}

		h.reportPassFail(logFile, UniqRunid);
		logFile.logTestFileClose("Conformance ", "Done");
		logFile.close();

		h.analyzeResults(xalan, resultsFile);

	}

	XalanTransformer::terminate();

	return 0;
}
<commit_msg>Removed unnecessary include<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
//#include <strstream.h>
#include <sstream>
#else
#include <iostream>
//#include <strstream>
#include <sstream>
#endif

#include <stdio.h>

#if !defined(XALAN_NO_NAMESPACES)
	using std::cerr;
	using std::cout;
	using std::cin;
	using std::endl;
	using std::ostringstream;
#endif

// XERCES HEADERS...
//	Most are included by HarnessInit.hpp
#include <parsers/DOMParser.hpp>

// XALAN HEADERS...
//	Most are included by FileUtility.hpp
#include <XalanTransformer/XercesDOMWrapperParsedSource.hpp>

// HARNESS HEADERS...
#include <Harness/XMLFileReporter.hpp>
#include <Harness/FileUtility.hpp>
#include <Harness/HarnessInit.hpp>

#if defined(XALAN_NO_NAMESPACES)
	typedef map<XalanDOMString, XalanDOMString, less<XalanDOMString> >	Hashtable;
#else
	typedef std::map<XalanDOMString, XalanDOMString>  Hashtable;
#endif

// This is here for memory leak testing.
#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

FileUtility		h;

void
setHelp()
{
	h.args.help << endl
		 << "conf dir [-category -out -gold -source (XST | XPL | DOM)]"
		 << endl
		 << endl
		 << "dir		(base directory for testcases)"
		 << endl
		 << "-sub dir	(specific directory)"
		 << endl
		 << "-out dir	(base directory for output)"
		 << endl
		 << "-gold dir	(base directory for gold files)"
		 << endl
		 << "-src type	(parsed source; XalanSourceTree(d), XercesParserLiasion, XercesDOM)"
		 << endl;
}

static const char* const 	excludeStylesheets[] =
{
	"output22.xsl",		// Excluded because it outputs EBCDIC
	0
};

inline bool
checkForExclusion(const XalanDOMString&		currentFile)
{
	for (size_t i = 0; excludeStylesheets[i] != 0; ++i)
	{
		if (equals(currentFile, excludeStylesheets[i]))
		{
			return true;
		}
	}

	return false;
}

void
parseWithTransformer(int sourceType, XalanTransformer &xalan, const XSLTInputSource &xmlInput,
					 const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget &output,
					 XMLFileReporter &logFile)
{
	const XalanParsedSource* parsedSource = 0;

	// Parse the XML source accordingly.
	//
	if (sourceType != 0 )
	{
		xalan.parseSource(xmlInput, parsedSource, true);
		h.data.xmlFormat = XalanDOMString("XercesParserLiasion");
	}
	else
	{
		xalan.parseSource(xmlInput, parsedSource, false);
		h.data.xmlFormat = XalanDOMString("XalanSourceTree");
	}

	// If the source was parsed correctly then perform the transform else report the failure.
	//
	if (parsedSource == 0)
	{
		// Report the failure and be sure to increment fail count.
		//
		cout << "ParseWTransformer - Failed to PARSE source document for " << h.data.testOrFile << endl;
		++h.data.fail;
		logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to PARSE source document."));
	}
	else
	{
		xalan.transform(*parsedSource, styleSheet, output);
		xalan.destroyParsedSource(parsedSource);
	}
}

void
parseWithXerces(XalanTransformer &xalan, const XSLTInputSource &xmlInput,
				const XalanCompiledStylesheet* styleSheet, const XSLTResultTarget &output,
				XMLFileReporter &logFile)
{

	h.data.xmlFormat = XalanDOMString("Xerces_DOM");

	DOMParser  theParser;
	theParser.setToCreateXMLDeclTypeNode(false);
	theParser.setDoValidation(true);
	theParser.setDoNamespaces(true);

	theParser.parse(xmlInput);
	DOM_Document theDOM = theParser.getDocument();

	theDOM.normalize();

	XercesDOMSupport	theDOMSupport;
	XercesParserLiaison theParserLiaison(theDOMSupport);

	try
	{
		const XercesDOMWrapperParsedSource	parsedSource(
					theDOM,
					theParserLiaison,
					theDOMSupport,
					XalanDOMString(xmlInput.getSystemId()));

		xalan.transform(parsedSource, styleSheet, output);
	}
	catch(...)
	{
		// Report the failure and be sure to increment fail count.
		//
		cout << "parseWXerces - Failed to PARSE source document for " << h.data.testOrFile << endl;
		++h.data.fail;
		logFile.logErrorResult(h.data.testOrFile, XalanDOMString("Failed to PARSE source document."));
	}
}

int
main(int			argc,
	 const char*	argv[])
{
#if !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

	// Set the program help string,  then get the command line parameters.
	//
	setHelp();

	if (h.getParams(argc, argv, "CONF-RESULTS") == true)
	{
		// Call the static initializers for xerces and xalan, and create a transformer
		//
		HarnessInit xmlPlatformUtils;
		XalanTransformer::initialize();
		XalanTransformer xalan;

		// Get drive designation for final analysis and generate Unique name for results log.
		//
		const XalanDOMString  drive(h.getDrive());			// This is used to get stylesheet for final analysis
		const XalanDOMString  resultFilePrefix("conf");		// This & UniqRunid used for log file name.
		const XalanDOMString  UniqRunid = h.generateUniqRunid();
		const XalanDOMString  resultsFile(drive + h.args.output + resultFilePrefix + UniqRunid + XMLSuffix);

		// Open results log, and do some initialization of result data.
		//
		XMLFileReporter	logFile(resultsFile);
		logFile.logTestFileInit("Conformance Testing:");
		h.data.xmlFormat = XalanDOMString("NotSet");

		// Get the list of Directories that are below conf and iterate through them
		//
		bool foundDir = false;		// Flag indicates directory found. Used in conjunction with -sub cmd-line arg.
		const FileNameVectorType	dirs = h.getDirectoryNames(h.args.base);

		for(FileNameVectorType::size_type	j = 0; j < dirs.size(); ++j)
		{
			// Skip all but the specified directory if the -sub cmd-line option was used.
			//
			const XalanDOMString currentDir(dirs[j]);
			if (length(h.args.sub) > 0 && !equals(currentDir, h.args.sub))
			{
				continue;
			}

			// Check that output directory is there.
			//
			const XalanDOMString  theOutputDir = h.args.output + currentDir;
			h.checkAndCreateDir(theOutputDir);

			// Indicate that directory was processed and get test files from the directory
			//
			foundDir = true;
			const FileNameVectorType files = h.getTestFileNames(h.args.base, currentDir, true);

			// Log directory in results log and process it's files.
			//
			logFile.logTestCaseInit(currentDir);
			for(FileNameVectorType::size_type i = 0; i < files.size(); i++)
			{
				Hashtable attrs;
				const XalanDOMString currentFile(files[i]);
				if (checkForExclusion(currentFile))
					continue;

				h.data.testOrFile = currentFile;
				const XalanDOMString  theXSLFile = h.args.base + currentDir + pathSep + currentFile;

				// Check and see if the .xml file exists. If not skip this .xsl file and continue.
				bool fileStatus = true;
				const XalanDOMString  theXMLFile = h.generateFileName(theXSLFile, "xml", &fileStatus);
				if (!fileStatus)
					continue;

				h.data.xmlFileURL = theXMLFile;
				h.data.xslFileURL = theXSLFile;

				XalanDOMString  theGoldFile = h.args.gold + currentDir + pathSep + currentFile;
				theGoldFile = h.generateFileName(theGoldFile, "out");

				const XalanDOMString  outbase =  h.args.output + currentDir + pathSep + currentFile;
				const XalanDOMString  theOutputFile = h.generateFileName(outbase, "out");

				const XSLTInputSource	xslInputSource(c_wstr(theXSLFile));
				const XSLTInputSource	xmlInputSource(c_wstr(theXMLFile));
				const XSLTResultTarget	resultFile(theOutputFile);

				// Parsing(compile) the XSL stylesheet and report the results..
				//
				const XalanCompiledStylesheet*	compiledSS = 0;
				xalan.compileStylesheet(xslInputSource, compiledSS);
				if (compiledSS == 0 )
				{
					// Report the failure and be sure to increment fail count.
					//
					cout << "Failed to PARSE stylesheet for " << currentFile << endl;
					h.data.fail += 1;
					logFile.logErrorResult(currentFile, XalanDOMString("Failed to PARSE stylesheet."));
					continue;
				}

				// Parse the Source XML based on input parameters, and then perform transform.
				//
				switch (h.args.source)
				{
					case 0:
					case 1:
						parseWithTransformer(h.args.source, xalan, xmlInputSource, compiledSS, resultFile, logFile);
						break;

					case 2:
						parseWithXerces(xalan, xmlInputSource, compiledSS, resultFile, logFile);
						break;
				}

				// Check and report results...  Then delete compiled stylesheet.
				//
				h.checkResults(theOutputFile, theGoldFile, logFile);
				xalan.destroyStylesheet(compiledSS);
			}

			logFile.logTestCaseClose("Done", "Pass");
		}

		// Check to see if -sub cmd-line directory was processed correctly.
		//
		if (!foundDir)
		{
			cout << "Specified test directory: \"" << c_str(TranscodeToLocalCodePage(h.args.sub)) << "\" not found" << endl;
		}

		h.reportPassFail(logFile, UniqRunid);
		logFile.logTestFileClose("Conformance ", "Done");
		logFile.close();

		h.analyzeResults(xalan, resultsFile);

	}

	XalanTransformer::terminate();

	return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "WebDevToolsFrontendImpl.h"

#include "InspectorFrontendClientImpl.h"
#include "V8InspectorFrontendHost.h"
#include "V8MouseEvent.h"
#include "V8Node.h"
#include "WebDevToolsFrontendClient.h"
#include "WebFrameImpl.h"
#include "WebScriptSource.h"
#include "WebViewImpl.h"
#include "bindings/v8/ScriptController.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/V8DOMWrapper.h"
#include "bindings/v8/V8Utilities.h"
#include "core/dom/Document.h"
#include "core/dom/Event.h"
#include "core/dom/Node.h"
#include "core/inspector/InspectorController.h"
#include "core/inspector/InspectorFrontendHost.h"
#include "core/page/ContextMenuController.h"
#include "core/page/DOMWindow.h"
#include "core/page/Frame.h"
#include "core/page/Page.h"
#include "core/page/Settings.h"
#include "core/platform/ContextMenuItem.h"
#include "core/platform/Pasteboard.h"
#include "weborigin/SecurityOrigin.h"
#include "wtf/OwnPtr.h"
#include "wtf/Vector.h"
#include "wtf/text/WTFString.h"

using namespace WebCore;

namespace WebKit {

class WebDevToolsFrontendImpl::InspectorFrontendResumeObserver : public ActiveDOMObject {
    WTF_MAKE_NONCOPYABLE(InspectorFrontendResumeObserver);
public:
    InspectorFrontendResumeObserver(WebDevToolsFrontendImpl* webDevToolsFrontendImpl, Document* document)
        : ActiveDOMObject(document)
        , m_webDevToolsFrontendImpl(webDevToolsFrontendImpl)
    {
        suspendIfNeeded();
    }

private:
    virtual bool canSuspend() const OVERRIDE
    {
        return true;
    }

    virtual void resume() OVERRIDE
    {
        m_webDevToolsFrontendImpl->resume();
    }

    WebDevToolsFrontendImpl* m_webDevToolsFrontendImpl;
};

static v8::Local<v8::String> ToV8String(const String& s)
{
    if (s.isNull())
        return v8::Local<v8::String>();

    // FIXME: Call v8String from the Bindings layer.
    return v8::String::New(reinterpret_cast<const uint16_t*>(s.bloatedCharacters()), s.length());
}

WebDevToolsFrontend* WebDevToolsFrontend::create(
    WebView* view,
    WebDevToolsFrontendClient* client,
    const WebString& applicationLocale)
{
    return new WebDevToolsFrontendImpl(
      static_cast<WebViewImpl*>(view),
      client,
      applicationLocale);
}

WebDevToolsFrontendImpl::WebDevToolsFrontendImpl(
    WebViewImpl* webViewImpl,
    WebDevToolsFrontendClient* client,
    const String& applicationLocale)
    : m_webViewImpl(webViewImpl)
    , m_client(client)
    , m_applicationLocale(applicationLocale)
    , m_inspectorFrontendDispatchTimer(this, &WebDevToolsFrontendImpl::maybeDispatch)
{
    InspectorController* ic = m_webViewImpl->page()->inspectorController();
    ic->setInspectorFrontendClient(adoptPtr(new InspectorFrontendClientImpl(m_webViewImpl->page(), m_client, this)));

    // Put each DevTools frontend Page into a private group so that it's not
    // deferred along with the inspected page.
    m_webViewImpl->page()->setGroupType(Page::InspectorPageGroup);
}

WebDevToolsFrontendImpl::~WebDevToolsFrontendImpl()
{
}

void WebDevToolsFrontendImpl::dispatchOnInspectorFrontend(const WebString& message)
{
    m_messages.append(message);
    maybeDispatch(0);
}

void WebDevToolsFrontendImpl::resume()
{
    // We should call maybeDispatch asynchronously here because we are not allowed to update activeDOMObjects list in
    // resume (See ScriptExecutionContext::resumeActiveDOMObjects).
    if (!m_inspectorFrontendDispatchTimer.isActive())
        m_inspectorFrontendDispatchTimer.startOneShot(0);
}

void WebDevToolsFrontendImpl::maybeDispatch(WebCore::Timer<WebDevToolsFrontendImpl>*)
{
    while (!m_messages.isEmpty()) {
        Document* document = m_webViewImpl->page()->mainFrame()->document();
        if (document->activeDOMObjectsAreSuspended()) {
            m_inspectorFrontendResumeObserver = adoptPtr(new InspectorFrontendResumeObserver(this, document));
            return;
        }
        m_inspectorFrontendResumeObserver.clear();
        doDispatchOnInspectorFrontend(m_messages.takeFirst());
    }
}

void WebDevToolsFrontendImpl::doDispatchOnInspectorFrontend(const WebString& message)
{
    WebFrameImpl* frame = m_webViewImpl->mainFrameImpl();
    v8::HandleScope scope;
    v8::Handle<v8::Context> frameContext = frame->frame() ? frame->frame()->script()->currentWorldContext() : v8::Local<v8::Context>();
    v8::Context::Scope contextScope(frameContext);
    v8::Handle<v8::Value> inspectorFrontendApiValue = frameContext->Global()->Get(v8::String::New("InspectorFrontendAPI"));
    if (!inspectorFrontendApiValue->IsObject())
        return;
    v8::Handle<v8::Object> inspectorFrontendApi = v8::Handle<v8::Object>::Cast(inspectorFrontendApiValue);
    v8::Handle<v8::Value> dispatchFunction = inspectorFrontendApi->Get(v8::String::New("dispatchMessage"));
     // The frame might have navigated away from the front-end page (which is still weird).
    if (!dispatchFunction->IsFunction())
        return;
    v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(dispatchFunction);
    Vector< v8::Handle<v8::Value> > args;
    args.append(ToV8String(message));
    v8::TryCatch tryCatch;
    tryCatch.SetVerbose(true);
    ScriptController::callFunctionWithInstrumentation(frame->frame() ? frame->frame()->document() : 0, function, inspectorFrontendApi, args.size(), args.data());
}

} // namespace WebKit
<commit_msg>Inspector should use v8String instead of faking it<commit_after>/*
 * Copyright (C) 2010 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "WebDevToolsFrontendImpl.h"

#include "InspectorFrontendClientImpl.h"
#include "V8InspectorFrontendHost.h"
#include "V8MouseEvent.h"
#include "V8Node.h"
#include "WebDevToolsFrontendClient.h"
#include "WebFrameImpl.h"
#include "WebScriptSource.h"
#include "WebViewImpl.h"
#include "bindings/v8/ScriptController.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/V8DOMWrapper.h"
#include "bindings/v8/V8Utilities.h"
#include "core/dom/Document.h"
#include "core/dom/Event.h"
#include "core/dom/Node.h"
#include "core/inspector/InspectorController.h"
#include "core/inspector/InspectorFrontendHost.h"
#include "core/page/ContextMenuController.h"
#include "core/page/DOMWindow.h"
#include "core/page/Frame.h"
#include "core/page/Page.h"
#include "core/page/Settings.h"
#include "core/platform/ContextMenuItem.h"
#include "core/platform/Pasteboard.h"
#include "weborigin/SecurityOrigin.h"
#include "wtf/OwnPtr.h"
#include "wtf/Vector.h"
#include "wtf/text/WTFString.h"

using namespace WebCore;

namespace WebKit {

class WebDevToolsFrontendImpl::InspectorFrontendResumeObserver : public ActiveDOMObject {
    WTF_MAKE_NONCOPYABLE(InspectorFrontendResumeObserver);
public:
    InspectorFrontendResumeObserver(WebDevToolsFrontendImpl* webDevToolsFrontendImpl, Document* document)
        : ActiveDOMObject(document)
        , m_webDevToolsFrontendImpl(webDevToolsFrontendImpl)
    {
        suspendIfNeeded();
    }

private:
    virtual bool canSuspend() const OVERRIDE
    {
        return true;
    }

    virtual void resume() OVERRIDE
    {
        m_webDevToolsFrontendImpl->resume();
    }

    WebDevToolsFrontendImpl* m_webDevToolsFrontendImpl;
};

WebDevToolsFrontend* WebDevToolsFrontend::create(
    WebView* view,
    WebDevToolsFrontendClient* client,
    const WebString& applicationLocale)
{
    return new WebDevToolsFrontendImpl(
      static_cast<WebViewImpl*>(view),
      client,
      applicationLocale);
}

WebDevToolsFrontendImpl::WebDevToolsFrontendImpl(
    WebViewImpl* webViewImpl,
    WebDevToolsFrontendClient* client,
    const String& applicationLocale)
    : m_webViewImpl(webViewImpl)
    , m_client(client)
    , m_applicationLocale(applicationLocale)
    , m_inspectorFrontendDispatchTimer(this, &WebDevToolsFrontendImpl::maybeDispatch)
{
    InspectorController* ic = m_webViewImpl->page()->inspectorController();
    ic->setInspectorFrontendClient(adoptPtr(new InspectorFrontendClientImpl(m_webViewImpl->page(), m_client, this)));

    // Put each DevTools frontend Page into a private group so that it's not
    // deferred along with the inspected page.
    m_webViewImpl->page()->setGroupType(Page::InspectorPageGroup);
}

WebDevToolsFrontendImpl::~WebDevToolsFrontendImpl()
{
}

void WebDevToolsFrontendImpl::dispatchOnInspectorFrontend(const WebString& message)
{
    m_messages.append(message);
    maybeDispatch(0);
}

void WebDevToolsFrontendImpl::resume()
{
    // We should call maybeDispatch asynchronously here because we are not allowed to update activeDOMObjects list in
    // resume (See ScriptExecutionContext::resumeActiveDOMObjects).
    if (!m_inspectorFrontendDispatchTimer.isActive())
        m_inspectorFrontendDispatchTimer.startOneShot(0);
}

void WebDevToolsFrontendImpl::maybeDispatch(WebCore::Timer<WebDevToolsFrontendImpl>*)
{
    while (!m_messages.isEmpty()) {
        Document* document = m_webViewImpl->page()->mainFrame()->document();
        if (document->activeDOMObjectsAreSuspended()) {
            m_inspectorFrontendResumeObserver = adoptPtr(new InspectorFrontendResumeObserver(this, document));
            return;
        }
        m_inspectorFrontendResumeObserver.clear();
        doDispatchOnInspectorFrontend(m_messages.takeFirst());
    }
}

void WebDevToolsFrontendImpl::doDispatchOnInspectorFrontend(const WebString& message)
{
    WebFrameImpl* frame = m_webViewImpl->mainFrameImpl();
    v8::Isolate* isolate = v8::Isolate::GetCurrent();
    v8::HandleScope scope;
    v8::Handle<v8::Context> frameContext = frame->frame() ? frame->frame()->script()->currentWorldContext() : v8::Local<v8::Context>();
    v8::Context::Scope contextScope(frameContext);
    v8::Handle<v8::Value> inspectorFrontendApiValue = frameContext->Global()->Get(v8::String::New("InspectorFrontendAPI"));
    if (!inspectorFrontendApiValue->IsObject())
        return;
    v8::Handle<v8::Object> inspectorFrontendApi = v8::Handle<v8::Object>::Cast(inspectorFrontendApiValue);
    v8::Handle<v8::Value> dispatchFunction = inspectorFrontendApi->Get(v8::String::New("dispatchMessage"));
     // The frame might have navigated away from the front-end page (which is still weird).
    if (!dispatchFunction->IsFunction())
        return;
    v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(dispatchFunction);
    Vector< v8::Handle<v8::Value> > args;
    args.append(v8String(message, isolate));
    v8::TryCatch tryCatch;
    tryCatch.SetVerbose(true);
    ScriptController::callFunctionWithInstrumentation(frame->frame() ? frame->frame()->document() : 0, function, inspectorFrontendApi, args.size(), args.data());
}

} // namespace WebKit
<|endoftext|>