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

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

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

=========================================================================*/
#include "ApplicationsWrapper/mvdApplicationsBrowser.h"

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)
#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperApplication.h"

//
// Monteverdi includes (sorted by alphabetic order)

namespace mvd
{
/*
  TRANSLATOR mvd::ApplicationsBrowser

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CONSTANTS                                                                 */

/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION                                             */

/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION                                              */

/*******************************************************************************/
ApplicationsBrowser
::ApplicationsBrowser( QObject* parent ) :
  QObject( parent ),
  m_AutoLoadPath("")
{
}

/*******************************************************************************/
ApplicationsBrowser
::~ApplicationsBrowser()
{
}

/*******************************************************************************/
void
ApplicationsBrowser
::SetAutoLoadPath(const std::string & itk_auto_load_path)
{
  m_AutoLoadPath = itk_auto_load_path;

  //
  // add the path
  otb::Wrapper::ApplicationRegistry::AddApplicationPath(m_AutoLoadPath);
}

/*******************************************************************************/
StringVector
ApplicationsBrowser
::GetAvailableApplications()
{
  //
  // get available application in search path
  StringVector appList(
    otb::Wrapper::ApplicationRegistry::GetAvailableApplications()
  );

  //
  // some verbosity
  // TODO : remove this verbosity later
  if ( appList.size() == 0 )
    {
    qWarning() << "Available OTB applications: NONE!";
    }
  else
    {
    qDebug() << "Available OTB applications:";

    for( StringVector::const_iterator it( appList.begin() );
	 it!=appList.end();
	 ++it )
      {
      qDebug() << "- " << it->c_str();
      }
    }

  return appList;
}

/*******************************************************************************/
StringVector
ApplicationsBrowser
::GetApplicationTags( const std::string& appName )
{
  //
  // instantiate the application using the factory
  otb::Wrapper::Application::Pointer application(
    otb::Wrapper::ApplicationRegistry::CreateApplication( appName )
  );

  if( application.IsNull() )
    return StringVector();

  //
  // get tags
  StringVector vtags( application->GetDocTags() );

  //
  // fill the OTBApps 'docName <-> name' map
  m_DocNameToNameMap[ application->GetDocName() ] = appName;

  return vtags;
}

/*******************************************************************************/
void
ApplicationsBrowser
::SearchAvailableApplicationsTags()
{
  //
  // clear previously filled map
  m_DocNameToNameMap.clear();

  //
  // get all the applications in the search path
  StringVector vapp = GetAvailableApplications();

  //
  // Fill the  map as following
  // - key   -> tag
  // - value -> list of applications having this tag
  ApplicationsTagContainer      outputContainer;
  StringVector::const_iterator  it = vapp.begin();

  while ( it != vapp.end() )
    {
    // get tags of current app
    StringVector ctags = GetApplicationTags( *it );

    // key will be the tag (easier for tree origanisation in )
    StringVector::const_iterator  itTag = ctags.begin();
    while ( itTag != ctags.end() )
      {

      // search for this tag in the output container
      ApplicationsTagContainer::iterator  pos = outputContainer.find( *itTag );
      if ( pos != outputContainer.end() )  // key found
        {
        //
        // append the application name (*it)
        (*pos).second.push_back(*it);
        }
      else
        {
        //
        // if tag not found in the container, add it
        std::pair< std::string, StringVector > currentAppTags;
        currentAppTags.first  = *itTag;
        currentAppTags.second.push_back( *it );
        outputContainer.insert( currentAppTags );
        }

      ++itTag;
      }

    ++it;
    }

  //
  // emit a signal with the ApplicationsTagContainer as
  // parameter
  emit AvailableApplicationsTagsChanged(outputContainer, m_DocNameToNameMap);
}

/*******************************************************************************/
/* SLOTS                                                                       */
/*******************************************************************************/

} // end namespace 'mvd'
<commit_msg>ENH: Applied patch from Otmane Lahlou which group untagged OTB-applications under the 'Unknown' tag.<commit_after>/*=========================================================================

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

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

=========================================================================*/
#include "ApplicationsWrapper/mvdApplicationsBrowser.h"
#include "Core/mvdAlgorithm.h"

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)
#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperApplication.h"

//
// Monteverdi includes (sorted by alphabetic order)

namespace mvd
{
/*
  TRANSLATOR mvd::ApplicationsBrowser

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CONSTANTS                                                                 */

/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION                                             */

/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION                                              */

/*******************************************************************************/
ApplicationsBrowser
::ApplicationsBrowser( QObject* parent ) :
  QObject( parent ),
  m_AutoLoadPath("")
{
}

/*******************************************************************************/
ApplicationsBrowser
::~ApplicationsBrowser()
{
}

/*******************************************************************************/
void
ApplicationsBrowser
::SetAutoLoadPath(const std::string & itk_auto_load_path)
{
  m_AutoLoadPath = itk_auto_load_path;

  //
  // add the path
  otb::Wrapper::ApplicationRegistry::AddApplicationPath(m_AutoLoadPath);
}

/*******************************************************************************/
StringVector
ApplicationsBrowser
::GetAvailableApplications()
{
  //
  // get available application in search path
  StringVector appList(
    otb::Wrapper::ApplicationRegistry::GetAvailableApplications()
  );

  //
  // some verbosity
  // TODO : remove this verbosity later
  if ( appList.size() == 0 )
    {
    qWarning() << "Available OTB applications: NONE!";
    }
  else
    {
    qDebug() << "Available OTB applications:";

    for( StringVector::const_iterator it( appList.begin() );
	 it!=appList.end();
	 ++it )
      {
      qDebug() << "- " << it->c_str();
      }
    }

  return appList;
}

/*******************************************************************************/
StringVector
ApplicationsBrowser
::GetApplicationTags( const std::string& appName )
{
  //
  // instantiate the application using the factory
  otb::Wrapper::Application::Pointer application(
    otb::Wrapper::ApplicationRegistry::CreateApplication( appName )
  );

  if( application.IsNull() )
    return StringVector();

  //
  // get tags
  StringVector vtags( application->GetDocTags() );

  //
  // fill the OTBApps 'docName <-> name' map
  m_DocNameToNameMap[ application->GetDocName() ] = appName;

  return vtags;
}

/*******************************************************************************/
void
ApplicationsBrowser
::SearchAvailableApplicationsTags()
{
  //
  // clear previously filled map
  m_DocNameToNameMap.clear();

  //
  // get all the applications in the search path
  StringVector vapp = GetAvailableApplications();

  //
  // Fill the  map as following
  // - key   -> tag
  // - value -> list of applications having this tag
  ApplicationsTagContainer      outputContainer;
  StringVector::const_iterator  it = vapp.begin();

  while ( it != vapp.end() )
    {
    // get tags of current app
    StringVector ctags = GetApplicationTags( *it );

    // case applications has no tag associated
    if (ctags.size() == 0 )
      {
      // add a default tag 'unknown'. The processing after remains
      // unchanged
      ctags.push_back( ToStdString(tr("Unknown")) );
      }

    // key will be the tag (easier for tree origanisation in )
    StringVector::const_iterator  itTag = ctags.begin();

    while ( itTag != ctags.end() )
      {

      // search for this tag in the output container
      ApplicationsTagContainer::iterator  pos = outputContainer.find( *itTag );
      if ( pos != outputContainer.end() )  // key found
        {
        //
        // append the application name (*it)
        (*pos).second.push_back(*it);
        }
      else
        {
        //
        // if tag not found in the container, add it
        std::pair< std::string, StringVector > currentAppTags;
        currentAppTags.first  = *itTag;
        currentAppTags.second.push_back( *it );
        outputContainer.insert( currentAppTags );
        }

      ++itTag;
      }

    ++it;
    }

  //
  // emit a signal with the ApplicationsTagContainer as
  // parameter
  emit AvailableApplicationsTagsChanged(outputContainer, m_DocNameToNameMap);
}

/*******************************************************************************/
/* SLOTS                                                                       */
/*******************************************************************************/

} // end namespace 'mvd'
<|endoftext|>


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

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

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

=========================================================================*/
#include "mvdWrapperQtWidgetView.h"

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)
#include "otbWrapperQtWidgetParameterGroup.h"
#include "otbWrapperQtWidgetProgressReport.h"
#include "otbWrapperOutputImageParameter.h"
#include "otbWrapperParameterGroup.h"
#include "otbWrapperChoiceParameter.h"
#include "otbWrapperQtWidgetSimpleProgressReport.h"
#include "otbWrapperApplicationHtmlDocGenerator.h"

//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdWrapperQtWidgetParameterFactory.h"

namespace mvd
{
namespace Wrapper
{
/*
  TRANSLATOR mvd::ApplicationLauncher

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CONSTANTS                                                                 */

/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION                                             */

/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION                                              */

/*******************************************************************************/
QtWidgetView::QtWidgetView(otb::Wrapper::Application* app)
{
  m_Model = new otb::Wrapper::QtWidgetModel(app);
  m_Application = app;
}

/*******************************************************************************/
QtWidgetView::~QtWidgetView()
{

}

/*******************************************************************************/
void QtWidgetView::CreateGui()
{
  // Create a VBoxLayout with the header, the input widgets, and the footer
  QVBoxLayout *mainLayout = new QVBoxLayout();
  QTabWidget *tab = new QTabWidget();

  tab->addTab(CreateInputWidgets(), "Parameters");
  QTextEdit *log = new QTextEdit();
  connect( m_Model->GetLogOutput(), SIGNAL(NewContentLog(QString)), log, SLOT(append(QString) ) );
  tab->addTab(log, "Logs");
  otb::Wrapper::QtWidgetProgressReport* prog =  new otb::Wrapper::QtWidgetProgressReport(m_Model);
  prog->SetApplication(m_Application);
  tab->addTab(prog, "Progress");
  tab->addTab(CreateDoc(), "Documentation");
  mainLayout->addWidget(tab);

  m_Message = new QLabel("Select parameters");
  connect( m_Model, SIGNAL(SetApplicationReady(bool)), this, SLOT(UpdateMessageAfterApplicationReady(bool)) );
  mainLayout->addWidget(m_Message);

  otb::Wrapper::QtWidgetSimpleProgressReport * progressReport =  new otb::Wrapper::QtWidgetSimpleProgressReport(m_Model);
  progressReport->SetApplication(m_Application);

  QHBoxLayout *footLayout = new QHBoxLayout;
  footLayout->addWidget(progressReport);
  footLayout->addWidget(CreateFooter());
  mainLayout->addLayout(footLayout);

  QGroupBox *mainGroup = new QGroupBox();
  mainGroup->setLayout(mainLayout);

  QVBoxLayout  *finalLayout = new QVBoxLayout();
  finalLayout->addWidget(mainGroup);

  // Make the final layout to the widget
  this->setLayout(finalLayout);
}

/*******************************************************************************/
QWidget* QtWidgetView::CreateInputWidgets()
{
  QScrollArea *scrollArea = new QScrollArea;
  // Put the main group inside a scroll area
  scrollArea->setWidget(mvd::Wrapper::QtWidgetParameterFactory::CreateQtWidget(m_Model->GetApplication()->GetParameterList(), m_Model));
  scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
  scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
  scrollArea->setWidgetResizable(true);

  return scrollArea;
}

/*******************************************************************************/
QWidget* QtWidgetView::CreateFooter()
{
  // an HLayout with two buttons : Execute and Quit
  QGroupBox *footerGroup = new QGroupBox;
  QHBoxLayout *footerLayout = new QHBoxLayout;

  footerGroup->setFixedHeight(40);
  footerGroup->setContentsMargins(0, 0, 0, 0);
  footerLayout->setContentsMargins(5, 5, 5, 5);

  m_ExecButton = new QPushButton(footerGroup);
  m_ExecButton->setDefault(true);
  m_ExecButton->setEnabled(false);
  m_ExecButton->setText(QObject::tr("Execute"));
  connect( m_ExecButton, SIGNAL(clicked()), m_Model, SLOT(ExecuteAndWriteOutputSlot() ) );
  connect( m_Model, SIGNAL(SetApplicationReady(bool)), m_ExecButton, SLOT(setEnabled(bool)) );
  connect( m_ExecButton, SIGNAL(clicked()), this, SLOT(UpdateMessageAfterExcuteClicked() ) );

  m_QuitButton = new QPushButton(footerGroup);
  m_QuitButton->setText(QObject::tr("Quit"));
  connect( m_QuitButton, SIGNAL(clicked()), this, SLOT(CloseSlot()) );

  // Put the buttons on the right
  footerLayout->addStretch();
  footerLayout->addWidget(m_ExecButton);
  footerLayout->addWidget(m_QuitButton);

  footerGroup->setLayout(footerLayout);

  return footerGroup;
}

/*******************************************************************************/
QWidget* QtWidgetView::CreateDoc()
{
  QTextEdit *text = new QTextEdit;
  text->setReadOnly(true);

  QTextDocument * doc = new QTextDocument();

  std::string docContain;
  otb::Wrapper::ApplicationHtmlDocGenerator::GenerateDoc( m_Application, docContain);

  doc->setHtml(docContain.c_str());

  text->setDocument(doc);

  return text;
}

/*******************************************************************************/
/* SLOTS                                                                       */
/*******************************************************************************/
void QtWidgetView::CloseSlot()
{
  // Close the widget
  this->close();

  // Emit a signal to close any widget that this gui belonging to
  emit QuitSignal();
}

/*******************************************************************************/
void QtWidgetView::UpdateMessageAfterExcuteClicked()
{
  m_Message->setText("Running");
}

/*******************************************************************************/
void QtWidgetView::UpdateMessageAfterApplicationReady( bool val )
{
  if(val == true)
    m_Message->setText("Ready to run");
  else
    m_Message->setText("Select parameters");
}

}
}
<commit_msg>ENH: remove unecessary includes<commit_after>/*=========================================================================

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

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

=========================================================================*/
#include "mvdWrapperQtWidgetView.h"

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)
#include "otbWrapperQtWidgetProgressReport.h"
#include "otbWrapperQtWidgetSimpleProgressReport.h"
#include "otbWrapperApplicationHtmlDocGenerator.h"

//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdWrapperQtWidgetParameterFactory.h"

namespace mvd
{
namespace Wrapper
{
/*
  TRANSLATOR mvd::ApplicationLauncher

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CONSTANTS                                                                 */

/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION                                             */

/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION                                              */

/*******************************************************************************/
QtWidgetView::QtWidgetView(otb::Wrapper::Application* app)
{
  m_Model = new otb::Wrapper::QtWidgetModel(app);
  m_Application = app;
}

/*******************************************************************************/
QtWidgetView::~QtWidgetView()
{

}

/*******************************************************************************/
void QtWidgetView::CreateGui()
{
  // Create a VBoxLayout with the header, the input widgets, and the footer
  QVBoxLayout *mainLayout = new QVBoxLayout();
  QTabWidget *tab = new QTabWidget();

  tab->addTab(CreateInputWidgets(), "Parameters");
  QTextEdit *log = new QTextEdit();
  connect( m_Model->GetLogOutput(), SIGNAL(NewContentLog(QString)), log, SLOT(append(QString) ) );
  tab->addTab(log, "Logs");
  otb::Wrapper::QtWidgetProgressReport* prog =  new otb::Wrapper::QtWidgetProgressReport(m_Model);
  prog->SetApplication(m_Application);
  tab->addTab(prog, "Progress");
  tab->addTab(CreateDoc(), "Documentation");
  mainLayout->addWidget(tab);

  m_Message = new QLabel("Select parameters");
  connect( m_Model, SIGNAL(SetApplicationReady(bool)), this, SLOT(UpdateMessageAfterApplicationReady(bool)) );
  mainLayout->addWidget(m_Message);

  otb::Wrapper::QtWidgetSimpleProgressReport * progressReport =  new otb::Wrapper::QtWidgetSimpleProgressReport(m_Model);
  progressReport->SetApplication(m_Application);

  QHBoxLayout *footLayout = new QHBoxLayout;
  footLayout->addWidget(progressReport);
  footLayout->addWidget(CreateFooter());
  mainLayout->addLayout(footLayout);

  QGroupBox *mainGroup = new QGroupBox();
  mainGroup->setLayout(mainLayout);

  QVBoxLayout  *finalLayout = new QVBoxLayout();
  finalLayout->addWidget(mainGroup);

  // Make the final layout to the widget
  this->setLayout(finalLayout);
}

/*******************************************************************************/
QWidget* QtWidgetView::CreateInputWidgets()
{
  QScrollArea *scrollArea = new QScrollArea;
  // Put the main group inside a scroll area
  scrollArea->setWidget(mvd::Wrapper::QtWidgetParameterFactory::CreateQtWidget(m_Model->GetApplication()->GetParameterList(), m_Model));
  scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
  scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
  scrollArea->setWidgetResizable(true);

  return scrollArea;
}

/*******************************************************************************/
QWidget* QtWidgetView::CreateFooter()
{
  // an HLayout with two buttons : Execute and Quit
  QGroupBox *footerGroup = new QGroupBox;
  QHBoxLayout *footerLayout = new QHBoxLayout;

  footerGroup->setFixedHeight(40);
  footerGroup->setContentsMargins(0, 0, 0, 0);
  footerLayout->setContentsMargins(5, 5, 5, 5);

  m_ExecButton = new QPushButton(footerGroup);
  m_ExecButton->setDefault(true);
  m_ExecButton->setEnabled(false);
  m_ExecButton->setText(QObject::tr("Execute"));
  connect( m_ExecButton, SIGNAL(clicked()), m_Model, SLOT(ExecuteAndWriteOutputSlot() ) );
  connect( m_Model, SIGNAL(SetApplicationReady(bool)), m_ExecButton, SLOT(setEnabled(bool)) );
  connect( m_ExecButton, SIGNAL(clicked()), this, SLOT(UpdateMessageAfterExcuteClicked() ) );

  m_QuitButton = new QPushButton(footerGroup);
  m_QuitButton->setText(QObject::tr("Quit"));
  connect( m_QuitButton, SIGNAL(clicked()), this, SLOT(CloseSlot()) );

  // Put the buttons on the right
  footerLayout->addStretch();
  footerLayout->addWidget(m_ExecButton);
  footerLayout->addWidget(m_QuitButton);

  footerGroup->setLayout(footerLayout);

  return footerGroup;
}

/*******************************************************************************/
QWidget* QtWidgetView::CreateDoc()
{
  QTextEdit *text = new QTextEdit;
  text->setReadOnly(true);

  QTextDocument * doc = new QTextDocument();

  std::string docContain;
  otb::Wrapper::ApplicationHtmlDocGenerator::GenerateDoc( m_Application, docContain);

  doc->setHtml(docContain.c_str());

  text->setDocument(doc);

  return text;
}

/*******************************************************************************/
/* SLOTS                                                                       */
/*******************************************************************************/
void QtWidgetView::CloseSlot()
{
  // Close the widget
  this->close();

  // Emit a signal to close any widget that this gui belonging to
  emit QuitSignal();
}

/*******************************************************************************/
void QtWidgetView::UpdateMessageAfterExcuteClicked()
{
  m_Message->setText("Running");
}

/*******************************************************************************/
void QtWidgetView::UpdateMessageAfterApplicationReady( bool val )
{
  if(val == true)
    m_Message->setText("Ready to run");
  else
    m_Message->setText("Select parameters");
}

}
}
<|endoftext|>


<commit_before>#include <array>
#include <atomic>
#include <string>
#include <iostream>
#include <vector>
#include <limits>
#include <cmath>
#include <memory>
#include <cstdio>
#include "immintrin.h"
#include "render_target.h"

/*
 * Convenient wrapper for BMP header information for a 32bpp BMP
 */
#pragma pack(1)
struct BMPHeader {
	std::array<uint8_t, 2> header;
	uint32_t file_size;
	// 4 reserved bytes we don't care about
	uint32_t dont_care = 0;
	// Offset in the file to the pixel array
	uint32_t px_array = 54;
	uint32_t header_size = 40;
	std::array<int32_t, 2> dims;
	uint16_t color_planes = 1;
	uint16_t bpp = 24;
	uint32_t compression = 0;
	uint32_t img_size;
	std::array<int32_t, 2> res;
	uint32_t color_palette = 0;
	uint32_t important_colors = 0;

	BMPHeader(uint32_t img_size, int32_t w, int32_t h)
		: file_size(54 + img_size), img_size(img_size)
	{
		// Workaround hacks to init header, dims and res because MSVC
		// is too slow to implement C++11/14
		header[0] = 'B';
		header[1] = 'M';
		dims[0] = w;
		dims[1] = h;
		res[0] = 2835;
		res[1] = 2835;
	}
};

Pixel::Pixel() : r(0), g(0), b(0), weight(0){}
Pixel::Pixel(const Pixel &p) : r(p.r), g(p.g), b(p.b), weight(p.weight){}

RenderTarget::RenderTarget(uint32_t width, uint32_t height)
	: width(width), height(height), pixels(width * height){}
void RenderTarget::write_samples(const Vec2f_8 &p, const Colorf_8 &c, __m256 mask){
	// Compute the discrete pixel coordinates which the sample hits
	const auto img_p = p - Vec2f_8{0.5};
	const auto *img_x = (const float*)&img_p.x;
	const auto *img_y = (const float*)&img_p.y;
	const auto *cr = (const float*)&c.r;
	const auto *cg = (const float*)&c.g;
	const auto *cb = (const float*)&c.b;
	const auto write_mask = _mm256_movemask_ps(mask);
	for (int i = 0, mask = 1; i < 8; ++i, mask <<= 1){
		if (write_mask & mask){
			int ix = clamp(static_cast<int>(img_x[i]), 0, static_cast<int>(width));
			int iy = clamp(static_cast<int>(img_y[i]), 0, static_cast<int>(height));
			Pixel &p = pixels[iy * width + ix];
			p.r += cr[i];
			p.g += cg[i];
			p.b += cb[i];
			p.weight += 1;
		}
	}
}
bool RenderTarget::save_image(const std::string &file) const {
	//Compute the correct image from the saved pixel data and write
	//it to the desired file
	std::string file_ext = file.substr(file.rfind(".") + 1);
	if (file_ext == "ppm"){
		std::vector<Color24> img(width * height);
		get_colorbuf(img);
		return save_ppm(file, &img[0].r);
	}
	if (file_ext == "bmp"){
		std::vector<Color24> img(width * height);
		get_colorbuf(img);
		//Do y-flip for BMP since BMP starts at the bottom-left
		for (uint32_t y = 0; y < height / 2; ++y){
			Color24 *a = &img[y * width];
			Color24 *b = &img[(height - y - 1) * width];
			for (uint32_t x = 0; x < width; ++x){
				std::swap(a[x], b[x]);
			}
		}
		// We also need to convert to BGRA order for BMP
		for (auto &c : img){
			std::swap(c.r, c.b);
		}
		return save_bmp(file, &img[0].r);
	}
	std::cout << "Unsupported output image format: " << file_ext << std::endl;
	return false;
}
uint32_t RenderTarget::get_width() const {
	return width;
}
uint32_t RenderTarget::get_height() const {
	return height;
}
void RenderTarget::get_colorbuf(std::vector<Color24> &img) const {
	//Compute the correct image from the saved pixel data
	img.resize(width * height);
	for (uint32_t y = 0; y < height; ++y){
		for (uint32_t x = 0; x < width; ++x){
			const Pixel &p = pixels[y * width + x];
			float weight = p.weight;
			if (weight != 0){
				Colorf c{p.r, p.g, p.b};
				c /= weight;
				c.normalize();
				img[y * width + x] = c.to_sRGB();
			}
		}
	}
}
bool RenderTarget::save_ppm(const std::string &file, const uint8_t *data) const {
	FILE *fp = fopen(file.c_str(), "wb");
	if (!fp){
		std::cerr << "RenderTarget::save_ppm Error: failed to open file "
			<< file << std::endl;
		return false;
	}
	fprintf(fp, "P6\n%d %d\n255\n", static_cast<int>(width), static_cast<int>(height));
	if (fwrite(data, 1, 3 * width * height, fp) != 3 * width * height){
		fclose(fp);
		return false;
	}
	fclose(fp);
	return true;
}
bool RenderTarget::save_bmp(const std::string &file, const uint8_t *data) const {
	FILE *fp = fopen(file.c_str(), "wb");
	if (!fp){
		std::cerr << "RenderTarget::save_bmp Error: failed to open file "
			<< file << std::endl;
		return false;
	}
	uint32_t w = width, h = height;
	BMPHeader bmp_header{4 * w * h, static_cast<int32_t>(w),
		static_cast<int32_t>(h)};
	if (fwrite(&bmp_header, sizeof(BMPHeader), 1, fp) != 1){
		fclose(fp);
		return false;
	}
	// Write each row follwed by any necessary padding
	uint32_t padding = (w * 3) % 4;
	for (uint32_t r = 0; r < h; ++r){
		if (fwrite(data + 3 * w * r, 1, 3 * w, fp) != 3 * w){
			fclose(fp);
			return false;
		}
		if (padding != 0){
			if (fwrite(data, 1, padding, fp) != padding){
				fclose(fp);
				return false;
			}
		}

	}
	fclose(fp);
	return true;
}

<commit_msg>Some small formatting tweaks<commit_after>#include <array>
#include <atomic>
#include <string>
#include <iostream>
#include <vector>
#include <limits>
#include <cmath>
#include <memory>
#include <cstdio>
#include "immintrin.h"
#include "render_target.h"

/*
 * Convenient wrapper for BMP header information for a 32bpp BMP
 */
#pragma pack(1)
struct BMPHeader {
	std::array<uint8_t, 2> header;
	uint32_t file_size;
	// 4 reserved bytes we don't care about
	uint32_t dont_care = 0;
	// Offset in the file to the pixel array
	uint32_t px_array = 54;
	uint32_t header_size = 40;
	std::array<int32_t, 2> dims;
	uint16_t color_planes = 1;
	uint16_t bpp = 24;
	uint32_t compression = 0;
	uint32_t img_size;
	std::array<int32_t, 2> res;
	uint32_t color_palette = 0;
	uint32_t important_colors = 0;

	BMPHeader(uint32_t img_size, int32_t w, int32_t h)
		: file_size(54 + img_size), img_size(img_size)
	{
		// Workaround hacks to init header, dims and res because MSVC
		// is too slow to implement C++11/14
		header[0] = 'B';
		header[1] = 'M';
		dims[0] = w;
		dims[1] = h;
		res[0] = 2835;
		res[1] = 2835;
	}
};

Pixel::Pixel() : r(0), g(0), b(0), weight(0){}
Pixel::Pixel(const Pixel &p) : r(p.r), g(p.g), b(p.b), weight(p.weight){}

RenderTarget::RenderTarget(uint32_t width, uint32_t height)
	: width(width), height(height), pixels(width * height){}
void RenderTarget::write_samples(const Vec2f_8 &p, const Colorf_8 &c, __m256 mask){
	// Compute the discrete pixel coordinates which the sample hits
	const auto img_p = p - Vec2f_8{0.5};
	const auto *img_x = (const float*)&img_p.x;
	const auto *img_y = (const float*)&img_p.y;
	const auto *cr = (const float*)&c.r;
	const auto *cg = (const float*)&c.g;
	const auto *cb = (const float*)&c.b;
	const auto write_mask = _mm256_movemask_ps(mask);
	for (int i = 0, mask = 1; i < 8; ++i, mask <<= 1){
		if (write_mask & mask){
			int ix = clamp(static_cast<int>(img_x[i]), 0, static_cast<int>(width));
			int iy = clamp(static_cast<int>(img_y[i]), 0, static_cast<int>(height));
			Pixel &p = pixels[iy * width + ix];
			p.r += cr[i];
			p.g += cg[i];
			p.b += cb[i];
			p.weight += 1;
		}
	}
}
bool RenderTarget::save_image(const std::string &file) const {
	// Compute the correct image from the saved pixel data and write
	// it to the desired file
	std::string file_ext = file.substr(file.rfind(".") + 1);
	if (file_ext == "ppm"){
		std::vector<Color24> img(width * height);
		get_colorbuf(img);
		return save_ppm(file, &img[0].r);
	}
	if (file_ext == "bmp"){
		std::vector<Color24> img(width * height);
		get_colorbuf(img);
		//Do y-flip for BMP since BMP starts at the bottom-left
		for (uint32_t y = 0; y < height / 2; ++y){
			Color24 *a = &img[y * width];
			Color24 *b = &img[(height - y - 1) * width];
			for (uint32_t x = 0; x < width; ++x){
				std::swap(a[x], b[x]);
			}
		}
		// We also need to convert to BGRA order for BMP
		for (auto &c : img){
			std::swap(c.r, c.b);
		}
		return save_bmp(file, &img[0].r);
	}
	std::cout << "Unsupported output image format: " << file_ext << std::endl;
	return false;
}
uint32_t RenderTarget::get_width() const {
	return width;
}
uint32_t RenderTarget::get_height() const {
	return height;
}
void RenderTarget::get_colorbuf(std::vector<Color24> &img) const {
	// Compute the correct image from the saved pixel data
	img.resize(width * height);
	for (uint32_t y = 0; y < height; ++y){
		for (uint32_t x = 0; x < width; ++x){
			const Pixel &p = pixels[y * width + x];
			float weight = p.weight;
			if (weight != 0){
				Colorf c{p.r, p.g, p.b};
				c /= weight;
				c.normalize();
				img[y * width + x] = c.to_sRGB();
			}
		}
	}
}
bool RenderTarget::save_ppm(const std::string &file, const uint8_t *data) const {
	FILE *fp = fopen(file.c_str(), "wb");
	if (!fp){
		std::cerr << "RenderTarget::save_ppm Error: failed to open file "
			<< file << std::endl;
		return false;
	}
	fprintf(fp, "P6\n%d %d\n255\n", static_cast<int>(width), static_cast<int>(height));
	if (fwrite(data, 1, 3 * width * height, fp) != 3 * width * height){
		fclose(fp);
		return false;
	}
	fclose(fp);
	return true;
}
bool RenderTarget::save_bmp(const std::string &file, const uint8_t *data) const {
	FILE *fp = fopen(file.c_str(), "wb");
	if (!fp){
		std::cerr << "RenderTarget::save_bmp Error: failed to open file "
			<< file << std::endl;
		return false;
	}
	uint32_t w = width, h = height;
	BMPHeader bmp_header{4 * w * h, static_cast<int32_t>(w),
		static_cast<int32_t>(h)};
	if (fwrite(&bmp_header, sizeof(BMPHeader), 1, fp) != 1){
		fclose(fp);
		return false;
	}
	// Write each row follwed by any necessary padding
	uint32_t padding = (w * 3) % 4;
	for (uint32_t r = 0; r < h; ++r){
		if (fwrite(data + 3 * w * r, 1, 3 * w, fp) != 3 * w){
			fclose(fp);
			return false;
		}
		if (padding != 0){
			if (fwrite(data, 1, padding, fp) != padding){
				fclose(fp);
				return false;
			}
		}

	}
	fclose(fp);
	return true;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: SlsFocusManager.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-13 17:28:15 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "controller/SlsFocusManager.hxx"

#include "controller/SlideSorterController.hxx"
#include "model/SlideSorterModel.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "view/SlideSorterView.hxx"
#include "view/SlsLayouter.hxx"
#include "Window.hxx"

namespace sd { namespace slidesorter { namespace controller {

FocusManager::FocusManager (SlideSorterController& rController)
    : mrController (rController),
      mnPageIndex (-1),
      mbPageIsFocused (false)
{
    if (mrController.GetModel().GetPageCount() > 0)
        mnPageIndex = 0;
}

FocusManager::~FocusManager (void)
{
}

void FocusManager::MoveFocus (FocusMoveDirection eDirection)
{
    if (mnPageIndex >= 0 && mbPageIsFocused)
    {
        HideFocusIndicator (GetFocusedPageDescriptor());

        int nColumnCount
            = mrController.GetView().GetLayouter().GetColumnCount();
        switch (eDirection)
        {
            case FMD_NONE:
                if (mnPageIndex >= mrController.GetModel().GetPageCount())
                    mnPageIndex = mrController.GetModel().GetPageCount() - 1;
                break;

            case FMD_LEFT:
                mnPageIndex -= 1;
                if (mnPageIndex < 0)
                    mnPageIndex = mrController.GetModel().GetPageCount() - 1;
                break;

            case FMD_RIGHT:
                mnPageIndex += 1;
                if (mnPageIndex >= mrController.GetModel().GetPageCount())
                    mnPageIndex = 0;
                break;

            case FMD_UP:
            {
                int nColumn = mnPageIndex % nColumnCount;
                mnPageIndex -= nColumnCount;
                if (mnPageIndex < 0)
                {
                    // Wrap arround to the bottom row or the one above and
                    // go to the correct column.
                    int nCandidate = mrController.GetModel().GetPageCount()-1;
                    int nCandidateColumn = nCandidate % nColumnCount;
                    if (nCandidateColumn > nColumn)
                        mnPageIndex = nCandidate - (nCandidateColumn-nColumn);
                    else if (nCandidateColumn < nColumn)
                        mnPageIndex = nCandidate
                            - nColumnCount
                            + (nColumn - nCandidateColumn);
                    else
                        mnPageIndex = nCandidate;
                }
            }
            break;

            case FMD_DOWN:
            {
                int nColumn = mnPageIndex % nColumnCount;
                mnPageIndex += nColumnCount;
                if (mnPageIndex >= mrController.GetModel().GetPageCount())
                {
                    // Wrap arround to the correct column.
                    mnPageIndex = nColumn;
                }
            }
            break;
        }

        ShowFocusIndicator (GetFocusedPageDescriptor());
    }
}

void FocusManager::ShowFocus (void)
{
    mbPageIsFocused = true;
    ShowFocusIndicator (GetFocusedPageDescriptor());
}

void FocusManager::HideFocus (void)
{
    mbPageIsFocused = false;
    HideFocusIndicator (GetFocusedPageDescriptor());
}

bool FocusManager::ToggleFocus (void)
{
    if (mnPageIndex >= 0)
    {
        if (mbPageIsFocused)
            HideFocus ();
        else
            ShowFocus ();
    }
    return mbPageIsFocused;
}

bool FocusManager::HasFocus (void) const
{
    return mrController.GetView().GetWindow()->HasFocus();
}

model::PageDescriptor* FocusManager::GetFocusedPageDescriptor (void) const
{
    return mrController.GetModel().GetPageDescriptor (mnPageIndex);
}

sal_Int32 FocusManager::GetFocusedPageIndex (void) const
{
    return mnPageIndex;
}

void FocusManager::FocusPage (sal_Int32 nPageIndex)
{
    if (nPageIndex != mnPageIndex)
    {
        // Hide the focus while switching it to the specified page.
        FocusHider aHider (*this);
        mnPageIndex = nPageIndex;
    }
}

bool FocusManager::IsFocusShowing (void) const
{
    return HasFocus() && mbPageIsFocused;
}

void FocusManager::HideFocusIndicator (model::PageDescriptor* pDescriptor)
{
    pDescriptor->RemoveFocus();
    mrController.GetView().RequestRepaint (*pDescriptor);
}

void FocusManager::ShowFocusIndicator (model::PageDescriptor* pDescriptor)
{
    if (pDescriptor != NULL)
    {
        pDescriptor->SetFocus ();

        // Scroll the focused page object into the visible area and repaint
        // it, so that the focus indicator becomes visible.
        view::SlideSorterView& rView (mrController.GetView());
        mrController.MakeRectangleVisible (
            rView.GetPageBoundingBox (
                *GetFocusedPageDescriptor(),
                view::SlideSorterView::CS_MODEL,
                view::SlideSorterView::BBT_INFO));

        mrController.GetView().RequestRepaint (*pDescriptor);
    }
}

FocusManager::FocusHider::FocusHider (FocusManager& rManager)
    : mrManager(rManager),
      mbFocusVisible(rManager.IsFocusShowing())
{
    mrManager.HideFocus();
}

FocusManager::FocusHider::~FocusHider (void)
{
    if (mbFocusVisible)
        mrManager.ShowFocus();
}

} } } // end of namespace ::sd::slidesorter::controller

<commit_msg>INTEGRATION: CWS impress29 (1.2.186); FILE MERGED 2005/01/13 16:50:19 af 1.2.186.2: #i39639# Guard code in HideFocusIndicator() against pDescriptor being NULL. 2005/01/13 10:16:28 af 1.2.186.1: #i32465# Added new SetFocusedPage() method in two variants.<commit_after>/*************************************************************************
 *
 *  $RCSfile: SlsFocusManager.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2005-01-25 15:34:22 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include "controller/SlsFocusManager.hxx"

#include "controller/SlideSorterController.hxx"
#include "model/SlideSorterModel.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "view/SlideSorterView.hxx"
#include "view/SlsLayouter.hxx"

#include "Window.hxx"
#include "sdpage.hxx"

namespace sd { namespace slidesorter { namespace controller {

FocusManager::FocusManager (SlideSorterController& rController)
    : mrController (rController),
      mnPageIndex (-1),
      mbPageIsFocused (false)
{
    if (mrController.GetModel().GetPageCount() > 0)
        mnPageIndex = 0;
}

FocusManager::~FocusManager (void)
{
}

void FocusManager::MoveFocus (FocusMoveDirection eDirection)
{
    if (mnPageIndex >= 0 && mbPageIsFocused)
    {
        HideFocusIndicator (GetFocusedPageDescriptor());

        int nColumnCount
            = mrController.GetView().GetLayouter().GetColumnCount();
        switch (eDirection)
        {
            case FMD_NONE:
                if (mnPageIndex >= mrController.GetModel().GetPageCount())
                    mnPageIndex = mrController.GetModel().GetPageCount() - 1;
                break;

            case FMD_LEFT:
                mnPageIndex -= 1;
                if (mnPageIndex < 0)
                    mnPageIndex = mrController.GetModel().GetPageCount() - 1;
                break;

            case FMD_RIGHT:
                mnPageIndex += 1;
                if (mnPageIndex >= mrController.GetModel().GetPageCount())
                    mnPageIndex = 0;
                break;

            case FMD_UP:
            {
                int nColumn = mnPageIndex % nColumnCount;
                mnPageIndex -= nColumnCount;
                if (mnPageIndex < 0)
                {
                    // Wrap arround to the bottom row or the one above and
                    // go to the correct column.
                    int nCandidate = mrController.GetModel().GetPageCount()-1;
                    int nCandidateColumn = nCandidate % nColumnCount;
                    if (nCandidateColumn > nColumn)
                        mnPageIndex = nCandidate - (nCandidateColumn-nColumn);
                    else if (nCandidateColumn < nColumn)
                        mnPageIndex = nCandidate
                            - nColumnCount
                            + (nColumn - nCandidateColumn);
                    else
                        mnPageIndex = nCandidate;
                }
            }
            break;

            case FMD_DOWN:
            {
                int nColumn = mnPageIndex % nColumnCount;
                mnPageIndex += nColumnCount;
                if (mnPageIndex >= mrController.GetModel().GetPageCount())
                {
                    // Wrap arround to the correct column.
                    mnPageIndex = nColumn;
                }
            }
            break;
        }

        ShowFocusIndicator (GetFocusedPageDescriptor());
    }
}

void FocusManager::ShowFocus (void)
{
    mbPageIsFocused = true;
    ShowFocusIndicator (GetFocusedPageDescriptor());
}

void FocusManager::HideFocus (void)
{
    mbPageIsFocused = false;
    HideFocusIndicator (GetFocusedPageDescriptor());
}

bool FocusManager::ToggleFocus (void)
{
    if (mnPageIndex >= 0)
    {
        if (mbPageIsFocused)
            HideFocus ();
        else
            ShowFocus ();
    }
    return mbPageIsFocused;
}

bool FocusManager::HasFocus (void) const
{
    return mrController.GetView().GetWindow()->HasFocus();
}

model::PageDescriptor* FocusManager::GetFocusedPageDescriptor (void) const
{
    return mrController.GetModel().GetPageDescriptor (mnPageIndex);
}

sal_Int32 FocusManager::GetFocusedPageIndex (void) const
{
    return mnPageIndex;
}

void FocusManager::FocusPage (sal_Int32 nPageIndex)
{
    if (nPageIndex != mnPageIndex)
    {
        // Hide the focus while switching it to the specified page.
        FocusHider aHider (*this);
        mnPageIndex = nPageIndex;
    }
}

void FocusManager::SetFocusedPage (const model::PageDescriptor& rDescriptor)
{
    FocusHider aFocusHider (*this);
    mnPageIndex = (rDescriptor.GetPage()->GetPageNum()-1)/2;
}

void FocusManager::SetFocusedPage (sal_Int32 nPageIndex)
{
    FocusHider aFocusHider (*this);
    mnPageIndex = nPageIndex;
}

bool FocusManager::IsFocusShowing (void) const
{
    return HasFocus() && mbPageIsFocused;
}

void FocusManager::HideFocusIndicator (model::PageDescriptor* pDescriptor)
{
    if (pDescriptor != NULL)
    {
        pDescriptor->RemoveFocus();
        mrController.GetView().RequestRepaint (*pDescriptor);
    }
}

void FocusManager::ShowFocusIndicator (model::PageDescriptor* pDescriptor)
{
    if (pDescriptor != NULL)
    {
        pDescriptor->SetFocus ();

        // Scroll the focused page object into the visible area and repaint
        // it, so that the focus indicator becomes visible.
        view::SlideSorterView& rView (mrController.GetView());
        mrController.MakeRectangleVisible (
            rView.GetPageBoundingBox (
                *GetFocusedPageDescriptor(),
                view::SlideSorterView::CS_MODEL,
                view::SlideSorterView::BBT_INFO));

        mrController.GetView().RequestRepaint (*pDescriptor);
    }
}

FocusManager::FocusHider::FocusHider (FocusManager& rManager)
    : mrManager(rManager),
      mbFocusVisible(rManager.IsFocusShowing())
{
    mrManager.HideFocus();
}

FocusManager::FocusHider::~FocusHider (void)
{
    if (mbFocusVisible)
        mrManager.ShowFocus();
}

} } } // end of namespace ::sd::slidesorter::controller

<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// catalog_test.cpp
//
// Identification: test/executor/drop_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <cstdio>

#include "gtest/gtest.h"
#include "common/harness.h"
#include "common/logger.h"
#include "catalog/bootstrapper.h"
#include "catalog/catalog.h"

namespace peloton {
namespace test {

//===--------------------------------------------------------------------===//
// Catalog Tests
//===--------------------------------------------------------------------===//

class DropTests : public PelotonTest {};

TEST_F(DropTests, DroppingTable) {

	auto &bootstrapper = catalog::Bootstrapper::GetInstance();
	auto global_catalog = bootstrapper.bootstrap();

	// Insert a table first
	  auto id_column =
		      catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
		                      "dept_id", true);
	  auto name_column =
	      catalog::Column(VALUE_TYPE_VARCHAR, 32,
	                      "dept_name", false);
	  std::unique_ptr<catalog::Schema> table_schema(new catalog::Schema({id_column, name_column}));
  global_catalog->CreateTable("default_database", "department_table", table_schema);
  EXPECT_EQ(global_catalog->GetDatabaseWithName("default_database")->GetTableCount(), 1);

  // Now dropping the table using the executer
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  auto txn = txn_manager.BeginTransaction();
  std::unique_ptr<executor::ExecutorContext> context(
      new executor::ExecutorContext(txn));
  planner::DropPlan node("department_table");
  executor::DropExecutor executor(&node, context.get());
  executor.Execute();
  EXPECT_EQ(global_catalog->GetDatabaseWithName("default_database")->GetTableCount(), 0);

}

}
}
<commit_msg>Fixing drop_test<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// catalog_test.cpp
//
// Identification: test/executor/drop_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <cstdio>

#include "gtest/gtest.h"
#include "common/harness.h"
#include "common/logger.h"
#include "catalog/bootstrapper.h"
#include "catalog/catalog.h"

namespace peloton {
namespace test {

//===--------------------------------------------------------------------===//
// Catalog Tests
//===--------------------------------------------------------------------===//

class DropTests : public PelotonTest {};

TEST_F(DropTests, DroppingTable) {

	auto &bootstrapper = catalog::Bootstrapper::GetInstance();
	auto global_catalog = bootstrapper.bootstrap();

  // Insert a table first
  auto id_column =
		  catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
						  "dept_id", true);
  auto name_column =
	  catalog::Column(VALUE_TYPE_VARCHAR, 32,
					  "dept_name", false);
  std::unique_ptr<catalog::Schema> table_schema(new catalog::Schema({id_column, name_column}));
  global_catalog->CreateDatabase("default_database");
  global_catalog->CreateTable("default_database", "department_table", std::move(table_schema));
  EXPECT_EQ(global_catalog->GetDatabaseWithName("default_database")->GetTableCount(), 1);

  // Now dropping the table using the executer
  auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
  auto txn = txn_manager.BeginTransaction();
  std::unique_ptr<executor::ExecutorContext> context(
      new executor::ExecutorContext(txn));
  planner::DropPlan node("department_table");
  executor::DropExecutor executor(&node, context.get());
  executor.Init();
  executor.Execute();
  EXPECT_EQ(global_catalog->GetDatabaseWithName("default_database")->GetTableCount(), 0);

}

}
}
<|endoftext|>


<commit_before>//===- lib/Linker/LinkItems.cpp - Link LLVM objects and libraries ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains routines to handle linking together LLVM bytecode files,
// and to handle annoying things like static libraries.
//
//===----------------------------------------------------------------------===//

#include "llvm/Linker.h"
#include "llvm/Module.h"

using namespace llvm;

// LinkItems - This function is the main entry point into linking. It takes a
// list of LinkItem which indicates the order the files should be linked and
// how each file should be treated (plain file or with library search). The
// function only links bytecode and produces a result list of items that are
// native objects.
bool
Linker::LinkInItems(const ItemList& Items, ItemList& NativeItems) {
  // Clear the NativeItems just in case
  NativeItems.clear();

  // For each linkage item ...
  for (ItemList::const_iterator I = Items.begin(), E = Items.end();
       I != E; ++I) {
    if (I->second) {
      // Link in the library suggested.
      bool is_bytecode = true;
      if (LinkInLibrary(I->first, is_bytecode))
        return true;
      if (!is_bytecode)
        NativeItems.push_back(*I);
    } else {
      // Link in the file suggested
      bool is_native = false;
      if (LinkInFile(sys::Path(I->first), is_native))
        return true;
      if (is_native)
        NativeItems.push_back(*I);
    }
  }

  // At this point we have processed all the link items provided to us. Since
  // we have an aggregated module at this point, the dependent libraries in
  // that module should also be aggregated with duplicates eliminated. This is
  // now the time to process the dependent libraries to resolve any remaining
  // symbols.
  bool is_bytecode;
  for (Module::lib_iterator I = Composite->lib_begin(),
         E = Composite->lib_end(); I != E; ++I)
    if(LinkInLibrary(*I, is_bytecode))
      return true;

  return false;
}

/// LinkInLibrary - links one library into the HeadModule.
///
bool Linker::LinkInLibrary(const std::string& Lib, bool& is_native) {
  is_native = false;
  // Determine where this library lives.
  sys::Path Pathname = FindLib(Lib);
  if (Pathname.isEmpty())
    return warning("Cannot find library '" + Lib + "'");

  // If its an archive, try to link it in
  std::string Magic;
  Pathname.getMagicNumber(Magic, 64);
  switch (sys::IdentifyFileType(Magic.c_str(), 64)) {
    default: assert(0 && "Bad file type identification");
    case sys::Unknown_FileType:
      return warning("Supposed library '" + Lib + "' isn't a library.");

    case sys::Bytecode_FileType:
    case sys::CompressedBytecode_FileType:
      // LLVM ".so" file.
      if (LinkInFile(Pathname, is_native))
        return error("Cannot link file '" + Pathname.toString() + "'");
      break;

    case sys::Archive_FileType:
      if (LinkInArchive(Pathname))
        return error("Cannot link archive '" + Pathname.toString() + "'");
      break;

    case sys::ELF_FileType:
    case sys::Mach_O_FileType:
    case sys::COFF_FileType:
      is_native = true;
      break;
  }
  return false;
}

/// LinkLibraries - takes the specified library files and links them into the
/// main bytecode object file.
///
/// Inputs:
///  Libraries  - The list of libraries to link into the module.
///
/// Return value:
///  FALSE - No error.
///  TRUE  - Error.
///
bool Linker::LinkInLibraries(const std::vector<std::string> &Libraries) {

  // Process the set of libraries we've been provided.
  bool is_bytecode;
  for (unsigned i = 0; i < Libraries.size(); ++i)
    if (LinkInLibrary(Libraries[i], is_bytecode))
      return true;

  // At this point we have processed all the libraries provided to us. Since
  // we have an aggregated module at this point, the dependent libraries in
  // that module should also be aggregated with duplicates eliminated. This is
  // now the time to process the dependent libraries to resolve any remaining
  // symbols.
  const Module::LibraryListType& DepLibs = Composite->getLibraries();
  for (Module::LibraryListType::const_iterator I = DepLibs.begin(),
         E = DepLibs.end(); I != E; ++I)
    if (LinkInLibrary(*I, is_bytecode))
      return true;

  return false;
}

/// LinkInFile - opens a bytecode file and links in all objects which
/// provide symbols that are currently undefined.
///
/// Inputs:
///  File - The pathname of the bytecode file.
///
/// Outputs:
///  ErrorMessage - A C++ string detailing what error occurred, if any.
///
/// Return Value:
///  TRUE  - An error occurred.
///  FALSE - No errors.
///
bool Linker::LinkInFile(const sys::Path &File, bool &is_native) {
  is_native = false;
  // Make sure we can at least read the file
  if (!File.canRead())
    return error("Cannot find linker input '" + File.toString() + "'");

  // If its an archive, try to link it in
  std::string Magic;
  File.getMagicNumber(Magic, 64);
  switch (sys::IdentifyFileType(Magic.c_str(), 64)) {
    default: assert(0 && "Bad file type identification");
    case sys::Unknown_FileType:
      return warning("Supposed object file '" + File.toString() +
                     "' not recognized as such");

    case sys::Archive_FileType:
      // A user may specify an ar archive without -l, perhaps because it
      // is not installed as a library. Detect that and link the archive.
      verbose("Linking archive file '" + File.toString() + "'");
      if (LinkInArchive(File))
        return error("Cannot link archive '" + File.toString() + "'");
      break;

    case sys::Bytecode_FileType:
    case sys::CompressedBytecode_FileType: {
      verbose("Linking bytecode file '" + File.toString() + "'");
      std::auto_ptr<Module> M(LoadObject(File));
      if (M.get() == 0)
        return error("Cannot load file '" + File.toString() + "'" + Error);
      if (LinkInModule(M.get()))
        return error("Cannot link file '" + File.toString() + "'" + Error);

      verbose("Linked in file '" + File.toString() + "'");
      break;
    }

    case sys::ELF_FileType:
    case sys::Mach_O_FileType:
    case sys::COFF_FileType:
      is_native = true;
      break;
  }
  return false;
}

/// LinkFiles - takes a module and a list of files and links them all together.
/// It locates the file either in the current directory, as its absolute
/// or relative pathname, or as a file somewhere in LLVM_LIB_SEARCH_PATH.
///
/// Inputs:
///  Files      - A vector of sys::Path indicating the LLVM bytecode filenames
///               to be linked.  The names can refer to a mixture of pure LLVM
///               bytecode files and archive (ar) formatted files.
///
/// Return value:
///  FALSE - No errors.
///  TRUE  - Some error occurred.
///
bool Linker::LinkInFiles(const std::vector<sys::Path> &Files) {
  bool is_native;
  for (unsigned i = 0; i < Files.size(); ++i)
    if (LinkInFile(Files[i], is_native))
      return true;
  return false;
}
<commit_msg>For PR1302: Use local variable names that match the function parameter name that it is passed to so the code is more clear, to wit: is_bytecode -> is_native<commit_after>//===- lib/Linker/LinkItems.cpp - Link LLVM objects and libraries ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains routines to handle linking together LLVM bytecode files,
// and to handle annoying things like static libraries.
//
//===----------------------------------------------------------------------===//

#include "llvm/Linker.h"
#include "llvm/Module.h"

using namespace llvm;

// LinkItems - This function is the main entry point into linking. It takes a
// list of LinkItem which indicates the order the files should be linked and
// how each file should be treated (plain file or with library search). The
// function only links bytecode and produces a result list of items that are
// native objects.
bool
Linker::LinkInItems(const ItemList& Items, ItemList& NativeItems) {
  // Clear the NativeItems just in case
  NativeItems.clear();

  // For each linkage item ...
  for (ItemList::const_iterator I = Items.begin(), E = Items.end();
       I != E; ++I) {
    if (I->second) {
      // Link in the library suggested.
      bool is_native = false;
      if (LinkInLibrary(I->first, is_native))
        return true;
      if (is_native)
        NativeItems.push_back(*I);
    } else {
      // Link in the file suggested
      bool is_native = false;
      if (LinkInFile(sys::Path(I->first), is_native))
        return true;
      if (is_native)
        NativeItems.push_back(*I);
    }
  }

  // At this point we have processed all the link items provided to us. Since
  // we have an aggregated module at this point, the dependent libraries in
  // that module should also be aggregated with duplicates eliminated. This is
  // now the time to process the dependent libraries to resolve any remaining
  // symbols.
  bool is_native;
  for (Module::lib_iterator I = Composite->lib_begin(),
         E = Composite->lib_end(); I != E; ++I)
    if(LinkInLibrary(*I, is_native))
      return true;

  return false;
}

/// LinkInLibrary - links one library into the HeadModule.
///
bool Linker::LinkInLibrary(const std::string& Lib, bool& is_native) {
  is_native = false;
  // Determine where this library lives.
  sys::Path Pathname = FindLib(Lib);
  if (Pathname.isEmpty())
    return warning("Cannot find library '" + Lib + "'");

  // If its an archive, try to link it in
  std::string Magic;
  Pathname.getMagicNumber(Magic, 64);
  switch (sys::IdentifyFileType(Magic.c_str(), 64)) {
    default: assert(0 && "Bad file type identification");
    case sys::Unknown_FileType:
      return warning("Supposed library '" + Lib + "' isn't a library.");

    case sys::Bytecode_FileType:
    case sys::CompressedBytecode_FileType:
      // LLVM ".so" file.
      if (LinkInFile(Pathname, is_native))
        return error("Cannot link file '" + Pathname.toString() + "'");
      break;

    case sys::Archive_FileType:
      if (LinkInArchive(Pathname))
        return error("Cannot link archive '" + Pathname.toString() + "'");
      break;

    case sys::ELF_FileType:
    case sys::Mach_O_FileType:
    case sys::COFF_FileType:
      is_native = true;
      break;
  }
  return false;
}

/// LinkLibraries - takes the specified library files and links them into the
/// main bytecode object file.
///
/// Inputs:
///  Libraries  - The list of libraries to link into the module.
///
/// Return value:
///  FALSE - No error.
///  TRUE  - Error.
///
bool Linker::LinkInLibraries(const std::vector<std::string> &Libraries) {

  // Process the set of libraries we've been provided.
  bool is_native = false;
  for (unsigned i = 0; i < Libraries.size(); ++i)
    if (LinkInLibrary(Libraries[i], is_native))
      return true;

  // At this point we have processed all the libraries provided to us. Since
  // we have an aggregated module at this point, the dependent libraries in
  // that module should also be aggregated with duplicates eliminated. This is
  // now the time to process the dependent libraries to resolve any remaining
  // symbols.
  const Module::LibraryListType& DepLibs = Composite->getLibraries();
  for (Module::LibraryListType::const_iterator I = DepLibs.begin(),
         E = DepLibs.end(); I != E; ++I)
    if (LinkInLibrary(*I, is_native))
      return true;

  return false;
}

/// LinkInFile - opens a bytecode file and links in all objects which
/// provide symbols that are currently undefined.
///
/// Inputs:
///  File - The pathname of the bytecode file.
///
/// Outputs:
///  ErrorMessage - A C++ string detailing what error occurred, if any.
///
/// Return Value:
///  TRUE  - An error occurred.
///  FALSE - No errors.
///
bool Linker::LinkInFile(const sys::Path &File, bool &is_native) {
  is_native = false;
  // Make sure we can at least read the file
  if (!File.canRead())
    return error("Cannot find linker input '" + File.toString() + "'");

  // If its an archive, try to link it in
  std::string Magic;
  File.getMagicNumber(Magic, 64);
  switch (sys::IdentifyFileType(Magic.c_str(), 64)) {
    default: assert(0 && "Bad file type identification");
    case sys::Unknown_FileType:
      return warning("Supposed object file '" + File.toString() +
                     "' not recognized as such");

    case sys::Archive_FileType:
      // A user may specify an ar archive without -l, perhaps because it
      // is not installed as a library. Detect that and link the archive.
      verbose("Linking archive file '" + File.toString() + "'");
      if (LinkInArchive(File))
        return error("Cannot link archive '" + File.toString() + "'");
      break;

    case sys::Bytecode_FileType:
    case sys::CompressedBytecode_FileType: {
      verbose("Linking bytecode file '" + File.toString() + "'");
      std::auto_ptr<Module> M(LoadObject(File));
      if (M.get() == 0)
        return error("Cannot load file '" + File.toString() + "'" + Error);
      if (LinkInModule(M.get()))
        return error("Cannot link file '" + File.toString() + "'" + Error);

      verbose("Linked in file '" + File.toString() + "'");
      break;
    }

    case sys::ELF_FileType:
    case sys::Mach_O_FileType:
    case sys::COFF_FileType:
      is_native = true;
      break;
  }
  return false;
}

/// LinkFiles - takes a module and a list of files and links them all together.
/// It locates the file either in the current directory, as its absolute
/// or relative pathname, or as a file somewhere in LLVM_LIB_SEARCH_PATH.
///
/// Inputs:
///  Files      - A vector of sys::Path indicating the LLVM bytecode filenames
///               to be linked.  The names can refer to a mixture of pure LLVM
///               bytecode files and archive (ar) formatted files.
///
/// Return value:
///  FALSE - No errors.
///  TRUE  - Some error occurred.
///
bool Linker::LinkInFiles(const std::vector<sys::Path> &Files) {
  bool is_native;
  for (unsigned i = 0; i < Files.size(); ++i)
    if (LinkInFile(Files[i], is_native))
      return true;
  return false;
}
<|endoftext|>


<commit_before>// PTABenEvalAAPass for 3.9
#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instruction.h"

#include <stdio.h>

using namespace llvm;

namespace {
struct PTABenEvalAAPass : public FunctionPass {
static char ID;

  llvm::StringRef NOALIAS;
  llvm::StringRef MAYALIAS;
  llvm::StringRef MUSTALIAS;
  llvm::StringRef PARTIALALIAS;
  llvm::StringRef EXPECTEDFAIL_MAYALIAS;
  llvm::StringRef EXPECTEDFAIL_NOALIAS;
  PTABenEvalAAPass() : FunctionPass(ID),
		       NOALIAS("NOALIAS"),
		       MAYALIAS("MAYALIAS"),
 		       MUSTALIAS("MUSTALIAS"),
		       PARTIALALIAS("PARTIALALIAS"),
		       EXPECTEDFAIL_MAYALIAS("EXPECTEDFAIL_MAYALIAS"),
		       EXPECTEDFAIL_NOALIAS("EXPECTEDFAIL_NOALIAS")
  {
    count = 0;
  }
  virtual void getAnalysisUsage(AnalysisUsage &AU) const ;
  int count;
  virtual bool runOnFunction(Function &F) {
    if (count == 0) printf("===== Alias Analysis Benchmark Evaluator Result =====\n");
    count++;
      //    errs() << "I saw a function called " << F.getName() << "!\n";
    AliasAnalysis *AA = &this->getAnalysis<AAResultsWrapperPass>().getAAResults();
    const char *ex, *s, *score;

    for (auto &BB : F) {
      for (auto &I : BB) {
	CallInst *call = dyn_cast<CallInst>(&I);
	if (call) {
          const Value *v = call->getCalledFunction();
          if (v == NULL) continue;
          const Function *called = dyn_cast<Function>(v);
          const StringRef &fun = called->getName();
          if (call->getNumArgOperands() != 2) continue;
	  Value* V1 = call->getArgOperand(0);
	  Value* V2 = call->getArgOperand(1);
	  AliasResult aares = AA->alias(V1, V2);
	  bool r = false;
	  if (fun.equals(NOALIAS)) {
            r = (aares == NoAlias); ex = "NO";
            if (aares == NoAlias)
              score = "true";
 	    else if (aares == MayAlias)
              score = "inadequate";
	    else if (aares == MustAlias)
              score = "false";
            else
              score = "unknown";
	  } else if (fun.equals(MAYALIAS)) {
	    r = (aares == MayAlias || aares == MustAlias); ex = "MAY";
            if (aares == NoAlias)
              score = "false";
 	    else if (aares == MayAlias)
              score = "enough";
	    else if (aares == MustAlias)
              score = "true";
            else
              score = "unknown";
	  } else if (fun.equals(MUSTALIAS)) {
	    r = (aares == MustAlias); ex = "MUST";
            if (aares == NoAlias)
              score = "false";
 	    else if (aares == MayAlias)
              score = "inadequate";
	    else if (aares == MustAlias)
              score = "true";
            else
              score = "unknown";
	  } else if (fun.equals(PARTIALALIAS)) {
	    r = (aares == MayAlias || aares == MustAlias); ex = "MAY";
            if (aares == NoAlias)
              score = "false";
 	    else if (aares == MayAlias)
              score = "enough";
	    else if (aares == MustAlias)
              score = "true";
            else
              score = "unknown";
	  } else if (fun.equals(EXPECTEDFAIL_MAYALIAS)) {
	    r = (aares != MayAlias && r != MustAlias); ex = "EXPECTEDFAIL_MAY";
            if (aares == NoAlias)
              score = "true";
 	    else if (aares == MayAlias)
              score = "false";
	    else if (aares == MustAlias)
              score = "false";
            else
              score = "unknown";
	  } else if (fun.equals(EXPECTEDFAIL_NOALIAS)) {
	    r = (aares != NoAlias); ex = "EXPECTEDFAIL_NO";
            if (aares == NoAlias)
              score = "false";
 	    else if (aares == MayAlias)
              score = "enough";
	    else if (aares == MustAlias)
              score = "true";
            else
              score = "unknown";
          } else {
            continue;
	  }
	  if (aares == NoAlias) s = "NO";
	  else if (aares == MayAlias) s = "MAY";
	  else if (aares == MustAlias) s = "MUST";
          else s = "UNKNOWN";
          if (r)
            printf("  pta %s %s ex %s ", score, s, ex);
          else
            printf("  pta %s %s ex %s ", score, s, ex);
          const llvm::DebugLoc &dg = I.getDebugLoc();
          if (dg)
            printf(" %d\n", dg.getLine());
          else
            printf("\n");
	}
      }
    }
    return false;
  }
};
}

void PTABenEvalAAPass::getAnalysisUsage(AnalysisUsage &AU) const {
  AU.addRequired<llvm::AAResultsWrapperPass>();
  //  AU.addRequired<llvm::MemoryDependenceWrapperPass>();
  //  AU.addRequired<llvm::DependenceAnalysisWrapperPass>();
}

char PTABenEvalAAPass::ID = 0;

// Automatically enable the pass.
// http://adriansampson.net/blog/clangpass.html
//static void registerPTABenEvalAAPass(const PassManagerBuilder &,
//				     legacy::PassManagerBase &PM) {
//  PM.add(new PTABenEvalAAPass());
//}
//static RegisterStandardPasses
//RegisterMyPass(PassManagerBuilder::EP_EarlyAsPossible,
//	       registerPTABenEvalAAPass);

static RegisterPass<PTABenEvalAAPass>
XF("aa-eval-ptaben", "Alias Analysis presision evaluator using PTABen", false, false);
<commit_msg>change score name<commit_after>// PTABenEvalAAPass for 3.9
#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instruction.h"

#include <stdio.h>

using namespace llvm;

namespace {
struct PTABenEvalAAPass : public FunctionPass {
static char ID;

  llvm::StringRef NOALIAS;
  llvm::StringRef MAYALIAS;
  llvm::StringRef MUSTALIAS;
  llvm::StringRef PARTIALALIAS;
  llvm::StringRef EXPECTEDFAIL_MAYALIAS;
  llvm::StringRef EXPECTEDFAIL_NOALIAS;
  PTABenEvalAAPass() : FunctionPass(ID),
		       NOALIAS("NOALIAS"),
		       MAYALIAS("MAYALIAS"),
 		       MUSTALIAS("MUSTALIAS"),
		       PARTIALALIAS("PARTIALALIAS"),
		       EXPECTEDFAIL_MAYALIAS("EXPECTEDFAIL_MAYALIAS"),
		       EXPECTEDFAIL_NOALIAS("EXPECTEDFAIL_NOALIAS")
  {
    count = 0;
  }
  virtual void getAnalysisUsage(AnalysisUsage &AU) const ;
  int count;
  virtual bool runOnFunction(Function &F) {
    if (count == 0) printf("===== Alias Analysis Benchmark Evaluator Result =====\n");
    count++;
      //    errs() << "I saw a function called " << F.getName() << "!\n";
    AliasAnalysis *AA = &this->getAnalysis<AAResultsWrapperPass>().getAAResults();
    const char *ex, *s, *score;

    for (auto &BB : F) {
      for (auto &I : BB) {
	CallInst *call = dyn_cast<CallInst>(&I);
	if (call) {
          const Value *v = call->getCalledFunction();
          if (v == NULL) continue;
          const Function *called = dyn_cast<Function>(v);
          const StringRef &fun = called->getName();
          if (call->getNumArgOperands() != 2) continue;
	  Value* V1 = call->getArgOperand(0);
	  Value* V2 = call->getArgOperand(1);
	  AliasResult aares = AA->alias(V1, V2);
	  bool r = false;
	  if (fun.equals(NOALIAS)) {
            r = (aares == NoAlias); ex = "NO";
            if (aares == NoAlias)
              score = "true";
 	    else if (aares == MayAlias)
              score = "inadequate";
	    else if (aares == MustAlias)
              score = "bug";
            else
              score = "unknown";
	  } else if (fun.equals(MAYALIAS)) {
	    r = (aares == MayAlias || aares == MustAlias); ex = "MAY";
            if (aares == NoAlias)
              score = "false";
 	    else if (aares == MayAlias)
              score = "enough";
	    else if (aares == MustAlias)
              score = "toomuch";
            else
              score = "unknown";
	  } else if (fun.equals(MUSTALIAS)) {
	    r = (aares == MustAlias); ex = "MUST";
            if (aares == NoAlias)
              score = "false";
 	    else if (aares == MayAlias)
              score = "inadequate";
	    else if (aares == MustAlias)
              score = "true";
            else
              score = "unknown";
	  } else if (fun.equals(PARTIALALIAS)) {
	    r = (aares == MayAlias || aares == MustAlias); ex = "MAY";
            if (aares == NoAlias)
              score = "false";
 	    else if (aares == MayAlias)
              score = "enough";
	    else if (aares == MustAlias)
              score = "toomuch";
            else
              score = "unknown";
	  } else if (fun.equals(EXPECTEDFAIL_MAYALIAS)) {
	    r = (aares != MayAlias && r != MustAlias); ex = "EXPECTEDFAIL_MAY";
            if (aares == NoAlias)
              score = "true";
 	    else if (aares == MayAlias)
              score = "false";
	    else if (aares == MustAlias)
              score = "false";
            else
              score = "unknown";
	  } else if (fun.equals(EXPECTEDFAIL_NOALIAS)) {
	    r = (aares != NoAlias); ex = "EXPECTEDFAIL_NO";
            if (aares == NoAlias)
              score = "false";
 	    else if (aares == MayAlias)
              score = "true";
	    else if (aares == MustAlias)
              score = "true";
            else
              score = "unknown";
          } else {
            continue;
	  }
	  if (aares == NoAlias) s = "NO";
	  else if (aares == MayAlias) s = "MAY";
	  else if (aares == MustAlias) s = "MUST";
          else s = "UNKNOWN";
          if (r)
            printf("  pta %s %s ex %s ", score, s, ex);
          else
            printf("  pta %s %s ex %s ", score, s, ex);
          const llvm::DebugLoc &dg = I.getDebugLoc();
          if (dg)
            printf(" %d\n", dg.getLine());
          else
            printf("\n");
	}
      }
    }
    return false;
  }
};
}

void PTABenEvalAAPass::getAnalysisUsage(AnalysisUsage &AU) const {
  AU.addRequired<llvm::AAResultsWrapperPass>();
  //  AU.addRequired<llvm::MemoryDependenceWrapperPass>();
  //  AU.addRequired<llvm::DependenceAnalysisWrapperPass>();
}

char PTABenEvalAAPass::ID = 0;

// Automatically enable the pass.
// http://adriansampson.net/blog/clangpass.html
//static void registerPTABenEvalAAPass(const PassManagerBuilder &,
//				     legacy::PassManagerBase &PM) {
//  PM.add(new PTABenEvalAAPass());
//}
//static RegisterStandardPasses
//RegisterMyPass(PassManagerBuilder::EP_EarlyAsPossible,
//	       registerPTABenEvalAAPass);

static RegisterPass<PTABenEvalAAPass>
XF("aa-eval-ptaben", "Alias Analysis presision evaluator using PTABen", false, false);
<|endoftext|>


<commit_before>/*******************************************************************************
  Copyright (c) 2011 Dmitry Matveev <me@dmitrymatveev.co.uk>
  Copyright (c) 2015 Vladimir Kondratiev <wulf@cicgroup.ru>

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

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

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

#include <cerrno>
#include <csetjmp>
#include <csignal>
#include <cstdlib>
#include "fail_test.hh"

#define INVALID_FILENO		10000
#define NONINOTIFY_FILENO	1 /* stdout */

static std::jmp_buf jbuf;
static void catch_segv (int signo)
{
    std::longjmp (jbuf, 1);
}

fail_test::fail_test (journal &j)
: test ("Failures", j)
{
}

void fail_test::setup ()
{
    cleanup ();
    system ("touch fail-working");
}

void fail_test::run ()
{
    consumer cons;
    sig_t oldsegvhandler;
    int wid = 0;
    int error = 0;

    wid = inotify_add_watch (INVALID_FILENO, "fail-working", IN_ALL_EVENTS);
    should ("watch id is -1, errno set to EBADF when starting watching an "
            "invalid file descriptor", wid == -1 && errno == EBADF);

    cons.output.reset ();
    error = inotify_rm_watch (INVALID_FILENO, 0);
    should ("watch id is -1, errno set to EBADF when stopping watching an "
            "invalid file descriptor", error == -1 && errno == EBADF);

    cons.output.reset ();
    wid = inotify_add_watch (NONINOTIFY_FILENO, "fail-working", IN_ALL_EVENTS);
    should ("watch id is -1, errno set to EINVAL when starting watching a "
            "valid noninotify file descriptor", wid == -1 && errno == EINVAL);

    cons.output.reset ();
    error = inotify_rm_watch (NONINOTIFY_FILENO, 0);
    should ("inotify_rm_watch returns -1, errno set to EINVAL when stopping "
            "watching a valid noninotify file descriptor",
            error == -1 && errno == EINVAL);

    cons.output.reset ();
    error = inotify_rm_watch (cons.get_fd (), INVALID_FILENO);
    should ("inotify_rm_watch returns -1, errno set to EINVAL when stopping "
            "watching an invalid watch descriptor",
            error == -1 && errno == EINVAL);

    cons.output.reset ();
    error = inotify_rm_watch (cons.get_fd (), NONINOTIFY_FILENO);
    should ("inotify_rm_watch returns -1, errno set to EINVAL when stopping "
            "watching an noninotify watch descriptor",
            error == -1 && errno == EINVAL);

    /* Add a watch, should fail */
    cons.output.reset ();
    cons.input.setup ("non-existent", IN_ALL_EVENTS);
    cons.output.wait ();

    wid = cons.output.added_watch_id ();
    error = cons.output.added_watch_error ();
    should ("watch id is -1, errno set to ENOENT when starting watching a "
            "non-existent file", wid == -1 && error == ENOENT);

    cons.output.reset ();
    cons.input.setup ("fail-working", IN_ATTRIB | IN_ONLYDIR);
    cons.output.wait ();

    wid = cons.output.added_watch_id ();
    error = cons.output.added_watch_error ();
    should ("watch id is -1, errno set to ENOTDIR when starting watching a "
            "file with IN_ONLYDIR flag set", wid == -1 && error == ENOTDIR);

    cons.output.reset ();
    cons.input.setup ("fail-working", 0);
    cons.output.wait ();

    wid = cons.output.added_watch_id ();
    error = cons.output.added_watch_error ();
    should ("watch id is -1, errno set to EINVAL when starting watching a "
            "file with no event flags set", wid == -1 && error == EINVAL);

    cons.output.reset ();
    chmod ("fail-working", 0);
    cons.input.setup ("fail-working", IN_ALL_EVENTS);
    cons.output.wait ();

    wid = cons.output.added_watch_id ();
    error = cons.output.added_watch_error ();
    should ("watch id is -1, errno set to EACCES when starting watching a "
            "file without read access", wid == -1 && error == EACCES);

    cons.output.reset ();
    oldsegvhandler = std::signal (SIGSEGV, catch_segv);
    if (setjmp(jbuf) == 0) {
        wid = inotify_add_watch (cons.get_fd (), (char *)-1, IN_ALL_EVENTS);
    } else {
        std::cout << "SIGSEGV catched!!! other tests will probably fail\n";
        wid = -1;
        errno = -SIGSEGV; /* Invalid errno */
    }
    std::signal (SIGSEGV, oldsegvhandler);
    should ("watch id is -1, errno set to EFAULT when starting watching a "
            "file with pathname pointing outside of the process's accessible "
            "address space", wid == -1 && errno == EFAULT);

    cons.input.interrupt ();
}

void fail_test::cleanup ()
{
    system ("rm -rf fail-working");
}
<commit_msg>Test suite: Skip EACCES error code check if run as root<commit_after>/*******************************************************************************
  Copyright (c) 2011 Dmitry Matveev <me@dmitrymatveev.co.uk>
  Copyright (c) 2015 Vladimir Kondratiev <wulf@cicgroup.ru>

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

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

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

#include <cerrno>
#include <csetjmp>
#include <csignal>
#include <cstdlib>
#include <unistd.h>
#include "fail_test.hh"

#define INVALID_FILENO		10000
#define NONINOTIFY_FILENO	1 /* stdout */

static std::jmp_buf jbuf;
static void catch_segv (int signo)
{
    std::longjmp (jbuf, 1);
}

fail_test::fail_test (journal &j)
: test ("Failures", j)
{
}

void fail_test::setup ()
{
    cleanup ();
    system ("touch fail-working");
}

void fail_test::run ()
{
    consumer cons;
    sig_t oldsegvhandler;
    int wid = 0;
    int error = 0;

    wid = inotify_add_watch (INVALID_FILENO, "fail-working", IN_ALL_EVENTS);
    should ("watch id is -1, errno set to EBADF when starting watching an "
            "invalid file descriptor", wid == -1 && errno == EBADF);

    cons.output.reset ();
    error = inotify_rm_watch (INVALID_FILENO, 0);
    should ("watch id is -1, errno set to EBADF when stopping watching an "
            "invalid file descriptor", error == -1 && errno == EBADF);

    cons.output.reset ();
    wid = inotify_add_watch (NONINOTIFY_FILENO, "fail-working", IN_ALL_EVENTS);
    should ("watch id is -1, errno set to EINVAL when starting watching a "
            "valid noninotify file descriptor", wid == -1 && errno == EINVAL);

    cons.output.reset ();
    error = inotify_rm_watch (NONINOTIFY_FILENO, 0);
    should ("inotify_rm_watch returns -1, errno set to EINVAL when stopping "
            "watching a valid noninotify file descriptor",
            error == -1 && errno == EINVAL);

    cons.output.reset ();
    error = inotify_rm_watch (cons.get_fd (), INVALID_FILENO);
    should ("inotify_rm_watch returns -1, errno set to EINVAL when stopping "
            "watching an invalid watch descriptor",
            error == -1 && errno == EINVAL);

    cons.output.reset ();
    error = inotify_rm_watch (cons.get_fd (), NONINOTIFY_FILENO);
    should ("inotify_rm_watch returns -1, errno set to EINVAL when stopping "
            "watching an noninotify watch descriptor",
            error == -1 && errno == EINVAL);

    /* Add a watch, should fail */
    cons.output.reset ();
    cons.input.setup ("non-existent", IN_ALL_EVENTS);
    cons.output.wait ();

    wid = cons.output.added_watch_id ();
    error = cons.output.added_watch_error ();
    should ("watch id is -1, errno set to ENOENT when starting watching a "
            "non-existent file", wid == -1 && error == ENOENT);

    cons.output.reset ();
    cons.input.setup ("fail-working", IN_ATTRIB | IN_ONLYDIR);
    cons.output.wait ();

    wid = cons.output.added_watch_id ();
    error = cons.output.added_watch_error ();
    should ("watch id is -1, errno set to ENOTDIR when starting watching a "
            "file with IN_ONLYDIR flag set", wid == -1 && error == ENOTDIR);

    cons.output.reset ();
    cons.input.setup ("fail-working", 0);
    cons.output.wait ();

    wid = cons.output.added_watch_id ();
    error = cons.output.added_watch_error ();
    should ("watch id is -1, errno set to EINVAL when starting watching a "
            "file with no event flags set", wid == -1 && error == EINVAL);

    if (geteuid() > 0) {
        cons.output.reset ();
        chmod ("fail-working", 0);
        cons.input.setup ("fail-working", IN_ALL_EVENTS);
        cons.output.wait ();

        wid = cons.output.added_watch_id ();
        error = cons.output.added_watch_error ();
        should ("watch id is -1, errno set to EACCES when starting watching a "
                "file without read access", wid == -1 && error == EACCES);
    } else {
        skip ("watch id is -1, errno set to EACCES when starting watching a "
              "file without read access (test is run with effective uid = 0)");
    }

    cons.output.reset ();
    oldsegvhandler = std::signal (SIGSEGV, catch_segv);
    if (setjmp(jbuf) == 0) {
        wid = inotify_add_watch (cons.get_fd (), (char *)-1, IN_ALL_EVENTS);
    } else {
        std::cout << "SIGSEGV catched!!! other tests will probably fail\n";
        wid = -1;
        errno = -SIGSEGV; /* Invalid errno */
    }
    std::signal (SIGSEGV, oldsegvhandler);
    should ("watch id is -1, errno set to EFAULT when starting watching a "
            "file with pathname pointing outside of the process's accessible "
            "address space", wid == -1 && errno == EFAULT);

    cons.input.interrupt ();
}

void fail_test::cleanup ()
{
    system ("rm -rf fail-working");
}
<|endoftext|>