<commit_before>//===- bugpoint.cpp - The LLVM Bugpoint utility ---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is an automated compiler debugger tool.  It is used to narrow
// down miscompilations and crash problems to a specific pass in the compiler,
// and the specific Module or Function input that is causing the problem.
//
//===----------------------------------------------------------------------===//

#include "BugDriver.h"
#include "ToolRunner.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/LLVMContext.h"
#include "llvm/PassManager.h"
#include "llvm/Support/PassNameParser.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/Valgrind.h"
#include "llvm/LinkAllVMCore.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"

//Enable this macro to debug bugpoint itself.
//#define DEBUG_BUGPOINT 1

using namespace llvm;

static cl::opt<bool>
FindBugs("find-bugs", cl::desc("Run many different optimization sequences "
                               "on program to find bugs"), cl::init(false));

static cl::list<std::string>
InputFilenames(cl::Positional, cl::OneOrMore,
               cl::desc("<input llvm ll/bc files>"));

static cl::opt<unsigned>
TimeoutValue("timeout", cl::init(300), cl::value_desc("seconds"),
             cl::desc("Number of seconds program is allowed to run before it "
                      "is killed (default is 300s), 0 disables timeout"));

static cl::opt<int>
MemoryLimit("mlimit", cl::init(-1), cl::value_desc("MBytes"),
             cl::desc("Maximum amount of memory to use. 0 disables check."
                      " Defaults to 100MB (800MB under valgrind)."));

static cl::opt<bool>
UseValgrind("enable-valgrind",
            cl::desc("Run optimizations through valgrind"));

// The AnalysesList is automatically populated with registered Passes by the
// PassNameParser.
//
static cl::list<const PassInfo*, bool, PassNameParser>
PassList(cl::desc("Passes available:"), cl::ZeroOrMore);

static cl::opt<bool>
StandardCompileOpts("std-compile-opts",
                   cl::desc("Include the standard compile time optimizations"));

static cl::opt<bool>
StandardLinkOpts("std-link-opts",
                 cl::desc("Include the standard link time optimizations"));

static cl::opt<bool>
OptLevelO1("O1",
           cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));

static cl::opt<bool>
OptLevelO2("O2",
           cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));

static cl::opt<bool>
OptLevelO3("O3",
           cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));

static cl::opt<std::string>
OverrideTriple("mtriple", cl::desc("Override target triple for module"));

/// BugpointIsInterrupted - Set to true when the user presses ctrl-c.
bool llvm::BugpointIsInterrupted = false;

#ifndef DEBUG_BUGPOINT
static void BugpointInterruptFunction() {
  BugpointIsInterrupted = true;
}
#endif

// Hack to capture a pass list.
namespace {
  class AddToDriver : public FunctionPassManager {
    BugDriver &D;
  public:
    AddToDriver(BugDriver &_D) : FunctionPassManager(0), D(_D) {}

    virtual void add(Pass *P) {
      const void *ID = P->getPassID();
      const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(ID);
      D.addPass(PI->getPassArgument());
    }
  };
}

int main(int argc, char **argv) {
#ifndef DEBUG_BUGPOINT
  llvm::sys::PrintStackTraceOnErrorSignal();
  llvm::PrettyStackTraceProgram X(argc, argv);
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
#endif

  // Initialize passes
  PassRegistry &Registry = *PassRegistry::getPassRegistry();
  initializeCore(Registry);
  initializeScalarOpts(Registry);
  initializeIPO(Registry);
  initializeAnalysis(Registry);
  initializeIPA(Registry);
  initializeTransformUtils(Registry);
  initializeInstCombine(Registry);
  initializeInstrumentation(Registry);
  initializeTarget(Registry);

  cl::ParseCommandLineOptions(argc, argv,
                              "LLVM automatic testcase reducer. See\nhttp://"
                              "llvm.org/cmds/bugpoint.html"
                              " for more information.\n");
#ifndef DEBUG_BUGPOINT
  sys::SetInterruptFunction(BugpointInterruptFunction);
#endif

  LLVMContext& Context = getGlobalContext();
  // If we have an override, set it and then track the triple we want Modules
  // to use.
  if (!OverrideTriple.empty()) {
    TargetTriple.setTriple(Triple::normalize(OverrideTriple));
    outs() << "Override triple set to '" << TargetTriple.getTriple() << "'\n";
  }

  if (MemoryLimit < 0) {
    // Set the default MemoryLimit.  Be sure to update the flag's description if
    // you change this.
    if (sys::RunningOnValgrind() || UseValgrind)
      MemoryLimit = 800;
    else
      MemoryLimit = 100;
  }

  BugDriver D(argv[0], FindBugs, TimeoutValue, MemoryLimit,
              UseValgrind, Context);
  if (D.addSources(InputFilenames)) return 1;

  AddToDriver PM(D);
  if (StandardCompileOpts) {
    PassManagerBuilder Builder;
    Builder.OptLevel = 3;
    Builder.Inliner = createFunctionInliningPass();
    Builder.populateModulePassManager(PM);
  }

  if (StandardLinkOpts) {
    PassManagerBuilder Builder;
    Builder.populateLTOPassManager(PM, /*Internalize=*/true,
                                   /*RunInliner=*/true);
  }

  if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
    PassManagerBuilder Builder;
    if (OptLevelO1)
      Builder.Inliner = createAlwaysInlinerPass();
    else if (OptLevelO2)
      Builder.Inliner = createFunctionInliningPass(225);
    else
      Builder.Inliner = createFunctionInliningPass(275);

    // Note that although clang/llvm-gcc use two separate passmanagers
    // here, it shouldn't normally make a difference.
    Builder.populateFunctionPassManager(PM);
    Builder.populateModulePassManager(PM);
  }

  for (std::vector<const PassInfo*>::iterator I = PassList.begin(),
         E = PassList.end();
       I != E; ++I) {
    const PassInfo* PI = *I;
    D.addPass(PI->getPassArgument());
  }

  // Bugpoint has the ability of generating a plethora of core files, so to
  // avoid filling up the disk, we prevent it
#ifndef DEBUG_BUGPOINT
  sys::Process::PreventCoreFiles();
#endif

  std::string Error;
  bool Failure = D.run(Error);
  if (!Error.empty()) {
    errs() << Error;
    return 1;
  }
  return Failure;
}
<commit_msg>Allow bugpoint to recognize -bb-vectorize<commit_after>//===- bugpoint.cpp - The LLVM Bugpoint utility ---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program is an automated compiler debugger tool.  It is used to narrow
// down miscompilations and crash problems to a specific pass in the compiler,
// and the specific Module or Function input that is causing the problem.
//
//===----------------------------------------------------------------------===//

#include "BugDriver.h"
#include "ToolRunner.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/LLVMContext.h"
#include "llvm/PassManager.h"
#include "llvm/Support/PassNameParser.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/Valgrind.h"
#include "llvm/LinkAllVMCore.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"

//Enable this macro to debug bugpoint itself.
//#define DEBUG_BUGPOINT 1

using namespace llvm;

static cl::opt<bool>
FindBugs("find-bugs", cl::desc("Run many different optimization sequences "
                               "on program to find bugs"), cl::init(false));

static cl::list<std::string>
InputFilenames(cl::Positional, cl::OneOrMore,
               cl::desc("<input llvm ll/bc files>"));

static cl::opt<unsigned>
TimeoutValue("timeout", cl::init(300), cl::value_desc("seconds"),
             cl::desc("Number of seconds program is allowed to run before it "
                      "is killed (default is 300s), 0 disables timeout"));

static cl::opt<int>
MemoryLimit("mlimit", cl::init(-1), cl::value_desc("MBytes"),
             cl::desc("Maximum amount of memory to use. 0 disables check."
                      " Defaults to 100MB (800MB under valgrind)."));

static cl::opt<bool>
UseValgrind("enable-valgrind",
            cl::desc("Run optimizations through valgrind"));

// The AnalysesList is automatically populated with registered Passes by the
// PassNameParser.
//
static cl::list<const PassInfo*, bool, PassNameParser>
PassList(cl::desc("Passes available:"), cl::ZeroOrMore);

static cl::opt<bool>
StandardCompileOpts("std-compile-opts",
                   cl::desc("Include the standard compile time optimizations"));

static cl::opt<bool>
StandardLinkOpts("std-link-opts",
                 cl::desc("Include the standard link time optimizations"));

static cl::opt<bool>
OptLevelO1("O1",
           cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));

static cl::opt<bool>
OptLevelO2("O2",
           cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));

static cl::opt<bool>
OptLevelO3("O3",
           cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));

static cl::opt<std::string>
OverrideTriple("mtriple", cl::desc("Override target triple for module"));

/// BugpointIsInterrupted - Set to true when the user presses ctrl-c.
bool llvm::BugpointIsInterrupted = false;

#ifndef DEBUG_BUGPOINT
static void BugpointInterruptFunction() {
  BugpointIsInterrupted = true;
}
#endif

// Hack to capture a pass list.
namespace {
  class AddToDriver : public FunctionPassManager {
    BugDriver &D;
  public:
    AddToDriver(BugDriver &_D) : FunctionPassManager(0), D(_D) {}

    virtual void add(Pass *P) {
      const void *ID = P->getPassID();
      const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(ID);
      D.addPass(PI->getPassArgument());
    }
  };
}

int main(int argc, char **argv) {
#ifndef DEBUG_BUGPOINT
  llvm::sys::PrintStackTraceOnErrorSignal();
  llvm::PrettyStackTraceProgram X(argc, argv);
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
#endif

  // Initialize passes
  PassRegistry &Registry = *PassRegistry::getPassRegistry();
  initializeCore(Registry);
  initializeScalarOpts(Registry);
  initializeVectorization(Registry);
  initializeIPO(Registry);
  initializeAnalysis(Registry);
  initializeIPA(Registry);
  initializeTransformUtils(Registry);
  initializeInstCombine(Registry);
  initializeInstrumentation(Registry);
  initializeTarget(Registry);

  cl::ParseCommandLineOptions(argc, argv,
                              "LLVM automatic testcase reducer. See\nhttp://"
                              "llvm.org/cmds/bugpoint.html"
                              " for more information.\n");
#ifndef DEBUG_BUGPOINT
  sys::SetInterruptFunction(BugpointInterruptFunction);
#endif

  LLVMContext& Context = getGlobalContext();
  // If we have an override, set it and then track the triple we want Modules
  // to use.
  if (!OverrideTriple.empty()) {
    TargetTriple.setTriple(Triple::normalize(OverrideTriple));
    outs() << "Override triple set to '" << TargetTriple.getTriple() << "'\n";
  }

  if (MemoryLimit < 0) {
    // Set the default MemoryLimit.  Be sure to update the flag's description if
    // you change this.
    if (sys::RunningOnValgrind() || UseValgrind)
      MemoryLimit = 800;
    else
      MemoryLimit = 100;
  }

  BugDriver D(argv[0], FindBugs, TimeoutValue, MemoryLimit,
              UseValgrind, Context);
  if (D.addSources(InputFilenames)) return 1;

  AddToDriver PM(D);
  if (StandardCompileOpts) {
    PassManagerBuilder Builder;
    Builder.OptLevel = 3;
    Builder.Inliner = createFunctionInliningPass();
    Builder.populateModulePassManager(PM);
  }

  if (StandardLinkOpts) {
    PassManagerBuilder Builder;
    Builder.populateLTOPassManager(PM, /*Internalize=*/true,
                                   /*RunInliner=*/true);
  }

  if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
    PassManagerBuilder Builder;
    if (OptLevelO1)
      Builder.Inliner = createAlwaysInlinerPass();
    else if (OptLevelO2)
      Builder.Inliner = createFunctionInliningPass(225);
    else
      Builder.Inliner = createFunctionInliningPass(275);

    // Note that although clang/llvm-gcc use two separate passmanagers
    // here, it shouldn't normally make a difference.
    Builder.populateFunctionPassManager(PM);
    Builder.populateModulePassManager(PM);
  }

  for (std::vector<const PassInfo*>::iterator I = PassList.begin(),
         E = PassList.end();
       I != E; ++I) {
    const PassInfo* PI = *I;
    D.addPass(PI->getPassArgument());
  }

  // Bugpoint has the ability of generating a plethora of core files, so to
  // avoid filling up the disk, we prevent it
#ifndef DEBUG_BUGPOINT
  sys::Process::PreventCoreFiles();
#endif

  std::string Error;
  bool Failure = D.run(Error);
  if (!Error.empty()) {
    errs() << Error;
    return 1;
  }
  return Failure;
}
<|endoftext|>


<commit_before>#ifndef __elxMovingImagePyramidBase_hxx
#define __elxMovingImagePyramidBase_hxx

#include "elxMovingImagePyramidBase.h"

namespace elastix
{
	using namespace itk;

	/**
	 * ******************* BeforeRegistrationBase *******************
	 */

	template <class TElastix>
		void MovingImagePyramidBase<TElastix>
		::BeforeRegistrationBase(void)
	{
		/** Call SetFixedSchedule.*/
		this->SetMovingSchedule();

	} // end BeforeRegistrationBase

	/**
	 * ********************** SetMovingSchedule *********************
	 */

	template <class TElastix>
		void MovingImagePyramidBase<TElastix>
		::SetMovingSchedule(void)
	{
		/** Get the ImageDimension.*/
		unsigned int MovingImageDimension = InputImageType::ImageDimension;
		unsigned int FixedImageDimension = FixedImageType::ImageDimension;

		/** Read numberOfResolutions.*/
		unsigned int numberOfResolutions = 0;
		this->m_Configuration->ReadParameter( numberOfResolutions, "NumberOfResolutions", 0, true );
		if ( numberOfResolutions == 0 )
		{
			xl::xout["error"] << "ERROR: NumberOfResolutions not specified!" << std::endl;
		}
		/** \todo quit program? */

		/** Create a movingSchedule.*/
		ScheduleType movingSchedule( numberOfResolutions, MovingImageDimension );
		movingSchedule.Fill( 0 );

		/** Are FixedPyramidSchedule and/or MovingPyramidSchedule available
		 * in the parameter-file?
		 */
		unsigned int temp_fix = 0;
		unsigned int temp_mov = 0;
		this->m_Configuration->ReadParameter( temp_fix, "FixedPyramidSchedule", 0, true );
		this->m_Configuration->ReadParameter( temp_mov, "MovingPyramidSchedule", 0, true );

		/** If the MovingPyramidSchedule exists:*/
		if ( temp_mov != 0 )
		{
			/** Always set the numberOfLevels first. */
			this->GetAsITKBaseType()->SetNumberOfLevels( numberOfResolutions );

			/** In this case set the movingPyramidSchedule to the
			 * MovingPyramidSchedule given in the parameter-file.
			 */
			for ( unsigned int i = 0; i < numberOfResolutions; i++ )
			{
				for ( unsigned int j = 0; j < MovingImageDimension; j++ )
				{
					this->m_Configuration->ReadParameter(
						movingSchedule[ i ][ j ],
						"MovingPyramidSchedule",
						i * MovingImageDimension + j );
				} // end for MovingImageDimension
			} // end for numberOfResolutions

			/** Set the schedule into this class.*/
			this->GetAsITKBaseType()->SetSchedule( movingSchedule );

		}
		/** If only the FixedPyramidSchedule exists:*/
		else if ( temp_fix != 0 && temp_mov == 0 && FixedImageDimension == MovingImageDimension )
		{
			/** Always set the numberOfLevels first. */
			this->GetAsITKBaseType()->SetNumberOfLevels( numberOfResolutions );

			/** In this case set the movingPyramidSchedule to the
			 * FixedPyramidSchedule given in the parameter-file.
			 */
			for ( unsigned int i = 0; i < numberOfResolutions; i++ )
			{
				for ( unsigned int j = 0; j < MovingImageDimension; j++ )
				{
					this->m_Configuration->ReadParameter(
						movingSchedule[ i ][ j ],
						"FixedPyramidSchedule",
						i * MovingImageDimension + j );
				} // end for MovingImageDimension
			} // end for numberOfResolutions

			/** Set the schedule into this class.*/
			this->GetAsITKBaseType()->SetSchedule( movingSchedule );

		}
		else if ( temp_fix != 0 && temp_mov == 0 && FixedImageDimension != MovingImageDimension )
		{
			xl::xout["warning"] << "WARNING: MovingImagePyramidSchedule is not specified!" << std::endl;
			xl::xout["warning"] << "A default schedule is assumed. " << std::endl;
			}
		/** If both PyramidSchedule's don't exist:*/
		else
		{
			/** In this case set the movingPyramidSchedule to the
			 * default schedule.
			 */
			this->GetAsITKBaseType()->SetNumberOfLevels( numberOfResolutions );

		} // end if

	} // end SetMovingSchedule

} // end namespace elastix

#endif // end #ifndef __elxMovingImagePyramidBase_hxx

<commit_msg>---------------------------------------------------------------------- MS:<commit_after>#ifndef __elxMovingImagePyramidBase_hxx
#define __elxMovingImagePyramidBase_hxx

#include "elxMovingImagePyramidBase.h"

namespace elastix
{
	using namespace itk;

	/**
	 * ******************* BeforeRegistrationBase *******************
	 */

	template <class TElastix>
		void MovingImagePyramidBase<TElastix>
		::BeforeRegistrationBase(void)
	{
		/** Call SetMovingSchedule.*/
		this->SetMovingSchedule();

	} // end BeforeRegistrationBase

	/**
	 * ********************** SetMovingSchedule *********************
	 */

	template <class TElastix>
		void MovingImagePyramidBase<TElastix>
		::SetMovingSchedule(void)
	{
		/** Get the ImageDimension.*/
		unsigned int MovingImageDimension = InputImageType::ImageDimension;
		unsigned int FixedImageDimension = FixedImageType::ImageDimension;

		/** Read numberOfResolutions.*/
		unsigned int numberOfResolutions = 0;
		this->m_Configuration->ReadParameter( numberOfResolutions, "NumberOfResolutions", 0, true );
		if ( numberOfResolutions == 0 )
		{
			xl::xout["error"] << "ERROR: NumberOfResolutions not specified!" << std::endl;
		}
		/** \todo quit program? */

		/** Create a movingSchedule.*/
		ScheduleType movingSchedule( numberOfResolutions, MovingImageDimension );
		movingSchedule.Fill( 0 );

		/** Are FixedPyramidSchedule and/or MovingPyramidSchedule available
		 * in the parameter-file?
		 */
		unsigned int temp_fix = 0;
		unsigned int temp_mov = 0;
		this->m_Configuration->ReadParameter( temp_fix, "FixedPyramidSchedule", 0, true );
		this->m_Configuration->ReadParameter( temp_mov, "MovingPyramidSchedule", 0, true );

		/** If the MovingPyramidSchedule exists:*/
		if ( temp_mov != 0 )
		{
			/** Always set the numberOfLevels first. */
			this->GetAsITKBaseType()->SetNumberOfLevels( numberOfResolutions );

			/** In this case set the movingPyramidSchedule to the
			 * MovingPyramidSchedule given in the parameter-file.
			 */
			for ( unsigned int i = 0; i < numberOfResolutions; i++ )
			{
				for ( unsigned int j = 0; j < MovingImageDimension; j++ )
				{
					this->m_Configuration->ReadParameter(
						movingSchedule[ i ][ j ],
						"MovingPyramidSchedule",
						i * MovingImageDimension + j );
				} // end for MovingImageDimension
			} // end for numberOfResolutions

			/** Set the schedule into this class.*/
			this->GetAsITKBaseType()->SetSchedule( movingSchedule );

		}
		/** If only the FixedPyramidSchedule exists:*/
		else if ( temp_fix != 0 && temp_mov == 0 && FixedImageDimension == MovingImageDimension )
		{
			/** Always set the numberOfLevels first. */
			this->GetAsITKBaseType()->SetNumberOfLevels( numberOfResolutions );

			/** In this case set the movingPyramidSchedule to the
			 * FixedPyramidSchedule given in the parameter-file.
			 */
			for ( unsigned int i = 0; i < numberOfResolutions; i++ )
			{
				for ( unsigned int j = 0; j < MovingImageDimension; j++ )
				{
					this->m_Configuration->ReadParameter(
						movingSchedule[ i ][ j ],
						"FixedPyramidSchedule",
						i * MovingImageDimension + j );
				} // end for MovingImageDimension
			} // end for numberOfResolutions

			/** Set the schedule into this class.*/
			this->GetAsITKBaseType()->SetSchedule( movingSchedule );

		}
		else if ( temp_fix != 0 && temp_mov == 0 && FixedImageDimension != MovingImageDimension )
		{
			xl::xout["warning"] << "WARNING: MovingImagePyramidSchedule is not specified!" << std::endl;
			xl::xout["warning"] << "A default schedule is assumed. " << std::endl;
		}
		/** If both PyramidSchedule's don't exist:*/
		else
		{
			/** In this case set the movingPyramidSchedule to the
			 * default schedule.
			 */
			this->GetAsITKBaseType()->SetNumberOfLevels( numberOfResolutions );

		} // end if

	} // end SetMovingSchedule

} // end namespace elastix

#endif // end #ifndef __elxMovingImagePyramidBase_hxx

<|endoftext|>


<commit_before><commit_msg>ENH: add documentation<commit_after><|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  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 "itkConstantBoundaryCondition.h"
#include "itkFFTConvolutionImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSimpleFilterWatcher.h"

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

  if ( argc < 4 )
    {
    std::cout << "Usage: " << argv[0]
      << " inputImage kernelImage outputImage [normalizeImage]" << std::endl;
    return EXIT_FAILURE;
    }

  const int ImageDimension = 2;

  typedef float                                  PixelType;
  typedef itk::Image<PixelType, ImageDimension>  ImageType;
  typedef itk::ImageFileReader<ImageType>        ReaderType;

  ReaderType::Pointer reader1 = ReaderType::New();
  reader1->SetFileName( argv[1] );
  reader1->Update();

  ReaderType::Pointer reader2 = ReaderType::New();
  reader2->SetFileName( argv[2] );
  reader2->Update();

  typedef itk::FFTConvolutionImageFilter<ImageType> ConvolutionFilterType;
  ConvolutionFilterType::Pointer convoluter
    = ConvolutionFilterType::New();
  convoluter->SetInput( reader1->GetOutput() );
  convoluter->SetKernelImage( reader2->GetOutput() );

  itk::SimpleFilterWatcher watcher(convoluter, "filter");

  if( argc >= 5 )
    {
    convoluter->SetNormalize( static_cast<bool>( atoi( argv[4] ) ) );
    }

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

  try
    {
    writer->Update();
    }
  catch ( itk::ExceptionObject & excp )
    {
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  //
  // Tests for raising code coverage
  //
  convoluter->Print( std::cout );

  ImageType::Pointer emtpyImage = ImageType::New();
  convoluter->SetInput( emtpyImage );
  try
    {
    convoluter->Update();
    std::cerr << "Failed to throw expected exception" << std::endl;
    return EXIT_FAILURE;
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cout << excp << std::endl;
    std::cout << "caught EXPECTED exception for empty image as input" << std::endl;
    }

  convoluter->NormalizeOn();
  if( !convoluter->GetNormalize() )
    {
    std::cerr << "Set/GetNormalize() error" << std::endl;
    return EXIT_FAILURE;
    }

  convoluter->NormalizeOff();
  if( convoluter->GetNormalize() )
    {
    std::cerr << "Set/GetNormalize() error" << std::endl;
    return EXIT_FAILURE;
    }

  convoluter->SetNormalize( true );
  if( !convoluter->GetNormalize() )
    {
    std::cerr << "Set/GetNormalize() error" << std::endl;
    return EXIT_FAILURE;
    }

  convoluter->SetNormalize( false );
  if( convoluter->GetNormalize() )
    {
    std::cerr << "Set/GetNormalize() error" << std::endl;
    return EXIT_FAILURE;
    }

  convoluter->SetOutputRegionMode( ConvolutionFilterType::SAME );
  if ( convoluter->GetOutputRegionMode() != ConvolutionFilterType::SAME )
    {
    std::cerr << "SetOutputRegionMode() error when argument is SAME" << std::endl;
    return EXIT_FAILURE;
    }

  convoluter->SetOutputRegionMode( ConvolutionFilterType::VALID );
  if ( convoluter->GetOutputRegionMode() != ConvolutionFilterType::VALID )
    {
    std::cerr << "SetOutputRegionMode() error when argument is VALID" << std::endl;
    return EXIT_FAILURE;
    }

  convoluter->SetOutputRegionModeToSame();
  if ( convoluter->GetOutputRegionMode() != ConvolutionFilterType::SAME )
    {
    std::cerr << "SetOutputRegionModeToSame() error" << std::endl;
    return EXIT_FAILURE;
    }

  convoluter->SetOutputRegionModeToValid();
  if ( convoluter->GetOutputRegionMode() != ConvolutionFilterType::VALID )
    {
    std::cerr << "SetOutputRegionModeToValid() error" << std::endl;
    return EXIT_FAILURE;
    }

  itk::ConstantBoundaryCondition< ImageType > constantBoundaryCondition;
  convoluter->SetBoundaryCondition( &constantBoundaryCondition );
  if ( convoluter->GetBoundaryCondition() != &constantBoundaryCondition )
    {
    std::cerr << "SetBoundaryCondition() error" << std::endl;
    return EXIT_FAILURE;
    }

  // Test VALID output region mode with kernel that is larger than
  // the input image. Should result in a zero-size valid region.
  ImageType::Pointer largeKernel = ImageType::New();
  ImageType::RegionType kernelRegion( reader1->GetOutput()->GetLargestPossibleRegion().GetSize() );
  kernelRegion.PadByRadius( 5 );

  largeKernel->SetRegions( kernelRegion );
  largeKernel->Allocate();
  convoluter->SetOutputRegionModeToValid();
  convoluter->SetInput( reader1->GetOutput() );
  convoluter->SetKernelImage( largeKernel );
  try
    {
    convoluter->Update();
    std::cerr << "Failed to catch expected exception when kernel is larger than the input image."
              << std::endl;
    return EXIT_FAILURE;
    }
  catch ( itk::ExceptionObject e )
    {
    std::cout << "Caught expected exception when kernel is larger than the input image."
              << std::endl;
    std::cout << e << std::endl;
    }

  // Test for invalid request region.
  ImageType::IndexType invalidIndex;
  invalidIndex.Fill( 1000 );
  ImageType::SizeType invalidSize;
  invalidSize.Fill( 1000 );
  ImageType::RegionType invalidRequestRegion( invalidIndex, invalidSize );
  convoluter->GetOutput()->SetRequestedRegion( invalidRequestRegion );
  try
    {
    convoluter->Update();
    std::cerr << "Failed to catch expected exception when request region is outside the largest "
              << "possible region." << std::endl;
    return EXIT_FAILURE;
    }
  catch ( itk::ExceptionObject e )
    {
    std::cout << "Caught expected exception when request region is outside the largest "
              << "possible region." << std::endl;
    std::cout << e << std::endl;
    }

  return EXIT_SUCCESS;
}
<commit_msg>STYLE: Fixed typo in test variable name<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  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 "itkConstantBoundaryCondition.h"
#include "itkFFTConvolutionImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSimpleFilterWatcher.h"

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

  if ( argc < 4 )
    {
    std::cout << "Usage: " << argv[0]
      << " inputImage kernelImage outputImage [normalizeImage]" << std::endl;
    return EXIT_FAILURE;
    }

  const int ImageDimension = 2;

  typedef float                                  PixelType;
  typedef itk::Image<PixelType, ImageDimension>  ImageType;
  typedef itk::ImageFileReader<ImageType>        ReaderType;

  ReaderType::Pointer reader1 = ReaderType::New();
  reader1->SetFileName( argv[1] );
  reader1->Update();

  ReaderType::Pointer reader2 = ReaderType::New();
  reader2->SetFileName( argv[2] );
  reader2->Update();

  typedef itk::FFTConvolutionImageFilter<ImageType> ConvolutionFilterType;
  ConvolutionFilterType::Pointer convoluter
    = ConvolutionFilterType::New();
  convoluter->SetInput( reader1->GetOutput() );
  convoluter->SetKernelImage( reader2->GetOutput() );

  itk::SimpleFilterWatcher watcher(convoluter, "filter");

  if( argc >= 5 )
    {
    convoluter->SetNormalize( static_cast<bool>( atoi( argv[4] ) ) );
    }

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

  try
    {
    writer->Update();
    }
  catch ( itk::ExceptionObject & excp )
    {
    std::cerr << excp << std::endl;
    return EXIT_FAILURE;
    }

  //
  // Tests for raising code coverage
  //
  convoluter->Print( std::cout );

  ImageType::Pointer emptyImage = ImageType::New();
  convoluter->SetInput( emptyImage );
  try
    {
    convoluter->Update();
    std::cerr << "Failed to throw expected exception" << std::endl;
    return EXIT_FAILURE;
    }
  catch( itk::ExceptionObject & excp )
    {
    std::cout << excp << std::endl;
    std::cout << "caught EXPECTED exception for empty image as input" << std::endl;
    }

  convoluter->NormalizeOn();
  if( !convoluter->GetNormalize() )
    {
    std::cerr << "Set/GetNormalize() error" << std::endl;
    return EXIT_FAILURE;
    }

  convoluter->NormalizeOff();
  if( convoluter->GetNormalize() )
    {
    std::cerr << "Set/GetNormalize() error" << std::endl;
    return EXIT_FAILURE;
    }

  convoluter->SetNormalize( true );
  if( !convoluter->GetNormalize() )
    {
    std::cerr << "Set/GetNormalize() error" << std::endl;
    return EXIT_FAILURE;
    }

  convoluter->SetNormalize( false );
  if( convoluter->GetNormalize() )
    {
    std::cerr << "Set/GetNormalize() error" << std::endl;
    return EXIT_FAILURE;
    }

  convoluter->SetOutputRegionMode( ConvolutionFilterType::SAME );
  if ( convoluter->GetOutputRegionMode() != ConvolutionFilterType::SAME )
    {
    std::cerr << "SetOutputRegionMode() error when argument is SAME" << std::endl;
    return EXIT_FAILURE;
    }

  convoluter->SetOutputRegionMode( ConvolutionFilterType::VALID );
  if ( convoluter->GetOutputRegionMode() != ConvolutionFilterType::VALID )
    {
    std::cerr << "SetOutputRegionMode() error when argument is VALID" << std::endl;
    return EXIT_FAILURE;
    }

  convoluter->SetOutputRegionModeToSame();
  if ( convoluter->GetOutputRegionMode() != ConvolutionFilterType::SAME )
    {
    std::cerr << "SetOutputRegionModeToSame() error" << std::endl;
    return EXIT_FAILURE;
    }

  convoluter->SetOutputRegionModeToValid();
  if ( convoluter->GetOutputRegionMode() != ConvolutionFilterType::VALID )
    {
    std::cerr << "SetOutputRegionModeToValid() error" << std::endl;
    return EXIT_FAILURE;
    }

  itk::ConstantBoundaryCondition< ImageType > constantBoundaryCondition;
  convoluter->SetBoundaryCondition( &constantBoundaryCondition );
  if ( convoluter->GetBoundaryCondition() != &constantBoundaryCondition )
    {
    std::cerr << "SetBoundaryCondition() error" << std::endl;
    return EXIT_FAILURE;
    }

  // Test VALID output region mode with kernel that is larger than
  // the input image. Should result in a zero-size valid region.
  ImageType::Pointer largeKernel = ImageType::New();
  ImageType::RegionType kernelRegion( reader1->GetOutput()->GetLargestPossibleRegion().GetSize() );
  kernelRegion.PadByRadius( 5 );

  largeKernel->SetRegions( kernelRegion );
  largeKernel->Allocate();
  convoluter->SetOutputRegionModeToValid();
  convoluter->SetInput( reader1->GetOutput() );
  convoluter->SetKernelImage( largeKernel );
  try
    {
    convoluter->Update();
    std::cerr << "Failed to catch expected exception when kernel is larger than the input image."
              << std::endl;
    return EXIT_FAILURE;
    }
  catch ( itk::ExceptionObject e )
    {
    std::cout << "Caught expected exception when kernel is larger than the input image."
              << std::endl;
    std::cout << e << std::endl;
    }

  // Test for invalid request region.
  ImageType::IndexType invalidIndex;
  invalidIndex.Fill( 1000 );
  ImageType::SizeType invalidSize;
  invalidSize.Fill( 1000 );
  ImageType::RegionType invalidRequestRegion( invalidIndex, invalidSize );
  convoluter->GetOutput()->SetRequestedRegion( invalidRequestRegion );
  try
    {
    convoluter->Update();
    std::cerr << "Failed to catch expected exception when request region is outside the largest "
              << "possible region." << std::endl;
    return EXIT_FAILURE;
    }
  catch ( itk::ExceptionObject e )
    {
    std::cout << "Caught expected exception when request region is outside the largest "
              << "possible region." << std::endl;
    std::cout << e << std::endl;
    }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * StoreTarget.cpp
 *
 *  Created on: 19 Jan 2016
 *      Author: hieu
 */
#include <boost/foreach.hpp>
#include "StoreTarget.h"
#include "line_splitter.hh"
#include "probing_hash_utils.hh"
#include "../OutputFileStream.h"
#include "../Util2.h"

using namespace std;

namespace Moses2
{

StoreTarget::StoreTarget(const std::string &basepath)
:m_basePath(basepath)
,m_vocab(basepath + "/TargetVocab.dat")
{
  std::string path = basepath + "/TargetColl.dat";
  m_fileTargetColl.open(path.c_str(),
      std::ios::out | std::ios::binary | std::ios::ate | std::ios::trunc);
  if (!m_fileTargetColl.is_open()) {
    throw "can't create file ";
  }

}

StoreTarget::~StoreTarget()
{
  assert(m_coll.empty());
  m_fileTargetColl.close();

  // vocab
  m_vocab.Save();
}

uint64_t StoreTarget::Save()
{
  uint64_t ret = m_fileTargetColl.tellp();

  // save to disk
  uint64_t numTP = m_coll.size();
  m_fileTargetColl.write((char*) &numTP, sizeof(uint64_t));

  for (size_t i = 0; i < m_coll.size(); ++i) {
    Save(*m_coll[i]);
  }

  // clear coll
  RemoveAllInColl(m_coll);
  m_coll.clear();

  // starting position of coll
  return ret;
}

void StoreTarget::Save(const target_text &rule)
{
  // metadata for each tp
  TargetPhraseInfo tpInfo;
  tpInfo.alignTerm = GetAlignId(rule.word_align_term);
  tpInfo.alignNonTerm = GetAlignId(rule.word_align_non_term);
  tpInfo.numWords = rule.target_phrase.size();
  tpInfo.propLength = rule.property.size();

  //cerr << "TPInfo=" << sizeof(TPInfo);
  m_fileTargetColl.write((char*) &tpInfo, sizeof(TargetPhraseInfo));

  // scores
  for (size_t i = 0; i < rule.prob.size(); ++i) {
    float prob = rule.prob[i];
    m_fileTargetColl.write((char*) &prob, sizeof(prob));
  }

  // tp
  for (size_t i = 0; i < rule.target_phrase.size(); ++i) {
    uint32_t vocabId = rule.target_phrase[i];
    m_fileTargetColl.write((char*) &vocabId, sizeof(vocabId));
  }

  // prop TODO

}

void StoreTarget::SaveAlignment()
{
  std::string path = m_basePath + "/Alignments.dat";
  Moses2::OutputFileStream file(path);

  BOOST_FOREACH(Alignments::value_type &valPair, m_aligns) {
    file << valPair.second << "\t";

    const std::vector<size_t> &aligns = valPair.first;
    BOOST_FOREACH(size_t align, aligns) {
      file << align << " ";
    }
    file << endl;
  }

}

void StoreTarget::Append(const line_text &line, bool log_prob, bool scfg)
{
  target_text *rule = new target_text;
  //cerr << "line.target_phrase=" << line.target_phrase << endl;

  // target_phrase
  vector<bool> nonTerms;
  util::TokenIter<util::SingleCharacter> it;
  it = util::TokenIter<util::SingleCharacter>(line.target_phrase,
      util::SingleCharacter(' '));
  while (it) {
    string tok = it->as_string();
    //cerr << "tok=" << tok << endl;
    uint32_t vocabId = m_vocab.GetVocabId(tok);

    if (scfg) {
      bool nonTerm = false;
      if (scfg && tok[0] == '[' && tok.back() == ']') {
        //cerr << "NON-TERM=" << tok << " " << nonTerms.size() << endl;
        nonTerm = true;
      }
      nonTerms.push_back(nonTerm);
    }

    rule->target_phrase.push_back(vocabId);
    it++;
  }

  // probs
  it = util::TokenIter<util::SingleCharacter>(line.prob,
      util::SingleCharacter(' '));
  while (it) {
    string tok = it->as_string();
    float prob = Scan<float>(tok);

    if (log_prob) {
      prob = FloorScore(log(prob));
      if (prob == 0.0f) prob = 0.0000000001;
    }

    rule->prob.push_back(prob);
    it++;
  }

  /*
  cerr << "nonTerms=";
  for (size_t i = 0; i < nonTerms.size(); ++i) {
    cerr << nonTerms[i] << " ";
  }
  cerr << endl;
  */

  // alignment
  it = util::TokenIter<util::SingleCharacter>(line.word_align,
      util::SingleCharacter(' '));
  while (it) {
    string tokPair = Trim(it->as_string());
    if (tokPair.empty()) {
      break;
    }

    vector<size_t> alignPair = Tokenize<size_t>(tokPair, "-");
    assert(alignPair.size() == 2);

    bool nonTerm = false;
    size_t sourcePos = alignPair[0];
    size_t targetPos = alignPair[1];
    if (scfg) {
      nonTerm = nonTerms[targetPos];
    }

    //cerr << targetPos << "=" << nonTerm << endl;

    if (nonTerm) {
      rule->word_align_non_term.push_back(sourcePos);
      rule->word_align_non_term.push_back(targetPos);
      //cerr << (int) rule->word_all1.back() << " ";
    }
    else {
      rule->word_align_term.push_back(sourcePos);
      rule->word_align_term.push_back(targetPos);
    }

    it++;
  }

  // extra scores
  string prop = line.property.as_string();
  AppendLexRO(prop, rule->prob, log_prob);

  //cerr << "line.property=" << line.property << endl;
  //cerr << "prop=" << prop << endl;

  // properties
  /*
   for (size_t i = 0; i < prop.size(); ++i) {
   rule->property.push_back(prop[i]);
   }
   */
  m_coll.push_back(rule);
}

uint32_t StoreTarget::GetAlignId(const std::vector<size_t> &align)
{
  boost::unordered_map<std::vector<size_t>, uint32_t>::iterator iter =
      m_aligns.find(align);
  if (iter == m_aligns.end()) {
    uint32_t ind = m_aligns.size();
    m_aligns[align] = ind;
    return ind;
  }
  else {
    return iter->second;
  }
}

void StoreTarget::AppendLexRO(std::string &prop, std::vector<float> &retvector,
    bool log_prob) const
{
  size_t startPos = prop.find("{{LexRO ");

  if (startPos != string::npos) {
    size_t endPos = prop.find("}}", startPos + 8);
    string lexProb = prop.substr(startPos + 8, endPos - startPos - 8);
    //cerr << "lexProb=" << lexProb << endl;

    // append lex probs to pt probs
    vector<float> scores = Tokenize<float>(lexProb);

    if (log_prob) {
      for (size_t i = 0; i < scores.size(); ++i) {
        scores[i] = FloorScore(log(scores[i]));
        if (scores[i] == 0.0f) scores[i] = 0.0000000001;
      }
    }

    for (size_t i = 0; i < scores.size(); ++i) {
      retvector.push_back(scores[i]);
    }

    // exclude LexRO property from property column
    prop = prop.substr(0, startPos)
        + prop.substr(endPos + 2, prop.size() - endPos - 2);
    //cerr << "line.property_to_be_binarized=" << line.property_to_be_binarized << "AAAA" << endl;
  }
}

} /* namespace Moses2 */
<commit_msg>gcc compile error<commit_after>/*
 * StoreTarget.cpp
 *
 *  Created on: 19 Jan 2016
 *      Author: hieu
 */
#include <boost/foreach.hpp>
#include "StoreTarget.h"
#include "line_splitter.hh"
#include "probing_hash_utils.hh"
#include "../OutputFileStream.h"
#include "../Util2.h"

using namespace std;

namespace Moses2
{

StoreTarget::StoreTarget(const std::string &basepath)
:m_basePath(basepath)
,m_vocab(basepath + "/TargetVocab.dat")
{
  std::string path = basepath + "/TargetColl.dat";
  m_fileTargetColl.open(path.c_str(),
      std::ios::out | std::ios::binary | std::ios::ate | std::ios::trunc);
  if (!m_fileTargetColl.is_open()) {
    throw "can't create file ";
  }

}

StoreTarget::~StoreTarget()
{
  assert(m_coll.empty());
  m_fileTargetColl.close();

  // vocab
  m_vocab.Save();
}

uint64_t StoreTarget::Save()
{
  uint64_t ret = m_fileTargetColl.tellp();

  // save to disk
  uint64_t numTP = m_coll.size();
  m_fileTargetColl.write((char*) &numTP, sizeof(uint64_t));

  for (size_t i = 0; i < m_coll.size(); ++i) {
    Save(*m_coll[i]);
  }

  // clear coll
  RemoveAllInColl(m_coll);
  m_coll.clear();

  // starting position of coll
  return ret;
}

void StoreTarget::Save(const target_text &rule)
{
  // metadata for each tp
  TargetPhraseInfo tpInfo;
  tpInfo.alignTerm = GetAlignId(rule.word_align_term);
  tpInfo.alignNonTerm = GetAlignId(rule.word_align_non_term);
  tpInfo.numWords = rule.target_phrase.size();
  tpInfo.propLength = rule.property.size();

  //cerr << "TPInfo=" << sizeof(TPInfo);
  m_fileTargetColl.write((char*) &tpInfo, sizeof(TargetPhraseInfo));

  // scores
  for (size_t i = 0; i < rule.prob.size(); ++i) {
    float prob = rule.prob[i];
    m_fileTargetColl.write((char*) &prob, sizeof(prob));
  }

  // tp
  for (size_t i = 0; i < rule.target_phrase.size(); ++i) {
    uint32_t vocabId = rule.target_phrase[i];
    m_fileTargetColl.write((char*) &vocabId, sizeof(vocabId));
  }

  // prop TODO

}

void StoreTarget::SaveAlignment()
{
  std::string path = m_basePath + "/Alignments.dat";
  Moses2::OutputFileStream file(path);

  BOOST_FOREACH(Alignments::value_type &valPair, m_aligns) {
    file << valPair.second << "\t";

    const std::vector<size_t> &aligns = valPair.first;
    BOOST_FOREACH(size_t align, aligns) {
      file << align << " ";
    }
    file << endl;
  }

}

void StoreTarget::Append(const line_text &line, bool log_prob, bool scfg)
{
  target_text *rule = new target_text;
  //cerr << "line.target_phrase=" << line.target_phrase << endl;

  // target_phrase
  vector<bool> nonTerms;
  util::TokenIter<util::SingleCharacter> it;
  it = util::TokenIter<util::SingleCharacter>(line.target_phrase,
      util::SingleCharacter(' '));
  while (it) {
    string tok = it->as_string();
    //cerr << "tok=" << tok << endl;
    uint32_t vocabId = m_vocab.GetVocabId(tok);

    if (scfg) {
      bool nonTerm = false;
      if (scfg && tok[0] == '[' && tok[tok.size() - 1] == ']') {
        //cerr << "NON-TERM=" << tok << " " << nonTerms.size() << endl;
        nonTerm = true;
      }
      nonTerms.push_back(nonTerm);
    }

    rule->target_phrase.push_back(vocabId);
    it++;
  }

  // probs
  it = util::TokenIter<util::SingleCharacter>(line.prob,
      util::SingleCharacter(' '));
  while (it) {
    string tok = it->as_string();
    float prob = Scan<float>(tok);

    if (log_prob) {
      prob = FloorScore(log(prob));
      if (prob == 0.0f) prob = 0.0000000001;
    }

    rule->prob.push_back(prob);
    it++;
  }

  /*
  cerr << "nonTerms=";
  for (size_t i = 0; i < nonTerms.size(); ++i) {
    cerr << nonTerms[i] << " ";
  }
  cerr << endl;
  */

  // alignment
  it = util::TokenIter<util::SingleCharacter>(line.word_align,
      util::SingleCharacter(' '));
  while (it) {
    string tokPair = Trim(it->as_string());
    if (tokPair.empty()) {
      break;
    }

    vector<size_t> alignPair = Tokenize<size_t>(tokPair, "-");
    assert(alignPair.size() == 2);

    bool nonTerm = false;
    size_t sourcePos = alignPair[0];
    size_t targetPos = alignPair[1];
    if (scfg) {
      nonTerm = nonTerms[targetPos];
    }

    //cerr << targetPos << "=" << nonTerm << endl;

    if (nonTerm) {
      rule->word_align_non_term.push_back(sourcePos);
      rule->word_align_non_term.push_back(targetPos);
      //cerr << (int) rule->word_all1.back() << " ";
    }
    else {
      rule->word_align_term.push_back(sourcePos);
      rule->word_align_term.push_back(targetPos);
    }

    it++;
  }

  // extra scores
  string prop = line.property.as_string();
  AppendLexRO(prop, rule->prob, log_prob);

  //cerr << "line.property=" << line.property << endl;
  //cerr << "prop=" << prop << endl;

  // properties
  /*
   for (size_t i = 0; i < prop.size(); ++i) {
   rule->property.push_back(prop[i]);
   }
   */
  m_coll.push_back(rule);
}

uint32_t StoreTarget::GetAlignId(const std::vector<size_t> &align)
{
  boost::unordered_map<std::vector<size_t>, uint32_t>::iterator iter =
      m_aligns.find(align);
  if (iter == m_aligns.end()) {
    uint32_t ind = m_aligns.size();
    m_aligns[align] = ind;
    return ind;
  }
  else {
    return iter->second;
  }
}

void StoreTarget::AppendLexRO(std::string &prop, std::vector<float> &retvector,
    bool log_prob) const
{
  size_t startPos = prop.find("{{LexRO ");

  if (startPos != string::npos) {
    size_t endPos = prop.find("}}", startPos + 8);
    string lexProb = prop.substr(startPos + 8, endPos - startPos - 8);
    //cerr << "lexProb=" << lexProb << endl;

    // append lex probs to pt probs
    vector<float> scores = Tokenize<float>(lexProb);

    if (log_prob) {
      for (size_t i = 0; i < scores.size(); ++i) {
        scores[i] = FloorScore(log(scores[i]));
        if (scores[i] == 0.0f) scores[i] = 0.0000000001;
      }
    }

    for (size_t i = 0; i < scores.size(); ++i) {
      retvector.push_back(scores[i]);
    }

    // exclude LexRO property from property column
    prop = prop.substr(0, startPos)
        + prop.substr(endPos + 2, prop.size() - endPos - 2);
    //cerr << "line.property_to_be_binarized=" << line.property_to_be_binarized << "AAAA" << endl;
  }
}

} /* namespace Moses2 */
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2009 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Modules/Legacy/Fields/CalculateSignedDistanceToField.h>
#include <Core/Datatypes/Legacy/Field/Field.h>

#include <Core/Algorithms/Legacy/Fields/DistanceField/CalculateSignedDistanceField.h>

using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules::Fields;

CalculateSignedDistanceToField::CalculateSignedDistanceToField()
  : Module(ModuleLookupInfo("CalculateSignedDistanceToField", "ChangeFieldData", "SCIRun"))
{
}

void CalculateSignedDistanceToField::execute()
{
  FieldHandle input, output, value;
  FieldHandle object;

  get_input_handle("Field",input,true);
  get_input_handle("ObjectField",object,true);

  bool value_connected = oport_connected("ValueField");

  if (inputs_changed_ || !oport_cached("SignedDistanceField") ||
      (!oport_cached("ValueField") && value_connected))
  {
    update_state(Executing);

    if (value_connected)
    {
      if(!(algo_.run(input,object,output,value))) return;

      send_output_handle("SignedDistanceField", output);
      send_output_handle("ValueField", value);
    }
    else
    {
      if(!(algo_.run(input,object,output))) return;

      send_output_handle("SignedDistanceField", output);
    }
  }
}

<commit_msg>getInput<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2009 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Modules/Legacy/Fields/CalculateSignedDistanceToField.h>
#include <Core/Datatypes/Legacy/Field/Field.h>

#include <Core/Algorithms/Legacy/Fields/DistanceField/CalculateSignedDistanceField.h>

using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules::Fields;

CalculateSignedDistanceToField::CalculateSignedDistanceToField()
  : Module(ModuleLookupInfo("CalculateSignedDistanceToField", "ChangeFieldData", "SCIRun"))
{
}

void CalculateSignedDistanceToField::execute()
{
  FieldHandle input = getRequiredInput(InputField);
  FieldHandle object = getRequiredInput(ObjectField);

  bool value_connected = oport_connected("ValueField");

  if (inputs_changed_ || !oport_cached("SignedDistanceField") ||
      (!oport_cached("ValueField") && value_connected))
  {
    update_state(Executing);

    if (value_connected)
    {
      if(!(algo_.run(input,object,output,value))) return;

      send_output_handle("SignedDistanceField", output);
      send_output_handle("ValueField", value);
    }
    else
    {
      if(!(algo_.run(input,object,output))) return;

      send_output_handle("SignedDistanceField", output);
    }
  }
}

<|endoftext|>


<commit_before>/**
* @file Simulation.cpp
* @author Benjamin Schlotter
* Implementation of class Simulation
*/

#include "Simulation.h"

using namespace naoth;
using namespace std;

  Simulation::Simulation()
  {
  DEBUG_REQUEST_REGISTER("Simulation:draw_one_action_point:global","draw_one_action_point:global", true);
  DEBUG_REQUEST_REGISTER("Simulation:draw_ball","draw_ball", true);
  DEBUG_REQUEST_REGISTER("Simulation:ActionTarget","ActionTarget", true);

  //actionRingBuffer.resize(ActionModel::numOfActions);
  //calculate the actions
  action_local.reserve(ActionModel::numOfActions);

  action_local.push_back(Action(ActionModel::none, Vector2d()));
  action_local.push_back(Action(ActionModel::kick_long, Vector2d(theParameters.action_long_kick_distance, 0))); // long
  action_local.push_back(Action(ActionModel::kick_short, Vector2d(theParameters.action_short_kick_distance, 0))); // short
  action_local.push_back(Action(ActionModel::sidekick_right, Vector2d(0, -theParameters.action_sidekick_distance))); // right
  action_local.push_back(Action(ActionModel::sidekick_left, Vector2d(0, theParameters.action_sidekick_distance))); // left
  }

  Simulation::~Simulation(){}

 void Simulation::execute()
 {
  Action& lonely_action = action_local[1];

  actionGlobal = calculateOneAction(lonely_action);

    DEBUG_REQUEST("Simulation:draw_one_action_point:global",
    FIELD_DRAWING_CONTEXT;
    PEN("000000", 1);

        CIRCLE( actionGlobal.x, actionGlobal.y, 50);

  );
}//end execute

Vector2d Simulation::calculateOneAction(Action& lonely_action) const
{
  GoalModel::Goal oppGoalModel = getSelfLocGoalModel().getOppGoal(getCompassDirection(), getFieldInfo());
  Vector2d oppGoalPostLeftPreview = getMotionStatus().plannedMotion.hip / oppGoalModel.leftPost;
  Vector2d oppGoalPostRightPreview = getMotionStatus().plannedMotion.hip / oppGoalModel.rightPost;

  //the endpoints of our line are a shortened version of the goal line
  Vector2d leftEndpoint = oppGoalPostLeftPreview + Vector2d(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius,0);
  Vector2d rightEndpoint = oppGoalPostRightPreview - Vector2d(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius,0);

  // this is the goalline we are shooting for
  Math::LineSegment goalLinePreview(leftEndpoint, rightEndpoint);

  Vector2d ballRelativePreview = getBallModel().positionPreview;

  DEBUG_REQUEST("Simulation:draw_ball",
    FIELD_DRAWING_CONTEXT;
    PEN("FF0000", 1);
      Vector2d Ball = getRobotPose() *ballRelativePreview;
    CIRCLE( Ball.x, Ball.y, 50);

  );

  lonely_action.target = lonely_action.predict(ballRelativePreview, 0.1, Math::fromDegrees(5));

  DEBUG_REQUEST("Simulation:ActionTarget",
    FIELD_DRAWING_CONTEXT;
    PEN("0000FF", 1);

    Vector2d Ball = getRobotPose() *lonely_action.target;
    CIRCLE( Ball.x, Ball.y, 50);

  );
  Math::LineSegment shootLine(ballRelativePreview, outsideField(lonely_action.target));

  Vector2d actionPoint;

  if(shootLine.intersect(goalLinePreview) && goalLinePreview.intersect(shootLine))
  {
    //actionGlobal = getRobotPose() * lonely_action.target;

    actionPoint = Vector2d(getFieldInfo().xPosOpponentGoal+200, 0.0);

  }
  else
  {
    actionPoint = getRobotPose() * lonely_action.target;
    actionPoint = outsideField(actionPoint);
  }

  return actionPoint;
}

  //correction of distance in percentage, angle in degrees
  Vector2d Simulation::Action::predict(const Vector2d& ball, double distance_variance, double angle_variance) const
  {
  double random_length = 2.0*Math::random()-1.0;
  double random_angle = 2.0*Math::random()-1.0;

  Vector2d noisyAction = actionVector + actionVector*(distance_variance*random_length);
  noisyAction.rotate(angle_variance*random_angle);

  return ball + noisyAction;
  }

  //calcualte according to the rules, without the roboter position, the ball position
  //if it goes outside the field
  Vector2d Simulation::outsideField(const Vector2d& globalPoint) const{
  Vector2d point = globalPoint;
   if(getFieldInfo().fieldRect.inside(point)){
     return point;
   }
   else{
     //an der linken Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter
     if(point.y  > getFieldInfo().yPosLeftSideline ){
       if(point.x-1000 < getFieldInfo().xThrowInLineOwn) point.x = getFieldInfo().xThrowInLineOwn;
       else point.x -= 1000;
       return Vector2d(point.x, getFieldInfo().yThrowInLineLeft);//range check

     }
     //an der rechten Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter
     else if(point.y  < getFieldInfo().yPosRightSideline){
       if(point.x-1000 < getFieldInfo().xThrowInLineOwn) point.x = getFieldInfo().xThrowInLineOwn;
       else point.x -= 1000;
       return Vector2d(point.x, getFieldInfo().yThrowInLineRight);//range check
     }
     //hinten raus -> an der seite wo raus geht
     else if(point.x < getFieldInfo().xPosOwnGroundline){
       if(point.y < 0)return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineRight);//range check
       else return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineLeft);
     }
     else{ //if(point.x > getFieldInfo().xPosOpponentGroundline){
       //vorne raus -> Ball einen Meter hinter Roboter mind ansto hhe. jeweils seite wo ins ausgeht
       if(point.y < 0)return Vector2d(0, getFieldInfo().yThrowInLineRight);//range check
       else return Vector2d(0, getFieldInfo().yThrowInLineLeft);
     }
   }
}

<commit_msg>Abbruchbedingung für Simulation hinzugefügt<commit_after>/**
* @file Simulation.cpp
* @author Benjamin Schlotter
* Implementation of class Simulation
*/

#include "Simulation.h"

using namespace naoth;
using namespace std;

  Simulation::Simulation()
  {
  DEBUG_REQUEST_REGISTER("Simulation:draw_one_action_point:global","draw_one_action_point:global", true);
  DEBUG_REQUEST_REGISTER("Simulation:draw_ball","draw_ball", true);
  DEBUG_REQUEST_REGISTER("Simulation:ActionTarget","ActionTarget", true);

  //actionRingBuffer.resize(ActionModel::numOfActions);
  //calculate the actions
  action_local.reserve(ActionModel::numOfActions);

  action_local.push_back(Action(ActionModel::none, Vector2d()));
  action_local.push_back(Action(ActionModel::kick_long, Vector2d(theParameters.action_long_kick_distance, 0))); // long
  action_local.push_back(Action(ActionModel::kick_short, Vector2d(theParameters.action_short_kick_distance, 0))); // short
  action_local.push_back(Action(ActionModel::sidekick_right, Vector2d(0, -theParameters.action_sidekick_distance))); // right
  action_local.push_back(Action(ActionModel::sidekick_left, Vector2d(0, theParameters.action_sidekick_distance))); // left
  }

  Simulation::~Simulation(){}

 void Simulation::execute()
 {
   if(!getBallModel().valid || getFrameInfo().getTimeInSeconds() >= getBallModel().frameInfoWhenBallWasSeen.getTimeInSeconds()+1){
     return;
   }
   else{
    Action& lonely_action = action_local[1];

    actionGlobal = calculateOneAction(lonely_action);

    DEBUG_REQUEST("Simulation:draw_one_action_point:global",
    FIELD_DRAWING_CONTEXT;
    PEN("000000", 1);

      CIRCLE( actionGlobal.x, actionGlobal.y, 50);

    );
   }
}//end execute

Vector2d Simulation::calculateOneAction(Action& lonely_action) const
{
  GoalModel::Goal oppGoalModel = getSelfLocGoalModel().getOppGoal(getCompassDirection(), getFieldInfo());
  Vector2d oppGoalPostLeftPreview = getMotionStatus().plannedMotion.hip / oppGoalModel.leftPost;
  Vector2d oppGoalPostRightPreview = getMotionStatus().plannedMotion.hip / oppGoalModel.rightPost;

  //the endpoints of our line are a shortened version of the goal line
  Vector2d leftEndpoint = oppGoalPostLeftPreview + Vector2d(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius,0);
  Vector2d rightEndpoint = oppGoalPostRightPreview - Vector2d(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius,0);

  // this is the goalline we are shooting for
  Math::LineSegment goalLinePreview(leftEndpoint, rightEndpoint);

  Vector2d ballRelativePreview = getBallModel().positionPreview;

  DEBUG_REQUEST("Simulation:draw_ball",
    FIELD_DRAWING_CONTEXT;
    PEN("FF0000", 1);
      Vector2d Ball = getRobotPose() *ballRelativePreview;
    CIRCLE( Ball.x, Ball.y, 50);

  );

  lonely_action.target = lonely_action.predict(ballRelativePreview, 0.1, Math::fromDegrees(5));

  DEBUG_REQUEST("Simulation:ActionTarget",
    FIELD_DRAWING_CONTEXT;
    PEN("0000FF", 1);

    Vector2d Ball = getRobotPose() *lonely_action.target;
    CIRCLE( Ball.x, Ball.y, 50);

  );
  //Math::LineSegment shootLine(ballRelativePreview, outsideField(lonely_action.target));//hmm
  Math::LineSegment shootLine(ballRelativePreview, lonely_action.target);

  Vector2d actionPoint;

  if(shootLine.intersect(goalLinePreview) && goalLinePreview.intersect(shootLine))
  {
    //actionGlobal = getRobotPose() * lonely_action.target;

    actionPoint = Vector2d(getFieldInfo().xPosOpponentGoal+200, 0.0);

  }
  else
  {
    actionPoint = getRobotPose() * lonely_action.target;
    actionPoint = outsideField(actionPoint);
  }

  return actionPoint;
}

  //correction of distance in percentage, angle in degrees
  Vector2d Simulation::Action::predict(const Vector2d& ball, double distance_variance, double angle_variance) const
  {
  double random_length = 2.0*Math::random()-1.0;
  double random_angle = 2.0*Math::random()-1.0;

  Vector2d noisyAction = actionVector + actionVector*(distance_variance*random_length);
  noisyAction.rotate(angle_variance*random_angle);

  return ball + noisyAction;
  }

  //calcualte according to the rules, without the roboter position, the ball position
  //if it goes outside the field
  Vector2d Simulation::outsideField(const Vector2d& globalPoint) const{
  Vector2d point = globalPoint;
   if(getFieldInfo().fieldRect.inside(point)){
     return point;
   }
   else{
     //an der linken Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter
     if(point.y  > getFieldInfo().yPosLeftSideline ){
       if(point.x-1000 < getFieldInfo().xThrowInLineOwn) point.x = getFieldInfo().xThrowInLineOwn;
       else point.x -= 1000;
       return Vector2d(point.x, getFieldInfo().yThrowInLineLeft);//range check

     }
     //an der rechten Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter
     else if(point.y  < getFieldInfo().yPosRightSideline){
       if(point.x-1000 < getFieldInfo().xThrowInLineOwn) point.x = getFieldInfo().xThrowInLineOwn;
       else point.x -= 1000;
       return Vector2d(point.x, getFieldInfo().yThrowInLineRight);//range check
     }
     //hinten raus -> an der seite wo raus geht
     else if(point.x < getFieldInfo().xPosOwnGroundline){
       if(point.y < 0)return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineRight);//range check
       else return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineLeft);
     }
     else{ //if(point.x > getFieldInfo().xPosOpponentGroundline){
       //vorne raus -> Ball einen Meter hinter Roboter mind ansto hhe. jeweils seite wo ins ausgeht
       if(point.y < 0)return Vector2d(0, getFieldInfo().yThrowInLineRight);//range check
       else return Vector2d(0, getFieldInfo().yThrowInLineLeft);
     }
   }
}

<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "DebugOperatorNew.h"

#include "Application.h"
#include "Framework.h"
#include "ConfigurationManager.h"
#include "CoreStringUtils.h"

#include <QDir>
#include <QGraphicsView>
#include <QTranslator>
#include <QLocale>
#include <QIcon>
#include <QWebSettings>

#ifdef Q_WS_MAC
#include <QMouseEvent>
#include <QWheelEvent>

#include "UiMainWindow.h"
#include "UiAPI.h"
#include "UiGraphicsView.h"
#endif

#include "MemoryLeakCheck.h"

using namespace Foundation;

Application::Application(Framework *framework_, int &argc, char **argv) :
    QApplication(argc, argv),
    framework(framework_),
    appActivated(true),
    nativeTranslator(new QTranslator),
    appTranslator(new QTranslator)
{
    QApplication::setApplicationName("realXtend-Naali");

#if defined(Q_WS_WIN) || defined(Q_WS_MAC)
        // If under windows, add run_dir/plugins as library path
        // unix users will get plugins from their OS Qt installation folder automatically

        QString runDirectory = QString::fromStdString(ReplaceChar(framework->GetPlatform()->GetInstallDirectory(), '\\', '/'));
        runDirectory += "/qtplugins";
        addLibraryPath(runDirectory);
#endif

    QDir dir("data/translations/qt_native_translations");
    QStringList qmFiles = GetQmFiles(dir);

    // Search then that is there corresponding native translations for system locals.
    QString loc = QLocale::system().name();
    loc.chop(3);

    QString name = "data/translations/qt_native_translations/qt_" + loc + ".qm";
    QStringList lst = qmFiles.filter(name);
    if (!lst.empty() )
        nativeTranslator->load(lst[0]);

    this->installTranslator(nativeTranslator);

    std::string default_language = framework->GetConfigManager()->DeclareSetting(Framework::ConfigurationGroup(),
        "language", std::string("data/translations/naali_en"));
    ChangeLanguage(QString::fromStdString(default_language));

    QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true); //enablig flash
}

Application::~Application()
{
    SAFE_DELETE(nativeTranslator);
    SAFE_DELETE(appTranslator);
}

QStringList Application::GetQmFiles(const QDir& dir)
{
     QStringList fileNames = dir.entryList(QStringList("*.qm"), QDir::Files, QDir::Name);
     QMutableStringListIterator i(fileNames);
     while (i.hasNext())
     {
         i.next();
         i.setValue(dir.filePath(i.value()));
     }
     return fileNames;
}

void Application::Go()
{
    installEventFilter(this);

    QObject::connect(&frameUpdateTimer, SIGNAL(timeout()), this, SLOT(UpdateFrame()));
    frameUpdateTimer.setSingleShot(true);
    frameUpdateTimer.start(0);

    try
    {
        exec ();
    }
    catch(const std::exception &e)
    {
        RootLogCritical(std::string("NaaliApplication::Go caught an exception: ") + (e.what() ? e.what() : "(null)"));
        throw;
    }
    catch(...)
    {
        RootLogCritical(std::string("NaaliApplication::Go caught an unknown exception!"));
        throw;
    }
}

bool Application::eventFilter(QObject *obj, QEvent *event)
{
#ifdef Q_WS_MAC // workaround for Mac, because mouse events are not received as it ought to be
    QMouseEvent *mouse = dynamic_cast<QMouseEvent*>(event);
    if (mouse)
    {
        if (dynamic_cast<UiMainWindow*>(obj))
        {
            switch(event->type())
            {
            case QEvent::MouseButtonPress:
                framework->Ui()->GraphicsView()->mousePressEvent(mouse);
                break;
            case QEvent::MouseButtonRelease:
                framework->Ui()->GraphicsView()->mouseReleaseEvent(mouse);
                break;
            case QEvent::MouseButtonDblClick:
                framework->Ui()->GraphicsView()->mouseDoubleClickEvent(mouse);
                break;
            case QEvent::MouseMove:
                if (mouse->buttons() == Qt::LeftButton)
                    framework->Ui()->GraphicsView()->mouseMoveEvent(mouse);
                break;
            }
        }
    }
#endif
    try
    {
        if (obj == this)
        {
            if (event->type() == QEvent::ApplicationActivate)
                appActivated = true;
            if (event->type() == QEvent::ApplicationDeactivate)
                appActivated = false;
        }

        return QObject::eventFilter(obj, event);
    }
    catch(const std::exception &e)
    {
        std::cout << std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)") << std::endl;
        RootLogCritical(std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)"));
        throw;
    } catch(...)
    {
        std::cout << std::string("QApp::eventFilter caught an unknown exception!") << std::endl;
        RootLogCritical(std::string("QApp::eventFilter caught an unknown exception!"));
        throw;
    }
}

void Application::ChangeLanguage(const QString& file)
{
    QString filename = file;
    if (!filename.endsWith(".qm", Qt::CaseInsensitive))
        filename.append(".qm");
    QString tmp = filename;
    tmp.chop(3);
    QString str = tmp.right(2);

    QString name = "data/translations/qt_native_translations/qt_" + str + ".qm";

    // Remove old translators then change them to new.
    removeTranslator(nativeTranslator);

    if (QFile::exists(name))
    {
        if (nativeTranslator != 0)
        {
            nativeTranslator->load(name);
            installTranslator(nativeTranslator);
        }
    }
    else
    {
        if (nativeTranslator != 0 && nativeTranslator->isEmpty())
        {
            installTranslator(nativeTranslator);
        }
        else
        {
            SAFE_DELETE(nativeTranslator);
            nativeTranslator = new QTranslator;
            installTranslator(nativeTranslator);
        }
    }

    // Remove old translators then change them to new.
    removeTranslator(appTranslator);
    if (appTranslator->load(filename))
    {
        installTranslator(appTranslator);
        framework->GetConfigManager()->SetSetting(Framework::ConfigurationGroup(), "language", file.toStdString());
    }

    emit LanguageChanged();
}

bool Application::notify(QObject *receiver, QEvent *event)
{
    try
    {
        return QApplication::notify(receiver, event);
    } catch(const std::exception &e)
    {
        std::cout << std::string("QApp::notify caught an exception: ") << (e.what() ? e.what() : "(null)") << std::endl;
        RootLogCritical(std::string("QApp::notify caught an exception: ") + (e.what() ? e.what() : "(null)"));
        throw;
    } catch(...)
    {
        std::cout << std::string("QApp::notify caught an unknown exception!") << std::endl;
        RootLogCritical(std::string("QApp::notify caught an unknown exception!"));
        throw;
    }
}

void Application::UpdateFrame()
{
    // Don't pump the QEvents to QApplication if we are exiting
    // also don't process our mainloop frames.
    if (framework->IsExiting())
        return;

    try
    {
        const tick_t frameStartTime = GetCurrentClockTime();

        QApplication::processEvents(QEventLoop::AllEvents, 1);
        QApplication::sendPostedEvents();

        framework->ProcessOneFrame();

        const boost::program_options::variables_map &options = framework->ProgramOptions();
        double targetFpsLimit = 60.0;
        if (options.count("fpslimit") > 0)
        {
            targetFpsLimit = options["fpslimit"].as<float>();
            if (targetFpsLimit < 1.f)
                targetFpsLimit = 0.f;
        }

        tick_t timeNow = GetCurrentClockTime();

        static tick_t timerFrequency = GetCurrentClockFreq();

        double msecsSpentInFrame = (double)(timeNow - frameStartTime) * 1000.0 / timerFrequency;
        const double msecsPerFrame = 1000.0 / targetFpsLimit;

        double msecsToSleep = std::min(std::max(0.0, msecsPerFrame - msecsSpentInFrame), msecsPerFrame);

        // Reduce frame rate when unfocused
        if (!frameUpdateTimer.isActive())
        {
            if (appActivated || framework->IsHeadless())
                frameUpdateTimer.start(msecsToSleep);
            else
                frameUpdateTimer.start(msecsToSleep + msecsPerFrame); // Proceed at half FPS speed when unfocused (but never at half FPS when running a headless server).
        }
    }
    catch(const std::exception &e)
    {
        std::cout << "QApp::UpdateFrame caught an exception: " << (e.what() ? e.what() : "(null)") << std::endl;
        RootLogCritical(std::string("QApp::UpdateFrame caught an exception: ") + (e.what() ? e.what() : "(null)"));
        throw;
    }
    catch(...)
    {
        std::cout << "QApp::UpdateFrame caught an unknown exception!" << std::endl;
        RootLogCritical(std::string("QApp::UpdateFrame caught an unknown exception!"));
        throw;
    }
}

void Application::AboutToExit()
{
    emit ExitRequested();

    // If no-one canceled the exit as a response to the signal, exit
    if (framework->IsExiting())
        quit();
}
<commit_msg>jj Fixed a bug where closing a QML application canvas caused the whole server to shut down when in headless mode.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "DebugOperatorNew.h"

#include "Application.h"
#include "Framework.h"
#include "ConfigurationManager.h"
#include "CoreStringUtils.h"

#include <QDir>
#include <QGraphicsView>
#include <QTranslator>
#include <QLocale>
#include <QIcon>
#include <QWebSettings>

#ifdef Q_WS_MAC
#include <QMouseEvent>
#include <QWheelEvent>

#include "UiMainWindow.h"
#include "UiAPI.h"
#include "UiGraphicsView.h"
#endif

#include "MemoryLeakCheck.h"

using namespace Foundation;

Application::Application(Framework *framework_, int &argc, char **argv) :
    QApplication(argc, argv),
    framework(framework_),
    appActivated(true),
    nativeTranslator(new QTranslator),
    appTranslator(new QTranslator)
{
    QApplication::setApplicationName("realXtend-Naali");

    // In headless mode, we create windows that are never shown.
    // Also, the user can open up debugging windows like the profiler or kNet network stats from the console,
    // so disable the whole application from closing when these are shut down.
    // For headful mode, we depend on explicitly checking on the closing of the main window, so we don't need
    // this flag in any case.
    setQuitOnLastWindowClosed(false);

#if defined(Q_WS_WIN) || defined(Q_WS_MAC)
        // If under windows, add run_dir/plugins as library path
        // unix users will get plugins from their OS Qt installation folder automatically

        QString runDirectory = QString::fromStdString(ReplaceChar(framework->GetPlatform()->GetInstallDirectory(), '\\', '/'));
        runDirectory += "/qtplugins";
        addLibraryPath(runDirectory);
#endif

    QDir dir("data/translations/qt_native_translations");
    QStringList qmFiles = GetQmFiles(dir);

    // Search then that is there corresponding native translations for system locals.
    QString loc = QLocale::system().name();
    loc.chop(3);

    QString name = "data/translations/qt_native_translations/qt_" + loc + ".qm";
    QStringList lst = qmFiles.filter(name);
    if (!lst.empty() )
        nativeTranslator->load(lst[0]);

    this->installTranslator(nativeTranslator);

    std::string default_language = framework->GetConfigManager()->DeclareSetting(Framework::ConfigurationGroup(),
        "language", std::string("data/translations/naali_en"));
    ChangeLanguage(QString::fromStdString(default_language));

    QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true); //enablig flash
}

Application::~Application()
{
    SAFE_DELETE(nativeTranslator);
    SAFE_DELETE(appTranslator);
}

QStringList Application::GetQmFiles(const QDir& dir)
{
     QStringList fileNames = dir.entryList(QStringList("*.qm"), QDir::Files, QDir::Name);
     QMutableStringListIterator i(fileNames);
     while (i.hasNext())
     {
         i.next();
         i.setValue(dir.filePath(i.value()));
     }
     return fileNames;
}

void Application::Go()
{
    installEventFilter(this);

    QObject::connect(&frameUpdateTimer, SIGNAL(timeout()), this, SLOT(UpdateFrame()));
    frameUpdateTimer.setSingleShot(true);
    frameUpdateTimer.start(0);

    try
    {
        exec ();
    }
    catch(const std::exception &e)
    {
        RootLogCritical(std::string("NaaliApplication::Go caught an exception: ") + (e.what() ? e.what() : "(null)"));
        throw;
    }
    catch(...)
    {
        RootLogCritical(std::string("NaaliApplication::Go caught an unknown exception!"));
        throw;
    }
}

bool Application::eventFilter(QObject *obj, QEvent *event)
{
#ifdef Q_WS_MAC // workaround for Mac, because mouse events are not received as it ought to be
    QMouseEvent *mouse = dynamic_cast<QMouseEvent*>(event);
    if (mouse)
    {
        if (dynamic_cast<UiMainWindow*>(obj))
        {
            switch(event->type())
            {
            case QEvent::MouseButtonPress:
                framework->Ui()->GraphicsView()->mousePressEvent(mouse);
                break;
            case QEvent::MouseButtonRelease:
                framework->Ui()->GraphicsView()->mouseReleaseEvent(mouse);
                break;
            case QEvent::MouseButtonDblClick:
                framework->Ui()->GraphicsView()->mouseDoubleClickEvent(mouse);
                break;
            case QEvent::MouseMove:
                if (mouse->buttons() == Qt::LeftButton)
                    framework->Ui()->GraphicsView()->mouseMoveEvent(mouse);
                break;
            }
        }
    }
#endif
    try
    {
        if (obj == this)
        {
            if (event->type() == QEvent::ApplicationActivate)
                appActivated = true;
            if (event->type() == QEvent::ApplicationDeactivate)
                appActivated = false;
        }

        return QObject::eventFilter(obj, event);
    }
    catch(const std::exception &e)
    {
        std::cout << std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)") << std::endl;
        RootLogCritical(std::string("QApp::eventFilter caught an exception: ") + (e.what() ? e.what() : "(null)"));
        throw;
    } catch(...)
    {
        std::cout << std::string("QApp::eventFilter caught an unknown exception!") << std::endl;
        RootLogCritical(std::string("QApp::eventFilter caught an unknown exception!"));
        throw;
    }
}

void Application::ChangeLanguage(const QString& file)
{
    QString filename = file;
    if (!filename.endsWith(".qm", Qt::CaseInsensitive))
        filename.append(".qm");
    QString tmp = filename;
    tmp.chop(3);
    QString str = tmp.right(2);

    QString name = "data/translations/qt_native_translations/qt_" + str + ".qm";

    // Remove old translators then change them to new.
    removeTranslator(nativeTranslator);

    if (QFile::exists(name))
    {
        if (nativeTranslator != 0)
        {
            nativeTranslator->load(name);
            installTranslator(nativeTranslator);
        }
    }
    else
    {
        if (nativeTranslator != 0 && nativeTranslator->isEmpty())
        {
            installTranslator(nativeTranslator);
        }
        else
        {
            SAFE_DELETE(nativeTranslator);
            nativeTranslator = new QTranslator;
            installTranslator(nativeTranslator);
        }
    }

    // Remove old translators then change them to new.
    removeTranslator(appTranslator);
    if (appTranslator->load(filename))
    {
        installTranslator(appTranslator);
        framework->GetConfigManager()->SetSetting(Framework::ConfigurationGroup(), "language", file.toStdString());
    }

    emit LanguageChanged();
}

bool Application::notify(QObject *receiver, QEvent *event)
{
    try
    {
        return QApplication::notify(receiver, event);
    } catch(const std::exception &e)
    {
        std::cout << std::string("QApp::notify caught an exception: ") << (e.what() ? e.what() : "(null)") << std::endl;
        RootLogCritical(std::string("QApp::notify caught an exception: ") + (e.what() ? e.what() : "(null)"));
        throw;
    } catch(...)
    {
        std::cout << std::string("QApp::notify caught an unknown exception!") << std::endl;
        RootLogCritical(std::string("QApp::notify caught an unknown exception!"));
        throw;
    }
}

void Application::UpdateFrame()
{
    // Don't pump the QEvents to QApplication if we are exiting
    // also don't process our mainloop frames.
    if (framework->IsExiting())
        return;

    try
    {
        const tick_t frameStartTime = GetCurrentClockTime();

        QApplication::processEvents(QEventLoop::AllEvents, 1);
        QApplication::sendPostedEvents();

        framework->ProcessOneFrame();

        const boost::program_options::variables_map &options = framework->ProgramOptions();
        double targetFpsLimit = 60.0;
        if (options.count("fpslimit") > 0)
        {
            targetFpsLimit = options["fpslimit"].as<float>();
            if (targetFpsLimit < 1.f)
                targetFpsLimit = 0.f;
        }

        tick_t timeNow = GetCurrentClockTime();

        static tick_t timerFrequency = GetCurrentClockFreq();

        double msecsSpentInFrame = (double)(timeNow - frameStartTime) * 1000.0 / timerFrequency;
        const double msecsPerFrame = 1000.0 / targetFpsLimit;

        double msecsToSleep = std::min(std::max(0.0, msecsPerFrame - msecsSpentInFrame), msecsPerFrame);

        // Reduce frame rate when unfocused
        if (!frameUpdateTimer.isActive())
        {
            if (appActivated || framework->IsHeadless())
                frameUpdateTimer.start(msecsToSleep);
            else
                frameUpdateTimer.start(msecsToSleep + msecsPerFrame); // Proceed at half FPS speed when unfocused (but never at half FPS when running a headless server).
        }
    }
    catch(const std::exception &e)
    {
        std::cout << "QApp::UpdateFrame caught an exception: " << (e.what() ? e.what() : "(null)") << std::endl;
        RootLogCritical(std::string("QApp::UpdateFrame caught an exception: ") + (e.what() ? e.what() : "(null)"));
        throw;
    }
    catch(...)
    {
        std::cout << "QApp::UpdateFrame caught an unknown exception!" << std::endl;
        RootLogCritical(std::string("QApp::UpdateFrame caught an unknown exception!"));
        throw;
    }
}

void Application::AboutToExit()
{
    emit ExitRequested();

    // If no-one canceled the exit as a response to the signal, exit
    if (framework->IsExiting())
        quit();
}
<|endoftext|>


<commit_before>#ifndef LIST_HPP
#define LIST_HPP

#include <sys/types.h>
#include <string.h>

namespace org_pqrs_KeyRemap4MacBook {
  class List {
  public:
    class Item {
      friend class List;

    public:
      Item(void) : prev_(NULL), next_(NULL) {}
      virtual ~Item(void) {}

      Item* getprev(void) { return prev_; }
      Item* getnext(void) { return next_; }

    protected:
      Item* prev_;
      Item* next_;
    };

    List(void);
    ~List(void);

    Item* front(void) { return front_; }
    Item* back(void) { return back_; }
    bool empty(void) const { return front_ == NULL; }
    size_t size(void) const { return size_; }

    Item* erase(Item* p);
    void clear(void);

    // We must call push_back with Item which allocated by "new".
    // Item will be deleted by pop/erase, you must not delete it yourself.
    //
    // Example:
    //   queue.push_back(new List::Item);
    //
    //   List::Item* p = queue.front();
    //   queue.pop_front();
    //
    // ----------------------------------------
    // *** Don't push same item twice. ***
    // *** BAD EXAMPLE ***
    // List::Item* item = new List::Item();
    // queue.push_back(item);
    // queue.push_back(item); // broken!!!
    //
    // ----------------------------------------
    void push_back(Item* p);
    void push_front(Item* p);
    void pop_front(void) { erase(front_); }

  private:
    List(const List& rhs) {}

    Item* front_;
    Item* back_;
    size_t size_;
  };
}

#endif
<commit_msg>misc changes<commit_after>#ifndef LIST_HPP
#define LIST_HPP

#include <sys/types.h>
#include <string.h>

namespace org_pqrs_KeyRemap4MacBook {
  class List {
  public:
    class Item {
      friend class List;

    public:
      Item(void) : prev_(NULL), next_(NULL) {}
      virtual ~Item(void) {}

      Item* getprev(void) { return prev_; }
      Item* getnext(void) { return next_; }

    protected:
      Item* prev_;
      Item* next_;
    };

    List(void);
    ~List(void);

    Item* front(void) { return front_; }
    Item* back(void) { return back_; }
    bool empty(void) const { return front_ == NULL; }
    size_t size(void) const { return size_; }

    Item* erase(Item* p);
    void clear(void);

    // We must call push_back with Item which allocated by "new".
    // Item will be deleted by pop/erase, you must not delete it yourself.
    //
    // Example:
    //   queue.push_back(new List::Item);
    //
    //   List::Item* p = queue.front();
    //   queue.pop_front();
    //
    // ----------------------------------------
    // *** Don't push same item twice. ***
    // *** BAD EXAMPLE ***
    // List::Item* item = new List::Item();
    // queue.push_back(item);
    // queue.push_back(item); // broken!!!
    //
    // ----------------------------------------
    void push_back(Item* p);
    void push_front(Item* p);
    void pop_front(void) { erase(front_); }

  private:
    List(const List& rhs) {}
    List& operator=(const List& rhs) { return *this; }

    Item* front_;
    Item* back_;
    size_t size_;
  };
}

#endif
<|endoftext|>


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

#include <string>
#include "sdps.h"
#include "hidreport.h"
#include "liberror.h"
#include "libcomm.h"
#include "buffer.h"
#include "sdp.h"
#include "rominfo.h"

IvtHeader *SDPCmdBase::search_ivt_header(shared_ptr<FileBuffer> data, size_t &off)
{
	for (off = 0; off < data->size(); off += 0x100)
	{
		IvtHeader *p = (IvtHeader*)(data->data() + off);
		if (p->IvtBarker == IVT_BARKER_HEADER)
			return p;
		if (p->IvtBarker == IVT_BARKER2_HEADER)
		{
			BootData *pDB = (BootData *) &(data->at(off + p->BootData - p->SelfAddr));

			/*Skip HDMI firmware for i.MX8MQ*/
			if (pDB->PluginFlag & 0xFFFFFFFE)
				continue;
			return p;
		}
	}
	off = -1;
	return NULL;
}

int SDPDcdCmd::run(CmdCtx*ctx)
{
	ROM_INFO * rom;
	rom = search_rom_info(ctx->m_config_item);
	if (rom == NULL)
	{
		string_ex err;
		err.format("%s:%d can't get rom info", __FUNCTION__, __LINE__);
		set_last_err_string(err);
		return -1;
	}
	init_cmd();

	shared_ptr<FileBuffer> buff = get_file_buffer(m_filename);

	size_t off = 0;
	IvtHeader *pIVT = search_ivt_header(buff, off);
	if (pIVT == NULL)
	{
		return 0;
	}

	if (pIVT->DCDAddress == 0)
		return 0;

	uint8_t * pdcd = &(buff->at(off + pIVT->DCDAddress - pIVT->SelfAddr));

	if (pdcd[0] != HAB_TAG_DCD)
	{
		string_ex err;
		err.format("%s:%d DCD TAG miss matched", __FUNCTION__, __LINE__);
		set_last_err_string(err);
		return -1;
	}

	uint32_t size = (pdcd[1] << 8) | pdcd[2];

	m_spdcmd.m_cmd = ROM_KERNEL_CMD_DCD_WRITE;
	m_spdcmd.m_addr = EndianSwap(rom->free_addr);
	m_spdcmd.m_count = EndianSwap(size);

	HIDTrans dev;
	if (dev.open(ctx->m_dev))
		return -1;

	HIDReport report(&dev);
	if (report.write(&m_spdcmd, sizeof(m_spdcmd), 1))
		return -1;

	if (report.write(pdcd, size, 2))
		return -1;

	if (check_ack(&report, ROM_WRITE_ACK))
		return -1;

	return 0;
}

int SDPSkipDCDCmd::run(CmdCtx*ctx)
{
	HIDTrans dev;
	if (dev.open(ctx->m_dev))
		return -1;

	HIDReport report(&dev);
	if (report.write(&m_spdcmd, sizeof(m_spdcmd), 1))
		return -1;

	if (check_ack(&report, ROM_OK_ACK))
		return -1;

	return 0;
}

int SDPBootCmd::run(CmdCtx *ctx)
{
	string str;
	str = "SDP: dcd -f ";
	str += m_filename;
	SDPDcdCmd dcd((char *)str.c_str());
	if (dcd.parser()) return -1;
	if (dcd.run(ctx)) return -1;

	str = "SDP: write -f ";
	str += m_filename;
	str += " -ivt 0";
	SDPWriteCmd wr((char *)str.c_str());
	if (wr.parser()) return -1;
	if (wr.run(ctx)) return -1;

	str = "SDP: jump -f ";
	str += m_filename;
	str += " -ivt";

	SDPJumpCmd jmp((char *)str.c_str());
	if (!m_nojump)
	{
		if (jmp.parser()) return -1;
		if (jmp.run(ctx)) return -1;
	}
	return 0;
}

int SDPStatusCmd::run(CmdCtx *ctx)
{
	HIDTrans dev;
	if (dev.open(ctx->m_dev))
		return -1;

	HIDReport report(&dev);
	if (report.write(&m_spdcmd, sizeof(m_spdcmd), 1))
		return -1;

	if (get_hab_type(&report) == HabUnknown)
		return -1;

	uint32_t status;
	if (get_status(&report, status, 4))
		return -1;

	return 0;
}

int SDPWriteCmd::run(CmdCtx*ctx)
{
	size_t size;
	uint8_t *pbuff;
	int offset = 0;

	shared_ptr<FileBuffer> fbuff = get_file_buffer(m_filename);

	if (fbuff == NULL)
		return -1;

	if (m_Ivt < 0)
	{
		pbuff = fbuff->data();
		size = fbuff->size();

		offset = m_offset;
		size -= m_offset;
	}
	else
	{
		size_t off;
		IvtHeader *pIvt = search_ivt_header(fbuff, off);
		for (int i = 0; i < m_Ivt; i++)
		{
			off += 0x100;
			pIvt = search_ivt_header(fbuff, off);
		}
		if (pIvt == NULL)
		{
			set_last_err_string("Can find validate IVT header");
			return -1;
		}

		BootData *pDB = (BootData *) &(fbuff->at(off + pIvt->BootData - pIvt->SelfAddr));

		m_download_addr = pIvt->SelfAddr;
		//size = fbuff->size() - off;
		size = pDB->ImageSize;

		pbuff = (uint8_t*)pIvt;
	}
	return run(ctx, pbuff + offset, size, m_download_addr);
}

int SDPWriteCmd::run(CmdCtx *ctx, void *pbuff, size_t size, uint32_t addr)
{
	HIDTrans dev;
	if (dev.open(ctx->m_dev))
		return -1;

	HIDReport report(&dev);

	report.m_notify_total = size;

	for (size_t i=0; i < size; i += m_max_download_pre_cmd)
	{
		size_t sz;
		sz = size - i;
		if (sz > m_max_download_pre_cmd)
			sz = m_max_download_pre_cmd;

		m_spdcmd.m_addr = EndianSwap((uint32_t)(addr + i)); // force use 32bit endian swap function;
		m_spdcmd.m_count = EndianSwap((uint32_t)sz); //force use 32bit endian swap function;

		report.m_postion_base = i;
		report.m_skip_notify = true;

		if (report.write(&m_spdcmd, sizeof(m_spdcmd), 1))
			return -1;

		report.m_skip_notify = false;

		if (report.write(((uint8_t*)pbuff)+i, sz, 2))
			return -1;

		if (check_ack(&report, ROM_STATUS_ACK))
			return -1;
	}

	return 0;
}

int SDPJumpCmd::run(CmdCtx *ctx)
{
	ROM_INFO * rom;
	rom = search_rom_info(ctx->m_config_item);

	HIDTrans dev;
	if (dev.open(ctx->m_dev))
		return -1;

	HIDReport report(&dev);

	if (rom == NULL)
	{
		string_ex err;
		err.format("%s:%d can't get rom info", __FUNCTION__, __LINE__);
		set_last_err_string(err);
		return -1;
	}

	if (rom->flags & ROM_INFO_SPL_JUMP)
	{
		m_spdcmd.m_addr = EndianSwap(m_jump_addr);
		if (report.write(&m_spdcmd, sizeof(m_spdcmd), 1))
			return -1;

		//Omit last return value.
		check_ack(&report, ROM_OK_ACK);
		return 0;
	}

	shared_ptr<FileBuffer> buff = get_file_buffer(m_filename);

	size_t off = 0;
	IvtHeader *pIVT = search_ivt_header(buff, off);

	m_spdcmd.m_addr = EndianSwap(pIVT->SelfAddr);

	if (rom->flags & ROM_INFO_HID_SKIP_DCD)
	{
		SDPSkipDCDCmd skipcmd(NULL);
		if (skipcmd.run(ctx))
			return -1;
	}
	else
	{	/*Clear DCD*/
		IvtHeader header;
		header = *pIVT;

		header.DCDAddress = 0;

		SDPWriteCmd writecmd(NULL);
		if(writecmd.run(ctx, &header, sizeof(header), pIVT->SelfAddr))
			return -1;
	}

	if (report.write(&m_spdcmd, sizeof(m_spdcmd), 1))
		return -1;

	//Omit last return value.
	check_ack(&report, ROM_OK_ACK);

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

#include <string>
#include "sdps.h"
#include "hidreport.h"
#include "liberror.h"
#include "libcomm.h"
#include "buffer.h"
#include "sdp.h"
#include "rominfo.h"

IvtHeader *SDPCmdBase::search_ivt_header(shared_ptr<FileBuffer> data, size_t &off)
{
	for (off = 0; off < data->size(); off += 0x100)
	{
		IvtHeader *p = (IvtHeader*)(data->data() + off);
		if (p->IvtBarker == IVT_BARKER_HEADER)
			return p;
		if (p->IvtBarker == IVT_BARKER2_HEADER)
		{
			BootData *pDB = (BootData *) &(data->at(off + p->BootData - p->SelfAddr));

			/*Skip HDMI firmware for i.MX8MQ*/
			if (pDB->PluginFlag & 0xFFFFFFFE)
				continue;
			return p;
		}
	}
	off = -1;
	return NULL;
}

int SDPDcdCmd::run(CmdCtx*ctx)
{
	ROM_INFO * rom;
	rom = search_rom_info(ctx->m_config_item);
	if (rom == NULL)
	{
		string_ex err;
		err.format("%s:%d can't get rom info", __FUNCTION__, __LINE__);
		set_last_err_string(err);
		return -1;
	}
	init_cmd();

	shared_ptr<FileBuffer> buff = get_file_buffer(m_filename);

	size_t off = 0;
	IvtHeader *pIVT = search_ivt_header(buff, off);
	if (pIVT == NULL)
	{
		return 0;
	}

	if (pIVT->DCDAddress == 0)
		return 0;

	uint8_t * pdcd = &(buff->at(off + pIVT->DCDAddress - pIVT->SelfAddr));

	if (pdcd[0] != HAB_TAG_DCD)
	{
		string_ex err;
		err.format("%s:%d DCD TAG miss matched", __FUNCTION__, __LINE__);
		set_last_err_string(err);
		return -1;
	}

	uint32_t size = (pdcd[1] << 8) | pdcd[2];

	m_spdcmd.m_cmd = ROM_KERNEL_CMD_DCD_WRITE;
	m_spdcmd.m_addr = EndianSwap(rom->free_addr);
	m_spdcmd.m_count = EndianSwap(size);

	HIDTrans dev;
	if (dev.open(ctx->m_dev))
		return -1;

	HIDReport report(&dev);
	if (report.write(&m_spdcmd, sizeof(m_spdcmd), 1))
		return -1;

	if (report.write(pdcd, size, 2))
		return -1;

	if (check_ack(&report, ROM_WRITE_ACK))
		return -1;

	return 0;
}

int SDPSkipDCDCmd::run(CmdCtx*ctx)
{
	HIDTrans dev;
	if (dev.open(ctx->m_dev))
		return -1;

	HIDReport report(&dev);
	if (report.write(&m_spdcmd, sizeof(m_spdcmd), 1))
		return -1;

	if (check_ack(&report, ROM_OK_ACK))
		return -1;

	return 0;
}

int SDPBootCmd::run(CmdCtx *ctx)
{
	string str;
	str = "SDP: dcd -f ";
	str += m_filename;
	SDPDcdCmd dcd((char *)str.c_str());
	if (dcd.parser()) return -1;
	if (dcd.run(ctx)) return -1;

	str = "SDP: write -f ";
	str += m_filename;
	str += " -ivt 0";
	SDPWriteCmd wr((char *)str.c_str());
	if (wr.parser()) return -1;
	if (wr.run(ctx)) return -1;

	str = "SDP: jump -f ";
	str += m_filename;
	str += " -ivt";

	SDPJumpCmd jmp((char *)str.c_str());
	if (!m_nojump)
	{
		if (jmp.parser()) return -1;
		if (jmp.run(ctx)) return -1;
	}
	return 0;
}

int SDPStatusCmd::run(CmdCtx *ctx)
{
	HIDTrans dev;
	if (dev.open(ctx->m_dev))
		return -1;

	HIDReport report(&dev);
	if (report.write(&m_spdcmd, sizeof(m_spdcmd), 1))
		return -1;

	if (get_hab_type(&report) == HabUnknown)
		return -1;

	uint32_t status;
	if (get_status(&report, status, 4))
		return -1;

	return 0;
}

int SDPWriteCmd::run(CmdCtx*ctx)
{
	size_t size;
	uint8_t *pbuff;
	int offset = 0;

	shared_ptr<FileBuffer> fbuff = get_file_buffer(m_filename);

	if (fbuff == NULL)
		return -1;

	if (m_Ivt < 0)
	{
		pbuff = fbuff->data();
		size = fbuff->size();

		offset = m_offset;
		size -= m_offset;
	}
	else
	{
		size_t off;
		IvtHeader *pIvt = search_ivt_header(fbuff, off);
		for (int i = 0; i < m_Ivt; i++)
		{
			off += 0x100;
			pIvt = search_ivt_header(fbuff, off);
		}
		if (pIvt == NULL)
		{
			set_last_err_string("Can find validate IVT header");
			return -1;
		}

		BootData *pDB = (BootData *) &(fbuff->at(off + pIvt->BootData - pIvt->SelfAddr));

		m_download_addr = pIvt->SelfAddr;
		//size = fbuff->size() - off;
		size = pDB->ImageSize;

		//ImageSize may be bigger than Imagesize because ImageSize include IVT offset
		//Difference boot storage have difference IVT offset.
		if (size > fbuff->size() - off)
			size = fbuff->size() - off;

		pbuff = (uint8_t*)pIvt;
	}
	return run(ctx, pbuff + offset, size, m_download_addr);
}

int SDPWriteCmd::run(CmdCtx *ctx, void *pbuff, size_t size, uint32_t addr)
{
	HIDTrans dev;
	if (dev.open(ctx->m_dev))
		return -1;

	HIDReport report(&dev);

	report.m_notify_total = size;

	for (size_t i=0; i < size; i += m_max_download_pre_cmd)
	{
		size_t sz;
		sz = size - i;
		if (sz > m_max_download_pre_cmd)
			sz = m_max_download_pre_cmd;

		m_spdcmd.m_addr = EndianSwap((uint32_t)(addr + i)); // force use 32bit endian swap function;
		m_spdcmd.m_count = EndianSwap((uint32_t)sz); //force use 32bit endian swap function;

		report.m_postion_base = i;
		report.m_skip_notify = true;

		if (report.write(&m_spdcmd, sizeof(m_spdcmd), 1))
			return -1;

		report.m_skip_notify = false;

		if (report.write(((uint8_t*)pbuff)+i, sz, 2))
			return -1;

		if (check_ack(&report, ROM_STATUS_ACK))
			return -1;
	}

	return 0;
}

int SDPJumpCmd::run(CmdCtx *ctx)
{
	ROM_INFO * rom;
	rom = search_rom_info(ctx->m_config_item);

	HIDTrans dev;
	if (dev.open(ctx->m_dev))
		return -1;

	HIDReport report(&dev);

	if (rom == NULL)
	{
		string_ex err;
		err.format("%s:%d can't get rom info", __FUNCTION__, __LINE__);
		set_last_err_string(err);
		return -1;
	}

	if (rom->flags & ROM_INFO_SPL_JUMP)
	{
		m_spdcmd.m_addr = EndianSwap(m_jump_addr);
		if (report.write(&m_spdcmd, sizeof(m_spdcmd), 1))
			return -1;

		//Omit last return value.
		check_ack(&report, ROM_OK_ACK);
		return 0;
	}

	shared_ptr<FileBuffer> buff = get_file_buffer(m_filename);

	size_t off = 0;
	IvtHeader *pIVT = search_ivt_header(buff, off);

	m_spdcmd.m_addr = EndianSwap(pIVT->SelfAddr);

	if (rom->flags & ROM_INFO_HID_SKIP_DCD)
	{
		SDPSkipDCDCmd skipcmd(NULL);
		if (skipcmd.run(ctx))
			return -1;
	}
	else
	{	/*Clear DCD*/
		IvtHeader header;
		header = *pIVT;

		header.DCDAddress = 0;

		SDPWriteCmd writecmd(NULL);
		if(writecmd.run(ctx, &header, sizeof(header), pIVT->SelfAddr))
			return -1;
	}

	if (report.write(&m_spdcmd, sizeof(m_spdcmd), 1))
		return -1;

	//Omit last return value.
	check_ack(&report, ROM_OK_ACK);

	return 0;
}
<|endoftext|>