<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <gtest/gtest.h>

#include <memory>
#include <vector>

#include "SurgSim/DataStructures/Vertices.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Framework/Scene.h"
#include "SurgSim/Graphics/OsgBoxRepresentation.h"
#include "SurgSim/Graphics/OsgManager.h"
#include "SurgSim/Graphics/OsgMaterial.h"
#include "SurgSim/Graphics/OsgLight.h"
#include "SurgSim/Graphics/OsgCurveRepresentation.h"
#include "SurgSim/Graphics/OsgViewElement.h"
#include "SurgSim/Graphics/RenderTests/RenderTest.h"
#include "SurgSim/Math/Quaternion.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Testing/MathUtilities.h"

#include <osg/LineWidth>
#include <osg/Hint>

using SurgSim::Math::Vector3d;
using SurgSim::Math::Vector4d;
using SurgSim::Math::Vector4f;
using SurgSim::Math::Quaterniond;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::makeRigidTransform;
using SurgSim::Math::makeRotationQuaternion;

using SurgSim::Testing::interpolate;
using SurgSim::Testing::interpolatePose;

namespace SurgSim
{
namespace Graphics
{

struct OsgCurveRepresentationRenderTests : public RenderTest
{

protected:
	DataStructures::VerticesPlain makeCube()
	{
		typedef DataStructures::VerticesPlain::VertexType Vertex;
		DataStructures::VerticesPlain result;
		result.addVertex(Vertex(Vector3d(0.1, -0.1, 0.1)));
		result.addVertex(Vertex(Vector3d(0.1, -0.1, 0.1)));
		result.addVertex(Vertex(Vector3d(-0.1, -0.1, 0.1)));
		result.addVertex(Vertex(Vector3d(-0.1, -0.1, -0.1)));
		result.addVertex(Vertex(Vector3d(0.1, -0.1, -0.1)));

		result.addVertex(Vertex(Vector3d(0.1, 0.1, 0.1)));
		result.addVertex(Vertex(Vector3d(-0.1, 0.1, 0.1)));
		result.addVertex(Vertex(Vector3d(-0.1, 0.1, -0.1)));
		result.addVertex(Vertex(Vector3d(0.1, 0.1, -0.1)));
		return result;
	}
};

TEST_F(OsgCurveRepresentationRenderTests, DynamicRotate)
{
	auto element = std::make_shared<Framework::BasicSceneElement>("Element");
	auto vertices = makeCube();
	auto representation = std::make_shared<OsgCurveRepresentation>("Curve");
	element->addComponent(representation);
	scene->addSceneElement(element);
	viewElement->enableManipulator(true);
	viewElement->setPose(makeRigidTransform(
							 Math::Vector3d(0.0, 0.0, -2.0),
							 Math::Vector3d(0.0, 0.0, 0.0),
							 Math::Vector3d(0.0, 1.0, 0.0)));

	auto material = buildMaterial("Shaders/material_curve.vert", "Shaders/material.frag");
	material->addUniform("vec4", "diffuseColor");
	material->setValue("diffuseColor", Vector4f(0.2, 0.2, 0.9, 1.0));

	material->addUniform("vec4", "specularColor");
	material->setValue("specularColor", Vector4f(0.4, 0.4, 0.4, 1.0));

	material->addUniform("float", "shininess");
	material->setValue("shininess", 64.0f);

	representation->setMaterial(material);
	element->addComponent(material);

	auto light = std::make_shared<Graphics::OsgLight>("Light");
	// light->setLocalPose(Math::makeRigidTranslation(Math::Vector3d(0.5, 0.5, 0.5)));
	viewElement->addComponent(light);

	/// Run the thread
	runtime->start();
	EXPECT_TRUE(graphicsManager->isInitialized());
	EXPECT_TRUE(viewElement->isInitialized());
	int numSteps = 10 * 60;

	auto widths = std::make_pair(0.1, 5.0);
	auto tensions = std::make_pair(0.1, 0.9);

	RigidTransform3d transform = makeRigidTransform(makeRotationQuaternion(0.02, Vector3d(0.0, 1.0, 1.0)),
								 Vector3d(0.0, -0.0, 0.0));

	for (int i = 0; i < numSteps; ++i)
	{

		double t = static_cast<double>(i) / numSteps;
		for (size_t i = 0; i < vertices.getNumVertices(); ++i)
		{
			vertices.setVertexPosition(i, transform * vertices.getVertexPosition(i));
		}

		representation->setWidth(interpolate(widths.first, widths.second, t));
		representation->setTension(interpolate(tensions.first, tensions.second, t));
		representation->updateControlPoints(vertices);

		boost::this_thread::sleep(boost::posix_time::milliseconds(1000.0 / 30.0));
	}
	boost::this_thread::sleep(boost::posix_time::milliseconds(100000));

}

}; // namespace Graphics
}; // namespace SurgSim
<commit_msg>Reduce sleep time after render test to 1 second (from 100).<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <gtest/gtest.h>

#include <memory>
#include <vector>

#include "SurgSim/DataStructures/Vertices.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Framework/Scene.h"
#include "SurgSim/Graphics/OsgBoxRepresentation.h"
#include "SurgSim/Graphics/OsgManager.h"
#include "SurgSim/Graphics/OsgMaterial.h"
#include "SurgSim/Graphics/OsgLight.h"
#include "SurgSim/Graphics/OsgCurveRepresentation.h"
#include "SurgSim/Graphics/OsgViewElement.h"
#include "SurgSim/Graphics/RenderTests/RenderTest.h"
#include "SurgSim/Math/Quaternion.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Testing/MathUtilities.h"

#include <osg/LineWidth>
#include <osg/Hint>

using SurgSim::Math::Vector3d;
using SurgSim::Math::Vector4d;
using SurgSim::Math::Vector4f;
using SurgSim::Math::Quaterniond;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::makeRigidTransform;
using SurgSim::Math::makeRotationQuaternion;

using SurgSim::Testing::interpolate;
using SurgSim::Testing::interpolatePose;

namespace SurgSim
{
namespace Graphics
{

struct OsgCurveRepresentationRenderTests : public RenderTest
{

protected:
	DataStructures::VerticesPlain makeCube()
	{
		typedef DataStructures::VerticesPlain::VertexType Vertex;
		DataStructures::VerticesPlain result;
		result.addVertex(Vertex(Vector3d(0.1, -0.1, 0.1)));
		result.addVertex(Vertex(Vector3d(0.1, -0.1, 0.1)));
		result.addVertex(Vertex(Vector3d(-0.1, -0.1, 0.1)));
		result.addVertex(Vertex(Vector3d(-0.1, -0.1, -0.1)));
		result.addVertex(Vertex(Vector3d(0.1, -0.1, -0.1)));

		result.addVertex(Vertex(Vector3d(0.1, 0.1, 0.1)));
		result.addVertex(Vertex(Vector3d(-0.1, 0.1, 0.1)));
		result.addVertex(Vertex(Vector3d(-0.1, 0.1, -0.1)));
		result.addVertex(Vertex(Vector3d(0.1, 0.1, -0.1)));
		return result;
	}
};

TEST_F(OsgCurveRepresentationRenderTests, DynamicRotate)
{
	auto element = std::make_shared<Framework::BasicSceneElement>("Element");
	auto vertices = makeCube();
	auto representation = std::make_shared<OsgCurveRepresentation>("Curve");
	element->addComponent(representation);
	scene->addSceneElement(element);
	viewElement->enableManipulator(true);
	viewElement->setPose(makeRigidTransform(
							 Math::Vector3d(0.0, 0.0, -2.0),
							 Math::Vector3d(0.0, 0.0, 0.0),
							 Math::Vector3d(0.0, 1.0, 0.0)));

	auto material = buildMaterial("Shaders/material_curve.vert", "Shaders/material.frag");
	material->addUniform("vec4", "diffuseColor");
	material->setValue("diffuseColor", Vector4f(0.2, 0.2, 0.9, 1.0));

	material->addUniform("vec4", "specularColor");
	material->setValue("specularColor", Vector4f(0.4, 0.4, 0.4, 1.0));

	material->addUniform("float", "shininess");
	material->setValue("shininess", 64.0f);

	representation->setMaterial(material);
	element->addComponent(material);

	auto light = std::make_shared<Graphics::OsgLight>("Light");
	// light->setLocalPose(Math::makeRigidTranslation(Math::Vector3d(0.5, 0.5, 0.5)));
	viewElement->addComponent(light);

	/// Run the thread
	runtime->start();
	EXPECT_TRUE(graphicsManager->isInitialized());
	EXPECT_TRUE(viewElement->isInitialized());
	int numSteps = 10 * 60;

	auto widths = std::make_pair(0.1, 5.0);
	auto tensions = std::make_pair(0.1, 0.9);

	RigidTransform3d transform = makeRigidTransform(makeRotationQuaternion(0.02, Vector3d(0.0, 1.0, 1.0)),
								 Vector3d(0.0, -0.0, 0.0));

	for (int i = 0; i < numSteps; ++i)
	{

		double t = static_cast<double>(i) / numSteps;
		for (size_t i = 0; i < vertices.getNumVertices(); ++i)
		{
			vertices.setVertexPosition(i, transform * vertices.getVertexPosition(i));
		}

		representation->setWidth(interpolate(widths.first, widths.second, t));
		representation->setTension(interpolate(tensions.first, tensions.second, t));
		representation->updateControlPoints(vertices);

		boost::this_thread::sleep(boost::posix_time::milliseconds(1000.0 / 30.0));
	}
	boost::this_thread::sleep(boost::posix_time::milliseconds(1000));

}

}; // namespace Graphics
}; // namespace SurgSim
<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

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

#include <iterator>

#include "otbImage.h"
#include "otbVectorData.h"
#include "otbRadiometricMomentsImageFunction.h"
#include "itkListSample.h"
#include "itkFixedArray.h"
#include "otbDescriptorsListSampleGenerator.h"
#include "otbImageFileReader.h"
#include "otbVectorDataFileReader.h"

const unsigned int Dimension = 2;
typedef int        LabelType;
typedef double     PixelType;
typedef double     FunctionPrecisionType;
typedef double     CoordRepType;

typedef otb::Image<PixelType, Dimension>                              ImageType;
typedef otb::VectorData<>                                             VectorDataType;
typedef otb::RadiometricMomentsImageFunction<ImageType, CoordRepType> FunctionType;

typedef FunctionType::OutputType                        SampleType;
typedef itk::Statistics::ListSample<SampleType>         ListSampleType;
typedef itk::FixedArray<LabelType, 1>                   LabelSampleType;
typedef itk::Statistics::ListSample<LabelSampleType>    LabelListSampleType;

typedef otb::DescriptorsListSampleGenerator
           < ImageType,
             VectorDataType,
             ListSampleType,
             LabelListSampleType,
             FunctionPrecisionType,
             CoordRepType > DescriptorsListSampleGeneratorType;

typedef otb::ImageFileReader<ImageType>           ImageReaderType;
typedef otb::VectorDataFileReader<VectorDataType> VectorDataReaderType;

typedef FunctionType::PointType PointType;
typedef DescriptorsListSampleGeneratorType::SamplesPositionType SamplesPositionType;

struct SampleEntry
{
  PointType  position;
  LabelType  label;
  SampleType measurement;
};

struct CompareSampleEntry
{
  bool operator () (SampleEntry p, SampleEntry q)
  {
    // order with the y axis position
    if (p.position[1] < q.position[1])
      return true;
    if (p.position[1] > q.position[1])
      return false;

    // If one the same line,
    // order with the x axis position
    if (p.position[0] < q.position[0])
      return true;

    return false;
  }
};

ostream &operator<<(ostream &stream, SampleEntry entry)
{
  stream << "---" << std::endl
         << "Label        : " << entry.label << std::endl
         << "Position     : " << entry.position << std::endl
         << "Measurements : " << entry.measurement;
  return stream;
}

int otbDescriptorsListSampleGeneratorNew(int itkNotUsed(argc), char* itkNotUsed(argv)[])
{
  // instantiation
  DescriptorsListSampleGeneratorType::Pointer generator = DescriptorsListSampleGeneratorType::New();

  std::cout << generator << std::endl;

  return EXIT_SUCCESS;
}

int otbDescriptorsListSampleGenerator(int argc, char* argv[])
{
  if (argc != 5)
    {
    std::cerr << "Wrong number of arguments" << std::endl;
    return EXIT_FAILURE;
    }

  const char* inputImageFileName = argv[1];
  const char* inputSamplesLocation = argv[2];
  const char* outputFileName = argv[3];
  int streaming = atoi(argv[4]);

  ImageReaderType::Pointer imageReader = ImageReaderType::New();
  imageReader->SetFileName(inputImageFileName);

  VectorDataReaderType::Pointer vectorDataReader = VectorDataReaderType::New();
  vectorDataReader->SetFileName(inputSamplesLocation);

  //imageReader->Update();
  //vectorDataReader->Update();

  FunctionType::Pointer descriptorsFunction = FunctionType::New();
  descriptorsFunction->SetInputImage(imageReader->GetOutput());
  descriptorsFunction->SetNeighborhoodRadius(5);

  DescriptorsListSampleGeneratorType::Pointer descriptorsGenerator = DescriptorsListSampleGeneratorType::New();
  descriptorsGenerator->SetInputImage(imageReader->GetOutput());
  descriptorsGenerator->SetSamplesLocations(vectorDataReader->GetOutput());
  descriptorsGenerator->SetDescriptorsFunction(descriptorsFunction.GetPointer());
  descriptorsGenerator->SetNeighborhoodRadius(5);

  if (streaming == 0)
    {
    descriptorsGenerator->GetStreamer()->SetNumberOfStreamDivisions(1);
    }
  else
    {
    descriptorsGenerator->GetStreamer()->SetNumberOfStreamDivisions(streaming);
    }

  descriptorsGenerator->Update();

  ListSampleType::Pointer      samples = descriptorsGenerator->GetListSample();
  LabelListSampleType::Pointer labels  = descriptorsGenerator->GetLabelListSample();
  SamplesPositionType&         positions = descriptorsGenerator->GetSamplesPositions();

  ListSampleType::Iterator sampleIt = samples->Begin();
  LabelListSampleType::Iterator labelIt = labels->Begin();
  SamplesPositionType::const_iterator posIt = positions.begin();

  ListSampleType::Iterator sampleEnd = samples->End();
  LabelListSampleType::Iterator labelEnd = labels->End();
  SamplesPositionType::const_iterator posEnd = positions.end();

  std::vector<SampleEntry> entries;

  while (sampleIt != sampleEnd && labelIt != labelEnd && posIt != posEnd)
    {
    SampleEntry entry;
    entry.position = *posIt;
    entry.label = labelIt.GetMeasurementVector()[0];
    entry.measurement = sampleIt.GetMeasurementVector();

    entries.push_back(entry);

    ++sampleIt;
    ++labelIt;
    ++posIt;
    }

  std::sort(entries.begin(), entries.end(), CompareSampleEntry());
  std::ofstream file(outputFileName);
  std::copy(entries.begin(), entries.end(), std::ostream_iterator<SampleEntry>(file, "\n"));
  file.close();

  return EXIT_SUCCESS;
}
<commit_msg>COMP : correct the test due to class changes<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

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

#include <iterator>

#include "otbImage.h"
#include "otbVectorData.h"
#include "otbRadiometricMomentsImageFunction.h"
#include "itkListSample.h"
#include "itkFixedArray.h"
#include "itkVariableLengthVector.h"
#include "otbDescriptorsListSampleGenerator.h"
#include "otbImageFileReader.h"
#include "otbVectorDataFileReader.h"
#include "otbImageFunctionAdapter.h"

const unsigned int Dimension = 2;
typedef int        LabelType;
typedef double     PixelType;
typedef double     FunctionPrecisionType;
typedef double     CoordRepType;

typedef otb::Image<PixelType, Dimension>                              ImageType;
typedef otb::VectorData<>                                             VectorDataType;
typedef otb::RadiometricMomentsImageFunction<ImageType, CoordRepType> FunctionType;
  typedef otb::ImageFunctionAdapter
    <ImageType,FunctionType>                                          AdapatedFunctionType;

//typedef FunctionType::OutputType                      SampleType;
typedef itk::VariableLengthVector<CoordRepType>         SampleType;
typedef itk::Statistics::ListSample<SampleType>         ListSampleType;
typedef itk::FixedArray<LabelType>                      LabelSampleType;
typedef itk::Statistics::ListSample<LabelSampleType>    LabelListSampleType;

typedef otb::DescriptorsListSampleGenerator
           < ImageType,
             VectorDataType,
             ListSampleType,
             LabelListSampleType,
             FunctionPrecisionType,
             CoordRepType > DescriptorsListSampleGeneratorType;

typedef otb::ImageFileReader<ImageType>           ImageReaderType;
typedef otb::VectorDataFileReader<VectorDataType> VectorDataReaderType;

typedef FunctionType::PointType PointType;
typedef DescriptorsListSampleGeneratorType::SamplesPositionType SamplesPositionType;

struct SampleEntry
{
  PointType  position;
  LabelType  label;
  SampleType measurement;
};

struct CompareSampleEntry
{
  bool operator () (SampleEntry p, SampleEntry q)
  {
    // order with the y axis position
    if (p.position[1] < q.position[1])
      return true;
    if (p.position[1] > q.position[1])
      return false;

    // If one the same line,
    // order with the x axis position
    if (p.position[0] < q.position[0])
      return true;

    return false;
  }
};

ostream &operator<<(ostream &stream, SampleEntry entry)
{
  stream << "---" << std::endl
         << "Label        : " << entry.label << std::endl
         << "Position     : " << entry.position << std::endl
         << "Measurements : " << entry.measurement;
  return stream;
}

int otbDescriptorsListSampleGeneratorNew(int itkNotUsed(argc), char* itkNotUsed(argv)[])
{
  // instantiation
  DescriptorsListSampleGeneratorType::Pointer generator = DescriptorsListSampleGeneratorType::New();

  std::cout << generator << std::endl;

  return EXIT_SUCCESS;
}

int otbDescriptorsListSampleGenerator(int argc, char* argv[])
{
  if (argc != 5)
    {
    std::cerr << "Wrong number of arguments" << std::endl;
    return EXIT_FAILURE;
    }

  const char* inputImageFileName = argv[1];
  const char* inputSamplesLocation = argv[2];
  const char* outputFileName = argv[3];
  int streaming = atoi(argv[4]);

  ImageReaderType::Pointer imageReader = ImageReaderType::New();
  imageReader->SetFileName(inputImageFileName);

  VectorDataReaderType::Pointer vectorDataReader = VectorDataReaderType::New();
  vectorDataReader->SetFileName(inputSamplesLocation);

  //imageReader->Update();
  //vectorDataReader->Update();

  AdapatedFunctionType::Pointer descriptorsFunction = AdapatedFunctionType::New();
  descriptorsFunction->SetInputImage(imageReader->GetOutput());
  descriptorsFunction->GetImageFunction()->SetNeighborhoodRadius(5);

  DescriptorsListSampleGeneratorType::Pointer descriptorsGenerator = DescriptorsListSampleGeneratorType::New();
  descriptorsGenerator->SetInputImage(imageReader->GetOutput());
  descriptorsGenerator->SetSamplesLocations(vectorDataReader->GetOutput());
  descriptorsGenerator->SetDescriptorsFunction(descriptorsFunction.GetPointer());
  descriptorsGenerator->SetNeighborhoodRadius(5);

  if (streaming == 0)
    {
    descriptorsGenerator->GetStreamer()->SetNumberOfStreamDivisions(1);
    }
  else
    {
    descriptorsGenerator->GetStreamer()->SetNumberOfStreamDivisions(streaming);
    }

  descriptorsGenerator->Update();

  ListSampleType::Pointer      samples = descriptorsGenerator->GetListSample();
  LabelListSampleType::Pointer labels  = descriptorsGenerator->GetLabelListSample();
  SamplesPositionType&         positions = descriptorsGenerator->GetSamplesPositions();

  ListSampleType::Iterator sampleIt = samples->Begin();
  LabelListSampleType::Iterator labelIt = labels->Begin();
  SamplesPositionType::const_iterator posIt = positions.begin();

  ListSampleType::Iterator sampleEnd = samples->End();
  LabelListSampleType::Iterator labelEnd = labels->End();
  SamplesPositionType::const_iterator posEnd = positions.end();

  std::vector<SampleEntry> entries;

  while (sampleIt != sampleEnd && labelIt != labelEnd && posIt != posEnd)
    {
    SampleEntry entry;
    entry.position = *posIt;
    entry.label = labelIt.GetMeasurementVector()[0];
    entry.measurement = sampleIt.GetMeasurementVector();

    entries.push_back(entry);

    ++sampleIt;
    ++labelIt;
    ++posIt;
    }

  std::sort(entries.begin(), entries.end(), CompareSampleEntry());
  std::ofstream file(outputFileName);
  std::copy(entries.begin(), entries.end(), std::ostream_iterator<SampleEntry>(file, "\n"));
  file.close();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_descriptor_shuffle.h"
#include "testing/gtest/include/gtest/gtest.h"

using base::InjectiveMultimap;
using base::InjectionArc;
using base::PerformInjectiveMultimap;
using base::InjectionDelegate;

namespace {
typedef testing::Test FileDescriptorShuffleTest;
}

// 'Duplicated' file descriptors start at this number
static const int kDuplicateBase = 1000;

struct Action {
  enum Type {
    CLOSE,
    MOVE,
    DUPLICATE,
  };

  Action(Type in_type, int in_fd1, int in_fd2 = -1)
      : type(in_type),
        fd1(in_fd1),
        fd2(in_fd2) {
  }

  bool operator==(const Action& other) const {
    return other.type == type &&
           other.fd1 == fd1 &&
           other.fd2 == fd2;
  }

  Type type;
  int fd1;
  int fd2;
};

class InjectionTracer : public InjectionDelegate {
 public:
  InjectionTracer()
      : next_duplicate_(kDuplicateBase) {
  }

  bool Duplicate(int* result, int fd) {
    *result = next_duplicate_++;
    actions_.push_back(Action(Action::DUPLICATE, *result, fd));
    return true;
  }

  bool Move(int src, int dest) {
    actions_.push_back(Action(Action::MOVE, src, dest));
    return true;
  }

  void Close(int fd) {
    actions_.push_back(Action(Action::CLOSE, fd));
  }

  const std::vector<Action>& actions() const { return actions_; }

 private:
  int next_duplicate_;
  std::vector<Action> actions_;
};

TEST(FileDescriptorShuffleTest, Empty) {
  InjectiveMultimap map;
  InjectionTracer tracer;

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(0u, tracer.actions().size());
}

TEST(FileDescriptorShuffleTest, Noop) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 0, false));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(0u, tracer.actions().size());
}

TEST(FileDescriptorShuffleTest, NoopAndClose) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 0, true));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(0u, tracer.actions().size());
}

TEST(FileDescriptorShuffleTest, Simple1) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, false));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(1u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] == Action(Action::MOVE, 0, 1));
}

TEST(FileDescriptorShuffleTest, Simple2) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, false));
  map.push_back(InjectionArc(2, 3, false));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(2u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 2, 3));
}

TEST(FileDescriptorShuffleTest, Simple3) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, true));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(2u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::CLOSE, 0));
}

TEST(FileDescriptorShuffleTest, Simple4) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(10, 0, true));
  map.push_back(InjectionArc(1, 1, true));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(2u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] == Action(Action::MOVE, 10, 0));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::CLOSE, 10));
}

TEST(FileDescriptorShuffleTest, Cycle) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, false));
  map.push_back(InjectionArc(1, 0, false));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(4u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] ==
              Action(Action::DUPLICATE, kDuplicateBase, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[2] == Action(Action::MOVE, kDuplicateBase, 0));
  EXPECT_TRUE(tracer.actions()[3] == Action(Action::CLOSE, kDuplicateBase));
}

TEST(FileDescriptorShuffleTest, CycleAndClose1) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, true));
  map.push_back(InjectionArc(1, 0, false));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(4u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] ==
              Action(Action::DUPLICATE, kDuplicateBase, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[2] == Action(Action::MOVE, kDuplicateBase, 0));
  EXPECT_TRUE(tracer.actions()[3] == Action(Action::CLOSE, kDuplicateBase));
}

TEST(FileDescriptorShuffleTest, CycleAndClose2) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, false));
  map.push_back(InjectionArc(1, 0, true));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(4u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] ==
              Action(Action::DUPLICATE, kDuplicateBase, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[2] == Action(Action::MOVE, kDuplicateBase, 0));
  EXPECT_TRUE(tracer.actions()[3] == Action(Action::CLOSE, kDuplicateBase));
}

TEST(FileDescriptorShuffleTest, CycleAndClose3) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, true));
  map.push_back(InjectionArc(1, 0, true));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(4u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] ==
              Action(Action::DUPLICATE, kDuplicateBase, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[2] == Action(Action::MOVE, kDuplicateBase, 0));
  EXPECT_TRUE(tracer.actions()[3] == Action(Action::CLOSE, kDuplicateBase));
}

TEST(FileDescriptorShuffleTest, Fanout) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, false));
  map.push_back(InjectionArc(0, 2, false));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(2u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 0, 2));
}

TEST(FileDescriptorShuffleTest, FanoutAndClose1) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, true));
  map.push_back(InjectionArc(0, 2, false));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(3u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 0, 2));
  EXPECT_TRUE(tracer.actions()[2] == Action(Action::CLOSE, 0));
}

TEST(FileDescriptorShuffleTest, FanoutAndClose2) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, false));
  map.push_back(InjectionArc(0, 2, true));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(3u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 0, 2));
  EXPECT_TRUE(tracer.actions()[2] == Action(Action::CLOSE, 0));
}

TEST(FileDescriptorShuffleTest, FanoutAndClose3) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, true));
  map.push_back(InjectionArc(0, 2, true));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(3u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 0, 2));
  EXPECT_TRUE(tracer.actions()[2] == Action(Action::CLOSE, 0));
}

class FailingDelegate : public InjectionDelegate {
 public:
  bool Duplicate(int* result, int fd) {
    return false;
  }

  bool Move(int src, int dest) {
    return false;
  }

  void Close(int fd) {
  }
};

TEST(FileDescriptorShuffleTest, EmptyWithFailure) {
  InjectiveMultimap map;
  FailingDelegate failing;

  EXPECT_TRUE(PerformInjectiveMultimap(map, &failing));
}

TEST(FileDescriptorShuffleTest, NoopWithFailure) {
  InjectiveMultimap map;
  FailingDelegate failing;
  map.push_back(InjectionArc(0, 0, false));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &failing));
}

TEST(FileDescriptorShuffleTest, Simple1WithFailure) {
  InjectiveMultimap map;
  FailingDelegate failing;
  map.push_back(InjectionArc(0, 1, false));

  EXPECT_FALSE(PerformInjectiveMultimap(map, &failing));
}
<commit_msg>Use ASSERT_EQ instead of EXPECT_EQ to avoid accessing invalid index in the following tests.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_descriptor_shuffle.h"
#include "testing/gtest/include/gtest/gtest.h"

using base::InjectiveMultimap;
using base::InjectionArc;
using base::PerformInjectiveMultimap;
using base::InjectionDelegate;

namespace {
typedef testing::Test FileDescriptorShuffleTest;
}

// 'Duplicated' file descriptors start at this number
static const int kDuplicateBase = 1000;

struct Action {
  enum Type {
    CLOSE,
    MOVE,
    DUPLICATE,
  };

  Action(Type in_type, int in_fd1, int in_fd2 = -1)
      : type(in_type),
        fd1(in_fd1),
        fd2(in_fd2) {
  }

  bool operator==(const Action& other) const {
    return other.type == type &&
           other.fd1 == fd1 &&
           other.fd2 == fd2;
  }

  Type type;
  int fd1;
  int fd2;
};

class InjectionTracer : public InjectionDelegate {
 public:
  InjectionTracer()
      : next_duplicate_(kDuplicateBase) {
  }

  bool Duplicate(int* result, int fd) {
    *result = next_duplicate_++;
    actions_.push_back(Action(Action::DUPLICATE, *result, fd));
    return true;
  }

  bool Move(int src, int dest) {
    actions_.push_back(Action(Action::MOVE, src, dest));
    return true;
  }

  void Close(int fd) {
    actions_.push_back(Action(Action::CLOSE, fd));
  }

  const std::vector<Action>& actions() const { return actions_; }

 private:
  int next_duplicate_;
  std::vector<Action> actions_;
};

TEST(FileDescriptorShuffleTest, Empty) {
  InjectiveMultimap map;
  InjectionTracer tracer;

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(0u, tracer.actions().size());
}

TEST(FileDescriptorShuffleTest, Noop) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 0, false));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(0u, tracer.actions().size());
}

TEST(FileDescriptorShuffleTest, NoopAndClose) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 0, true));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  EXPECT_EQ(0u, tracer.actions().size());
}

TEST(FileDescriptorShuffleTest, Simple1) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, false));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  ASSERT_EQ(1u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] == Action(Action::MOVE, 0, 1));
}

TEST(FileDescriptorShuffleTest, Simple2) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, false));
  map.push_back(InjectionArc(2, 3, false));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  ASSERT_EQ(2u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 2, 3));
}

TEST(FileDescriptorShuffleTest, Simple3) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, true));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  ASSERT_EQ(2u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::CLOSE, 0));
}

TEST(FileDescriptorShuffleTest, Simple4) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(10, 0, true));
  map.push_back(InjectionArc(1, 1, true));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  ASSERT_EQ(2u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] == Action(Action::MOVE, 10, 0));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::CLOSE, 10));
}

TEST(FileDescriptorShuffleTest, Cycle) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, false));
  map.push_back(InjectionArc(1, 0, false));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  ASSERT_EQ(4u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] ==
              Action(Action::DUPLICATE, kDuplicateBase, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[2] == Action(Action::MOVE, kDuplicateBase, 0));
  EXPECT_TRUE(tracer.actions()[3] == Action(Action::CLOSE, kDuplicateBase));
}

TEST(FileDescriptorShuffleTest, CycleAndClose1) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, true));
  map.push_back(InjectionArc(1, 0, false));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  ASSERT_EQ(4u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] ==
              Action(Action::DUPLICATE, kDuplicateBase, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[2] == Action(Action::MOVE, kDuplicateBase, 0));
  EXPECT_TRUE(tracer.actions()[3] == Action(Action::CLOSE, kDuplicateBase));
}

TEST(FileDescriptorShuffleTest, CycleAndClose2) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, false));
  map.push_back(InjectionArc(1, 0, true));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  ASSERT_EQ(4u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] ==
              Action(Action::DUPLICATE, kDuplicateBase, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[2] == Action(Action::MOVE, kDuplicateBase, 0));
  EXPECT_TRUE(tracer.actions()[3] == Action(Action::CLOSE, kDuplicateBase));
}

TEST(FileDescriptorShuffleTest, CycleAndClose3) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, true));
  map.push_back(InjectionArc(1, 0, true));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  ASSERT_EQ(4u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] ==
              Action(Action::DUPLICATE, kDuplicateBase, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[2] == Action(Action::MOVE, kDuplicateBase, 0));
  EXPECT_TRUE(tracer.actions()[3] == Action(Action::CLOSE, kDuplicateBase));
}

TEST(FileDescriptorShuffleTest, Fanout) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, false));
  map.push_back(InjectionArc(0, 2, false));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  ASSERT_EQ(2u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 0, 2));
}

TEST(FileDescriptorShuffleTest, FanoutAndClose1) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, true));
  map.push_back(InjectionArc(0, 2, false));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  ASSERT_EQ(3u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 0, 2));
  EXPECT_TRUE(tracer.actions()[2] == Action(Action::CLOSE, 0));
}

TEST(FileDescriptorShuffleTest, FanoutAndClose2) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, false));
  map.push_back(InjectionArc(0, 2, true));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  ASSERT_EQ(3u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 0, 2));
  EXPECT_TRUE(tracer.actions()[2] == Action(Action::CLOSE, 0));
}

TEST(FileDescriptorShuffleTest, FanoutAndClose3) {
  InjectiveMultimap map;
  InjectionTracer tracer;
  map.push_back(InjectionArc(0, 1, true));
  map.push_back(InjectionArc(0, 2, true));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &tracer));
  ASSERT_EQ(3u, tracer.actions().size());
  EXPECT_TRUE(tracer.actions()[0] == Action(Action::MOVE, 0, 1));
  EXPECT_TRUE(tracer.actions()[1] == Action(Action::MOVE, 0, 2));
  EXPECT_TRUE(tracer.actions()[2] == Action(Action::CLOSE, 0));
}

class FailingDelegate : public InjectionDelegate {
 public:
  bool Duplicate(int* result, int fd) {
    return false;
  }

  bool Move(int src, int dest) {
    return false;
  }

  void Close(int fd) {
  }
};

TEST(FileDescriptorShuffleTest, EmptyWithFailure) {
  InjectiveMultimap map;
  FailingDelegate failing;

  EXPECT_TRUE(PerformInjectiveMultimap(map, &failing));
}

TEST(FileDescriptorShuffleTest, NoopWithFailure) {
  InjectiveMultimap map;
  FailingDelegate failing;
  map.push_back(InjectionArc(0, 0, false));

  EXPECT_TRUE(PerformInjectiveMultimap(map, &failing));
}

TEST(FileDescriptorShuffleTest, Simple1WithFailure) {
  InjectiveMultimap map;
  FailingDelegate failing;
  map.push_back(InjectionArc(0, 1, false));

  EXPECT_FALSE(PerformInjectiveMultimap(map, &failing));
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hf_title.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 17:56:37 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef ADC_DISPLAY_HF_TITLE_HXX
#define ADC_DISPLAY_HF_TITLE_HXX

// USED SERVICES
    // BASE CLASSES
#include <toolkit/htmlfactory.hxx>
    // COMPONENTS
    // PARAMETERS

class HF_TitleTable : public HtmlMaker
{
  public:
                        HF_TitleTable(
                            Xml::Element &      o_rOut );
    virtual             ~HF_TitleTable();

    void                Produce_Title(
                            const char *        i_title );
    /// @return a Html::TableCell reference.
    Xml::Element &      Add_Row();
};

class HF_SubTitleTable : public HtmlMaker
{
  public:
    enum E_SubLevel
    {
        sublevel_1,     /// Big title.
        sublevel_2,     /// Small title.
        sublevel_3      /// No title.
    };

    /** @param i_nColumns [1 .. n]
        @param i_nSubTitleLevel [1 .. 2]
        1 is a bit bigger than 2.
    */

                        HF_SubTitleTable(
                            Xml::Element &      o_rOut,
                            const String &      i_label,
                            const String &      i_title,
                            int                 i_nColumns,
                            E_SubLevel          i_eSubTitleLevel = sublevel_1 );
    virtual             ~HF_SubTitleTable();

    /// @return an Html::TableRow reference.
    Xml::Element &      Add_Row();
};

// IMPLEMENTATION

#endif
<commit_msg>INTEGRATION: CWS adc14 (1.3.22); FILE MERGED 2006/04/27 09:43:31 np 1.3.22.1: #i62433#, Combine See Also tags, put deprecated and unpublished into title line.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hf_title.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2006-05-03 16:57:45 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef ADC_DISPLAY_HF_TITLE_HXX
#define ADC_DISPLAY_HF_TITLE_HXX

// USED SERVICES
    // BASE CLASSES
#include <toolkit/htmlfactory.hxx>
    // COMPONENTS
    // PARAMETERS

class HF_TitleTable : public HtmlMaker
{
  public:
                        HF_TitleTable(
                            Xml::Element &      o_rOut );
    virtual             ~HF_TitleTable();

    void                Produce_Title(
                            const char *        i_title );
    void                Produce_Title(
                            const char *        i_annotations,
//                            const char *        i_label,
                            const char *        i_title );

    /// @return a Html::TableCell reference.
    Xml::Element &      Add_Row();
};

class HF_SubTitleTable : public HtmlMaker
{
  public:
    enum E_SubLevel
    {
        sublevel_1,     /// Big title.
        sublevel_2,     /// Small title.
        sublevel_3      /// No title.
    };

    /** @param i_nColumns [1 .. n]
        @param i_nSubTitleLevel [1 .. 2]
        1 is a bit bigger than 2.
    */

                        HF_SubTitleTable(
                            Xml::Element &      o_rOut,
                            const String &      i_label,
                            const String &      i_title,
                            int                 i_nColumns,
                            E_SubLevel          i_eSubTitleLevel = sublevel_1 );
    virtual             ~HF_SubTitleTable();

    /// @return an Html::TableRow reference.
    Xml::Element &      Add_Row();
};

// IMPLEMENTATION

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/ui_test_utils.h"

// This file contains tests for the ProfileManager that require a heavyweight
// InProcessBrowserTest.  These include tests involving profile deletion.

// TODO(jeremy): crbug.com/103355 - These tests should be enabled on all
// platforms.
#if defined(OS_MACOSX)
class ProfileManagerBrowserTest : public InProcessBrowserTest {
 protected:
  // An observer that returns back to test code after a new profile
  // is initialized.
  class BlockOnProfileInitObserver : public ProfileManagerObserver {
   public:
    void OnProfileCreated(Profile* profile, Status status) {
      if (status == ProfileManagerObserver::STATUS_INITIALIZED) {
        MessageLoop::current()->Quit();
      }
    }
  };
};

// Delete single profile and make sure a new one is created.
IN_PROC_BROWSER_TEST_F(ProfileManagerBrowserTest, DeleteSingletonProfile) {
  ProfileManager* profile_manager = g_browser_process->profile_manager();
  ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();

  // We should start out with 1 profile.
  ASSERT_EQ(cache.GetNumberOfProfiles(), 1U);

  // Delete singleton profile.
  FilePath singleton_profile_path = cache.GetPathOfProfileAtIndex(0);
  EXPECT_FALSE(singleton_profile_path.empty());
  profile_manager->ScheduleProfileForDeletion(singleton_profile_path);

  // Spin things till profile is actually deleted.
  ui_test_utils::RunAllPendingInMessageLoop();

  // Make sure a new profile was created automatically.
  EXPECT_EQ(cache.GetNumberOfProfiles(), 1U);
  FilePath new_profile_path = cache.GetPathOfProfileAtIndex(0);
  EXPECT_NE(new_profile_path, singleton_profile_path);

  // Make sure that last used profile preference is set correctly.
  Profile* last_used = ProfileManager::GetLastUsedProfile();
  EXPECT_EQ(new_profile_path, last_used->GetPath());
}

// Delete all profiles in a multi profile setup and make sure a new one is
// created.

#if defined(OS_MACOSX)
// See crbug.com/104851
#define MAYBE_DeleteAllProfiles FLAKY_DeleteAllProfiles
#else
#define MAYBE_DeleteAllProfiles DeleteAllProfiles
#endif

IN_PROC_BROWSER_TEST_F(ProfileManagerBrowserTest, MAYBE_DeleteAllProfiles) {
  ProfileManager* profile_manager = g_browser_process->profile_manager();
  ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();

  // Create an additional profile.
  BlockOnProfileInitObserver observer;
  FilePath new_path = profile_manager->GenerateNextProfileDirectoryPath();
  profile_manager->CreateProfileAsync(new_path, &observer);

  // Spin to allow profile creation to take place, loop is terminated
  // by BlockOnProfileInitObserver when the profile is created.
  ui_test_utils::RunMessageLoop();

  ASSERT_EQ(cache.GetNumberOfProfiles(), 2U);

  // Delete all profiles.
  FilePath profile_path1 = cache.GetPathOfProfileAtIndex(0);
  FilePath profile_path2 = cache.GetPathOfProfileAtIndex(1);
  EXPECT_FALSE(profile_path1.empty());
  EXPECT_FALSE(profile_path2.empty());
  profile_manager->ScheduleProfileForDeletion(profile_path1);
  profile_manager->ScheduleProfileForDeletion(profile_path2);

  // Spin things so deletion can take place.
  ui_test_utils::RunAllPendingInMessageLoop();

  // Make sure a new profile was created automatically.
  EXPECT_EQ(cache.GetNumberOfProfiles(), 1U);
  FilePath new_profile_path = cache.GetPathOfProfileAtIndex(0);
  EXPECT_NE(new_profile_path, profile_path1);
  EXPECT_NE(new_profile_path, profile_path2);

  // Make sure that last used profile preference is set correctly.
  Profile* last_used = ProfileManager::GetLastUsedProfile();
  EXPECT_EQ(new_profile_path, last_used->GetPath());
}
#endif // OS_MACOSX
<commit_msg>Revert 111358 - Marking ProfileManagerBrowserTest.DeleteAllProfiles as flaky on mac.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/ui_test_utils.h"

// This file contains tests for the ProfileManager that require a heavyweight
// InProcessBrowserTest.  These include tests involving profile deletion.

// TODO(jeremy): crbug.com/103355 - These tests should be enabled on all
// platforms.
#if defined(OS_MACOSX)
class ProfileManagerBrowserTest : public InProcessBrowserTest {
 protected:
  // An observer that returns back to test code after a new profile
  // is initialized.
  class BlockOnProfileInitObserver : public ProfileManagerObserver {
   public:
    void OnProfileCreated(Profile* profile, Status status) {
      if (status == ProfileManagerObserver::STATUS_INITIALIZED) {
        MessageLoop::current()->Quit();
      }
    }
  };
};

// Delete single profile and make sure a new one is created.
IN_PROC_BROWSER_TEST_F(ProfileManagerBrowserTest, DeleteSingletonProfile) {
  ProfileManager* profile_manager = g_browser_process->profile_manager();
  ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();

  // We should start out with 1 profile.
  ASSERT_EQ(cache.GetNumberOfProfiles(), 1U);

  // Delete singleton profile.
  FilePath singleton_profile_path = cache.GetPathOfProfileAtIndex(0);
  EXPECT_FALSE(singleton_profile_path.empty());
  profile_manager->ScheduleProfileForDeletion(singleton_profile_path);

  // Spin things till profile is actually deleted.
  ui_test_utils::RunAllPendingInMessageLoop();

  // Make sure a new profile was created automatically.
  EXPECT_EQ(cache.GetNumberOfProfiles(), 1U);
  FilePath new_profile_path = cache.GetPathOfProfileAtIndex(0);
  EXPECT_NE(new_profile_path, singleton_profile_path);

  // Make sure that last used profile preference is set correctly.
  Profile* last_used = ProfileManager::GetLastUsedProfile();
  EXPECT_EQ(new_profile_path, last_used->GetPath());
}

// Delete all profiles in a multi profile setup and make sure a new one is
// created.
IN_PROC_BROWSER_TEST_F(ProfileManagerBrowserTest, DeleteAllProfiles) {
  ProfileManager* profile_manager = g_browser_process->profile_manager();
  ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();

  // Create an additional profile.
  BlockOnProfileInitObserver observer;
  FilePath new_path = profile_manager->GenerateNextProfileDirectoryPath();
  profile_manager->CreateProfileAsync(new_path, &observer);

  // Spin to allow profile creation to take place, loop is terminated
  // by BlockOnProfileInitObserver when the profile is created.
  ui_test_utils::RunMessageLoop();

  ASSERT_EQ(cache.GetNumberOfProfiles(), 2U);

  // Delete all profiles.
  FilePath profile_path1 = cache.GetPathOfProfileAtIndex(0);
  FilePath profile_path2 = cache.GetPathOfProfileAtIndex(1);
  EXPECT_FALSE(profile_path1.empty());
  EXPECT_FALSE(profile_path2.empty());
  profile_manager->ScheduleProfileForDeletion(profile_path1);
  profile_manager->ScheduleProfileForDeletion(profile_path2);

  // Spin things so deletion can take place.
  ui_test_utils::RunAllPendingInMessageLoop();

  // Make sure a new profile was created automatically.
  EXPECT_EQ(cache.GetNumberOfProfiles(), 1U);
  FilePath new_profile_path = cache.GetPathOfProfileAtIndex(0);
  EXPECT_NE(new_profile_path, profile_path1);
  EXPECT_NE(new_profile_path, profile_path2);

  // Make sure that last used profile preference is set correctly.
  Profile* last_used = ProfileManager::GetLastUsedProfile();
  EXPECT_EQ(new_profile_path, last_used->GetPath());
}
#endif // OS_MACOSX
<|endoftext|>


<commit_before><commit_msg>Fix missing favicon for chrome://extensions/<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/net/connection_tester.h"

#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/threading/thread_restrictions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/importer/firefox_proxy_settings.h"
#include "chrome/common/chrome_switches.h"
#include "net/base/cert_verifier.h"
#include "net/base/cookie_monster.h"
#include "net/base/dnsrr_resolver.h"
#include "net/base/host_resolver.h"
#include "net/base/host_resolver_impl.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/base/ssl_config_service_defaults.h"
#include "net/disk_cache/disk_cache.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_network_session.h"
#include "net/proxy/proxy_config_service_fixed.h"
#include "net/proxy/proxy_script_fetcher_impl.h"
#include "net/socket/client_socket_factory.h"
#include "net/spdy/spdy_session_pool.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"

namespace {

// ExperimentURLRequestContext ------------------------------------------------

// An instance of ExperimentURLRequestContext is created for each experiment
// run by ConnectionTester. The class initializes network dependencies according
// to the specified "experiment".
class ExperimentURLRequestContext : public net::URLRequestContext {
 public:
  explicit ExperimentURLRequestContext(
      net::URLRequestContext* proxy_request_context)
      : proxy_request_context_(proxy_request_context) {}

  int Init(const ConnectionTester::Experiment& experiment) {
    int rv;

    // Create a custom HostResolver for this experiment.
    rv = CreateHostResolver(experiment.host_resolver_experiment,
                            &host_resolver_);
    if (rv != net::OK)
      return rv;  // Failure.

    // Create a custom ProxyService for this this experiment.
    rv = CreateProxyService(experiment.proxy_settings_experiment,
                            &proxy_service_);
    if (rv != net::OK)
      return rv;  // Failure.

    // The rest of the dependencies are standard, and don't depend on the
    // experiment being run.
    cert_verifier_ = new net::CertVerifier;
    dnsrr_resolver_ = new net::DnsRRResolver;
    ftp_transaction_factory_ = new net::FtpNetworkLayer(host_resolver_);
    ssl_config_service_ = new net::SSLConfigServiceDefaults;
    http_auth_handler_factory_ = net::HttpAuthHandlerFactory::CreateDefault(
        host_resolver_);
    scoped_refptr<net::HttpNetworkSession> network_session(
        new net::HttpNetworkSession(
            host_resolver_,
            cert_verifier_,
            dnsrr_resolver_,
            NULL /* dns_cert_checker */,
            NULL /* ssl_host_info_factory */,
            proxy_service_,
            net::ClientSocketFactory::GetDefaultFactory(),
            ssl_config_service_,
            new net::SpdySessionPool(NULL),
            http_auth_handler_factory_,
            NULL /* network_delegate */,
            NULL /* net_log */));
    http_transaction_factory_ = new net::HttpCache(
        network_session,
        net::HttpCache::DefaultBackend::InMemory(0));
    // In-memory cookie store.
    cookie_store_ = new net::CookieMonster(NULL, NULL);

    return net::OK;
  }

 protected:
  virtual ~ExperimentURLRequestContext() {
    delete ftp_transaction_factory_;
    delete http_transaction_factory_;
    delete http_auth_handler_factory_;
    delete dnsrr_resolver_;
    delete cert_verifier_;
    delete host_resolver_;
  }

 private:
  // Creates a host resolver for |experiment|. On success returns net::OK and
  // fills |host_resolver| with a new pointer. Otherwise returns a network
  // error code.
  int CreateHostResolver(
      ConnectionTester::HostResolverExperiment experiment,
      net::HostResolver** host_resolver) {
    // Create a vanilla HostResolver that disables caching.
    const size_t kMaxJobs = 50u;
    net::HostResolverImpl* impl =
        new net::HostResolverImpl(NULL, NULL, kMaxJobs, NULL);

    *host_resolver = impl;

    // Modify it slightly based on the experiment being run.
    switch (experiment) {
      case ConnectionTester::HOST_RESOLVER_EXPERIMENT_PLAIN:
        return net::OK;
      case ConnectionTester::HOST_RESOLVER_EXPERIMENT_DISABLE_IPV6:
        impl->SetDefaultAddressFamily(net::ADDRESS_FAMILY_IPV4);
        return net::OK;
      case ConnectionTester::HOST_RESOLVER_EXPERIMENT_IPV6_PROBE: {
        // Note that we don't use impl->ProbeIPv6Support() since that finishes
        // asynchronously and may not take effect in time for the test.
        // So instead we will probe synchronously (might take 100-200 ms).
        net::AddressFamily family = net::IPv6Supported() ?
            net::ADDRESS_FAMILY_UNSPECIFIED : net::ADDRESS_FAMILY_IPV4;
        impl->SetDefaultAddressFamily(family);
        return net::OK;
      }
      default:
        NOTREACHED();
        return net::ERR_UNEXPECTED;
    }
  }

  // Creates a proxy config service for |experiment|. On success returns net::OK
  // and fills |config_service| with a new pointer. Otherwise returns a network
  // error code.
  int CreateProxyConfigService(
      ConnectionTester::ProxySettingsExperiment experiment,
      scoped_ptr<net::ProxyConfigService>* config_service) {
    scoped_ptr<base::ThreadRestrictions::ScopedAllowIO> allow_io;
    switch (experiment) {
      case ConnectionTester::PROXY_EXPERIMENT_USE_SYSTEM_SETTINGS:
        return CreateSystemProxyConfigService(config_service);
      case ConnectionTester::PROXY_EXPERIMENT_USE_FIREFOX_SETTINGS:
        // http://crbug.com/67664: This call can lead to blocking IO on the IO
        // thread.  This is a bug and should be fixed.
        allow_io.reset(new base::ThreadRestrictions::ScopedAllowIO);
        return CreateFirefoxProxyConfigService(config_service);
      case ConnectionTester::PROXY_EXPERIMENT_USE_AUTO_DETECT:
        config_service->reset(new net::ProxyConfigServiceFixed(
            net::ProxyConfig::CreateAutoDetect()));
        return net::OK;
      case ConnectionTester::PROXY_EXPERIMENT_USE_DIRECT:
        config_service->reset(new net::ProxyConfigServiceFixed(
            net::ProxyConfig::CreateDirect()));
        return net::OK;
      default:
        NOTREACHED();
        return net::ERR_UNEXPECTED;
    }
  }

  // Creates a proxy service for |experiment|. On success returns net::OK
  // and fills |config_service| with a new pointer. Otherwise returns a network
  // error code.
  int CreateProxyService(
      ConnectionTester::ProxySettingsExperiment experiment,
      scoped_refptr<net::ProxyService>* proxy_service) {
    // Create an appropriate proxy config service.
    scoped_ptr<net::ProxyConfigService> config_service;
    int rv = CreateProxyConfigService(experiment, &config_service);
    if (rv != net::OK)
      return rv;  // Failure.

    if (CommandLine::ForCurrentProcess()->HasSwitch(
        switches::kSingleProcess)) {
      // We can't create a standard proxy resolver in single-process mode.
      // Rather than falling-back to some other implementation, fail.
      return net::ERR_NOT_IMPLEMENTED;
    }

    *proxy_service = net::ProxyService::CreateUsingV8ProxyResolver(
        config_service.release(),
        0u,
        new net::ProxyScriptFetcherImpl(proxy_request_context_),
        host_resolver(),
        NULL);

    return net::OK;
  }

  // Creates a proxy config service that pulls from the system proxy settings.
  // On success returns net::OK and fills |config_service| with a new pointer.
  // Otherwise returns a network error code.
  int CreateSystemProxyConfigService(
      scoped_ptr<net::ProxyConfigService>* config_service) {
#if defined(OS_LINUX)
    // TODO(eroman): This is not supported on Linux yet, because of how
    // construction needs ot happen on the UI thread.
    return net::ERR_NOT_IMPLEMENTED;
#else
    config_service->reset(
        net::ProxyService::CreateSystemProxyConfigService(
            MessageLoop::current(), NULL));
    return net::OK;
#endif
  }

  // Creates a fixed proxy config service that is initialized using Firefox's
  // current proxy settings. On success returns net::OK and fills
  // |config_service| with a new pointer. Otherwise returns a network error
  // code.
  int CreateFirefoxProxyConfigService(
      scoped_ptr<net::ProxyConfigService>* config_service) {
    // Fetch Firefox's proxy settings (can fail if Firefox is not installed).
    FirefoxProxySettings firefox_settings;
    if (!FirefoxProxySettings::GetSettings(&firefox_settings))
      return net::ERR_FILE_NOT_FOUND;

    if (FirefoxProxySettings::SYSTEM == firefox_settings.config_type())
      return CreateSystemProxyConfigService(config_service);

    net::ProxyConfig config;
    if (firefox_settings.ToProxyConfig(&config)) {
      config_service->reset(new net::ProxyConfigServiceFixed(config));
      return net::OK;
    }

    return net::ERR_FAILED;
  }

  const scoped_refptr<net::URLRequestContext> proxy_request_context_;
};

}  // namespace

// ConnectionTester::TestRunner ----------------------------------------------

// TestRunner is a helper class for running an individual experiment. It can
// be deleted any time after it is started, and this will abort the request.
class ConnectionTester::TestRunner : public net::URLRequest::Delegate {
 public:
  // |tester| must remain alive throughout the TestRunner's lifetime.
  // |tester| will be notified of completion.
  explicit TestRunner(ConnectionTester* tester) : tester_(tester) {}

  // Starts running |experiment|. Notifies tester->OnExperimentCompleted() when
  // it is done.
  void Run(const Experiment& experiment);

  // Overridden from net::URLRequest::Delegate:
  virtual void OnResponseStarted(net::URLRequest* request);
  virtual void OnReadCompleted(net::URLRequest* request, int bytes_read);
  // TODO(eroman): handle cases requiring authentication.

 private:
  // The number of bytes to read each response body chunk.
  static const int kReadBufferSize = 1024;

  // Starts reading the response's body (and keeps reading until an error or
  // end of stream).
  void ReadBody(net::URLRequest* request);

  // Called when the request has completed (for both success and failure).
  void OnResponseCompleted(net::URLRequest* request);

  ConnectionTester* tester_;
  scoped_ptr<net::URLRequest> request_;

  DISALLOW_COPY_AND_ASSIGN(TestRunner);
};

void ConnectionTester::TestRunner::OnResponseStarted(net::URLRequest* request) {
  if (!request->status().is_success()) {
    OnResponseCompleted(request);
    return;
  }

  // Start reading the body.
  ReadBody(request);
}

void ConnectionTester::TestRunner::OnReadCompleted(net::URLRequest* request,
                                                   int bytes_read) {
  if (bytes_read <= 0) {
    OnResponseCompleted(request);
    return;
  }

  // Keep reading until the stream is closed. Throw the data read away.
  ReadBody(request);
}

void ConnectionTester::TestRunner::ReadBody(net::URLRequest* request) {
  // Read the response body |kReadBufferSize| bytes at a time.
  scoped_refptr<net::IOBuffer> unused_buffer(
      new net::IOBuffer(kReadBufferSize));
  int num_bytes;
  if (request->Read(unused_buffer, kReadBufferSize, &num_bytes)) {
    OnReadCompleted(request, num_bytes);
  } else if (!request->status().is_io_pending()) {
    // Read failed synchronously.
    OnResponseCompleted(request);
  }
}

void ConnectionTester::TestRunner::OnResponseCompleted(
    net::URLRequest* request) {
  int result = net::OK;
  if (!request->status().is_success()) {
    DCHECK_NE(net::ERR_IO_PENDING, request->status().os_error());
    result = request->status().os_error();
  }
  tester_->OnExperimentCompleted(result);
}

void ConnectionTester::TestRunner::Run(const Experiment& experiment) {
  // Try to create a net::URLRequestContext for this experiment.
  scoped_refptr<ExperimentURLRequestContext> context(
      new ExperimentURLRequestContext(tester_->proxy_request_context_));
  int rv = context->Init(experiment);
  if (rv != net::OK) {
    // Complete the experiment with a failure.
    tester_->OnExperimentCompleted(rv);
    return;
  }

  // Fetch a request using the experimental context.
  request_.reset(new net::URLRequest(experiment.url, this));
  request_->set_context(context);
  request_->Start();
}

// ConnectionTester ----------------------------------------------------------

ConnectionTester::ConnectionTester(
    Delegate* delegate,
    net::URLRequestContext* proxy_request_context)
    : delegate_(delegate), proxy_request_context_(proxy_request_context) {
  DCHECK(delegate);
  DCHECK(proxy_request_context);
}

ConnectionTester::~ConnectionTester() {
  // Cancellation happens automatically by deleting test_runner_.
}

void ConnectionTester::RunAllTests(const GURL& url) {
  // Select all possible experiments to run. (In no particular order).
  // It is possible that some of these experiments are actually duplicates.
  GetAllPossibleExperimentCombinations(url, &remaining_experiments_);

  delegate_->OnStartConnectionTestSuite();
  StartNextExperiment();
}

// static
string16 ConnectionTester::ProxySettingsExperimentDescription(
    ProxySettingsExperiment experiment) {
  // TODO(eroman): Use proper string resources.
  switch (experiment) {
    case PROXY_EXPERIMENT_USE_DIRECT:
      return ASCIIToUTF16("Don't use any proxy");
    case PROXY_EXPERIMENT_USE_SYSTEM_SETTINGS:
      return ASCIIToUTF16("Use system proxy settings");
    case PROXY_EXPERIMENT_USE_FIREFOX_SETTINGS:
      return ASCIIToUTF16("Use Firefox's proxy settings");
    case PROXY_EXPERIMENT_USE_AUTO_DETECT:
      return ASCIIToUTF16("Auto-detect proxy settings");
    default:
      NOTREACHED();
      return string16();
  }
}

// static
string16 ConnectionTester::HostResolverExperimentDescription(
    HostResolverExperiment experiment) {
  // TODO(eroman): Use proper string resources.
  switch (experiment) {
    case HOST_RESOLVER_EXPERIMENT_PLAIN:
      return string16();
    case HOST_RESOLVER_EXPERIMENT_DISABLE_IPV6:
      return ASCIIToUTF16("Disable IPv6 host resolving");
    case HOST_RESOLVER_EXPERIMENT_IPV6_PROBE:
      return ASCIIToUTF16("Probe for IPv6 host resolving");
    default:
      NOTREACHED();
      return string16();
  }
}

// static
void ConnectionTester::GetAllPossibleExperimentCombinations(
    const GURL& url,
    ConnectionTester::ExperimentList* list) {
  list->clear();
  for (size_t resolver_experiment = 0;
       resolver_experiment < HOST_RESOLVER_EXPERIMENT_COUNT;
       ++resolver_experiment) {
    for (size_t proxy_experiment = 0;
         proxy_experiment < PROXY_EXPERIMENT_COUNT;
         ++proxy_experiment) {
      Experiment experiment(
          url,
          static_cast<ProxySettingsExperiment>(proxy_experiment),
          static_cast<HostResolverExperiment>(resolver_experiment));
      list->push_back(experiment);
    }
  }
}

void ConnectionTester::StartNextExperiment() {
  DCHECK(!remaining_experiments_.empty());
  DCHECK(!current_test_runner_.get());

  delegate_->OnStartConnectionTestExperiment(current_experiment());

  current_test_runner_.reset(new TestRunner(this));
  current_test_runner_->Run(current_experiment());
}

void ConnectionTester::OnExperimentCompleted(int result) {
  Experiment current = current_experiment();

  // Advance to the next experiment.
  remaining_experiments_.erase(remaining_experiments_.begin());
  current_test_runner_.reset();

  // Notify the delegate of completion.
  delegate_->OnCompletedConnectionTestExperiment(current, result);

  if (remaining_experiments_.empty()) {
    delegate_->OnCompletedConnectionTestSuite();
  } else {
    StartNextExperiment();
  }
}
<commit_msg>Don't delete the URLRequest within the completion callback, in the ConnectionTester, as that was leading to a wonky teardown.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/net/connection_tester.h"

#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/task.h"
#include "base/threading/thread_restrictions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/importer/firefox_proxy_settings.h"
#include "chrome/common/chrome_switches.h"
#include "net/base/cert_verifier.h"
#include "net/base/cookie_monster.h"
#include "net/base/dnsrr_resolver.h"
#include "net/base/host_resolver.h"
#include "net/base/host_resolver_impl.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/base/ssl_config_service_defaults.h"
#include "net/disk_cache/disk_cache.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_network_session.h"
#include "net/proxy/proxy_config_service_fixed.h"
#include "net/proxy/proxy_script_fetcher_impl.h"
#include "net/socket/client_socket_factory.h"
#include "net/spdy/spdy_session_pool.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"

namespace {

// ExperimentURLRequestContext ------------------------------------------------

// An instance of ExperimentURLRequestContext is created for each experiment
// run by ConnectionTester. The class initializes network dependencies according
// to the specified "experiment".
class ExperimentURLRequestContext : public net::URLRequestContext {
 public:
  explicit ExperimentURLRequestContext(
      net::URLRequestContext* proxy_request_context)
      : proxy_request_context_(proxy_request_context) {}

  int Init(const ConnectionTester::Experiment& experiment) {
    int rv;

    // Create a custom HostResolver for this experiment.
    rv = CreateHostResolver(experiment.host_resolver_experiment,
                            &host_resolver_);
    if (rv != net::OK)
      return rv;  // Failure.

    // Create a custom ProxyService for this this experiment.
    rv = CreateProxyService(experiment.proxy_settings_experiment,
                            &proxy_service_);
    if (rv != net::OK)
      return rv;  // Failure.

    // The rest of the dependencies are standard, and don't depend on the
    // experiment being run.
    cert_verifier_ = new net::CertVerifier;
    dnsrr_resolver_ = new net::DnsRRResolver;
    ftp_transaction_factory_ = new net::FtpNetworkLayer(host_resolver_);
    ssl_config_service_ = new net::SSLConfigServiceDefaults;
    http_auth_handler_factory_ = net::HttpAuthHandlerFactory::CreateDefault(
        host_resolver_);
    scoped_refptr<net::HttpNetworkSession> network_session(
        new net::HttpNetworkSession(
            host_resolver_,
            cert_verifier_,
            dnsrr_resolver_,
            NULL /* dns_cert_checker */,
            NULL /* ssl_host_info_factory */,
            proxy_service_,
            net::ClientSocketFactory::GetDefaultFactory(),
            ssl_config_service_,
            new net::SpdySessionPool(NULL),
            http_auth_handler_factory_,
            NULL /* network_delegate */,
            NULL /* net_log */));
    http_transaction_factory_ = new net::HttpCache(
        network_session,
        net::HttpCache::DefaultBackend::InMemory(0));
    // In-memory cookie store.
    cookie_store_ = new net::CookieMonster(NULL, NULL);

    return net::OK;
  }

 protected:
  virtual ~ExperimentURLRequestContext() {
    delete ftp_transaction_factory_;
    delete http_transaction_factory_;
    delete http_auth_handler_factory_;
    delete dnsrr_resolver_;
    delete cert_verifier_;
    delete host_resolver_;
  }

 private:
  // Creates a host resolver for |experiment|. On success returns net::OK and
  // fills |host_resolver| with a new pointer. Otherwise returns a network
  // error code.
  int CreateHostResolver(
      ConnectionTester::HostResolverExperiment experiment,
      net::HostResolver** host_resolver) {
    // Create a vanilla HostResolver that disables caching.
    const size_t kMaxJobs = 50u;
    net::HostResolverImpl* impl =
        new net::HostResolverImpl(NULL, NULL, kMaxJobs, NULL);

    *host_resolver = impl;

    // Modify it slightly based on the experiment being run.
    switch (experiment) {
      case ConnectionTester::HOST_RESOLVER_EXPERIMENT_PLAIN:
        return net::OK;
      case ConnectionTester::HOST_RESOLVER_EXPERIMENT_DISABLE_IPV6:
        impl->SetDefaultAddressFamily(net::ADDRESS_FAMILY_IPV4);
        return net::OK;
      case ConnectionTester::HOST_RESOLVER_EXPERIMENT_IPV6_PROBE: {
        // Note that we don't use impl->ProbeIPv6Support() since that finishes
        // asynchronously and may not take effect in time for the test.
        // So instead we will probe synchronously (might take 100-200 ms).
        net::AddressFamily family = net::IPv6Supported() ?
            net::ADDRESS_FAMILY_UNSPECIFIED : net::ADDRESS_FAMILY_IPV4;
        impl->SetDefaultAddressFamily(family);
        return net::OK;
      }
      default:
        NOTREACHED();
        return net::ERR_UNEXPECTED;
    }
  }

  // Creates a proxy config service for |experiment|. On success returns net::OK
  // and fills |config_service| with a new pointer. Otherwise returns a network
  // error code.
  int CreateProxyConfigService(
      ConnectionTester::ProxySettingsExperiment experiment,
      scoped_ptr<net::ProxyConfigService>* config_service) {
    scoped_ptr<base::ThreadRestrictions::ScopedAllowIO> allow_io;
    switch (experiment) {
      case ConnectionTester::PROXY_EXPERIMENT_USE_SYSTEM_SETTINGS:
        return CreateSystemProxyConfigService(config_service);
      case ConnectionTester::PROXY_EXPERIMENT_USE_FIREFOX_SETTINGS:
        // http://crbug.com/67664: This call can lead to blocking IO on the IO
        // thread.  This is a bug and should be fixed.
        allow_io.reset(new base::ThreadRestrictions::ScopedAllowIO);
        return CreateFirefoxProxyConfigService(config_service);
      case ConnectionTester::PROXY_EXPERIMENT_USE_AUTO_DETECT:
        config_service->reset(new net::ProxyConfigServiceFixed(
            net::ProxyConfig::CreateAutoDetect()));
        return net::OK;
      case ConnectionTester::PROXY_EXPERIMENT_USE_DIRECT:
        config_service->reset(new net::ProxyConfigServiceFixed(
            net::ProxyConfig::CreateDirect()));
        return net::OK;
      default:
        NOTREACHED();
        return net::ERR_UNEXPECTED;
    }
  }

  // Creates a proxy service for |experiment|. On success returns net::OK
  // and fills |config_service| with a new pointer. Otherwise returns a network
  // error code.
  int CreateProxyService(
      ConnectionTester::ProxySettingsExperiment experiment,
      scoped_refptr<net::ProxyService>* proxy_service) {
    // Create an appropriate proxy config service.
    scoped_ptr<net::ProxyConfigService> config_service;
    int rv = CreateProxyConfigService(experiment, &config_service);
    if (rv != net::OK)
      return rv;  // Failure.

    if (CommandLine::ForCurrentProcess()->HasSwitch(
        switches::kSingleProcess)) {
      // We can't create a standard proxy resolver in single-process mode.
      // Rather than falling-back to some other implementation, fail.
      return net::ERR_NOT_IMPLEMENTED;
    }

    *proxy_service = net::ProxyService::CreateUsingV8ProxyResolver(
        config_service.release(),
        0u,
        new net::ProxyScriptFetcherImpl(proxy_request_context_),
        host_resolver(),
        NULL);

    return net::OK;
  }

  // Creates a proxy config service that pulls from the system proxy settings.
  // On success returns net::OK and fills |config_service| with a new pointer.
  // Otherwise returns a network error code.
  int CreateSystemProxyConfigService(
      scoped_ptr<net::ProxyConfigService>* config_service) {
#if defined(OS_LINUX)
    // TODO(eroman): This is not supported on Linux yet, because of how
    // construction needs ot happen on the UI thread.
    return net::ERR_NOT_IMPLEMENTED;
#else
    config_service->reset(
        net::ProxyService::CreateSystemProxyConfigService(
            MessageLoop::current(), NULL));
    return net::OK;
#endif
  }

  // Creates a fixed proxy config service that is initialized using Firefox's
  // current proxy settings. On success returns net::OK and fills
  // |config_service| with a new pointer. Otherwise returns a network error
  // code.
  int CreateFirefoxProxyConfigService(
      scoped_ptr<net::ProxyConfigService>* config_service) {
    // Fetch Firefox's proxy settings (can fail if Firefox is not installed).
    FirefoxProxySettings firefox_settings;
    if (!FirefoxProxySettings::GetSettings(&firefox_settings))
      return net::ERR_FILE_NOT_FOUND;

    if (FirefoxProxySettings::SYSTEM == firefox_settings.config_type())
      return CreateSystemProxyConfigService(config_service);

    net::ProxyConfig config;
    if (firefox_settings.ToProxyConfig(&config)) {
      config_service->reset(new net::ProxyConfigServiceFixed(config));
      return net::OK;
    }

    return net::ERR_FAILED;
  }

  const scoped_refptr<net::URLRequestContext> proxy_request_context_;
};

}  // namespace

// ConnectionTester::TestRunner ----------------------------------------------

// TestRunner is a helper class for running an individual experiment. It can
// be deleted any time after it is started, and this will abort the request.
class ConnectionTester::TestRunner : public net::URLRequest::Delegate {
 public:
  // |tester| must remain alive throughout the TestRunner's lifetime.
  // |tester| will be notified of completion.
  explicit TestRunner(ConnectionTester* tester)
      : tester_(tester),
        ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {}

  // Starts running |experiment|. Notifies tester->OnExperimentCompleted() when
  // it is done.
  void Run(const Experiment& experiment);

  // Overridden from net::URLRequest::Delegate:
  virtual void OnResponseStarted(net::URLRequest* request);
  virtual void OnReadCompleted(net::URLRequest* request, int bytes_read);
  // TODO(eroman): handle cases requiring authentication.

 private:
  // The number of bytes to read each response body chunk.
  static const int kReadBufferSize = 1024;

  // Starts reading the response's body (and keeps reading until an error or
  // end of stream).
  void ReadBody(net::URLRequest* request);

  // Called when the request has completed (for both success and failure).
  void OnResponseCompleted(net::URLRequest* request);
  void OnExperimentCompletedWithResult(int result);

  ConnectionTester* tester_;
  scoped_ptr<net::URLRequest> request_;

  ScopedRunnableMethodFactory<TestRunner> method_factory_;

  DISALLOW_COPY_AND_ASSIGN(TestRunner);
};

void ConnectionTester::TestRunner::OnResponseStarted(net::URLRequest* request) {
  if (!request->status().is_success()) {
    OnResponseCompleted(request);
    return;
  }

  // Start reading the body.
  ReadBody(request);
}

void ConnectionTester::TestRunner::OnReadCompleted(net::URLRequest* request,
                                                   int bytes_read) {
  if (bytes_read <= 0) {
    OnResponseCompleted(request);
    return;
  }

  // Keep reading until the stream is closed. Throw the data read away.
  ReadBody(request);
}

void ConnectionTester::TestRunner::ReadBody(net::URLRequest* request) {
  // Read the response body |kReadBufferSize| bytes at a time.
  scoped_refptr<net::IOBuffer> unused_buffer(
      new net::IOBuffer(kReadBufferSize));
  int num_bytes;
  if (request->Read(unused_buffer, kReadBufferSize, &num_bytes)) {
    OnReadCompleted(request, num_bytes);
  } else if (!request->status().is_io_pending()) {
    // Read failed synchronously.
    OnResponseCompleted(request);
  }
}

void ConnectionTester::TestRunner::OnResponseCompleted(
    net::URLRequest* request) {
  int result = net::OK;
  if (!request->status().is_success()) {
    DCHECK_NE(net::ERR_IO_PENDING, request->status().os_error());
    result = request->status().os_error();
  }

  // Post a task to notify the parent rather than handling it right away,
  // to avoid re-entrancy problems with URLRequest. (Don't want the caller
  // to end up deleting the URLRequest while in the middle of processing).
  MessageLoop::current()->PostTask(
      FROM_HERE,
      method_factory_.NewRunnableMethod(
          &TestRunner::OnExperimentCompletedWithResult, result));
}

void ConnectionTester::TestRunner::OnExperimentCompletedWithResult(int result) {
  tester_->OnExperimentCompleted(result);
}

void ConnectionTester::TestRunner::Run(const Experiment& experiment) {
  // Try to create a net::URLRequestContext for this experiment.
  scoped_refptr<ExperimentURLRequestContext> context(
      new ExperimentURLRequestContext(tester_->proxy_request_context_));
  int rv = context->Init(experiment);
  if (rv != net::OK) {
    // Complete the experiment with a failure.
    tester_->OnExperimentCompleted(rv);
    return;
  }

  // Fetch a request using the experimental context.
  request_.reset(new net::URLRequest(experiment.url, this));
  request_->set_context(context);
  request_->Start();
}

// ConnectionTester ----------------------------------------------------------

ConnectionTester::ConnectionTester(
    Delegate* delegate,
    net::URLRequestContext* proxy_request_context)
    : delegate_(delegate), proxy_request_context_(proxy_request_context) {
  DCHECK(delegate);
  DCHECK(proxy_request_context);
}

ConnectionTester::~ConnectionTester() {
  // Cancellation happens automatically by deleting test_runner_.
}

void ConnectionTester::RunAllTests(const GURL& url) {
  // Select all possible experiments to run. (In no particular order).
  // It is possible that some of these experiments are actually duplicates.
  GetAllPossibleExperimentCombinations(url, &remaining_experiments_);

  delegate_->OnStartConnectionTestSuite();
  StartNextExperiment();
}

// static
string16 ConnectionTester::ProxySettingsExperimentDescription(
    ProxySettingsExperiment experiment) {
  // TODO(eroman): Use proper string resources.
  switch (experiment) {
    case PROXY_EXPERIMENT_USE_DIRECT:
      return ASCIIToUTF16("Don't use any proxy");
    case PROXY_EXPERIMENT_USE_SYSTEM_SETTINGS:
      return ASCIIToUTF16("Use system proxy settings");
    case PROXY_EXPERIMENT_USE_FIREFOX_SETTINGS:
      return ASCIIToUTF16("Use Firefox's proxy settings");
    case PROXY_EXPERIMENT_USE_AUTO_DETECT:
      return ASCIIToUTF16("Auto-detect proxy settings");
    default:
      NOTREACHED();
      return string16();
  }
}

// static
string16 ConnectionTester::HostResolverExperimentDescription(
    HostResolverExperiment experiment) {
  // TODO(eroman): Use proper string resources.
  switch (experiment) {
    case HOST_RESOLVER_EXPERIMENT_PLAIN:
      return string16();
    case HOST_RESOLVER_EXPERIMENT_DISABLE_IPV6:
      return ASCIIToUTF16("Disable IPv6 host resolving");
    case HOST_RESOLVER_EXPERIMENT_IPV6_PROBE:
      return ASCIIToUTF16("Probe for IPv6 host resolving");
    default:
      NOTREACHED();
      return string16();
  }
}

// static
void ConnectionTester::GetAllPossibleExperimentCombinations(
    const GURL& url,
    ConnectionTester::ExperimentList* list) {
  list->clear();
  for (size_t resolver_experiment = 0;
       resolver_experiment < HOST_RESOLVER_EXPERIMENT_COUNT;
       ++resolver_experiment) {
    for (size_t proxy_experiment = 0;
         proxy_experiment < PROXY_EXPERIMENT_COUNT;
         ++proxy_experiment) {
      Experiment experiment(
          url,
          static_cast<ProxySettingsExperiment>(proxy_experiment),
          static_cast<HostResolverExperiment>(resolver_experiment));
      list->push_back(experiment);
    }
  }
}

void ConnectionTester::StartNextExperiment() {
  DCHECK(!remaining_experiments_.empty());
  DCHECK(!current_test_runner_.get());

  delegate_->OnStartConnectionTestExperiment(current_experiment());

  current_test_runner_.reset(new TestRunner(this));
  current_test_runner_->Run(current_experiment());
}

void ConnectionTester::OnExperimentCompleted(int result) {
  Experiment current = current_experiment();

  // Advance to the next experiment.
  remaining_experiments_.erase(remaining_experiments_.begin());
  current_test_runner_.reset();

  // Notify the delegate of completion.
  delegate_->OnCompletedConnectionTestExperiment(current, result);

  if (remaining_experiments_.empty()) {
    delegate_->OnCompletedConnectionTestSuite();
  } else {
    StartNextExperiment();
  }
}
<|endoftext|>


<commit_before>#include "common.h"
#include "Integrator.h"
#include "IntegrableProperty.h"
#include "EventManager.h"

void Integrator::Update(DeltaTicks &dt) {
	accumulator += dt;
	if(accumulator.Seconds() > 1.0f) { accumulator.SetSeconds(1.0f); }
	alphaMicroseconds = static_cast<uint32_t>(accumulator.Seconds() * 1000000.0f);

	while(accumulator >= timestep) {
		Tick(timestep.Seconds());
		accumulator -= timestep;
	}
}

void Integrator::Tick(DeltaTicks::seconds_type seconds) {
	for(auto it = engine->objects.left.begin(); it != engine->objects.left.end(); ++it) {
		auto property = it->info->Get<IntegrableProperty>().lock();
		if(property) {
			for(auto integrable : *property->GetIntegrables()) {
				integrable->Integrate(seconds);
			}
		}
	}
	engine->GetSystem<EventManager>().lock()->FireIn("integrator", "ticked", seconds);
}
<commit_msg>Set integrator microseconds value at end of tick<commit_after>#include "common.h"
#include "Integrator.h"
#include "IntegrableProperty.h"
#include "EventManager.h"

void Integrator::Update(DeltaTicks &dt) {
	accumulator += dt;
	if(accumulator.Seconds() > 1.0f) { accumulator.SetSeconds(1.0f); }

	while(accumulator >= timestep) {
		Tick(timestep.Seconds());
		accumulator -= timestep;
	}

	alphaMicroseconds = static_cast<uint32_t>(accumulator.Seconds() * 1000000.0f);
}

void Integrator::Tick(DeltaTicks::seconds_type seconds) {
	for(auto it = engine->objects.left.begin(); it != engine->objects.left.end(); ++it) {
		auto property = it->info->Get<IntegrableProperty>().lock();
		if(property) {
			for(auto integrable : *property->GetIntegrables()) {
				integrable->Integrate(seconds);
			}
		}
	}
	engine->GetSystem<EventManager>().lock()->FireIn("integrator", "ticked", seconds);
}
<|endoftext|>


<commit_before>//
// Name:     app.cpp
// Purpose:  The application class the CManager application.
//
// Copyright (c) 2001-2003 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
#pragma implementation
#pragma interface
#endif

// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "vtlib/vtlib.h"
#include "vtlib/core/NavEngines.h"
#include "vtlib/core/vtSOG.h"
#include "vtdata/vtLog.h"

#include "app.h"
#include "frame.h"

// #include <osgDB/ReadFile>

static void Args(int argc, wxChar **argv)
{
   return;
}

IMPLEMENT_APP(vtApp)

class LogCatcher : public wxLog
{
    void DoLogString(const wxChar *szString, time_t t)
	{
		VTLOG(" wxLog: ");
		VTLOG(szString);
		VTLOG("\n");
	}
};

//
// Initialize the app object
//
bool vtApp::OnInit(void)
{
	// Redirect the wxWindows log messages to our own logging stream
	wxLog *logger = new LogCatcher();
	wxLog::SetActiveTarget(logger);

	Args(argc, argv);

	g_Log._StartLog("debug.txt");
	VTLOG("CManager\n");

	//
	// Create the main frame window
	//
	VTLOG("Creating frame\n");
	wxString title = _T("Content Manager");
	vtFrame *frame = new vtFrame(NULL, title,
		wxPoint(50, 50), wxSize(800, 600));

	VTLOG("Setup scene\n");
	vtScene *pScene = vtGetScene();
	pScene->Init();
	pScene->SetBgColor(RGBf(0.5f, 0.5f, 0.5f));

	VTLOG(" creating camera\n");
	vtCamera *pCamera = pScene->GetCamera();
	pCamera->SetName2("Default Camera");

	m_pRoot = new vtGroup();
	m_pRoot->SetName2("Root");
	pScene->SetRoot(m_pRoot);

#if VTLIB_SGL
	CreateTestSGLScene();
#endif

	// make a simple directional light
	VTLOG(" creating light\n");
	vtLight *pLight = new vtLight();
	pLight->SetName2("Light");
	vtMovLight *pMovLight = new vtMovLight(pLight);
	pMovLight->SetName2("Movable Light");
	pLight->SetAmbient(RGBf(1, 1, 1));
	pMovLight->SetTrans(FPoint3(0.0f, 0.0f, 5.0f));
	m_pRoot->AddChild(pMovLight);

	// SOG testing, currently disabled
#if 0
#if 0
	// make a yellow sphere
	vtMaterialArray *pMats = new vtMaterialArray();
	pMats->AddRGBMaterial(RGBf(1.0f, 1.0f, 0.0f), RGBf(0.0f, 0.0f, 1.0f));
	vtGeom *pGeom = CreateSphereGeom(pMats, 0, VT_Normals, 0.5, 16);
	pGeom->SetName2("Yellow Sphere");
	pMats->Release();

	OutputSOG osog;

	FILE *fp = fopen("output.sog", "wb");
	osog.WriteHeader(fp);
	osog.WriteSingleGeometry(fp, pGeom);
	fclose(fp);
	m_pRoot->AddChild(pGeom);
#else
	InputSOG isog;

	FILE *fp = fopen("output.sog", "rb");
	vtGroup *pGroup = new vtGroup;
	bool success = isog.ReadContents(fp, pGroup);
	fclose(fp);
	m_pRoot->AddChild(pGroup);
#endif
#endif

	// make a trackball controller for the camera
	VTLOG(" creating trackball\n");
	m_pTrackball = new vtTrackball(3.0f);
	m_pTrackball->SetTarget(pScene->GetCamera());
	m_pTrackball->SetName2("Trackball");
	m_pTrackball->SetRotateButton(VT_LEFT, 0);
	m_pTrackball->SetZoomButton(VT_LEFT|VT_RIGHT, 0);
	m_pTrackball->SetZoomScale(3000.0f);
	m_pTrackball->SetTranslateButton(VT_RIGHT, 0);
	pScene->AddEngine(m_pTrackball);

	// Memleak Testing
//	GetMainFrame()->AddModelFromFile("E:/3D/Sample FLT files/spitfire.flt");
//	vtNode *pNode = vtNode::LoadModel("E:/3D/Sample FLT files/spitfire.flt");
//	if (pNode)
//		m_pRoot->AddChild(pNode);
//	GetMainFrame()->AddNewItem();

//	osg::ref_ptr<osg::Node> node = osgDB::readNodeFile("E:/3D/Sample FLT files/spitfire.flt");
//	node = NULL;

	VTLOG(" end of OnInit\n");
	return TRUE;
}

int vtApp::OnExit(void)
{
	VTLOG("App OnExit\n");

	vtCamera *pCamera = vtGetScene()->GetCamera();
	pCamera->Release();

	m_pRoot->Release();
	return 0;
}

<commit_msg>improved shutdown<commit_after>//
// Name:     app.cpp
// Purpose:  The application class the CManager application.
//
// Copyright (c) 2001-2003 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#ifdef __GNUG__
#pragma implementation
#pragma interface
#endif

// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "vtlib/vtlib.h"
#include "vtlib/core/NavEngines.h"
#include "vtlib/core/vtSOG.h"
#include "vtdata/vtLog.h"

#include "app.h"
#include "frame.h"

// #include <osgDB/ReadFile>

static void Args(int argc, wxChar **argv)
{
   return;
}

IMPLEMENT_APP(vtApp)

class LogCatcher : public wxLog
{
    void DoLogString(const wxChar *szString, time_t t)
	{
		VTLOG(" wxLog: ");
		VTLOG(szString);
		VTLOG("\n");
	}
};

//
// Initialize the app object
//
bool vtApp::OnInit(void)
{
	// Redirect the wxWindows log messages to our own logging stream
	wxLog *logger = new LogCatcher();
	wxLog::SetActiveTarget(logger);

	Args(argc, argv);

	g_Log._StartLog("debug.txt");
	VTLOG("CManager\n");

	//
	// Create the main frame window
	//
	VTLOG("Creating frame\n");
	wxString title = _T("Content Manager");
	vtFrame *frame = new vtFrame(NULL, title,
		wxPoint(50, 50), wxSize(800, 600));

	VTLOG("Setup scene\n");
	vtScene *pScene = vtGetScene();
	pScene->Init();
	pScene->SetBgColor(RGBf(0.5f, 0.5f, 0.5f));

	VTLOG(" creating camera\n");
	vtCamera *pCamera = pScene->GetCamera();
	pCamera->SetName2("Default Camera");

	m_pRoot = new vtGroup();
	m_pRoot->SetName2("Root");
	pScene->SetRoot(m_pRoot);

#if VTLIB_SGL
	CreateTestSGLScene();
#endif

	// make a simple directional light
	VTLOG(" creating light\n");
	vtLight *pLight = new vtLight();
	pLight->SetName2("Light");
	vtMovLight *pMovLight = new vtMovLight(pLight);
	pMovLight->SetName2("Movable Light");
	pLight->SetAmbient(RGBf(1, 1, 1));
	pMovLight->SetTrans(FPoint3(0.0f, 0.0f, 5.0f));
	m_pRoot->AddChild(pMovLight);

	// SOG testing, currently disabled
#if 0
#if 0
	// make a yellow sphere
	vtMaterialArray *pMats = new vtMaterialArray();
	pMats->AddRGBMaterial(RGBf(1.0f, 1.0f, 0.0f), RGBf(0.0f, 0.0f, 1.0f));
	vtGeom *pGeom = CreateSphereGeom(pMats, 0, VT_Normals, 0.5, 16);
	pGeom->SetName2("Yellow Sphere");
	pMats->Release();

	OutputSOG osog;

	FILE *fp = fopen("output.sog", "wb");
	osog.WriteHeader(fp);
	osog.WriteSingleGeometry(fp, pGeom);
	fclose(fp);
	m_pRoot->AddChild(pGeom);
#else
	InputSOG isog;

	FILE *fp = fopen("output.sog", "rb");
	vtGroup *pGroup = new vtGroup;
	bool success = isog.ReadContents(fp, pGroup);
	fclose(fp);
	m_pRoot->AddChild(pGroup);
#endif
#endif

	// make a trackball controller for the camera
	VTLOG(" creating trackball\n");
	m_pTrackball = new vtTrackball(3.0f);
	m_pTrackball->SetTarget(pScene->GetCamera());
	m_pTrackball->SetName2("Trackball");
	m_pTrackball->SetRotateButton(VT_LEFT, 0);
	m_pTrackball->SetZoomButton(VT_LEFT|VT_RIGHT, 0);
	m_pTrackball->SetZoomScale(3000.0f);
	m_pTrackball->SetTranslateButton(VT_RIGHT, 0);
	pScene->AddEngine(m_pTrackball);

	// Memleak Testing
//	GetMainFrame()->AddModelFromFile("E:/3D/Sample FLT files/spitfire.flt");
//	vtNode *pNode = vtNode::LoadModel("E:/3D/Sample FLT files/spitfire.flt");
//	if (pNode)
//		m_pRoot->AddChild(pNode);
//	GetMainFrame()->AddNewItem();

//	osg::ref_ptr<osg::Node> node = osgDB::readNodeFile("E:/3D/Sample FLT files/spitfire.flt");
//	node = NULL;

	VTLOG(" end of OnInit\n");
	return TRUE;
}

int vtApp::OnExit(void)
{
	VTLOG("App OnExit\n");

	vtCamera *pCamera = vtGetScene()->GetCamera();
	pCamera->Release();

	vtGetScene()->SetRoot(NULL);
	m_pRoot->Release();

	vtGetScene()->Shutdown();
	return 0;
}

<|endoftext|>