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

  Program:   Visualization Toolkit
  Module:    TestMatrix3x3.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

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

#include "vtkMatrix3x3.h"
#include "vtkTransform2D.h"
#include "vtkPoints2D.h"
#include "vtkNew.h"
#include "vtkMathUtilities.h"

int TestMatrix3x3(int,char *[])
{
  // Instantiate a vtkMatrix3x3 and test out the funtions.
  vtkNew<vtkMatrix3x3> matrix;
  cout << "Testing vtkMatrix3x3..." << endl;
  if (!matrix->IsIdentity())
    {
    vtkGenericWarningMacro("Matrix should be initialized to identity.");
    return 1;
    }
  matrix->Invert();
  if (!matrix->IsIdentity())
    {
    vtkGenericWarningMacro("Inverse of identity should be identity.");
    return 1;
    }
  // Check copying and comparison
  vtkNew<vtkMatrix3x3> matrix2;
  matrix2->DeepCopy(matrix.GetPointer());
  if (*matrix.GetPointer() != *matrix2.GetPointer())
    {
    vtkGenericWarningMacro("DeepCopy of vtkMatrix3x3 failed.");
    return 1;
    }
  if (!(*matrix.GetPointer() == *matrix2.GetPointer()))
    {
    vtkGenericWarningMacro("Problem with vtkMatrix3x3::operator==");
    return 1;
    }
  matrix2->SetElement(0, 0, 5.0);
  if (!(*matrix.GetPointer() != *matrix2.GetPointer()))
    {
    vtkGenericWarningMacro("Problem with vtkMatrix3x3::operator!=");
    return 1;
    }
  if (*matrix.GetPointer() == *matrix2.GetPointer())
    {
    vtkGenericWarningMacro("Problem with vtkMatrix3x3::operator==");
    return 1;
    }

  if (!vtkMathUtilities::FuzzyCompare(matrix2->GetElement(0, 0), 5.0))
    {
    vtkGenericWarningMacro("Value not stored in matrix properly.");
    return 1;
    }
  matrix2->SetElement(1, 2, 42.0);
  if (!vtkMathUtilities::FuzzyCompare(matrix2->GetElement(1, 2), 42.0))
    {
    vtkGenericWarningMacro("Value not stored in matrix properly.");
    return 1;
    }

  // Test matrix transpose
  matrix2->Transpose();
  if (!vtkMathUtilities::FuzzyCompare(matrix2->GetElement(0, 0), 5.0) ||
      !vtkMathUtilities::FuzzyCompare(matrix2->GetElement(2, 1), 42.0))
    {
    vtkGenericWarningMacro("vtkMatrix::Transpose failed.");
    return 1;
    }

  matrix2->Invert();
  if (!vtkMathUtilities::FuzzyCompare(matrix2->GetElement(0, 0), 0.2) ||
      !vtkMathUtilities::FuzzyCompare(matrix2->GetElement(2, 1), -42.0))
    {
    vtkGenericWarningMacro("vtkMatrix::Transpose failed.");
    return 1;
    }

  // Not test the 2D transform with some 2D points
  vtkNew<vtkTransform2D> transform;
  vtkNew<vtkPoints2D> points;
  vtkNew<vtkPoints2D> points2;
  points->SetNumberOfPoints(3);
  points->SetPoint(0, 0.0, 0.0);
  points->SetPoint(1, 3.0, 4.9);
  points->SetPoint(2, 42.0, 69.0);

  transform->TransformPoints(points.GetPointer(), points2.GetPointer());
  for (int i = 0; i < 3; ++i)
    {
    double p1[2], p2[2];
    points->GetPoint(i, p1);
    points2->GetPoint(i, p2);
    if (!vtkMathUtilities::FuzzyCompare(p1[0], p2[0], 1e-5) ||
        !vtkMathUtilities::FuzzyCompare(p1[1], p2[1], 1e-5))
      {
      vtkGenericWarningMacro("Identity transform moved points."
                             << " Delta: "
                             << p1[0] - (p2[0]-2.0)
                             << ", "
                             << p1[1] - (p2[1]-6.9));
      return 1;
      }
    }
  transform->Translate(2.0, 6.9);
  transform->TransformPoints(points.GetPointer(), points2.GetPointer());
  for (int i = 0; i < 3; ++i)
    {
    double p1[2], p2[2];
    points->GetPoint(i, p1);
    points2->GetPoint(i, p2);
    if (!vtkMathUtilities::FuzzyCompare(p1[0], p2[0] - 2.0, 1e-5) ||
        !vtkMathUtilities::FuzzyCompare(p1[1], p2[1] - 6.9, 1e-5))
      {
      vtkGenericWarningMacro("Translation transform failed. Delta: "
                             << p1[0] - (p2[0]-2.0)
                             << ", "
                             << p1[1] - (p2[1]-6.9));

      return 1;
      }
    }
  transform->InverseTransformPoints(points2.GetPointer(), points2.GetPointer());
  for (int i = 0; i < 3; ++i)
    {
    double p1[2], p2[2];
    points->GetPoint(i, p1);
    points2->GetPoint(i, p2);
    if (!vtkMathUtilities::FuzzyCompare(p1[0], p2[0], 1e-5) ||
        !vtkMathUtilities::FuzzyCompare(p1[1], p2[1], 1e-5))
      {
      vtkGenericWarningMacro("Inverse transform did not return original points."
                             << " Delta: "
                             << p1[0] - (p2[0]-2.0)
                             << ", "
                             << p1[1] - (p2[1]-6.9));
      return 1;
      }
    }

  return 0;
}
<commit_msg>Added tests for a few uncovered vtkMatrix3x3 methods<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestMatrix3x3.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

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

#include "vtkMatrix3x3.h"
#include "vtkTransform2D.h"
#include "vtkPoints2D.h"
#include "vtkNew.h"
#include "vtkMathUtilities.h"

int TestMatrix3x3(int,char *[])
{
  // Instantiate a vtkMatrix3x3 and test out the funtions.
  vtkNew<vtkMatrix3x3> matrix;
  cout << "Testing vtkMatrix3x3..." << endl;
  if (!matrix->IsIdentity())
    {
    vtkGenericWarningMacro("Matrix should be initialized to identity.");
    return 1;
    }
  matrix->Invert();
  if (!matrix->IsIdentity())
    {
    vtkGenericWarningMacro("Inverse of identity should be identity.");
    return 1;
    }
  // Check copying and comparison
  vtkNew<vtkMatrix3x3> matrix2;
  matrix2->DeepCopy(matrix.GetPointer());
  if (*matrix.GetPointer() != *matrix2.GetPointer())
    {
    vtkGenericWarningMacro("DeepCopy of vtkMatrix3x3 failed.");
    return 1;
    }
  if (!(*matrix.GetPointer() == *matrix2.GetPointer()))
    {
    vtkGenericWarningMacro("Problem with vtkMatrix3x3::operator==");
    return 1;
    }
  matrix2->SetElement(0, 0, 5.0);
  if (!(*matrix.GetPointer() != *matrix2.GetPointer()))
    {
    vtkGenericWarningMacro("Problem with vtkMatrix3x3::operator!=");
    return 1;
    }
  if (*matrix.GetPointer() == *matrix2.GetPointer())
    {
    vtkGenericWarningMacro("Problem with vtkMatrix3x3::operator==");
    return 1;
    }

  if (!vtkMathUtilities::FuzzyCompare(matrix2->GetElement(0, 0), 5.0))
    {
    vtkGenericWarningMacro("Value not stored in matrix properly.");
    return 1;
    }
  matrix2->SetElement(1, 2, 42.0);
  if (!vtkMathUtilities::FuzzyCompare(matrix2->GetElement(1, 2), 42.0))
    {
    vtkGenericWarningMacro("Value not stored in matrix properly.");
    return 1;
    }

  // Test matrix transpose
  matrix2->Transpose();
  if (!vtkMathUtilities::FuzzyCompare(matrix2->GetElement(0, 0), 5.0) ||
      !vtkMathUtilities::FuzzyCompare(matrix2->GetElement(2, 1), 42.0))
    {
    vtkGenericWarningMacro("vtkMatrix::Transpose failed.");
    return 1;
    }

  matrix2->Invert();
  if (!vtkMathUtilities::FuzzyCompare(matrix2->GetElement(0, 0), 0.2) ||
      !vtkMathUtilities::FuzzyCompare(matrix2->GetElement(2, 1), -42.0))
    {
    vtkGenericWarningMacro("vtkMatrix::Invert failed.");
    return 1;
    }

  // Multiply a coordinate by this matrix.
  double inout[3] = {12.3, 45.6, 78.9};
  matrix2->MultiplyPoint(inout, inout);

  if (!vtkMathUtilities::FuzzyCompare(inout[0], 2.46, 1e-5) ||
      !vtkMathUtilities::FuzzyCompare(inout[1], 45.6, 1e-5) ||
      !vtkMathUtilities::FuzzyCompare(inout[2], -1836.3, 1e-5))
    {
    vtkGenericWarningMacro("vtkMatrix::MultiplyPoint failed.");
    return 1;
    }

  // Not test the 2D transform with some 2D points
  vtkNew<vtkTransform2D> transform;
  vtkNew<vtkPoints2D> points;
  vtkNew<vtkPoints2D> points2;
  points->SetNumberOfPoints(3);
  points->SetPoint(0, 0.0, 0.0);
  points->SetPoint(1, 3.0, 4.9);
  points->SetPoint(2, 42.0, 69.0);

  transform->TransformPoints(points.GetPointer(), points2.GetPointer());
  for (int i = 0; i < 3; ++i)
    {
    double p1[2], p2[2];
    points->GetPoint(i, p1);
    points2->GetPoint(i, p2);
    if (!vtkMathUtilities::FuzzyCompare(p1[0], p2[0], 1e-5) ||
        !vtkMathUtilities::FuzzyCompare(p1[1], p2[1], 1e-5))
      {
      vtkGenericWarningMacro("Identity transform moved points."
                             << " Delta: "
                             << p1[0] - (p2[0]-2.0)
                             << ", "
                             << p1[1] - (p2[1]-6.9));
      return 1;
      }
    }
  transform->Translate(2.0, 6.9);
  transform->TransformPoints(points.GetPointer(), points2.GetPointer());
  for (int i = 0; i < 3; ++i)
    {
    double p1[2], p2[2];
    points->GetPoint(i, p1);
    points2->GetPoint(i, p2);
    if (!vtkMathUtilities::FuzzyCompare(p1[0], p2[0] - 2.0, 1e-5) ||
        !vtkMathUtilities::FuzzyCompare(p1[1], p2[1] - 6.9, 1e-5))
      {
      vtkGenericWarningMacro("Translation transform failed. Delta: "
                             << p1[0] - (p2[0]-2.0)
                             << ", "
                             << p1[1] - (p2[1]-6.9));

      return 1;
      }
    }
  transform->InverseTransformPoints(points2.GetPointer(), points2.GetPointer());
  for (int i = 0; i < 3; ++i)
    {
    double p1[2], p2[2];
    points->GetPoint(i, p1);
    points2->GetPoint(i, p2);
    if (!vtkMathUtilities::FuzzyCompare(p1[0], p2[0], 1e-5) ||
        !vtkMathUtilities::FuzzyCompare(p1[1], p2[1], 1e-5))
      {
      vtkGenericWarningMacro("Inverse transform did not return original points."
                             << " Delta: "
                             << p1[0] - (p2[0]-2.0)
                             << ", "
                             << p1[1] - (p2[1]-6.9));
      return 1;
      }
    }

  // Zero out the matrix.
  matrix->Zero();
  for (int i = 0; i < 3; i++)
    {
    for (int j = 0; j < 3; j++)
      {
      if (matrix->GetElement(i, j) != 0.0)
        {
        vtkGenericWarningMacro("vtkMatrix::Zero failed.");
        return 1;
        }
      }
    }

  return 0;
}
<|endoftext|>


<commit_before>/// @file
/// @author  Ivan Vucica
/// @author  Kresimir Spes
/// @author  Boris Mikic
/// @version 2.3
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php

#include <hltypes/hmap.h>
#include <hltypes/hstring.h>

#include "Platform.h"
#include "Window.h"

namespace april
{
	gvec2 getDisplayResolution()
	{
		return getSystemInfo().displayResolution;
	}

	void messageBox(chstr title, chstr text, MessageBoxButton buttonMask, MessageBoxStyle style,
		hmap<MessageBoxButton, hstr> customButtonTitles, void(*callback)(MessageBoxButton))
	{
		MessageBoxStyle passedStyle = style;
		if (style & AMSGSTYLE_TERMINATEAPPONDISPLAY)
		{
			// TODO - move somewhere else, this file should be completely platform independent
#if !TARGET_OS_IPHONE
			window->terminateMainLoop();
			window->destroy();
#endif
			passedStyle = (MessageBoxStyle)(passedStyle & AMSGSTYLE_MODAL);
		}
		messageBox_platform(title, text, buttonMask, passedStyle, customButtonTitles, callback);
		if (style & AMSGSTYLE_TERMINATEAPPONDISPLAY)
		{
			exit(1);
		}
	}

	void _makeButtonLabels(hstr* ok, hstr* yes, hstr* no, hstr* cancel,
		MessageBoxButton buttonMask, hmap<MessageBoxButton, hstr> customButtonTitles)
	{
		if ((buttonMask & AMSGBTN_OK) && (buttonMask & AMSGBTN_CANCEL))
		{
			*ok = customButtonTitles.try_get_by_key(AMSGBTN_OK, "OK");
			*cancel = customButtonTitles.try_get_by_key(AMSGBTN_CANCEL, "Cancel");
		}
		else if ((buttonMask & AMSGBTN_YES) && (buttonMask & AMSGBTN_NO && buttonMask & AMSGBTN_CANCEL))
		{
			*yes = customButtonTitles.try_get_by_key(AMSGBTN_YES, "Yes");
			*no = customButtonTitles.try_get_by_key(AMSGBTN_NO, "No");
			*cancel = customButtonTitles.try_get_by_key(AMSGBTN_CANCEL, "Cancel");
		}
		else if (buttonMask & AMSGBTN_OK)
		{
			*ok = customButtonTitles.try_get_by_key(AMSGBTN_OK, "OK");
		}
		else if ((buttonMask & AMSGBTN_YES) && (buttonMask & AMSGBTN_NO))
		{
			*yes = customButtonTitles.try_get_by_key(AMSGBTN_YES, "Yes");
			*no = customButtonTitles.try_get_by_key(AMSGBTN_NO, "No");
		}
	}

}
<commit_msg>messageBox bug fix<commit_after>/// @file
/// @author  Ivan Vucica
/// @author  Kresimir Spes
/// @author  Boris Mikic
/// @version 2.3
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php

#include <hltypes/hmap.h>
#include <hltypes/hstring.h>

#include "Platform.h"
#include "Window.h"

namespace april
{
	gvec2 getDisplayResolution()
	{
		return getSystemInfo().displayResolution;
	}

	void messageBox(chstr title, chstr text, MessageBoxButton buttonMask, MessageBoxStyle style,
		hmap<MessageBoxButton, hstr> customButtonTitles, void(*callback)(MessageBoxButton))
	{
		MessageBoxStyle passedStyle = style;
		if (style & AMSGSTYLE_TERMINATEAPPONDISPLAY)
		{
			// TODO - move somewhere else, this file should be completely platform independent
#ifndef _IOS
			window->terminateMainLoop();
			window->destroy();
#endif
			passedStyle = (MessageBoxStyle)(passedStyle | AMSGSTYLE_MODAL);
		}
		messageBox_platform(title, text, buttonMask, passedStyle, customButtonTitles, callback);
		if (style & AMSGSTYLE_TERMINATEAPPONDISPLAY)
		{
			exit(1);
		}
	}

	void _makeButtonLabels(hstr* ok, hstr* yes, hstr* no, hstr* cancel,
		MessageBoxButton buttonMask, hmap<MessageBoxButton, hstr> customButtonTitles)
	{
		if ((buttonMask & AMSGBTN_OK) && (buttonMask & AMSGBTN_CANCEL))
		{
			*ok = customButtonTitles.try_get_by_key(AMSGBTN_OK, "OK");
			*cancel = customButtonTitles.try_get_by_key(AMSGBTN_CANCEL, "Cancel");
		}
		else if ((buttonMask & AMSGBTN_YES) && (buttonMask & AMSGBTN_NO && buttonMask & AMSGBTN_CANCEL))
		{
			*yes = customButtonTitles.try_get_by_key(AMSGBTN_YES, "Yes");
			*no = customButtonTitles.try_get_by_key(AMSGBTN_NO, "No");
			*cancel = customButtonTitles.try_get_by_key(AMSGBTN_CANCEL, "Cancel");
		}
		else if (buttonMask & AMSGBTN_OK)
		{
			*ok = customButtonTitles.try_get_by_key(AMSGBTN_OK, "OK");
		}
		else if ((buttonMask & AMSGBTN_YES) && (buttonMask & AMSGBTN_NO))
		{
			*yes = customButtonTitles.try_get_by_key(AMSGBTN_YES, "Yes");
			*no = customButtonTitles.try_get_by_key(AMSGBTN_NO, "No");
		}
	}

}
<|endoftext|>


<commit_before>#include "ConnectionController.hpp"

#include "Core/Status.hpp"
#include "Models/Connection.hpp"
#include "Services/IHttpServer.hpp"

using namespace Core;
using namespace Services;
using namespace Models;
using namespace Controllers;

ConnectionController::ConnectionController(
  std::shared_ptr<IWiFiManager> wifiManager) :
  wifiManager(wifiManager) {
}

void
ConnectionController::registerOn(IHttpServer &httpServer) {
  httpServer.addGetHandler("/connection", [&](IHttpRequest& request) {
    onGetConnection(request);
  });
  httpServer.addPostHandler("/connection", [&](IHttpRequest& request) {
    onPostConnection(request);
  });
  httpServer.addDeleteHandler("/connection", [&](IHttpRequest& request) {
    onDeleteConnection(request);
  });
}

IHttpResponse
ConnectionController::onGetConnection(IHttpRequest& request) {
  if (!wifiManager->hasConnection())
    return Status::ResourceNotFound;

  return Connection(
    wifiManager->getNetwork(),
    wifiManager->isConnected()
  );
}

IHttpResponse
ConnectionController::onPostConnection(IHttpRequest& request) {
  if (wifiManager->hasConnection())
    return Status::Conflict;

  std::shared_ptr<IEntity> entity;
  Status status = request.getJson(entity);
  if (!status.isOk())
    return status;

  Connection* connection = Connection::dynamicCast(entity.get());
  if (connection == nullptr)
    return Status::IncorrectObjectType;

  status = wifiManager->connect(
    connection->getNetworkSsid(),
    connection->getNetworkPassword());
  if (!status.isOk())
    return Response::status(status);

  return Response::resourceCreated("/connection");
}

IHttpResponse
ConnectionController::onDeleteConnection(IHttpRequest& request) {
  Status status;
  if (wifiManager->hasConnection()) {
    status = wifiManager->disconnect();
  } else {
    status = Status::ResourceNotFound;
  }
  return Response::Status(status);
}
<commit_msg>Experimetns with response2<commit_after>#include "ConnectionController.hpp"

#include "Core/Status.hpp"
#include "Models/Connection.hpp"
#include "Services/IHttpServer.hpp"

using namespace Core;
using namespace Services;
using namespace Models;
using namespace Controllers;

ConnectionController::ConnectionController(
  std::shared_ptr<IWiFiManager> wifiManager) :
  wifiManager(wifiManager) {
}

void
ConnectionController::registerOn(IHttpServer &httpServer) {
  httpServer.addGetHandler("/connection", [&](IHttpRequest& request) {
    onGetConnection(request);
  });
  httpServer.addPostHandler("/connection", [&](IHttpRequest& request) {
    onPostConnection(request);
  });
  httpServer.addDeleteHandler("/connection", [&](IHttpRequest& request) {
    onDeleteConnection(request);
  });
}

std::shared_ptr<IHttpResponse>
ConnectionController::onGetConnection(IHttpRequest& request) {
  if (!wifiManager->hasConnection())
    return Status::ResourceNotFound;

  return Response::FromEntity(std::shared_ptr<IEntity>(new Connection(
    wifiManager->getNetwork(),
    wifiManager->isConnected()
  ));
}

std::shared_ptr<IHttpResponse>
ConnectionController::onPostConnection(IHttpRequest& request) {
  if (wifiManager->hasConnection())
    return Status::Conflict;

  std::shared_ptr<IEntity> entity;
  Status status = request.getJson(entity);
  if (!status.isOk())
    return status;

  Connection* connection = Connection::dynamicCast(entity.get());
  if (connection == nullptr)
    return Status::IncorrectObjectType;

  status = wifiManager->connect(
    connection->getNetworkSsid(),
    connection->getNetworkPassword());
  if (!status.isOk())
    return Response::status(status);

  return Response::resourceCreated("/connection");
}

std::shared_ptr<IHttpResponse>
ConnectionController::onDeleteConnection(IHttpRequest& request) {
  Status status;
  if (wifiManager->hasConnection()) {
    status = wifiManager->disconnect();
  } else {
    status = Status::ResourceNotFound;
  }
  return Response::status(status);
}
<|endoftext|>


<commit_before>#include "Rainback.hpp"

#include <iostream>

#include <functional>
#include <QTextStream>
#include <QApplication>
#include <QPushButton>
#include <QLineEdit>
#include <QTextEdit>
#include <QRegExp>
#include <QFileSystemWatcher>

#include <lua-cxx/LuaValue.hpp>
#include <lua-cxx/loaders.hpp>
#include <lua-cxx/userdata.hpp>
#include <lua-cxx/QObjectObserver.hpp>

#include "LuaPainter.hpp"
#include "LuaFont.hpp"

namespace lua {

template<>
struct UserdataType<QWidget>
{
    constexpr static const char* name = "QWidget";

    static void initialize(LuaStack& stack, QWidget& widget)
    {
        auto userdata = stack.save();
        lua::push(stack, userdata);
        lua::qobject(stack, widget);

        lua::push(stack, lua::value::table);
        auto methods = stack.save();

        methods["resize"] = std::function<void(QWidget&, const int, const int)>(
            [](QWidget& widget, const int w, const int h) {
                widget.resize(w, h);
            }
        );

        methods["setGeometry"] = std::function<void(QWidget&, const int, const int, const int, const int)>(
            [](QWidget& widget, const int x, const int y, const int w, const int h) {
                widget.setGeometry(x, y, w, h);
            }
        );

        methods["__methods"] = methods;

        auto worker = stack.lua()(""
            "return function(userdata, methods)\n"
            "    local mt = getmetatable(userdata);\n"
            ""
            "    local defaultIndex = mt.__index;\n"
            "    function mt.__index(self, key)\n"
            "        return methods[key] or defaultIndex(self, key);\n"
            "    end;\n"
            "end;\n"
        );
        worker(userdata, methods);

        auto observer = new lua::QObjectObserver(&widget, userdata.as<LuaUserdata*>());
        observer->setDestroyOnGC(true);
    }
};

} // namespace lua

std::shared_ptr<LuaFont> newFont(LuaStack& stack)
{
    switch (stack.size()) {
    case 0:
        return std::make_shared<LuaFont>();
    case 1:
        return std::make_shared<LuaFont>(stack.as<QString>(1));
    default:
        return std::make_shared<LuaFont>(
            stack.as<QString>(1),
            stack.as<int>(2)
        );
    }
}

namespace rainback {

void Rainback::assertWidget()
{
    if (!_widget) {
        throw LuaException("This function must not be used when no widget is available");
    }
}

Rainback::Rainback(Lua& lua) :
    _widget(nullptr),
    _lua(lua)
{
	if (_lua["unpack"].isNil()) {
		_lua["unpack"] = _lua["table"]["unpack"];
	}

    _lua["Rainback"] = lua::value::table;

    _lua["Rainback"]["globals"] = lua::value::table;

    _lua["Rainback"]["AddModuleDirectory"] =
    std::function<void(const std::string&, const std::string&)>(
        [this](const std::string& root, const std::string& prefix) {
            auto loader = std::make_shared<DirectoryModuleLoader>();
            loaders.push_back(loader);
            loader->setRoot(QDir(root.c_str()));
            loader->setPrefix(prefix);
            _lua.addModuleLoader(loader.get());
        }
    );

    _lua["Rainback"]["LoadDirectory"] = std::function<void(const std::string&, const bool)>(
        [this](const std::string& path, const bool recurse) {
            lua::load_dir(_lua, QDir(path.c_str()), recurse);
        }
    );

    _lua["Rainback"]["Font"] = newFont;

    _lua["Rainback"]["Button"] = lua::LuaCallable([this](LuaStack& stack) {
            assertWidget();
            stack.clear();
            lua::push<QWidget*>(stack, new QPushButton(_widget), true);
        }
    );

    _lua["Rainback"]["LineEdit"] = lua::LuaCallable([this](LuaStack& stack) {
            assertWidget();
            stack.clear();
            lua::push<QWidget*>(stack, new QLineEdit(_widget), true);
        }
    );

    _lua["Rainback"]["TextEdit"] = lua::LuaCallable([this](LuaStack& stack) {
            assertWidget();
            stack.clear();
            lua::push<QWidget*>(stack, new QTextEdit(_widget), true);
        }
    );

    _lua["Rainback" ]["ScreenWidth"] = std::function<int()>([this]() {
        assertWidget();
        return _widget->width();
    });

    _lua["Rainback" ]["ScreenHeight"] = std::function<int()>([this]() {
        assertWidget();
        return _widget->height();
    });

    _lua["Rainback"]["GetTime"] = std::function<long()>([this]() {
        return elapsed.elapsed();
    });

    _lua["Rainback"]["StartTick"] =
    std::function<std::function<void()>(const int)>([this](const int framerate) {
        timer.start(1000 / framerate);
        return [this]() {
            timer.stop();
        };
    });

    _lua["Rainback"]["GetCursorPosition"] =
    std::function<void(LuaStack&)>([this](LuaStack& stack) {
        assertWidget();
        QPoint pos(_widget->mapFromGlobal(QCursor::pos()));
        stack.clear();
        lua::push(stack, pos.x());
        lua::push(stack, pos.y());
    });

    _lua["Rainback"]["Update"] = std::function<void()>([this]() {
        assertWidget();
        _widget->update();
    });

    _lua["Rainback"]["Close"] = std::function<void()>([this]() {
        assertWidget();
        qApp->closeAllWindows();
    });

    _lua["Rainback"]["SetBackgroundColor"] = std::function<void(const int, const int, const int)>(
        [this](const int r, const int g, const int b) {
            assertWidget();
            _widget->setAutoFillBackground(true);
            QPalette p(_widget->palette());
            p.setColor(QPalette::Background, QColor(r, g, b));
            _widget->setPalette(p);
        }
    );

    _lua["Rainback"]["FileExists"] = std::function<bool(const QString&)>(
        [this](const QString& fileName) {
            return QFile(fileName).exists();
        }
    );

    _lua["Rainback"]["ReadFile"] = std::function<QString(const QString&)>(
        [this](const QString& fileName) {
            QFile file(fileName);
            openFile(file, QIODevice::ReadOnly, true);
            // Using QTextStream here breaks for Unicode strings
            return QString(file.readAll());
        }
    );

    _lua["Rainback"]["ReadCompressedFile"] = std::function<QString(const QString&)>(
        [this](const QString& fileName) {
            QFile file(fileName);
            openFile(file, QIODevice::ReadOnly, true);
            return QString(qUncompress(file.readAll()));
        }
    );

    _lua["Rainback"]["WriteFile"] = std::function<void(const QString&, const QString&)>(
        [this](const QString& fileName, const QString& data) {
            QFile file(fileName);
            openFile(file, QIODevice::WriteOnly | QIODevice::Truncate, false);
            QTextStream(&file) << data;
        }
    );

    _lua["Rainback"]["WriteCompressedFile"] = std::function<void(const QString&, const QString&)>(
        [this](const QString& fileName, const QString& data) {
            QFile file(fileName);
            openFile(file, QIODevice::WriteOnly | QIODevice::Truncate, false);
            file.write(qCompress(data.toUtf8()));
        }
    );

    _lua["Rainback"]["WatchFile"] = std::function<void(LuaStack&)>(
        [this](LuaStack& stack) {
            auto watcher = new QFileSystemWatcher(this);

            for (int i=1; i <= stack.size(); ++i) {
                watcher->addPath(stack.as<QString>(i));
            }
            stack.clear();

            lua::push<QObject*>(stack, watcher, true);
            auto observer = new lua::QObjectObserver(watcher, stack.as<LuaUserdata*>(-1));
            observer->setDestroyOnGC(true);
        }
    );

    _lua["string"]["grep"] = lua::LuaCallable([](LuaStack& stack) {
        auto str = stack.as<QString>(1);
        QRegExp re(stack.as<QString>(2));
        stack.clear();

        if (re.indexIn(str) == -1) {
            return;
        }

        for (int i = 0; i <= re.captureCount(); ++i) {
            lua::push(stack, re.cap(i));
        }
    });

    lua::qvariantPusher(QVariant::Size, [](LuaStack& stack, const QVariant& source) {
        lua::push(stack, lua::value::table);

        auto size = source.toSize();
        stack.set("width", size.width());
        stack.set("height", size.height());
    });

    elapsed.start();

    connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));
    connect(qApp, SIGNAL(lastWindowClosed()), this, SLOT(close()));
}

void Rainback::openFile(QFile& file, const QIODevice::OpenMode& flags, const bool checkExists)
{
    if (checkExists && !file.exists()) {
        throw LuaException(
            (QString("The specified file '") + file.fileName() + "' does not exist").toStdString()
        );
    }
    if (!file.open(flags)) {
        throw LuaException(
            (QString("The specified file '") + file.fileName() + "' failed to open: " + file.error()).toStdString()
        );
    }
}

void Rainback::timeout()
{
    rainback::dispatch(_lua, "UPDATE");
}

void Rainback::close()
{
    rainback::dispatch(_lua, "CLOSE");
}

} // namespace rainback

// vim: set ts=4 sw=4 :
<commit_msg>Use our own error<commit_after>#include "Rainback.hpp"

#include <iostream>

#include <functional>
#include <QTextStream>
#include <QApplication>
#include <QPushButton>
#include <QLineEdit>
#include <QTextEdit>
#include <QRegExp>
#include <QFileSystemWatcher>

#include <lua-cxx/LuaValue.hpp>
#include <lua-cxx/loaders.hpp>
#include <lua-cxx/userdata.hpp>
#include <lua-cxx/QObjectObserver.hpp>

#include "LuaPainter.hpp"
#include "LuaFont.hpp"

namespace lua {

template<>
struct UserdataType<QWidget>
{
    constexpr static const char* name = "QWidget";

    static void initialize(LuaStack& stack, QWidget& widget)
    {
        auto userdata = stack.save();
        lua::push(stack, userdata);
        lua::qobject(stack, widget);

        lua::push(stack, lua::value::table);
        auto methods = stack.save();

        methods["resize"] = std::function<void(QWidget&, const int, const int)>(
            [](QWidget& widget, const int w, const int h) {
                widget.resize(w, h);
            }
        );

        methods["setGeometry"] = std::function<void(QWidget&, const int, const int, const int, const int)>(
            [](QWidget& widget, const int x, const int y, const int w, const int h) {
                widget.setGeometry(x, y, w, h);
            }
        );

        methods["__methods"] = methods;

        auto worker = stack.lua()(""
            "return function(userdata, methods)\n"
            "    local mt = getmetatable(userdata);\n"
            ""
            "    local defaultIndex = mt.__index;\n"
            "    function mt.__index(self, key)\n"
            "        return methods[key] or defaultIndex(self, key);\n"
            "    end;\n"
            "end;\n"
        );
        worker(userdata, methods);

        auto observer = new lua::QObjectObserver(&widget, userdata.as<LuaUserdata*>());
        observer->setDestroyOnGC(true);
    }
};

} // namespace lua

std::shared_ptr<LuaFont> newFont(LuaStack& stack)
{
    switch (stack.size()) {
    case 0:
        return std::make_shared<LuaFont>();
    case 1:
        return std::make_shared<LuaFont>(stack.as<QString>(1));
    default:
        return std::make_shared<LuaFont>(
            stack.as<QString>(1),
            stack.as<int>(2)
        );
    }
}

namespace rainback {

void Rainback::assertWidget()
{
    if (!_widget) {
        throw LuaException("This function must not be used when no widget is available");
    }
}

Rainback::Rainback(Lua& lua) :
    _widget(nullptr),
    _lua(lua)
{
	if (_lua["unpack"].isNil()) {
		_lua["unpack"] = _lua["table"]["unpack"];
	}

    _lua["Rainback"] = lua::value::table;

    _lua["error"] = lua::LuaCallable([](LuaStack& stack) {
        stack.error(stack.as<std::string>(-1));
    });

    _lua["Rainback"]["globals"] = lua::value::table;

    _lua["Rainback"]["AddModuleDirectory"] =
    std::function<void(const std::string&, const std::string&)>(
        [this](const std::string& root, const std::string& prefix) {
            auto loader = std::make_shared<DirectoryModuleLoader>();
            loaders.push_back(loader);
            loader->setRoot(QDir(root.c_str()));
            loader->setPrefix(prefix);
            _lua.addModuleLoader(loader.get());
        }
    );

    _lua["Rainback"]["LoadDirectory"] = std::function<void(const std::string&, const bool)>(
        [this](const std::string& path, const bool recurse) {
            lua::load_dir(_lua, QDir(path.c_str()), recurse);
        }
    );

    _lua["Rainback"]["Font"] = newFont;

    _lua["Rainback"]["Button"] = lua::LuaCallable([this](LuaStack& stack) {
            assertWidget();
            stack.clear();
            lua::push<QWidget*>(stack, new QPushButton(_widget), true);
        }
    );

    _lua["Rainback"]["LineEdit"] = lua::LuaCallable([this](LuaStack& stack) {
            assertWidget();
            stack.clear();
            lua::push<QWidget*>(stack, new QLineEdit(_widget), true);
        }
    );

    _lua["Rainback"]["TextEdit"] = lua::LuaCallable([this](LuaStack& stack) {
            assertWidget();
            stack.clear();
            lua::push<QWidget*>(stack, new QTextEdit(_widget), true);
        }
    );

    _lua["Rainback" ]["ScreenWidth"] = std::function<int()>([this]() {
        assertWidget();
        return _widget->width();
    });

    _lua["Rainback" ]["ScreenHeight"] = std::function<int()>([this]() {
        assertWidget();
        return _widget->height();
    });

    _lua["Rainback"]["GetTime"] = std::function<long()>([this]() {
        return elapsed.elapsed();
    });

    _lua["Rainback"]["StartTick"] =
    std::function<std::function<void()>(const int)>([this](const int framerate) {
        timer.start(1000 / framerate);
        return [this]() {
            timer.stop();
        };
    });

    _lua["Rainback"]["GetCursorPosition"] =
    std::function<void(LuaStack&)>([this](LuaStack& stack) {
        assertWidget();
        QPoint pos(_widget->mapFromGlobal(QCursor::pos()));
        stack.clear();
        lua::push(stack, pos.x());
        lua::push(stack, pos.y());
    });

    _lua["Rainback"]["Update"] = std::function<void()>([this]() {
        assertWidget();
        _widget->update();
    });

    _lua["Rainback"]["Close"] = std::function<void()>([this]() {
        assertWidget();
        qApp->closeAllWindows();
    });

    _lua["Rainback"]["SetBackgroundColor"] = std::function<void(const int, const int, const int)>(
        [this](const int r, const int g, const int b) {
            assertWidget();
            _widget->setAutoFillBackground(true);
            QPalette p(_widget->palette());
            p.setColor(QPalette::Background, QColor(r, g, b));
            _widget->setPalette(p);
        }
    );

    _lua["Rainback"]["FileExists"] = std::function<bool(const QString&)>(
        [this](const QString& fileName) {
            return QFile(fileName).exists();
        }
    );

    _lua["Rainback"]["ReadFile"] = std::function<QString(const QString&)>(
        [this](const QString& fileName) {
            QFile file(fileName);
            openFile(file, QIODevice::ReadOnly, true);
            // Using QTextStream here breaks for Unicode strings
            return QString(file.readAll());
        }
    );

    _lua["Rainback"]["ReadCompressedFile"] = std::function<QString(const QString&)>(
        [this](const QString& fileName) {
            QFile file(fileName);
            openFile(file, QIODevice::ReadOnly, true);
            return QString(qUncompress(file.readAll()));
        }
    );

    _lua["Rainback"]["WriteFile"] = std::function<void(const QString&, const QString&)>(
        [this](const QString& fileName, const QString& data) {
            QFile file(fileName);
            openFile(file, QIODevice::WriteOnly | QIODevice::Truncate, false);
            QTextStream(&file) << data;
        }
    );

    _lua["Rainback"]["WriteCompressedFile"] = std::function<void(const QString&, const QString&)>(
        [this](const QString& fileName, const QString& data) {
            QFile file(fileName);
            openFile(file, QIODevice::WriteOnly | QIODevice::Truncate, false);
            file.write(qCompress(data.toUtf8()));
        }
    );

    _lua["Rainback"]["WatchFile"] = std::function<void(LuaStack&)>(
        [this](LuaStack& stack) {
            auto watcher = new QFileSystemWatcher(this);

            for (int i=1; i <= stack.size(); ++i) {
                watcher->addPath(stack.as<QString>(i));
            }
            stack.clear();

            lua::push<QObject*>(stack, watcher, true);
            auto observer = new lua::QObjectObserver(watcher, stack.as<LuaUserdata*>(-1));
            observer->setDestroyOnGC(true);
        }
    );

    _lua["string"]["grep"] = lua::LuaCallable([](LuaStack& stack) {
        auto str = stack.as<QString>(1);
        QRegExp re(stack.as<QString>(2));
        stack.clear();

        if (re.indexIn(str) == -1) {
            return;
        }

        for (int i = 0; i <= re.captureCount(); ++i) {
            lua::push(stack, re.cap(i));
        }
    });

    lua::qvariantPusher(QVariant::Size, [](LuaStack& stack, const QVariant& source) {
        lua::push(stack, lua::value::table);

        auto size = source.toSize();
        stack.set("width", size.width());
        stack.set("height", size.height());
    });

    elapsed.start();

    connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));
    connect(qApp, SIGNAL(lastWindowClosed()), this, SLOT(close()));
}

void Rainback::openFile(QFile& file, const QIODevice::OpenMode& flags, const bool checkExists)
{
    if (checkExists && !file.exists()) {
        throw LuaException(
            (QString("The specified file '") + file.fileName() + "' does not exist").toStdString()
        );
    }
    if (!file.open(flags)) {
        throw LuaException(
            (QString("The specified file '") + file.fileName() + "' failed to open: " + file.error()).toStdString()
        );
    }
}

void Rainback::timeout()
{
    rainback::dispatch(_lua, "UPDATE");
}

void Rainback::close()
{
    rainback::dispatch(_lua, "CLOSE");
}

} // namespace rainback

// vim: set ts=4 sw=4 :
<|endoftext|>


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

#include <pcl/apps/modeler/statistical_outlier_removal_worker.h>
#include <pcl/apps/modeler/parameter.h>
#include <pcl/apps/modeler/parameter_dialog.h>
#include <pcl/apps/modeler/cloud_mesh.h>
#include <pcl/apps/modeler/cloud_mesh_item.h>
#include <pcl/filters/statistical_outlier_removal.h>

//////////////////////////////////////////////////////////////////////////////////////////////
pcl::modeler::StatisticalOutlierRemovalWorker::StatisticalOutlierRemovalWorker(const QList<CloudMeshItem*>& cloud_mesh_items, QWidget* parent) :
  AbstractWorker(cloud_mesh_items, parent),
  mean_k_(NULL), stddev_mul_thresh_(NULL)
{
}

//////////////////////////////////////////////////////////////////////////////////////////////
pcl::modeler::StatisticalOutlierRemovalWorker::~StatisticalOutlierRemovalWorker(void)
{
  delete mean_k_;
  delete stddev_mul_thresh_;
}

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::modeler::StatisticalOutlierRemovalWorker::initParameters(CloudMeshItem* cloud_mesh_item)
{
  return;
}

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::modeler::StatisticalOutlierRemovalWorker::setupParameters()
{
  mean_k_ = new IntParameter("Mean K", "The number of nearest neighbors to use for mean distance estimation", 8, 1, 1024, 1);
  stddev_mul_thresh_ = new DoubleParameter("Standard Deviation Multiplier", "The distance threshold will be equal to: mean + stddev_mult * stddev. Points will be classified as inlier or outlier if their average neighbor distance is below or above this threshold respectively.", 1.0, 0.1, 10, 0.1);

  parameter_dialog_->addParameter(mean_k_);
  parameter_dialog_->addParameter(stddev_mul_thresh_);

  return;
}

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::modeler::StatisticalOutlierRemovalWorker::processImpl(CloudMeshItem* cloud_mesh_item)
{
  pcl::StatisticalOutlierRemoval<pcl::PointSurfel> sor;
  sor.setInputCloud(cloud_mesh_item->getCloudMesh()->getCloud());
  sor.setMeanK(*mean_k_);
  sor.setStddevMulThresh(*stddev_mul_thresh_);

  CloudMesh::PointCloudPtr cloud(new CloudMesh::PointCloud());
  sor.filter(*cloud);

  cloud_mesh_item->getCloudMesh()->getCloud() = cloud;

  emitDataUpdated(cloud_mesh_item);

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

#include <pcl/apps/modeler/statistical_outlier_removal_worker.h>
#include <pcl/apps/modeler/parameter.h>
#include <pcl/apps/modeler/parameter_dialog.h>
#include <pcl/apps/modeler/cloud_mesh.h>
#include <pcl/apps/modeler/cloud_mesh_item.h>
#include <pcl/filters/statistical_outlier_removal.h>

//////////////////////////////////////////////////////////////////////////////////////////////
pcl::modeler::StatisticalOutlierRemovalWorker::StatisticalOutlierRemovalWorker(const QList<CloudMeshItem*>& cloud_mesh_items, QWidget* parent) :
  AbstractWorker(cloud_mesh_items, parent),
  mean_k_(NULL), stddev_mul_thresh_(NULL)
{
}

//////////////////////////////////////////////////////////////////////////////////////////////
pcl::modeler::StatisticalOutlierRemovalWorker::~StatisticalOutlierRemovalWorker(void)
{
  delete mean_k_;
  delete stddev_mul_thresh_;
}

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::modeler::StatisticalOutlierRemovalWorker::initParameters(CloudMeshItem* cloud_mesh_item)
{
  return;
}

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::modeler::StatisticalOutlierRemovalWorker::setupParameters()
{
  mean_k_ = new IntParameter("Mean K", "The number of nearest neighbors to use for mean distance estimation", 8, 1, 1024, 1);
  stddev_mul_thresh_ = new DoubleParameter("Standard Deviation Multiplier", "The distance threshold will be equal to: mean + stddev_mult * stddev. Points will be classified as inlier or outlier if their average neighbor distance is below or above this threshold respectively.", 1.0, 0.1, 10, 0.1);

  parameter_dialog_->addParameter(mean_k_);
  parameter_dialog_->addParameter(stddev_mul_thresh_);

  return;
}

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::modeler::StatisticalOutlierRemovalWorker::processImpl(CloudMeshItem* cloud_mesh_item)
{
  pcl::StatisticalOutlierRemoval<pcl::PointSurfel> sor;
  sor.setInputCloud(cloud_mesh_item->getCloudMesh()->getCloud());
  sor.setMeanK(*mean_k_);
  sor.setStddevMulThresh(*stddev_mul_thresh_);

  CloudMesh::PointCloudPtr cloud(new CloudMesh::PointCloud());
  sor.filter(*cloud);

  cloud_mesh_item->getCloudMesh()->getCloud() = cloud;

  emitDataUpdated(cloud_mesh_item);

  return;
}<|endoftext|>


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

   The MIT License

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

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

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

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

#include "ArcBall.hpp"
#include <glm/gtx/vec_swizzle.hpp>

namespace spire {

//------------------------------------------------------------------------------
  ArcBall::ArcBall(const glm::vec3& center, float radius, bool inverted, const glm::mat4& screenToTCS) :
    mScreenToTCS(screenToTCS),
    mCenter(center),
    mRadius(radius),
    invertHemisphere(inverted)
{
  // glm uses the following format for quaternions: w,x,y,z.
  //        w,    x,    y,    z
  glm::quat qOne(1.0, 0.0, 0.0, 0.0);
  glm::vec3 vZero(0.0, 0.0, 0.0);

  mQDown       = qOne;
  mQNow        = qOne;
  mVSphereDown = mouseOnSphere(vZero);
}

//------------------------------------------------------------------------------
glm::vec3 ArcBall::mouseOnSphere(const glm::vec3& tscMouse)
{
  glm::vec3 ballMouse((tscMouse - mCenter) / mRadius);

  float mag_sq = glm::dot(ballMouse, ballMouse);
  if (mag_sq > 1.0)
  {
    // Since we are outside of the sphere, map to the visible boundary of the sphere.
    ballMouse *= 1.0 / sqrtf(mag_sq);
  }
  else
  {
    // Essentially, we are normalizing the vector by adding the missing z component.
    ballMouse.z = sqrtf(1.0 - mag_sq);
  }

  if(invertHemisphere)
    ballMouse.z = -ballMouse.z;

  return ballMouse;
}

//------------------------------------------------------------------------------
void ArcBall::beginDrag(const glm::vec2& msc)
{
  mQDown       = mQNow;
  mVSphereDown = mouseOnSphere(xyz(mScreenToTCS * glm::vec4(msc, 0.0f, 1.0f)));
}

//------------------------------------------------------------------------------
void ArcBall::drag(const glm::vec2& msc)
{
  glm::vec3 mVSphereNow = mouseOnSphere(xyz(mScreenToTCS * glm::vec4(msc, 0.0f, 1.0f)));

  // Construct a quaternion from two points on the unit sphere.
  glm::quat mQDrag = quatFromUnitSphere(mVSphereDown, mVSphereNow);
  mQNow = mQDrag * mQDown;
  if(glm::dot(mVSphereDown, mVSphereNow) < 0.0)
    beginDrag(msc);
}

//------------------------------------------------------------------------------
void ArcBall::setLocationOnSphere(glm::vec3 location, glm::vec3 up)
{
  glm::mat4 mMatNow = glm::lookAt(location, glm::vec3(0.0f), up);
  mQNow = glm::quat_cast(mMatNow);
}

//------------------------------------------------------------------------------
glm::quat ArcBall::quatFromUnitSphere(const glm::vec3& from, const glm::vec3& to)
{
  //TODO: check if cross is 0 before normalize. Crashes on Windows
  auto c = glm::cross(from, to);
  if (c == glm::vec3(0, 0, 0))
    return {};

  glm::vec3 axis = glm::normalize(c);

  // Give arbitrary non-zero vector because no rotation
  if (std::isnan(axis[0]))
    axis = from;

  float angle = std::acos(glm::dot(from, to));

  if(angle <= 0.00001 || std::isnan(angle))
    return glm::quat(1.0, 0.0, 0.0, 0.0);

  return glm::angleAxis(angle, axis);
}

//------------------------------------------------------------------------------
glm::mat4 ArcBall::getTransformation() const
{
  return glm::mat4_cast(mQNow);
}

} // namespace spire
<commit_msg>Fixed widget rotation<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

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

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

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

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

#include "ArcBall.hpp"
#include <glm/gtx/vec_swizzle.hpp>

namespace spire {

//------------------------------------------------------------------------------
  ArcBall::ArcBall(const glm::vec3& center, float radius, bool inverted, const glm::mat4& screenToTCS) :
    mScreenToTCS(screenToTCS),
    mCenter(center),
    mRadius(radius),
    invertHemisphere(inverted)
{
  // glm uses the following format for quaternions: w,x,y,z.
  //        w,    x,    y,    z
  glm::quat qOne(1.0, 0.0, 0.0, 0.0);
  glm::vec3 vZero(0.0, 0.0, 0.0);

  mQDown       = qOne;
  mQNow        = qOne;
  mVSphereDown = mouseOnSphere(vZero);
}

//------------------------------------------------------------------------------
glm::vec3 ArcBall::mouseOnSphere(const glm::vec3& tscMouse)
{
  glm::vec3 ballMouse(xy(tscMouse - mCenter) / mRadius, 0.0);

  float mag_sq = glm::dot(ballMouse, ballMouse);
  if (mag_sq > 1.0)
  {
    // Since we are outside of the sphere, map to the visible boundary of the sphere.
    ballMouse *= 1.0 / sqrtf(mag_sq);
  }
  else
  {
    // Essentially, we are normalizing the vector by adding the missing z component.
    ballMouse.z = sqrtf(1.0 - mag_sq);
  }

  if(invertHemisphere)
    ballMouse.z = -ballMouse.z;

  return ballMouse;
}

//------------------------------------------------------------------------------
void ArcBall::beginDrag(const glm::vec2& msc)
{
  mQDown       = mQNow;
  mVSphereDown = mouseOnSphere(xyz(mScreenToTCS * glm::vec4(msc, 0.0f, 1.0f)));
}

//------------------------------------------------------------------------------
void ArcBall::drag(const glm::vec2& msc)
{
  glm::vec3 mVSphereNow = mouseOnSphere(xyz(mScreenToTCS * glm::vec4(msc, 0.0f, 1.0f)));

  // Construct a quaternion from two points on the unit sphere.
  glm::quat mQDrag = quatFromUnitSphere(mVSphereDown, mVSphereNow);
  mQNow = mQDrag * mQDown;
  if(glm::dot(mVSphereDown, mVSphereNow) < 0.0)
    beginDrag(msc);
}

//------------------------------------------------------------------------------
void ArcBall::setLocationOnSphere(glm::vec3 location, glm::vec3 up)
{
  glm::mat4 mMatNow = glm::lookAt(location, glm::vec3(0.0f), up);
  mQNow = glm::quat_cast(mMatNow);
}

//------------------------------------------------------------------------------
glm::quat ArcBall::quatFromUnitSphere(const glm::vec3& from, const glm::vec3& to)
{
  //TODO: check if cross is 0 before normalize. Crashes on Windows
  auto c = glm::cross(from, to);
  if (c == glm::vec3(0, 0, 0))
    return {};

  glm::vec3 axis = glm::normalize(c);

  // Give arbitrary non-zero vector because no rotation
  if (std::isnan(axis[0]))
    axis = from;

  float angle = std::acos(glm::dot(from, to));

  if(angle <= 0.00001 || std::isnan(angle))
    return glm::quat(1.0, 0.0, 0.0, 0.0);

  return glm::angleAxis(angle, axis);
}

//------------------------------------------------------------------------------
glm::mat4 ArcBall::getTransformation() const
{
  return glm::mat4_cast(mQNow);
}

} // namespace spire
<|endoftext|>


<commit_before>//
//  PhysicsManager.cpp
//  CatchiOS
//
//  Created by John Barbero Unenge on 10/7/12.
//  Copyright (c) 2012 John Barbero Unenge. All rights reserved.
//

#include "PhysicsManager.hpp"
#include "../../EventHandling/EventBus.hpp"
#include "../../Helper/Logger.hpp"

Vector2d * GRAVITY_VECTOR = new Vector2d(0.0, -15.0);

PhysicsManager::PhysicsManager()
{
    m_pBodyArray = 0;
    EventBus::getSharedInstance()->addEventListener(this);
}
PhysicsManager::~PhysicsManager()
{

}

void PhysicsManager::update(float dt)
{
    if (m_pBodyArray == 0) {
        Log(LOG_ERROR, "PhysicsManager", "PBodiesArray is null!");
        return;
    }

    for (int i = 0; i < m_pBodyArray->m_index; i++) {
        if (m_pBodyArray->m_bodies[i]->isAffectedByGravity()) {
            m_pBodyArray->m_bodies[i]->addVector(GRAVITY_VECTOR);
            m_pBodyArray->m_bodies[i]->applyForce(dt);
        }
    }
    for (int i = 0; i < m_pBodyArray->m_index; i++) {
        for (int j = 0; j < m_pBodyArray->m_index; j++) {
            if (m_pBodyArray->m_bodies[i]->isStationary() && m_pBodyArray->m_bodies[i] != m_pBodyArray->m_bodies[j] && m_pBodyArray->m_bodies[i]->isColliding(m_pBodyArray->m_bodies[j])) {
                if (m_pBodyArray->m_bodies[i]->isAffectedByGravity()) {
                    m_pBodyArray->m_bodies[i]->revertForce(dt);
                    m_pBodyArray->m_bodies[i]->resetMovementVector();
                }
                if (m_pBodyArray->m_bodies[j]->isAffectedByGravity()) {
                    m_pBodyArray->m_bodies[j]->revertForce(dt);
                    m_pBodyArray->m_bodies[j]->resetMovementVector();
                }
                PBody**  source = new PBody*[2];
                source[0] = m_pBodyArray->m_bodies[i];
                source[1] =  m_pBodyArray->m_bodies[j];
                EventBus::getSharedInstance()->publishEvent(DID_COLLIDE, source);
                delete [] source;
            }
        }
    }
//    Log(LOG_INFO, "PhysicsManager", "Updating");
}

void PhysicsManager::addPBody(PBody* pBody)
{
    if (m_pBodyArray == 0)
        m_pBodyArray = new PBodyArray();

    if (m_pBodyArray->m_index == m_pBodyArray->m_size) {
        m_pBodyArray->m_size += 20;
        PBody** newPBody = new PBody*[m_pBodyArray->m_size];
        for (int i = 0; i < m_pBodyArray->m_index; i++) {
            newPBody[i] = m_pBodyArray->m_bodies[i];
        }
        m_pBodyArray->m_bodies = newPBody;
    }

    m_pBodyArray->m_bodies[m_pBodyArray->m_index++] = pBody;
}

void PhysicsManager::removePBody(PBody* pBody)
{
    for (int i = 0; i < m_pBodyArray->m_index; i++) {
        if (m_pBodyArray->m_bodies[i] == pBody) {
            m_pBodyArray->m_bodies[i] = m_pBodyArray->m_bodies[--m_pBodyArray->m_index];
        }
    }
}

bool PhysicsManager::isColliding(PBody* b1, PBody* b2)
{
    if (b1->getPosition()->m_x + b1->getSize()->m_x < b2->getPosition()->m_x)
        return false;
    if (b1->getPosition()->m_y > b2->getPosition()->m_y + b2->getSize()->m_y)
        return false;
    if (b1->getPosition()->m_x > b2->getPosition()->m_x + b2->getSize()->m_x)
        return false;
    if (b1->getPosition()->m_y + b1->getSize()->m_y < b2->getPosition()->m_y)
        return false;

    return true;
}

void PhysicsManager::onEvent (EEvent event, void* source)
{
    if (event == PBODY_CREATED)
        this->addPBody((PBody *)source);
}<commit_msg>Changed the PhysicsManager to complie with how the new PBody works.<commit_after>//
//  PhysicsManager.cpp
//  CatchiOS
//
//  Created by John Barbero Unenge on 10/7/12.
//  Copyright (c) 2012 John Barbero Unenge. All rights reserved.
//

#include "PhysicsManager.hpp"
#include "../../EventHandling/EventBus.hpp"
#include "../../Helper/Logger.hpp"

Vector2d* GRAVITY_VECTOR = new Vector2d(0.0, -15.);
Vector2d* VECTOR_X_ONLY = new Vector2d(1,0);
Vector2d* VECTOR_Y_ONLY = new Vector2d(0,1);

PhysicsManager::PhysicsManager()
{
    m_pBodyArray = 0;
    EventBus::getSharedInstance()->addEventListener(this);
}
PhysicsManager::~PhysicsManager()
{

}

void PhysicsManager::update(float dt)
{
    if (m_pBodyArray == 0) {
        Log(LOG_ERROR, "PhysicsManager", "PBodiesArray is null!");
        return;
    }

    for (int i = 0; i < m_pBodyArray->m_index; i++) {
        if (m_pBodyArray->m_bodies[i]->isAffectedByGravity()) {
            m_pBodyArray->m_bodies[i]->addVector(GRAVITY_VECTOR);
        }
    }

    for (int i = 0; i < m_pBodyArray->m_index; i++) {
        if (!m_pBodyArray->m_bodies[i]->isStationary()) {

            if (m_pBodyArray->m_bodies[i]->isAffectedByGravity()) {
                m_pBodyArray->m_bodies[i]->applyForceWithMask(VECTOR_X_ONLY, dt);

            for (int j = 0; j < m_pBodyArray->m_index; j++) {
                if (m_pBodyArray->m_bodies[i] != m_pBodyArray->m_bodies[j] && m_pBodyArray->m_bodies[i]->isCollidingWithBody(m_pBodyArray->m_bodies[j])) {
                    m_pBodyArray->m_bodies[i]->revertForceWithMask(VECTOR_X_ONLY, dt);
                    Vector2d v = *GRAVITY_VECTOR * *VECTOR_X_ONLY;
                    m_pBodyArray->m_bodies[i]->removeVector(&v);

                    // Extra logic when colliding on the X axis
                    m_pBodyArray->m_bodies[i]->maskMovementVector(0, 1);
                }
            }

            m_pBodyArray->m_bodies[i]->applyForceWithMask(VECTOR_Y_ONLY, dt);
            for (int j = 0; j < m_pBodyArray->m_index; j++) {
                if (m_pBodyArray->m_bodies[i] != m_pBodyArray->m_bodies[j] && m_pBodyArray->m_bodies[i]->isCollidingWithBody(m_pBodyArray->m_bodies[j])) {
                    m_pBodyArray->m_bodies[i]->revertForceWithMask(VECTOR_Y_ONLY, dt);
                    Vector2d v = *GRAVITY_VECTOR * *VECTOR_Y_ONLY;
                    m_pBodyArray->m_bodies[i]->removeVector(&v);

                    // Extra logic when colliding on the Y axis
                    m_pBodyArray->m_bodies[i]->maskMovementVector(1, 0);
                }
                }
            }
        }
    }
//    Log(LOG_INFO, "PhysicsManager", "Updating");
}

void PhysicsManager::addPBody(PBody* pBody)
{
    if (m_pBodyArray == 0)
        m_pBodyArray = new PBodyArray();

    if (m_pBodyArray->m_index == m_pBodyArray->m_size) {
        m_pBodyArray->m_size += 20;
        PBody** newPBody = new PBody*[m_pBodyArray->m_size];
        for (int i = 0; i < m_pBodyArray->m_index; i++) {
            newPBody[i] = m_pBodyArray->m_bodies[i];
        }
        m_pBodyArray->m_bodies = newPBody;
    }

    m_pBodyArray->m_bodies[m_pBodyArray->m_index++] = pBody;
}

void PhysicsManager::removePBody(PBody* pBody)
{
    for (int i = 0; i < m_pBodyArray->m_index; i++) {
        if (m_pBodyArray->m_bodies[i] == pBody) {
            m_pBodyArray->m_bodies[i] = m_pBodyArray->m_bodies[--m_pBodyArray->m_index];
        }
    }
}

void PhysicsManager::onEvent (EEvent event, void* source)
{
    if (event == PBODY_CREATED)
        this->addPBody((PBody *)source);
}<|endoftext|>


<commit_before>//===-- BuildSystemFrontend.cpp -------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "llbuild/BuildSystem/BuildSystemFrontend.h"

#include "llbuild/Basic/FileSystem.h"
#include "llbuild/Basic/LLVM.h"
#include "llbuild/BuildSystem/BuildExecutionQueue.h"
#include "llbuild/BuildSystem/BuildFile.h"

#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"

#include <atomic>
#include <memory>

#include <unistd.h>

using namespace llbuild;
using namespace llbuild::buildsystem;

#pragma mark - BuildSystemInvocation implementation

void BuildSystemInvocation::getUsage(int optionWidth, raw_ostream& os) {
  const struct Options {
    llvm::StringRef option, helpText;
  } options[] = {
    { "--help", "show this help message and exit" },
    { "-C <PATH>, --chdir <PATH>", "change directory to PATH before building" },
    { "--no-db", "disable use of a build database" },
    { "--db <PATH>", "enable building against the database at PATH" },
    { "-f <PATH>", "load the build task file at PATH" },
    { "--serial", "do not build in parallel" },
    { "-v, --verbose", "show verbose status information" },
    { "--trace <PATH>", "trace build engine operation to PATH" },
  };

  for (const auto& entry: options) {
    os << "  " << llvm::format("%-*s", optionWidth, entry.option) << " "
       << entry.helpText << "\n";
  }
}

void BuildSystemInvocation::parse(llvm::ArrayRef<std::string> args,
                                  llvm::SourceMgr& sourceMgr) {
  auto error = [&](const Twine &message) {
    sourceMgr.PrintMessage(llvm::SMLoc{}, llvm::SourceMgr::DK_Error, message);
    hadErrors = true;
  };

  while (!args.empty()) {
    const auto& option = args.front();
    args = args.slice(1);

    if (option == "-") {
      for (const auto& arg: args) {
        positionalArgs.push_back(arg);
      }
      break;
    }

    if (!option.empty() && option[0] != '-') {
      positionalArgs.push_back(option);
      continue;
    }

    if (option == "--help") {
      showUsage = true;
      break;
    } else if (option == "--no-db") {
      dbPath = "";
    } else if (option == "--db") {
      if (args.empty()) {
        error("missing argument to '" + option + "'");
        break;
      }
      dbPath = args[0];
      args = args.slice(1);
    } else if (option == "-C" || option == "--chdir") {
      if (args.empty()) {
        error("missing argument to '" + option + "'");
        break;
      }
      chdirPath = args[0];
      args = args.slice(1);
    } else if (option == "-f") {
      if (args.empty()) {
        error("missing argument to '" + option + "'");
        break;
      }
      buildFilePath = args[0];
      args = args.slice(1);
    } else if (option == "--serial") {
      useSerialBuild = true;
    } else if (option == "-v" || option == "--verbose") {
      showVerboseStatus = true;
    } else if (option == "--trace") {
      if (args.empty()) {
        error("missing argument to '" + option + "'");
        break;
      }
      traceFilePath = args[0];
      args = args.slice(1);
    } else {
      error("invalid option '" + option + "'");
      break;
    }
  }
}

#pragma mark - BuildSystemFrontendDelegate implementation

namespace {

struct BuildSystemFrontendDelegateImpl;

class BuildSystemFrontendExecutionQueueDelegate
      : public BuildExecutionQueueDelegate {
  BuildSystemFrontendDelegateImpl &delegateImpl;

  bool showVerboseOutput() const;

  BuildSystem& getSystem() const;

public:
  BuildSystemFrontendExecutionQueueDelegate(
          BuildSystemFrontendDelegateImpl& delegateImpl)
      : delegateImpl(delegateImpl) { }

  virtual void commandStarted(Command* command) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandStarted(command);
  }

  virtual void commandFinished(Command* command) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandFinished(command);
  }

  virtual void commandProcessStarted(Command* command,
                                     ProcessHandle handle) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandProcessStarted(
          command, BuildSystemFrontendDelegate::ProcessHandle { handle.id });
  }

  virtual void commandProcessHadError(Command* command, ProcessHandle handle,
                                      const Twine& message) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandProcessHadError(
          command, BuildSystemFrontendDelegate::ProcessHandle { handle.id },
          message);
  }

  virtual void commandProcessHadOutput(Command* command, ProcessHandle handle,
                                       StringRef data) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandProcessHadOutput(
          command, BuildSystemFrontendDelegate::ProcessHandle { handle.id },
          data);
  }

  virtual void commandProcessFinished(Command* command, ProcessHandle handle,
                                      int exitStatus) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandProcessFinished(
          command, BuildSystemFrontendDelegate::ProcessHandle { handle.id },
          exitStatus);
  }
};

struct BuildSystemFrontendDelegateImpl {
  llvm::SourceMgr& sourceMgr;
  const BuildSystemInvocation& invocation;

  StringRef bufferBeingParsed;
  std::atomic<unsigned> numErrors{0};
  std::atomic<unsigned> numFailedCommands{0};

  BuildSystemFrontendExecutionQueueDelegate executionQueueDelegate;

  BuildSystemFrontend* frontend = nullptr;
  BuildSystem* system = nullptr;

  BuildSystemFrontendDelegateImpl(llvm::SourceMgr& sourceMgr,
                                  const BuildSystemInvocation& invocation)
      : sourceMgr(sourceMgr), invocation(invocation),
        executionQueueDelegate(*this) {}
};

bool BuildSystemFrontendExecutionQueueDelegate::showVerboseOutput() const {
  return delegateImpl.invocation.showVerboseStatus;
}

BuildSystem& BuildSystemFrontendExecutionQueueDelegate::getSystem() const {
  assert(delegateImpl.system);
  return *delegateImpl.system;
}

}

BuildSystemFrontendDelegate::
BuildSystemFrontendDelegate(llvm::SourceMgr& sourceMgr,
                            const BuildSystemInvocation& invocation,
                            StringRef name,
                            uint32_t version)
    : BuildSystemDelegate(name, version),
      impl(new BuildSystemFrontendDelegateImpl(sourceMgr, invocation))
{

}

BuildSystemFrontendDelegate::~BuildSystemFrontendDelegate() {
  delete static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);
}

void
BuildSystemFrontendDelegate::setFileContentsBeingParsed(StringRef buffer) {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  impl->bufferBeingParsed = buffer;
}

BuildSystemFrontend& BuildSystemFrontendDelegate::getFrontend() {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  return *impl->frontend;
}

llvm::SourceMgr& BuildSystemFrontendDelegate::getSourceMgr() {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  return impl->sourceMgr;
}

unsigned BuildSystemFrontendDelegate::getNumErrors() {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  return impl->numErrors;
}

unsigned BuildSystemFrontendDelegate::getNumFailedCommands() {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  return impl->numFailedCommands;
}

void
BuildSystemFrontendDelegate::error(const Twine& message) {
  error("", {}, message.str());
}

void
BuildSystemFrontendDelegate::error(StringRef filename,
                                   const Token& at,
                                   const Twine& message) {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  ++impl->numErrors;

  // If we have a file and token, resolve the location and range to one
  // accessible by the source manager.
  //
  // FIXME: We shouldn't need to do this, but should switch llbuild to using
  // SourceMgr natively.
  llvm::SMLoc loc{};
  llvm::SMRange range{};
  if (!filename.empty() && at.start) {
    // FIXME: We ignore errors here, for now, this will be resolved when we move
    // to SourceMgr completely.
    auto buffer = getFileSystem().getFileContents(filename);
    if (buffer) {
      unsigned offset = at.start - impl->bufferBeingParsed.data();
      if (offset + at.length < buffer->getBufferSize()) {
        range.Start = loc = llvm::SMLoc::getFromPointer(
            buffer->getBufferStart() + offset);
        range.End = llvm::SMLoc::getFromPointer(
            buffer->getBufferStart() + (offset + at.length));
        getSourceMgr().AddNewSourceBuffer(std::move(buffer), llvm::SMLoc{});
      }
    }
  }

  if (range.Start.isValid()) {
    getSourceMgr().PrintMessage(loc, llvm::SourceMgr::DK_Error, message, range);
  } else {
    getSourceMgr().PrintMessage(loc, llvm::SourceMgr::DK_Error, message);
  }
  fflush(stderr);
}

std::unique_ptr<BuildExecutionQueue>
BuildSystemFrontendDelegate::createExecutionQueue() {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  if (impl->invocation.useSerialBuild) {
    return std::unique_ptr<BuildExecutionQueue>(
        createLaneBasedExecutionQueue(impl->executionQueueDelegate, 1));
  }

  // Get the number of CPUs to use.
  long numCPUs = sysconf(_SC_NPROCESSORS_ONLN);
  unsigned numLanes;
  if (numCPUs < 0) {
    error("<unknown>", {}, "unable to detect number of CPUs");
    numLanes = 1;
  } else {
    numLanes = numCPUs + 2;
  }

  return std::unique_ptr<BuildExecutionQueue>(
      createLaneBasedExecutionQueue(impl->executionQueueDelegate, numLanes));
}

bool BuildSystemFrontendDelegate::isCancelled() {
  // Stop the build after any command failures.
  return getNumFailedCommands() > 0;
}

void BuildSystemFrontendDelegate::hadCommandFailure() {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  // Increment the failed command count.
  ++impl->numFailedCommands;
}

void BuildSystemFrontendDelegate::commandStarted(Command*) {
}

void BuildSystemFrontendDelegate::commandFinished(Command*) {
}

void BuildSystemFrontendDelegate::commandProcessStarted(Command* command,
                                                        ProcessHandle handle) {
  // Log the command.
  //
  // FIXME: Design the logging and status output APIs.
  SmallString<64> description;
  if (getFrontend().getInvocation().showVerboseStatus) {
    command->getVerboseDescription(description);
  } else {
    command->getShortDescription(description);

    // If the short description is empty, always show the verbose one.
    if (description.empty()) {
      command->getVerboseDescription(description);
    }
  }
  fprintf(stdout, "%s\n", description.c_str());
  fflush(stdout);
}

void BuildSystemFrontendDelegate::
commandProcessHadError(Command* command, ProcessHandle handle,
                       const Twine& message) {
  SmallString<256> buffer;
  auto str = message.toStringRef(buffer);

  // FIXME: Design the logging and status output APIs.
  fwrite(str.data(), str.size(), 1, stderr);
  fputc('\n', stderr);
  fflush(stderr);
}

void BuildSystemFrontendDelegate::
commandProcessHadOutput(Command* command, ProcessHandle handle,
                        StringRef data) {
  // FIXME: Design the logging and status output APIs.
  fwrite(data.data(), data.size(), 1, stdout);
  fflush(stdout);
}

void BuildSystemFrontendDelegate::
commandProcessFinished(Command*, ProcessHandle handle,
                       int exitStatus) {
}

#pragma mark - BuildSystemFrontend implementation

BuildSystemFrontend::
BuildSystemFrontend(BuildSystemFrontendDelegate& delegate,
                    const BuildSystemInvocation& invocation)
    : delegate(delegate), invocation(invocation)
{
  auto delegateImpl =
    static_cast<BuildSystemFrontendDelegateImpl*>(delegate.impl);

  delegateImpl->frontend = this;
}

bool BuildSystemFrontend::build(StringRef targetToBuild) {
  // Honor the --chdir option, if used.
  if (!invocation.chdirPath.empty()) {
    if (::chdir(invocation.chdirPath.c_str()) < 0) {
      getDelegate().error(Twine("unable to honor --chdir: ") + strerror(errno));
      return false;
    }
  }

  // Create the build system.
  BuildSystem system(delegate, invocation.buildFilePath);

  // Register the system back pointer.
  //
  // FIXME: Eliminate this.
  auto delegateImpl =
    static_cast<BuildSystemFrontendDelegateImpl*>(delegate.impl);
  delegateImpl->system = &system;

  // Enable tracing, if requested.
  if (!invocation.traceFilePath.empty()) {
    std::string error;
    if (!system.enableTracing(invocation.traceFilePath, &error)) {
      getDelegate().error(Twine("unable to enable tracing: ") + error);
      return false;
    }
  }

  // Attach the database.
  if (!invocation.dbPath.empty()) {
    // If the database path is relative, always make it relative to the input
    // file.
    SmallString<256> tmp;
    StringRef dbPath = invocation.dbPath;
    if (llvm::sys::path::has_relative_path(invocation.dbPath)) {
      llvm::sys::path::append(
          tmp, llvm::sys::path::parent_path(invocation.buildFilePath),
          invocation.dbPath);
      dbPath = tmp.str();
    }

    std::string error;
    if (!system.attachDB(dbPath, &error)) {
      getDelegate().error(Twine("unable to attach DB: ") + error);
      return false;
    }
  }

  // If something unspecified failed about the build, return an error.
  if (!system.build(targetToBuild)) {
    return false;
  }

  // If there were failed commands, report the count and return an error.
  if (delegate.getNumFailedCommands()) {
    getDelegate().error("build had " + Twine(delegate.getNumFailedCommands()) +
                        " command failures");
    return false;
  }

  // Otherwise, return an error only if there were unspecified errors.
  return delegate.getNumErrors() == 0;
}
<commit_msg>[BuildSystem] Fix the check for dbPath relativeness.<commit_after>//===-- BuildSystemFrontend.cpp -------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "llbuild/BuildSystem/BuildSystemFrontend.h"

#include "llbuild/Basic/FileSystem.h"
#include "llbuild/Basic/LLVM.h"
#include "llbuild/BuildSystem/BuildExecutionQueue.h"
#include "llbuild/BuildSystem/BuildFile.h"

#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"

#include <atomic>
#include <memory>

#include <unistd.h>

using namespace llbuild;
using namespace llbuild::buildsystem;

#pragma mark - BuildSystemInvocation implementation

void BuildSystemInvocation::getUsage(int optionWidth, raw_ostream& os) {
  const struct Options {
    llvm::StringRef option, helpText;
  } options[] = {
    { "--help", "show this help message and exit" },
    { "-C <PATH>, --chdir <PATH>", "change directory to PATH before building" },
    { "--no-db", "disable use of a build database" },
    { "--db <PATH>", "enable building against the database at PATH" },
    { "-f <PATH>", "load the build task file at PATH" },
    { "--serial", "do not build in parallel" },
    { "-v, --verbose", "show verbose status information" },
    { "--trace <PATH>", "trace build engine operation to PATH" },
  };

  for (const auto& entry: options) {
    os << "  " << llvm::format("%-*s", optionWidth, entry.option) << " "
       << entry.helpText << "\n";
  }
}

void BuildSystemInvocation::parse(llvm::ArrayRef<std::string> args,
                                  llvm::SourceMgr& sourceMgr) {
  auto error = [&](const Twine &message) {
    sourceMgr.PrintMessage(llvm::SMLoc{}, llvm::SourceMgr::DK_Error, message);
    hadErrors = true;
  };

  while (!args.empty()) {
    const auto& option = args.front();
    args = args.slice(1);

    if (option == "-") {
      for (const auto& arg: args) {
        positionalArgs.push_back(arg);
      }
      break;
    }

    if (!option.empty() && option[0] != '-') {
      positionalArgs.push_back(option);
      continue;
    }

    if (option == "--help") {
      showUsage = true;
      break;
    } else if (option == "--no-db") {
      dbPath = "";
    } else if (option == "--db") {
      if (args.empty()) {
        error("missing argument to '" + option + "'");
        break;
      }
      dbPath = args[0];
      args = args.slice(1);
    } else if (option == "-C" || option == "--chdir") {
      if (args.empty()) {
        error("missing argument to '" + option + "'");
        break;
      }
      chdirPath = args[0];
      args = args.slice(1);
    } else if (option == "-f") {
      if (args.empty()) {
        error("missing argument to '" + option + "'");
        break;
      }
      buildFilePath = args[0];
      args = args.slice(1);
    } else if (option == "--serial") {
      useSerialBuild = true;
    } else if (option == "-v" || option == "--verbose") {
      showVerboseStatus = true;
    } else if (option == "--trace") {
      if (args.empty()) {
        error("missing argument to '" + option + "'");
        break;
      }
      traceFilePath = args[0];
      args = args.slice(1);
    } else {
      error("invalid option '" + option + "'");
      break;
    }
  }
}

#pragma mark - BuildSystemFrontendDelegate implementation

namespace {

struct BuildSystemFrontendDelegateImpl;

class BuildSystemFrontendExecutionQueueDelegate
      : public BuildExecutionQueueDelegate {
  BuildSystemFrontendDelegateImpl &delegateImpl;

  bool showVerboseOutput() const;

  BuildSystem& getSystem() const;

public:
  BuildSystemFrontendExecutionQueueDelegate(
          BuildSystemFrontendDelegateImpl& delegateImpl)
      : delegateImpl(delegateImpl) { }

  virtual void commandStarted(Command* command) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandStarted(command);
  }

  virtual void commandFinished(Command* command) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandFinished(command);
  }

  virtual void commandProcessStarted(Command* command,
                                     ProcessHandle handle) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandProcessStarted(
          command, BuildSystemFrontendDelegate::ProcessHandle { handle.id });
  }

  virtual void commandProcessHadError(Command* command, ProcessHandle handle,
                                      const Twine& message) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandProcessHadError(
          command, BuildSystemFrontendDelegate::ProcessHandle { handle.id },
          message);
  }

  virtual void commandProcessHadOutput(Command* command, ProcessHandle handle,
                                       StringRef data) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandProcessHadOutput(
          command, BuildSystemFrontendDelegate::ProcessHandle { handle.id },
          data);
  }

  virtual void commandProcessFinished(Command* command, ProcessHandle handle,
                                      int exitStatus) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandProcessFinished(
          command, BuildSystemFrontendDelegate::ProcessHandle { handle.id },
          exitStatus);
  }
};

struct BuildSystemFrontendDelegateImpl {
  llvm::SourceMgr& sourceMgr;
  const BuildSystemInvocation& invocation;

  StringRef bufferBeingParsed;
  std::atomic<unsigned> numErrors{0};
  std::atomic<unsigned> numFailedCommands{0};

  BuildSystemFrontendExecutionQueueDelegate executionQueueDelegate;

  BuildSystemFrontend* frontend = nullptr;
  BuildSystem* system = nullptr;

  BuildSystemFrontendDelegateImpl(llvm::SourceMgr& sourceMgr,
                                  const BuildSystemInvocation& invocation)
      : sourceMgr(sourceMgr), invocation(invocation),
        executionQueueDelegate(*this) {}
};

bool BuildSystemFrontendExecutionQueueDelegate::showVerboseOutput() const {
  return delegateImpl.invocation.showVerboseStatus;
}

BuildSystem& BuildSystemFrontendExecutionQueueDelegate::getSystem() const {
  assert(delegateImpl.system);
  return *delegateImpl.system;
}

}

BuildSystemFrontendDelegate::
BuildSystemFrontendDelegate(llvm::SourceMgr& sourceMgr,
                            const BuildSystemInvocation& invocation,
                            StringRef name,
                            uint32_t version)
    : BuildSystemDelegate(name, version),
      impl(new BuildSystemFrontendDelegateImpl(sourceMgr, invocation))
{

}

BuildSystemFrontendDelegate::~BuildSystemFrontendDelegate() {
  delete static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);
}

void
BuildSystemFrontendDelegate::setFileContentsBeingParsed(StringRef buffer) {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  impl->bufferBeingParsed = buffer;
}

BuildSystemFrontend& BuildSystemFrontendDelegate::getFrontend() {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  return *impl->frontend;
}

llvm::SourceMgr& BuildSystemFrontendDelegate::getSourceMgr() {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  return impl->sourceMgr;
}

unsigned BuildSystemFrontendDelegate::getNumErrors() {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  return impl->numErrors;
}

unsigned BuildSystemFrontendDelegate::getNumFailedCommands() {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  return impl->numFailedCommands;
}

void
BuildSystemFrontendDelegate::error(const Twine& message) {
  error("", {}, message.str());
}

void
BuildSystemFrontendDelegate::error(StringRef filename,
                                   const Token& at,
                                   const Twine& message) {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  ++impl->numErrors;

  // If we have a file and token, resolve the location and range to one
  // accessible by the source manager.
  //
  // FIXME: We shouldn't need to do this, but should switch llbuild to using
  // SourceMgr natively.
  llvm::SMLoc loc{};
  llvm::SMRange range{};
  if (!filename.empty() && at.start) {
    // FIXME: We ignore errors here, for now, this will be resolved when we move
    // to SourceMgr completely.
    auto buffer = getFileSystem().getFileContents(filename);
    if (buffer) {
      unsigned offset = at.start - impl->bufferBeingParsed.data();
      if (offset + at.length < buffer->getBufferSize()) {
        range.Start = loc = llvm::SMLoc::getFromPointer(
            buffer->getBufferStart() + offset);
        range.End = llvm::SMLoc::getFromPointer(
            buffer->getBufferStart() + (offset + at.length));
        getSourceMgr().AddNewSourceBuffer(std::move(buffer), llvm::SMLoc{});
      }
    }
  }

  if (range.Start.isValid()) {
    getSourceMgr().PrintMessage(loc, llvm::SourceMgr::DK_Error, message, range);
  } else {
    getSourceMgr().PrintMessage(loc, llvm::SourceMgr::DK_Error, message);
  }
  fflush(stderr);
}

std::unique_ptr<BuildExecutionQueue>
BuildSystemFrontendDelegate::createExecutionQueue() {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  if (impl->invocation.useSerialBuild) {
    return std::unique_ptr<BuildExecutionQueue>(
        createLaneBasedExecutionQueue(impl->executionQueueDelegate, 1));
  }

  // Get the number of CPUs to use.
  long numCPUs = sysconf(_SC_NPROCESSORS_ONLN);
  unsigned numLanes;
  if (numCPUs < 0) {
    error("<unknown>", {}, "unable to detect number of CPUs");
    numLanes = 1;
  } else {
    numLanes = numCPUs + 2;
  }

  return std::unique_ptr<BuildExecutionQueue>(
      createLaneBasedExecutionQueue(impl->executionQueueDelegate, numLanes));
}

bool BuildSystemFrontendDelegate::isCancelled() {
  // Stop the build after any command failures.
  return getNumFailedCommands() > 0;
}

void BuildSystemFrontendDelegate::hadCommandFailure() {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  // Increment the failed command count.
  ++impl->numFailedCommands;
}

void BuildSystemFrontendDelegate::commandStarted(Command*) {
}

void BuildSystemFrontendDelegate::commandFinished(Command*) {
}

void BuildSystemFrontendDelegate::commandProcessStarted(Command* command,
                                                        ProcessHandle handle) {
  // Log the command.
  //
  // FIXME: Design the logging and status output APIs.
  SmallString<64> description;
  if (getFrontend().getInvocation().showVerboseStatus) {
    command->getVerboseDescription(description);
  } else {
    command->getShortDescription(description);

    // If the short description is empty, always show the verbose one.
    if (description.empty()) {
      command->getVerboseDescription(description);
    }
  }
  fprintf(stdout, "%s\n", description.c_str());
  fflush(stdout);
}

void BuildSystemFrontendDelegate::
commandProcessHadError(Command* command, ProcessHandle handle,
                       const Twine& message) {
  SmallString<256> buffer;
  auto str = message.toStringRef(buffer);

  // FIXME: Design the logging and status output APIs.
  fwrite(str.data(), str.size(), 1, stderr);
  fputc('\n', stderr);
  fflush(stderr);
}

void BuildSystemFrontendDelegate::
commandProcessHadOutput(Command* command, ProcessHandle handle,
                        StringRef data) {
  // FIXME: Design the logging and status output APIs.
  fwrite(data.data(), data.size(), 1, stdout);
  fflush(stdout);
}

void BuildSystemFrontendDelegate::
commandProcessFinished(Command*, ProcessHandle handle,
                       int exitStatus) {
}

#pragma mark - BuildSystemFrontend implementation

BuildSystemFrontend::
BuildSystemFrontend(BuildSystemFrontendDelegate& delegate,
                    const BuildSystemInvocation& invocation)
    : delegate(delegate), invocation(invocation)
{
  auto delegateImpl =
    static_cast<BuildSystemFrontendDelegateImpl*>(delegate.impl);

  delegateImpl->frontend = this;
}

bool BuildSystemFrontend::build(StringRef targetToBuild) {
  // Honor the --chdir option, if used.
  if (!invocation.chdirPath.empty()) {
    if (::chdir(invocation.chdirPath.c_str()) < 0) {
      getDelegate().error(Twine("unable to honor --chdir: ") + strerror(errno));
      return false;
    }
  }

  // Create the build system.
  BuildSystem system(delegate, invocation.buildFilePath);

  // Register the system back pointer.
  //
  // FIXME: Eliminate this.
  auto delegateImpl =
    static_cast<BuildSystemFrontendDelegateImpl*>(delegate.impl);
  delegateImpl->system = &system;

  // Enable tracing, if requested.
  if (!invocation.traceFilePath.empty()) {
    std::string error;
    if (!system.enableTracing(invocation.traceFilePath, &error)) {
      getDelegate().error(Twine("unable to enable tracing: ") + error);
      return false;
    }
  }

  // Attach the database.
  if (!invocation.dbPath.empty()) {
    // If the database path is relative, always make it relative to the input
    // file.
    SmallString<256> tmp;
    StringRef dbPath = invocation.dbPath;
    if (llvm::sys::path::is_relative(invocation.dbPath) && dbPath.find("://") == StringRef::npos && !dbPath.startswith(":")) {
      llvm::sys::path::append(
          tmp, llvm::sys::path::parent_path(invocation.buildFilePath),
          invocation.dbPath);
      dbPath = tmp.str();
    }

    std::string error;
    if (!system.attachDB(dbPath, &error)) {
      getDelegate().error(Twine("unable to attach DB: ") + error);
      return false;
    }
  }

  // If something unspecified failed about the build, return an error.
  if (!system.build(targetToBuild)) {
    return false;
  }

  // If there were failed commands, report the count and return an error.
  if (delegate.getNumFailedCommands()) {
    getDelegate().error("build had " + Twine(delegate.getNumFailedCommands()) +
                        " command failures");
    return false;
  }

  // Otherwise, return an error only if there were unspecified errors.
  return delegate.getNumErrors() == 0;
}
<|endoftext|>


<commit_before>//===-- AlphaTargetAsmInfo.cpp - Alpha asm properties -----------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the AlphaTargetAsmInfo properties.
//
//===----------------------------------------------------------------------===//

#include "AlphaTargetMachine.h"
#include "AlphaTargetAsmInfo.h"

using namespace llvm;

AlphaTargetAsmInfo::AlphaTargetAsmInfo(const AlphaTargetMachine &TM)
  : TargetAsmInfo(TM) {
  AlignmentIsInBytes = false;
  PrivateGlobalPrefix = "$";
  JumpTableDirective = ".gprel32";
  JumpTableDataSection = "\t.section .rodata\n";
  WeakRefDirective = "\t.weak\t";
}
<commit_msg>Apparently alpha doesn't use ElfTargetAsmInfo (?)<commit_after>//===-- AlphaTargetAsmInfo.cpp - Alpha asm properties -----------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of the AlphaTargetAsmInfo properties.
//
//===----------------------------------------------------------------------===//

#include "AlphaTargetMachine.h"
#include "AlphaTargetAsmInfo.h"

using namespace llvm;

AlphaTargetAsmInfo::AlphaTargetAsmInfo(const AlphaTargetMachine &TM)
  : TargetAsmInfo(TM) {
  AlignmentIsInBytes = false;
  PrivateGlobalPrefix = "$";
  JumpTableDirective = ".gprel32";
  JumpTableDataSection = "\t.section .rodata\n";
  WeakRefDirective = "\t.weak\t";

  TextSection = getOrCreateSection("_text", true, SectionKind::Text);
  DataSection = getOrCreateSection("_data", true, SectionKind::DataRel);
}
<|endoftext|>