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

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

All rights reserved.

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.

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

#ifndef __itktubeSingleValuedCostFunctionImageSource_hxx
#define __itktubeSingleValuedCostFunctionImageSource_hxx

#include "itktubeSingleValuedCostFunctionImageSource.h"

#include <itkImageRegionIteratorWithIndex.h>
#include <itkProgressReporter.h>

namespace itk
{

namespace tube
{

template< class TCostFunction, unsigned int VNumberOfParameters >
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::SingleValuedCostFunctionImageSource():
  m_ParametersLowerBound( NumberOfParameters ),
  m_ParametersUpperBound( NumberOfParameters ),
  m_ParametersStep( NumberOfParameters )
{
  this->m_ParametersLowerBound.Fill( 0.0 );
  this->m_ParametersUpperBound.Fill( 10.0 );
  this->m_ParametersStep.Fill( 1.0 );
}

template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::SetParametersLowerBound( const ParametersType & lowerBound )
{
  const SizeValueType lowerBoundSize = lowerBound.GetSize();
  if( lowerBoundSize != NumberOfParameters )
    {
    itkExceptionMacro( << "The ParametersLowerBound size: " << lowerBoundSize
      << " does not equal the expected number of parameters: " << NumberOfParameters
      << std::endl );
    }
  for( SizeValueType ii = 0; ii < lowerBoundSize; ++ii )
    {
    if( this->m_ParametersLowerBound[ii] != lowerBound[ii] )
      {
      this->m_ParametersLowerBound = lowerBound;
      this->Modified();
      break;
      }
    }
}

template< class TCostFunction, unsigned int VNumberOfParameters >
typename SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >::ParametersType
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::GetParametersLowerBound() const
{
  return this->m_ParametersLowerBound;
}

template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::SetParametersUpperBound( const ParametersType & upperBound )
{
  const SizeValueType upperBoundSize = upperBound.GetSize();
  if( upperBoundSize != NumberOfParameters )
    {
    itkExceptionMacro( << "The ParametersUpperBound size: " << upperBoundSize
      << " does not equal the expected number of parameters: " << NumberOfParameters
      << std::endl );
    }
  for( SizeValueType ii = 0; ii < upperBoundSize; ++ii )
    {
    if( this->m_ParametersUpperBound[ii] != upperBound[ii] )
      {
      this->m_ParametersUpperBound = upperBound;
      this->Modified();
      break;
      }
    }
}

template< class TCostFunction, unsigned int VNumberOfParameters >
typename SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >::ParametersType
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::GetParametersUpperBound() const
{
  return this->m_ParametersUpperBound;
}

template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::SetParametersStep( const ParametersType & step )
{
  const SizeValueType stepSize = step.GetSize();
  if( stepSize != NumberOfParameters )
    {
    itkExceptionMacro( << "The ParametersStep size: " << stepSize
      << " does not equal the expected number of parameters: " << NumberOfParameters
      << std::endl );
    }
  for( SizeValueType ii = 0; ii < stepSize; ++ii )
    {
    if( this->m_ParametersStep[ii] != step[ii] )
      {
      this->m_ParametersStep = step;
      this->Modified();
      break;
      }
    }
}

template< class TCostFunction, unsigned int VNumberOfParameters >
typename SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >::ParametersType
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::GetParametersStep() const
{
  return this->m_ParametersStep;
}

template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::GenerateOutputInformation()
{
  Superclass::GenerateOutputInformation();

  OutputImageType * outputImage = this->GetOutput();

  typename OutputImageType::IndexType index;
  index.Fill( 0 );
  typename OutputImageType::SizeType size;
  typename OutputImageType::PointType origin;
  typename OutputImageType::SpacingType spacing;
  for( unsigned int ii = 0; ii < NumberOfParameters; ++ii )
    {
    origin[ii] = this->m_ParametersLowerBound[ii];
    spacing[ii] = this->m_ParametersStep[ii];
    size[ii] = static_cast< SizeValueType >( (this->m_ParametersUpperBound[ii] - this->m_ParametersLowerBound[ii]) /
      this->m_ParametersStep[ii] ) + 1;
    }
  typename OutputImageType::RegionType region;
  region.SetIndex( index );
  region.SetSize( size );

  outputImage->SetLargestPossibleRegion( region );
  outputImage->SetSpacing( spacing );
  outputImage->SetOrigin( origin );
  typename OutputImageType::DirectionType direction;
  direction.SetIdentity();
  outputImage->SetDirection( direction );
}

template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::BeforeThreadedGenerateData()
{
  if( this->m_CostFunction.IsNull() )
    {
    itkExceptionMacro( << "Cost function must be assigned!" );
    }
}

template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::ThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId )
{
  OutputImageType * outputImage = this->GetOutput(0);

  ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() );

  typedef ImageRegionIteratorWithIndex< OutputImageType > ImageIteratorType;
  ImageIteratorType imageIt( outputImage, outputRegionForThread );
  for( imageIt.GoToBegin(); !imageIt.IsAtEnd(); ++imageIt )
    {
    const typename OutputImageType::IndexType index = imageIt.GetIndex();
    typename OutputImageType::PointType point;
    outputImage->TransformIndexToPhysicalPoint( index, point );
    ParametersType parameters( NumberOfParameters );
    parameters.SetData( point.GetDataPointer() );
    const MeasureType measure = this->m_CostFunction->GetValue( parameters );
    imageIt.Set( measure );
    progress.CompletedPixel();
    }
}

} // End namespace tube

} // End namespace itk

#endif // End !defined(__itktubeSingleValuedCostFunctionImageSource_hxx)
<commit_msg>ENH: Output cast in SingleValuedCostFunctionImageSource.<commit_after>/*=========================================================================

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

All rights reserved.

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.

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

#ifndef __itktubeSingleValuedCostFunctionImageSource_hxx
#define __itktubeSingleValuedCostFunctionImageSource_hxx

#include "itktubeSingleValuedCostFunctionImageSource.h"

#include <itkImageRegionIteratorWithIndex.h>
#include <itkProgressReporter.h>

namespace itk
{

namespace tube
{

template< class TCostFunction, unsigned int VNumberOfParameters >
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::SingleValuedCostFunctionImageSource():
  m_ParametersLowerBound( NumberOfParameters ),
  m_ParametersUpperBound( NumberOfParameters ),
  m_ParametersStep( NumberOfParameters )
{
  this->m_ParametersLowerBound.Fill( 0.0 );
  this->m_ParametersUpperBound.Fill( 10.0 );
  this->m_ParametersStep.Fill( 1.0 );
}

template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::SetParametersLowerBound( const ParametersType & lowerBound )
{
  const SizeValueType lowerBoundSize = lowerBound.GetSize();
  if( lowerBoundSize != NumberOfParameters )
    {
    itkExceptionMacro( << "The ParametersLowerBound size: " << lowerBoundSize
      << " does not equal the expected number of parameters: " << NumberOfParameters
      << std::endl );
    }
  for( SizeValueType ii = 0; ii < lowerBoundSize; ++ii )
    {
    if( this->m_ParametersLowerBound[ii] != lowerBound[ii] )
      {
      this->m_ParametersLowerBound = lowerBound;
      this->Modified();
      break;
      }
    }
}

template< class TCostFunction, unsigned int VNumberOfParameters >
typename SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >::ParametersType
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::GetParametersLowerBound() const
{
  return this->m_ParametersLowerBound;
}

template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::SetParametersUpperBound( const ParametersType & upperBound )
{
  const SizeValueType upperBoundSize = upperBound.GetSize();
  if( upperBoundSize != NumberOfParameters )
    {
    itkExceptionMacro( << "The ParametersUpperBound size: " << upperBoundSize
      << " does not equal the expected number of parameters: " << NumberOfParameters
      << std::endl );
    }
  for( SizeValueType ii = 0; ii < upperBoundSize; ++ii )
    {
    if( this->m_ParametersUpperBound[ii] != upperBound[ii] )
      {
      this->m_ParametersUpperBound = upperBound;
      this->Modified();
      break;
      }
    }
}

template< class TCostFunction, unsigned int VNumberOfParameters >
typename SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >::ParametersType
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::GetParametersUpperBound() const
{
  return this->m_ParametersUpperBound;
}

template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::SetParametersStep( const ParametersType & step )
{
  const SizeValueType stepSize = step.GetSize();
  if( stepSize != NumberOfParameters )
    {
    itkExceptionMacro( << "The ParametersStep size: " << stepSize
      << " does not equal the expected number of parameters: " << NumberOfParameters
      << std::endl );
    }
  for( SizeValueType ii = 0; ii < stepSize; ++ii )
    {
    if( this->m_ParametersStep[ii] != step[ii] )
      {
      this->m_ParametersStep = step;
      this->Modified();
      break;
      }
    }
}

template< class TCostFunction, unsigned int VNumberOfParameters >
typename SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >::ParametersType
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::GetParametersStep() const
{
  return this->m_ParametersStep;
}

template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::GenerateOutputInformation()
{
  Superclass::GenerateOutputInformation();

  OutputImageType * outputImage = this->GetOutput();

  typename OutputImageType::IndexType index;
  index.Fill( 0 );
  typename OutputImageType::SizeType size;
  typename OutputImageType::PointType origin;
  typename OutputImageType::SpacingType spacing;
  for( unsigned int ii = 0; ii < NumberOfParameters; ++ii )
    {
    origin[ii] = this->m_ParametersLowerBound[ii];
    spacing[ii] = this->m_ParametersStep[ii];
    size[ii] = static_cast< SizeValueType >( (this->m_ParametersUpperBound[ii] - this->m_ParametersLowerBound[ii]) /
      this->m_ParametersStep[ii] ) + 1;
    }
  typename OutputImageType::RegionType region;
  region.SetIndex( index );
  region.SetSize( size );

  outputImage->SetLargestPossibleRegion( region );
  outputImage->SetSpacing( spacing );
  outputImage->SetOrigin( origin );
  typename OutputImageType::DirectionType direction;
  direction.SetIdentity();
  outputImage->SetDirection( direction );
}

template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::BeforeThreadedGenerateData()
{
  if( this->m_CostFunction.IsNull() )
    {
    itkExceptionMacro( << "Cost function must be assigned!" );
    }
}

template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::ThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId )
{
  OutputImageType * outputImage = this->GetOutput(0);

  ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() );

  typedef ImageRegionIteratorWithIndex< OutputImageType > ImageIteratorType;
  ImageIteratorType imageIt( outputImage, outputRegionForThread );
  for( imageIt.GoToBegin(); !imageIt.IsAtEnd(); ++imageIt )
    {
    const typename OutputImageType::IndexType index = imageIt.GetIndex();
    typename OutputImageType::PointType point;
    outputImage->TransformIndexToPhysicalPoint( index, point );
    ParametersType parameters( NumberOfParameters );
    parameters.SetData( point.GetDataPointer() );
    const MeasureType measure = this->m_CostFunction->GetValue( parameters );
    imageIt.Set( static_cast< typename OutputImageType::PixelType >( measure ) );
    progress.CompletedPixel();
    }
}

} // End namespace tube

} // End namespace itk

#endif // End !defined(__itktubeSingleValuedCostFunctionImageSource_hxx)
<|endoftext|>


<commit_before>/*
*
* XMLFileReporter.cpp
*
* Copyright 2000 Lotus Development Corporation. All rights reserved.
* This software is subject to the Lotus Software Agreement, Restricted
* Rights for U.S. government users and applicable export regulations.
*/

#include <stdlib.h>
#include "XMLFileReporter.hpp"

#include "PlatformSupport/XalanUnicode.hpp"

const XalanDOMString  XMLFileReporter::OPT_FILENAME("filename");
const XalanDOMString  XMLFileReporter::ELEM_RESULTSFILE("resultsfile");
const XalanDOMString  XMLFileReporter::ELEM_TESTFILE("testfile");
const XalanDOMString  XMLFileReporter::ELEM_FILERESULT("fileresult");
const XalanDOMString  XMLFileReporter::ELEM_TESTCASE("testcase");
const XalanDOMString  XMLFileReporter::ELEM_CASERESULT("caseresult");
const XalanDOMString  XMLFileReporter::ELEM_CHECKRESULT("checkresult");
const XalanDOMString  XMLFileReporter::ELEM_STATISTIC("statistic");
const XalanDOMString  XMLFileReporter::ELEM_LONGVAL("longval");
const XalanDOMString  XMLFileReporter::ELEM_DOUBLEVAL("doubleval");
const XalanDOMString  XMLFileReporter::ELEM_MESSAGE("message");
const XalanDOMString  XMLFileReporter::ELEM_ARBITRARY("arbitrary");
const XalanDOMString  XMLFileReporter::ELEM_HASHTABLE("hashtable");
const XalanDOMString  XMLFileReporter::ELEM_HASHITEM("hashitem");
const XalanDOMString  XMLFileReporter::ATTR_LEVEL("level");
const XalanDOMString  XMLFileReporter::ATTR_DESC("desc");
const XalanDOMString  XMLFileReporter::ATTR_TIME("time");
const XalanDOMString  XMLFileReporter::ATTR_RESULT("result");
const XalanDOMString  XMLFileReporter::ATTR_KEY("key");
const XalanDOMString  XMLFileReporter::ATTR_FILENAME = XMLFileReporter::OPT_FILENAME;

const XalanDOMString XMLFileReporter::TESTCASEINIT_HDR("<" + ELEM_TESTCASE + " " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::TESTCASECLOSE_HDR("<" + ELEM_CASERESULT + " " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::MESSAGE_HDR("<" + ELEM_MESSAGE + " " + ATTR_LEVEL + "=\"");
const XalanDOMString XMLFileReporter::STATISTIC_HDR("<" + ELEM_STATISTIC + " " + ATTR_LEVEL + "=\"");
const XalanDOMString XMLFileReporter::ARBITRARY_HDR("<" + ELEM_ARBITRARY + " " + ATTR_LEVEL + "=\"");
const XalanDOMString XMLFileReporter::HASHTABLE_HDR("<" + ELEM_HASHTABLE + " " + ATTR_LEVEL + "=\"");
const XalanDOMString XMLFileReporter::HASHITEM_HDR("  <" + ELEM_HASHITEM + " " + ATTR_KEY + "=\"");
const XalanDOMString XMLFileReporter::CHECKPASS_HDR("<" + ELEM_CHECKRESULT + " " + ATTR_RESULT + "=\"" + "PASS" + "\" " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::CHECKAMBG_HDR("<" + ELEM_CHECKRESULT + " " + ATTR_RESULT + "=\"" + "AMBG" + "\" " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::CHECKERRR_HDR("<" + ELEM_CHECKRESULT + " " + ATTR_RESULT + "=\"" + "ERRR" + "\" " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::CHECKFAIL_HDR("<" + ELEM_CHECKRESULT + " " + ATTR_RESULT + "=\"" + "FAIL" + "\" " + ATTR_DESC + "=\"");

XMLFileReporter::XMLFileReporter():
	m_anyOutput(false),
	m_fileName(""),
	m_fileHandle(0),
	m_ready(false),
	m_error(false),
	m_flushOnCaseClose(true)
{
}

XMLFileReporter::XMLFileReporter(const XalanDOMString& fileName):
	m_anyOutput(false),
	m_fileName(fileName),
	m_fileHandle(0),
	m_ready(false),
	m_error(false),
	m_flushOnCaseClose(true)
{
    m_ready = initialize();
}

XMLFileReporter::XMLFileReporter(const char* fileName):
	m_anyOutput(false),
	m_fileName(XalanDOMString(fileName)),
	m_fileHandle(0),
	m_ready(false),
	m_error(false),
	m_flushOnCaseClose(true)
{
    m_ready = initialize();
}

bool
XMLFileReporter::initialize()
{
    if (length(m_fileName) == 0)
    {
        // We don't have a valid file, so bail
        m_error = true;
        m_ready = false;
        fprintf(stderr, "XMLFileReporter.initialize() ERROR: file name is blank");
        return(false);
    }

    // Create a file and ensure it has a place to live
	m_fileHandle = fopen(&m_fileName.transcode().front(), "w");
	if (m_fileHandle == 0)
	{
        // Couldn't create or find the directory for the file to live in, so bail
        m_error = true;
        m_ready = false;
        fprintf(stderr, "XMLFileReporter.initialize() ERROR: unble to open file, %s", m_fileName);
        return(false);
	}

    m_ready = true;
    startResultsFile();
    // fprintf(stderr, "DEBUG:XMLFileReporter.initialize() complete with " + fileName);

    return m_ready;
}

bool
XMLFileReporter::getFlushOnCaseClose()
{
    return(m_flushOnCaseClose);
}

const XalanDOMString&
XMLFileReporter::getFileName() const
{
    return(m_fileName);
}

void
XMLFileReporter::setFileName(const XalanDOMString& fileName)
{
	m_fileName = fileName;
}

bool
XMLFileReporter::checkError()
{
    // Ensure our underlying reporter, if one, is still OK
    if (m_fileHandle == 0)
    {
        m_error = true;
    }
    return(m_error);
}

bool
XMLFileReporter::isReady()
{
    // Ensure our underlying reporter, if one, is still OK
    if (m_fileHandle == 0)
    {
        // NEEDSWORK: should we set m_ready = false in this case?
        //            errors in the PrintStream are not necessarily fatal
        m_error = true;
        m_ready = false;
    }
    return(m_ready);
}

void
XMLFileReporter::flush()
{
    if (isReady())
    {
		fflush(m_fileHandle);
    }
}

void
XMLFileReporter::close()
{
    fflush(m_fileHandle);
    if (isReady())
    {
		if (m_fileHandle != 0)
		{
			closeResultsFile();
			fclose(m_fileHandle);
		}
    }
    m_ready = false;
}

void
XMLFileReporter::logTestFileInit(const XalanDOMString& msg)
{
    if (isReady())
    {
        printToFile("<" + ELEM_TESTFILE
                              + " " + ATTR_DESC + "=\"" + escapestring(msg) + "\" " + ATTR_TIME + "=\"" + getDateTimeString() + "\">");
    }
}

void
XMLFileReporter::logTestFileClose(const XalanDOMString& msg, const XalanDOMString& result)
{
    if (isReady())
    {
        printToFile("<" + ELEM_FILERESULT
                              + " " + ATTR_DESC + "=\"" + escapestring(msg) + "\" " + ATTR_RESULT + "=\"" + result + "\" " + ATTR_TIME + "=\"" + getDateTimeString() + "\"/>");
        printToFile("</" + ELEM_TESTFILE + ">");
    }
    flush();
}

void
XMLFileReporter::logTestCaseInit(const XalanDOMString& msg)
{
    if (isReady())
    {
        printToFile(TESTCASEINIT_HDR + escapestring(msg) + "\">");
    }
}

void
XMLFileReporter::logTestCaseClose(const XalanDOMString& msg, const XalanDOMString& result)
{
    if (isReady())
    {
        printToFile(TESTCASECLOSE_HDR + escapestring(msg) + "\" " + ATTR_RESULT + "=\"" + result + "\"/>");
        printToFile("</" + ELEM_TESTCASE + ">");
    }
    if (getFlushOnCaseClose())
    {
        flush();
    }
}

void
XMLFileReporter::logMessage(int level, const XalanDOMString& msg)
{
	char tmp[20];
	sprintf(tmp, "%d", level);

    if (isReady())
    {
        printToFile(MESSAGE_HDR + tmp + "\">");
        printToFile(escapestring(msg));
        printToFile("</" + ELEM_MESSAGE +">");
    }
}

void
XMLFileReporter::logElement(int level, const XalanDOMString& element, Hashtable attrs,const XalanDOMString& msg)
{
	if (isReady()
        && (element.empty() == 0)
        && (attrs.empty() == 0)
       )
    {
		char tmp[20];
		sprintf(tmp, "%d", level);

        printToFile("<" + escapestring(element) + " " + ATTR_LEVEL + "=\""
                              + tmp + "\"");

		Hashtable::iterator theEnd = attrs.end();

       	for(Hashtable::iterator i = attrs.begin(); i != theEnd; ++i)
        {

            printToFile((*i).first + "=\""
                                  + (*i).second + "\"");
        }

        printToFile(XalanDOMString(">"));
        if (msg.empty() != 0)
            printToFile(escapestring(msg));
        printToFile("</" + escapestring(element) + ">");
    }
}

void
XMLFileReporter::logStatistic (int level, long lVal, double dVal, const XalanDOMString& msg)
{
 	char tmp[20];

	if (isReady())
    {
		sprintf(tmp, "%d", level);
        printToFile(STATISTIC_HDR + tmp + "\" " + ATTR_DESC + "=\"" + escapestring(msg) + "\">");

		sprintf(tmp, "%d", lVal);
		printToFile("<" + ELEM_LONGVAL + ">" + tmp + "</" + ELEM_LONGVAL + ">");

		sprintf(tmp, "%d", dVal);
        printToFile("<" + ELEM_DOUBLEVAL + ">" + tmp + "</" + ELEM_DOUBLEVAL + ">");

		printToFile("</" + ELEM_STATISTIC + ">");

    }
}

void
XMLFileReporter::logArbitraryMessage (int level, const XalanDOMString& msg)
{
	char tmp[20];
	sprintf(tmp, "%d", level);

    if (isReady())
    {
		printToFile(ARBITRARY_HDR + tmp + "\">");
        printToFile(escapestring(msg));
        printToFile("</" + ELEM_ARBITRARY +">");
    }
}

/*
void logHashtable (int level, Hashtable hash, XalanDOMString msg)
{
    if (isReady())
    {
        printToFile(HASHTABLE_HDR + level + "\" " + ATTR_DESC + "=\"" + msg + "\">");
        if (hash == null)
        {
            printToFile("<" + ELEM_HASHITEM + " " + ATTR_KEY + "=\"null\">");
            printToFile("</" + ELEM_HASHITEM + ">");
        }
        try
        {
            for (Enumeration enum = hash.keys(); enum.hasMoreElements();)
            {
                Object key = enum.nextElement();
                // Ensure we'll have clean output by pre-fetching value before outputting anything
                XalanDOMString value = hash.get(key).tostring();
                printToFile(HASHITEM_HDR + key.tostring() + "\">");
                printToFile(value);
                printToFile("</" + ELEM_HASHITEM + ">");
            }
        }
        catch (Exception e)
        {
            // No-op: should ensure we have clean output
        }
        printToFile("</" + ELEM_HASHTABLE +">");
    }
}
*/

void
XMLFileReporter::logCheckPass(const XalanDOMString& comment)
{
    if (isReady())
    {
        printToFile(CHECKPASS_HDR + escapestring(comment) + "\"/>");
    }
}

void
XMLFileReporter::logCheckAmbiguous(const XalanDOMString& comment)
{
    if (isReady())
    {
        printToFile(CHECKAMBG_HDR + escapestring(comment) + "\"/>");
    }
}

void
XMLFileReporter::logCheckFail(const XalanDOMString& comment)
{
    if (isReady())
    {
        printToFile(CHECKFAIL_HDR + escapestring(comment) + "\"/>");
    }
}

void
XMLFileReporter::logCheckErr(const XalanDOMString& comment)
{
    if (isReady())
    {
        printToFile(CHECKERRR_HDR + escapestring(comment) + "\"/>");
    }
}

static const XalanDOMChar	theLessThanString[] =
{
	XalanUnicode::charAmpersand,
	XalanUnicode::charLetter_l,
	XalanUnicode::charLetter_t,
	XalanUnicode::charSemicolon,
	0
};

static const XalanDOMChar	theGreaterThanString[] =
{
	XalanUnicode::charAmpersand,
	XalanUnicode::charLetter_g,
	XalanUnicode::charLetter_t,
	XalanUnicode::charSemicolon,
	0
};

XalanDOMString
XMLFileReporter::escapestring(const XalanDOMString&  s)
{
    XalanDOMString		sb;

    const unsigned int	length = s.length();

    for (unsigned int i = 0; i < length; i++)
    {
        const XalanDOMChar	ch = charAt(s, i);

        if (XalanUnicode::charLessThanSign == ch)
        {
			append(sb, theLessThanString);
        }
        else if (XalanUnicode::charGreaterThanSign == ch)
        {
			append(sb, theGreaterThanString);
        }
        // Note: Skipping escaping of UTF-16 surrogates and & ampersands, since
        //  I don't think we'll be outputting them or they won't affect our output
        else
        {
            append(sb, ch);
        }
    }

	return sb;
}

bool
XMLFileReporter::startResultsFile()
{
    if (isReady())
    {
        // Write out XML header and root test result element
        printToFile(XalanDOMString("<?xml version=\"1.0\"?>"));

        // Note: this tag is closed in our .close() method, which the caller had better call!
        printToFile("<" + ELEM_RESULTSFILE + " " + ATTR_FILENAME + "=\"" + m_fileName + "\">");

        return true;
    }
    else
	{
        return false;
	}
}

bool
XMLFileReporter::closeResultsFile()
{
    if (isReady())
    {
		printToFile("</" + ELEM_RESULTSFILE + ">");
        return true;
    }
    else
        return false;
}

bool
XMLFileReporter::printToFile(const XalanDOMString&	output)
{
    if (isReady())
    {
        fprintf(m_fileHandle, &output.transcode().front());
		fprintf(m_fileHandle, "\n");
        return true;
    }
    else
        return false;
}

XalanDOMString
XMLFileReporter::getDateTimeString()
{
	struct tm *tmNow;
	time_t time_tNow;

	time(&time_tNow);
	tmNow = localtime(&time_tNow);

	const char* const	theTime = asctime(tmNow);

	return XalanDOMString(theTime, strlen(theTime) - 1);
}
<commit_msg>Removed Level attribute from logElement method<commit_after>/*
*
* XMLFileReporter.cpp
*
* Copyright 2000 Lotus Development Corporation. All rights reserved.
* This software is subject to the Lotus Software Agreement, Restricted
* Rights for U.S. government users and applicable export regulations.
*/

#include <stdlib.h>
#include "XMLFileReporter.hpp"

#include "PlatformSupport/XalanUnicode.hpp"

const XalanDOMString  XMLFileReporter::OPT_FILENAME("filename");
const XalanDOMString  XMLFileReporter::ELEM_RESULTSFILE("resultsfile");
const XalanDOMString  XMLFileReporter::ELEM_TESTFILE("testfile");
const XalanDOMString  XMLFileReporter::ELEM_FILERESULT("fileresult");
const XalanDOMString  XMLFileReporter::ELEM_TESTCASE("testcase");
const XalanDOMString  XMLFileReporter::ELEM_CASERESULT("caseresult");
const XalanDOMString  XMLFileReporter::ELEM_CHECKRESULT("checkresult");
const XalanDOMString  XMLFileReporter::ELEM_STATISTIC("statistic");
const XalanDOMString  XMLFileReporter::ELEM_LONGVAL("longval");
const XalanDOMString  XMLFileReporter::ELEM_DOUBLEVAL("doubleval");
const XalanDOMString  XMLFileReporter::ELEM_MESSAGE("message");
const XalanDOMString  XMLFileReporter::ELEM_ARBITRARY("arbitrary");
const XalanDOMString  XMLFileReporter::ELEM_HASHTABLE("hashtable");
const XalanDOMString  XMLFileReporter::ELEM_HASHITEM("hashitem");
const XalanDOMString  XMLFileReporter::ATTR_LEVEL("level");
const XalanDOMString  XMLFileReporter::ATTR_DESC("desc");
const XalanDOMString  XMLFileReporter::ATTR_TIME("time");
const XalanDOMString  XMLFileReporter::ATTR_RESULT("result");
const XalanDOMString  XMLFileReporter::ATTR_KEY("key");
const XalanDOMString  XMLFileReporter::ATTR_FILENAME = XMLFileReporter::OPT_FILENAME;

const XalanDOMString XMLFileReporter::TESTCASEINIT_HDR("<" + ELEM_TESTCASE + " " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::TESTCASECLOSE_HDR("<" + ELEM_CASERESULT + " " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::MESSAGE_HDR("<" + ELEM_MESSAGE + " " + ATTR_LEVEL + "=\"");
const XalanDOMString XMLFileReporter::STATISTIC_HDR("<" + ELEM_STATISTIC + " " + ATTR_LEVEL + "=\"");
const XalanDOMString XMLFileReporter::ARBITRARY_HDR("<" + ELEM_ARBITRARY + " " + ATTR_LEVEL + "=\"");
const XalanDOMString XMLFileReporter::HASHTABLE_HDR("<" + ELEM_HASHTABLE + " " + ATTR_LEVEL + "=\"");
const XalanDOMString XMLFileReporter::HASHITEM_HDR("  <" + ELEM_HASHITEM + " " + ATTR_KEY + "=\"");
const XalanDOMString XMLFileReporter::CHECKPASS_HDR("<" + ELEM_CHECKRESULT + " " + ATTR_RESULT + "=\"" + "PASS" + "\" " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::CHECKAMBG_HDR("<" + ELEM_CHECKRESULT + " " + ATTR_RESULT + "=\"" + "AMBG" + "\" " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::CHECKERRR_HDR("<" + ELEM_CHECKRESULT + " " + ATTR_RESULT + "=\"" + "ERRR" + "\" " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::CHECKFAIL_HDR("<" + ELEM_CHECKRESULT + " " + ATTR_RESULT + "=\"" + "FAIL" + "\" " + ATTR_DESC + "=\"");

XMLFileReporter::XMLFileReporter():
	m_anyOutput(false),
	m_fileName(""),
	m_fileHandle(0),
	m_ready(false),
	m_error(false),
	m_flushOnCaseClose(true)
{
}

XMLFileReporter::XMLFileReporter(const XalanDOMString& fileName):
	m_anyOutput(false),
	m_fileName(fileName),
	m_fileHandle(0),
	m_ready(false),
	m_error(false),
	m_flushOnCaseClose(true)
{
    m_ready = initialize();
}

XMLFileReporter::XMLFileReporter(const char* fileName):
	m_anyOutput(false),
	m_fileName(XalanDOMString(fileName)),
	m_fileHandle(0),
	m_ready(false),
	m_error(false),
	m_flushOnCaseClose(true)
{
    m_ready = initialize();
}

bool
XMLFileReporter::initialize()
{
    if (length(m_fileName) == 0)
    {
        // We don't have a valid file, so bail
        m_error = true;
        m_ready = false;
        fprintf(stderr, "XMLFileReporter.initialize() ERROR: file name is blank");
        return(false);
    }

    // Create a file and ensure it has a place to live
	m_fileHandle = fopen(&m_fileName.transcode().front(), "w");
	if (m_fileHandle == 0)
	{
        // Couldn't create or find the directory for the file to live in, so bail
        m_error = true;
        m_ready = false;
        fprintf(stderr, "XMLFileReporter.initialize() ERROR: unble to open file, %s", m_fileName);
        return(false);
	}

    m_ready = true;
    startResultsFile();
    // fprintf(stderr, "DEBUG:XMLFileReporter.initialize() complete with " + fileName);

    return m_ready;
}

bool
XMLFileReporter::getFlushOnCaseClose()
{
    return(m_flushOnCaseClose);
}

const XalanDOMString&
XMLFileReporter::getFileName() const
{
    return(m_fileName);
}

void
XMLFileReporter::setFileName(const XalanDOMString& fileName)
{
	m_fileName = fileName;
}

bool
XMLFileReporter::checkError()
{
    // Ensure our underlying reporter, if one, is still OK
    if (m_fileHandle == 0)
    {
        m_error = true;
    }
    return(m_error);
}

bool
XMLFileReporter::isReady()
{
    // Ensure our underlying reporter, if one, is still OK
    if (m_fileHandle == 0)
    {
        // NEEDSWORK: should we set m_ready = false in this case?
        //            errors in the PrintStream are not necessarily fatal
        m_error = true;
        m_ready = false;
    }
    return(m_ready);
}

void
XMLFileReporter::flush()
{
    if (isReady())
    {
		fflush(m_fileHandle);
    }
}

void
XMLFileReporter::close()
{
    fflush(m_fileHandle);
    if (isReady())
    {
		if (m_fileHandle != 0)
		{
			closeResultsFile();
			fclose(m_fileHandle);
		}
    }
    m_ready = false;
}

void
XMLFileReporter::logTestFileInit(const XalanDOMString& msg)
{
    if (isReady())
    {
        printToFile("<" + ELEM_TESTFILE
                              + " " + ATTR_DESC + "=\"" + escapestring(msg) + "\" " + ATTR_TIME + "=\"" + getDateTimeString() + "\">");
    }
}

void
XMLFileReporter::logTestFileClose(const XalanDOMString& msg, const XalanDOMString& result)
{
    if (isReady())
    {
        printToFile("<" + ELEM_FILERESULT
                              + " " + ATTR_DESC + "=\"" + escapestring(msg) + "\" " + ATTR_RESULT + "=\"" + result + "\" " + ATTR_TIME + "=\"" + getDateTimeString() + "\"/>");
        printToFile("</" + ELEM_TESTFILE + ">");
    }
    flush();
}

void
XMLFileReporter::logTestCaseInit(const XalanDOMString& msg)
{
    if (isReady())
    {
        printToFile(TESTCASEINIT_HDR + escapestring(msg) + "\">");
    }
}

void
XMLFileReporter::logTestCaseClose(const XalanDOMString& msg, const XalanDOMString& result)
{
    if (isReady())
    {
        printToFile(TESTCASECLOSE_HDR + escapestring(msg) + "\" " + ATTR_RESULT + "=\"" + result + "\"/>");
        printToFile("</" + ELEM_TESTCASE + ">");
    }
    if (getFlushOnCaseClose())
    {
        flush();
    }
}

void
XMLFileReporter::logMessage(int level, const XalanDOMString& msg)
{
	char tmp[20];
	sprintf(tmp, "%d", level);

    if (isReady())
    {
        printToFile(MESSAGE_HDR + tmp + "\">");
        printToFile(escapestring(msg));
        printToFile("</" + ELEM_MESSAGE +">");
    }
}

void
XMLFileReporter::logElement(int level, const XalanDOMString& element, Hashtable attrs,const XalanDOMString& msg)
{
	if (isReady()
        && (element.empty() == 0)
        && (attrs.empty() == 0)
       )
    {
		char tmp[20];
		sprintf(tmp, "%d", level);
//
//		Took out this level attribute cuz we don't use it.
//      printToFile("<" + escapestring(element) + " " + ATTR_LEVEL + "=\""
//                      + tmp + "\"");
        printToFile("<" + escapestring(element) + " ");

		Hashtable::iterator theEnd = attrs.end();

       	for(Hashtable::iterator i = attrs.begin(); i != theEnd; ++i)
        {

            printToFile((*i).first + "=\""
                                  + (*i).second + "\"");
        }

        printToFile(XalanDOMString(">"));
        if (msg.empty() != 0)
            printToFile(escapestring(msg));
        printToFile("</" + escapestring(element) + ">");
    }
}

void
XMLFileReporter::logStatistic (int level, long lVal, double dVal, const XalanDOMString& msg)
{
 	char tmp[20];

	if (isReady())
    {
		sprintf(tmp, "%d", level);
        printToFile(STATISTIC_HDR + tmp + "\" " + ATTR_DESC + "=\"" + escapestring(msg) + "\">");

		sprintf(tmp, "%d", lVal);
		printToFile("<" + ELEM_LONGVAL + ">" + tmp + "</" + ELEM_LONGVAL + ">");

		sprintf(tmp, "%d", dVal);
        printToFile("<" + ELEM_DOUBLEVAL + ">" + tmp + "</" + ELEM_DOUBLEVAL + ">");

		printToFile("</" + ELEM_STATISTIC + ">");

    }
}

void
XMLFileReporter::logArbitraryMessage (int level, const XalanDOMString& msg)
{
	char tmp[20];
	sprintf(tmp, "%d", level);

    if (isReady())
    {
		printToFile(ARBITRARY_HDR + tmp + "\">");
        printToFile(escapestring(msg));
        printToFile("</" + ELEM_ARBITRARY +">");
    }
}

/*
void logHashtable (int level, Hashtable hash, XalanDOMString msg)
{
    if (isReady())
    {
        printToFile(HASHTABLE_HDR + level + "\" " + ATTR_DESC + "=\"" + msg + "\">");
        if (hash == null)
        {
            printToFile("<" + ELEM_HASHITEM + " " + ATTR_KEY + "=\"null\">");
            printToFile("</" + ELEM_HASHITEM + ">");
        }
        try
        {
            for (Enumeration enum = hash.keys(); enum.hasMoreElements();)
            {
                Object key = enum.nextElement();
                // Ensure we'll have clean output by pre-fetching value before outputting anything
                XalanDOMString value = hash.get(key).tostring();
                printToFile(HASHITEM_HDR + key.tostring() + "\">");
                printToFile(value);
                printToFile("</" + ELEM_HASHITEM + ">");
            }
        }
        catch (Exception e)
        {
            // No-op: should ensure we have clean output
        }
        printToFile("</" + ELEM_HASHTABLE +">");
    }
}
*/

void
XMLFileReporter::logCheckPass(const XalanDOMString& comment)
{
    if (isReady())
    {
        printToFile(CHECKPASS_HDR + escapestring(comment) + "\"/>");
    }
}

void
XMLFileReporter::logCheckAmbiguous(const XalanDOMString& comment)
{
    if (isReady())
    {
        printToFile(CHECKAMBG_HDR + escapestring(comment) + "\"/>");
    }
}

void
XMLFileReporter::logCheckFail(const XalanDOMString& comment)
{
    if (isReady())
    {
        printToFile(CHECKFAIL_HDR + escapestring(comment) + "\"/>");
    }
}

void
XMLFileReporter::logCheckErr(const XalanDOMString& comment)
{
    if (isReady())
    {
        printToFile(CHECKERRR_HDR + escapestring(comment) + "\"/>");
    }
}

static const XalanDOMChar	theLessThanString[] =
{
	XalanUnicode::charAmpersand,
	XalanUnicode::charLetter_l,
	XalanUnicode::charLetter_t,
	XalanUnicode::charSemicolon,
	0
};

static const XalanDOMChar	theGreaterThanString[] =
{
	XalanUnicode::charAmpersand,
	XalanUnicode::charLetter_g,
	XalanUnicode::charLetter_t,
	XalanUnicode::charSemicolon,
	0
};

XalanDOMString
XMLFileReporter::escapestring(const XalanDOMString&  s)
{
    XalanDOMString		sb;

    const unsigned int	length = s.length();

    for (unsigned int i = 0; i < length; i++)
    {
        const XalanDOMChar	ch = charAt(s, i);

        if (XalanUnicode::charLessThanSign == ch)
        {
			append(sb, theLessThanString);
        }
        else if (XalanUnicode::charGreaterThanSign == ch)
        {
			append(sb, theGreaterThanString);
        }
        // Note: Skipping escaping of UTF-16 surrogates and & ampersands, since
        //  I don't think we'll be outputting them or they won't affect our output
        else
        {
            append(sb, ch);
        }
    }

	return sb;
}

bool
XMLFileReporter::startResultsFile()
{
    if (isReady())
    {
        // Write out XML header and root test result element
        printToFile(XalanDOMString("<?xml version=\"1.0\"?>"));

        // Note: this tag is closed in our .close() method, which the caller had better call!
        printToFile("<" + ELEM_RESULTSFILE + " " + ATTR_FILENAME + "=\"" + m_fileName + "\">");

        return true;
    }
    else
	{
        return false;
	}
}

bool
XMLFileReporter::closeResultsFile()
{
    if (isReady())
    {
		printToFile("</" + ELEM_RESULTSFILE + ">");
        return true;
    }
    else
        return false;
}

bool
XMLFileReporter::printToFile(const XalanDOMString&	output)
{
    if (isReady())
    {
        fprintf(m_fileHandle, &output.transcode().front());
		fprintf(m_fileHandle, "\n");
        return true;
    }
    else
        return false;
}

XalanDOMString
XMLFileReporter::getDateTimeString()
{
	struct tm *tmNow;
	time_t time_tNow;

	time(&time_tNow);
	tmNow = localtime(&time_tNow);

	const char* const	theTime = asctime(tmNow);

	return XalanDOMString(theTime, strlen(theTime) - 1);
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the  "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#if !defined(TESTHARNESS_HEADER_GUARD_1357924680)
#define TESTHARNESS_HEADER_GUARD_1357924680

// Base header file.  Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>

#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <fstream.h>
#else
#include <fstream>
#endif

#include <xalanc/Include/XalanMemoryManagement.hpp>
#include <xalanc/Include/XalanVector.hpp>
#include <xalanc/Include/XalanMap.hpp>

#include <xalanc/PlatformSupport/DOMStringHelper.hpp>

#include <xalanc/XalanDOM/XalanNode.hpp>
#include <xalanc/XalanDOM/XalanDOMString.hpp>

#include <xalanc/Harness/XalanFileUtility.hpp>
#include <xalanc/Harness/XalanXMLFileReporter.hpp>

#include "Utils.hpp"
#include "Logger.hpp"
#include "Timer.hpp"

XALAN_USING_XALAN(XalanMemMgrs)
XALAN_USING_XALAN(XalanVector)
XALAN_USING_XALAN(XalanMap)
XALAN_USING_XALAN(XalanNode)
XALAN_USING_XALAN(XalanDOMString)
XALAN_USING_XALAN(XalanFileUtility)
XALAN_USING_XALAN(XalanXMLFileReporter)

/**
 * Processor interface options
 */
struct ProcessorOptions
{
    XalanNode*  initOptions;
    XalanNode*  compileOptions;
    XalanNode*  parseOptions;
    XalanNode*  resultOptions;
    XalanNode*  transformOptions;

    ProcessorOptions() :
            initOptions(0),
            compileOptions(0),
            parseOptions(0),
            resultOptions(0),
            transformOptions(0)
    {
    }
};

/**
 * Test case
 */
class TestCase
{
public:

    TestCase();

    TestCase(const TestCase& theRhs);

    XalanDOMString  stylesheet;
    XalanDOMString  inputDocument;
    XalanDOMString  resultDocument;
    XalanDOMString  resultDirectory;
    XalanDOMString  goldResult;
    long            numIterations;
    long            minTimeToExecute;
    bool            verifyResult;
    XalanDOMString  inputMode;

    typedef XalanMap<XalanDOMString, ProcessorOptions>  ProcessorOptionsMap;

    ProcessorOptionsMap processorOptions;
};

typedef TestCase                    TestCaseType;
typedef XalanVector<TestCaseType>   TestCasesType;

/**
 *  Test harness
 */
template <class Processor>
class TestHarness
{
public:

    typedef typename Processor::CompiledStylesheetType  CompiledStylesheetType;
    typedef typename Processor::ParsedInputSourceType   ParsedInputSourceType;
    typedef typename Processor::ResultTargetType        ResultTargetType;

    typedef typename XalanXMLFileReporter::Hashtable    TestAttributesType;

    TestHarness();

    void init(
            XalanFileUtility&       fileUtility,
            XalanXMLFileReporter&   reporter,
            Logger&                 logger);

    void terminate();

    void executeTestCase(const TestCaseType& testCase);

    void executeTestCases(const TestCasesType& testCases);

protected:

    Processor m_processor;

    XalanFileUtility*       m_fileUtility;

    XalanXMLFileReporter*   m_reporter;

    Logger*                 m_logger;
};

template <class Processor>
void
TestHarness<Processor>::executeTestCases(const TestCasesType& testCases)
{
    TestCasesType::const_iterator testCaseIter = testCases.begin();
    while (testCaseIter != testCases.end())
    {
        executeTestCase(*testCaseIter);
        ++testCaseIter;
    }
}

template <class Processor>
void
TestHarness<Processor>::executeTestCase(const TestCaseType& testCase)
{
    TestAttributesType testAttributes(XalanMemMgrs::getDefaultXercesMemMgr());

    testAttributes.insert(TestAttributesType::value_type(XalanDOMString("stylesheet"), testCase.stylesheet));
    testAttributes.insert(TestAttributesType::value_type(XalanDOMString("input-document"), testCase.inputDocument));

    try {

        CompiledStylesheetType  compiledStylesheet;
        ParsedInputSourceType   parsedInputSource;
        ResultTargetType        resultTarget;

        static const ProcessorOptions defaultProcessor;

        TestCase::ProcessorOptionsMap::const_iterator iter = testCase.processorOptions.find(m_processor.getName());

        const ProcessorOptions&  processor = iter != testCase.processorOptions.end() ? iter->second : defaultProcessor;

        m_fileUtility->checkAndCreateDir(testCase.resultDirectory);

        Timer timeCompile;

        if (testCase.inputMode == XalanDOMString("stream"))
        {
#if defined(XALAN_CLASSIC_IOSTREAMS)
            XALAN_USING_XALAN(CharVectorType)
            XALAN_USING_XALAN(c_str)

            XALAN_USING_STD(istringstream)

            CharVectorType  buffer;
            fileToStream(testCase.stylesheet, buffer);

            istrstream      compilerStream(c_str(buffer));
#else
            XALAN_USING_STD(istringstream)

            istringstream compilerStream;
            fileToStream(testCase.stylesheet, compilerStream);
#endif
            timeCompile.start();
            compiledStylesheet = m_processor.compileStylesheet(
                    compilerStream,
                    processor.compileOptions);
            timeCompile.stop();
        }
        else if (testCase.inputMode == XalanDOMString("file"))
        {
            timeCompile.start();
            compiledStylesheet = m_processor.compileStylesheet(
                    testCase.stylesheet,
                    processor.compileOptions);
            timeCompile.stop();
        }
        else
        {
            m_logger->error()
                    << "Mode: "
                    << testCase.inputMode.c_str()
                    << " is inavlid for stylesheet: "
                    << testCase.stylesheet
                    << endl;
        }

        m_reporter->addMetricToAttrs("compile-xsl", timeCompile.getElapsedTime(), testAttributes);

        long numIterations = 0;

        long totalParseInputTime = 0;
        long minParseInputTime = LONG_MAX;
        long maxParseInputTime = 0 ;

        long totalTransformTime = 0;
        long minTransformTime = LONG_MAX;
        long maxTransformTime = 0;

        Timer timeTotalRun;
        timeTotalRun.start();

        while (numIterations < testCase.numIterations
            && timeTotalRun.getElapsedTime() < testCase.minTimeToExecute)
        {
            Timer timeInput;
            if (testCase.inputMode == XalanDOMString("stream"))
            {
#if defined(XALAN_CLASSIC_IOSTREAMS)
                XALAN_USING_XALAN(CharVectorType)
                XALAN_USING_XALAN(c_str)

                XALAN_USING_STD(istringstream)

                CharVectorType  buffer;
                fileToStream(testCase.inputDocument, buffer);

                istrstream      inputStream(c_str(buffer));
#else
                XALAN_USING_STD(istringstream)

                istringstream inputStream;
                fileToStream(testCase.inputDocument, inputStream);
#endif

                timeInput.start();
                parsedInputSource = m_processor.parseInputSource(
                        inputStream,
                        processor.parseOptions);
                timeInput.stop();
            }
            else if (testCase.inputMode == XalanDOMString("file"))
            {
                timeInput.start();
                parsedInputSource = m_processor.parseInputSource(
                        testCase.inputDocument,
                        processor.parseOptions);
                timeInput.stop();
            }
            else
            {
                m_logger->error()
                    << "Mode: "
                    << testCase.inputMode.c_str()
                    << " is inavlid for input document: "
                    << testCase.inputDocument
                    << endl;
            }

            totalParseInputTime += timeInput.getElapsedTime();
            minParseInputTime = timeInput.getElapsedTime() < minParseInputTime ? timeInput.getElapsedTime() : minParseInputTime;
            maxParseInputTime = timeInput.getElapsedTime() > maxParseInputTime ? timeInput.getElapsedTime() : maxParseInputTime;

            resultTarget = m_processor.createResultTarget(
                    testCase.resultDocument,
                    processor.resultOptions);

            Timer timeTransform;
            timeTransform.start();
            m_processor.transform(
                    compiledStylesheet,
                    parsedInputSource,
                    resultTarget);
            timeTransform.stop();

            totalTransformTime += timeTransform.getElapsedTime();
            minTransformTime = timeTransform.getElapsedTime() < minTransformTime ? timeTransform.getElapsedTime() : minTransformTime;
            maxTransformTime = timeTransform.getElapsedTime() > maxTransformTime ? timeTransform.getElapsedTime() : maxTransformTime;

            ++numIterations;
        }

        timeTotalRun.stop();

        m_processor.releaseStylesheet(compiledStylesheet);
        m_processor.releaseInputSource(parsedInputSource);
        m_processor.releaseResultTarget(resultTarget);

        if (true == testCase.verifyResult)
        {
            testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("yes")));
            if (checkFileExists(testCase.resultDocument))
            {
                if (checkFileExists(testCase.goldResult))
                {
                    if (m_fileUtility->compareSerializedResults(
                            testCase.resultDocument,
                            testCase.goldResult))
                    {
                        testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("pass")));
                    }
                    else
                    {
                        testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("fail")));
                    }
                }
                else
                {
                    testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
                }
            }
            else
            {
                testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
            }
        }
        else
        {
            testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("no")));
        }

        m_reporter->addMetricToAttrs("num-iterations", numIterations, testAttributes);
        m_reporter->addMetricToAttrs("elapsed-time", timeTotalRun.getElapsedTime(), testAttributes);
        m_reporter->addMetricToAttrs("min-parse-input", minParseInputTime, testAttributes);
        m_reporter->addMetricToAttrs("max-parse-input", maxParseInputTime, testAttributes);
        m_reporter->addMetricToAttrs("avg-parse-input", totalParseInputTime / numIterations, testAttributes);
        m_reporter->addMetricToAttrs("min-transform", minTransformTime, testAttributes);
        m_reporter->addMetricToAttrs("max-transform", maxTransformTime, testAttributes);
        m_reporter->addMetricToAttrs("avg-transform", totalTransformTime / numIterations, testAttributes);

        testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("yes")));

    }
    catch (XalanDOMString exception)
    {
        m_logger->error()
                << "Error encountered during transformation: "
                << testCase.stylesheet.c_str()
                << ", error: "
                << exception.c_str()
                << endl;

        testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("no")));
    }

    m_reporter->logElementWAttrs(1, "testcase", testAttributes, "");
}

template <class Processor>
TestHarness<Processor>::TestHarness()
{

}

template <class Processor>
void
TestHarness<Processor>::init(
        XalanFileUtility&       fileUtility,
        XalanXMLFileReporter&   reporter,
        Logger&                 logger)
{
    m_processor.init();

    m_fileUtility = &fileUtility;

    m_reporter = &reporter;

    m_logger = &logger;
}

template <class Processor>
void
TestHarness<Processor>::terminate()
{
   m_processor.terminate();
}

#endif // TESTHARNESS_HEADER_GUARD_1357924680
<commit_msg>Patch for Jira issue XALANC-660.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the  "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#if !defined(TESTHARNESS_HEADER_GUARD_1357924680)
#define TESTHARNESS_HEADER_GUARD_1357924680

// Base header file.  Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>

#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <fstream.h>
#else
#include <fstream>
#endif

#include <xalanc/Include/XalanMemoryManagement.hpp>
#include <xalanc/Include/XalanVector.hpp>
#include <xalanc/Include/XalanMap.hpp>

#include <xalanc/PlatformSupport/DOMStringHelper.hpp>

#include <xalanc/XalanDOM/XalanNode.hpp>
#include <xalanc/XalanDOM/XalanDOMString.hpp>

#include <xalanc/Harness/XalanFileUtility.hpp>
#include <xalanc/Harness/XalanXMLFileReporter.hpp>

#include "Utils.hpp"
#include "Logger.hpp"
#include "Timer.hpp"

XALAN_USING_XALAN(XalanMemMgrs)
XALAN_USING_XALAN(XalanVector)
XALAN_USING_XALAN(XalanMap)
XALAN_USING_XALAN(XalanNode)
XALAN_USING_XALAN(XalanDOMString)
XALAN_USING_XALAN(XalanFileUtility)
XALAN_USING_XALAN(XalanXMLFileReporter)

/**
 * Processor interface options
 */
struct ProcessorOptions
{
    XalanNode*  initOptions;
    XalanNode*  compileOptions;
    XalanNode*  parseOptions;
    XalanNode*  resultOptions;
    XalanNode*  transformOptions;

    ProcessorOptions() :
            initOptions(0),
            compileOptions(0),
            parseOptions(0),
            resultOptions(0),
            transformOptions(0)
    {
    }
};

/**
 * Test case
 */
class TestCase
{
public:

    TestCase();

    TestCase(const TestCase& theRhs);

    XalanDOMString  stylesheet;
    XalanDOMString  inputDocument;
    XalanDOMString  resultDocument;
    XalanDOMString  resultDirectory;
    XalanDOMString  goldResult;
    long            numIterations;
    long            minTimeToExecute;
    bool            verifyResult;
    XalanDOMString  inputMode;

    typedef XalanMap<XalanDOMString, ProcessorOptions>  ProcessorOptionsMap;

    ProcessorOptionsMap processorOptions;
};

typedef TestCase                    TestCaseType;
typedef XalanVector<TestCaseType>   TestCasesType;

/**
 *  Test harness
 */
template <class Processor>
class TestHarness
{
public:

    typedef typename Processor::CompiledStylesheetType  CompiledStylesheetType;
    typedef typename Processor::ParsedInputSourceType   ParsedInputSourceType;
    typedef typename Processor::ResultTargetType        ResultTargetType;

    typedef typename XalanXMLFileReporter::Hashtable    TestAttributesType;

    TestHarness();

    void init(
            XalanFileUtility&       fileUtility,
            XalanXMLFileReporter&   reporter,
            Logger&                 logger);

    void terminate();

    void executeTestCase(const TestCaseType& testCase);

    void executeTestCases(const TestCasesType& testCases);

protected:

    Processor m_processor;

    XalanFileUtility*       m_fileUtility;

    XalanXMLFileReporter*   m_reporter;

    Logger*                 m_logger;
};

template <class Processor>
void
TestHarness<Processor>::executeTestCases(const TestCasesType& testCases)
{
    TestCasesType::const_iterator testCaseIter = testCases.begin();
    while (testCaseIter != testCases.end())
    {
        executeTestCase(*testCaseIter);
        ++testCaseIter;
    }
}

template <class Processor>
void
TestHarness<Processor>::executeTestCase(const TestCaseType& testCase)
{
    TestAttributesType testAttributes(XalanMemMgrs::getDefaultXercesMemMgr());

    testAttributes.insert(TestAttributesType::value_type(XalanDOMString("stylesheet"), testCase.stylesheet));
    testAttributes.insert(TestAttributesType::value_type(XalanDOMString("input-document"), testCase.inputDocument));

    try {

        CompiledStylesheetType  compiledStylesheet;
        ParsedInputSourceType   parsedInputSource;
        ResultTargetType        resultTarget;

        static const ProcessorOptions defaultProcessor;

        TestCase::ProcessorOptionsMap::const_iterator iter = testCase.processorOptions.find(m_processor.getName());

        const ProcessorOptions&  processor = iter != testCase.processorOptions.end() ? iter->second : defaultProcessor;

        m_fileUtility->checkAndCreateDir(testCase.resultDirectory);

        Timer timeCompile;

        if (testCase.inputMode == XalanDOMString("stream"))
        {
#if defined(XALAN_CLASSIC_IOSTREAMS)
            XALAN_USING_XALAN(CharVectorType)
            XALAN_USING_XALAN(c_str)

            XALAN_USING_STD(istringstream)

            CharVectorType  buffer;
            fileToStream(testCase.stylesheet, buffer);

            istrstream      compilerStream(c_str(buffer));
#else
            XALAN_USING_STD(istringstream)

            istringstream compilerStream;
            fileToStream(testCase.stylesheet, compilerStream);
#endif
            timeCompile.start();
            compiledStylesheet = m_processor.compileStylesheet(
                    compilerStream,
                    processor.compileOptions);
            timeCompile.stop();
        }
        else if (testCase.inputMode == XalanDOMString("file"))
        {
            timeCompile.start();
            compiledStylesheet = m_processor.compileStylesheet(
                    testCase.stylesheet,
                    processor.compileOptions);
            timeCompile.stop();
        }
        else
        {
            XALAN_USING_STD(endl)

            m_logger->error()
                    << "Mode: "
                    << testCase.inputMode.c_str()
                    << " is inavlid for stylesheet: "
                    << testCase.stylesheet
                    << endl;
        }

        m_reporter->addMetricToAttrs("compile-xsl", timeCompile.getElapsedTime(), testAttributes);

        long numIterations = 0;

        long totalParseInputTime = 0;
        long minParseInputTime = LONG_MAX;
        long maxParseInputTime = 0 ;

        long totalTransformTime = 0;
        long minTransformTime = LONG_MAX;
        long maxTransformTime = 0;

        Timer timeTotalRun;
        timeTotalRun.start();

        while (numIterations < testCase.numIterations
            && timeTotalRun.getElapsedTime() < testCase.minTimeToExecute)
        {
            Timer timeInput;
            if (testCase.inputMode == XalanDOMString("stream"))
            {
#if defined(XALAN_CLASSIC_IOSTREAMS)
                XALAN_USING_XALAN(CharVectorType)
                XALAN_USING_XALAN(c_str)

                XALAN_USING_STD(istringstream)

                CharVectorType  buffer;
                fileToStream(testCase.inputDocument, buffer);

                istrstream      inputStream(c_str(buffer));
#else
                XALAN_USING_STD(istringstream)

                istringstream inputStream;
                fileToStream(testCase.inputDocument, inputStream);
#endif

                timeInput.start();
                parsedInputSource = m_processor.parseInputSource(
                        inputStream,
                        processor.parseOptions);
                timeInput.stop();
            }
            else if (testCase.inputMode == XalanDOMString("file"))
            {
                timeInput.start();
                parsedInputSource = m_processor.parseInputSource(
                        testCase.inputDocument,
                        processor.parseOptions);
                timeInput.stop();
            }
            else
            {
                XALAN_USING_STD(endl)

                m_logger->error()
                    << "Mode: "
                    << testCase.inputMode.c_str()
                    << " is inavlid for input document: "
                    << testCase.inputDocument
                    << endl;
            }

            totalParseInputTime += timeInput.getElapsedTime();
            minParseInputTime = timeInput.getElapsedTime() < minParseInputTime ? timeInput.getElapsedTime() : minParseInputTime;
            maxParseInputTime = timeInput.getElapsedTime() > maxParseInputTime ? timeInput.getElapsedTime() : maxParseInputTime;

            resultTarget = m_processor.createResultTarget(
                    testCase.resultDocument,
                    processor.resultOptions);

            Timer timeTransform;
            timeTransform.start();
            m_processor.transform(
                    compiledStylesheet,
                    parsedInputSource,
                    resultTarget);
            timeTransform.stop();

            totalTransformTime += timeTransform.getElapsedTime();
            minTransformTime = timeTransform.getElapsedTime() < minTransformTime ? timeTransform.getElapsedTime() : minTransformTime;
            maxTransformTime = timeTransform.getElapsedTime() > maxTransformTime ? timeTransform.getElapsedTime() : maxTransformTime;

            ++numIterations;
        }

        timeTotalRun.stop();

        m_processor.releaseStylesheet(compiledStylesheet);
        m_processor.releaseInputSource(parsedInputSource);
        m_processor.releaseResultTarget(resultTarget);

        if (true == testCase.verifyResult)
        {
            testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("yes")));
            if (checkFileExists(testCase.resultDocument))
            {
                if (checkFileExists(testCase.goldResult))
                {
                    if (m_fileUtility->compareSerializedResults(
                            testCase.resultDocument,
                            testCase.goldResult))
                    {
                        testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("pass")));
                    }
                    else
                    {
                        testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("fail")));
                    }
                }
                else
                {
                    testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
                }
            }
            else
            {
                testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
            }
        }
        else
        {
            testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("no")));
        }

        m_reporter->addMetricToAttrs("num-iterations", numIterations, testAttributes);
        m_reporter->addMetricToAttrs("elapsed-time", timeTotalRun.getElapsedTime(), testAttributes);
        m_reporter->addMetricToAttrs("min-parse-input", minParseInputTime, testAttributes);
        m_reporter->addMetricToAttrs("max-parse-input", maxParseInputTime, testAttributes);
        m_reporter->addMetricToAttrs("avg-parse-input", totalParseInputTime / numIterations, testAttributes);
        m_reporter->addMetricToAttrs("min-transform", minTransformTime, testAttributes);
        m_reporter->addMetricToAttrs("max-transform", maxTransformTime, testAttributes);
        m_reporter->addMetricToAttrs("avg-transform", totalTransformTime / numIterations, testAttributes);

        testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("yes")));

    }
    catch (const XalanDOMString& exception)
    {
        XALAN_USING_STD(endl)

        m_logger->error()
                << "Error encountered during transformation: "
                << testCase.stylesheet.c_str()
                << ", error: "
                << exception.c_str()
                << endl;

        testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("no")));
    }

    m_reporter->logElementWAttrs(1, "testcase", testAttributes, "");
}

template <class Processor>
TestHarness<Processor>::TestHarness()
{

}

template <class Processor>
void
TestHarness<Processor>::init(
        XalanFileUtility&       fileUtility,
        XalanXMLFileReporter&   reporter,
        Logger&                 logger)
{
    m_processor.init();

    m_fileUtility = &fileUtility;

    m_reporter = &reporter;

    m_logger = &logger;
}

template <class Processor>
void
TestHarness<Processor>::terminate()
{
   m_processor.terminate();
}

#endif // TESTHARNESS_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before>/*
* Copyright 2008, 2009, 2010 Free Software Foundation, Inc.
* Copyright 2010 Kestrel Signal Processing, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "Transceiver.h"
#include "radioDevice.h"
#include "DummyLoad.h"

#include <time.h>
#include <signal.h>

#include <GSMCommon.h>
#include <Logger.h>
#include <Configuration.h>

#ifdef RESAMPLE
  #define DEVICERATE 400e3
#else
  #define DEVICERATE 1625e3/6
#endif

using namespace std;

ConfigurationTable gConfig("/etc/OpenBTS/OpenBTS.db");

volatile bool gbShutdown = false;
static void ctrlCHandler(int signo)
{
   cout << "Received shutdown signal" << endl;;
   gbShutdown = true;
}

int main(int argc, char *argv[])
{
  std::string deviceArgs;

  if (argc == 3)
  {
    deviceArgs = std::string(argv[2]);
  }
  else
  {
    deviceArgs = "";
  }

  if ( signal( SIGINT, ctrlCHandler ) == SIG_ERR )
  {
    cerr << "Couldn't install signal handler for SIGINT" << endl;
    exit(1);
  }

  if ( signal( SIGTERM, ctrlCHandler ) == SIG_ERR )
  {
    cerr << "Couldn't install signal handler for SIGTERM" << endl;
    exit(1);
  }
  // Configure logger.
  gLogInit("transceiver",gConfig.getStr("Log.Level").c_str(),LOG_LOCAL7);

  int numARFCN=1;

  LOG(NOTICE) << "starting transceiver with " << numARFCN << " ARFCNs (argc=" << argc << ")";

  srandom(time(NULL));

  int mOversamplingRate = numARFCN/2 + numARFCN;
  RadioDevice *usrp = RadioDevice::make(DEVICERATE * SAMPSPERSYM);
  if (!usrp->open(deviceArgs)) {
    LOG(ALERT) << "Transceiver exiting..." << std::endl;
    return EXIT_FAILURE;
  }

  RadioInterface* radio = new RadioInterface(usrp,3,SAMPSPERSYM,mOversamplingRate,false);
  Transceiver *trx = new Transceiver(5700,"127.0.0.1",SAMPSPERSYM,GSM::Time(3,0),radio);
  trx->receiveFIFO(radio->receiveFIFO());
/*
  signalVector *gsmPulse = generateGSMPulse(2,1);
  BitVector normalBurstSeg = "0000101010100111110010101010010110101110011000111001101010000";
  BitVector normalBurst(BitVector(normalBurstSeg,gTrainingSequence[0]),normalBurstSeg);
  signalVector *modBurst = modulateBurst(normalBurst,*gsmPulse,8,1);
  signalVector *modBurst9 = modulateBurst(normalBurst,*gsmPulse,9,1);
  signalVector *interpolationFilter = createLPF(0.6/mOversamplingRate,6*mOversamplingRate,1);
  signalVector totalBurst1(*modBurst,*modBurst9);
  signalVector totalBurst2(*modBurst,*modBurst);
  signalVector totalBurst(totalBurst1,totalBurst2);
  scaleVector(totalBurst,usrp->fullScaleInputValue());
  double beaconFreq = -1.0*(numARFCN-1)*200e3;
  signalVector finalVec(625*mOversamplingRate);
  for (int j = 0; j < numARFCN; j++) {
	signalVector *frequencyShifter = new signalVector(625*mOversamplingRate);
	frequencyShifter->fill(1.0);
	frequencyShift(frequencyShifter,frequencyShifter,2.0*M_PI*(beaconFreq+j*400e3)/(1625.0e3/6.0*mOversamplingRate));
  	signalVector *interpVec = polyphaseResampleVector(totalBurst,mOversamplingRate,1,interpolationFilter);
	multVector(*interpVec,*frequencyShifter);
	addVector(finalVec,*interpVec);
  }
  signalVector::iterator itr = finalVec.begin();
  short finalVecShort[2*finalVec.size()];
  short *shortItr = finalVecShort;
  while (itr < finalVec.end()) {
	*shortItr++ = (short) (itr->real());
	*shortItr++ = (short) (itr->imag());
	itr++;
  }
  usrp->loadBurst(finalVecShort,finalVec.size());
*/
  trx->start();
  //int i = 0;
  while(!gbShutdown) { sleep(1); }//i++; if (i==60) break;}

  cout << "Shutting down transceiver..." << endl;

//  trx->stop();
  delete trx;
//  delete radio;
}
<commit_msg>Transceiver52M: Read IP address and port to bind to from a configuration instead of hardcoding them.<commit_after>/*
* Copyright 2008, 2009, 2010 Free Software Foundation, Inc.
* Copyright 2010 Kestrel Signal Processing, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "Transceiver.h"
#include "radioDevice.h"
#include "DummyLoad.h"

#include <time.h>
#include <signal.h>

#include <GSMCommon.h>
#include <Logger.h>
#include <Configuration.h>

#ifdef RESAMPLE
  #define DEVICERATE 400e3
#else
  #define DEVICERATE 1625e3/6
#endif

using namespace std;

ConfigurationTable gConfig("/etc/OpenBTS/OpenBTS.db");

volatile bool gbShutdown = false;
static void ctrlCHandler(int signo)
{
   cout << "Received shutdown signal" << endl;;
   gbShutdown = true;
}

int main(int argc, char *argv[])
{
  std::string deviceArgs;

  if (argc == 3)
  {
    deviceArgs = std::string(argv[2]);
  }
  else
  {
    deviceArgs = "";
  }

  if ( signal( SIGINT, ctrlCHandler ) == SIG_ERR )
  {
    cerr << "Couldn't install signal handler for SIGINT" << endl;
    exit(1);
  }

  if ( signal( SIGTERM, ctrlCHandler ) == SIG_ERR )
  {
    cerr << "Couldn't install signal handler for SIGTERM" << endl;
    exit(1);
  }
  // Configure logger.
  gLogInit("transceiver",gConfig.getStr("Log.Level").c_str(),LOG_LOCAL7);

  int numARFCN=1;

  LOG(NOTICE) << "starting transceiver with " << numARFCN << " ARFCNs (argc=" << argc << ")";

  srandom(time(NULL));

  int mOversamplingRate = numARFCN/2 + numARFCN;
  RadioDevice *usrp = RadioDevice::make(DEVICERATE * SAMPSPERSYM);
  if (!usrp->open(deviceArgs)) {
    LOG(ALERT) << "Transceiver exiting..." << std::endl;
    return EXIT_FAILURE;
  }

  RadioInterface* radio = new RadioInterface(usrp,3,SAMPSPERSYM,mOversamplingRate,false);
  Transceiver *trx = new Transceiver(gConfig.getNum("TRX.Port"),gConfig.getStr("TRX.IP").c_str(),SAMPSPERSYM,GSM::Time(3,0),radio);
  trx->receiveFIFO(radio->receiveFIFO());
/*
  signalVector *gsmPulse = generateGSMPulse(2,1);
  BitVector normalBurstSeg = "0000101010100111110010101010010110101110011000111001101010000";
  BitVector normalBurst(BitVector(normalBurstSeg,gTrainingSequence[0]),normalBurstSeg);
  signalVector *modBurst = modulateBurst(normalBurst,*gsmPulse,8,1);
  signalVector *modBurst9 = modulateBurst(normalBurst,*gsmPulse,9,1);
  signalVector *interpolationFilter = createLPF(0.6/mOversamplingRate,6*mOversamplingRate,1);
  signalVector totalBurst1(*modBurst,*modBurst9);
  signalVector totalBurst2(*modBurst,*modBurst);
  signalVector totalBurst(totalBurst1,totalBurst2);
  scaleVector(totalBurst,usrp->fullScaleInputValue());
  double beaconFreq = -1.0*(numARFCN-1)*200e3;
  signalVector finalVec(625*mOversamplingRate);
  for (int j = 0; j < numARFCN; j++) {
	signalVector *frequencyShifter = new signalVector(625*mOversamplingRate);
	frequencyShifter->fill(1.0);
	frequencyShift(frequencyShifter,frequencyShifter,2.0*M_PI*(beaconFreq+j*400e3)/(1625.0e3/6.0*mOversamplingRate));
  	signalVector *interpVec = polyphaseResampleVector(totalBurst,mOversamplingRate,1,interpolationFilter);
	multVector(*interpVec,*frequencyShifter);
	addVector(finalVec,*interpVec);
  }
  signalVector::iterator itr = finalVec.begin();
  short finalVecShort[2*finalVec.size()];
  short *shortItr = finalVecShort;
  while (itr < finalVec.end()) {
	*shortItr++ = (short) (itr->real());
	*shortItr++ = (short) (itr->imag());
	itr++;
  }
  usrp->loadBurst(finalVecShort,finalVec.size());
*/
  trx->start();
  //int i = 0;
  while(!gbShutdown) { sleep(1); }//i++; if (i==60) break;}

  cout << "Shutting down transceiver..." << endl;

//  trx->stop();
  delete trx;
//  delete radio;
}
<|endoftext|>


<commit_before>/*****************************************************************************
 * standardpanel.cpp : The "standard" playlist panel : just a treeview
 ****************************************************************************
 * Copyright (C) 2000-2005 the VideoLAN team
 * $Id$
 *
 * Authors: Clément Stenac <zorglub@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#include "qt4.hpp"
#include "dialogs_provider.hpp"
#include "playlist_model.hpp"
#include "components/playlist/panels.hpp"
#include "util/customwidgets.hpp"

#include <vlc_intf_strings.h>

#include <QTreeView>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QHeaderView>
#include <QKeyEvent>
#include <QModelIndexList>
#include <QToolBar>
#include <QLabel>
#include <QSpacerItem>
#include <QMenu>

#include <assert.h>

StandardPLPanel::StandardPLPanel( PlaylistWidget *_parent,
                                  intf_thread_t *_p_intf,
                                  playlist_t *p_playlist,
                                  playlist_item_t *p_root ):
                                  PLPanel( _parent, _p_intf )
{
    model = new PLModel( p_playlist, p_intf, p_root, -1, this );

    /* Create and configure the QTreeView */
    view = new QVLCTreeView( 0 );
    view->setModel(model);
    view->setIconSize( QSize(20,20) );
    view->setAlternatingRowColors( true );
    view->setAnimated( true );
    view->setSortingEnabled( true );
    view->setSelectionMode( QAbstractItemView::ExtendedSelection );
    view->setDragEnabled( true );
    view->setAcceptDrops( true );
    view->setDropIndicatorShown( true );
    view->setAutoScroll( true );

    view->header()->resizeSection( 0, 230 );
    view->header()->resizeSection( 1, 170 );
    view->header()->setSortIndicatorShown( true );
    view->header()->setClickable( true );
    view->header()->setContextMenuPolicy( Qt::CustomContextMenu );

    CONNECT( view, activated( const QModelIndex& ) ,
             model,activateItem( const QModelIndex& ) );
    CONNECT( view, rightClicked( QModelIndex , QPoint ),
             this, doPopup( QModelIndex, QPoint ) );
    CONNECT( model, dataChanged( const QModelIndex&, const QModelIndex& ),
             this, handleExpansion( const QModelIndex& ) );
    CONNECT( view->header(), customContextMenuRequested( const QPoint & ),
             this, popupSelectColumn( QPoint ) );

    currentRootId = -1;
    CONNECT( parent, rootChanged(int), this, setCurrentRootId( int ) );

    QVBoxLayout *layout = new QVBoxLayout();
    layout->setSpacing( 0 ); layout->setMargin( 0 );

    /* Buttons configuration */
    QHBoxLayout *buttons = new QHBoxLayout();

    addButton = new QPushButton( QIcon( ":/pixmaps/playlist_add.png" ), "", this );
    addButton->setMaximumWidth( 25 );
    BUTTONACT( addButton, popupAdd() );
    buttons->addWidget( addButton );

    randomButton = new QPushButton( this );
    if( model->hasRandom() )
    {
        randomButton->setIcon( QIcon( ":/pixmaps/playlist_shuffle_on.png" ));
        randomButton->setToolTip( qtr( I_PL_RANDOM ));
    }
    else
    {
         randomButton->setIcon( QIcon( ":/pixmaps/playlist_shuffle_off.png" ) );
         randomButton->setToolTip( qtr( I_PL_NORANDOM ));
    }
    BUTTONACT( randomButton, toggleRandom() );
    buttons->addWidget( randomButton );

    QSpacerItem *spacer = new QSpacerItem( 10, 20 );
    buttons->addItem( spacer );

    repeatButton = new QPushButton( this );
    if( model->hasRepeat() )
    {
        repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_one.png" ) );
        repeatButton->setToolTip( qtr( I_PL_REPEAT ));
    }
    else if( model->hasLoop() )
    {
        repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_all.png" ) );
        repeatButton->setToolTip( qtr( I_PL_LOOP ));
    }
    else
    {
        repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_off.png" ) );
        repeatButton->setToolTip( qtr( I_PL_NOREPEAT ));
    }
    BUTTONACT( repeatButton, toggleRepeat() );
    buttons->addWidget( repeatButton );

    QLabel *filter = new QLabel( qtr(I_PL_SEARCH) + " " );
    buttons->addWidget( filter );
    searchLine = new  ClickLineEdit( qtr(I_PL_FILTER), 0 );
    CONNECT( searchLine, textChanged(QString), this, search(QString));
    buttons->addWidget( searchLine ); filter->setBuddy( searchLine );

    QPushButton *clear = new QPushButton( qfu( "CL") );
    clear->setMaximumWidth( 30 );
    clear->setToolTip( qtr( "Clear" ));
    BUTTONACT( clear, clearFilter() );
    buttons->addWidget( clear );

    layout->addWidget( view );
    layout->addLayout( buttons );
//    layout->addWidget( bar );
    setLayout( layout );
}

void StandardPLPanel::toggleRepeat()
{
    if( model->hasRepeat() )
    {
        model->setRepeat( false ); model->setLoop( true );
        repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_all.png" ) );
        repeatButton->setToolTip( qtr( I_PL_LOOP ));
    }
    else if( model->hasLoop() )
    {
        model->setRepeat( false ) ; model->setLoop( false );
        repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_off.png" ) );
        repeatButton->setToolTip( qtr( I_PL_NOREPEAT ));
    }
    else
    {
        model->setRepeat( true );
        repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_one.png" ) );
        repeatButton->setToolTip( qtr( I_PL_REPEAT ));
    }
}

void StandardPLPanel::toggleRandom()
{
    bool prev = model->hasRandom();
    model->setRandom( !prev );
    randomButton->setIcon( prev ?
                QIcon( ":/pixmaps/playlist_shuffle_off.png" ) :
                QIcon( ":/pixmaps/playlist_shuffle_on.png" ) );
    randomButton->setToolTip( prev ? qtr( I_PL_NORANDOM ) : qtr(I_PL_RANDOM ) );
}

void StandardPLPanel::handleExpansion( const QModelIndex &index )
{
    if( model->isCurrent( index ) )
        view->scrollTo( index, QAbstractItemView::EnsureVisible );
}

void StandardPLPanel::setCurrentRootId( int _new )
{
    currentRootId = _new;
    if( currentRootId == THEPL->p_local_category->i_id ||
        currentRootId == THEPL->p_local_onelevel->i_id  )
    {
        addButton->setEnabled( true );
        addButton->setToolTip( qtr(I_PL_ADDPL) );
    }
    else if( ( THEPL->p_ml_category &&
                        currentRootId == THEPL->p_ml_category->i_id ) ||
             ( THEPL->p_ml_onelevel &&
                        currentRootId == THEPL->p_ml_onelevel->i_id ) )
    {
        addButton->setEnabled( true );
        addButton->setToolTip( qtr(I_PL_ADDML) );
    }
    else
        addButton->setEnabled( false );
}

void StandardPLPanel::popupAdd()
{
    QMenu popup;
    if( currentRootId == THEPL->p_local_category->i_id ||
        currentRootId == THEPL->p_local_onelevel->i_id )
    {
        popup.addAction( qtr(I_PL_ADDF), THEDP, SLOT(simplePLAppendDialog()));
        popup.addAction( qtr(I_PL_ADVADD), THEDP, SLOT(PLAppendDialog()) );
        popup.addAction( qtr(I_PL_ADDDIR), THEDP, SLOT( PLAppendDir()) );
    }
    else if( ( THEPL->p_ml_category &&
                currentRootId == THEPL->p_ml_category->i_id ) ||
             ( THEPL->p_ml_onelevel &&
                currentRootId == THEPL->p_ml_onelevel->i_id ) )
    {
        popup.addAction( qtr(I_PL_ADDF), THEDP, SLOT(simpleMLAppendDialog()));
        popup.addAction( qtr(I_PL_ADVADD), THEDP, SLOT( MLAppendDialog() ) );
        popup.addAction( qtr(I_PL_ADDDIR), THEDP, SLOT( MLAppendDir() ) );
    }
    popup.exec( QCursor::pos() );
}

void StandardPLPanel::popupSelectColumn( QPoint )
{
    ContextUpdateMapper = new QSignalMapper(this);

    QMenu selectColMenu;

#define ADD_META_ACTION( meta ) { \
   QAction* option = selectColMenu.addAction( qfu(VLC_META_##meta) );     \
   option->setCheckable( true );                                           \
   option->setChecked( model->shownFlags() & VLC_META_ENGINE_##meta );   \
   ContextUpdateMapper->setMapping( option, VLC_META_ENGINE_##meta );      \
   CONNECT( option, triggered(), ContextUpdateMapper, map() );             \
   }
    CONNECT( ContextUpdateMapper, mapped( int ),  model, viewchanged( int ) );

    ADD_META_ACTION( TITLE );
    ADD_META_ACTION( ARTIST );
    ADD_META_ACTION( DURATION );
    ADD_META_ACTION( COLLECTION );
    ADD_META_ACTION( GENRE );
    ADD_META_ACTION( SEQ_NUM );
    ADD_META_ACTION( RATING );
    ADD_META_ACTION( DESCRIPTION );

#undef ADD_META_ACTION

    selectColMenu.exec( QCursor::pos() );
 }

void StandardPLPanel::clearFilter()
{
    searchLine->setText( "" );
}

void StandardPLPanel::search( QString searchText )
{
    model->search( searchText );
}

void StandardPLPanel::doPopup( QModelIndex index, QPoint point )
{
    if( !index.isValid() ) return;
    QItemSelectionModel *selection = view->selectionModel();
    QModelIndexList list = selection->selectedIndexes();
    model->popup( index, point, list );
}

void StandardPLPanel::setRoot( int i_root_id )
{
    playlist_item_t *p_item = playlist_ItemGetById( THEPL, i_root_id,
                                                    VLC_TRUE );
    assert( p_item );
    p_item = playlist_GetPreferredNode( THEPL, p_item );
    assert( p_item );
    model->rebuild( p_item );
}

void StandardPLPanel::removeItem( int i_id )
{
    model->removeItem( i_id );
}

void StandardPLPanel::keyPressEvent( QKeyEvent *e )
{
    switch( e->key() )
    {
    case Qt::Key_Back:
    case Qt::Key_Delete:
        deleteSelection();
        break;
    }
}

void StandardPLPanel::deleteSelection()
{
    QItemSelectionModel *selection = view->selectionModel();
    QModelIndexList list = selection->selectedIndexes();
    model->doDelete( list );
}

StandardPLPanel::~StandardPLPanel()
{}
<commit_msg>Qt4 - small cosmetic for the playlist.<commit_after>/*****************************************************************************
 * standardpanel.cpp : The "standard" playlist panel : just a treeview
 ****************************************************************************
 * Copyright (C) 2000-2005 the VideoLAN team
 * $Id$
 *
 * Authors: Clément Stenac <zorglub@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#include "qt4.hpp"
#include "dialogs_provider.hpp"
#include "playlist_model.hpp"
#include "components/playlist/panels.hpp"
#include "util/customwidgets.hpp"

#include <vlc_intf_strings.h>

#include <QTreeView>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QHeaderView>
#include <QKeyEvent>
#include <QModelIndexList>
#include <QToolBar>
#include <QLabel>
#include <QSpacerItem>
#include <QMenu>

#include <assert.h>

StandardPLPanel::StandardPLPanel( PlaylistWidget *_parent,
                                  intf_thread_t *_p_intf,
                                  playlist_t *p_playlist,
                                  playlist_item_t *p_root ):
                                  PLPanel( _parent, _p_intf )
{
    model = new PLModel( p_playlist, p_intf, p_root, -1, this );

    QVBoxLayout *layout = new QVBoxLayout();
    layout->setSpacing( 0 ); layout->setMargin( 0 );

    /* Create and configure the QTreeView */
    view = new QVLCTreeView( 0 );
    view->setModel(model);
    view->setIconSize( QSize( 20, 20 ) );
    view->setAlternatingRowColors( true );
    view->setAnimated( true );
    view->setSortingEnabled( true );
    view->setSelectionMode( QAbstractItemView::ExtendedSelection );
    view->setDragEnabled( true );
    view->setAcceptDrops( true );
    view->setDropIndicatorShown( true );
    view->setAutoScroll( true );

    view->header()->resizeSection( 0, 230 );
    view->header()->resizeSection( 1, 80 );
    view->header()->setSortIndicatorShown( true );
    view->header()->setClickable( true );
    view->header()->setContextMenuPolicy( Qt::CustomContextMenu );

    CONNECT( view, activated( const QModelIndex& ) ,
             model,activateItem( const QModelIndex& ) );
    CONNECT( view, rightClicked( QModelIndex , QPoint ),
             this, doPopup( QModelIndex, QPoint ) );
    CONNECT( model, dataChanged( const QModelIndex&, const QModelIndex& ),
             this, handleExpansion( const QModelIndex& ) );
    CONNECT( view->header(), customContextMenuRequested( const QPoint & ),
             this, popupSelectColumn( QPoint ) );

    currentRootId = -1;
    CONNECT( parent, rootChanged( int ), this, setCurrentRootId( int ) );

    /* Buttons configuration */
    QHBoxLayout *buttons = new QHBoxLayout;

    addButton = new QPushButton( QIcon( ":/pixmaps/playlist_add.png" ), "", this );
    addButton->setMaximumWidth( 25 );
    BUTTONACT( addButton, popupAdd() );
    buttons->addWidget( addButton );

    randomButton = new QPushButton( this );
    if( model->hasRandom() )
    {
        randomButton->setIcon( QIcon( ":/pixmaps/playlist_shuffle_on.png" ));
        randomButton->setToolTip( qtr( I_PL_RANDOM ));
    }
    else
    {
         randomButton->setIcon( QIcon( ":/pixmaps/playlist_shuffle_off.png" ) );
         randomButton->setToolTip( qtr( I_PL_NORANDOM ));
    }
    BUTTONACT( randomButton, toggleRandom() );
    buttons->addWidget( randomButton );

    QSpacerItem *spacer = new QSpacerItem( 10, 20 );
    buttons->addItem( spacer );

    repeatButton = new QPushButton( this );
    if( model->hasRepeat() )
    {
        repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_one.png" ) );
        repeatButton->setToolTip( qtr( I_PL_REPEAT ));
    }
    else if( model->hasLoop() )
    {
        repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_all.png" ) );
        repeatButton->setToolTip( qtr( I_PL_LOOP ));
    }
    else
    {
        repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_off.png" ) );
        repeatButton->setToolTip( qtr( I_PL_NOREPEAT ));
    }
    BUTTONACT( repeatButton, toggleRepeat() );
    buttons->addWidget( repeatButton );

    QLabel *filter = new QLabel( qtr(I_PL_SEARCH) + " " );
    buttons->addWidget( filter );
    searchLine = new  ClickLineEdit( qtr(I_PL_FILTER), 0 );
    CONNECT( searchLine, textChanged(QString), this, search(QString));
    buttons->addWidget( searchLine ); filter->setBuddy( searchLine );

    QPushButton *clear = new QPushButton( qfu( "CL") );
    clear->setMaximumWidth( 30 );
    clear->setToolTip( qtr( "Clear" ));
    BUTTONACT( clear, clearFilter() );
    buttons->addWidget( clear );

    layout->addWidget( view );
    layout->addLayout( buttons );
//    layout->addWidget( bar );
    setLayout( layout );
}

void StandardPLPanel::toggleRepeat()
{
    if( model->hasRepeat() )
    {
        model->setRepeat( false ); model->setLoop( true );
        repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_all.png" ) );
        repeatButton->setToolTip( qtr( I_PL_LOOP ));
    }
    else if( model->hasLoop() )
    {
        model->setRepeat( false ) ; model->setLoop( false );
        repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_off.png" ) );
        repeatButton->setToolTip( qtr( I_PL_NOREPEAT ));
    }
    else
    {
        model->setRepeat( true );
        repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_one.png" ) );
        repeatButton->setToolTip( qtr( I_PL_REPEAT ));
    }
}

void StandardPLPanel::toggleRandom()
{
    bool prev = model->hasRandom();
    model->setRandom( !prev );
    randomButton->setIcon( prev ?
                QIcon( ":/pixmaps/playlist_shuffle_off.png" ) :
                QIcon( ":/pixmaps/playlist_shuffle_on.png" ) );
    randomButton->setToolTip( prev ? qtr( I_PL_NORANDOM ) : qtr(I_PL_RANDOM ) );
}

void StandardPLPanel::handleExpansion( const QModelIndex &index )
{
    if( model->isCurrent( index ) )
        view->scrollTo( index, QAbstractItemView::EnsureVisible );
}

void StandardPLPanel::setCurrentRootId( int _new )
{
    currentRootId = _new;
    if( currentRootId == THEPL->p_local_category->i_id ||
        currentRootId == THEPL->p_local_onelevel->i_id  )
    {
        addButton->setEnabled( true );
        addButton->setToolTip( qtr(I_PL_ADDPL) );
    }
    else if( ( THEPL->p_ml_category &&
                        currentRootId == THEPL->p_ml_category->i_id ) ||
             ( THEPL->p_ml_onelevel &&
                        currentRootId == THEPL->p_ml_onelevel->i_id ) )
    {
        addButton->setEnabled( true );
        addButton->setToolTip( qtr(I_PL_ADDML) );
    }
    else
        addButton->setEnabled( false );
}

void StandardPLPanel::popupAdd()
{
    QMenu popup;
    if( currentRootId == THEPL->p_local_category->i_id ||
        currentRootId == THEPL->p_local_onelevel->i_id )
    {
        popup.addAction( qtr(I_PL_ADDF), THEDP, SLOT(simplePLAppendDialog()));
        popup.addAction( qtr(I_PL_ADVADD), THEDP, SLOT(PLAppendDialog()) );
        popup.addAction( qtr(I_PL_ADDDIR), THEDP, SLOT( PLAppendDir()) );
    }
    else if( ( THEPL->p_ml_category &&
                currentRootId == THEPL->p_ml_category->i_id ) ||
             ( THEPL->p_ml_onelevel &&
                currentRootId == THEPL->p_ml_onelevel->i_id ) )
    {
        popup.addAction( qtr(I_PL_ADDF), THEDP, SLOT(simpleMLAppendDialog()));
        popup.addAction( qtr(I_PL_ADVADD), THEDP, SLOT( MLAppendDialog() ) );
        popup.addAction( qtr(I_PL_ADDDIR), THEDP, SLOT( MLAppendDir() ) );
    }
    popup.exec( QCursor::pos() );
}

void StandardPLPanel::popupSelectColumn( QPoint )
{
    ContextUpdateMapper = new QSignalMapper(this);

    QMenu selectColMenu;

#define ADD_META_ACTION( meta ) { \
   QAction* option = selectColMenu.addAction( qfu(VLC_META_##meta) );     \
   option->setCheckable( true );                                           \
   option->setChecked( model->shownFlags() & VLC_META_ENGINE_##meta );   \
   ContextUpdateMapper->setMapping( option, VLC_META_ENGINE_##meta );      \
   CONNECT( option, triggered(), ContextUpdateMapper, map() );             \
   }
    CONNECT( ContextUpdateMapper, mapped( int ),  model, viewchanged( int ) );

    ADD_META_ACTION( TITLE );
    ADD_META_ACTION( ARTIST );
    ADD_META_ACTION( DURATION );
    ADD_META_ACTION( COLLECTION );
    ADD_META_ACTION( GENRE );
    ADD_META_ACTION( SEQ_NUM );
    ADD_META_ACTION( RATING );
    ADD_META_ACTION( DESCRIPTION );

#undef ADD_META_ACTION

    selectColMenu.exec( QCursor::pos() );
 }

void StandardPLPanel::clearFilter()
{
    searchLine->setText( "" );
}

void StandardPLPanel::search( QString searchText )
{
    model->search( searchText );
}

void StandardPLPanel::doPopup( QModelIndex index, QPoint point )
{
    if( !index.isValid() ) return;
    QItemSelectionModel *selection = view->selectionModel();
    QModelIndexList list = selection->selectedIndexes();
    model->popup( index, point, list );
}

void StandardPLPanel::setRoot( int i_root_id )
{
    playlist_item_t *p_item = playlist_ItemGetById( THEPL, i_root_id,
                                                    VLC_TRUE );
    assert( p_item );
    p_item = playlist_GetPreferredNode( THEPL, p_item );
    assert( p_item );
    model->rebuild( p_item );
}

void StandardPLPanel::removeItem( int i_id )
{
    model->removeItem( i_id );
}

void StandardPLPanel::keyPressEvent( QKeyEvent *e )
{
    switch( e->key() )
    {
    case Qt::Key_Back:
    case Qt::Key_Delete:
        deleteSelection();
        break;
    }
}

void StandardPLPanel::deleteSelection()
{
    QItemSelectionModel *selection = view->selectionModel();
    QModelIndexList list = selection->selectedIndexes();
    model->doDelete( list );
}

StandardPLPanel::~StandardPLPanel()
{}
<|endoftext|>


<commit_before><commit_msg>Fix crash on engine shutdown in gerstner scene<commit_after><|endoftext|>