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

  This file is part of the elastix software.

  Copyright (c) University Medical Center Utrecht. All rights reserved.
  See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
  details.

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

======================================================================*/

#ifndef __transformix_CXX_
#define __transformix_CXX_

#include "transformix.h"

int main( int argc, char **argv )
{
  /** Check if "-help" or "--version" was asked for.*/
  if ( argc == 1 )
  {
    std::cout << "Use \"transformix --help\" for information about transformix-usage." << std::endl;
    return 0;
  }
  else if ( argc == 2 )
  {
    std::string argument( argv[ 1 ] );
    if ( argument == "-help" || argument == "--help" )
    {
      PrintHelp();
      return 0;
    }
    else if( argument == "--version" )
    {
      std::cout << std::fixed;
      std::cout << std::showpoint;
      std::cout << std::setprecision(3);
      std::cout << "transformix version: " << __ELASTIX_VERSION << std::endl;
      return 0;
    }
    else
    {
      std::cout << "Use \"transformix --help\" for information about transformix-usage." << std::endl;
      return 0;
    }
  }

  /** Some typedef's.*/
  typedef elx::TransformixMain                      TransformixMainType;
  typedef TransformixMainType::Pointer              TransformixMainPointer;
  typedef TransformixMainType::ArgumentMapType      ArgumentMapType;
  typedef ArgumentMapType::value_type               ArgumentMapEntryType;

  /** Declare an instance of the Transformix class. */
  TransformixMainPointer  transformix;

  /** Initialize. */
  int               returndummy = 0;
  ArgumentMapType   argMap;
  bool              outFolderPresent = false;
  std::string       outFolder = "";
  std::string       logFileName = "";

  /** Put command line parameters into parameterFileList. */
  for ( unsigned int i = 1; static_cast<long>(i) < argc - 1; i += 2 )
  {
    std::string key( argv[ i ] );
    std::string value( argv[ i + 1 ] );

    if ( key == "-out" )
    {
      /** Make sure that last character of the output folder equals a '/'. */
      if ( value.find_last_of( "/" ) != value.size() - 1 )
      {
        value.append( "/" );
      }

      /** Save this information. */
      outFolderPresent = true;
      outFolder = value;

    } // end if key == "-out"

    /** Attempt to save the arguments in the ArgumentMap. */
    if ( argMap.count( key ) == 0 )
    {
      argMap.insert( ArgumentMapEntryType( key.c_str(), value.c_str() ) );
    }
    else
    {
      /** Duplicate arguments. */
      std::cerr << "WARNING!" << std::endl;
      std::cerr << "Argument "<< key.c_str() << "is only required once." << std::endl;
      std::cerr << "Arguments " << key.c_str() << " " << value.c_str() << "are ignored" << std::endl;
    }

  } // end for loop

  /** The argv0 argument, required for finding the component.dll/so's. */
  argMap.insert( ArgumentMapEntryType( "-argv0", argv[ 0 ] )  );

  /** Check that the option "-tp" is given. */
  if ( argMap.count( "-tp" ) == 0 )
  {
    std::cerr << "ERROR: No CommandLine option \"-tp\" given!" << std::endl;
    returndummy |= -1;
  }

  /** Check that at least one of the options "-in" or "-ipp" or "-jac" is given. */
  if ( argMap.count( "-in" ) == 0
    && argMap.count( "-ipp" ) == 0
    && argMap.count( "-def" ) == 0
    && argMap.count( "-jac" ) == 0 )
  {
    std::cerr << "ERROR: At least one of the CommandLine options \"-in\" or "
      << "\"-def\" or \"-jac\" should be given!" << std::endl;
    returndummy |= -1;
  }

  /** Check if the -out option is given and setup xout. */
  if ( outFolderPresent )
  {
    /** Check if the output directory exists. */
    bool outFolderExists = itksys::SystemTools::FileIsDirectory( outFolder.c_str() );
    if ( !outFolderExists )
    {
      std::cerr << "ERROR: the output directory does not exist." << std::endl;
      std::cerr << "You are responsible for creating it." << std::endl;
      returndummy |= -2;
    }
    else
    {
      /** Setup xout. */
      logFileName = argMap[ "-out" ] + "transformix.log" ;
      int returndummy2 = elx::xoutSetup( logFileName.c_str() );
      if ( returndummy2 )
      {
        std::cerr << "ERROR while setting up xout." << std::endl;
      }
      returndummy |= returndummy2;
    }
  }
  else
  {
    returndummy = -2;
    std::cerr << "ERROR: No CommandLine option \"-out\" given!" << std::endl;
  }

  /** Stop if some fatal errors occurred. */
  if ( returndummy )
  {
    return returndummy;
  }

  elxout << std::endl;

  /** Declare a timer, start it and print the start time. */
  tmr::Timer::Pointer totaltimer = tmr::Timer::New();
  totaltimer->StartTimer();
  elxout << "transformix is started at " << totaltimer->PrintStartTime()
    << ".\n" << std::endl;

  /** Print where transformix was run. */
  itksys::SystemInformation info;
  info.RunCPUCheck();
  info.RunOSCheck();
  info.RunMemoryCheck();
  elxout << "transformix runs at: " << info.GetHostname() << std::endl;
  elxout << "  " << info.GetOSName() << " "
    << info.GetOSRelease() << ( info.Is64Bits() ? " (x64), " : ", " )
    << info.GetOSVersion()
    << ", with " << info.GetTotalPhysicalMemory() << " MB memory."
    << std::endl;

  /**
   * ********************* START TRANSFORMATION *******************
   */

  /** Set transformix. */
  transformix = TransformixMainType::New();

  /** Print a start message. */
  elxout << "Running transformix with parameter file \""
      << argMap[ "-tp" ] << "\".\n" << std::endl;

  /** Run transformix. */
  returndummy = transformix->Run( argMap );

  /** Check if transformix run without errors. */
  if ( returndummy != 0 )
  {
    xl::xout["error"] << "Errors occurred" << std::endl;
    return returndummy;
  }

  /** Stop timer and print it. */
  totaltimer->StopTimer();
  elxout << "\nTransformix has finished at " <<
    totaltimer->PrintStopTime() << "." << std::endl;
  elxout << "Elapsed time: " <<
    totaltimer->PrintElapsedTimeDHMS() << ".\n" << std::endl;

  /** Clean up. */
  transformix = 0;
  TransformixMainType::UnloadComponents();

  /** Exit and return the error code. */
  return returndummy;

} // end main

/**
 * *********************** PrintHelp ****************************
 */

void PrintHelp( void )
{
  /** Print the version. */
  std::cout << std::fixed;
  std::cout << std::showpoint;
  std::cout << std::setprecision( 3 );
  std::cout << "transformix version: " << __ELASTIX_VERSION << "\n" << std::endl;

  /** What is transformix? */
  std::cout << "transformix applies a transform on an input image and/or "
    "generates a deformation field.\n";
  std::cout << "The transform is specified in the transform-parameter file.\n"
    << std::endl;

  /** Mandatory arguments. */
  std::cout << "Call transformix from the command line with mandatory arguments:\n";
  std::cout << "-out      output directory\n";
  std::cout << "-tp       transform-parameter file, only 1\n" << std::endl;

  /** Optional arguments. */
  std::cout << "Optional extra commands:\n";
  std::cout << "-in       input image to deform\n";
  std::cout << "-def      file containing input-image points\n";
  std::cout << "          the point are transformed according to the specified "
    "transform-parameter file\n";
  std::cout << "          use \"-def all\" to transform all points from the "
    "input-image, which effectively generates a deformation field.\n";
  std::cout << "-jac      use \"-jac all\" to generate an image with the "
    << "determinant of the spatial Jacobian\n";
  std::cout << "-priority set the process priority to high or belownormal "
    "(Windows only)\n";
  std::cout << "-threads  set the maximum number of threads of transformix\n";
  std::cout << "At least one of the options \"-in\" or \"-def\" or \"-jac\" should be given.\n"
    << std::endl;

  /** The parameter file. */
  std::cout << "The transform-parameter file must contain all the information "
    "necessary for transformix to run properly. That includes which transform "
    "to use, with which parameters, etc.\n";
  std::cout << "For a usable transform-parameter file, see the output of "
    "elastix.\n" << std::endl;

  std::cout << "Need further help? Check the website http://elastix.isi.uu.nl, "
    "or mail elastix.support@gmail.com." << std::endl;

} // end PrintHelp()

#endif // end #ifndef __transformix_CXX_

<commit_msg>SK: -DOC: added some documentation for the '-jacmat all' option -BUG: -jacmat was not counted as one of the mandatory -in -def -jac -jacmat<commit_after>/*======================================================================

  This file is part of the elastix software.

  Copyright (c) University Medical Center Utrecht. All rights reserved.
  See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
  details.

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

======================================================================*/

#ifndef __transformix_CXX_
#define __transformix_CXX_

#include "transformix.h"

int main( int argc, char **argv )
{
  /** Check if "-help" or "--version" was asked for.*/
  if ( argc == 1 )
  {
    std::cout << "Use \"transformix --help\" for information about transformix-usage." << std::endl;
    return 0;
  }
  else if ( argc == 2 )
  {
    std::string argument( argv[ 1 ] );
    if ( argument == "-help" || argument == "--help" )
    {
      PrintHelp();
      return 0;
    }
    else if( argument == "--version" )
    {
      std::cout << std::fixed;
      std::cout << std::showpoint;
      std::cout << std::setprecision(3);
      std::cout << "transformix version: " << __ELASTIX_VERSION << std::endl;
      return 0;
    }
    else
    {
      std::cout << "Use \"transformix --help\" for information about transformix-usage." << std::endl;
      return 0;
    }
  }

  /** Some typedef's.*/
  typedef elx::TransformixMain                      TransformixMainType;
  typedef TransformixMainType::Pointer              TransformixMainPointer;
  typedef TransformixMainType::ArgumentMapType      ArgumentMapType;
  typedef ArgumentMapType::value_type               ArgumentMapEntryType;

  /** Declare an instance of the Transformix class. */
  TransformixMainPointer  transformix;

  /** Initialize. */
  int               returndummy = 0;
  ArgumentMapType   argMap;
  bool              outFolderPresent = false;
  std::string       outFolder = "";
  std::string       logFileName = "";

  /** Put command line parameters into parameterFileList. */
  for ( unsigned int i = 1; static_cast<long>(i) < argc - 1; i += 2 )
  {
    std::string key( argv[ i ] );
    std::string value( argv[ i + 1 ] );

    if ( key == "-out" )
    {
      /** Make sure that last character of the output folder equals a '/'. */
      if ( value.find_last_of( "/" ) != value.size() - 1 )
      {
        value.append( "/" );
      }

      /** Save this information. */
      outFolderPresent = true;
      outFolder = value;

    } // end if key == "-out"

    /** Attempt to save the arguments in the ArgumentMap. */
    if ( argMap.count( key ) == 0 )
    {
      argMap.insert( ArgumentMapEntryType( key.c_str(), value.c_str() ) );
    }
    else
    {
      /** Duplicate arguments. */
      std::cerr << "WARNING!" << std::endl;
      std::cerr << "Argument "<< key.c_str() << "is only required once." << std::endl;
      std::cerr << "Arguments " << key.c_str() << " " << value.c_str() << "are ignored" << std::endl;
    }

  } // end for loop

  /** The argv0 argument, required for finding the component.dll/so's. */
  argMap.insert( ArgumentMapEntryType( "-argv0", argv[ 0 ] )  );

  /** Check that the option "-tp" is given. */
  if ( argMap.count( "-tp" ) == 0 )
  {
    std::cerr << "ERROR: No CommandLine option \"-tp\" given!" << std::endl;
    returndummy |= -1;
  }

  /** Check that at least one of the following options is given. */
  if ( argMap.count( "-in" ) == 0
    && argMap.count( "-ipp" ) == 0
    && argMap.count( "-def" ) == 0
    && argMap.count( "-jac" ) == 0
    && argMap.count( "-jacmat" ) == 0 )
  {
    std::cerr << "ERROR: At least one of the CommandLine options \"-in\",	"
      << "\"-def\", \"-jac\", or \"-jacmat\" should be given!" << std::endl;
    returndummy |= -1;
  }

  /** Check if the -out option is given and setup xout. */
  if ( outFolderPresent )
  {
    /** Check if the output directory exists. */
    bool outFolderExists = itksys::SystemTools::FileIsDirectory( outFolder.c_str() );
    if ( !outFolderExists )
    {
      std::cerr << "ERROR: the output directory does not exist." << std::endl;
      std::cerr << "You are responsible for creating it." << std::endl;
      returndummy |= -2;
    }
    else
    {
      /** Setup xout. */
      logFileName = argMap[ "-out" ] + "transformix.log" ;
      int returndummy2 = elx::xoutSetup( logFileName.c_str() );
      if ( returndummy2 )
      {
        std::cerr << "ERROR while setting up xout." << std::endl;
      }
      returndummy |= returndummy2;
    }
  }
  else
  {
    returndummy = -2;
    std::cerr << "ERROR: No CommandLine option \"-out\" given!" << std::endl;
  }

  /** Stop if some fatal errors occurred. */
  if ( returndummy )
  {
    return returndummy;
  }

  elxout << std::endl;

  /** Declare a timer, start it and print the start time. */
  tmr::Timer::Pointer totaltimer = tmr::Timer::New();
  totaltimer->StartTimer();
  elxout << "transformix is started at " << totaltimer->PrintStartTime()
    << ".\n" << std::endl;

  /** Print where transformix was run. */
  itksys::SystemInformation info;
  info.RunCPUCheck();
  info.RunOSCheck();
  info.RunMemoryCheck();
  elxout << "transformix runs at: " << info.GetHostname() << std::endl;
  elxout << "  " << info.GetOSName() << " "
    << info.GetOSRelease() << ( info.Is64Bits() ? " (x64), " : ", " )
    << info.GetOSVersion()
    << ", with " << info.GetTotalPhysicalMemory() << " MB memory."
    << std::endl;

  /**
   * ********************* START TRANSFORMATION *******************
   */

  /** Set transformix. */
  transformix = TransformixMainType::New();

  /** Print a start message. */
  elxout << "Running transformix with parameter file \""
      << argMap[ "-tp" ] << "\".\n" << std::endl;

  /** Run transformix. */
  returndummy = transformix->Run( argMap );

  /** Check if transformix run without errors. */
  if ( returndummy != 0 )
  {
    xl::xout["error"] << "Errors occurred" << std::endl;
    return returndummy;
  }

  /** Stop timer and print it. */
  totaltimer->StopTimer();
  elxout << "\nTransformix has finished at " <<
    totaltimer->PrintStopTime() << "." << std::endl;
  elxout << "Elapsed time: " <<
    totaltimer->PrintElapsedTimeDHMS() << ".\n" << std::endl;

  /** Clean up. */
  transformix = 0;
  TransformixMainType::UnloadComponents();

  /** Exit and return the error code. */
  return returndummy;

} // end main

/**
 * *********************** PrintHelp ****************************
 */

void PrintHelp( void )
{
  /** Print the version. */
  std::cout << std::fixed;
  std::cout << std::showpoint;
  std::cout << std::setprecision( 3 );
  std::cout << "transformix version: " << __ELASTIX_VERSION << "\n" << std::endl;

  /** What is transformix? */
  std::cout << "transformix applies a transform on an input image and/or "
    "generates a deformation field.\n";
  std::cout << "The transform is specified in the transform-parameter file.\n"
    << std::endl;

  /** Mandatory arguments. */
  std::cout << "Call transformix from the command line with mandatory arguments:\n";
  std::cout << "-out      output directory\n";
  std::cout << "-tp       transform-parameter file, only 1\n" << std::endl;

  /** Optional arguments. */
  std::cout << "Optional extra commands:\n";
  std::cout << "-in       input image to deform\n";
  std::cout << "-def      file containing input-image points\n";
  std::cout << "          the point are transformed according to the specified "
    "transform-parameter file\n";
  std::cout << "          use \"-def all\" to transform all points from the "
    "input-image, which effectively generates a deformation field.\n";
  std::cout << "-jac      use \"-jac all\" to generate an image with the "
    << "determinant of the spatial Jacobian\n";
  std::cout << "-jacmat   use \"-jacmat all\" to generate an image with the "
    << "spatial Jacobian matrix at each voxel\n";
  std::cout << "-priority set the process priority to high or belownormal "
    "(Windows only)\n";
  std::cout << "-threads  set the maximum number of threads of transformix\n";
  std::cout << "At least one of the options \"-in\", \"-def\", \"-jac\", or \"-jacmat\" should be given.\n"
    << std::endl;

  /** The parameter file. */
  std::cout << "The transform-parameter file must contain all the information "
    "necessary for transformix to run properly. That includes which transform "
    "to use, with which parameters, etc.\n";
  std::cout << "For a usable transform-parameter file, see the output of "
    "elastix.\n" << std::endl;

  std::cout << "Need further help? Check the website http://elastix.isi.uu.nl, "
    "or mail elastix.support@gmail.com." << std::endl;

} // end PrintHelp()

#endif // end #ifndef __transformix_CXX_

<|endoftext|>


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

#include "tools/json_schema_compiler/util.h"

#include "base/values.h"

namespace json_schema_compiler {
namespace util {

bool GetItemFromList(const ListValue& from, int index, int* out) {
  return from.GetInteger(index, out);
}

bool GetItemFromList(const ListValue& from, int index, bool* out) {
  return from.GetBoolean(index, out);
}

bool GetItemFromList(const ListValue& from, int index, double* out) {
  return from.GetDouble(index, out);
}

bool GetItemFromList(const ListValue& from, int index, std::string* out) {
  return from.GetString(index, out);
}

bool GetItemFromList(const ListValue& from, int index,
    linked_ptr<base::DictionaryValue>* out) {
  DictionaryValue* dict = NULL;
  if (!from.GetDictionary(index, &dict)) {
    return false;
  }
  *out = linked_ptr<DictionaryValue>(dict->DeepCopy());
  return true;
}

void AddItemToList(const int from, base::ListValue* out) {
  out->Append(base::Value::CreateIntegerValue(from));
}
void AddItemToList(const bool from, base::ListValue* out) {
  out->Append(base::Value::CreateBooleanValue(from));
}
void AddItemToList(const double from, base::ListValue* out) {
  out->Append(base::Value::CreateDoubleValue(from));
}
void AddItemToList(const std::string& from, base::ListValue* out) {
  out->Append(base::Value::CreateStringValue(from));
}
void AddItemToList(const linked_ptr<base::DictionaryValue> from,
    base::ListValue* out) {
  out->Append(static_cast<Value*>(from->DeepCopy()));
}

}  // namespace api_util
}  // namespace extensions
<commit_msg>json_schema_compiler: make util::AddItemToList take a const reference to match the compiler.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "tools/json_schema_compiler/util.h"

#include "base/values.h"

namespace json_schema_compiler {
namespace util {

bool GetItemFromList(const ListValue& from, int index, int* out) {
  return from.GetInteger(index, out);
}

bool GetItemFromList(const ListValue& from, int index, bool* out) {
  return from.GetBoolean(index, out);
}

bool GetItemFromList(const ListValue& from, int index, double* out) {
  return from.GetDouble(index, out);
}

bool GetItemFromList(const ListValue& from, int index, std::string* out) {
  return from.GetString(index, out);
}

bool GetItemFromList(const ListValue& from, int index,
    linked_ptr<base::DictionaryValue>* out) {
  DictionaryValue* dict = NULL;
  if (!from.GetDictionary(index, &dict)) {
    return false;
  }
  *out = linked_ptr<DictionaryValue>(dict->DeepCopy());
  return true;
}

void AddItemToList(const int from, base::ListValue* out) {
  out->Append(base::Value::CreateIntegerValue(from));
}
void AddItemToList(const bool from, base::ListValue* out) {
  out->Append(base::Value::CreateBooleanValue(from));
}
void AddItemToList(const double from, base::ListValue* out) {
  out->Append(base::Value::CreateDoubleValue(from));
}
void AddItemToList(const std::string& from, base::ListValue* out) {
  out->Append(base::Value::CreateStringValue(from));
}
void AddItemToList(const linked_ptr<base::DictionaryValue>& from,
    base::ListValue* out) {
  out->Append(static_cast<Value*>(from->DeepCopy()));
}

}  // namespace api_util
}  // namespace extensions
<|endoftext|>


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

#include "thread.h"
#include "sysinfo.h"
#include "string.h"

#include <iostream>
#include <xmmintrin.h>

#if defined(PTHREADS_WIN32)
#pragma comment (lib, "pthreadVC.lib")
#endif

////////////////////////////////////////////////////////////////////////////////
/// Windows Platform
////////////////////////////////////////////////////////////////////////////////

#if defined(__WIN32__)

#define WIN32_LEAN_AND_MEAN
#include <windows.h>

namespace embree
{
  /*! set the affinity of a given thread */
  void setAffinity(HANDLE thread, ssize_t affinity)
  {
    OSVERSIONINFO osvi;
    ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx(&osvi);
    typedef WORD (WINAPI *GetActiveProcessorGroupCountFunc)();
    typedef DWORD (WINAPI *GetActiveProcessorCountFunc)(WORD);
    typedef BOOL (WINAPI *SetThreadGroupAffinityFunc)(HANDLE, const GROUP_AFFINITY *, PGROUP_AFFINITY);
    typedef BOOL (WINAPI *SetThreadIdealProcessorExFunc)(HANDLE, PPROCESSOR_NUMBER, PPROCESSOR_NUMBER);
    HMODULE hlib = LoadLibrary("Kernel32");
    GetActiveProcessorGroupCountFunc pGetActiveProcessorGroupCount = (GetActiveProcessorGroupCountFunc)GetProcAddress(hlib, "GetActiveProcessorGroupCount");
    GetActiveProcessorCountFunc pGetActiveProcessorCount = (GetActiveProcessorCountFunc)GetProcAddress(hlib, "GetActiveProcessorCount");
    SetThreadGroupAffinityFunc pSetThreadGroupAffinity = (SetThreadGroupAffinityFunc)GetProcAddress(hlib, "SetThreadGroupAffinity");
    SetThreadIdealProcessorExFunc pSetThreadIdealProcessorEx = (SetThreadIdealProcessorExFunc)GetProcAddress(hlib, "SetThreadIdealProcessorEx");
    if (pGetActiveProcessorGroupCount && pGetActiveProcessorCount && pSetThreadGroupAffinity && pSetThreadIdealProcessorEx &&
       ((osvi.dwMajorVersion > 6) || ((osvi.dwMajorVersion == 6) && (osvi.dwMinorVersion >= 1))))
    {
      int groups = pGetActiveProcessorGroupCount();
      int totalProcessors = 0, group = 0, number = 0;
      for (int i = 0; i<groups; i++) {
        int processors = pGetActiveProcessorCount(i);
        if (totalProcessors + processors > affinity) {
          group = i;
          number = (int)affinity - totalProcessors;
          break;
        }
        totalProcessors += processors;
      }

      GROUP_AFFINITY groupAffinity;
      groupAffinity.Group = (WORD)group;
      groupAffinity.Mask = (KAFFINITY)(uint64_t(1) << number);
      groupAffinity.Reserved[0] = 0;
      groupAffinity.Reserved[1] = 0;
      groupAffinity.Reserved[2] = 0;
      if (!pSetThreadGroupAffinity(thread, &groupAffinity, nullptr))
        THROW_RUNTIME_ERROR("cannot set thread group affinity");

      PROCESSOR_NUMBER processorNumber;
      processorNumber.Group = group;
      processorNumber.Number = number;
      processorNumber.Reserved = 0;
      if (!pSetThreadIdealProcessorEx(thread, &processorNumber, nullptr))
        THROW_RUNTIME_ERROR("cannot set ideal processor");

    } else {

      if (!SetThreadAffinityMask(thread, DWORD_PTR(uint64_t(1) << affinity)))
        THROW_RUNTIME_ERROR("cannot set thread affinity mask");
      if (SetThreadIdealProcessor(thread, (DWORD)affinity) == (DWORD)-1)
        THROW_RUNTIME_ERROR("cannot set ideal processor");
      }
  }

  /*! set affinity of the calling thread */
  void setAffinity(ssize_t affinity) {
    setAffinity(GetCurrentThread(), affinity);
  }

  struct ThreadStartupData
  {
  public:
    ThreadStartupData (thread_func f, void* arg)
      : f(f), arg(arg) {}
  public:
    thread_func f;
    void* arg;
  };

  static void* threadStartup(ThreadStartupData* parg)
  {
    _mm_setcsr(_mm_getcsr() | /*FTZ:*/ (1<<15) | /*DAZ:*/ (1<<6));
    parg->f(parg->arg);
    delete parg;
    return nullptr;
  }

#if !defined(PTHREADS_WIN32)

  /*! creates a hardware thread running on specific core */
  thread_t createThread(thread_func f, void* arg, size_t stack_size, ssize_t threadID)
  {
    HANDLE thread = CreateThread(nullptr, stack_size, (LPTHREAD_START_ROUTINE)threadStartup, new ThreadStartupData(f,arg), 0, nullptr);
    if (thread == nullptr) THROW_RUNTIME_ERROR("cannot create thread");
    if (threadID >= 0) setAffinity(thread, threadID);
    return thread_t(thread);
  }

  /*! the thread calling this function gets yielded */
  void yield() {
    SwitchToThread();
  }

  /*! waits until the given thread has terminated */
  void join(thread_t tid) {
    WaitForSingleObject(HANDLE(tid), INFINITE);
    CloseHandle(HANDLE(tid));
  }

  /*! destroy a hardware thread by its handle */
  void destroyThread(thread_t tid) {
    TerminateThread(HANDLE(tid),0);
    CloseHandle(HANDLE(tid));
  }

  /*! creates thread local storage */
  tls_t createTls() {
    return tls_t(TlsAlloc());
  }

  /*! set the thread local storage pointer */
  void setTls(tls_t tls, void* const ptr) {
    TlsSetValue(DWORD(size_t(tls)), ptr);
  }

  /*! return the thread local storage pointer */
  void* getTls(tls_t tls) {
    return TlsGetValue(DWORD(size_t(tls)));
  }

  /*! destroys thread local storage identifier */
  void destroyTls(tls_t tls) {
    TlsFree(DWORD(size_t(tls)));
  }
#endif
}

#endif

////////////////////////////////////////////////////////////////////////////////
/// Linux Platform
////////////////////////////////////////////////////////////////////////////////

#if defined(__LINUX__)
namespace embree
{
  /*! set affinity of the calling thread */
  void setAffinity(ssize_t affinity)
  {
    cpu_set_t cset;
    CPU_ZERO(&cset);
    CPU_SET(affinity, &cset);

    if (pthread_setaffinity_np(pthread_self(), sizeof(cset), &cset) != 0)
      std::cerr << "Thread: cannot set affinity" << std::endl;
  }
}
#endif

////////////////////////////////////////////////////////////////////////////////
/// MacOSX Platform
////////////////////////////////////////////////////////////////////////////////

#if defined(__MACOSX__)

#include <mach/thread_act.h>
#include <mach/thread_policy.h>
#include <mach/mach_init.h>

namespace embree
{
  /*! set affinity of the calling thread */
  void setAffinity(ssize_t affinity)
  {
    thread_affinity_policy ap;
    ap.affinity_tag = affinity;
    if (thread_policy_set(mach_thread_self(),THREAD_AFFINITY_POLICY,(thread_policy_t)&ap,THREAD_AFFINITY_POLICY_COUNT) != KERN_SUCCESS)
      std::cerr << "Thread: cannot set affinity" << std::endl;
  }
}
#endif

////////////////////////////////////////////////////////////////////////////////
/// Unix Platform
////////////////////////////////////////////////////////////////////////////////

#if defined(__UNIX__) || defined(PTHREADS_WIN32)

#include <pthread.h>
#include <sched.h>

#if defined(__USE_NUMA__)
#include <numa.h>
#endif

namespace embree
{
  struct ThreadStartupData
  {
  public:
    ThreadStartupData (thread_func f, void* arg, int affinity)
      : f(f), arg(arg), affinity(affinity) {}
  public:
    thread_func f;
    void* arg;
    ssize_t affinity;
  };

  static void* threadStartup(ThreadStartupData* parg)
  {
    _mm_setcsr(_mm_getcsr() | /*FTZ:*/ (1<<15) | /*DAZ:*/ (1<<6));

#if !defined(__LINUX__)
    if (parg->affinity >= 0)
	setAffinity(parg->affinity);
#endif

    parg->f(parg->arg);
    delete parg;
    return nullptr;
  }

  /*! creates a hardware thread running on specific core */
  thread_t createThread(thread_func f, void* arg, size_t stack_size, ssize_t threadID)
  {
#ifdef __MIC__
    threadID++; // start counting at 1 on MIC
#endif

    /* set stack size */
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    if (stack_size > 0) pthread_attr_setstacksize (&attr, stack_size);

    /* create thread */
    pthread_t* tid = new pthread_t;
    if (pthread_create(tid,&attr,(void*(*)(void*))threadStartup,new ThreadStartupData(f,arg,threadID)) != 0)
      THROW_RUNTIME_ERROR("pthread_create");

    /* set affinity */
#if defined(__LINUX__)
    if (threadID >= 0) {
      cpu_set_t cset;
      CPU_ZERO(&cset);
      CPU_SET(threadID, &cset);
      int ret = pthread_setaffinity_np(*tid,sizeof(cpu_set_t),&cset);
      if (ret)
        std::cout << "WARNING: setting thread affinity failed" << std::endl;
    }
#endif

    return thread_t(tid);
  }

  /*! the thread calling this function gets yielded */
  void yield() {
    sched_yield();
  }

  /*! waits until the given thread has terminated */
  void join(thread_t tid) {
    if (pthread_join(*(pthread_t*)tid, nullptr) != 0)
      THROW_RUNTIME_ERROR("pthread_join");
    delete (pthread_t*)tid;
  }

  /*! destroy a hardware thread by its handle */
  void destroyThread(thread_t tid) {
    pthread_cancel(*(pthread_t*)tid);
    delete (pthread_t*)tid;
  }

  /*! creates thread local storage */
  tls_t createTls() {
    static int cntr = 0;
    pthread_key_t* key = new pthread_key_t;
    if (pthread_key_create(key,nullptr) != 0)
      THROW_RUNTIME_ERROR("pthread_key_create");

    return tls_t(key);
  }

  /*! return the thread local storage pointer */
  void* getTls(tls_t tls)
  {
    assert(tls);
    return pthread_getspecific(*(pthread_key_t*)tls);
  }

  /*! set the thread local storage pointer */
  void setTls(tls_t tls, void* const ptr)
  {
    assert(tls);
    if (pthread_setspecific(*(pthread_key_t*)tls, ptr) != 0)
      THROW_RUNTIME_ERROR("pthread_setspecific");
  }

  /*! destroys thread local storage identifier */
  void destroyTls(tls_t tls)
  {
    assert(tls);
    if (pthread_key_delete(*(pthread_key_t*)tls) != 0)
      THROW_RUNTIME_ERROR("pthread_key_delete");
    delete (pthread_key_t*)tls;
  }
}

#endif
<commit_msg>exp affinity settings<commit_after>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "thread.h"
#include "sysinfo.h"
#include "string.h"

#include <iostream>
#include <xmmintrin.h>

#if defined(PTHREADS_WIN32)
#pragma comment (lib, "pthreadVC.lib")
#endif

////////////////////////////////////////////////////////////////////////////////
/// Windows Platform
////////////////////////////////////////////////////////////////////////////////

#if defined(__WIN32__)

#define WIN32_LEAN_AND_MEAN
#include <windows.h>

namespace embree
{
  /*! set the affinity of a given thread */
  void setAffinity(HANDLE thread, ssize_t affinity)
  {
    OSVERSIONINFO osvi;
    ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx(&osvi);
    typedef WORD (WINAPI *GetActiveProcessorGroupCountFunc)();
    typedef DWORD (WINAPI *GetActiveProcessorCountFunc)(WORD);
    typedef BOOL (WINAPI *SetThreadGroupAffinityFunc)(HANDLE, const GROUP_AFFINITY *, PGROUP_AFFINITY);
    typedef BOOL (WINAPI *SetThreadIdealProcessorExFunc)(HANDLE, PPROCESSOR_NUMBER, PPROCESSOR_NUMBER);
    HMODULE hlib = LoadLibrary("Kernel32");
    GetActiveProcessorGroupCountFunc pGetActiveProcessorGroupCount = (GetActiveProcessorGroupCountFunc)GetProcAddress(hlib, "GetActiveProcessorGroupCount");
    GetActiveProcessorCountFunc pGetActiveProcessorCount = (GetActiveProcessorCountFunc)GetProcAddress(hlib, "GetActiveProcessorCount");
    SetThreadGroupAffinityFunc pSetThreadGroupAffinity = (SetThreadGroupAffinityFunc)GetProcAddress(hlib, "SetThreadGroupAffinity");
    SetThreadIdealProcessorExFunc pSetThreadIdealProcessorEx = (SetThreadIdealProcessorExFunc)GetProcAddress(hlib, "SetThreadIdealProcessorEx");
    if (pGetActiveProcessorGroupCount && pGetActiveProcessorCount && pSetThreadGroupAffinity && pSetThreadIdealProcessorEx &&
       ((osvi.dwMajorVersion > 6) || ((osvi.dwMajorVersion == 6) && (osvi.dwMinorVersion >= 1))))
    {
      int groups = pGetActiveProcessorGroupCount();
      int totalProcessors = 0, group = 0, number = 0;
      for (int i = 0; i<groups; i++) {
        int processors = pGetActiveProcessorCount(i);
        if (totalProcessors + processors > affinity) {
          group = i;
          number = (int)affinity - totalProcessors;
          break;
        }
        totalProcessors += processors;
      }

      GROUP_AFFINITY groupAffinity;
      groupAffinity.Group = (WORD)group;
      groupAffinity.Mask = (KAFFINITY)(uint64_t(1) << number);
      groupAffinity.Reserved[0] = 0;
      groupAffinity.Reserved[1] = 0;
      groupAffinity.Reserved[2] = 0;
      if (!pSetThreadGroupAffinity(thread, &groupAffinity, nullptr))
        THROW_RUNTIME_ERROR("cannot set thread group affinity");

      PROCESSOR_NUMBER processorNumber;
      processorNumber.Group = group;
      processorNumber.Number = number;
      processorNumber.Reserved = 0;
      if (!pSetThreadIdealProcessorEx(thread, &processorNumber, nullptr))
        THROW_RUNTIME_ERROR("cannot set ideal processor");

    } else {

      if (!SetThreadAffinityMask(thread, DWORD_PTR(uint64_t(1) << affinity)))
        THROW_RUNTIME_ERROR("cannot set thread affinity mask");
      if (SetThreadIdealProcessor(thread, (DWORD)affinity) == (DWORD)-1)
        THROW_RUNTIME_ERROR("cannot set ideal processor");
      }
  }

  /*! set affinity of the calling thread */
  void setAffinity(ssize_t affinity) {
    setAffinity(GetCurrentThread(), affinity);
  }

  struct ThreadStartupData
  {
  public:
    ThreadStartupData (thread_func f, void* arg)
      : f(f), arg(arg) {}
  public:
    thread_func f;
    void* arg;
  };

  static void* threadStartup(ThreadStartupData* parg)
  {
    _mm_setcsr(_mm_getcsr() | /*FTZ:*/ (1<<15) | /*DAZ:*/ (1<<6));
    parg->f(parg->arg);
    delete parg;
    return nullptr;
  }

#if !defined(PTHREADS_WIN32)

  /*! creates a hardware thread running on specific core */
  thread_t createThread(thread_func f, void* arg, size_t stack_size, ssize_t threadID)
  {
    HANDLE thread = CreateThread(nullptr, stack_size, (LPTHREAD_START_ROUTINE)threadStartup, new ThreadStartupData(f,arg), 0, nullptr);
    if (thread == nullptr) THROW_RUNTIME_ERROR("cannot create thread");
    if (threadID >= 0) setAffinity(thread, threadID);
    return thread_t(thread);
  }

  /*! the thread calling this function gets yielded */
  void yield() {
    SwitchToThread();
  }

  /*! waits until the given thread has terminated */
  void join(thread_t tid) {
    WaitForSingleObject(HANDLE(tid), INFINITE);
    CloseHandle(HANDLE(tid));
  }

  /*! destroy a hardware thread by its handle */
  void destroyThread(thread_t tid) {
    TerminateThread(HANDLE(tid),0);
    CloseHandle(HANDLE(tid));
  }

  /*! creates thread local storage */
  tls_t createTls() {
    return tls_t(TlsAlloc());
  }

  /*! set the thread local storage pointer */
  void setTls(tls_t tls, void* const ptr) {
    TlsSetValue(DWORD(size_t(tls)), ptr);
  }

  /*! return the thread local storage pointer */
  void* getTls(tls_t tls) {
    return TlsGetValue(DWORD(size_t(tls)));
  }

  /*! destroys thread local storage identifier */
  void destroyTls(tls_t tls) {
    TlsFree(DWORD(size_t(tls)));
  }
#endif
}

#endif

////////////////////////////////////////////////////////////////////////////////
/// Linux Platform
////////////////////////////////////////////////////////////////////////////////

#if defined(__LINUX__)
namespace embree
{
  ssize_t mapThreadID(ssize_t threadID)
  {
#if 1
#define THREADS_PER_CORE 4
#define CORES 52
#define OFFSET 34
    ssize_t ID = OFFSET + ((threadID%THREADS_PER_CORE)*CORES) + (threadID/THREADS_PER_CORE);
#else
    ssize_t ID = threadID;
#endif
    //std::cout << threadID << " -> " << ID << std::endl;
    return ID;
  }
  /*! set affinity of the calling thread */
  void setAffinity(ssize_t affinity)
  {
    cpu_set_t cset;
    CPU_ZERO(&cset);
    CPU_SET(mapThreadID(affinity), &cset);

    if (pthread_setaffinity_np(pthread_self(), sizeof(cset), &cset) != 0)
      std::cerr << "Thread: cannot set affinity" << std::endl;
  }
}
#endif

////////////////////////////////////////////////////////////////////////////////
/// MacOSX Platform
////////////////////////////////////////////////////////////////////////////////

#if defined(__MACOSX__)

#include <mach/thread_act.h>
#include <mach/thread_policy.h>
#include <mach/mach_init.h>

namespace embree
{
  /*! set affinity of the calling thread */
  void setAffinity(ssize_t affinity)
  {
    thread_affinity_policy ap;
    ap.affinity_tag = affinity;
    if (thread_policy_set(mach_thread_self(),THREAD_AFFINITY_POLICY,(thread_policy_t)&ap,THREAD_AFFINITY_POLICY_COUNT) != KERN_SUCCESS)
      std::cerr << "Thread: cannot set affinity" << std::endl;
  }
}
#endif

////////////////////////////////////////////////////////////////////////////////
/// Unix Platform
////////////////////////////////////////////////////////////////////////////////

#if defined(__UNIX__) || defined(PTHREADS_WIN32)

#include <pthread.h>
#include <sched.h>

#if defined(__USE_NUMA__)
#include <numa.h>
#endif

namespace embree
{
  struct ThreadStartupData
  {
  public:
    ThreadStartupData (thread_func f, void* arg, int affinity)
      : f(f), arg(arg), affinity(affinity) {}
  public:
    thread_func f;
    void* arg;
    ssize_t affinity;
  };

  static void* threadStartup(ThreadStartupData* parg)
  {
    _mm_setcsr(_mm_getcsr() | /*FTZ:*/ (1<<15) | /*DAZ:*/ (1<<6));

#if !defined(__LINUX__)
    if (parg->affinity >= 0)
	setAffinity(parg->affinity);
#endif

    parg->f(parg->arg);
    delete parg;
    return nullptr;
  }

  /*! creates a hardware thread running on specific core */
  thread_t createThread(thread_func f, void* arg, size_t stack_size, ssize_t threadID)
  {
#ifdef __MIC__
    threadID++; // start counting at 1 on MIC
#endif

    /* set stack size */
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    if (stack_size > 0) pthread_attr_setstacksize (&attr, stack_size);

    /* create thread */
    pthread_t* tid = new pthread_t;
    if (pthread_create(tid,&attr,(void*(*)(void*))threadStartup,new ThreadStartupData(f,arg,threadID)) != 0)
      THROW_RUNTIME_ERROR("pthread_create");

    /* set affinity */
#if defined(__LINUX__)
    if (threadID >= 0) {
      cpu_set_t cset;
      CPU_ZERO(&cset);
      CPU_SET(mapThreadID(threadID), &cset);
      int ret = pthread_setaffinity_np(*tid,sizeof(cpu_set_t),&cset);
      if (ret)
        std::cout << "WARNING: setting thread affinity failed" << std::endl;
    }
#endif

    return thread_t(tid);
  }

  /*! the thread calling this function gets yielded */
  void yield() {
    sched_yield();
  }

  /*! waits until the given thread has terminated */
  void join(thread_t tid) {
    if (pthread_join(*(pthread_t*)tid, nullptr) != 0)
      THROW_RUNTIME_ERROR("pthread_join");
    delete (pthread_t*)tid;
  }

  /*! destroy a hardware thread by its handle */
  void destroyThread(thread_t tid) {
    pthread_cancel(*(pthread_t*)tid);
    delete (pthread_t*)tid;
  }

  /*! creates thread local storage */
  tls_t createTls() {
    static int cntr = 0;
    pthread_key_t* key = new pthread_key_t;
    if (pthread_key_create(key,nullptr) != 0)
      THROW_RUNTIME_ERROR("pthread_key_create");

    return tls_t(key);
  }

  /*! return the thread local storage pointer */
  void* getTls(tls_t tls)
  {
    assert(tls);
    return pthread_getspecific(*(pthread_key_t*)tls);
  }

  /*! set the thread local storage pointer */
  void setTls(tls_t tls, void* const ptr)
  {
    assert(tls);
    if (pthread_setspecific(*(pthread_key_t*)tls, ptr) != 0)
      THROW_RUNTIME_ERROR("pthread_setspecific");
  }

  /*! destroys thread local storage identifier */
  void destroyTls(tls_t tls)
  {
    assert(tls);
    if (pthread_key_delete(*(pthread_key_t*)tls) != 0)
      THROW_RUNTIME_ERROR("pthread_key_delete");
    delete (pthread_key_t*)tls;
  }
}

#endif
<|endoftext|>


<commit_before>// Copyright (C) 2018 Elviss Strazdins
// This file is part of the Ouzel engine.

#pragma once

#include "core/Setup.h"

#if OUZEL_COMPILE_DIRECT3D11

#include <atomic>
#include <map>
#include <d3d11.h>
#include "graphics/RenderDevice.hpp"
#include "graphics/Texture.hpp"
#include "thread/Thread.hpp"

namespace ouzel
{
    namespace graphics
    {
        class RenderDeviceD3D11: public RenderDevice
        {
            friend Renderer;
        public:
            virtual ~RenderDeviceD3D11();

            virtual void setClearColor(Color color) override;

            virtual std::vector<Size2> getSupportedResolutions() const override;

            ID3D11Device* getDevice() const { return device; }
            ID3D11DeviceContext* getContext() const { return context; }

            struct SamplerStateDesc
            {
                Texture::Filter filter;
                Texture::Address addressX;
                Texture::Address addressY;
                uint32_t maxAnisotropy;

                bool operator<(const SamplerStateDesc& other) const
                {
                    return std::tie(filter, addressX, addressY, maxAnisotropy) < std::tie(other.filter, other.addressX, other.addressY, other.maxAnisotropy);
                }
            };

            ID3D11SamplerState* getSamplerState(const SamplerStateDesc& desc);
            bool setFullscreen(bool newFullscreen);

        protected:
            RenderDeviceD3D11();

            virtual bool init(Window* newWindow,
                              const Size2& newSize,
                              uint32_t newSampleCount,
                              Texture::Filter newTextureFilter,
                              uint32_t newMaxAnisotropy,
                              bool newVerticalSync,
                              bool newDepth,
                              bool newDebugRenderer) override;

            virtual void setSize(const Size2& newSize);

            virtual bool processCommands(CommandBuffer& commands) override;
            bool resizeBackBuffer(UINT newWidth, UINT newHeight);
            bool uploadBuffer(ID3D11Buffer* buffer, const void* data, uint32_t dataSize);
            virtual bool generateScreenshot(const std::string& filename) override;
            void main();

            virtual BlendStateResource* createBlendState() override;
            virtual TextureResource* createTexture() override;
            virtual ShaderResource* createShader() override;
            virtual BufferResource* createBuffer() override;

            IDXGIOutput* getOutput() const;

            ID3D11Device* device = nullptr;
            ID3D11DeviceContext* context = nullptr;
            IDXGISwapChain* swapChain = nullptr;
            IDXGIAdapter* adapter = nullptr;
            ID3D11Texture2D* backBuffer = nullptr;
            ID3D11RenderTargetView* renderTargetView = nullptr;
            std::map<SamplerStateDesc, ID3D11SamplerState*> samplerStates;
            ID3D11RasterizerState* rasterizerStates[12];
            ID3D11Texture2D* depthStencilTexture = nullptr;
            ID3D11DepthStencilView* depthStencilView = nullptr;
            ID3D11DepthStencilState* depthStencilStates[4];

            UINT frameBufferWidth = 0;
            UINT frameBufferHeight = 0;

            UINT swapInterval = 0;
            FLOAT frameBufferClearColor[4];

            std::atomic<bool> running;
            Thread renderThread;
        };
    } // namespace graphics
} // namespace ouzel

#endif
<commit_msg>Delete the RenderDeviceD3D11.hpp<commit_after><|endoftext|>


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

#include <algorithm>

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

#include <framework/URLInputSource.hpp>
#include <parsers/DOMParser.hpp>
#include <parsers/SAXParser.hpp>
#include <sax/SAXParseException.hpp>

#include <Include/XalanAutoPtr.hpp>

#include <PlatformSupport/ExecutionContext.hpp>
#include <PlatformSupport/STLHelper.hpp>
#include <PlatformSupport/XalanUnicode.hpp>

#include <DOMSupport/DOMSupport.hpp>

#include "XercesDOMSupport.hpp"
#include "XercesDocumentBridge.hpp"

static const XalanDOMChar	theDefaultSpecialCharacters[] =
{
		XalanUnicode::charLessThanSign,
		XalanUnicode::charGreaterThanSign,
		XalanUnicode::charAmpersand,
		XalanUnicode::charApostrophe,
		XalanUnicode::charQuoteMark,
		XalanUnicode::charCR,
		XalanUnicode::charLF,
		0
};

XercesParserLiaison::XercesParserLiaison(XercesDOMSupport&	theSupport) :
	m_DOMSupport(theSupport),
	m_specialCharacters(theDefaultSpecialCharacters),
	m_indent(-1),
	m_shouldExpandEntityRefs(true),
	m_useValidation(false),
	m_includeIgnorableWhitespace(true),
	m_doNamespaces(true),
	m_exitOnFirstFatalError(true),
	m_entityResolver(0),
	m_errorHandler(this),
	m_documentMap(),
	m_buildBridge(true),
	m_threadSafe(false),
	m_executionContext(0)
{
}

XercesParserLiaison::~XercesParserLiaison()
{
	reset();
}

void
XercesParserLiaison::reset()
{
#if !defined(XALAN_NO_NAMESPACES)
	using std::for_each;
#endif

	// Delete any live documents.
	for_each(m_documentMap.begin(),
			 m_documentMap.end(),
			 makeMapValueDeleteFunctor(m_documentMap));

	m_documentMap.clear();

	m_DOMSupport.reset();

	m_executionContext = 0;
}

ExecutionContext*
XercesParserLiaison::getExecutionContext() const
{
	return m_executionContext;
}

void
XercesParserLiaison::setExecutionContext(ExecutionContext&	theContext)
{
	m_executionContext = &theContext;
}

bool
XercesParserLiaison::supportsSAX() const
{
	return true;
}

void
XercesParserLiaison::parseXMLStream(
			const InputSource&		urlInputSource,
			DocumentHandler&		handler,
			const XalanDOMString&	/* identifier */)
{
	XalanAutoPtr<SAXParser>		theParser(CreateSAXParser());

	theParser->setDocumentHandler(&handler);

	theParser->parse(urlInputSource);
}

XalanDocument*
XercesParserLiaison::parseXMLStream(
			const InputSource&		reader,
			const XalanDOMString&	/* identifier */)
{
	XalanAutoPtr<DOMParser>		theParser(CreateDOMParser());

	theParser->parse(reader);

	const DOM_Document	theXercesDocument =
		theParser->getDocument();

	XercesDocumentBridge*	theNewDocument = 0;

	if (theXercesDocument.isNull() == false)
	{
		theNewDocument = createDocument(theXercesDocument, m_threadSafe, m_buildBridge);

		m_documentMap[theNewDocument] = theNewDocument;
	}

	return theNewDocument;
}

XalanDocument*
XercesParserLiaison::createDocument()
{
	const DOM_Document	theXercesDocument =
		DOM_Document::createDocument();

	return createDocument(theXercesDocument, false, false);
}

XalanDocument*
XercesParserLiaison::createDOMFactory()
{
	return createDocument();
}

void
XercesParserLiaison::destroyDocument(XalanDocument*		theDocument)
{
	if (mapDocument(theDocument) != 0)
	{
		m_documentMap.erase(theDocument);

		delete theDocument;
	}
}

void
XercesParserLiaison::setSpecialCharacters(const XalanDOMString&	str)
{
	m_specialCharacters = str;
}

const XalanDOMString&
XercesParserLiaison::getSpecialCharacters() const
{
	return m_specialCharacters;
}

int
XercesParserLiaison::getIndent() const
{
	return m_indent;
}

void
XercesParserLiaison::setIndent(int	i)
{
	m_indent = i;
}

bool
XercesParserLiaison::getShouldExpandEntityRefs() const
{
	return m_shouldExpandEntityRefs;
}

void
XercesParserLiaison::SetShouldExpandEntityRefs(bool	b)
{
	m_shouldExpandEntityRefs = b;
}

bool
XercesParserLiaison::getUseValidation() const
{
	return m_useValidation;
}

void
XercesParserLiaison::setUseValidation(bool	b)
{
	m_useValidation = b;
}

const XalanDOMString
XercesParserLiaison::getParserDescription() const
{
	return XALAN_STATIC_UCODE_STRING("Xerces");
}

bool
XercesParserLiaison::getIncludeIgnorableWhitespace() const
{
	return m_includeIgnorableWhitespace;
}

void
XercesParserLiaison::setIncludeIgnorableWhitespace(bool	include)
{
	m_includeIgnorableWhitespace = include;
}

ErrorHandler*
XercesParserLiaison::getErrorHandler()
{
	return m_errorHandler;
}

const ErrorHandler*
XercesParserLiaison::getErrorHandler() const
{
	return m_errorHandler;
}

void
XercesParserLiaison::setErrorHandler(ErrorHandler*	handler)
{
	assert(handler != 0);

	m_errorHandler = handler;
}

bool
XercesParserLiaison::getDoNamespaces() const
{
	return m_doNamespaces;
}

void
XercesParserLiaison::setDoNamespaces(bool	newState)
{
	m_doNamespaces = newState;
}

bool
XercesParserLiaison::getExitOnFirstFatalError() const
{
	return m_exitOnFirstFatalError;
}

void
XercesParserLiaison::setExitOnFirstFatalError(bool	newState)
{
	m_exitOnFirstFatalError = newState;
}

EntityResolver*
XercesParserLiaison::getEntityResolver()
{
	return m_entityResolver;
}

const EntityResolver*
XercesParserLiaison::getEntityResolver() const
{
	return m_entityResolver;
}

void
XercesParserLiaison::setEntityResolver(EntityResolver*	resolver)
{
	m_entityResolver = resolver;
}

XalanDocument*
XercesParserLiaison::createDocument(const DOM_Document&		theXercesDocument)
{
	return createDocument(theXercesDocument, false, false);
}

XercesDocumentBridge*
XercesParserLiaison::mapDocument(const XalanDocument*	theDocument) const
{
	const DocumentMapType::const_iterator	i =
		m_documentMap.find(theDocument);

	return i != m_documentMap.end() ? (*i).second : 0;
}

DOM_Document
XercesParserLiaison::mapXercesDocument(const XalanDocument*		theDocument) const
{
	const DocumentMapType::const_iterator	i =
		m_documentMap.find(theDocument);

	return i != m_documentMap.end() ? (*i).second->getXercesDocument() : DOM_Document();
}

void
XercesParserLiaison::fatalError(const SAXParseException&	e)
{
	XalanDOMString	theMessage("Fatal Error");

	formatErrorMessage(e, theMessage);

	if (m_executionContext != 0)
	{
		// We call warning() because we don't want the execution
		// context to potentially throw an exception.
		m_executionContext->warn(theMessage);
	}
	else
	{
#if !defined(XALAN_NO_NAMESPACES)
		using std::cerr;
		using std::endl;
#endif

		cerr << endl << theMessage << endl;
	}

	throw e;
}

void
XercesParserLiaison::error(const SAXParseException&		e)
{
	XalanDOMString	theMessage("Error ");

	formatErrorMessage(e, theMessage);

	if (m_executionContext != 0)
	{
		// We call warn() because we don't want the execution
		// context to potentially throw an exception.
		m_executionContext->warn(theMessage);
	}
	else
	{
#if !defined(XALAN_NO_NAMESPACES)
		using std::cerr;
		using std::endl;
#endif

		cerr << endl << theMessage << endl;
	}
}

void
XercesParserLiaison::warning(const SAXParseException&	e)
{
	XalanDOMString	theMessage("Warning ");

	formatErrorMessage(e, theMessage);

	if (m_executionContext != 0)
	{
		m_executionContext->warn(theMessage);
	}
	else
	{
#if !defined(XALAN_NO_NAMESPACES)
		using std::cerr;
		using std::endl;
#endif

		cerr << endl << theMessage << endl;
	}
}

void
XercesParserLiaison::formatErrorMessage(const SAXParseException& e, XalanDOMString& theMessage)
{
	append(theMessage, " at (file ");
	append(theMessage, e.getSystemId());
	append(theMessage, ", line ");
	append(theMessage, LongToDOMString(long(e.getLineNumber())));
	append(theMessage, ", column ");
	append(theMessage, LongToDOMString(long(e.getColumnNumber())));
	append(theMessage, "): ");
	append(theMessage, e.getMessage());
}

void
XercesParserLiaison::resetErrors()
{
}

DOMParser*
XercesParserLiaison::CreateDOMParser()
{
	DOMParser* const	theParser = new DOMParser;

	theParser->setExpandEntityReferences(m_shouldExpandEntityRefs);

	theParser->setDoValidation(m_useValidation);

	theParser->setIncludeIgnorableWhitespace(m_includeIgnorableWhitespace);

	theParser->setDoNamespaces(m_doNamespaces);

	theParser->setExitOnFirstFatalError(m_exitOnFirstFatalError);

	if (m_entityResolver != 0)
	{
		theParser->setEntityResolver(m_entityResolver);
	}

	theParser->setErrorHandler(m_errorHandler);

	// Xerces has a non-standard node type to represent the XML decl.
	// Why did they ever do this?
	theParser->setToCreateXMLDeclTypeNode(false);

	return theParser;
}

SAXParser*
XercesParserLiaison::CreateSAXParser()
{
	SAXParser* const	theParser = new SAXParser;

	theParser->setDoValidation(m_useValidation);

	// $$$ ToDo: For the time being, we cannot process namespaces
	// with SAX due to the age of Xerces' SAX interfaces.
//	theParser->setDoNamespaces(m_doNamespaces);

	theParser->setExitOnFirstFatalError(m_exitOnFirstFatalError);

	if (m_entityResolver != 0)
	{
		theParser->setEntityResolver(m_entityResolver);
	}

	theParser->setErrorHandler(m_errorHandler);

	return theParser;
}

XercesDocumentBridge*
XercesParserLiaison::createDocument(
			const DOM_Document&		theXercesDocument,
			bool					threadSafe,
			bool					buildBridge)
{
	XercesDocumentBridge* const		theNewDocument =
		new XercesDocumentBridge(theXercesDocument, threadSafe, buildBridge);

	m_documentMap[theNewDocument] = theNewDocument;

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

#include <algorithm>

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

#include <framework/URLInputSource.hpp>
#include <parsers/DOMParser.hpp>
#include <parsers/SAXParser.hpp>
#include <sax/SAXParseException.hpp>

#include <Include/XalanAutoPtr.hpp>

#include <PlatformSupport/ExecutionContext.hpp>
#include <PlatformSupport/STLHelper.hpp>
#include <PlatformSupport/XalanUnicode.hpp>

#include <DOMSupport/DOMSupport.hpp>

#include "XercesDocumentBridge.hpp"
#include "XercesDOMSupport.hpp"

static const XalanDOMChar	theDefaultSpecialCharacters[] =
{
		XalanUnicode::charLessThanSign,
		XalanUnicode::charGreaterThanSign,
		XalanUnicode::charAmpersand,
		XalanUnicode::charApostrophe,
		XalanUnicode::charQuoteMark,
		XalanUnicode::charCR,
		XalanUnicode::charLF,
		0
};

XercesParserLiaison::XercesParserLiaison(XercesDOMSupport&	theSupport) :
	m_DOMSupport(theSupport),
	m_specialCharacters(theDefaultSpecialCharacters),
	m_indent(-1),
	m_shouldExpandEntityRefs(true),
	m_useValidation(false),
	m_includeIgnorableWhitespace(true),
	m_doNamespaces(true),
	m_exitOnFirstFatalError(true),
	m_entityResolver(0),
	m_errorHandler(this),
	m_documentMap(),
	m_buildBridge(true),
	m_threadSafe(false),
	m_executionContext(0)
{
}

XercesParserLiaison::~XercesParserLiaison()
{
	reset();
}

void
XercesParserLiaison::reset()
{
#if !defined(XALAN_NO_NAMESPACES)
	using std::for_each;
#endif

	// Delete any live documents.
	for_each(m_documentMap.begin(),
			 m_documentMap.end(),
			 makeMapValueDeleteFunctor(m_documentMap));

	m_documentMap.clear();

	m_DOMSupport.reset();

	m_executionContext = 0;
}

ExecutionContext*
XercesParserLiaison::getExecutionContext() const
{
	return m_executionContext;
}

void
XercesParserLiaison::setExecutionContext(ExecutionContext&	theContext)
{
	m_executionContext = &theContext;
}

bool
XercesParserLiaison::supportsSAX() const
{
	return true;
}

void
XercesParserLiaison::parseXMLStream(
			const InputSource&		urlInputSource,
			DocumentHandler&		handler,
			const XalanDOMString&	/* identifier */)
{
	XalanAutoPtr<SAXParser>		theParser(CreateSAXParser());

	theParser->setDocumentHandler(&handler);

	theParser->parse(urlInputSource);
}

XalanDocument*
XercesParserLiaison::parseXMLStream(
			const InputSource&		reader,
			const XalanDOMString&	/* identifier */)
{
	XalanAutoPtr<DOMParser>		theParser(CreateDOMParser());

	theParser->parse(reader);

	const DOM_Document	theXercesDocument =
		theParser->getDocument();

	XercesDocumentBridge*	theNewDocument = 0;

	if (theXercesDocument.isNull() == false)
	{
		theNewDocument = createDocument(theXercesDocument, m_threadSafe, m_buildBridge);

		m_documentMap[theNewDocument] = theNewDocument;
	}

	return theNewDocument;
}

XalanDocument*
XercesParserLiaison::createDocument()
{
	const DOM_Document	theXercesDocument =
		DOM_Document::createDocument();

	return createDocument(theXercesDocument, false, false);
}

XalanDocument*
XercesParserLiaison::createDOMFactory()
{
	return createDocument();
}

void
XercesParserLiaison::destroyDocument(XalanDocument*		theDocument)
{
	if (mapDocument(theDocument) != 0)
	{
		m_documentMap.erase(theDocument);

		delete theDocument;
	}
}

void
XercesParserLiaison::setSpecialCharacters(const XalanDOMString&	str)
{
	m_specialCharacters = str;
}

const XalanDOMString&
XercesParserLiaison::getSpecialCharacters() const
{
	return m_specialCharacters;
}

int
XercesParserLiaison::getIndent() const
{
	return m_indent;
}

void
XercesParserLiaison::setIndent(int	i)
{
	m_indent = i;
}

bool
XercesParserLiaison::getShouldExpandEntityRefs() const
{
	return m_shouldExpandEntityRefs;
}

void
XercesParserLiaison::SetShouldExpandEntityRefs(bool	b)
{
	m_shouldExpandEntityRefs = b;
}

bool
XercesParserLiaison::getUseValidation() const
{
	return m_useValidation;
}

void
XercesParserLiaison::setUseValidation(bool	b)
{
	m_useValidation = b;
}

const XalanDOMString
XercesParserLiaison::getParserDescription() const
{
	return XALAN_STATIC_UCODE_STRING("Xerces");
}

bool
XercesParserLiaison::getIncludeIgnorableWhitespace() const
{
	return m_includeIgnorableWhitespace;
}

void
XercesParserLiaison::setIncludeIgnorableWhitespace(bool	include)
{
	m_includeIgnorableWhitespace = include;
}

ErrorHandler*
XercesParserLiaison::getErrorHandler()
{
	return m_errorHandler;
}

const ErrorHandler*
XercesParserLiaison::getErrorHandler() const
{
	return m_errorHandler;
}

void
XercesParserLiaison::setErrorHandler(ErrorHandler*	handler)
{
	assert(handler != 0);

	m_errorHandler = handler;
}

bool
XercesParserLiaison::getDoNamespaces() const
{
	return m_doNamespaces;
}

void
XercesParserLiaison::setDoNamespaces(bool	newState)
{
	m_doNamespaces = newState;
}

bool
XercesParserLiaison::getExitOnFirstFatalError() const
{
	return m_exitOnFirstFatalError;
}

void
XercesParserLiaison::setExitOnFirstFatalError(bool	newState)
{
	m_exitOnFirstFatalError = newState;
}

EntityResolver*
XercesParserLiaison::getEntityResolver()
{
	return m_entityResolver;
}

const EntityResolver*
XercesParserLiaison::getEntityResolver() const
{
	return m_entityResolver;
}

void
XercesParserLiaison::setEntityResolver(EntityResolver*	resolver)
{
	m_entityResolver = resolver;
}

XalanDocument*
XercesParserLiaison::createDocument(const DOM_Document&		theXercesDocument)
{
	return createDocument(theXercesDocument, false, false);
}

XercesDocumentBridge*
XercesParserLiaison::mapDocument(const XalanDocument*	theDocument) const
{
	const DocumentMapType::const_iterator	i =
		m_documentMap.find(theDocument);

	return i != m_documentMap.end() ? (*i).second : 0;
}

DOM_Document
XercesParserLiaison::mapXercesDocument(const XalanDocument*		theDocument) const
{
	const DocumentMapType::const_iterator	i =
		m_documentMap.find(theDocument);

	return i != m_documentMap.end() ? (*i).second->getXercesDocument() : DOM_Document();
}

void
XercesParserLiaison::fatalError(const SAXParseException&	e)
{
	XalanDOMString	theMessage("Fatal Error");

	formatErrorMessage(e, theMessage);

	if (m_executionContext != 0)
	{
		// We call warning() because we don't want the execution
		// context to potentially throw an exception.
		m_executionContext->warn(theMessage);
	}
	else
	{
#if !defined(XALAN_NO_NAMESPACES)
		using std::cerr;
		using std::endl;
#endif

		cerr << endl << theMessage << endl;
	}

	throw e;
}

void
XercesParserLiaison::error(const SAXParseException&		e)
{
	XalanDOMString	theMessage("Error ");

	formatErrorMessage(e, theMessage);

	if (m_executionContext != 0)
	{
		// We call warn() because we don't want the execution
		// context to potentially throw an exception.
		m_executionContext->warn(theMessage);
	}
	else
	{
#if !defined(XALAN_NO_NAMESPACES)
		using std::cerr;
		using std::endl;
#endif

		cerr << endl << theMessage << endl;
	}
}

void
XercesParserLiaison::warning(const SAXParseException&	e)
{
	XalanDOMString	theMessage("Warning ");

	formatErrorMessage(e, theMessage);

	if (m_executionContext != 0)
	{
		m_executionContext->warn(theMessage);
	}
	else
	{
#if !defined(XALAN_NO_NAMESPACES)
		using std::cerr;
		using std::endl;
#endif

		cerr << endl << theMessage << endl;
	}
}

void
XercesParserLiaison::formatErrorMessage(const SAXParseException& e, XalanDOMString& theMessage)
{
	append(theMessage, " at (file ");
	append(theMessage, e.getSystemId());
	append(theMessage, ", line ");
	append(theMessage, LongToDOMString(long(e.getLineNumber())));
	append(theMessage, ", column ");
	append(theMessage, LongToDOMString(long(e.getColumnNumber())));
	append(theMessage, "): ");
	append(theMessage, e.getMessage());
}

void
XercesParserLiaison::resetErrors()
{
}

DOMParser*
XercesParserLiaison::CreateDOMParser()
{
	DOMParser* const	theParser = new DOMParser;

	theParser->setExpandEntityReferences(m_shouldExpandEntityRefs);

	theParser->setDoValidation(m_useValidation);

	theParser->setIncludeIgnorableWhitespace(m_includeIgnorableWhitespace);

	theParser->setDoNamespaces(m_doNamespaces);

	theParser->setExitOnFirstFatalError(m_exitOnFirstFatalError);

	if (m_entityResolver != 0)
	{
		theParser->setEntityResolver(m_entityResolver);
	}

	theParser->setErrorHandler(m_errorHandler);

	// Xerces has a non-standard node type to represent the XML decl.
	// Why did they ever do this?
	theParser->setToCreateXMLDeclTypeNode(false);

	return theParser;
}

SAXParser*
XercesParserLiaison::CreateSAXParser()
{
	SAXParser* const	theParser = new SAXParser;

	theParser->setDoValidation(m_useValidation);

	// $$$ ToDo: For the time being, we cannot process namespaces
	// with SAX due to the age of Xerces' SAX interfaces.
//	theParser->setDoNamespaces(m_doNamespaces);

	theParser->setExitOnFirstFatalError(m_exitOnFirstFatalError);

	if (m_entityResolver != 0)
	{
		theParser->setEntityResolver(m_entityResolver);
	}

	theParser->setErrorHandler(m_errorHandler);

	return theParser;
}

XercesDocumentBridge*
XercesParserLiaison::createDocument(
			const DOM_Document&		theXercesDocument,
			bool					threadSafe,
			bool					buildBridge)
{
	XercesDocumentBridge* const		theNewDocument =
		new XercesDocumentBridge(theXercesDocument, threadSafe, buildBridge);

	m_documentMap[theNewDocument] = theNewDocument;

	return theNewDocument;
}
<|endoftext|>


<commit_before>/*****************************************************************************\
 *                        ANALYSIS PERFORMANCE TOOLS                         *
 *                                  wxparaver                                *
 *              Paraver Trace Visualization and Analysis Tool                *
 *****************************************************************************
 *     ___     This library is free software; you can redistribute it and/or *
 *    /  __         modify it under the terms of the GNU LGPL as published   *
 *   /  /  _____    by the Free Software Foundation; either version 2.1      *
 *  /  /  /     \   of the License, or (at your option) any later version.   *
 * (  (  ( B S C )                                                           *
 *  \  \  \_____/   This library is distributed in hope that it will be      *
 *   \  \__         useful but WITHOUT ANY WARRANTY; without even the        *
 *    \___          implied warranty of MERCHANTABILITY or FITNESS FOR A     *
 *                  PARTICULAR PURPOSE. See the GNU LGPL for more details.   *
 *                                                                           *
 * You should have received a copy of the GNU Lesser General Public License  *
 * along with this library; if not, write to the Free Software Foundation,   *
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA          *
 * The GNU LEsser General Public License is contained in the file COPYING.   *
 *                                 ---------                                 *
 *   Barcelona Supercomputing Center - Centro Nacional de Supercomputacion   *
\*****************************************************************************/

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\
 | @file: $HeadURL$
 | @last_commit: $Date$
 | @version:     $Revision$
\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

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

#ifdef __BORLANDC__
#pragma hdrstop
#endif

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

////@begin includes
////@end includes

// Signal handling
#include <signal.h>
#include <stdio.h>

#include "wxparaverapp.h"
#include "connection.h"

////@begin XPM images
////@end XPM images

#ifndef WIN32
struct sigaction act;
#endif

/*!
 * Application instance implementation
 */

////@begin implement app
IMPLEMENT_APP( wxparaverApp )
////@end implement app

/*!
 * wxparaverApp type definition
 */

IMPLEMENT_CLASS( wxparaverApp, wxApp )

/*!
 * wxparaverApp event table definition
 */

BEGIN_EVENT_TABLE( wxparaverApp, wxApp )

////@begin wxparaverApp event table entries
////@end wxparaverApp event table entries

END_EVENT_TABLE()

/*!
 * Constructor for wxparaverApp
 */

wxparaverApp::wxparaverApp()
{
  Init();
}

/*!
 * Member initialisation
 */

void wxparaverApp::Init()
{
////@begin wxparaverApp member initialisation
	globalTiming = false;
	globalTimingBegin = 0;
	globalTimingEnd = 0;
	globalTimingCallDialog = NULL;
	globalTimingBeginIsSet = false;
	eventTypeForCode = 60000119;
////@end wxparaverApp member initialisation
  m_locale.Init();
}

/*!
 * Initialisation for wxparaverApp
 */

paraverMain* wxparaverApp::mainWindow = NULL;

#ifndef WIN32
volatile bool sig1 = false;
volatile bool sig2 = false;

void wxparaverApp::handler( int signalNumber )
{
  sigdelset( &act.sa_mask, SIGUSR1 );
  sigdelset( &act.sa_mask, SIGUSR2 );

//  wxMutexGuiEnter();
//  wxparaverApp::mainWindow->OnSignal( signalNumber );
//  wxMutexGuiLeave();
  if ( signalNumber == SIGUSR1 )
  {
    sig1 = true;
  }
  else
  {
    sig1 = false;
  }

  sig2 = !sig1;

//  wxIdleEvent event;
//  event.RequestMore();
//  wxTheApp->SendIdleEvents( mainWindow, event );
  mainWindow->Raise();

  sigaddset( &act.sa_mask, SIGUSR1 );
  sigaddset( &act.sa_mask, SIGUSR2 );
  sigaction( SIGUSR1, &act, NULL );
  sigaction( SIGUSR2, &act, NULL );
}

void wxparaverApp::presetUserSignals()
{

  act.sa_handler = &handler;
  act.sa_flags = 0;

  if ( sigemptyset( &act.sa_mask ) != 0 )
  {
    /* Handle error */
  }

  if ( sigaddset( &act.sa_mask, SIGUSR1 ))
  {
    /* Handle error */
  }

  if ( sigaddset( &act.sa_mask, SIGUSR2 ))
  {
    /* Handle error */
  }

  if ( sigaction( SIGUSR1, &act, NULL ) != 0 )
  {
    /* Handle error */
  }

  if ( sigaction( SIGUSR2, &act, NULL ) != 0 )
  {
    /* Handle error */
  }
}
#endif

bool wxparaverApp::OnInit()
{
  ParaverConfig::getInstance()->readParaverConfigFile();

  if( ParaverConfig::getInstance()->getGlobalSingleInstance() )
  {
    const wxString name = wxString::Format( _( "wxparaver-%s" ), wxGetUserId().c_str());
    m_checker = new wxSingleInstanceChecker(name);
    if ( !m_checker->IsAnotherRunning() )
    {
      m_server = new stServer;

#ifdef WIN32
      if( !m_server->Create( wxT( "wxparaver_service" ) ) )
#else
      const wxString service_name = wxString::Format( _( "/tmp/wxparaver_service-%s" ), wxGetUserId().c_str());
      if( !m_server->Create( service_name ) )
#endif
        wxLogDebug( wxT( "Failed to create an IPC service." ) );
    }
    else
    {
      wxLogNull logNull;

      stClient *client = new stClient;
      wxString hostName = wxT( "localhost" );
#ifdef WIN32
      wxConnectionBase *connection = client->MakeConnection( hostName,
                                                             wxT( "wxparaver_service" ),
                                                             wxT( "wxparaver" ) );
#else
      const wxString service_name = wxString::Format( _( "/tmp/wxparaver_service-%s" ), wxGetUserId().c_str());
      wxConnectionBase *connection = client->MakeConnection( hostName,
                                                             service_name,
                                                             wxT( "wxparaver" ) );
#endif
      if( connection )
      {
        connection->Execute( wxT( "BEGIN" ) );
        for( int i = 1; i < argc; ++i )
          connection->Execute( argv[ i ] );
        connection->Execute( wxT( "END" ) );
        connection->Disconnect();
        delete connection;
      }
      else
      {
        wxMessageBox( wxT( "Sorry, the existing instance may be too busy to respond." ),
                      wxT( "wxparaver" ), wxICON_INFORMATION|wxOK );
      }

      delete client;
      return false;
    }
  }

  wxCmdLineEntryDesc argumentsParseSyntax[] =
  {
    { wxCMD_LINE_SWITCH,
      wxT("h"),
      wxT("help"),
      wxT("Show this help."),
      wxCMD_LINE_VAL_STRING,
      wxCMD_LINE_OPTION_HELP },

    { wxCMD_LINE_OPTION,
      wxT("t"),
      wxT("type"),
      wxT("Event type to code linking."),
      wxCMD_LINE_VAL_NUMBER,
      wxCMD_LINE_PARAM_OPTIONAL },

    { wxCMD_LINE_PARAM,
      NULL,
      NULL,
      wxT( "(trace.prv | trace.prv.gz) (configuration.cfg)" ),
      wxCMD_LINE_VAL_STRING,
      wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE },

    { wxCMD_LINE_NONE }
  };

#if wxUSE_XPM
  wxImage::AddHandler(new wxXPMHandler);
#endif
#if wxUSE_LIBPNG
  wxImage::AddHandler(new wxPNGHandler);
#endif
#if wxUSE_LIBJPEG
  wxImage::AddHandler(new wxJPEGHandler);
#endif
#if wxUSE_GIF
  wxImage::AddHandler(new wxGIFHandler);
#endif

  wxCmdLineParser paraverCommandLineParser( argumentsParseSyntax, argc, argv );
  paraverCommandLineParser.Parse();

  wxSize mainWindowSize( ParaverConfig::getInstance()->getMainWindowWidth(),
                         ParaverConfig::getInstance()->getMainWindowHeight() );
  mainWindow = new paraverMain( NULL, SYMBOL_PARAVERMAIN_IDNAME, SYMBOL_PARAVERMAIN_TITLE, SYMBOL_PARAVERMAIN_POSITION, mainWindowSize );
  //mainWindow = new paraverMain( NULL );

  mainWindow->Show(true);

  long int tmpType;
  if( paraverCommandLineParser.Found( wxT("t"), &tmpType ) )
    eventTypeForCode = tmpType;

  mainWindow->commandLineLoadings( paraverCommandLineParser );

/*
  paraverMain *mainWindow;
  mainWindow = new paraverMain( NULL );

  mainWindow->Show(true);

  mainWindow->commandLineLoadings( paraverCommandLineParser );
*/
#ifndef WIN32
  presetUserSignals();
#endif

  return true;
}

/*!
 * Cleanup for wxparaverApp
 */

int wxparaverApp::OnExit()
{
//  double w, h;
//  wxparaverApp::mainWindow->GetAuiManager().GetDockSizeConstraint( &w, &h );
//  cout<<w<<" "<<h<<endl;
//  cout << wxparaverApp::mainWindow->GetAuiManager().SavePaneInfo(
//            wxparaverApp::mainWindow->GetAuiManager().GetPane( wxparaverApp::mainWindow->choiceWindowBrowser ) ).mb_str()<<endl;
  ParaverConfig::getInstance()->writeParaverConfigFile();

  if( m_checker != NULL )
    delete m_checker;

  if( m_server != NULL )
    delete m_server;

////@begin wxparaverApp cleanup
	return wxApp::OnExit();
////@end wxparaverApp cleanup
}

#ifdef WIN32
int wxparaverApp::FilterEvent(wxEvent& event)
{
  if ( event.GetEventType()==wxEVT_KEY_DOWN &&
       ((wxKeyEvent&)event).ControlDown() &&
       ((wxKeyEvent&)event).GetKeyCode() == (long) 'C'
     )
  {
    mainWindow->OnKeyCopy();
    return true;
  }
  else if ( event.GetEventType()==wxEVT_KEY_DOWN &&
            ((wxKeyEvent&)event).ControlDown() &&
            ((wxKeyEvent&)event).GetKeyCode() == (long) 'V'
          )
  {
    mainWindow->OnKeyPaste();
    return true;
  }

  return -1;
}
#endif

void wxparaverApp::ActivateGlobalTiming( wxDialog* whichDialog )
{
  globalTimingCallDialog = whichDialog;
  wxSetCursor( *wxCROSS_CURSOR );
  globalTiming = true;
  globalTimingBeginIsSet = false;
  globalTimingCallDialog->Enable( false );
  globalTimingCallDialog->MakeModal( false );
#ifdef WIN32
  globalTimingCallDialog->Iconize( true );
#endif
  mainWindow->Raise();
}

void wxparaverApp::DeactivateGlobalTiming()
{
  wxSetCursor( wxNullCursor );
  globalTiming = false;
  globalTimingBeginIsSet = false;
  globalTimingCallDialog->Enable( true );
  globalTimingCallDialog->MakeModal( true );
#ifdef WIN32
  globalTimingCallDialog->Iconize( false );
#endif
  globalTimingCallDialog->Raise();
}

<commit_msg>*** empty log message ***<commit_after>/*****************************************************************************\
 *                        ANALYSIS PERFORMANCE TOOLS                         *
 *                                  wxparaver                                *
 *              Paraver Trace Visualization and Analysis Tool                *
 *****************************************************************************
 *     ___     This library is free software; you can redistribute it and/or *
 *    /  __         modify it under the terms of the GNU LGPL as published   *
 *   /  /  _____    by the Free Software Foundation; either version 2.1      *
 *  /  /  /     \   of the License, or (at your option) any later version.   *
 * (  (  ( B S C )                                                           *
 *  \  \  \_____/   This library is distributed in hope that it will be      *
 *   \  \__         useful but WITHOUT ANY WARRANTY; without even the        *
 *    \___          implied warranty of MERCHANTABILITY or FITNESS FOR A     *
 *                  PARTICULAR PURPOSE. See the GNU LGPL for more details.   *
 *                                                                           *
 * You should have received a copy of the GNU Lesser General Public License  *
 * along with this library; if not, write to the Free Software Foundation,   *
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA          *
 * The GNU LEsser General Public License is contained in the file COPYING.   *
 *                                 ---------                                 *
 *   Barcelona Supercomputing Center - Centro Nacional de Supercomputacion   *
\*****************************************************************************/

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\
 | @file: $HeadURL$
 | @last_commit: $Date$
 | @version:     $Revision$
\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

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

#ifdef __BORLANDC__
#pragma hdrstop
#endif

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

////@begin includes
////@end includes

// Signal handling
#include <signal.h>
#include <stdio.h>

#include "wxparaverapp.h"
#include "connection.h"

////@begin XPM images
////@end XPM images

#ifndef WIN32
struct sigaction act;
#endif

/*!
 * Application instance implementation
 */

////@begin implement app
IMPLEMENT_APP( wxparaverApp )
////@end implement app

/*!
 * wxparaverApp type definition
 */

IMPLEMENT_CLASS( wxparaverApp, wxApp )

/*!
 * wxparaverApp event table definition
 */

BEGIN_EVENT_TABLE( wxparaverApp, wxApp )

////@begin wxparaverApp event table entries
////@end wxparaverApp event table entries

END_EVENT_TABLE()

/*!
 * Constructor for wxparaverApp
 */

wxparaverApp::wxparaverApp()
{
  Init();
}

/*!
 * Member initialisation
 */

void wxparaverApp::Init()
{
////@begin wxparaverApp member initialisation
	globalTiming = false;
	globalTimingBegin = 0;
	globalTimingEnd = 0;
	globalTimingCallDialog = NULL;
	globalTimingBeginIsSet = false;
	eventTypeForCode = 60000119;
////@end wxparaverApp member initialisation
  m_locale.Init();
}

/*!
 * Initialisation for wxparaverApp
 */

paraverMain* wxparaverApp::mainWindow = NULL;

#ifndef WIN32
volatile bool sig1 = false;
volatile bool sig2 = false;

void wxparaverApp::handler( int signalNumber )
{
  sigdelset( &act.sa_mask, SIGUSR1 );
  sigdelset( &act.sa_mask, SIGUSR2 );

//  wxMutexGuiEnter();
//  wxparaverApp::mainWindow->OnSignal( signalNumber );
//  wxMutexGuiLeave();
  if ( signalNumber == SIGUSR1 )
  {
    sig1 = true;
  }
  else
  {
    sig1 = false;
  }

  sig2 = !sig1;

//  wxIdleEvent event;
//  event.RequestMore();
//  wxTheApp->SendIdleEvents( mainWindow, event );
  mainWindow->Raise();

  sigaddset( &act.sa_mask, SIGUSR1 );
  sigaddset( &act.sa_mask, SIGUSR2 );
  sigaction( SIGUSR1, &act, NULL );
  sigaction( SIGUSR2, &act, NULL );
}

void wxparaverApp::presetUserSignals()
{

  act.sa_handler = &handler;
  act.sa_flags = 0;

  if ( sigemptyset( &act.sa_mask ) != 0 )
  {
    /* Handle error */
  }

  if ( sigaddset( &act.sa_mask, SIGUSR1 ))
  {
    /* Handle error */
  }

  if ( sigaddset( &act.sa_mask, SIGUSR2 ))
  {
    /* Handle error */
  }

  if ( sigaction( SIGUSR1, &act, NULL ) != 0 )
  {
    /* Handle error */
  }

  if ( sigaction( SIGUSR2, &act, NULL ) != 0 )
  {
    /* Handle error */
  }
}
#endif

bool wxparaverApp::OnInit()
{
  ParaverConfig::getInstance()->readParaverConfigFile();

  if( ParaverConfig::getInstance()->getGlobalSingleInstance() )
  {
    const wxString name = wxString::Format( _( "wxparaver-%s" ), wxGetUserId().c_str());
    m_checker = new wxSingleInstanceChecker(name);
    if ( !m_checker->IsAnotherRunning() )
    {
      m_server = new stServer;

#ifdef WIN32
      if( !m_server->Create( wxT( "wxparaver_service" ) ) )
#else
      const wxString service_name = wxString::Format( _( "/tmp/wxparaver_service-%s" ), wxGetUserId().c_str());
      if( !m_server->Create( service_name ) )
#endif
        wxLogDebug( wxT( "Failed to create an IPC service." ) );
    }
    else
    {
      wxLogNull logNull;

      stClient *client = new stClient;
      wxString hostName = wxT( "localhost" );
#ifdef WIN32
      wxConnectionBase *connection = client->MakeConnection( hostName,
                                                             wxT( "wxparaver_service" ),
                                                             wxT( "wxparaver" ) );
#else
      const wxString service_name = wxString::Format( _( "/tmp/wxparaver_service-%s" ), wxGetUserId().c_str());
      wxConnectionBase *connection = client->MakeConnection( hostName,
                                                             service_name,
                                                             wxT( "wxparaver" ) );
#endif
      if( connection )
      {
        connection->Execute( wxT( "BEGIN" ) );
        for( int i = 1; i < argc; ++i )
          connection->Execute( argv[ i ] );
        connection->Execute( wxT( "END" ) );
        connection->Disconnect();
        delete connection;
      }
      else
      {
        wxMessageBox( wxT( "Sorry, the existing instance may be too busy to respond." ),
                      wxT( "wxparaver" ), wxICON_INFORMATION|wxOK );
      }

      delete client;
      return false;
    }
  }

  wxCmdLineEntryDesc argumentsParseSyntax[] =
  {
    { wxCMD_LINE_SWITCH,
      wxT("h"),
      wxT("help"),
      wxT("Show this help."),
      wxCMD_LINE_VAL_STRING,
      wxCMD_LINE_OPTION_HELP },

    { wxCMD_LINE_OPTION,
      wxT("t"),
      wxT("type"),
      wxT("Event type to code linking."),
      wxCMD_LINE_VAL_NUMBER,
      wxCMD_LINE_PARAM_OPTIONAL },

    { wxCMD_LINE_PARAM,
      NULL,
      NULL,
      wxT( "(trace.prv | trace.prv.gz) (configuration.cfg)" ),
      wxCMD_LINE_VAL_STRING,
      wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE },

    { wxCMD_LINE_NONE }
  };

#if wxUSE_XPM
  wxImage::AddHandler(new wxXPMHandler);
#endif
#if wxUSE_LIBPNG
  wxImage::AddHandler(new wxPNGHandler);
#endif
#if wxUSE_LIBJPEG
  wxImage::AddHandler(new wxJPEGHandler);
#endif
#if wxUSE_GIF
  wxImage::AddHandler(new wxGIFHandler);
#endif

  wxCmdLineParser paraverCommandLineParser( argumentsParseSyntax, argc, argv );
  paraverCommandLineParser.Parse();

  wxSize mainWindowSize( ParaverConfig::getInstance()->getMainWindowWidth(),
                         ParaverConfig::getInstance()->getMainWindowHeight() );
  mainWindow = new paraverMain( NULL, SYMBOL_PARAVERMAIN_IDNAME, SYMBOL_PARAVERMAIN_TITLE, SYMBOL_PARAVERMAIN_POSITION, mainWindowSize );
  //mainWindow = new paraverMain( NULL );

  mainWindow->Show(true);

  long int tmpType;
  if( paraverCommandLineParser.Found( wxT("t"), &tmpType ) )
    eventTypeForCode = tmpType;

  mainWindow->commandLineLoadings( paraverCommandLineParser );

/*
  paraverMain *mainWindow;
  mainWindow = new paraverMain( NULL );

  mainWindow->Show(true);

  mainWindow->commandLineLoadings( paraverCommandLineParser );
*/
#ifndef WIN32
  presetUserSignals();
#endif

  return true;
}

/*!
 * Cleanup for wxparaverApp
 */

int wxparaverApp::OnExit()
{
//  double w, h;
//  wxparaverApp::mainWindow->GetAuiManager().GetDockSizeConstraint( &w, &h );
//  cout<<w<<" "<<h<<endl;
//  cout << wxparaverApp::mainWindow->GetAuiManager().SavePaneInfo(
//            wxparaverApp::mainWindow->GetAuiManager().GetPane( wxparaverApp::mainWindow->choiceWindowBrowser ) ).mb_str()<<endl;
  ParaverConfig::getInstance()->writeParaverConfigFile();

  if( m_checker != NULL )
    delete m_checker;

  if( m_server != NULL )
    delete m_server;

  // Every time you write some code without goto(s), God kills a kitten. Or was it the other way around?
  goto the_kitten_goto;
  the_kitten_goto:

////@begin wxparaverApp cleanup
	return wxApp::OnExit();
////@end wxparaverApp cleanup
}

#ifdef WIN32
int wxparaverApp::FilterEvent(wxEvent& event)
{
  if ( event.GetEventType()==wxEVT_KEY_DOWN &&
       ((wxKeyEvent&)event).ControlDown() &&
       ((wxKeyEvent&)event).GetKeyCode() == (long) 'C'
     )
  {
    mainWindow->OnKeyCopy();
    return true;
  }
  else if ( event.GetEventType()==wxEVT_KEY_DOWN &&
            ((wxKeyEvent&)event).ControlDown() &&
            ((wxKeyEvent&)event).GetKeyCode() == (long) 'V'
          )
  {
    mainWindow->OnKeyPaste();
    return true;
  }

  return -1;
}
#endif

void wxparaverApp::ActivateGlobalTiming( wxDialog* whichDialog )
{
  globalTimingCallDialog = whichDialog;
  wxSetCursor( *wxCROSS_CURSOR );
  globalTiming = true;
  globalTimingBeginIsSet = false;
  globalTimingCallDialog->Enable( false );
  globalTimingCallDialog->MakeModal( false );
#ifdef WIN32
  globalTimingCallDialog->Iconize( true );
#endif
  mainWindow->Raise();
}

void wxparaverApp::DeactivateGlobalTiming()
{
  wxSetCursor( wxNullCursor );
  globalTiming = false;
  globalTimingBeginIsSet = false;
  globalTimingCallDialog->Enable( true );
  globalTimingCallDialog->MakeModal( true );
#ifdef WIN32
  globalTimingCallDialog->Iconize( false );
#endif
  globalTimingCallDialog->Raise();
}

<|endoftext|>


<commit_before><commit_msg>Main: reset TextureProjector on destroyShadowTextures<commit_after><|endoftext|>