<commit_before>/*
 * TTBlue Data Object Base Class
 * Copyright © 2008, Timothy Place
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTDataObject.h"
#include "TTEnvironment.h"
#include "TTMatrixArray.h"

/****************************************************************************************************/

TTDataObject::TTDataObject(TTValue& arguments)
	: TTObject(arguments)
{
	registerAttribute(TT("bypass"),	kTypeBoolean,	&mBypass,	(TTSetterMethod)&TTDataObject::setBypass);

//	registerMessage(TT("calculate"),				(TTMethod)&TTAudioObject::calculateMessage);
	registerMessage(TT("test"),						TTMethod(&TTObject::test));
	registerMessage(TT("resetBenchmarking"),		(TTMethod)&TTDataObject::resetBenchmarking, kTTMessagePassNone);
	registerMessage(TT("getProcessingBenchmark"),	(TTMethod)&TTDataObject::getProcessingBenchmark);

	TTObjectInstantiate(kTTSym_matrixarray, (TTObjectPtr*)&mInputArray, 2);
	TTObjectInstantiate(kTTSym_matrixarray, (TTObjectPtr*)&mOutputArray, 2);

	// Set Defaults...
    setMatrixCalculate(&TTDataObject::defaultMatrixCalculateMethod);
	setAttributeValue(TT("bypass"),			kTTBoolNo);
}

TTDataObject::~TTDataObject()
{
	TTObjectRelease((TTObjectPtr*)&mInputArray);
	TTObjectRelease((TTObjectPtr*)&mOutputArray);
}

TTErr TTDataObject::setMatrixCalculate(TTMatrixCalculateMethod newMatrixCalculateMethod)
{
	mMatrixCalculateMethod = newMatrixCalculateMethod;
	if (!mBypass)
		mCurrentMatrixCalculateMethod = mMatrixCalculateMethod;
	return kTTErrNone;
}

TTErr TTDataObject::setBypass(const TTValue& value)
{
	mBypass = value;
	if (mBypass) {
		mCurrentMatrixCalculateMethod = &TTDataObject::bypassMatrixCalculate;
	}
//	else if (attrMute) {
//		currentProcessMethod = &TTAudioObject::muteProcess;
//	}
	else {
		if (mMatrixCalculateMethod)
			mCurrentMatrixCalculateMethod = mMatrixCalculateMethod;
		else
			mCurrentMatrixCalculateMethod = &TTDataObject::defaultMatrixCalculateMethod;
	}
	return kTTErrNone;
}

TTErr TTDataObject::bypassMatrixCalculate(const TTMatrixArray* inputs, TTMatrixArray* outputs)
{
	for (TTUInt16 i=0; i < outputs->getMatrixCount(); i++) {
		TTMatrixPtr out = outputs->getMatrix(i);

		if (i < inputs->getMatrixCount()) {
			TTMatrixPtr in = inputs->getMatrix(i);
			TTMatrix::copy(in, out);
		}
		else
			out->clear();
	}
	return kTTErrNone;
}

TTErr TTDataObject::defaultMatrixCalculateMethod(const TTMatrixArray* inputs, TTMatrixArray* outputs)
{
	return bypassMatrixCalculate(inputs, outputs);
}

TTErr TTDataObject::calculate(const TTMatrixArray* inputs, TTMatrixArray* outputs)
{
	TTErr	err = kTTErrGeneric;

	if (valid) {
		lock();
		mStartProcessingTime = TTGetTimeInMicroseconds();
		err = (this->*mCurrentMatrixCalculateMethod)(inputs, outputs);
		mAccumulatedProcessingTime += (TTGetTimeInMicroseconds() - mStartProcessingTime);
		mAccumulatedProcessingCalls++;
		unlock();
	}
	return err;
}

TTErr TTDataObject::calculate(const TTMatrix& x, TTMatrix& y)
{
	TTErr	err = kTTErrGeneric;

	if (valid) {
		lock();
		mInputArray->setMatrixCount(1);
		mInputArray->setMatrix(0, (TTMatrix&)x);
		mOutputArray->setMatrixCount(1);
		mOutputArray->setMatrix(0, y);
		mStartProcessingTime = TTGetTimeInMicroseconds();
		err = (this->*mCurrentMatrixCalculateMethod)(mInputArray, mOutputArray);
		mAccumulatedProcessingTime += (TTGetTimeInMicroseconds() - mStartProcessingTime);
		mAccumulatedProcessingCalls++;
		unlock();
	}
	return err;
}

TTErr TTDataObject::resetBenchmarking()
{
	mAccumulatedProcessingTime = 0.0;
	mStartProcessingTime = 0.0;
	mAccumulatedProcessingCalls = 0.0;
	return kTTErrNone;
}

TTErr TTDataObject::getProcessingBenchmark(TTValueRef v)
{
	v = mAccumulatedProcessingTime / mAccumulatedProcessingCalls;
	return kTTErrNone;
}

<commit_msg>TTDataObject: fix for uninitialized memory.<commit_after>/*
 * TTBlue Data Object Base Class
 * Copyright © 2008, Timothy Place
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTDataObject.h"
#include "TTEnvironment.h"
#include "TTMatrixArray.h"

/****************************************************************************************************/

TTDataObject::TTDataObject(TTValue& arguments) :
	TTObject(arguments),
	mMatrixCalculateMethod(NULL),
	mCurrentMatrixCalculateMethod(NULL),
	mBypass(NO),
	mInputArray(NULL),
	mOutputArray(NULL),
	mStartProcessingTime(0.0),
	mAccumulatedProcessingTime(0.0),
	mAccumulatedProcessingCalls(0.0),
	mReserved1(0),
	mReserved2(0)
{
	registerAttribute(TT("bypass"),	kTypeBoolean,	&mBypass,	(TTSetterMethod)&TTDataObject::setBypass);

//	registerMessage(TT("calculate"),				(TTMethod)&TTAudioObject::calculateMessage);
	registerMessage(TT("test"),						TTMethod(&TTObject::test));
	registerMessage(TT("resetBenchmarking"),		(TTMethod)&TTDataObject::resetBenchmarking, kTTMessagePassNone);
	registerMessage(TT("getProcessingBenchmark"),	(TTMethod)&TTDataObject::getProcessingBenchmark);

	TTObjectInstantiate(kTTSym_matrixarray, (TTObjectPtr*)&mInputArray, 2);
	TTObjectInstantiate(kTTSym_matrixarray, (TTObjectPtr*)&mOutputArray, 2);

	// Set Defaults...
    setMatrixCalculate(&TTDataObject::defaultMatrixCalculateMethod);
	setAttributeValue(TT("bypass"),			kTTBoolNo);
}

TTDataObject::~TTDataObject()
{
	TTObjectRelease((TTObjectPtr*)&mInputArray);
	TTObjectRelease((TTObjectPtr*)&mOutputArray);
}

TTErr TTDataObject::setMatrixCalculate(TTMatrixCalculateMethod newMatrixCalculateMethod)
{
	mMatrixCalculateMethod = newMatrixCalculateMethod;
	if (!mBypass)
		mCurrentMatrixCalculateMethod = mMatrixCalculateMethod;
	return kTTErrNone;
}

TTErr TTDataObject::setBypass(const TTValue& value)
{
	mBypass = value;
	if (mBypass) {
		mCurrentMatrixCalculateMethod = &TTDataObject::bypassMatrixCalculate;
	}
//	else if (attrMute) {
//		currentProcessMethod = &TTAudioObject::muteProcess;
//	}
	else {
		if (mMatrixCalculateMethod)
			mCurrentMatrixCalculateMethod = mMatrixCalculateMethod;
		else
			mCurrentMatrixCalculateMethod = &TTDataObject::defaultMatrixCalculateMethod;
	}
	return kTTErrNone;
}

TTErr TTDataObject::bypassMatrixCalculate(const TTMatrixArray* inputs, TTMatrixArray* outputs)
{
	for (TTUInt16 i=0; i < outputs->getMatrixCount(); i++) {
		TTMatrixPtr out = outputs->getMatrix(i);

		if (i < inputs->getMatrixCount()) {
			TTMatrixPtr in = inputs->getMatrix(i);
			TTMatrix::copy(in, out);
		}
		else
			out->clear();
	}
	return kTTErrNone;
}

TTErr TTDataObject::defaultMatrixCalculateMethod(const TTMatrixArray* inputs, TTMatrixArray* outputs)
{
	return bypassMatrixCalculate(inputs, outputs);
}

TTErr TTDataObject::calculate(const TTMatrixArray* inputs, TTMatrixArray* outputs)
{
	TTErr	err = kTTErrGeneric;

	if (valid) {
		lock();
		mStartProcessingTime = TTGetTimeInMicroseconds();
		err = (this->*mCurrentMatrixCalculateMethod)(inputs, outputs);
		mAccumulatedProcessingTime += (TTGetTimeInMicroseconds() - mStartProcessingTime);
		mAccumulatedProcessingCalls++;
		unlock();
	}
	return err;
}

TTErr TTDataObject::calculate(const TTMatrix& x, TTMatrix& y)
{
	TTErr	err = kTTErrGeneric;

	if (valid) {
		lock();
		mInputArray->setMatrixCount(1);
		mInputArray->setMatrix(0, (TTMatrix&)x);
		mOutputArray->setMatrixCount(1);
		mOutputArray->setMatrix(0, y);
		mStartProcessingTime = TTGetTimeInMicroseconds();
		err = (this->*mCurrentMatrixCalculateMethod)(mInputArray, mOutputArray);
		mAccumulatedProcessingTime += (TTGetTimeInMicroseconds() - mStartProcessingTime);
		mAccumulatedProcessingCalls++;
		unlock();
	}
	return err;
}

TTErr TTDataObject::resetBenchmarking()
{
	mAccumulatedProcessingTime = 0.0;
	mStartProcessingTime = 0.0;
	mAccumulatedProcessingCalls = 0.0;
	return kTTErrNone;
}

TTErr TTDataObject::getProcessingBenchmark(TTValueRef v)
{
	v = mAccumulatedProcessingTime / mAccumulatedProcessingCalls;
	return kTTErrNone;
}

<|endoftext|>


<commit_before>#include <boost/python.hpp>
#include <string>

/* VK HEADERS */
#include "version.h"
#include "node.h"

using namespace boost::python;
using valkyrie::Version;
using valkyrie::Node;

BOOST_PYTHON_MODULE (pyvalkyrie)
{
    // version
    class_<Version>("Version", no_init)
            .def("major", &Version::getMajor)
            .staticmethod("major")
            .def("minor", &Version::getMinor)
            .staticmethod("minor")
            .def("patch", &Version::getPatch)
            .staticmethod("patch")
            .def("is_at_least", &Version::isAtLeast)
            .staticmethod("is_at_least")
            .def("name", &Version::getVersion)
            .staticmethod("name")
    ;

    // node
    class_<Node>("Node", init<int, double, double, double>())
            .def("id", &Node::get_id)
            .def("x" , &Node::get_x)
            .def("y" , &Node::get_y)
            .def("z" , &Node::get_z)
    ;
}

<commit_msg>replaced .def with .add_property for Node bindings.<commit_after>#include <boost/python.hpp>
#include <string>

/* VK HEADERS */
#include "version.h"
#include "node.h"

using namespace boost::python;
using valkyrie::Version;
using valkyrie::Node;

BOOST_PYTHON_MODULE (pyvalkyrie)
{
    // version
    class_<Version>("Version", no_init)
            .def("major", &Version::getMajor)
            .staticmethod("major")
            .def("minor", &Version::getMinor)
            .staticmethod("minor")
            .def("patch", &Version::getPatch)
            .staticmethod("patch")
            .def("is_at_least", &Version::isAtLeast)
            .staticmethod("is_at_least")
            .def("name", &Version::getVersion)
            .staticmethod("name")
    ;

    // node
    class_<Node>("Node", init<int, double, double, double>())
            .add_property("id", &Node::get_id)
            .add_property("x" , &Node::get_x)
            .add_property("y" , &Node::get_y)
            .add_property("z" , &Node::get_z)
    ;
}

<|endoftext|>


<commit_before>/*
 * DesktopWebPage.cpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "DesktopWebPage.hpp"

#include <core/Log.hpp>
#include <core/Error.hpp>

#include <QWidget>
#include <QtDebug>
#include "DesktopNetworkAccessManager.hpp"
#include "DesktopWindowTracker.hpp"
#include "DesktopSatelliteWindow.hpp"
#include "DesktopSecondaryWindow.hpp"
#include "DesktopMainWindow.hpp"

#include "DesktopUtils.hpp"

extern QString sharedSecret;

namespace desktop {

namespace {

WindowTracker s_windowTracker;

} // anonymous namespace

WebPage::WebPage(QUrl baseUrl, QWidget *parent) :
      QWebPage(parent),
      baseUrl_(baseUrl),
      navigated_(false)
{
   settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
   settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows, true);
   setNetworkAccessManager(new NetworkAccessManager(sharedSecret, parent));
   defaultSaveDir_ = QDir::home();
}

void WebPage::setBaseUrl(const QUrl& baseUrl)
{
   baseUrl_ = baseUrl;
}

void WebPage::activateSatelliteWindow(QString name)
{
   BrowserWindow* pSatellite = s_windowTracker.getWindow(name);
   if (pSatellite)
      desktop::raiseAndActivateWindow(pSatellite);
}

void WebPage::prepareForSatelliteWindow(
                              const PendingSatelliteWindow& pendingWnd)
{
   pendingSatelliteWindow_ = pendingWnd;
}

QWebPage* WebPage::createWindow(QWebPage::WebWindowType)
{
   // check if this is a satellite window
   if (!pendingSatelliteWindow_.isEmpty())
   {
      // capture pending window params then clear them (one time only)
      QString name = pendingSatelliteWindow_.name;
      MainWindow* pMainWindow = pendingSatelliteWindow_.pMainWindow;
      int width = pendingSatelliteWindow_.width;
      int height = pendingSatelliteWindow_.height;
      pendingSatelliteWindow_ = PendingSatelliteWindow();

      // check for an existing window of this name
      BrowserWindow* pSatellite = s_windowTracker.getWindow(name);
      if (pSatellite)
      {
         // activate the browser then return NULL to indicate
         // we didn't create a new WebView
         desktop::raiseAndActivateWindow(pSatellite);
         return NULL;
      }
      // create a new window if we didn't find one
      else
      {
         // create and size
         pSatellite = new SatelliteWindow(pMainWindow);
         pSatellite->resize(width, height);

         // try to tile the window (but leave pdf window alone
         // since it is so large)
         if (name != QString::fromAscii("pdf"))
         {
            // calculate location to move to

            // y always attempts to be 25 pixels above then faults back
            // to 25 pixels below if that would be offscreen
            const int OVERLAP = 25;
            int moveY = pMainWindow->y() - OVERLAP;
            if (moveY < 0)
               moveY = pMainWindow->y() + OVERLAP;

            // x is based on centering over main window
            int moveX = pMainWindow->x() +
                        (pMainWindow->width() / 2) -
                        (width / 2);

            // perform movve
            pSatellite->move(moveX, moveY);
         }

         // add to tracker
         s_windowTracker.addWindow(name, pSatellite);

         // show and return the browser
         pSatellite->show();
         return pSatellite->webView()->webPage();
      }
   }
   else
   {
      SecondaryWindow* pWindow = new SecondaryWindow(baseUrl_);
      pWindow->show();
      return pWindow->webView()->webPage();
   }
}

bool WebPage::shouldInterruptJavaScript()
{
   return false;
}

void WebPage::javaScriptConsoleMessage(const QString& message, int /*lineNumber*/, const QString& /*sourceID*/)
{
   qDebug() << message;
}

QString WebPage::userAgentForUrl(const QUrl &url) const
{
   return this->QWebPage::userAgentForUrl(url) + QString::fromAscii(" Qt/") + QString::fromAscii(qVersion());
}

bool WebPage::acceptNavigationRequest(QWebFrame* pWebFrame,
                                       const QNetworkRequest& request,
                                       NavigationType navType)
{
   QUrl url = request.url();

   if (url.toString() == QString::fromAscii("about:blank"))
      return true;

   if (url.scheme() != QString::fromAscii("http")
       && url.scheme() != QString::fromAscii("https")
       && url.scheme() != QString::fromAscii("mailto")
       && url.scheme() != QString::fromAscii("data"))
   {
      qDebug() << url.toString();
      return false;
   }

   // determine if this is a local request (handle internally only if local)
   std::string host = url.host().toStdString();
   bool isLocal = host == "localhost" || host == "127.0.0.1";

   if ((baseUrl_.isEmpty() && isLocal) ||
       (url.scheme() == baseUrl_.scheme()
        && url.host() == baseUrl_.host()
        && url.port() == baseUrl_.port()))
   {
      navigated_ = true;
      return true;
   }
   // allow local viewer urls to be handled internally by Qt
   else if (isLocal && !viewerUrl_.isEmpty() &&
            url.toString().startsWith(viewerUrl_))
   {
      navigated_ = true;
      return true;
   }
   else
   {
      if (url.scheme() == QString::fromUtf8("data") &&
          (navType == QWebPage::NavigationTypeLinkClicked ||
           navType == QWebPage::NavigationTypeFormSubmitted))
      {
         handleBase64Download(pWebFrame, url);
      }
      else
      {
         desktop::openUrl(url);
      }

      if (!navigated_)
         this->view()->window()->deleteLater();

      return false;
   }
}

void WebPage::handleBase64Download(QWebFrame* pWebFrame, QUrl url)
{
   // look for beginning of base64 data
   QString base64 = QString::fromUtf8("base64,");
   int pos = url.path().indexOf(base64);
   if (pos == -1)
   {
      LOG_ERROR_MESSAGE("Base64 designator not found in data url");
      return;
   }

   // extract the base64 data from the uri
   QString base64Data = url.path();
   base64Data.remove(0, pos + base64.length());
   QByteArray base64ByteArray(base64Data.toStdString().c_str());
   QByteArray byteArray = QByteArray::fromBase64(base64ByteArray);

   // find the a tag in the page with this href
   QWebElement aTag;
   QString urlString = url.toString(QUrl::None);
   QWebElementCollection aElements = pWebFrame->findAllElements(
                                             QString::fromUtf8("a"));
   for (int i=0; i<aElements.count(); i++)
   {
      QWebElement a = aElements.at(i);
      QString href = a.attribute(QString::fromUtf8("href"));
      href.replace(QChar::fromAscii('\n'), QString::fromUtf8(""));
      if (href == urlString)
      {
         aTag = a;
         break;
      }
   }

   // if no a tag was found then bail
   if (aTag.isNull())
   {
      LOG_ERROR_MESSAGE("Unable to finding matching a tag for data url");
      return;
   }

   // get the download attribute (default filename)
   QString download = aTag.attribute(QString::fromUtf8("download"));
   QString defaultFilename = defaultSaveDir_.absoluteFilePath(download);

   // prompt for filename
   QString filename = QFileDialog::getSaveFileName(
                                            NULL,
                                            tr("Download File"),
                                            defaultFilename,
                                            defaultSaveDir_.absolutePath(),
                                            0,
                                            standardFileDialogOptions());
   if (!filename.isEmpty())
   {
      // write the file
      QFile file(filename);
      if (file.open(QIODevice::WriteOnly))
      {
         if (file.write(byteArray) == -1)
         {
            showFileError(QString::fromUtf8("writing"),
                          filename,
                          file.errorString());
         }

         file.close();
      }
      else
      {
         showFileError(QString::fromUtf8("writing"),
                       filename,
                       file.errorString());
      }

      // persist the defaultSaveDir
      defaultSaveDir_ = QFileInfo(file).dir();
   }
}

}
<commit_msg>provide default file extension for base64 downloads<commit_after>/*
 * DesktopWebPage.cpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "DesktopWebPage.hpp"

#include <core/Log.hpp>
#include <core/Error.hpp>
#include <core/FilePath.hpp>

#include <QWidget>
#include <QtDebug>
#include "DesktopNetworkAccessManager.hpp"
#include "DesktopWindowTracker.hpp"
#include "DesktopSatelliteWindow.hpp"
#include "DesktopSecondaryWindow.hpp"
#include "DesktopMainWindow.hpp"

#include "DesktopUtils.hpp"

using namespace core;

extern QString sharedSecret;

namespace desktop {

namespace {

WindowTracker s_windowTracker;

} // anonymous namespace

WebPage::WebPage(QUrl baseUrl, QWidget *parent) :
      QWebPage(parent),
      baseUrl_(baseUrl),
      navigated_(false)
{
   settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
   settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows, true);
   setNetworkAccessManager(new NetworkAccessManager(sharedSecret, parent));
   defaultSaveDir_ = QDir::home();
}

void WebPage::setBaseUrl(const QUrl& baseUrl)
{
   baseUrl_ = baseUrl;
}

void WebPage::activateSatelliteWindow(QString name)
{
   BrowserWindow* pSatellite = s_windowTracker.getWindow(name);
   if (pSatellite)
      desktop::raiseAndActivateWindow(pSatellite);
}

void WebPage::prepareForSatelliteWindow(
                              const PendingSatelliteWindow& pendingWnd)
{
   pendingSatelliteWindow_ = pendingWnd;
}

QWebPage* WebPage::createWindow(QWebPage::WebWindowType)
{
   // check if this is a satellite window
   if (!pendingSatelliteWindow_.isEmpty())
   {
      // capture pending window params then clear them (one time only)
      QString name = pendingSatelliteWindow_.name;
      MainWindow* pMainWindow = pendingSatelliteWindow_.pMainWindow;
      int width = pendingSatelliteWindow_.width;
      int height = pendingSatelliteWindow_.height;
      pendingSatelliteWindow_ = PendingSatelliteWindow();

      // check for an existing window of this name
      BrowserWindow* pSatellite = s_windowTracker.getWindow(name);
      if (pSatellite)
      {
         // activate the browser then return NULL to indicate
         // we didn't create a new WebView
         desktop::raiseAndActivateWindow(pSatellite);
         return NULL;
      }
      // create a new window if we didn't find one
      else
      {
         // create and size
         pSatellite = new SatelliteWindow(pMainWindow);
         pSatellite->resize(width, height);

         // try to tile the window (but leave pdf window alone
         // since it is so large)
         if (name != QString::fromAscii("pdf"))
         {
            // calculate location to move to

            // y always attempts to be 25 pixels above then faults back
            // to 25 pixels below if that would be offscreen
            const int OVERLAP = 25;
            int moveY = pMainWindow->y() - OVERLAP;
            if (moveY < 0)
               moveY = pMainWindow->y() + OVERLAP;

            // x is based on centering over main window
            int moveX = pMainWindow->x() +
                        (pMainWindow->width() / 2) -
                        (width / 2);

            // perform movve
            pSatellite->move(moveX, moveY);
         }

         // add to tracker
         s_windowTracker.addWindow(name, pSatellite);

         // show and return the browser
         pSatellite->show();
         return pSatellite->webView()->webPage();
      }
   }
   else
   {
      SecondaryWindow* pWindow = new SecondaryWindow(baseUrl_);
      pWindow->show();
      return pWindow->webView()->webPage();
   }
}

bool WebPage::shouldInterruptJavaScript()
{
   return false;
}

void WebPage::javaScriptConsoleMessage(const QString& message, int /*lineNumber*/, const QString& /*sourceID*/)
{
   qDebug() << message;
}

QString WebPage::userAgentForUrl(const QUrl &url) const
{
   return this->QWebPage::userAgentForUrl(url) + QString::fromAscii(" Qt/") + QString::fromAscii(qVersion());
}

bool WebPage::acceptNavigationRequest(QWebFrame* pWebFrame,
                                       const QNetworkRequest& request,
                                       NavigationType navType)
{
   QUrl url = request.url();

   if (url.toString() == QString::fromAscii("about:blank"))
      return true;

   if (url.scheme() != QString::fromAscii("http")
       && url.scheme() != QString::fromAscii("https")
       && url.scheme() != QString::fromAscii("mailto")
       && url.scheme() != QString::fromAscii("data"))
   {
      qDebug() << url.toString();
      return false;
   }

   // determine if this is a local request (handle internally only if local)
   std::string host = url.host().toStdString();
   bool isLocal = host == "localhost" || host == "127.0.0.1";

   if ((baseUrl_.isEmpty() && isLocal) ||
       (url.scheme() == baseUrl_.scheme()
        && url.host() == baseUrl_.host()
        && url.port() == baseUrl_.port()))
   {
      navigated_ = true;
      return true;
   }
   // allow local viewer urls to be handled internally by Qt
   else if (isLocal && !viewerUrl_.isEmpty() &&
            url.toString().startsWith(viewerUrl_))
   {
      navigated_ = true;
      return true;
   }
   else
   {
      if (url.scheme() == QString::fromUtf8("data") &&
          (navType == QWebPage::NavigationTypeLinkClicked ||
           navType == QWebPage::NavigationTypeFormSubmitted))
      {
         handleBase64Download(pWebFrame, url);
      }
      else
      {
         desktop::openUrl(url);
      }

      if (!navigated_)
         this->view()->window()->deleteLater();

      return false;
   }
}

void WebPage::handleBase64Download(QWebFrame* pWebFrame, QUrl url)
{
   // look for beginning of base64 data
   QString base64 = QString::fromUtf8("base64,");
   int pos = url.path().indexOf(base64);
   if (pos == -1)
   {
      LOG_ERROR_MESSAGE("Base64 designator not found in data url");
      return;
   }

   // extract the base64 data from the uri
   QString base64Data = url.path();
   base64Data.remove(0, pos + base64.length());
   QByteArray base64ByteArray(base64Data.toStdString().c_str());
   QByteArray byteArray = QByteArray::fromBase64(base64ByteArray);

   // find the a tag in the page with this href
   QWebElement aTag;
   QString urlString = url.toString(QUrl::None);
   QWebElementCollection aElements = pWebFrame->findAllElements(
                                             QString::fromUtf8("a"));
   for (int i=0; i<aElements.count(); i++)
   {
      QWebElement a = aElements.at(i);
      QString href = a.attribute(QString::fromUtf8("href"));
      href.replace(QChar::fromAscii('\n'), QString::fromUtf8(""));
      if (href == urlString)
      {
         aTag = a;
         break;
      }
   }

   // if no a tag was found then bail
   if (aTag.isNull())
   {
      LOG_ERROR_MESSAGE("Unable to finding matching a tag for data url");
      return;
   }

   // get the download attribute (default filename)
   QString download = aTag.attribute(QString::fromUtf8("download"));
   QString defaultFilename = defaultSaveDir_.absoluteFilePath(download);

   // prompt for filename
   QString filename = QFileDialog::getSaveFileName(
                                            NULL,
                                            tr("Download File"),
                                            defaultFilename,
                                            defaultSaveDir_.absolutePath(),
                                            0,
                                            standardFileDialogOptions());
   if (!filename.isEmpty())
   {
      // see if we need to force the extension
      FilePath defaultFilePath(defaultFilename.toUtf8().constData());
      FilePath chosenFilePath(filename.toUtf8().constData());
      if (chosenFilePath.extension().empty() &&
          !defaultFilePath.extension().empty())
      {
         filename += QString::fromStdString(defaultFilePath.extension());
      }

      // write the file
      QFile file(filename);
      if (file.open(QIODevice::WriteOnly))
      {
         if (file.write(byteArray) == -1)
         {
            showFileError(QString::fromUtf8("writing"),
                          filename,
                          file.errorString());
         }

         file.close();
      }
      else
      {
         showFileError(QString::fromUtf8("writing"),
                       filename,
                       file.errorString());
      }

      // persist the defaultSaveDir
      defaultSaveDir_ = QFileInfo(file).dir();
   }
}

}
<|endoftext|>


<commit_before>/*
    Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable

    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.
*/
/**
 * @author Valentin Al. Sitnick
 * @version $Revision: 1.1 $
 *
 */

/* *********************************************************************** */

#include "events.h"
#include "utils.h"
#include "fake.h"

static bool test = false;
static bool util = false;
static bool flag = false;

const char test_case_name[] = "GetClassSignature0102";

/* *********************************************************************** */

JNIEXPORT jint JNICALL Agent_OnLoad(prms_AGENT_ONLOAD)
{
    Callbacks CB;
    check_AGENT_ONLOAD;
    jvmtiEvent events[] = { JVMTI_EVENT_EXCEPTION, JVMTI_EVENT_VM_DEATH };
    cb_exc;
    cb_death;
    return func_for_Agent_OnLoad(vm, options, reserved, &CB, events,
            sizeof(events)/4, test_case_name, DEBUG_OUT);
}

/* *********************************************************************** */

void JNICALL callbackException(prms_EXCPT)
{
    check_EXCPT;

    if (flag) return;

    jvmtiError result;
    jclass myclass = NULL;
    char* signature;
    char* generic;

    /*
     * Function separate all other exceptions in all other method
     */
    if (!check_phase_and_method_debug(jvmti_env, method, SPP_LIVE_ONLY,
                "special_method", DEBUG_OUT)) return;

    result = jvmti_env->GetMethodDeclaringClass(method, &myclass);
    if (DEBUG_OUT)
    {
        fprintf(stderr, "\tnative: GetMethodDeclaringClass result = %d (must be zero) \n", result);
        fprintf(stderr, "\tnative: method is %p \n", method);
        fprintf(stderr, "\tnative: myclass is %p \n", myclass);
    }
    if (result != JVMTI_ERROR_NONE) return;

    flag = true;
    util = true;

    result = jvmti_env->GetClassSignature((jclass)thread, &signature, &generic);
    fprintf(stderr, "\tnative: GetClassSignature result = %d (must be JVMTI_ERROR_INVALID_CLASS (21)) \n", result);
    fprintf(stderr, "\tnative: classes ptr is %p \n", myclass);
    fprintf(stderr, "\tnative: signature is %s \n", signature);
    fprintf(stderr, "\tnative: generic is %s \n", generic);
    fflush(stderr);

    if (result != JVMTI_ERROR_INVALID_CLASS) return;
    test = true;
}

void JNICALL callbackVMDeath(prms_VMDEATH)
{
    check_VMDEATH;
    func_for_callback_VMDeath(jni_env, jvmti_env, test_case_name, test, util);
}

/* *********************************************************************** */

<commit_msg>Apply patch from HARMONY-4315: [buildtest][vts] Test vm/jvmti/funcs/GetClassSignature/GetClassSignature0102/GetClassSignature0102.xml crashes when it tries to print wrong data<commit_after>/*
    Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable

    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.
*/
/**
 * @author Valentin Al. Sitnick
 * @version $Revision: 1.1 $
 *
 */

/* *********************************************************************** */

#include "events.h"
#include "utils.h"
#include "fake.h"

static bool test = false;
static bool util = false;
static bool flag = false;

const char test_case_name[] = "GetClassSignature0102";

/* *********************************************************************** */

JNIEXPORT jint JNICALL Agent_OnLoad(prms_AGENT_ONLOAD)
{
    Callbacks CB;
    check_AGENT_ONLOAD;
    jvmtiEvent events[] = { JVMTI_EVENT_EXCEPTION, JVMTI_EVENT_VM_DEATH };
    cb_exc;
    cb_death;
    return func_for_Agent_OnLoad(vm, options, reserved, &CB, events,
            sizeof(events)/4, test_case_name, DEBUG_OUT);
}

/* *********************************************************************** */

void JNICALL callbackException(prms_EXCPT)
{
    check_EXCPT;

    if (flag) return;

    jvmtiError result;
    jclass myclass = NULL;
    char* signature;
    char* generic;

    /*
     * Function separate all other exceptions in all other method
     */
    if (!check_phase_and_method_debug(jvmti_env, method, SPP_LIVE_ONLY,
                "special_method", DEBUG_OUT)) return;

    result = jvmti_env->GetMethodDeclaringClass(method, &myclass);
    if (DEBUG_OUT)
    {
        fprintf(stderr, "\tnative: GetMethodDeclaringClass result = %d (must be zero) \n", result);
        fprintf(stderr, "\tnative: method is %p \n", method);
        fprintf(stderr, "\tnative: myclass is %p \n", myclass);
    }
    if (result != JVMTI_ERROR_NONE) return;

    flag = true;
    util = true;

    result = jvmti_env->GetClassSignature((jclass)thread, &signature, &generic);
    fprintf(stderr, "\tnative: GetClassSignature result = %d (must be JVMTI_ERROR_INVALID_CLASS (21)) \n", result);
    fflush(stderr);

    if (result != JVMTI_ERROR_INVALID_CLASS) return;
    test = true;
}

void JNICALL callbackVMDeath(prms_VMDEATH)
{
    check_VMDEATH;
    func_for_callback_VMDeath(jni_env, jvmti_env, test_case_name, test, util);
}

/* *********************************************************************** */

<|endoftext|>


<commit_before>//===--------------------------------------------------------------------------------*- C++ -*-===//
//                          _
//                         | |
//                       __| | __ ___      ___ ___
//                      / _` |/ _` \ \ /\ / / '_  |
//                     | (_| | (_| |\ V  V /| | | |
//                      \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain
//
//
//  This file is distributed under the MIT License (MIT).
//  See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//

#include "dawn/Compiler/DawnCompiler.h"
#include "dawn/CodeGen/CXXNaive/CXXNaiveCodeGen.h"
#include "dawn/CodeGen/CodeGen.h"
#include "dawn/CodeGen/Cuda/CudaCodeGen.h"
#include "dawn/CodeGen/GridTools/GTCodeGen.h"
#include "dawn/Optimizer/OptimizerContext.h"
#include "dawn/Optimizer/PassComputeStageExtents.h"
#include "dawn/Optimizer/PassDataLocalityMetric.h"
#include "dawn/Optimizer/PassFieldVersioning.h"
#include "dawn/Optimizer/PassInlining.h"
#include "dawn/Optimizer/PassMultiStageSplitter.h"
#include "dawn/Optimizer/PassPrintStencilGraph.h"
#include "dawn/Optimizer/PassSSA.h"
#include "dawn/Optimizer/PassSetBlockSize.h"
#include "dawn/Optimizer/PassSetBoundaryCondition.h"
#include "dawn/Optimizer/PassSetCaches.h"
#include "dawn/Optimizer/PassSetNonTempCaches.h"
#include "dawn/Optimizer/PassSetStageGraph.h"
#include "dawn/Optimizer/PassSetStageName.h"
#include "dawn/Optimizer/PassSetSyncStage.h"
#include "dawn/Optimizer/PassStageMerger.h"
#include "dawn/Optimizer/PassStageReordering.h"
#include "dawn/Optimizer/PassStageSplitter.h"
#include "dawn/Optimizer/PassStencilSplitter.h"
#include "dawn/Optimizer/PassTemporaryFirstAccess.h"
#include "dawn/Optimizer/PassTemporaryMerger.h"
#include "dawn/Optimizer/PassTemporaryToStencilFunction.h"
#include "dawn/Optimizer/PassTemporaryType.h"
#include "dawn/SIR/SIR.h"
#include "dawn/Serialization/IIRSerializer.h"
#include "dawn/Support/EditDistance.h"
#include "dawn/Support/Logging.h"
#include "dawn/Support/StringSwitch.h"
#include "dawn/Support/StringUtil.h"
#include "dawn/Support/Unreachable.h"

namespace dawn {

namespace {

/// @brief Make a suggestion to the user if there is a small typo (only works with string options)
template <class T>
struct ComputeEditDistance {
  static std::string getSuggestion(const T& value, const std::vector<T>& possibleValues) {
    return "";
  }
};

template <>
struct ComputeEditDistance<std::string> {
  static std::string getSuggestion(const std::string& value,
                                   const std::vector<std::string>& possibleValues) {
    if(possibleValues.empty())
      return "";

    std::vector<unsigned> editDistances;
    std::transform(possibleValues.begin(), possibleValues.end(), std::back_inserter(editDistances),
                   [&](const std::string& val) { return computeEditDistance(value, val); });

    // Find minimum edit distance
    unsigned minEditDistance = editDistances[0], minEditDistanceIdx = 0;
    for(unsigned i = 1; i < editDistances.size(); ++i)
      if(editDistances[i] < minEditDistance) {
        minEditDistance = editDistances[i];
        minEditDistanceIdx = i;
      }

    return minEditDistance <= 2 ? "did you mean '" + possibleValues[minEditDistanceIdx] + "' ?"
                                : "";
  }
};
} // anonymous namespace

/// @brief Report a diagnostic concering an invalid Option
template <class T>
static DiagnosticsBuilder buildDiag(const std::string& option, const T& value, std::string reason,
                                    std::vector<T> possibleValues = std::vector<T>{}) {
  DiagnosticsBuilder diag(DiagnosticsKind::Error, SourceLocation());
  diag << "invalid value '" << value << "' of option '" << option << "'";

  if(!reason.empty()) {
    diag << ", " << reason;
  } else {
    auto suggestion = ComputeEditDistance<T>::getSuggestion(value, possibleValues);

    if(!suggestion.empty())
      diag << ", " << suggestion;
    else if(!possibleValues.empty())
      diag << ", possible values " << RangeToString()(possibleValues);
  }
  return diag;
}

static std::string remove_fileextension(std::string fullName, std::string extension) {
  std::string truncation = "";
  std::size_t pos = 0;
  while((pos = fullName.find(extension)) != std::string::npos) {
    truncation += fullName.substr(0, pos);
    fullName.erase(0, pos + extension.length());
  }
  return truncation;
}

DawnCompiler::DawnCompiler(Options* options) : diagnostics_(make_unique<DiagnosticsEngine>()) {
  options_ = options ? make_unique<Options>(*options) : make_unique<Options>();
}

std::unique_ptr<OptimizerContext> DawnCompiler::runOptimizer(std::shared_ptr<SIR> const& SIR) {
  // -reorder
  using ReorderStrategyKind = ReorderStrategy::ReorderStrategyKind;
  ReorderStrategyKind reorderStrategy = StringSwitch<ReorderStrategyKind>(options_->ReorderStrategy)
                                            .Case("none", ReorderStrategyKind::RK_None)
                                            .Case("greedy", ReorderStrategyKind::RK_Greedy)
                                            .Case("scut", ReorderStrategyKind::RK_Partitioning)
                                            .Default(ReorderStrategyKind::RK_Unknown);

  if(reorderStrategy == ReorderStrategyKind::RK_Unknown) {
    diagnostics_->report(
        buildDiag("-reorder", options_->ReorderStrategy, "", {"none", "greedy", "scut"}));
    return nullptr;
  }

  using MultistageSplitStrategy = PassMultiStageSplitter::MultiStageSplittingStrategy;
  MultistageSplitStrategy mssSplitStrategy;
  if(options_->MaxCutMSS) {
    mssSplitStrategy = MultistageSplitStrategy::SS_MaxCut;
  } else {
    mssSplitStrategy = MultistageSplitStrategy::SS_Optimized;
  }

  // -max-fields
  int maxFields = options_->MaxFieldsPerStencil;

  IIRSerializer::SerializationKind serializationKind = IIRSerializer::SK_Json;
  if(options_->SerializeIIR) { /*|| (options_->LoadSerialized != "")) {*/
    if(options_->IIRFormat == "json") {
      serializationKind = IIRSerializer::SK_Json;
    } else if(options_->IIRFormat == "byte") {
      serializationKind = IIRSerializer::SK_Byte;

    } else {
      dawn_unreachable("Unknown SIRFormat option");
    }
  }

  // Initialize optimizer
  std::unique_ptr<OptimizerContext> optimizer =
      make_unique<OptimizerContext>(getDiagnostics(), getOptions(), SIR);
  PassManager& passManager = optimizer->getPassManager();

  // Setup pass interface
  optimizer->checkAndPushBack<PassInlining>(true, PassInlining::IK_InlineProcedures);
  optimizer->checkAndPushBack<PassTemporaryFirstAccess>();
  optimizer->checkAndPushBack<PassFieldVersioning>();
  optimizer->checkAndPushBack<PassSSA>();
  optimizer->checkAndPushBack<PassMultiStageSplitter>(mssSplitStrategy);
  optimizer->checkAndPushBack<PassStageSplitter>();
  optimizer->checkAndPushBack<PassPrintStencilGraph>();
  optimizer->checkAndPushBack<PassTemporaryType>();
  optimizer->checkAndPushBack<PassSetStageName>();
  optimizer->checkAndPushBack<PassSetStageGraph>();
  optimizer->checkAndPushBack<PassStageReordering>(reorderStrategy);
  optimizer->checkAndPushBack<PassStageMerger>();
  optimizer->checkAndPushBack<PassStencilSplitter>(maxFields);
  optimizer->checkAndPushBack<PassTemporaryType>();
  optimizer->checkAndPushBack<PassTemporaryMerger>();
  optimizer->checkAndPushBack<PassInlining>(
      (getOptions().InlineSF || getOptions().PassTmpToFunction),
      PassInlining::IK_ComputationsOnTheFly);
  optimizer->checkAndPushBack<PassTemporaryToStencilFunction>();
  optimizer->checkAndPushBack<PassSetNonTempCaches>();
  optimizer->checkAndPushBack<PassSetCaches>();
  optimizer->checkAndPushBack<PassComputeStageExtents>();
  optimizer->checkAndPushBack<PassSetBoundaryCondition>();
  optimizer->checkAndPushBack<PassSetBlockSize>();
  optimizer->checkAndPushBack<PassDataLocalityMetric>();
  optimizer->checkAndPushBack<PassSetSyncStage>();

  DAWN_LOG(INFO) << "All the passes ran with the current command line arugments:";
  for(const auto& a : passManager.getPasses()) {
    DAWN_LOG(INFO) << a->getName();
  }
  // Run optimization passes
  for(auto& stencil : optimizer->getStencilInstantiationMap()) {
    std::shared_ptr<iir::StencilInstantiation> instantiation = stencil.second;
    DAWN_LOG(INFO) << "Starting Optimization and Analysis passes for `" << instantiation->getName()
                   << "` ...";
    if(!passManager.runAllPassesOnStecilInstantiation(instantiation))
      return nullptr;
    DAWN_LOG(INFO) << "Done with Optimization and Analysis passes for `" << instantiation->getName()
                   << "`";

    if(options_->SerializeIIR) {
      IIRSerializer::serialize(
          remove_fileextension(instantiation->getMetaData().fileName_, ".cpp") + ".iir",
          instantiation, serializationKind);
    }

    stencil.second = instantiation;
  }

  return optimizer;
}

std::unique_ptr<codegen::TranslationUnit> DawnCompiler::compile(const std::shared_ptr<SIR>& SIR) {
  diagnostics_->clear();
  diagnostics_->setFilename(SIR->Filename);

  // Check if options are valid

  // -max-halo
  if(options_->MaxHaloPoints < 0) {
    diagnostics_->report(buildDiag("-max-halo", options_->MaxHaloPoints,
                                   "maximum number of allowed halo points must be >= 0"));
    return nullptr;
  }

  // Initialize optimizer
  auto optimizer = runOptimizer(SIR);

  if(diagnostics_->hasErrors()) {
    DAWN_LOG(INFO) << "Errors occured. Skipping code generation.";
    return nullptr;
  }

  // Generate code
  std::unique_ptr<codegen::CodeGen> CG;

  if(options_->Backend == "gridtools") {
    CG = make_unique<codegen::gt::GTCodeGen>(optimizer.get());
  } else if(options_->Backend == "c++-naive") {
    CG = make_unique<codegen::cxxnaive::CXXNaiveCodeGen>(optimizer.get());
  } else if(options_->Backend == "cuda") {
    CG = make_unique<codegen::cuda::CudaCodeGen>(optimizer.get());
  } else if(options_->Backend == "c++-opt") {
    dawn_unreachable("GTClangOptCXX not supported yet");
  } else {
    diagnostics_->report(buildDiag("-backend", options_->Backend,
                                   "backend options must be : " +
                                       dawn::RangeToString(", ", "", "")(std::vector<std::string>{
                                           "gridtools", "c++-naive", "c++-opt"})));
    return nullptr;
  }

  return CG->generateCode();
}

const DiagnosticsEngine& DawnCompiler::getDiagnostics() const { return *diagnostics_.get(); }
DiagnosticsEngine& DawnCompiler::getDiagnostics() { return *diagnostics_.get(); }

const Options& DawnCompiler::getOptions() const { return *options_.get(); }
Options& DawnCompiler::getOptions() { return *options_.get(); }

} // namespace dawn
<commit_msg>disable currently broken TFA (#198)<commit_after>//===--------------------------------------------------------------------------------*- C++ -*-===//
//                          _
//                         | |
//                       __| | __ ___      ___ ___
//                      / _` |/ _` \ \ /\ / / '_  |
//                     | (_| | (_| |\ V  V /| | | |
//                      \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain
//
//
//  This file is distributed under the MIT License (MIT).
//  See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//

#include "dawn/Compiler/DawnCompiler.h"
#include "dawn/CodeGen/CXXNaive/CXXNaiveCodeGen.h"
#include "dawn/CodeGen/CodeGen.h"
#include "dawn/CodeGen/Cuda/CudaCodeGen.h"
#include "dawn/CodeGen/GridTools/GTCodeGen.h"
#include "dawn/Optimizer/OptimizerContext.h"
#include "dawn/Optimizer/PassComputeStageExtents.h"
#include "dawn/Optimizer/PassDataLocalityMetric.h"
#include "dawn/Optimizer/PassFieldVersioning.h"
#include "dawn/Optimizer/PassInlining.h"
#include "dawn/Optimizer/PassMultiStageSplitter.h"
#include "dawn/Optimizer/PassPrintStencilGraph.h"
#include "dawn/Optimizer/PassSSA.h"
#include "dawn/Optimizer/PassSetBlockSize.h"
#include "dawn/Optimizer/PassSetBoundaryCondition.h"
#include "dawn/Optimizer/PassSetCaches.h"
#include "dawn/Optimizer/PassSetNonTempCaches.h"
#include "dawn/Optimizer/PassSetStageGraph.h"
#include "dawn/Optimizer/PassSetStageName.h"
#include "dawn/Optimizer/PassSetSyncStage.h"
#include "dawn/Optimizer/PassStageMerger.h"
#include "dawn/Optimizer/PassStageReordering.h"
#include "dawn/Optimizer/PassStageSplitter.h"
#include "dawn/Optimizer/PassStencilSplitter.h"
#include "dawn/Optimizer/PassTemporaryFirstAccess.h"
#include "dawn/Optimizer/PassTemporaryMerger.h"
#include "dawn/Optimizer/PassTemporaryToStencilFunction.h"
#include "dawn/Optimizer/PassTemporaryType.h"
#include "dawn/SIR/SIR.h"
#include "dawn/Serialization/IIRSerializer.h"
#include "dawn/Support/EditDistance.h"
#include "dawn/Support/Logging.h"
#include "dawn/Support/StringSwitch.h"
#include "dawn/Support/StringUtil.h"
#include "dawn/Support/Unreachable.h"

namespace dawn {

namespace {

/// @brief Make a suggestion to the user if there is a small typo (only works with string options)
template <class T>
struct ComputeEditDistance {
  static std::string getSuggestion(const T& value, const std::vector<T>& possibleValues) {
    return "";
  }
};

template <>
struct ComputeEditDistance<std::string> {
  static std::string getSuggestion(const std::string& value,
                                   const std::vector<std::string>& possibleValues) {
    if(possibleValues.empty())
      return "";

    std::vector<unsigned> editDistances;
    std::transform(possibleValues.begin(), possibleValues.end(), std::back_inserter(editDistances),
                   [&](const std::string& val) { return computeEditDistance(value, val); });

    // Find minimum edit distance
    unsigned minEditDistance = editDistances[0], minEditDistanceIdx = 0;
    for(unsigned i = 1; i < editDistances.size(); ++i)
      if(editDistances[i] < minEditDistance) {
        minEditDistance = editDistances[i];
        minEditDistanceIdx = i;
      }

    return minEditDistance <= 2 ? "did you mean '" + possibleValues[minEditDistanceIdx] + "' ?"
                                : "";
  }
};
} // anonymous namespace

/// @brief Report a diagnostic concering an invalid Option
template <class T>
static DiagnosticsBuilder buildDiag(const std::string& option, const T& value, std::string reason,
                                    std::vector<T> possibleValues = std::vector<T>{}) {
  DiagnosticsBuilder diag(DiagnosticsKind::Error, SourceLocation());
  diag << "invalid value '" << value << "' of option '" << option << "'";

  if(!reason.empty()) {
    diag << ", " << reason;
  } else {
    auto suggestion = ComputeEditDistance<T>::getSuggestion(value, possibleValues);

    if(!suggestion.empty())
      diag << ", " << suggestion;
    else if(!possibleValues.empty())
      diag << ", possible values " << RangeToString()(possibleValues);
  }
  return diag;
}

static std::string remove_fileextension(std::string fullName, std::string extension) {
  std::string truncation = "";
  std::size_t pos = 0;
  while((pos = fullName.find(extension)) != std::string::npos) {
    truncation += fullName.substr(0, pos);
    fullName.erase(0, pos + extension.length());
  }
  return truncation;
}

DawnCompiler::DawnCompiler(Options* options) : diagnostics_(make_unique<DiagnosticsEngine>()) {
  options_ = options ? make_unique<Options>(*options) : make_unique<Options>();
}

std::unique_ptr<OptimizerContext> DawnCompiler::runOptimizer(std::shared_ptr<SIR> const& SIR) {
  // -reorder
  using ReorderStrategyKind = ReorderStrategy::ReorderStrategyKind;
  ReorderStrategyKind reorderStrategy = StringSwitch<ReorderStrategyKind>(options_->ReorderStrategy)
                                            .Case("none", ReorderStrategyKind::RK_None)
                                            .Case("greedy", ReorderStrategyKind::RK_Greedy)
                                            .Case("scut", ReorderStrategyKind::RK_Partitioning)
                                            .Default(ReorderStrategyKind::RK_Unknown);

  if(reorderStrategy == ReorderStrategyKind::RK_Unknown) {
    diagnostics_->report(
        buildDiag("-reorder", options_->ReorderStrategy, "", {"none", "greedy", "scut"}));
    return nullptr;
  }

  using MultistageSplitStrategy = PassMultiStageSplitter::MultiStageSplittingStrategy;
  MultistageSplitStrategy mssSplitStrategy;
  if(options_->MaxCutMSS) {
    mssSplitStrategy = MultistageSplitStrategy::SS_MaxCut;
  } else {
    mssSplitStrategy = MultistageSplitStrategy::SS_Optimized;
  }

  // -max-fields
  int maxFields = options_->MaxFieldsPerStencil;

  IIRSerializer::SerializationKind serializationKind = IIRSerializer::SK_Json;
  if(options_->SerializeIIR) { /*|| (options_->LoadSerialized != "")) {*/
    if(options_->IIRFormat == "json") {
      serializationKind = IIRSerializer::SK_Json;
    } else if(options_->IIRFormat == "byte") {
      serializationKind = IIRSerializer::SK_Byte;

    } else {
      dawn_unreachable("Unknown SIRFormat option");
    }
  }

  // Initialize optimizer
  std::unique_ptr<OptimizerContext> optimizer =
      make_unique<OptimizerContext>(getDiagnostics(), getOptions(), SIR);
  PassManager& passManager = optimizer->getPassManager();

  // Setup pass interface
  optimizer->checkAndPushBack<PassInlining>(true, PassInlining::IK_InlineProcedures);
  // This pass is currently broken and needs to be redesigned before it can be enabled
  //  optimizer->checkAndPushBack<PassTemporaryFirstAccss>();
  optimizer->checkAndPushBack<PassFieldVersioning>();
  optimizer->checkAndPushBack<PassSSA>();
  optimizer->checkAndPushBack<PassMultiStageSplitter>(mssSplitStrategy);
  optimizer->checkAndPushBack<PassStageSplitter>();
  optimizer->checkAndPushBack<PassPrintStencilGraph>();
  optimizer->checkAndPushBack<PassTemporaryType>();
  optimizer->checkAndPushBack<PassSetStageName>();
  optimizer->checkAndPushBack<PassSetStageGraph>();
  optimizer->checkAndPushBack<PassStageReordering>(reorderStrategy);
  optimizer->checkAndPushBack<PassStageMerger>();
  optimizer->checkAndPushBack<PassStencilSplitter>(maxFields);
  optimizer->checkAndPushBack<PassTemporaryType>();
  optimizer->checkAndPushBack<PassTemporaryMerger>();
  optimizer->checkAndPushBack<PassInlining>(
      (getOptions().InlineSF || getOptions().PassTmpToFunction),
      PassInlining::IK_ComputationsOnTheFly);
  optimizer->checkAndPushBack<PassTemporaryToStencilFunction>();
  optimizer->checkAndPushBack<PassSetNonTempCaches>();
  optimizer->checkAndPushBack<PassSetCaches>();
  optimizer->checkAndPushBack<PassComputeStageExtents>();
  optimizer->checkAndPushBack<PassSetBoundaryCondition>();
  optimizer->checkAndPushBack<PassSetBlockSize>();
  optimizer->checkAndPushBack<PassDataLocalityMetric>();
  optimizer->checkAndPushBack<PassSetSyncStage>();

  DAWN_LOG(INFO) << "All the passes ran with the current command line arugments:";
  for(const auto& a : passManager.getPasses()) {
    DAWN_LOG(INFO) << a->getName();
  }
  // Run optimization passes
  for(auto& stencil : optimizer->getStencilInstantiationMap()) {
    std::shared_ptr<iir::StencilInstantiation> instantiation = stencil.second;
    DAWN_LOG(INFO) << "Starting Optimization and Analysis passes for `" << instantiation->getName()
                   << "` ...";
    if(!passManager.runAllPassesOnStecilInstantiation(instantiation))
      return nullptr;
    DAWN_LOG(INFO) << "Done with Optimization and Analysis passes for `" << instantiation->getName()
                   << "`";

    if(options_->SerializeIIR) {
      IIRSerializer::serialize(
          remove_fileextension(instantiation->getMetaData().fileName_, ".cpp") + ".iir",
          instantiation, serializationKind);
    }

    stencil.second = instantiation;
  }

  return optimizer;
}

std::unique_ptr<codegen::TranslationUnit> DawnCompiler::compile(const std::shared_ptr<SIR>& SIR) {
  diagnostics_->clear();
  diagnostics_->setFilename(SIR->Filename);

  // Check if options are valid

  // -max-halo
  if(options_->MaxHaloPoints < 0) {
    diagnostics_->report(buildDiag("-max-halo", options_->MaxHaloPoints,
                                   "maximum number of allowed halo points must be >= 0"));
    return nullptr;
  }

  // Initialize optimizer
  auto optimizer = runOptimizer(SIR);

  if(diagnostics_->hasErrors()) {
    DAWN_LOG(INFO) << "Errors occured. Skipping code generation.";
    return nullptr;
  }

  // Generate code
  std::unique_ptr<codegen::CodeGen> CG;

  if(options_->Backend == "gridtools") {
    CG = make_unique<codegen::gt::GTCodeGen>(optimizer.get());
  } else if(options_->Backend == "c++-naive") {
    CG = make_unique<codegen::cxxnaive::CXXNaiveCodeGen>(optimizer.get());
  } else if(options_->Backend == "cuda") {
    CG = make_unique<codegen::cuda::CudaCodeGen>(optimizer.get());
  } else if(options_->Backend == "c++-opt") {
    dawn_unreachable("GTClangOptCXX not supported yet");
  } else {
    diagnostics_->report(buildDiag("-backend", options_->Backend,
                                   "backend options must be : " +
                                       dawn::RangeToString(", ", "", "")(std::vector<std::string>{
                                           "gridtools", "c++-naive", "c++-opt"})));
    return nullptr;
  }

  return CG->generateCode();
}

const DiagnosticsEngine& DawnCompiler::getDiagnostics() const { return *diagnostics_.get(); }
DiagnosticsEngine& DawnCompiler::getDiagnostics() { return *diagnostics_.get(); }

const Options& DawnCompiler::getOptions() const { return *options_.get(); }
Options& DawnCompiler::getOptions() { return *options_.get(); }

} // namespace dawn
<|endoftext|>


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

#include <boost/thread/thread.hpp>
#include <boost/make_shared.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/io/pcd_io.h>
#include <pcl/io/openni_camera/openni_driver.h>
#include <pcl/filters/fast_voxel_grid.h>
#include <pcl/features/boundary.h>
#include <pcl/features/integral_image_normal.h>
#include <pcl/console/parse.h>
#include <pcl/common/time.h>
#include <pcl/visualization/cloud_viewer.h>

typedef pcl::visualization::PointCloudColorHandler<sensor_msgs::PointCloud2> ColorHandler;
typedef ColorHandler::Ptr ColorHandlerPtr;
typedef ColorHandler::ConstPtr ColorHandlerConstPtr;

#define FPS_CALC(_WHAT_) \
do \
{ \
    static unsigned count = 0;\
    static double last = pcl::getTime ();\
    double now = pcl::getTime (); \
    ++count; \
    if (now - last >= 1.0) \
    { \
      std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" <<  std::endl; \
      count = 0; \
      last = now; \
    } \
}while(false)

class OpenNIIntegralImageNormalEstimation
{
  public:
    typedef pcl::PointCloud<pcl::PointXYZRGBNormal> Cloud;
    typedef typename Cloud::Ptr CloudPtr;
    typedef typename Cloud::ConstPtr CloudConstPtr;

    OpenNIIntegralImageNormalEstimation (const std::string& device_id = "")
      : viewer ("PCL OpenNI NormalEstimation Viewer")
    , device_id_(device_id)
    {
      ne_.setNormalEstimationMethod (ne_.AVERAGE_3D_GRADIENT);
      //ne_.setNormalEstimationMethod (ne_.COVARIANCE_MATRIX);
      ne_.setRectSize (10, 10);
      new_cloud_ = false;

      pass_.setFilterFieldName ("z");
      pass_.setFilterLimits (0.0, 1.0);
      pass_.setDownsampleAllData (true);
      pass_.setLeafSize (0.005, 0.005, 0.005);

      typename pcl::OrganizedDataIndex<pcl::PointXYZRGBNormal>::Ptr tree (new pcl::OrganizedDataIndex<pcl::PointXYZRGBNormal>);
      be_.setRadiusSearch (0.02);
      be_.setSearchMethod (tree);
    }

    void
    cloud_cb (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr& cloud)
    {
      boost::mutex::scoped_lock lock (mtx_);
      //lock while we set our cloud;
      FPS_CALC ("computation");

      cloud_.reset (new pcl::PointCloud<pcl::PointXYZRGBNormal>);

      // Estimate surface normals
      ne_.setInputCloud (cloud);
      ne_.compute (*cloud_);
      copyPointCloud (*cloud, *cloud_);

//      cloud_pass_.reset (new pcl::PointCloud<pcl::PointXYZRGBNormal>);
      // Passthrough
//      pass_.setInputCloud (cloud_);
//      pass_.filter (*cloud_pass_);

      be_.setInputCloud (cloud_);
      be_.setInputNormals (cloud_);
      boundaries_.reset (new pcl::PointCloud<pcl::Boundary>);
      be_.compute (*boundaries_);

      new_cloud_ = true;
    }

    void
    viz_cb (pcl::visualization::PCLVisualizer& viz)
    {
      boost::mutex::scoped_lock lock (mtx_);
      if (!cloud_)
      {
        boost::this_thread::sleep(boost::posix_time::seconds(1));
        return;
      }

      // Render the data
      if (new_cloud_ && cloud_ && boundaries_)
      {
        CloudPtr temp_cloud;
        temp_cloud.swap (cloud_); //here we set cloud_ to null, so that

//        if (!viz.updatePointCloud<pcl::PointXYZRGBNormal> (temp_cloud, "OpenNICloud"))
//        {
//          viz.addPointCloud<pcl::PointXYZRGBNormal> (temp_cloud, "OpenNICloud");
//          viz.resetCameraViewpoint ("OpenNICloud");
//        }

        viz.removePointCloud ("normalcloud");
        sensor_msgs::PointCloud2::Ptr cloud2 (new sensor_msgs::PointCloud2);
        pcl::toROSMsg (*boundaries_, *cloud2);
        ColorHandlerConstPtr color_handler (new pcl::visualization::PointCloudColorHandlerGenericField<sensor_msgs::PointCloud2> (cloud2, "boundary_point"));
        viz.addPointCloud<pcl::PointXYZRGBNormal> (temp_cloud, color_handler, "normalcloud");
        viz.resetCameraViewpoint ("normalcloud");
        new_cloud_ = false;
      }
    }

    void
    run ()
    {
      pcl::Grabber* interface = new pcl::OpenNIGrabber (device_id_);

      boost::function<void (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &)> f = boost::bind (&OpenNIIntegralImageNormalEstimation::cloud_cb, this, _1);
      boost::signals2::connection c = interface->registerCallback (f);

      viewer.runOnVisualizationThread (boost::bind(&OpenNIIntegralImageNormalEstimation::viz_cb, this, _1), "viz_cb");

      interface->start ();

      while (!viewer.wasStopped ())
      {
        boost::this_thread::sleep(boost::posix_time::seconds(1));
      }

      interface->stop ();
    }

    pcl::FastVoxelGrid<pcl::PointXYZRGBNormal> pass_;
    pcl::IntegralImageNormalEstimation<pcl::PointXYZRGB, pcl::PointXYZRGBNormal> ne_;
    pcl::BoundaryEstimation<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal, pcl::Boundary> be_;
    pcl::visualization::CloudViewer viewer;
    std::string device_id_;
    boost::mutex mtx_;
    // Data
    pcl::PointCloud<pcl::Boundary>::Ptr boundaries_;
    CloudPtr cloud_, cloud_pass_;
    bool new_cloud_;
};

void
usage (char ** argv)
{
  std::cout << "usage: " << argv[0] << " <device_id> <options>\n\n";

  openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
  if (driver.getNumberDevices () > 0)
  {
    for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx)
    {
      cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx)
              << ", connected: " << (int)driver.getBus (deviceIdx) << " @ " << (int)driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl;
      cout << "device_id may be #1, #2, ... for the first second etc device in the list or" << endl
           << "                 bus@address for the device connected to a specific usb-bus / address combination (wotks only in Linux) or" << endl
           << "                 <serial-number> (only in Linux and for devices which provide serial numbers)"  << endl;
    }
  }
  else
    cout << "No devices connected." << endl;
}

int
main (int argc, char ** argv)
{
  std::string arg;
  if (argc > 1)
    arg = std::string (argv[1]);

  if (arg == "--help" || arg == "-h")
  {
    usage (argv);
    return 1;
  }

  pcl::OpenNIGrabber grabber ("");
  if (grabber.providesCallback<pcl::OpenNIGrabber::sig_cb_openni_point_cloud_rgb> ())
  {
    OpenNIIntegralImageNormalEstimation v ("");
    v.run ();
  }
  else
    PCL_ERROR ("The input device does not provide a PointXYZRGB mode.\n");

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

#include <boost/thread/thread.hpp>
#include <boost/make_shared.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/io/pcd_io.h>
#include <pcl/io/openni_camera/openni_driver.h>
#include <pcl/filters/fast_voxel_grid.h>
#include <pcl/features/boundary.h>
#include <pcl/features/integral_image_normal.h>
#include <pcl/console/parse.h>
#include <pcl/common/time.h>
#include <pcl/visualization/cloud_viewer.h>

typedef pcl::visualization::PointCloudColorHandler<sensor_msgs::PointCloud2> ColorHandler;
typedef ColorHandler::Ptr ColorHandlerPtr;
typedef ColorHandler::ConstPtr ColorHandlerConstPtr;

#define FPS_CALC(_WHAT_) \
do \
{ \
    static unsigned count = 0;\
    static double last = pcl::getTime ();\
    double now = pcl::getTime (); \
    ++count; \
    if (now - last >= 1.0) \
    { \
      std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" <<  std::endl; \
      count = 0; \
      last = now; \
    } \
}while(false)

class OpenNIIntegralImageNormalEstimation
{
  public:
    typedef pcl::PointCloud<pcl::PointXYZRGBNormal> Cloud;
    typedef Cloud::Ptr CloudPtr;
    typedef Cloud::ConstPtr CloudConstPtr;

    OpenNIIntegralImageNormalEstimation (const std::string& device_id = "")
      : viewer ("PCL OpenNI NormalEstimation Viewer")
    , device_id_(device_id)
    {
      ne_.setNormalEstimationMethod (ne_.AVERAGE_3D_GRADIENT);
      //ne_.setNormalEstimationMethod (ne_.COVARIANCE_MATRIX);
      ne_.setRectSize (10, 10);
      new_cloud_ = false;

      pass_.setFilterFieldName ("z");
      pass_.setFilterLimits (0.0, 1.0);
      pass_.setDownsampleAllData (true);
      pass_.setLeafSize (0.005, 0.005, 0.005);

      pcl::OrganizedDataIndex<pcl::PointXYZRGBNormal>::Ptr tree (new pcl::OrganizedDataIndex<pcl::PointXYZRGBNormal>);
      be_.setRadiusSearch (0.02);
      be_.setSearchMethod (tree);
    }

    void
    cloud_cb (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr& cloud)
    {
      boost::mutex::scoped_lock lock (mtx_);
      //lock while we set our cloud;
      FPS_CALC ("computation");

      cloud_.reset (new pcl::PointCloud<pcl::PointXYZRGBNormal>);

      // Estimate surface normals
      ne_.setInputCloud (cloud);
      ne_.compute (*cloud_);
      copyPointCloud (*cloud, *cloud_);

//      cloud_pass_.reset (new pcl::PointCloud<pcl::PointXYZRGBNormal>);
      // Passthrough
//      pass_.setInputCloud (cloud_);
//      pass_.filter (*cloud_pass_);

      be_.setInputCloud (cloud_);
      be_.setInputNormals (cloud_);
      boundaries_.reset (new pcl::PointCloud<pcl::Boundary>);
      be_.compute (*boundaries_);

      new_cloud_ = true;
    }

    void
    viz_cb (pcl::visualization::PCLVisualizer& viz)
    {
      boost::mutex::scoped_lock lock (mtx_);
      if (!cloud_)
      {
        boost::this_thread::sleep(boost::posix_time::seconds(1));
        return;
      }

      // Render the data
      if (new_cloud_ && cloud_ && boundaries_)
      {
        CloudPtr temp_cloud;
        temp_cloud.swap (cloud_); //here we set cloud_ to null, so that

//        if (!viz.updatePointCloud<pcl::PointXYZRGBNormal> (temp_cloud, "OpenNICloud"))
//        {
//          viz.addPointCloud<pcl::PointXYZRGBNormal> (temp_cloud, "OpenNICloud");
//          viz.resetCameraViewpoint ("OpenNICloud");
//        }

        viz.removePointCloud ("normalcloud");
        sensor_msgs::PointCloud2::Ptr cloud2 (new sensor_msgs::PointCloud2);
        pcl::toROSMsg (*boundaries_, *cloud2);
        ColorHandlerConstPtr color_handler (new pcl::visualization::PointCloudColorHandlerGenericField<sensor_msgs::PointCloud2> (cloud2, "boundary_point"));
        viz.addPointCloud<pcl::PointXYZRGBNormal> (temp_cloud, color_handler, "normalcloud");
        viz.resetCameraViewpoint ("normalcloud");
        new_cloud_ = false;
      }
    }

    void
    run ()
    {
      pcl::Grabber* interface = new pcl::OpenNIGrabber (device_id_);

      boost::function<void (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &)> f = boost::bind (&OpenNIIntegralImageNormalEstimation::cloud_cb, this, _1);
      boost::signals2::connection c = interface->registerCallback (f);

      viewer.runOnVisualizationThread (boost::bind(&OpenNIIntegralImageNormalEstimation::viz_cb, this, _1), "viz_cb");

      interface->start ();

      while (!viewer.wasStopped ())
      {
        boost::this_thread::sleep(boost::posix_time::seconds(1));
      }

      interface->stop ();
    }

    pcl::FastVoxelGrid<pcl::PointXYZRGBNormal> pass_;
    pcl::IntegralImageNormalEstimation<pcl::PointXYZRGB, pcl::PointXYZRGBNormal> ne_;
    pcl::BoundaryEstimation<pcl::PointXYZRGBNormal, pcl::PointXYZRGBNormal, pcl::Boundary> be_;
    pcl::visualization::CloudViewer viewer;
    std::string device_id_;
    boost::mutex mtx_;
    // Data
    pcl::PointCloud<pcl::Boundary>::Ptr boundaries_;
    CloudPtr cloud_, cloud_pass_;
    bool new_cloud_;
};

void
usage (char ** argv)
{
  std::cout << "usage: " << argv[0] << " <device_id> <options>\n\n";

  openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
  if (driver.getNumberDevices () > 0)
  {
    for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx)
    {
      cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx)
              << ", connected: " << (int)driver.getBus (deviceIdx) << " @ " << (int)driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl;
      cout << "device_id may be #1, #2, ... for the first second etc device in the list or" << endl
           << "                 bus@address for the device connected to a specific usb-bus / address combination (wotks only in Linux) or" << endl
           << "                 <serial-number> (only in Linux and for devices which provide serial numbers)"  << endl;
    }
  }
  else
    cout << "No devices connected." << endl;
}

int
main (int argc, char ** argv)
{
  std::string arg;
  if (argc > 1)
    arg = std::string (argv[1]);

  if (arg == "--help" || arg == "-h")
  {
    usage (argv);
    return 1;
  }

  pcl::OpenNIGrabber grabber ("");
  if (grabber.providesCallback<pcl::OpenNIGrabber::sig_cb_openni_point_cloud_rgb> ())
  {
    OpenNIIntegralImageNormalEstimation v ("");
    v.run ();
  }
  else
    PCL_ERROR ("The input device does not provide a PointXYZRGB mode.\n");

  return (0);
}
<|endoftext|>


<commit_before>//********************************************************************
//     Example of the reconstruction that generates the ESD
// Input files:
//   a) file containing the ITS clusters
//      (the AliITSFindClustersV2.C macro can be used to generate it)
//   b) file containing the TPC clusters
//      (the AliTPCFindClusters.C macro can be used to generate it)
//   c) file containing the TRD clusters
//      (the AliTRDdigits2cluster.C macro can be used to generate it)
//   d) file containing the TOF digits
//      (the AliTOFSDigits2Digits.C macro can be used to generate it)
// Ouput file:
//      AliESDs.root containing the ESD events
//
// Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
//********************************************************************

#if !defined(__CINT__) || defined(__MAKECINT__)
  #include <Riostream.h>
  #include "TFile.h"
  #include "TSystem.h"
  #include "TStopwatch.h"
  #include "TArrayF.h"

  #include "AliMagF.h"
  #include "AliRun.h"
  #include "AliRunLoader.h"
  #include "AliLoader.h"
  #include "AliHeader.h"
  #include "AliGenEventHeader.h"

  #include "AliESD.h"
  #include "AliESDpid.h"

  #include "AliITS.h"
  #include "AliITSgeom.h"
  #include "AliITStrackerV2.h"
  #include "AliV0vertexer.h"
  #include "AliCascadeVertexer.h"
  #include "AliITSpidESD.h"
  #include "AliITSLoader.h"

  #include "AliTPCParam.h"
  #include "AliTPCtracker.h"
  #include "AliTPCpidESD.h"
  #include "AliTPCLoader.h"

  #include "AliTRDtracker.h"
  #include "AliTRDPartID.h"

  #include "AliTOFpidESD.h"
  #include "AliTOF.h"
  #include "AliTOFGeometry.h"
#endif

extern AliRun *gAlice;
extern TFile *gFile;

Int_t AliESDtest(Int_t nev=1,Int_t run=0) {

/**** Initialization of the NewIO *******/

   if (gAlice) {
      delete gAlice->GetRunLoader();
      delete gAlice;
      gAlice=0;
   }

   AliRunLoader *rl = AliRunLoader::Open("galice.root");
   if (rl == 0x0) {
      cerr<<"Can not open session"<<endl;
      return 1;
   }
   Int_t retval = rl->LoadgAlice();
   if (retval) {
      cerr<<"AliESDtest.C : LoadgAlice returned error"<<endl;
      delete rl;
      return 1;
   }
   retval = rl->LoadHeader();
   if (retval) {
      cerr<<"AliESDtest.C : LoadHeader returned error"<<endl;
      delete rl;
      return 2;
   }
   gAlice=rl->GetAliRun();

   AliKalmanTrack::SetConvConst(
      1000/0.299792458/gAlice->Field()->SolenoidField()
   );

/**** The ITS corner ********************/

   AliITSLoader* itsl = (AliITSLoader*)rl->GetLoader("ITSLoader");
   if (itsl == 0x0) {
      cerr<<"AliESDtest.C : Can not get the ITS loader"<<endl;
      return 3;
   }
   itsl->LoadRecPoints("read");

   AliITS *dITS = (AliITS*)gAlice->GetDetector("ITS");
   if (!dITS) {
      cerr<<"AliESDtest.C : Can not find the ITS detector !"<<endl;
      return 4;
   }
   AliITSgeom *geom = dITS->GetITSgeom();

   //An instance of the ITS tracker
   AliITStrackerV2 itsTracker(geom);

   //An instance of the ITS PID maker
   Double_t parITS[]={35.5,0.11,10.};
   AliITSpidESD itsPID(parITS);

   //An instance of the V0 finder
   Double_t cuts[]={33,  // max. allowed chi2
                    0.16,// min. allowed negative daughter's impact parameter
                    0.05,// min. allowed positive daughter's impact parameter
                    0.080,// max. allowed DCA between the daughter tracks
                    0.998,// max. allowed cosine of V0's pointing angle
                    0.9,  // min. radius of the fiducial volume
                    2.9   // max. radius of the fiducial volume
                   };
   AliV0vertexer vtxer(cuts);

   Double_t cts[]={33.,    // max. allowed chi2
                    0.05,   // min. allowed V0 impact parameter
                    0.008,  // window around the Lambda mass
                    0.035,  // min. allowed bachelor's impact parameter
                    0.10,   // max. allowed DCA between a V0 and a track
                    0.9985, //max. allowed cosine of the cascade pointing angle
                    0.9,    // min. radius of the fiducial volume
                    2.9     // max. radius of the fiducial volume
                   };
   AliCascadeVertexer cvtxer=AliCascadeVertexer(cts);

/**** The TPC corner ********************/

   AliTPCLoader* tpcl = (AliTPCLoader*)rl->GetLoader("TPCLoader");
   if (tpcl == 0x0) {
      cerr<<"AliESDtest.C : can not get the TPC loader"<<endl;
      return 5;
   }
   tpcl->LoadRecPoints("read");

   rl->CdGAFile();
   AliTPCParam *par=(AliTPCParam *)gDirectory->Get("75x40_100x60_150x60");
   if (!par) {
      cerr<<"TPC parameters have not been found !\n";
      return 6;
   }

   //An instance of the TPC tracker
   AliTPCtracker tpcTracker(par);

   //An instance of the TPC PID maker
   Double_t parTPC[]={45.0,0.08,10.};
   AliTPCpidESD tpcPID(parTPC);

/**** The TRD corner ********************/

   AliLoader* trdl = rl->GetLoader("TRDLoader");
   if (trdl == 0x0) {
      cerr<<"AliESDtest.C : can not get the TRD loader"<<endl;
      return 5;
   }
   trdl->LoadRecPoints("read");

   //An instance of the TRD tracker
   rl->CdGAFile();
   AliTRDtracker trdTracker(gFile);  //galice.root file

/*
   //An instance of the TRD PID maker
   TFile* pidFile = TFile::Open("pid.root");
   if (!pidFile->IsOpen()) {
     cerr << "Can't get pid.root !\n";
     return 7;
   }
   AliTRDPartID* trdPID = (AliTRDPartID*) pidFile->Get("AliTRDPartID");
   if (!trdPID) {
     cerr << "Can't get PID object !\n";
     return 8;
   }
*/

/**** The TOF corner ********************/
   AliTOF *dTOF = (AliTOF*)gAlice->GetDetector("TOF");
   if (!dTOF) {
      cerr<<"AliESDtest.C : Can not find the TOF detector !"<<endl;
      return 4;
   }
   AliTOFGeometry *tofGeo = dTOF->GetGeometry();
   if (!tofGeo) {
      cerr<<"AliESDtest.C : Can not find the TOF geometry !"<<endl;
      return 4;
   }

   AliLoader* tofl = rl->GetLoader("TOFLoader");
   if (tofl == 0x0) {
      cerr<<"AliESDtest.C : can not get the TOF loader"<<endl;
      return 5;
   }
   tofl->LoadDigits("read");

   //Instance of the TOF PID maker
   Double_t parTOF[]={130.,5.};
   AliTOFpidESD tofPID(parTOF);

   //rl->UnloadgAlice();

   TFile *ef=TFile::Open("AliESDs.root","RECREATE");
   if (!ef->IsOpen()) {cerr<<"Can't AliESDs.root !\n"; return 1;}

   TStopwatch timer;
   Int_t rc=0;
   if (nev>rl->GetNumberOfEvents()) nev=rl->GetNumberOfEvents();
   //The loop over events
   for (Int_t i=0; i<nev; i++) {
     cerr<<"\n\nProcessing event number : "<<i<<endl;
     AliESD *event=new AliESD();
     event->SetRunNumber(run);
     event->SetEventNumber(i);
     event->SetMagneticField(gAlice->Field()->SolenoidField());

     rl->GetEvent(i);

//***** Primary vertex reconstruction (MC vertex position, for the moment)
     TArrayF v(3);
     rl->GetHeader()->GenEventHeader()->PrimaryVertex(v);
     Double_t vtx[3]={v[0],v[1],v[2]};
     Double_t cvtx[6]={
       0.005,
       0.000, 0.005,
       0.000, 0.000, 0.010
     };
     event->SetVertex(vtx,cvtx);
     cvtx[1]=cvtx[0]; cvtx[2]=cvtx[5]; //trackers use only the diag.elements

//***** Initial path towards the primary vertex
     tpcTracker.SetVertex(vtx,cvtx);
     TTree *tpcTree=tpcl->TreeR();
     if (!tpcTree) {
        cerr<<"Can't get the TPC cluster tree !\n";
        return 4;
     }
     tpcTracker.LoadClusters(tpcTree);
     rc+=tpcTracker.Clusters2Tracks(event);
     tpcPID.MakePID(event);                 // preliminary PID
     AliESDpid::MakePID(event);             // for the ITS tracker

     itsTracker.SetVertex(vtx,cvtx);
     TTree *itsTree=itsl->TreeR();
     if (!itsTree) {
        cerr<<"Can't get the ITS cluster tree !\n";
        return 4;
     }
     itsTracker.LoadClusters(itsTree);
     rc+=itsTracker.Clusters2Tracks(event);

//***** Back propagation towards the outer barrel detectors
     rc+=itsTracker.PropagateBack(event);

     rc+=tpcTracker.PropagateBack(event);

     TTree *trdTree=trdl->TreeR();
     if (!trdTree) {
        cerr<<"Can't get the TRD cluster tree !\n";
        return 4;
     }
     trdTracker.LoadClusters(trdTree);
     rc+=trdTracker.PropagateBack(event);

/*
     for (Int_t iTrack = 0; iTrack < event->GetNumberOfTracks(); iTrack++) {
       AliESDtrack* track = event->GetTrack(iTrack);
       trdPID->MakePID(track);
     }
*/

     TTree *tofTree=tofl->TreeD();
     if (!tofTree) {
        cerr<<"Can't get the TOF cluster tree !\n";
        return 4;
     }
     tofPID.LoadClusters(tofTree,tofGeo);
     tofPID.MakePID(event);
     tofPID.UnloadClusters();

//***** Now the final refit at the primary vertex...
     rc+=trdTracker.RefitInward(event);
     trdTracker.UnloadClusters();

     rc+=tpcTracker.RefitInward(event);
     tpcTracker.UnloadClusters();
     tpcPID.MakePID(event);

     rc+=itsTracker.RefitInward(event);
     itsTracker.UnloadClusters();
     itsPID.MakePID(event);

//***** Here is the combined PID
     AliESDpid::MakePID(event);

//***** Hyperon reconstruction
     vtxer.SetVertex(vtx);
     rc+=vtxer.Tracks2V0vertices(event);            // V0 finding
     rc+=cvtxer.V0sTracks2CascadeVertices(event);   // cascade finding

//***** Some final manipulations with this event
     if (rc==0) {
        Char_t ename[100];
        sprintf(ename,"%d",i);
	ef->cd();
        if (!event->Write(ename)) rc++;
     }
     if (rc) {
        cerr<<"Something bad happened...\n";
     }
     delete event;
   }
   timer.Stop(); timer.Print();

   //pidFile->Close();

   delete par;

   ef->Close();

   delete rl;

   return rc;
}
<commit_msg>Check points introduced (Yu.Belikov)<commit_after>//********************************************************************
//     Example of the reconstruction that generates the ESD
// Input files:
//   a) file containing the ITS clusters
//      (the AliITSFindClustersV2.C macro can be used to generate it)
//   b) file containing the TPC clusters
//      (the AliTPCFindClusters.C macro can be used to generate it)
//   c) file containing the TRD clusters
//      (the AliTRDdigits2cluster.C macro can be used to generate it)
//   d) file containing the TOF digits
//      (the AliTOFSDigits2Digits.C macro can be used to generate it)
// Ouput file:
//      AliESDs.root containing the ESD events
//
// Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
//********************************************************************

#if !defined(__CINT__) || defined(__MAKECINT__)
  #include <Riostream.h>
  #include "TFile.h"
  #include "TSystem.h"
  #include "TStopwatch.h"
  #include "TArrayF.h"

  #include "AliMagF.h"
  #include "AliRun.h"
  #include "AliRunLoader.h"
  #include "AliLoader.h"
  #include "AliHeader.h"
  #include "AliGenEventHeader.h"

  #include "AliESD.h"
  #include "AliESDpid.h"

  #include "AliITS.h"
  #include "AliITSgeom.h"
  #include "AliITStrackerV2.h"
  #include "AliV0vertexer.h"
  #include "AliCascadeVertexer.h"
  #include "AliITSpidESD.h"
  #include "AliITSLoader.h"

  #include "AliTPCParam.h"
  #include "AliTPCtracker.h"
  #include "AliTPCpidESD.h"
  #include "AliTPCLoader.h"

  #include "AliTRDtracker.h"
  #include "AliTRDPartID.h"

  #include "AliTOFpidESD.h"
  #include "AliTOF.h"
  #include "AliTOFGeometry.h"
#endif

extern AliRun *gAlice;
extern TFile *gFile;

Int_t AliESDtest(Int_t nev=1,Int_t run=0) {

/**** Initialization of the NewIO *******/

   if (gAlice) {
      delete gAlice->GetRunLoader();
      delete gAlice;
      gAlice=0;
   }

   AliRunLoader *rl = AliRunLoader::Open("galice.root");
   if (rl == 0x0) {
      cerr<<"Can not open session"<<endl;
      return 1;
   }
   Int_t retval = rl->LoadgAlice();
   if (retval) {
      cerr<<"AliESDtest.C : LoadgAlice returned error"<<endl;
      delete rl;
      return 1;
   }
   retval = rl->LoadHeader();
   if (retval) {
      cerr<<"AliESDtest.C : LoadHeader returned error"<<endl;
      delete rl;
      return 2;
   }
   gAlice=rl->GetAliRun();

   AliKalmanTrack::SetConvConst(
      1000/0.299792458/gAlice->Field()->SolenoidField()
   );

/**** The ITS corner ********************/

   AliITSLoader* itsl = (AliITSLoader*)rl->GetLoader("ITSLoader");
   if (itsl == 0x0) {
      cerr<<"AliESDtest.C : Can not get the ITS loader"<<endl;
      return 3;
   }
   itsl->LoadRecPoints("read");

   AliITS *dITS = (AliITS*)gAlice->GetDetector("ITS");
   if (!dITS) {
      cerr<<"AliESDtest.C : Can not find the ITS detector !"<<endl;
      return 4;
   }
   AliITSgeom *geom = dITS->GetITSgeom();

   //An instance of the ITS tracker
   AliITStrackerV2 itsTracker(geom);

   //An instance of the ITS PID maker
   Double_t parITS[]={35.5,0.11,10.};
   AliITSpidESD itsPID(parITS);

   //An instance of the V0 finder
   Double_t cuts[]={33,  // max. allowed chi2
                    0.16,// min. allowed negative daughter's impact parameter
                    0.05,// min. allowed positive daughter's impact parameter
                    0.080,// max. allowed DCA between the daughter tracks
                    0.998,// max. allowed cosine of V0's pointing angle
                    0.9,  // min. radius of the fiducial volume
                    2.9   // max. radius of the fiducial volume
                   };
   AliV0vertexer vtxer(cuts);

   Double_t cts[]={33.,    // max. allowed chi2
                    0.05,   // min. allowed V0 impact parameter
                    0.008,  // window around the Lambda mass
                    0.035,  // min. allowed bachelor's impact parameter
                    0.10,   // max. allowed DCA between a V0 and a track
                    0.9985, //max. allowed cosine of the cascade pointing angle
                    0.9,    // min. radius of the fiducial volume
                    2.9     // max. radius of the fiducial volume
                   };
   AliCascadeVertexer cvtxer=AliCascadeVertexer(cts);

/**** The TPC corner ********************/

   AliTPCLoader* tpcl = (AliTPCLoader*)rl->GetLoader("TPCLoader");
   if (tpcl == 0x0) {
      cerr<<"AliESDtest.C : can not get the TPC loader"<<endl;
      return 5;
   }
   tpcl->LoadRecPoints("read");

   rl->CdGAFile();
   AliTPCParam *par=(AliTPCParam *)gDirectory->Get("75x40_100x60_150x60");
   if (!par) {
      cerr<<"TPC parameters have not been found !\n";
      return 6;
   }

   //An instance of the TPC tracker
   AliTPCtracker tpcTracker(par);

   //An instance of the TPC PID maker
   Double_t parTPC[]={45.0,0.08,10.};
   AliTPCpidESD tpcPID(parTPC);

/**** The TRD corner ********************/

   AliLoader* trdl = rl->GetLoader("TRDLoader");
   if (trdl == 0x0) {
      cerr<<"AliESDtest.C : can not get the TRD loader"<<endl;
      return 5;
   }
   trdl->LoadRecPoints("read");

   //An instance of the TRD tracker
   rl->CdGAFile();
   AliTRDtracker trdTracker(gFile);  //galice.root file

/*
   //An instance of the TRD PID maker
   TFile* pidFile = TFile::Open("pid.root");
   if (!pidFile->IsOpen()) {
     cerr << "Can't get pid.root !\n";
     return 7;
   }
   AliTRDPartID* trdPID = (AliTRDPartID*) pidFile->Get("AliTRDPartID");
   if (!trdPID) {
     cerr << "Can't get PID object !\n";
     return 8;
   }
*/

/**** The TOF corner ********************/
   AliTOF *dTOF = (AliTOF*)gAlice->GetDetector("TOF");
   if (!dTOF) {
      cerr<<"AliESDtest.C : Can not find the TOF detector !"<<endl;
      return 4;
   }
   AliTOFGeometry *tofGeo = dTOF->GetGeometry();
   if (!tofGeo) {
      cerr<<"AliESDtest.C : Can not find the TOF geometry !"<<endl;
      return 4;
   }

   AliLoader* tofl = rl->GetLoader("TOFLoader");
   if (tofl == 0x0) {
      cerr<<"AliESDtest.C : can not get the TOF loader"<<endl;
      return 5;
   }
   tofl->LoadDigits("read");

   //Instance of the TOF PID maker
   Double_t parTOF[]={130.,5.};
   AliTOFpidESD tofPID(parTOF);

   //rl->UnloadgAlice();

   TFile *bf=TFile::Open("AliESDcheck.root","RECREATE");
   if (!bf || !bf->IsOpen()) {
      cerr<<"Can't open AliESDcheck.root !\n"; return 1;
   }
   TFile *ef=TFile::Open("AliESDs.root","RECREATE");
   if (!ef || !ef->IsOpen()) {cerr<<"Can't open AliESDs.root !\n"; return 2;}

   TStopwatch timer;
   Int_t rc=0;
   if (nev>rl->GetNumberOfEvents()) nev=rl->GetNumberOfEvents();
   //The loop over events
   for (Int_t i=0; i<nev; i++) {
     Char_t ename[100];

     cerr<<"\n\nProcessing event number : "<<i<<endl;
     AliESD *event=new AliESD();
     event->SetRunNumber(run);
     event->SetEventNumber(i);
     event->SetMagneticField(gAlice->Field()->SolenoidField());

     rl->GetEvent(i);

//***** Primary vertex reconstruction (MC vertex position, for the moment)
     TArrayF v(3);
     rl->GetHeader()->GenEventHeader()->PrimaryVertex(v);
     Double_t vtx[3]={v[0],v[1],v[2]};
     Double_t cvtx[6]={
       0.005,
       0.000, 0.005,
       0.000, 0.000, 0.010
     };
     event->SetVertex(vtx,cvtx);
     cvtx[1]=cvtx[0]; cvtx[2]=cvtx[5]; //trackers use only the diag.elements

//***** Initial path towards the primary vertex
     tpcTracker.SetVertex(vtx,cvtx);
     TTree *tpcTree=tpcl->TreeR();
     if (!tpcTree) {
        cerr<<"Can't get the TPC cluster tree !\n";
        return 4;
     }
     tpcTracker.LoadClusters(tpcTree);
     rc+=tpcTracker.Clusters2Tracks(event);
     tpcPID.MakePID(event);                 // preliminary PID
     AliESDpid::MakePID(event);             // for the ITS tracker

     itsTracker.SetVertex(vtx,cvtx);
     TTree *itsTree=itsl->TreeR();
     if (!itsTree) {
        cerr<<"Can't get the ITS cluster tree !\n";
        return 4;
     }
     itsTracker.LoadClusters(itsTree);
     rc+=itsTracker.Clusters2Tracks(event);

       //checkpoint
       bf->cd();
       sprintf(ename,"in%d",i);
       event->Write(ename); bf->Flush();
       ef->cd();

//***** Back propagation towards the outer barrel detectors
     rc+=itsTracker.PropagateBack(event);

     rc+=tpcTracker.PropagateBack(event);

     TTree *trdTree=trdl->TreeR();
     if (!trdTree) {
        cerr<<"Can't get the TRD cluster tree !\n";
        return 4;
     }
     trdTracker.LoadClusters(trdTree);
     rc+=trdTracker.PropagateBack(event);

/*
     for (Int_t iTrack = 0; iTrack < event->GetNumberOfTracks(); iTrack++) {
       AliESDtrack* track = event->GetTrack(iTrack);
       trdPID->MakePID(track);
     }
*/

     TTree *tofTree=tofl->TreeD();
     if (!tofTree) {
        cerr<<"Can't get the TOF cluster tree !\n";
        return 4;
     }
     tofPID.LoadClusters(tofTree,tofGeo);
     tofPID.MakePID(event);
     tofPID.UnloadClusters();

       //checkpoint
       bf->cd();
       strcat(ename,";*"); bf->Delete(ename);
       sprintf(ename,"out%d",i);
       event->Write(ename); bf->Flush();
       ef->cd();

//***** Now the final refit at the primary vertex...
     rc+=trdTracker.RefitInward(event);
     trdTracker.UnloadClusters();

     rc+=tpcTracker.RefitInward(event);
     tpcTracker.UnloadClusters();
     tpcPID.MakePID(event);

     rc+=itsTracker.RefitInward(event);
     itsTracker.UnloadClusters();
     itsPID.MakePID(event);

//***** Here is the combined PID
     AliESDpid::MakePID(event);

       //checkpoint
       bf->cd();
       strcat(ename,";*"); bf->Delete(ename);
       sprintf(ename,"refit%d",i);
       event->Write(ename); bf->Flush();
       ef->cd();

       bf->Close();

//***** Hyperon reconstruction
     vtxer.SetVertex(vtx);
     rc+=vtxer.Tracks2V0vertices(event);            // V0 finding
     rc+=cvtxer.V0sTracks2CascadeVertices(event);   // cascade finding

//***** Some final manipulations with this event
     if (rc==0) {
        sprintf(ename,"%d",i);
	ef->cd();
        if (!event->Write(ename)) rc++; ef->Flush();
        bf=TFile::Open("AliESDcheck.root","RECREATE");
     }
     if (rc) {
        cerr<<"Something bad happened...\n";
        bf=TFile::Open("AliESDcheck.root","UPDATE");
     }
     delete event;
   }
   timer.Stop(); timer.Print();

   //pidFile->Close();

   delete par;

   ef->Close();
   bf->Close();

   delete rl;

   return rc;
}
<|endoftext|>