<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 "orc/OrcFile.hh"
#include "wrap/gtest-wrapper.h"
#include "TestDriver.hh"

#include <sstream>

TEST(Reader, simpleTest) {
  orc::ReaderOptions opts;
  std::ostringstream filename;
  filename << exampleDirectory << "/demo-11-none.orc";
  std::unique_ptr<orc::Reader> reader =
    orc::createReader(orc::readLocalFile(filename.str()), opts);

  EXPECT_EQ(orc::CompressionKind_NONE, reader->getCompression());
  EXPECT_EQ(256 * 1024, reader->getCompressionSize());
  EXPECT_EQ(385, reader->getNumberOfStripes());
  EXPECT_EQ(1920800, reader->getNumberOfRows());
  EXPECT_EQ(10000, reader->getRowIndexStride());
  EXPECT_EQ(5069718, reader->getContentLength());
  EXPECT_EQ(filename.str(), reader->getStreamName());
  EXPECT_EQ(0, reader->getMetadataKeys().size());
  EXPECT_FALSE(reader->hasMetadataValue("foo"));
  EXPECT_EQ(18446744073709551615UL, reader->getRowNumber());

  const orc::Type& rootType = reader->getType();
  EXPECT_EQ(0, rootType.getColumnId());
  EXPECT_EQ(orc::STRUCT, rootType.getKind());
  ASSERT_EQ(9, rootType.getSubtypeCount());
  EXPECT_EQ("_col0", rootType.getFieldName(0));
  EXPECT_EQ("_col1", rootType.getFieldName(1));
  EXPECT_EQ("_col2", rootType.getFieldName(2));
  EXPECT_EQ("_col3", rootType.getFieldName(3));
  EXPECT_EQ("_col4", rootType.getFieldName(4));
  EXPECT_EQ("_col5", rootType.getFieldName(5));
  EXPECT_EQ("_col6", rootType.getFieldName(6));
  EXPECT_EQ("_col7", rootType.getFieldName(7));
  EXPECT_EQ("_col8", rootType.getFieldName(8));
  EXPECT_EQ(orc::INT, rootType.getSubtype(0).getKind());
  EXPECT_EQ(orc::STRING, rootType.getSubtype(1).getKind());
  EXPECT_EQ(orc::STRING, rootType.getSubtype(2).getKind());
  EXPECT_EQ(orc::STRING, rootType.getSubtype(3).getKind());
  EXPECT_EQ(orc::INT, rootType.getSubtype(4).getKind());
  EXPECT_EQ(orc::STRING, rootType.getSubtype(5).getKind());
  EXPECT_EQ(orc::INT, rootType.getSubtype(6).getKind());
  EXPECT_EQ(orc::INT, rootType.getSubtype(7).getKind());
  EXPECT_EQ(orc::INT, rootType.getSubtype(8).getKind());
  for(unsigned int i=0; i < 9; ++i) {
    EXPECT_EQ(i + 1, rootType.getSubtype(i).getColumnId()) << "fail on " << i;
  }
  const bool* selected = reader->getSelectedColumns();
  for(int i=0; i < 10; ++i) {
    EXPECT_EQ(true, selected[i]) << "fail on " << i;
  }

  unsigned long rowCount = 0;
  std::unique_ptr<orc::ColumnVectorBatch> batch = reader->createRowBatch(1024);
  while (reader->next(*batch)) {
    EXPECT_EQ(rowCount, reader->getRowNumber());
    rowCount += batch->numElements;
  }
  EXPECT_EQ(1920800, rowCount);
  EXPECT_EQ(1920000, reader->getRowNumber());
}
<commit_msg>Correct unit test to use proper assertion macros.<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 "orc/OrcFile.hh"
#include "TestDriver.hh"

#include "gmock/gmock.h"
#include "wrap/gtest-wrapper.h"

#include <sstream>

namespace {

using ::testing::IsEmpty;

TEST(Reader, simpleTest) {
  orc::ReaderOptions opts;
  std::ostringstream filename;
  filename << exampleDirectory << "/demo-11-none.orc";
  std::unique_ptr<orc::Reader> reader =
    orc::createReader(orc::readLocalFile(filename.str()), opts);

  EXPECT_EQ(orc::CompressionKind_NONE, reader->getCompression());
  EXPECT_EQ(256 * 1024, reader->getCompressionSize());
  EXPECT_EQ(385, reader->getNumberOfStripes());
  EXPECT_EQ(1920800, reader->getNumberOfRows());
  EXPECT_EQ(10000, reader->getRowIndexStride());
  EXPECT_EQ(5069718, reader->getContentLength());
  EXPECT_EQ(filename.str(), reader->getStreamName());
  EXPECT_THAT(reader->getMetadataKeys(), IsEmpty());
  EXPECT_FALSE(reader->hasMetadataValue("foo"));
  EXPECT_EQ(18446744073709551615UL, reader->getRowNumber());

  const orc::Type& rootType = reader->getType();
  EXPECT_EQ(0, rootType.getColumnId());
  EXPECT_EQ(orc::STRUCT, rootType.getKind());
  ASSERT_EQ(9, rootType.getSubtypeCount());
  EXPECT_EQ("_col0", rootType.getFieldName(0));
  EXPECT_EQ("_col1", rootType.getFieldName(1));
  EXPECT_EQ("_col2", rootType.getFieldName(2));
  EXPECT_EQ("_col3", rootType.getFieldName(3));
  EXPECT_EQ("_col4", rootType.getFieldName(4));
  EXPECT_EQ("_col5", rootType.getFieldName(5));
  EXPECT_EQ("_col6", rootType.getFieldName(6));
  EXPECT_EQ("_col7", rootType.getFieldName(7));
  EXPECT_EQ("_col8", rootType.getFieldName(8));
  EXPECT_EQ(orc::INT, rootType.getSubtype(0).getKind());
  EXPECT_EQ(orc::STRING, rootType.getSubtype(1).getKind());
  EXPECT_EQ(orc::STRING, rootType.getSubtype(2).getKind());
  EXPECT_EQ(orc::STRING, rootType.getSubtype(3).getKind());
  EXPECT_EQ(orc::INT, rootType.getSubtype(4).getKind());
  EXPECT_EQ(orc::STRING, rootType.getSubtype(5).getKind());
  EXPECT_EQ(orc::INT, rootType.getSubtype(6).getKind());
  EXPECT_EQ(orc::INT, rootType.getSubtype(7).getKind());
  EXPECT_EQ(orc::INT, rootType.getSubtype(8).getKind());
  for(unsigned int i=0; i < 9; ++i) {
    EXPECT_EQ(i + 1, rootType.getSubtype(i).getColumnId()) << "fail on " << i;
  }
  const bool* const selected = reader->getSelectedColumns();
  for (size_t i = 0; i < 10; ++i) {
    EXPECT_EQ(true, selected[i]) << "fail on " << i;
  }

  unsigned long rowCount = 0;
  std::unique_ptr<orc::ColumnVectorBatch> batch = reader->createRowBatch(1024);
  while (reader->next(*batch)) {
    EXPECT_EQ(rowCount, reader->getRowNumber());
    rowCount += batch->numElements;
  }
  EXPECT_EQ(1920800, rowCount);
  EXPECT_EQ(1920000, reader->getRowNumber());
}

}  // namespace
<|endoftext|>


<commit_before>// http://www.alittlemadness.com/2009/03/31/c-unit-testing-with-boosttest/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Suites
#include <boost/test/unit_test.hpp>
#include "toolbox.h"
#include <armadillo>

using namespace arma;
using namespace std;
using namespace toolbox;

struct myTestObject
{
    int m;
    fvec quaternion;

    myTestObject() : m(2), quaternion(4)
    {
        BOOST_TEST_MESSAGE("setup mass");

        quaternion << 1 << 0 << 0 << 0;

    }

    ~myTestObject()
    {
        BOOST_TEST_MESSAGE("teardown mass");
    }
};

int add(int i, int j) {
    return i + j;
}

int rotationConversion(fvec quaternion) {
	float tol = 1e-6;

	//fvec quaternion(4);
	fmat myR;
	fvec euler;
	fvec newQuat;

	// Test no rotation
	//quaternion << 1 << 0 << 0 << 0;
	myR = CToolbox::quaternion2rot3D(quaternion);
	euler = CToolbox::quaternion2euler(quaternion);
  	newQuat = CToolbox::euler2quaternion(euler(0),euler(1),euler(2));

	if (abs(sum(quaternion - newQuat)) > tol ) {
		cout << "ERROR!!!" << endl;
		return 1;
	}
	return 0;
}

BOOST_FIXTURE_TEST_SUITE(Maths, myTestObject)

BOOST_AUTO_TEST_CASE(universeInOrder)
{
    BOOST_CHECK(add(m, 2) == 4);
    BOOST_CHECK(rotationConversion(quaternion) == 0);
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>testing some c++11 features<commit_after>// http://www.alittlemadness.com/2009/03/31/c-unit-testing-with-boosttest/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Suites
#include <boost/test/unit_test.hpp>
#include "toolbox.h"
#include <armadillo>

using namespace arma;
using namespace std;
using namespace toolbox;

struct myTestObject
{
    int m;
    fvec quaternion;

    myTestObject() : m(2), quaternion(4)
    {
        BOOST_TEST_MESSAGE("setup mass");

        quaternion << 1 << 0 << 0 << 0;

    }

    ~myTestObject()
    {
        BOOST_TEST_MESSAGE("teardown mass");
    }
};

int add(int i, int j) {
	auto a = i;
	//std::vector<int> b = {0,1,2,3};
	//for (int x : b) {
	//	cout << x << endl;
	//}
    return i + j + a;
}

int rotationConversion(fvec quaternion) {
	float tol = 1e-6;

	//static_assert(__cplusplus > 199711L, "Program requires C++11 capable compiler");
	auto b = add(5,6);
	cout << b << endl;

	//fvec quaternion(4);
	fmat myR;
	fvec euler;
	fvec newQuat;

	// Test no rotation
	//quaternion << 1 << 0 << 0 << 0;
	myR = CToolbox::quaternion2rot3D(quaternion);
	euler = CToolbox::quaternion2euler(quaternion);
  	newQuat = CToolbox::euler2quaternion(euler(0),euler(1),euler(2));

	if (abs(sum(quaternion - newQuat)) > tol ) {
		cout << "ERROR!!!" << endl;
		return 1;
	}
	return 0;
}

BOOST_FIXTURE_TEST_SUITE(Maths, myTestObject)

BOOST_AUTO_TEST_CASE(universeInOrder)
{
    BOOST_CHECK(add(m, 2) == 6);
    BOOST_CHECK(rotationConversion(quaternion) == 0);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>//===-- llc.cpp - Implement the LLVM Compiler -----------------------------===//
//
// This is the llc compiler driver.
//
//===----------------------------------------------------------------------===//

#include "llvm/Bytecode/Reader.h"
#include "llvm/Target/TargetMachineImpls.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Linker.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/Support/PassNameParser.h"
#include "Support/CommandLine.h"
#include "Support/Signals.h"
#include <memory>
#include <fstream>

//------------------------------------------------------------------------------
// Option declarations for LLC.
//------------------------------------------------------------------------------

// Make all registered optimization passes available to llc.  These passes
// will all be run before the simplification and lowering steps used by the
// back-end code generator, and will be run in the order specified on the
// command line. The OptimizationList is automatically populated with
// registered Passes by the PassNameParser.
//
static cl::list<const PassInfo*, bool,
                FilteredPassNameParser<PassInfo::Optimization> >
OptimizationList(cl::desc("Optimizations available:"));

// General options for llc.  Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));

static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));

static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));

static cl::opt<bool>
DumpAsm("d", cl::desc("Print bytecode before native code generation"),
        cl::Hidden);

static cl::opt<std::string>
TraceLibPath("tracelibpath", cl::desc("Path to libinstr for trace code"),
             cl::value_desc("directory"), cl::Hidden);

// flags set from -tracem and -trace options to control tracing
static bool TraceFunctions   = false;
static bool TraceBasicBlocks = false;

// GetFileNameRoot - Helper function to get the basename of a filename...
static inline std::string
GetFileNameRoot(const std::string &InputFilename)
{
  std::string IFN = InputFilename;
  std::string outputFilename;
  int Len = IFN.length();
  if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
    outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
  } else {
    outputFilename = IFN;
  }
  return outputFilename;
}

static bool
insertTraceCodeFor(Module &M)
{
  PassManager Passes;

  // Insert trace code in all functions in the module
  if (TraceBasicBlocks)
    Passes.add(createTraceValuesPassForBasicBlocks());
  else if (TraceFunctions)
    Passes.add(createTraceValuesPassForFunction());
  else
    return false;

  // Eliminate duplication in constant pool
  Passes.add(createConstantMergePass());

  // Run passes to insert and clean up trace code...
  Passes.run(M);

  std::string ErrorMessage;

  // Load the module that contains the runtime helper routines neccesary for
  // pointer hashing and stuff...  link this module into the program if possible
  //
  Module *TraceModule = ParseBytecodeFile(TraceLibPath+"libinstr.bc");

  // Check if the TraceLibPath contains a valid module.  If not, try to load
  // the module from the current LLVM-GCC install directory.  This is kindof
  // a hack, but allows people to not HAVE to have built the library.
  //
  if (TraceModule == 0)
    TraceModule = ParseBytecodeFile("/home/vadve/lattner/cvs/gcc_install/lib/"
                                    "gcc-lib/llvm/3.1/libinstr.bc");

  // If we still didn't get it, cancel trying to link it in...
  if (TraceModule == 0)
    std::cerr <<"WARNING: couldn't load trace routines to link into program!\n";
  else
    {
      // Link in the trace routines... if this fails, don't panic, because the
      // compile should still succeed, but the native linker will probably fail.
      //
      std::auto_ptr<Module> TraceRoutines(TraceModule);
      if (LinkModules(&M, TraceRoutines.get(), &ErrorMessage))
        std::cerr << "WARNING: Error linking in trace routines: "
                  << ErrorMessage << "\n";
    }

  // Write out the module with tracing code just before code generation
  assert (InputFilename != "-"
          && "Cannot write out traced bytecode when reading input from stdin");
  std::string TraceFilename = GetFileNameRoot(InputFilename) + ".trace.bc";

  std::ofstream Out(TraceFilename.c_str());
  if (!Out.good())
    std::cerr << "Error opening '" << TraceFilename
              << "'!: Skipping output of trace code as bytecode\n";
  else
    {
      std::cerr << "Emitting trace code to '" << TraceFilename
                << "' for comparison...\n";
      WriteBytecodeToFile(&M, Out);
    }

  return true;
}

// Making tracing a module pass so the entire module with tracing
// can be written out before continuing.
struct InsertTracingCodePass: public Pass {
  virtual bool run(Module &M) {
    return insertTraceCodeFor(M);
  }
};

//===---------------------------------------------------------------------===//
// Function main()
//
// Entry point for the llc compiler.
//===---------------------------------------------------------------------===//

int
main(int argc, char **argv)
{
  cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");

  // Allocate a target... in the future this will be controllable on the
  // command line.
  std::auto_ptr<TargetMachine> target(allocateSparcTargetMachine());
  assert(target.get() && "Could not allocate target machine!");

  TargetMachine &Target = *target.get();
  const TargetData &TD = Target.getTargetData();

  // Load the module to be compiled...
  std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
  if (M.get() == 0)
    {
      std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
      return 1;
    }

  // Build up all of the passes that we want to do to the module...
  PassManager Passes;

  Passes.add(new TargetData("llc", TD.isLittleEndian(), TD.getPointerSize(),
                            TD.getPointerAlignment(), TD.getDoubleAlignment()));

  // Create a new optimization pass for each one specified on the command line
  // Deal specially with tracing passes, which must be run differently than opt.
  //
  for (unsigned i = 0; i < OptimizationList.size(); ++i)
    {
      const PassInfo *Opt = OptimizationList[i];

      if (std::string(Opt->getPassArgument()) == "trace")
        TraceFunctions = !(TraceBasicBlocks = true);
      else if (std::string(Opt->getPassArgument()) == "tracem")
        TraceFunctions = !(TraceBasicBlocks = false);
      else
        { // handle other passes as normal optimization passes
          if (Opt->getNormalCtor())
            Passes.add(Opt->getNormalCtor()());
          else if (Opt->getTargetCtor())
            Passes.add(Opt->getTargetCtor()(Target));
          else
            std::cerr << argv[0] << ": cannot create pass: "
                      << Opt->getPassName() << "\n";
        }
    }

  // Run tracing passes after other optimization passes and before llc passes.
  if (TraceFunctions || TraceBasicBlocks)
    Passes.add(new InsertTracingCodePass);

  // Decompose multi-dimensional refs into a sequence of 1D refs
  Passes.add(createDecomposeMultiDimRefsPass());

  // Replace malloc and free instructions with library calls.
  // Do this after tracing until lli implements these lib calls.
  // For now, it will emulate malloc and free internally.
  Passes.add(createLowerAllocationsPass());

  // If LLVM dumping after transformations is requested, add it to the pipeline
  if (DumpAsm)
    Passes.add(new PrintFunctionPass("Code after xformations: \n", &std::cerr));

  // Strip all of the symbols from the bytecode so that it will be smaller...
  Passes.add(createSymbolStrippingPass());

  // Figure out where we are going to send the output...
  std::ostream *Out = 0;
  if (OutputFilename != "")
    {   // Specified an output filename?
      if (!Force && std::ifstream(OutputFilename.c_str())) {
        // If force is not specified, make sure not to overwrite a file!
        std::cerr << argv[0] << ": error opening '" << OutputFilename
                  << "': file exists!\n"
                  << "Use -f command line argument to force output\n";
        return 1;
      }
      Out = new std::ofstream(OutputFilename.c_str());

      // Make sure that the Out file gets unlink'd from the disk if we get a
      // SIGINT
      RemoveFileOnSignal(OutputFilename);
    }
  else
    {
      if (InputFilename == "-")
        {
          OutputFilename = "-";
          Out = &std::cout;
        }
      else
        {
          std::string OutputFilename = GetFileNameRoot(InputFilename);
          OutputFilename += ".s";

          if (!Force && std::ifstream(OutputFilename.c_str()))
            {
              // If force is not specified, make sure not to overwrite a file!
              std::cerr << argv[0] << ": error opening '" << OutputFilename
                        << "': file exists!\n"
                        << "Use -f command line argument to force output\n";
              return 1;
            }

          Out = new std::ofstream(OutputFilename.c_str());
          if (!Out->good())
            {
              std::cerr << argv[0] << ": error opening " << OutputFilename
                        << "!\n";
              delete Out;
              return 1;
            }

          // Make sure that the Out file gets unlink'd from the disk if we get a
          // SIGINT
          RemoveFileOnSignal(OutputFilename);
        }
    }

  // Ask the target to add backend passes as neccesary
  if (Target.addPassesToEmitAssembly(Passes, *Out)) {
    std::cerr << argv[0] << ": target '" << Target.getName()
              << " does not support static compilation!\n";
  } else {
    // Run our queue of passes all at once now, efficiently.
    Passes.run(*M.get());
  }

  // Delete the ostream if it's not a stdout stream
  if (Out != &std::cout) delete Out;

  return 0;
}
<commit_msg>Add a new option to disable stripping of bytecode files<commit_after>//===-- llc.cpp - Implement the LLVM Compiler -----------------------------===//
//
// This is the llc compiler driver.
//
//===----------------------------------------------------------------------===//

#include "llvm/Bytecode/Reader.h"
#include "llvm/Target/TargetMachineImpls.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Linker.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/Support/PassNameParser.h"
#include "Support/CommandLine.h"
#include "Support/Signals.h"
#include <memory>
#include <fstream>

//------------------------------------------------------------------------------
// Option declarations for LLC.
//------------------------------------------------------------------------------

// Make all registered optimization passes available to llc.  These passes
// will all be run before the simplification and lowering steps used by the
// back-end code generator, and will be run in the order specified on the
// command line. The OptimizationList is automatically populated with
// registered Passes by the PassNameParser.
//
static cl::list<const PassInfo*, bool,
                FilteredPassNameParser<PassInfo::Optimization> >
OptimizationList(cl::desc("Optimizations available:"));

// General options for llc.  Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));

static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));

static cl::opt<bool> Force("f", cl::desc("Overwrite output files"));

static cl::opt<bool>
DisableStrip("disable-strip",
          cl::desc("Do not strip the LLVM bytecode included in the executable"));

static cl::opt<bool>
DumpAsm("d", cl::desc("Print bytecode before native code generation"),
        cl::Hidden);

static cl::opt<std::string>
TraceLibPath("tracelibpath", cl::desc("Path to libinstr for trace code"),
             cl::value_desc("directory"), cl::Hidden);

// flags set from -tracem and -trace options to control tracing
static bool TraceFunctions   = false;
static bool TraceBasicBlocks = false;

// GetFileNameRoot - Helper function to get the basename of a filename...
static inline std::string
GetFileNameRoot(const std::string &InputFilename)
{
  std::string IFN = InputFilename;
  std::string outputFilename;
  int Len = IFN.length();
  if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
    outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
  } else {
    outputFilename = IFN;
  }
  return outputFilename;
}

static bool
insertTraceCodeFor(Module &M)
{
  PassManager Passes;

  // Insert trace code in all functions in the module
  if (TraceBasicBlocks)
    Passes.add(createTraceValuesPassForBasicBlocks());
  else if (TraceFunctions)
    Passes.add(createTraceValuesPassForFunction());
  else
    return false;

  // Eliminate duplication in constant pool
  Passes.add(createConstantMergePass());

  // Run passes to insert and clean up trace code...
  Passes.run(M);

  std::string ErrorMessage;

  // Load the module that contains the runtime helper routines neccesary for
  // pointer hashing and stuff...  link this module into the program if possible
  //
  Module *TraceModule = ParseBytecodeFile(TraceLibPath+"libinstr.bc");

  // Check if the TraceLibPath contains a valid module.  If not, try to load
  // the module from the current LLVM-GCC install directory.  This is kindof
  // a hack, but allows people to not HAVE to have built the library.
  //
  if (TraceModule == 0)
    TraceModule = ParseBytecodeFile("/home/vadve/lattner/cvs/gcc_install/lib/"
                                    "gcc-lib/llvm/3.1/libinstr.bc");

  // If we still didn't get it, cancel trying to link it in...
  if (TraceModule == 0)
    std::cerr <<"WARNING: couldn't load trace routines to link into program!\n";
  else
    {
      // Link in the trace routines... if this fails, don't panic, because the
      // compile should still succeed, but the native linker will probably fail.
      //
      std::auto_ptr<Module> TraceRoutines(TraceModule);
      if (LinkModules(&M, TraceRoutines.get(), &ErrorMessage))
        std::cerr << "WARNING: Error linking in trace routines: "
                  << ErrorMessage << "\n";
    }

  // Write out the module with tracing code just before code generation
  assert (InputFilename != "-"
          && "Cannot write out traced bytecode when reading input from stdin");
  std::string TraceFilename = GetFileNameRoot(InputFilename) + ".trace.bc";

  std::ofstream Out(TraceFilename.c_str());
  if (!Out.good())
    std::cerr << "Error opening '" << TraceFilename
              << "'!: Skipping output of trace code as bytecode\n";
  else
    {
      std::cerr << "Emitting trace code to '" << TraceFilename
                << "' for comparison...\n";
      WriteBytecodeToFile(&M, Out);
    }

  return true;
}

// Making tracing a module pass so the entire module with tracing
// can be written out before continuing.
struct InsertTracingCodePass: public Pass {
  virtual bool run(Module &M) {
    return insertTraceCodeFor(M);
  }
};

//===---------------------------------------------------------------------===//
// Function main()
//
// Entry point for the llc compiler.
//===---------------------------------------------------------------------===//

int
main(int argc, char **argv)
{
  cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");

  // Allocate a target... in the future this will be controllable on the
  // command line.
  std::auto_ptr<TargetMachine> target(allocateSparcTargetMachine());
  assert(target.get() && "Could not allocate target machine!");

  TargetMachine &Target = *target.get();
  const TargetData &TD = Target.getTargetData();

  // Load the module to be compiled...
  std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
  if (M.get() == 0)
    {
      std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
      return 1;
    }

  // Build up all of the passes that we want to do to the module...
  PassManager Passes;

  Passes.add(new TargetData("llc", TD.isLittleEndian(), TD.getPointerSize(),
                            TD.getPointerAlignment(), TD.getDoubleAlignment()));

  // Create a new optimization pass for each one specified on the command line
  // Deal specially with tracing passes, which must be run differently than opt.
  //
  for (unsigned i = 0; i < OptimizationList.size(); ++i)
    {
      const PassInfo *Opt = OptimizationList[i];

      if (std::string(Opt->getPassArgument()) == "trace")
        TraceFunctions = !(TraceBasicBlocks = true);
      else if (std::string(Opt->getPassArgument()) == "tracem")
        TraceFunctions = !(TraceBasicBlocks = false);
      else
        { // handle other passes as normal optimization passes
          if (Opt->getNormalCtor())
            Passes.add(Opt->getNormalCtor()());
          else if (Opt->getTargetCtor())
            Passes.add(Opt->getTargetCtor()(Target));
          else
            std::cerr << argv[0] << ": cannot create pass: "
                      << Opt->getPassName() << "\n";
        }
    }

  // Run tracing passes after other optimization passes and before llc passes.
  if (TraceFunctions || TraceBasicBlocks)
    Passes.add(new InsertTracingCodePass);

  // Decompose multi-dimensional refs into a sequence of 1D refs
  Passes.add(createDecomposeMultiDimRefsPass());

  // Replace malloc and free instructions with library calls.
  // Do this after tracing until lli implements these lib calls.
  // For now, it will emulate malloc and free internally.
  Passes.add(createLowerAllocationsPass());

  // If LLVM dumping after transformations is requested, add it to the pipeline
  if (DumpAsm)
    Passes.add(new PrintFunctionPass("Code after xformations: \n", &std::cerr));

  // Strip all of the symbols from the bytecode so that it will be smaller...
  if (!DisableStrip)
    Passes.add(createSymbolStrippingPass());

  // Figure out where we are going to send the output...
  std::ostream *Out = 0;
  if (OutputFilename != "")
    {   // Specified an output filename?
      if (!Force && std::ifstream(OutputFilename.c_str())) {
        // If force is not specified, make sure not to overwrite a file!
        std::cerr << argv[0] << ": error opening '" << OutputFilename
                  << "': file exists!\n"
                  << "Use -f command line argument to force output\n";
        return 1;
      }
      Out = new std::ofstream(OutputFilename.c_str());

      // Make sure that the Out file gets unlink'd from the disk if we get a
      // SIGINT
      RemoveFileOnSignal(OutputFilename);
    }
  else
    {
      if (InputFilename == "-")
        {
          OutputFilename = "-";
          Out = &std::cout;
        }
      else
        {
          std::string OutputFilename = GetFileNameRoot(InputFilename);
          OutputFilename += ".s";

          if (!Force && std::ifstream(OutputFilename.c_str()))
            {
              // If force is not specified, make sure not to overwrite a file!
              std::cerr << argv[0] << ": error opening '" << OutputFilename
                        << "': file exists!\n"
                        << "Use -f command line argument to force output\n";
              return 1;
            }

          Out = new std::ofstream(OutputFilename.c_str());
          if (!Out->good())
            {
              std::cerr << argv[0] << ": error opening " << OutputFilename
                        << "!\n";
              delete Out;
              return 1;
            }

          // Make sure that the Out file gets unlink'd from the disk if we get a
          // SIGINT
          RemoveFileOnSignal(OutputFilename);
        }
    }

  // Ask the target to add backend passes as neccesary
  if (Target.addPassesToEmitAssembly(Passes, *Out)) {
    std::cerr << argv[0] << ": target '" << Target.getName()
              << " does not support static compilation!\n";
  } else {
    // Run our queue of passes all at once now, efficiently.
    Passes.run(*M.get());
  }

  // Delete the ostream if it's not a stdout stream
  if (Out != &std::cout) delete Out;

  return 0;
}
<|endoftext|>


<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <cstdint>
#include <cstring> // memcpy

#include <visionaray/math/math.h>

#include <gtest/gtest.h>

using namespace visionaray;

TEST(Norm, Unsigned)
{
    // Test initialization --------------------------------

    unorm< 8> un8;
    unorm<16> un16;
    unorm< 8> un8s[4];
    unorm<16> un16s[4];

    // init with 0

    un8 = 0.0f;

    EXPECT_EQ(uint8_t(un8),   numeric_limits<uint8_t>::lowest());
    EXPECT_EQ(uint16_t(un16), numeric_limits<uint16_t>::lowest());

    EXPECT_FLOAT_EQ(float(un8),  0.0f);
    EXPECT_FLOAT_EQ(float(un16), 0.0f);

    // init with 1

    un8  = 1.0f;
    un16 = 1.0f;

    EXPECT_EQ(uint8_t(un8),   numeric_limits<uint8_t>::max());
    EXPECT_EQ(uint16_t(un16), numeric_limits<uint16_t>::max());

    EXPECT_FLOAT_EQ(float(un8),  1.0f);
    EXPECT_FLOAT_EQ(float(un16), 1.0f);

    // init with byte arrays

    uint8_t arr8[]      = { 0,   128,   255,   255 };
    uint16_t arr16[]    = { 0, 32767, 65535, 65535 };

    std::memcpy(un8s,  arr8,  4 * sizeof(uint8_t));
    std::memcpy(un16s, arr16, 4 * sizeof(uint16_t));

    for (int i = 0; i < 4; ++i)
    {
        EXPECT_EQ(uint8_t(un8s[i]),   arr8[i]);
        EXPECT_EQ(uint16_t(un16s[i]), arr16[i]);

        EXPECT_FLOAT_EQ(float(un8s[i]),  static_cast<float>(arr8[i])  / numeric_limits<uint8_t>::max());
        EXPECT_FLOAT_EQ(float(un16s[i]), static_cast<float>(arr16[i]) / numeric_limits<uint16_t>::max());
    }
}
<commit_msg>Also test unorm<32><commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <cstdint>
#include <cstring> // memcpy

#include <visionaray/math/math.h>

#include <gtest/gtest.h>

using namespace visionaray;

TEST(Norm, Unsigned)
{
    // Some convenience -----------------------------------

    static const uint8_t  max8  = numeric_limits<uint8_t>::max();
    static const uint16_t max16 = numeric_limits<uint16_t>::max();
    static const uint32_t max32 = numeric_limits<uint32_t>::max();

    static const uint8_t  low8  = numeric_limits<uint8_t>::lowest();
    static const uint16_t low16 = numeric_limits<uint16_t>::lowest();
    static const uint32_t low32 = numeric_limits<uint32_t>::lowest();

    // Test initialization --------------------------------

    unorm< 8> un8;
    unorm<16> un16;
    unorm<32> un32;
    unorm< 8> un8s[4];
    unorm<16> un16s[4];
    unorm<32> un32s[4];

    // init with 0

    un8  = 0.0f;
    un16 = 0.0f;
    un32 = 0.0f;

    EXPECT_EQ(uint8_t(un8),   low8);
    EXPECT_EQ(uint16_t(un16), low16);
    EXPECT_EQ(uint32_t(un32), low32);

    EXPECT_FLOAT_EQ(float(un8),  0.0f);
    EXPECT_FLOAT_EQ(float(un16), 0.0f);
    EXPECT_FLOAT_EQ(float(un32), 0.0f);

    // init with 1

    un8  = 1.0f;
    un16 = 1.0f;
    un32 = 1.0f;

    EXPECT_EQ(uint8_t(un8),   max8);
    EXPECT_EQ(uint16_t(un16), max16);
    EXPECT_EQ(uint32_t(un32), max32);

    EXPECT_FLOAT_EQ(float(un8),  1.0f);
    EXPECT_FLOAT_EQ(float(un16), 1.0f);
    EXPECT_FLOAT_EQ(float(un32), 1.0f);

    // init with byte arrays

    uint8_t arr8[]      = { 0, uint8_t( max8  / 2), max8,  max8 };
    uint16_t arr16[]    = { 0, uint16_t(max16 / 2), max16, max16 };
    uint32_t arr32[]    = { 0, uint32_t(max32 / 2), max32, max32 };

    std::memcpy(un8s,  arr8,  sizeof(arr8));
    std::memcpy(un16s, arr16, sizeof(arr16));
    std::memcpy(un32s, arr32, sizeof(arr32));

    for (int i = 0; i < 4; ++i)
    {
        EXPECT_EQ(uint8_t(un8s[i]),   arr8[i]);
        EXPECT_EQ(uint16_t(un16s[i]), arr16[i]);
        EXPECT_EQ(uint32_t(un32s[i]), arr32[i]);

        EXPECT_FLOAT_EQ(float(un8s[i]),  static_cast<float>(arr8[i])  / max8);
        EXPECT_FLOAT_EQ(float(un16s[i]), static_cast<float>(arr16[i]) / max16);
        EXPECT_FLOAT_EQ(float(un32s[i]), static_cast<float>(arr32[i]) / max32);
    }
}
<|endoftext|>


<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <iostream>
#include <visionaray/math/math.h>

#include <gtest/gtest.h>

using namespace visionaray;

//-------------------------------------------------------------------------------------------------
//
// Test setup:
//
//
//      Y
//
//      -
//
//  300 -               B--------
//                      |   C-- |----
//  250 -               |   |   |   |
//                      ---------   |
//  200 -                   |       |
//                          ---------
//  150 -
//
//  100 -   A--------   D---F----
//          | G---- |   |   |   |
//   50 -   | |   | |   |   E----
//          | ----- |   |   |   |
//    0 -   ---------   ---------
//
//      /   |   |   |   |   |   |   |   |   X
//          0  50  100 150 200 250 300
//
//-------------------------------------------------------------------------------------------------

//-------------------------------------------------------------------------------------------------
// Helper functions
//

template <typename RectA, typename RectB>
RectA convert_xywh(RectB const& rect)
{
    return RectA(rect.x, rect.y, rect.w, rect.h);
}

//-------------------------------------------------------------------------------------------------
// Tests
//

TEST(Rect, XYWH)
{

    // init -----------------------------------------------

    recti Ai(  0,   0, 100, 100);
    recti Bi(150, 225, 100,  75);
    recti Ci(200, 175, 100, 100);
    recti Di(150,   0,  50, 100);
    recti Ei(200,   0,  50,  50);
    recti Fi(200,  50,  50,  50);
    recti Gi( 25,  25,  50,  50);

    rectf Af = convert_xywh<rectf>(Ai);
    rectf Bf = convert_xywh<rectf>(Bi);
    rectf Cf = convert_xywh<rectf>(Ci);
    rectf Df = convert_xywh<rectf>(Di);
    rectf Ef = convert_xywh<rectf>(Ei);
    rectf Ff = convert_xywh<rectf>(Fi);

    // test validity checks -------------------------------

    recti empty(0, 0, 0, 0);
    recti valid = Ai;
    recti invalid;
    invalid.invalidate();

    EXPECT_TRUE( empty.valid());
    EXPECT_TRUE( empty.empty());
    EXPECT_FALSE(empty.invalid());

    EXPECT_TRUE( valid.valid());
    EXPECT_FALSE(valid.empty());
    EXPECT_FALSE(valid.invalid());

    EXPECT_FALSE(invalid.valid());
    EXPECT_TRUE( invalid.empty());
    EXPECT_TRUE( invalid.invalid());

    invalid = Ai;
    invalid.w = -1;

    EXPECT_FALSE(invalid.valid());
    EXPECT_TRUE( invalid.empty());
    EXPECT_TRUE( invalid.invalid());

    invalid = Ai;
    invalid.h = -1;

    EXPECT_FALSE(invalid.valid());
    EXPECT_TRUE( invalid.empty());
    EXPECT_TRUE( invalid.invalid());

    // test contains() ------------------------------------

    // contains point?
    EXPECT_FALSE(Ai.contains(vec2i(-1, -1)));
    EXPECT_TRUE( Ai.contains(vec2i(0, 0)));
    EXPECT_TRUE( Ai.contains(vec2i(1, 1)));
    EXPECT_TRUE( Ai.contains(vec2i(99, 99)));
    EXPECT_TRUE( Ai.contains(vec2i(100, 100)));
    EXPECT_FALSE(Ai.contains(vec2i(101, 101)));

    // contains rectangle?
    EXPECT_TRUE( Ai.contains(Ai));
    EXPECT_TRUE( Ai.contains(Gi));
    EXPECT_FALSE(Gi.contains(Ai));
    EXPECT_FALSE(Ai.contains(Bi));
    EXPECT_FALSE(Bi.contains(Ci));
    EXPECT_FALSE(Ci.contains(Bi));
    EXPECT_FALSE(Di.contains(Ei));
    EXPECT_FALSE(Ei.contains(Fi));

    // test overlapping() ---------------------------------

    EXPECT_FALSE(overlapping(Ai, Bi));
    EXPECT_TRUE( overlapping(Bi, Ci));
    EXPECT_TRUE( overlapping(Di, Ei));
    EXPECT_TRUE( overlapping(Ei, Fi));

    EXPECT_FALSE(overlapping(Af, Bf));
    EXPECT_TRUE( overlapping(Bf, Cf));
    EXPECT_TRUE( overlapping(Df, Ef));
    EXPECT_TRUE( overlapping(Ef, Ff));

    // test combine() -------------------------------------

    EXPECT_TRUE(combine(Ei, Fi) == recti(200, 0, 50, 100));
    EXPECT_TRUE(combine(Bi, Ci) == recti(150, 175, 150, 125));
    EXPECT_TRUE(combine(Di, combine(Ei, Fi)) == recti(150, 0, 100, 100));

    // test intersect() -----------------------------------

    EXPECT_TRUE(intersect(Ai, Bi).empty());
    EXPECT_TRUE(intersect(Di, Ei).empty());
    EXPECT_TRUE(intersect(Ei, Fi).empty());
    EXPECT_TRUE(intersect(Bi, Ci) == recti(200, 225, 50, 50));

}
<commit_msg>Unnecessary include directive<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <visionaray/math/math.h>

#include <gtest/gtest.h>

using namespace visionaray;

//-------------------------------------------------------------------------------------------------
//
// Test setup:
//
//
//      Y
//
//      -
//
//  300 -               B--------
//                      |   C-- |----
//  250 -               |   |   |   |
//                      ---------   |
//  200 -                   |       |
//                          ---------
//  150 -
//
//  100 -   A--------   D---F----
//          | G---- |   |   |   |
//   50 -   | |   | |   |   E----
//          | ----- |   |   |   |
//    0 -   ---------   ---------
//
//      /   |   |   |   |   |   |   |   |   X
//          0  50  100 150 200 250 300
//
//-------------------------------------------------------------------------------------------------

//-------------------------------------------------------------------------------------------------
// Helper functions
//

template <typename RectA, typename RectB>
RectA convert_xywh(RectB const& rect)
{
    return RectA(rect.x, rect.y, rect.w, rect.h);
}

//-------------------------------------------------------------------------------------------------
// Tests
//

TEST(Rect, XYWH)
{

    // init -----------------------------------------------

    recti Ai(  0,   0, 100, 100);
    recti Bi(150, 225, 100,  75);
    recti Ci(200, 175, 100, 100);
    recti Di(150,   0,  50, 100);
    recti Ei(200,   0,  50,  50);
    recti Fi(200,  50,  50,  50);
    recti Gi( 25,  25,  50,  50);

    rectf Af = convert_xywh<rectf>(Ai);
    rectf Bf = convert_xywh<rectf>(Bi);
    rectf Cf = convert_xywh<rectf>(Ci);
    rectf Df = convert_xywh<rectf>(Di);
    rectf Ef = convert_xywh<rectf>(Ei);
    rectf Ff = convert_xywh<rectf>(Fi);

    // test validity checks -------------------------------

    recti empty(0, 0, 0, 0);
    recti valid = Ai;
    recti invalid;
    invalid.invalidate();

    EXPECT_TRUE( empty.valid());
    EXPECT_TRUE( empty.empty());
    EXPECT_FALSE(empty.invalid());

    EXPECT_TRUE( valid.valid());
    EXPECT_FALSE(valid.empty());
    EXPECT_FALSE(valid.invalid());

    EXPECT_FALSE(invalid.valid());
    EXPECT_TRUE( invalid.empty());
    EXPECT_TRUE( invalid.invalid());

    invalid = Ai;
    invalid.w = -1;

    EXPECT_FALSE(invalid.valid());
    EXPECT_TRUE( invalid.empty());
    EXPECT_TRUE( invalid.invalid());

    invalid = Ai;
    invalid.h = -1;

    EXPECT_FALSE(invalid.valid());
    EXPECT_TRUE( invalid.empty());
    EXPECT_TRUE( invalid.invalid());

    // test contains() ------------------------------------

    // contains point?
    EXPECT_FALSE(Ai.contains(vec2i(-1, -1)));
    EXPECT_TRUE( Ai.contains(vec2i(0, 0)));
    EXPECT_TRUE( Ai.contains(vec2i(1, 1)));
    EXPECT_TRUE( Ai.contains(vec2i(99, 99)));
    EXPECT_TRUE( Ai.contains(vec2i(100, 100)));
    EXPECT_FALSE(Ai.contains(vec2i(101, 101)));

    // contains rectangle?
    EXPECT_TRUE( Ai.contains(Ai));
    EXPECT_TRUE( Ai.contains(Gi));
    EXPECT_FALSE(Gi.contains(Ai));
    EXPECT_FALSE(Ai.contains(Bi));
    EXPECT_FALSE(Bi.contains(Ci));
    EXPECT_FALSE(Ci.contains(Bi));
    EXPECT_FALSE(Di.contains(Ei));
    EXPECT_FALSE(Ei.contains(Fi));

    // test overlapping() ---------------------------------

    EXPECT_FALSE(overlapping(Ai, Bi));
    EXPECT_TRUE( overlapping(Bi, Ci));
    EXPECT_TRUE( overlapping(Di, Ei));
    EXPECT_TRUE( overlapping(Ei, Fi));

    EXPECT_FALSE(overlapping(Af, Bf));
    EXPECT_TRUE( overlapping(Bf, Cf));
    EXPECT_TRUE( overlapping(Df, Ef));
    EXPECT_TRUE( overlapping(Ef, Ff));

    // test combine() -------------------------------------

    EXPECT_TRUE(combine(Ei, Fi) == recti(200, 0, 50, 100));
    EXPECT_TRUE(combine(Bi, Ci) == recti(150, 175, 150, 125));
    EXPECT_TRUE(combine(Di, combine(Ei, Fi)) == recti(150, 0, 100, 100));

    // test intersect() -----------------------------------

    EXPECT_TRUE(intersect(Ai, Bi).empty());
    EXPECT_TRUE(intersect(Di, Ei).empty());
    EXPECT_TRUE(intersect(Ei, Fi).empty());
    EXPECT_TRUE(intersect(Bi, Ci) == recti(200, 225, 50, 50));

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cmtree.cxx,v $
 *
 *  $Revision: 1.37 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 15:20:21 $
 *
 *  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
 *
 ************************************************************************/

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

#include <stdio.h>

#include "subtree.hxx"
#ifndef CONFIGMGR_CHANGE_HXX
#include "change.hxx"
#endif
#ifndef CONFIGMGR_TREECHANGELIST_HXX
#include "treechangelist.hxx"
#endif

#ifndef CONFIGMGR_TREEPROVIDER_HXX
#include "treeprovider.hxx"
#endif

//#include "treeactions.hxx"

#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef INCLUDED_DEQUE
#include <deque>
#define INCLUDED_DEQUE
#endif
#ifndef INCLUDED_VECTOR
#include <vector>
#define INCLUDED_VECTOR
#endif
#ifndef INCLUDED_IOSTREAM
#include <iostream>
#define INCLUDED_IOSTREAM
#endif
#ifndef INCLUDED_EXCEPTION
#include <exception>
#define INCLUDED_EXCEPTION
#endif
#ifndef INCLUDED_SET
#include <set>
#define INCLUDED_SET
#endif

using namespace std;
using namespace rtl;
using namespace com::sun::star::uno;

namespace configmgr
{

// ------------------------ ChildListSet implementations ------------------------
    ChildListSet::ChildListSet(ChildListSet const& aSet, treeop::DeepChildCopy)
    {
        for(ChildList::iterator it = aSet.GetSet().begin();
            it != aSet.GetSet().end();
            ++it)
        {
            INode* pOrg = *it;
            std::auto_ptr<INode> aCopy = pOrg->clone();
            m_aChildList.insert(m_aChildList.end(), aCopy.release());
        }
    }
    ChildListSet::~ChildListSet()
    {
        for(ChildList::iterator it = m_aChildList.begin();
            it != m_aChildList.end();
            ++it)
            delete *it;
    }

// ---------------------------- Node implementation ----------------------------

    INode::INode(node::Attributes _aAttr):m_aAttributes(_aAttr){}
    INode::INode(OUString const& aName, node::Attributes _aAttr)
          :m_aName(aName)
          ,m_aAttributes(_aAttr){}
    // CopyCTor will be create automatically

    INode::~INode() {}

    ISubtree*         INode::asISubtree(){return NULL;}
    ISubtree const*   INode::asISubtree() const {return NULL;}
    ValueNode*       INode::asValueNode() {return NULL;}
    ValueNode const* INode::asValueNode() const {return NULL;}

    void INode::modifyState(node::State _eNewState)
    {
        m_aAttributes.setState(_eNewState);
    }

    void INode::modifyAccess(node::Access _aAccessLevel)
    {
        OSL_ENSURE( node::accessWritable <= _aAccessLevel && _aAccessLevel <= node::accessReadonly,"Invalid access level for Node");

        m_aAttributes.setAccess(_aAccessLevel);
    }

    void INode::markMandatory()
    {
        m_aAttributes.markMandatory();
    }

    void INode::markRemovable()
    {
        m_aAttributes.markRemovable();
    }

    void INode::promoteAccessToDefault()
      {
        if (m_aAttributes.isFinalized())
            m_aAttributes.setAccess(node::accessReadonly);

        if ( m_aAttributes.isMandatory())
            m_aAttributes.setRemovability(false,false);
    }

    void INode::forceReadonlyToFinalized()
      {
        if (m_aAttributes.isReadonly())
        {
            m_aAttributes.setAccess(node::accessFinal);
        }
    }

// ------------------------- SearchNode implementation -------------------------
    SearchNode::SearchNode():INode(node::Attributes()){}
    SearchNode::SearchNode(OUString const& aName)
        :INode(aName, node::Attributes()){}

    std::auto_ptr<INode> SearchNode::clone() const {return std::auto_ptr<INode>(new SearchNode(*this));}

    SearchNode::~SearchNode(){}

    //==========================================================================
    //= OPropagateLevels
    //==========================================================================
    /** fills a subtree with the correct level informations
    */
    struct OPropagateLevels : public NodeModification
    {
    public:
        typedef sal_Int16 Level;
        OPropagateLevels(Level _nParentLevel, Level _nParentDefaultLevel)
        : m_nLevel          ( childLevel(_nParentLevel) )
        , m_nDefaultLevel   ( childLevel(_nParentDefaultLevel) )
        {
        }
        virtual void handle(ValueNode&) { /* not interested in value nodes */ }
        virtual void handle(ISubtree& _rSubtree)
        {
            _rSubtree.setLevels(m_nLevel, m_nDefaultLevel);
        }

        static Level childLevel(Level _nLevel)
        {
            OSL_ASSERT(0 > treeop::ALL_LEVELS);
            return (_nLevel > 0) ? _nLevel-1 : _nLevel;
        }
    protected:
        Level   m_nLevel;
        Level   m_nDefaultLevel;
    };

// -------------------------- ISubtree implementation --------------------------
    ISubtree* ISubtree::asISubtree() {return this;}
    ISubtree const* ISubtree::asISubtree() const {return this;}

    //--------------------------------------------------------------------------
    static inline bool adjustLevel(sal_Int16& _rLevel, sal_Int16 _nNewLevel)
    {
        if (_rLevel == treeop::ALL_LEVELS)   return false;
        if (_nNewLevel <= _rLevel &&
            _nNewLevel != treeop::ALL_LEVELS) return false;

        _rLevel = _nNewLevel;
        return true;
    }

    //--------------------------------------------------------------------------
    void ISubtree::setLevels(sal_Int16 _nLevel, sal_Int16 _nDefaultLevels)
    {
        bool bActive = false;

        if (_nLevel && adjustLevel(m_nLevel, _nLevel))
            bActive = true;

        if (_nDefaultLevels && adjustLevel(m_nDefaultLevels, _nDefaultLevels))
            bActive = true;

        // forward the level numbers to any child subtrees we have
        if (bActive)
        {
            OPropagateLevels aPropagate(_nLevel,_nDefaultLevels);
            aPropagate.applyToChildren(*this);
        }
    }

// --------------------------- Subtree implementation ---------------------------
    std::auto_ptr<INode> Subtree::clone() const
    {
        return std::auto_ptr<INode>(new Subtree(*this, treeop::DeepChildCopy()));
    }

    INode* Subtree::doGetChild(OUString const& aName) const
    {
        SearchNode searchObj(aName);

#if OSL_DEBUG_LEVEL > 1
        for (ChildList::iterator it2 = m_aChildren.GetSet().begin();
            it2 != m_aChildren.GetSet().end();
            ++it2)
        {
            INode* pINode = *it2;
            OUString aName2 = pINode->getName();
            volatile int dummy;
            dummy = 0;
        }
#endif

        ChildList::iterator it = m_aChildren.GetSet().find(&searchObj);
        if (it == m_aChildren.GetSet().end())
            return NULL;
        else
            return *it;
    }

    INode* Subtree::addChild(std::auto_ptr<INode> aNode)    // takes ownership
    {
        OUString aName = aNode->getName();
        std::pair<ChildList::iterator, bool> aInserted =
            m_aChildren.GetSet().insert(aNode.get());
        if (aInserted.second)
            aNode.release();
        return *aInserted.first;
    }

    ::std::auto_ptr<INode> Subtree::removeChild(OUString const& aName)
    {
        SearchNode searchObj(aName);
        ChildList::const_iterator it = m_aChildren.GetSet().find(&searchObj);

        ::std::auto_ptr<INode> aReturn;
        if (m_aChildren.GetSet().end() != it)
        {
            aReturn = ::std::auto_ptr<INode>(*it);
            m_aChildren.GetSet().erase(it);
        }
        return aReturn;
    }
//  // -------------------------- ValueNode implementation --------------------------

    void Subtree::forEachChild(NodeAction& anAction) const
    {
        for(ChildList::const_iterator it = m_aChildren.GetSet().begin();
            it != m_aChildren.GetSet().end();
            ++it)
            (**it).dispatch(anAction);
    }

    void Subtree::forEachChild(NodeModification& anAction)
    {
        ChildList::iterator it = m_aChildren.GetSet().begin();
        while( it != m_aChildren.GetSet().end() )
        {
            // modification-safe iteration
            (**it++).dispatch(anAction);
        }
      }

//  // -------------------------- ValueNode implementation --------------------------
    bool ValueNode::setValueType(uno::Type const& _aType)
    {
        if (_aType == this->getValueType()) return true;

        if (!this->isNull()) return false;

        uno::TypeClass eTC = this->getValueType().getTypeClass();
        if (eTC != uno::TypeClass_VOID && eTC != uno::TypeClass_ANY)
            return false;

        m_aValuePair = AnyPair(_aType);

        OSL_ASSERT(_aType == this->getValueType());

        return true;
    }
    bool ValueNode::setValue(Any const& _aValue)
    {
        sal_Bool bRet = m_aValuePair.setFirst(_aValue);
        if (bRet) this->markAsDefault(false);
        return !! bRet;
    }

    bool ValueNode::changeDefault(Any const& _aValue)
    {
        return !! m_aValuePair.setSecond(_aValue);
    }

    void ValueNode::setDefault()
    {
        OSL_PRECOND( hasUsableDefault(), "No default value to set for value node");
        m_aValuePair.clear( selectValue() );
        this->markAsDefault();
        OSL_POSTCOND( isDefault(), "Could not set value node to default");
    }

    void ValueNode::promoteToDefault()
    {
        if (!isDefault())
        {
            if (m_aValuePair.hasFirst())
            {
                OSL_VERIFY( m_aValuePair.setSecond(m_aValuePair.getFirst()) );
                m_aValuePair.clear( selectValue() );
            }
            else
            {
                m_aValuePair.clear( selectDeflt() );
                OSL_ASSERT( m_aValuePair.isNull() );
            }

            this->markAsDefault();

            OSL_ENSURE( !m_aValuePair.hasFirst(), "Leaving orphaned value in after promoting to default");
        }
        else
            OSL_ENSURE( !m_aValuePair.hasFirst(), "Orphaned value in default node won't be promoted");

        OSL_POSTCOND( isDefault(), "Could not promote value node to default");
    }

    std::auto_ptr<INode> ValueNode::clone() const
    {
        return std::auto_ptr<INode>(new ValueNode(*this));
    }

    ValueNode* ValueNode::asValueNode() {return this;}
    ValueNode const* ValueNode::asValueNode() const {return this;}

} // namespace configmgr

<commit_msg>INTEGRATION: CWS sb63 (1.37.8); FILE MERGED 2006/10/20 08:33:19 sb 1.37.8.1: #i68959# Patch by cmc: removed unneeded include.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cmtree.cxx,v $
 *
 *  $Revision: 1.38 $
 *
 *  last change: $Author: kz $ $Date: 2006-11-06 14:49:54 $
 *
 *  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
 *
 ************************************************************************/

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

#include <stdio.h>

#include "subtree.hxx"
#ifndef CONFIGMGR_CHANGE_HXX
#include "change.hxx"
#endif
#ifndef CONFIGMGR_TREECHANGELIST_HXX
#include "treechangelist.hxx"
#endif

#ifndef CONFIGMGR_TREEPROVIDER_HXX
#include "treeprovider.hxx"
#endif

//#include "treeactions.hxx"

#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef INCLUDED_DEQUE
#include <deque>
#define INCLUDED_DEQUE
#endif
#ifndef INCLUDED_VECTOR
#include <vector>
#define INCLUDED_VECTOR
#endif
#ifndef INCLUDED_EXCEPTION
#include <exception>
#define INCLUDED_EXCEPTION
#endif
#ifndef INCLUDED_SET
#include <set>
#define INCLUDED_SET
#endif

using namespace std;
using namespace rtl;
using namespace com::sun::star::uno;

namespace configmgr
{

// ------------------------ ChildListSet implementations ------------------------
    ChildListSet::ChildListSet(ChildListSet const& aSet, treeop::DeepChildCopy)
    {
        for(ChildList::iterator it = aSet.GetSet().begin();
            it != aSet.GetSet().end();
            ++it)
        {
            INode* pOrg = *it;
            std::auto_ptr<INode> aCopy = pOrg->clone();
            m_aChildList.insert(m_aChildList.end(), aCopy.release());
        }
    }
    ChildListSet::~ChildListSet()
    {
        for(ChildList::iterator it = m_aChildList.begin();
            it != m_aChildList.end();
            ++it)
            delete *it;
    }

// ---------------------------- Node implementation ----------------------------

    INode::INode(node::Attributes _aAttr):m_aAttributes(_aAttr){}
    INode::INode(OUString const& aName, node::Attributes _aAttr)
          :m_aName(aName)
          ,m_aAttributes(_aAttr){}
    // CopyCTor will be create automatically

    INode::~INode() {}

    ISubtree*         INode::asISubtree(){return NULL;}
    ISubtree const*   INode::asISubtree() const {return NULL;}
    ValueNode*       INode::asValueNode() {return NULL;}
    ValueNode const* INode::asValueNode() const {return NULL;}

    void INode::modifyState(node::State _eNewState)
    {
        m_aAttributes.setState(_eNewState);
    }

    void INode::modifyAccess(node::Access _aAccessLevel)
    {
        OSL_ENSURE( node::accessWritable <= _aAccessLevel && _aAccessLevel <= node::accessReadonly,"Invalid access level for Node");

        m_aAttributes.setAccess(_aAccessLevel);
    }

    void INode::markMandatory()
    {
        m_aAttributes.markMandatory();
    }

    void INode::markRemovable()
    {
        m_aAttributes.markRemovable();
    }

    void INode::promoteAccessToDefault()
      {
        if (m_aAttributes.isFinalized())
            m_aAttributes.setAccess(node::accessReadonly);

        if ( m_aAttributes.isMandatory())
            m_aAttributes.setRemovability(false,false);
    }

    void INode::forceReadonlyToFinalized()
      {
        if (m_aAttributes.isReadonly())
        {
            m_aAttributes.setAccess(node::accessFinal);
        }
    }

// ------------------------- SearchNode implementation -------------------------
    SearchNode::SearchNode():INode(node::Attributes()){}
    SearchNode::SearchNode(OUString const& aName)
        :INode(aName, node::Attributes()){}

    std::auto_ptr<INode> SearchNode::clone() const {return std::auto_ptr<INode>(new SearchNode(*this));}

    SearchNode::~SearchNode(){}

    //==========================================================================
    //= OPropagateLevels
    //==========================================================================
    /** fills a subtree with the correct level informations
    */
    struct OPropagateLevels : public NodeModification
    {
    public:
        typedef sal_Int16 Level;
        OPropagateLevels(Level _nParentLevel, Level _nParentDefaultLevel)
        : m_nLevel          ( childLevel(_nParentLevel) )
        , m_nDefaultLevel   ( childLevel(_nParentDefaultLevel) )
        {
        }
        virtual void handle(ValueNode&) { /* not interested in value nodes */ }
        virtual void handle(ISubtree& _rSubtree)
        {
            _rSubtree.setLevels(m_nLevel, m_nDefaultLevel);
        }

        static Level childLevel(Level _nLevel)
        {
            OSL_ASSERT(0 > treeop::ALL_LEVELS);
            return (_nLevel > 0) ? _nLevel-1 : _nLevel;
        }
    protected:
        Level   m_nLevel;
        Level   m_nDefaultLevel;
    };

// -------------------------- ISubtree implementation --------------------------
    ISubtree* ISubtree::asISubtree() {return this;}
    ISubtree const* ISubtree::asISubtree() const {return this;}

    //--------------------------------------------------------------------------
    static inline bool adjustLevel(sal_Int16& _rLevel, sal_Int16 _nNewLevel)
    {
        if (_rLevel == treeop::ALL_LEVELS)   return false;
        if (_nNewLevel <= _rLevel &&
            _nNewLevel != treeop::ALL_LEVELS) return false;

        _rLevel = _nNewLevel;
        return true;
    }

    //--------------------------------------------------------------------------
    void ISubtree::setLevels(sal_Int16 _nLevel, sal_Int16 _nDefaultLevels)
    {
        bool bActive = false;

        if (_nLevel && adjustLevel(m_nLevel, _nLevel))
            bActive = true;

        if (_nDefaultLevels && adjustLevel(m_nDefaultLevels, _nDefaultLevels))
            bActive = true;

        // forward the level numbers to any child subtrees we have
        if (bActive)
        {
            OPropagateLevels aPropagate(_nLevel,_nDefaultLevels);
            aPropagate.applyToChildren(*this);
        }
    }

// --------------------------- Subtree implementation ---------------------------
    std::auto_ptr<INode> Subtree::clone() const
    {
        return std::auto_ptr<INode>(new Subtree(*this, treeop::DeepChildCopy()));
    }

    INode* Subtree::doGetChild(OUString const& aName) const
    {
        SearchNode searchObj(aName);

#if OSL_DEBUG_LEVEL > 1
        for (ChildList::iterator it2 = m_aChildren.GetSet().begin();
            it2 != m_aChildren.GetSet().end();
            ++it2)
        {
            INode* pINode = *it2;
            OUString aName2 = pINode->getName();
            volatile int dummy;
            dummy = 0;
        }
#endif

        ChildList::iterator it = m_aChildren.GetSet().find(&searchObj);
        if (it == m_aChildren.GetSet().end())
            return NULL;
        else
            return *it;
    }

    INode* Subtree::addChild(std::auto_ptr<INode> aNode)    // takes ownership
    {
        OUString aName = aNode->getName();
        std::pair<ChildList::iterator, bool> aInserted =
            m_aChildren.GetSet().insert(aNode.get());
        if (aInserted.second)
            aNode.release();
        return *aInserted.first;
    }

    ::std::auto_ptr<INode> Subtree::removeChild(OUString const& aName)
    {
        SearchNode searchObj(aName);
        ChildList::const_iterator it = m_aChildren.GetSet().find(&searchObj);

        ::std::auto_ptr<INode> aReturn;
        if (m_aChildren.GetSet().end() != it)
        {
            aReturn = ::std::auto_ptr<INode>(*it);
            m_aChildren.GetSet().erase(it);
        }
        return aReturn;
    }
//  // -------------------------- ValueNode implementation --------------------------

    void Subtree::forEachChild(NodeAction& anAction) const
    {
        for(ChildList::const_iterator it = m_aChildren.GetSet().begin();
            it != m_aChildren.GetSet().end();
            ++it)
            (**it).dispatch(anAction);
    }

    void Subtree::forEachChild(NodeModification& anAction)
    {
        ChildList::iterator it = m_aChildren.GetSet().begin();
        while( it != m_aChildren.GetSet().end() )
        {
            // modification-safe iteration
            (**it++).dispatch(anAction);
        }
      }

//  // -------------------------- ValueNode implementation --------------------------
    bool ValueNode::setValueType(uno::Type const& _aType)
    {
        if (_aType == this->getValueType()) return true;

        if (!this->isNull()) return false;

        uno::TypeClass eTC = this->getValueType().getTypeClass();
        if (eTC != uno::TypeClass_VOID && eTC != uno::TypeClass_ANY)
            return false;

        m_aValuePair = AnyPair(_aType);

        OSL_ASSERT(_aType == this->getValueType());

        return true;
    }
    bool ValueNode::setValue(Any const& _aValue)
    {
        sal_Bool bRet = m_aValuePair.setFirst(_aValue);
        if (bRet) this->markAsDefault(false);
        return !! bRet;
    }

    bool ValueNode::changeDefault(Any const& _aValue)
    {
        return !! m_aValuePair.setSecond(_aValue);
    }

    void ValueNode::setDefault()
    {
        OSL_PRECOND( hasUsableDefault(), "No default value to set for value node");
        m_aValuePair.clear( selectValue() );
        this->markAsDefault();
        OSL_POSTCOND( isDefault(), "Could not set value node to default");
    }

    void ValueNode::promoteToDefault()
    {
        if (!isDefault())
        {
            if (m_aValuePair.hasFirst())
            {
                OSL_VERIFY( m_aValuePair.setSecond(m_aValuePair.getFirst()) );
                m_aValuePair.clear( selectValue() );
            }
            else
            {
                m_aValuePair.clear( selectDeflt() );
                OSL_ASSERT( m_aValuePair.isNull() );
            }

            this->markAsDefault();

            OSL_ENSURE( !m_aValuePair.hasFirst(), "Leaving orphaned value in after promoting to default");
        }
        else
            OSL_ENSURE( !m_aValuePair.hasFirst(), "Orphaned value in default node won't be promoted");

        OSL_POSTCOND( isDefault(), "Could not promote value node to default");
    }

    std::auto_ptr<INode> ValueNode::clone() const
    {
        return std::auto_ptr<INode>(new ValueNode(*this));
    }

    ValueNode* ValueNode::asValueNode() {return this;}
    ValueNode const* ValueNode::asValueNode() const {return this;}

} // namespace configmgr

<|endoftext|>


<commit_before>/*
 *  Copyright 2018 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
#include "test/scenario/stats_collection.h"

#include "test/gtest.h"
#include "test/scenario/scenario.h"

namespace webrtc {
namespace test {
namespace {
void CreateAnalyzedStream(Scenario* s,
                          NetworkSimulationConfig network_config,
                          VideoQualityAnalyzer* analyzer,
                          CallStatsCollectors* collectors) {
  VideoStreamConfig config;
  config.encoder.codec = VideoStreamConfig::Encoder::Codec::kVideoCodecVP8;
  config.encoder.implementation =
      VideoStreamConfig::Encoder::Implementation::kSoftware;
  config.hooks.frame_pair_handlers = {analyzer->Handler()};
  auto* caller = s->CreateClient("caller", CallClientConfig());
  auto* callee = s->CreateClient("callee", CallClientConfig());
  auto route =
      s->CreateRoutes(caller, {s->CreateSimulationNode(network_config)}, callee,
                      {s->CreateSimulationNode(NetworkSimulationConfig())});
  VideoStreamPair* video = s->CreateVideoStream(route->forward(), config);
  auto* audio = s->CreateAudioStream(route->forward(), AudioStreamConfig());
  s->Every(TimeDelta::Seconds(1), [=] {
    collectors->call.AddStats(caller->GetStats());
    collectors->video_send.AddStats(video->send()->GetStats(), s->Now());
    collectors->audio_receive.AddStats(audio->receive()->GetStats());

    // Querying the video stats from within the expected runtime environment
    // (i.e. the TQ that belongs to the CallClient, not the Scenario TQ that
    // we're currently on).
    VideoReceiveStream::Stats video_receive_stats;
    auto* video_stream = video->receive();
    callee->SendTask([&video_stream, &video_receive_stats]() {
      video_receive_stats = video_stream->GetStats();
    });
    collectors->video_receive.AddStats(video_receive_stats);
  });
}
}  // namespace

TEST(ScenarioAnalyzerTest, PsnrIsHighWhenNetworkIsGood) {
  VideoQualityAnalyzer analyzer;
  CallStatsCollectors stats;
  {
    Scenario s;
    NetworkSimulationConfig good_network;
    good_network.bandwidth = DataRate::KilobitsPerSec(1000);
    CreateAnalyzedStream(&s, good_network, &analyzer, &stats);
    s.RunFor(TimeDelta::Seconds(3));
  }
  // This is a change detecting test, the targets are based on previous runs and
  // might change due to changes in configuration and encoder etc. The main
  // purpose is to show how the stats can be used. To avoid being overly
  // sensistive to change, the ranges are chosen to be quite large.
  EXPECT_NEAR(analyzer.stats().psnr_with_freeze.Mean(), 43, 10);
  EXPECT_NEAR(stats.call.stats().target_rate.Mean().kbps(), 700, 300);
  EXPECT_NEAR(stats.video_send.stats().media_bitrate.Mean().kbps(), 500, 200);
  EXPECT_NEAR(stats.video_receive.stats().resolution.Mean(), 180, 10);
  EXPECT_NEAR(stats.audio_receive.stats().jitter_buffer.Mean().ms(), 40, 20);
}

TEST(ScenarioAnalyzerTest, PsnrIsLowWhenNetworkIsBad) {
  VideoQualityAnalyzer analyzer;
  CallStatsCollectors stats;
  {
    Scenario s;
    NetworkSimulationConfig bad_network;
    bad_network.bandwidth = DataRate::KilobitsPerSec(100);
    bad_network.loss_rate = 0.02;
    CreateAnalyzedStream(&s, bad_network, &analyzer, &stats);
    s.RunFor(TimeDelta::Seconds(3));
  }
  // This is a change detecting test, the targets are based on previous runs and
  // might change due to changes in configuration and encoder etc.
  EXPECT_NEAR(analyzer.stats().psnr_with_freeze.Mean(), 20, 10);
  EXPECT_NEAR(stats.call.stats().target_rate.Mean().kbps(), 75, 50);
  EXPECT_NEAR(stats.video_send.stats().media_bitrate.Mean().kbps(), 100, 50);
  EXPECT_NEAR(stats.video_receive.stats().resolution.Mean(), 180, 10);
  EXPECT_NEAR(stats.audio_receive.stats().jitter_buffer.Mean().ms(), 250, 150);
}

TEST(ScenarioAnalyzerTest, CountsCapturedButNotRendered) {
  VideoQualityAnalyzer analyzer;
  CallStatsCollectors stats;
  {
    Scenario s;
    NetworkSimulationConfig long_delays;
    long_delays.delay = TimeDelta::Seconds(5);
    CreateAnalyzedStream(&s, long_delays, &analyzer, &stats);
    // Enough time to send frames but not enough to deliver.
    s.RunFor(TimeDelta::Millis(100));
  }
  EXPECT_GE(analyzer.stats().capture.count, 1);
  EXPECT_EQ(analyzer.stats().render.count, 0);
}
}  // namespace test
}  // namespace webrtc
<commit_msg>Update PsnrIsLowWhenNetworkIsBad test jitter_buffer mean value, as the congestion window default config changed.<commit_after>/*
 *  Copyright 2018 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
#include "test/scenario/stats_collection.h"

#include "test/gtest.h"
#include "test/scenario/scenario.h"

namespace webrtc {
namespace test {
namespace {
void CreateAnalyzedStream(Scenario* s,
                          NetworkSimulationConfig network_config,
                          VideoQualityAnalyzer* analyzer,
                          CallStatsCollectors* collectors) {
  VideoStreamConfig config;
  config.encoder.codec = VideoStreamConfig::Encoder::Codec::kVideoCodecVP8;
  config.encoder.implementation =
      VideoStreamConfig::Encoder::Implementation::kSoftware;
  config.hooks.frame_pair_handlers = {analyzer->Handler()};
  auto* caller = s->CreateClient("caller", CallClientConfig());
  auto* callee = s->CreateClient("callee", CallClientConfig());
  auto route =
      s->CreateRoutes(caller, {s->CreateSimulationNode(network_config)}, callee,
                      {s->CreateSimulationNode(NetworkSimulationConfig())});
  VideoStreamPair* video = s->CreateVideoStream(route->forward(), config);
  auto* audio = s->CreateAudioStream(route->forward(), AudioStreamConfig());
  s->Every(TimeDelta::Seconds(1), [=] {
    collectors->call.AddStats(caller->GetStats());
    collectors->video_send.AddStats(video->send()->GetStats(), s->Now());
    collectors->audio_receive.AddStats(audio->receive()->GetStats());

    // Querying the video stats from within the expected runtime environment
    // (i.e. the TQ that belongs to the CallClient, not the Scenario TQ that
    // we're currently on).
    VideoReceiveStream::Stats video_receive_stats;
    auto* video_stream = video->receive();
    callee->SendTask([&video_stream, &video_receive_stats]() {
      video_receive_stats = video_stream->GetStats();
    });
    collectors->video_receive.AddStats(video_receive_stats);
  });
}
}  // namespace

TEST(ScenarioAnalyzerTest, PsnrIsHighWhenNetworkIsGood) {
  VideoQualityAnalyzer analyzer;
  CallStatsCollectors stats;
  {
    Scenario s;
    NetworkSimulationConfig good_network;
    good_network.bandwidth = DataRate::KilobitsPerSec(1000);
    CreateAnalyzedStream(&s, good_network, &analyzer, &stats);
    s.RunFor(TimeDelta::Seconds(3));
  }
  // This is a change detecting test, the targets are based on previous runs and
  // might change due to changes in configuration and encoder etc. The main
  // purpose is to show how the stats can be used. To avoid being overly
  // sensistive to change, the ranges are chosen to be quite large.
  EXPECT_NEAR(analyzer.stats().psnr_with_freeze.Mean(), 43, 10);
  EXPECT_NEAR(stats.call.stats().target_rate.Mean().kbps(), 700, 300);
  EXPECT_NEAR(stats.video_send.stats().media_bitrate.Mean().kbps(), 500, 200);
  EXPECT_NEAR(stats.video_receive.stats().resolution.Mean(), 180, 10);
  EXPECT_NEAR(stats.audio_receive.stats().jitter_buffer.Mean().ms(), 40, 20);
}

TEST(ScenarioAnalyzerTest, PsnrIsLowWhenNetworkIsBad) {
  VideoQualityAnalyzer analyzer;
  CallStatsCollectors stats;
  {
    Scenario s;
    NetworkSimulationConfig bad_network;
    bad_network.bandwidth = DataRate::KilobitsPerSec(100);
    bad_network.loss_rate = 0.02;
    CreateAnalyzedStream(&s, bad_network, &analyzer, &stats);
    s.RunFor(TimeDelta::Seconds(3));
  }
  // This is a change detecting test, the targets are based on previous runs and
  // might change due to changes in configuration and encoder etc.
  EXPECT_NEAR(analyzer.stats().psnr_with_freeze.Mean(), 20, 10);
  EXPECT_NEAR(stats.call.stats().target_rate.Mean().kbps(), 75, 50);
  EXPECT_NEAR(stats.video_send.stats().media_bitrate.Mean().kbps(), 100, 50);
  EXPECT_NEAR(stats.video_receive.stats().resolution.Mean(), 180, 10);
  EXPECT_NEAR(stats.audio_receive.stats().jitter_buffer.Mean().ms(), 250, 200);
}

TEST(ScenarioAnalyzerTest, CountsCapturedButNotRendered) {
  VideoQualityAnalyzer analyzer;
  CallStatsCollectors stats;
  {
    Scenario s;
    NetworkSimulationConfig long_delays;
    long_delays.delay = TimeDelta::Seconds(5);
    CreateAnalyzedStream(&s, long_delays, &analyzer, &stats);
    // Enough time to send frames but not enough to deliver.
    s.RunFor(TimeDelta::Millis(100));
  }
  EXPECT_GE(analyzer.stats().capture.count, 1);
  EXPECT_EQ(analyzer.stats().render.count, 0);
}
}  // namespace test
}  // namespace webrtc
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the $MODULE$ of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtGui>
#include <QtTest>

class tst_QTouchEvent : public QObject
{
    Q_OBJECT
public:
    tst_QTouchEvent() { }
    ~tst_QTouchEvent() { }

private slots:
    void touchDisabledByDefault();
    void touchEventAcceptedByDefault();
};

void tst_QTouchEvent::touchDisabledByDefault()
{
    // the widget attribute is not enabled by default
    QWidget widget;
    QVERIFY(!widget.testAttribute(Qt::WA_AcceptTouchEvents));

    // events should not be accepted since they are not enabled
    QList<QTouchEvent::TouchPoint> touchPoints;
    touchPoints.append(QTouchEvent::TouchPoint(0));
    QTouchEvent touchEvent(QEvent::TouchBegin,
                           Qt::NoModifier,
                           Qt::TouchPointPressed,
                           touchPoints);
    bool res = QApplication::sendEvent(&widget, &touchEvent)
               && touchEvent.isAccepted();
    QVERIFY(!res);
}

void tst_QTouchEvent::touchEventAcceptedByDefault()
{
    // enabling touch events should automatically accept touch events
    QWidget widget;
    widget.setAttribute(Qt::WA_AcceptTouchEvents);

    QList<QTouchEvent::TouchPoint> touchPoints;
    touchPoints.append(QTouchEvent::TouchPoint(0));
    QTouchEvent touchEvent(QEvent::TouchBegin,
                           Qt::NoModifier,
                           Qt::TouchPointPressed,
                           touchPoints);
    bool res = QApplication::sendEvent(&widget, &touchEvent)
               && touchEvent.isAccepted();
    QVERIFY(res);
}

QTEST_MAIN(tst_QTouchEvent)

#include "tst_qtouchevent.moc"
<commit_msg>make QTouchEvent autotest pass<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the $MODULE$ of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtGui>
#include <QtTest>

class tst_QTouchEvent : public QObject
{
    Q_OBJECT
public:
    tst_QTouchEvent() { }
    ~tst_QTouchEvent() { }

private slots:
    void touchDisabledByDefault();
    void touchEventAcceptedByDefault();
};

void tst_QTouchEvent::touchDisabledByDefault()
{
    // the widget attribute is not enabled by default
    QWidget widget;
    QVERIFY(!widget.testAttribute(Qt::WA_AcceptTouchEvents));

    // events should not be accepted since they are not enabled
    QList<QTouchEvent::TouchPoint> touchPoints;
    touchPoints.append(QTouchEvent::TouchPoint(0));
    QTouchEvent touchEvent(QEvent::TouchBegin,
                           Qt::NoModifier,
                           Qt::TouchPointPressed,
                           touchPoints);
    bool res = QApplication::sendEvent(&widget, &touchEvent);
    QVERIFY(!res);
    QVERIFY(!touchEvent.isAccepted());
}

void tst_QTouchEvent::touchEventAcceptedByDefault()
{
    // enabling touch events should automatically accept touch events
    QWidget widget;
    widget.setAttribute(Qt::WA_AcceptTouchEvents);

    QList<QTouchEvent::TouchPoint> touchPoints;
    touchPoints.append(QTouchEvent::TouchPoint(0));
    QTouchEvent touchEvent(QEvent::TouchBegin,
                           Qt::NoModifier,
                           Qt::TouchPointPressed,
                           touchPoints);
    bool res = QApplication::sendEvent(&widget, &touchEvent);
    QVERIFY(!res); // not handled...
    QVERIFY(touchEvent.isAccepted()); // but accepted
}

QTEST_MAIN(tst_QTouchEvent)

#include "tst_qtouchevent.moc"
<|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 "chrome/renderer/devtools_agent.h"

#include <map>

#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/devtools_agent_filter.h"
#include "chrome/renderer/render_view.h"
#include "grit/webkit_chromium_resources.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsAgent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebPoint.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/glue/webkit_glue.h"

using WebKit::WebDevToolsAgent;
using WebKit::WebDevToolsAgentClient;
using WebKit::WebPoint;
using WebKit::WebString;
using WebKit::WebCString;
using WebKit::WebVector;
using WebKit::WebView;

namespace {

class WebKitClientMessageLoopImpl
    : public WebDevToolsAgentClient::WebKitClientMessageLoop {
 public:
  WebKitClientMessageLoopImpl() : message_loop_(MessageLoop::current()) { }
  virtual ~WebKitClientMessageLoopImpl() {
    message_loop_ = NULL;
  }
  virtual void run() {
    bool old_state = message_loop_->NestableTasksAllowed();
    message_loop_->SetNestableTasksAllowed(true);
    message_loop_->Run();
    message_loop_->SetNestableTasksAllowed(old_state);
  }
  virtual void quitNow() {
    message_loop_->QuitNow();
  }
 private:
  MessageLoop* message_loop_;
};

} //  namespace

// static
std::map<int, DevToolsAgent*> DevToolsAgent::agent_for_routing_id_;

DevToolsAgent::DevToolsAgent(int routing_id, RenderView* render_view)
    : routing_id_(routing_id),
      render_view_(render_view) {
  agent_for_routing_id_[routing_id] = this;

  CommandLine* cmd = CommandLine::ForCurrentProcess();
  expose_v8_debugger_protocol_ =cmd->HasSwitch(switches::kRemoteShellPort);
}

DevToolsAgent::~DevToolsAgent() {
  agent_for_routing_id_.erase(routing_id_);
}

void DevToolsAgent::OnNavigate() {
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent) {
    web_agent->didNavigate();
  }
}

// Called on the Renderer thread.
bool DevToolsAgent::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(DevToolsAgent, message)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_Attach, OnAttach)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_Detach, OnDetach)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_FrontendLoaded, OnFrontendLoaded)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DispatchOnInspectorBackend,
                        OnDispatchOnInspectorBackend)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_InspectElement, OnInspectElement)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_SetApuAgentEnabled,
                        OnSetApuAgentEnabled)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void DevToolsAgent::sendMessageToInspectorFrontend(
    const WebKit::WebString& message) {
  IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
      routing_id_,
      DevToolsClientMsg_DispatchOnInspectorFrontend(message.utf8()));
  render_view_->Send(m);
}

void DevToolsAgent::sendDebuggerOutput(const WebKit::WebString& data) {
  IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
      routing_id_,
      DevToolsClientMsg_DebuggerOutput(data.utf8()));
  render_view_->Send(m);
}

void DevToolsAgent::sendDispatchToAPU(const WebKit::WebString& data) {
  IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
      routing_id_,
      DevToolsClientMsg_DispatchToAPU(data.utf8()));
  render_view_->Send(m);
}

int DevToolsAgent::hostIdentifier() {
  return routing_id_;
}

void DevToolsAgent::forceRepaint() {
  render_view_->GenerateFullRepaint();
}

void DevToolsAgent::runtimeFeatureStateChanged(
    const WebKit::WebString& feature,
    bool enabled) {
  render_view_->Send(new ViewHostMsg_DevToolsRuntimePropertyChanged(
      routing_id_,
      feature.utf8(),
      enabled ? "true" : "false"));
}

void DevToolsAgent::runtimePropertyChanged(
    const WebKit::WebString& name,
    const WebKit::WebString& value) {
  render_view_->Send(new ViewHostMsg_DevToolsRuntimePropertyChanged(
      routing_id_,
      name.utf8(),
      value.utf8()));
}

WebCString DevToolsAgent::injectedScriptSource() {
  base::StringPiece injectjsWebkit =
      webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_WEBKIT_JS);
  return WebCString(injectjsWebkit.data(), injectjsWebkit.length());
}

WebCString DevToolsAgent::debuggerScriptSource() {
  base::StringPiece debuggerScriptjs =
      webkit_glue::GetDataResource(IDR_DEVTOOLS_DEBUGGER_SCRIPT_JS);
  return WebCString(debuggerScriptjs.data(), debuggerScriptjs.length());
}

WebKit::WebDevToolsAgentClient::WebKitClientMessageLoop*
    DevToolsAgent::createClientMessageLoop() {
  return new WebKitClientMessageLoopImpl();
}

bool DevToolsAgent::exposeV8DebuggerProtocol() {
  return expose_v8_debugger_protocol_;
}

// static
DevToolsAgent* DevToolsAgent::FromHostId(int host_id) {
  std::map<int, DevToolsAgent*>::iterator it =
      agent_for_routing_id_.find(host_id);
  if (it != agent_for_routing_id_.end()) {
    return it->second;
  }
  return NULL;
}

void DevToolsAgent::OnAttach(
    const DevToolsRuntimeProperties& runtime_properties) {
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent) {
    web_agent->attach();
    for (DevToolsRuntimeProperties::const_iterator it =
             runtime_properties.begin();
         it != runtime_properties.end(); ++it) {
      web_agent->setRuntimeFeatureEnabled(WebString::fromUTF8(it->first),
                                          it->second == "true");
    }
  }
}

void DevToolsAgent::OnDetach() {
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent)
    web_agent->detach();
}

void DevToolsAgent::OnFrontendLoaded() {
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent)
    web_agent->frontendLoaded();
}

void DevToolsAgent::OnDispatchOnInspectorBackend(const std::string& message) {
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent)
    web_agent->dispatchOnInspectorBackend(WebString::fromUTF8(message));
}

void DevToolsAgent::OnInspectElement(int x, int y) {
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent) {
    web_agent->attach();
    web_agent->inspectElementAt(WebPoint(x, y));
  }
}

void DevToolsAgent::OnSetApuAgentEnabled(bool enabled) {
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent)
    web_agent->setRuntimeFeatureEnabled("apu-agent", enabled);
}

WebDevToolsAgent* DevToolsAgent::GetWebAgent() {
  WebView* web_view = render_view_->webview();
  if (!web_view)
    return NULL;
  return web_view->devToolsAgent();
}
<commit_msg>DevTools: complete migration to runtime properties started upstream.<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 "chrome/renderer/devtools_agent.h"

#include <map>

#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/devtools_agent_filter.h"
#include "chrome/renderer/render_view.h"
#include "grit/webkit_chromium_resources.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsAgent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebPoint.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/glue/webkit_glue.h"

using WebKit::WebDevToolsAgent;
using WebKit::WebDevToolsAgentClient;
using WebKit::WebPoint;
using WebKit::WebString;
using WebKit::WebCString;
using WebKit::WebVector;
using WebKit::WebView;

namespace {

class WebKitClientMessageLoopImpl
    : public WebDevToolsAgentClient::WebKitClientMessageLoop {
 public:
  WebKitClientMessageLoopImpl() : message_loop_(MessageLoop::current()) { }
  virtual ~WebKitClientMessageLoopImpl() {
    message_loop_ = NULL;
  }
  virtual void run() {
    bool old_state = message_loop_->NestableTasksAllowed();
    message_loop_->SetNestableTasksAllowed(true);
    message_loop_->Run();
    message_loop_->SetNestableTasksAllowed(old_state);
  }
  virtual void quitNow() {
    message_loop_->QuitNow();
  }
 private:
  MessageLoop* message_loop_;
};

} //  namespace

// static
std::map<int, DevToolsAgent*> DevToolsAgent::agent_for_routing_id_;

DevToolsAgent::DevToolsAgent(int routing_id, RenderView* render_view)
    : routing_id_(routing_id),
      render_view_(render_view) {
  agent_for_routing_id_[routing_id] = this;

  CommandLine* cmd = CommandLine::ForCurrentProcess();
  expose_v8_debugger_protocol_ =cmd->HasSwitch(switches::kRemoteShellPort);
}

DevToolsAgent::~DevToolsAgent() {
  agent_for_routing_id_.erase(routing_id_);
}

void DevToolsAgent::OnNavigate() {
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent) {
    web_agent->didNavigate();
  }
}

// Called on the Renderer thread.
bool DevToolsAgent::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(DevToolsAgent, message)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_Attach, OnAttach)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_Detach, OnDetach)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_FrontendLoaded, OnFrontendLoaded)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DispatchOnInspectorBackend,
                        OnDispatchOnInspectorBackend)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_InspectElement, OnInspectElement)
    IPC_MESSAGE_HANDLER(DevToolsAgentMsg_SetApuAgentEnabled,
                        OnSetApuAgentEnabled)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void DevToolsAgent::sendMessageToInspectorFrontend(
    const WebKit::WebString& message) {
  IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
      routing_id_,
      DevToolsClientMsg_DispatchOnInspectorFrontend(message.utf8()));
  render_view_->Send(m);
}

void DevToolsAgent::sendDebuggerOutput(const WebKit::WebString& data) {
  IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
      routing_id_,
      DevToolsClientMsg_DebuggerOutput(data.utf8()));
  render_view_->Send(m);
}

void DevToolsAgent::sendDispatchToAPU(const WebKit::WebString& data) {
  IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(
      routing_id_,
      DevToolsClientMsg_DispatchToAPU(data.utf8()));
  render_view_->Send(m);
}

int DevToolsAgent::hostIdentifier() {
  return routing_id_;
}

void DevToolsAgent::forceRepaint() {
  render_view_->GenerateFullRepaint();
}

void DevToolsAgent::runtimeFeatureStateChanged(
    const WebKit::WebString& feature,
    bool enabled) {
  render_view_->Send(new ViewHostMsg_DevToolsRuntimePropertyChanged(
      routing_id_,
      feature.utf8(),
      enabled ? "true" : "false"));
}

void DevToolsAgent::runtimePropertyChanged(
    const WebKit::WebString& name,
    const WebKit::WebString& value) {
  render_view_->Send(new ViewHostMsg_DevToolsRuntimePropertyChanged(
      routing_id_,
      name.utf8(),
      value.utf8()));
}

WebCString DevToolsAgent::injectedScriptSource() {
  base::StringPiece injectjsWebkit =
      webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_WEBKIT_JS);
  return WebCString(injectjsWebkit.data(), injectjsWebkit.length());
}

WebCString DevToolsAgent::debuggerScriptSource() {
  base::StringPiece debuggerScriptjs =
      webkit_glue::GetDataResource(IDR_DEVTOOLS_DEBUGGER_SCRIPT_JS);
  return WebCString(debuggerScriptjs.data(), debuggerScriptjs.length());
}

WebKit::WebDevToolsAgentClient::WebKitClientMessageLoop*
    DevToolsAgent::createClientMessageLoop() {
  return new WebKitClientMessageLoopImpl();
}

bool DevToolsAgent::exposeV8DebuggerProtocol() {
  return expose_v8_debugger_protocol_;
}

// static
DevToolsAgent* DevToolsAgent::FromHostId(int host_id) {
  std::map<int, DevToolsAgent*>::iterator it =
      agent_for_routing_id_.find(host_id);
  if (it != agent_for_routing_id_.end()) {
    return it->second;
  }
  return NULL;
}

void DevToolsAgent::OnAttach(
    const DevToolsRuntimeProperties& runtime_properties) {
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent) {
    web_agent->attach();
    for (DevToolsRuntimeProperties::const_iterator it =
             runtime_properties.begin();
         it != runtime_properties.end(); ++it) {
      web_agent->setRuntimeProperty(WebString::fromUTF8(it->first),
                                    WebString::fromUTF8(it->second));
    }
  }
}

void DevToolsAgent::OnDetach() {
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent)
    web_agent->detach();
}

void DevToolsAgent::OnFrontendLoaded() {
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent)
    web_agent->frontendLoaded();
}

void DevToolsAgent::OnDispatchOnInspectorBackend(const std::string& message) {
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent)
    web_agent->dispatchOnInspectorBackend(WebString::fromUTF8(message));
}

void DevToolsAgent::OnInspectElement(int x, int y) {
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent) {
    web_agent->attach();
    web_agent->inspectElementAt(WebPoint(x, y));
  }
}

void DevToolsAgent::OnSetApuAgentEnabled(bool enabled) {
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent)
    web_agent->setRuntimeProperty("apu-agent", enabled ?
        WebString::fromUTF8("true") : WebString::fromUTF8("false"));
}

WebDevToolsAgent* DevToolsAgent::GetWebAgent() {
  WebView* web_view = render_view_->webview();
  if (!web_view)
    return NULL;
  return web_view->devToolsAgent();
}
<|endoftext|>