<commit_before>// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
// SPDX-License-Identifier: MIT
// Copyright (c) 2019 Daniil Goncharov <neargye@gmail.com>.
//
// 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.

#define CATCH_CONFIG_MAIN
#include <catch.hpp>

#define MAGIC_ENUM_RANGE 120
#include <magic_enum.hpp>

#include <array>
#include <string>
#include <sstream>

enum class Color { RED = -12, GREEN = 7, BLUE = 15 };

enum class Numbers : char { one = 10, two = 20, three = 30 };

enum Directions { Up = 85, Down = -42, Right = 119, Left = -119 };

enum number : unsigned long { one = 10, two = 20, three = 30 };

TEST_CASE("enum_cast") {
  SECTION("string") {
#if defined(_MSC_VER) && _MSC_VER < 1920
#  define constexpr // Visual Studio 2017 have bug with string_view constexpr compare.
#endif

    constexpr auto cr = yae::enum_cast<Color>("RED");
    REQUIRE(cr.value() == Color::RED);
    REQUIRE(yae::enum_cast<Color>("GREEN").value() == Color::GREEN);
    REQUIRE(yae::enum_cast<Color>("BLUE").value() == Color::BLUE);
    REQUIRE_FALSE(yae::enum_cast<Color>("None").has_value());

    constexpr auto no = yae::enum_cast<Numbers>("one");
    REQUIRE(no.value() == Numbers::one);
    REQUIRE(yae::enum_cast<Numbers>("two").value() == Numbers::two);
    REQUIRE(yae::enum_cast<Numbers>("three").value() == Numbers::three);
    REQUIRE_FALSE(yae::enum_cast<Numbers>("None").has_value());

    constexpr auto dr = yae::enum_cast<Directions>("Right");
    REQUIRE(yae::enum_cast<Directions>("Up").value() == Directions::Up);
    REQUIRE(yae::enum_cast<Directions>("Down").value() == Directions::Down);
    REQUIRE(dr.value() == Directions::Right);
    REQUIRE(yae::enum_cast<Directions>("Left").value() == Directions::Left);
    REQUIRE_FALSE(yae::enum_cast<Directions>("None").has_value());

    constexpr auto nt = yae::enum_cast<number>("three");
    REQUIRE(yae::enum_cast<number>("one").value() == number::one);
    REQUIRE(yae::enum_cast<number>("two").value() == number::two);
    REQUIRE(nt.value() == number::three);
    REQUIRE_FALSE(yae::enum_cast<number>("None").has_value());

#undef constexpr
  }

  SECTION("string") {
    constexpr auto cr = yae::enum_cast<Color>(-12);
    REQUIRE(cr.value() == Color::RED);
    REQUIRE(yae::enum_cast<Color>(7).value() == Color::GREEN);
    REQUIRE(yae::enum_cast<Color>(15).value() == Color::BLUE);
    REQUIRE_FALSE(yae::enum_cast<Color>(0).has_value());

    constexpr auto no = yae::enum_cast<Numbers>(10);
    REQUIRE(no.value() == Numbers::one);
    REQUIRE(yae::enum_cast<Numbers>(20).value() == Numbers::two);
    REQUIRE(yae::enum_cast<Numbers>(30).value() == Numbers::three);
    REQUIRE_FALSE(yae::enum_cast<Numbers>(0).has_value());

    constexpr auto dr = yae::enum_cast<Directions>(119);
    REQUIRE(yae::enum_cast<Directions>(85).value() == Directions::Up);
    REQUIRE(yae::enum_cast<Directions>(-42).value() == Directions::Down);
    REQUIRE(dr.value() == Directions::Right);
    REQUIRE(yae::enum_cast<Directions>(-119).value() == Directions::Left);
    REQUIRE_FALSE(yae::enum_cast<Directions>(0).has_value());

    constexpr auto nt = yae::enum_cast<number>(30);
    REQUIRE(yae::enum_cast<number>(10).value() == number::one);
    REQUIRE(yae::enum_cast<number>(20).value() == number::two);
    REQUIRE(nt.value() == number::three);
    REQUIRE_FALSE(yae::enum_cast<number>(0).has_value());
  }
}

TEST_CASE("enum_value") {
 constexpr auto cr = yae::enum_value<Color>(0);
  REQUIRE(cr == Color::RED);
  REQUIRE(yae::enum_value<Color>(1) == Color::GREEN);
  REQUIRE(yae::enum_value<Color>(2) == Color::BLUE);

  constexpr auto no = yae::enum_value<Numbers>(0);
  REQUIRE(no == Numbers::one);
  REQUIRE(yae::enum_value<Numbers>(1) == Numbers::two);
  REQUIRE(yae::enum_value<Numbers>(2) == Numbers::three);

  constexpr auto dr = yae::enum_value<Directions>(3);
  REQUIRE(yae::enum_value<Directions>(0) == Directions::Left);
  REQUIRE(yae::enum_value<Directions>(1) == Directions::Down);
  REQUIRE(yae::enum_value<Directions>(2) == Directions::Up);
  REQUIRE(dr == Directions::Right);

  constexpr auto nt = yae::enum_value<number>(2);
  REQUIRE(yae::enum_value<number>(0) == number::one);
  REQUIRE(yae::enum_value<number>(1) == number::two);
  REQUIRE(nt == number::three);
}

TEST_CASE("enum_values") {
  constexpr auto mge_s1 = yae::enum_values<Color>();
  REQUIRE(mge_s1 == std::array<Color, 3>{Color::RED, Color::GREEN, Color::BLUE});

  constexpr auto mge_s2 = yae::enum_values<Numbers>();
  REQUIRE(mge_s2 == std::array<Numbers, 3>{Numbers::one, Numbers::two, Numbers::three});

  constexpr auto mge_s3 = yae::enum_values<Directions>();
  REQUIRE(mge_s3 == std::array<Directions, 4>{Directions::Left, Directions::Down, Directions::Up, Directions::Right});

  constexpr auto mge_s4 = yae::enum_values<number>();
  REQUIRE(mge_s4 == std::array<number, 3>{number::one, number::two, number::three});
}

TEST_CASE("enum_count") {
  constexpr auto mge_s1 = yae::enum_count<Color>();
  REQUIRE(mge_s1 == 3);

  constexpr auto mge_s2 = yae::enum_count<Numbers>();
  REQUIRE(mge_s2 == 3);

  constexpr auto mge_s3 = yae::enum_count<Directions>();
  REQUIRE(mge_s3 == 4);

  constexpr auto mge_s4 = yae::enum_count<number>();
  REQUIRE(mge_s4 == 3);
}

TEST_CASE("enum_name") {
  constexpr Color cr = Color::RED;
  constexpr auto cr_name = yae::enum_name(cr);
  Color cm[3] = {Color::RED, Color::GREEN, Color::BLUE};
  REQUIRE(cr_name.value() == "RED");
  REQUIRE(yae::enum_name(Color::BLUE).value() == "BLUE");
  REQUIRE(yae::enum_name(cm[1]).value() == "GREEN");
  REQUIRE_FALSE(yae::enum_name(static_cast<Color>(MAGIC_ENUM_RANGE)).has_value());
  REQUIRE_FALSE(yae::enum_name(static_cast<Color>(-MAGIC_ENUM_RANGE)).has_value());

  constexpr Numbers no = Numbers::one;
  constexpr auto no_name = yae::enum_name(no);
  REQUIRE(no_name.value() == "one");
  REQUIRE(yae::enum_name(Numbers::two).value() == "two");
  REQUIRE(yae::enum_name(Numbers::three).value() == "three");
  REQUIRE_FALSE(yae::enum_name(static_cast<Numbers>(MAGIC_ENUM_RANGE)).has_value());
  REQUIRE_FALSE(yae::enum_name(static_cast<Numbers>(-MAGIC_ENUM_RANGE)).has_value());

  constexpr Directions dr = Directions::Right;
  constexpr auto dr_name = yae::enum_name(dr);
  REQUIRE(yae::enum_name(Directions::Up).value() == "Up");
  REQUIRE(yae::enum_name(Directions::Down).value() == "Down");
  REQUIRE(dr_name.value() == "Right");
  REQUIRE(yae::enum_name(Directions::Left).value() == "Left");
  REQUIRE_FALSE(yae::enum_name(static_cast<Directions>(MAGIC_ENUM_RANGE)).has_value());
  REQUIRE_FALSE(yae::enum_name(static_cast<Directions>(-MAGIC_ENUM_RANGE)).has_value());

  constexpr number nt = number::three;
  constexpr auto nt_name = yae::enum_name(nt);
  REQUIRE(yae::enum_name(number::one).value() == "one");
  REQUIRE(yae::enum_name(number::two).value() == "two");
  REQUIRE(nt_name.value() == "three");
  REQUIRE_FALSE(yae::enum_name(static_cast<number>(MAGIC_ENUM_RANGE)).has_value());
  REQUIRE_FALSE(yae::enum_name(static_cast<number>(-MAGIC_ENUM_RANGE)).has_value());
}

TEST_CASE("enum_names") {
  constexpr auto mge_s1 = yae::enum_names<Color>();
  REQUIRE(mge_s1 == std::array<std::string_view, 3>{"RED", "GREEN", "BLUE"});

  constexpr auto mge_s2 = yae::enum_names<Numbers>();
  REQUIRE(mge_s2 == std::array<std::string_view, 3>{"one", "two", "three"});

  constexpr auto mge_s3 = yae::enum_names<Directions>();
  REQUIRE(mge_s3 == std::array<std::string_view, 4>{"Left", "Down", "Up", "Right"});

  constexpr auto mge_s4 = yae::enum_names<number>();
  REQUIRE(mge_s4 == std::array<std::string_view, 3>{"one", "two", "three"});
}

TEST_CASE("operator<<") {
  auto test_ostream = [](auto e, std::string_view name) {
    using namespace yae::ops;
    std::stringstream ss;
    ss << e;
    REQUIRE(ss.str() == name);
  };

  test_ostream(Color::RED, "RED");
  test_ostream(Color::GREEN, "GREEN");
  test_ostream(Color::BLUE, "BLUE");
  test_ostream((Color)0, "");

  test_ostream(Numbers::one, "one");
  test_ostream(Numbers::two, "two");
  test_ostream(Numbers::three, "three");
  test_ostream((Numbers)0, "");

  test_ostream(Directions::Up, "Up");
  test_ostream(Directions::Down, "Down");
  test_ostream(Directions::Right, "Right");
  test_ostream(Directions::Left, "Left");
  test_ostream((Directions)0, "");

  test_ostream(number::one, "one");
  test_ostream(number::two, "two");
  test_ostream(number::three, "three");
  test_ostream((number)0, "");
}
<commit_msg>fix warnings<commit_after>// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
// SPDX-License-Identifier: MIT
// Copyright (c) 2019 Daniil Goncharov <neargye@gmail.com>.
//
// 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.

#define CATCH_CONFIG_MAIN
#include <catch.hpp>

#define MAGIC_ENUM_RANGE 120
#include <magic_enum.hpp>

#include <array>
#include <string_view>
#include <sstream>

enum class Color { RED = -12, GREEN = 7, BLUE = 15 };

enum class Numbers : char { one = 10, two = 20, three = 30 };

enum Directions { Up = 85, Down = -42, Right = 119, Left = -119 };

enum number : unsigned long { one = 10, two = 20, three = 30 };

TEST_CASE("enum_cast") {
  SECTION("string") {
#if defined(_MSC_VER) && _MSC_VER < 1920
#  define constexpr // Visual Studio 2017 have bug with string_view constexpr compare.
#endif

    constexpr auto cr = yae::enum_cast<Color>("RED");
    REQUIRE(cr.value() == Color::RED);
    REQUIRE(yae::enum_cast<Color>("GREEN").value() == Color::GREEN);
    REQUIRE(yae::enum_cast<Color>("BLUE").value() == Color::BLUE);
    REQUIRE_FALSE(yae::enum_cast<Color>("None").has_value());

    constexpr auto no = yae::enum_cast<Numbers>("one");
    REQUIRE(no.value() == Numbers::one);
    REQUIRE(yae::enum_cast<Numbers>("two").value() == Numbers::two);
    REQUIRE(yae::enum_cast<Numbers>("three").value() == Numbers::three);
    REQUIRE_FALSE(yae::enum_cast<Numbers>("None").has_value());

    constexpr auto dr = yae::enum_cast<Directions>("Right");
    REQUIRE(yae::enum_cast<Directions>("Up").value() == Directions::Up);
    REQUIRE(yae::enum_cast<Directions>("Down").value() == Directions::Down);
    REQUIRE(dr.value() == Directions::Right);
    REQUIRE(yae::enum_cast<Directions>("Left").value() == Directions::Left);
    REQUIRE_FALSE(yae::enum_cast<Directions>("None").has_value());

    constexpr auto nt = yae::enum_cast<number>("three");
    REQUIRE(yae::enum_cast<number>("one").value() == number::one);
    REQUIRE(yae::enum_cast<number>("two").value() == number::two);
    REQUIRE(nt.value() == number::three);
    REQUIRE_FALSE(yae::enum_cast<number>("None").has_value());

#undef constexpr
  }

  SECTION("integer") {
    constexpr auto cr = yae::enum_cast<Color>(-12);
    REQUIRE(cr.value() == Color::RED);
    REQUIRE(yae::enum_cast<Color>(7).value() == Color::GREEN);
    REQUIRE(yae::enum_cast<Color>(15).value() == Color::BLUE);
    REQUIRE_FALSE(yae::enum_cast<Color>(0).has_value());

    constexpr auto no = yae::enum_cast<Numbers>(10);
    REQUIRE(no.value() == Numbers::one);
    REQUIRE(yae::enum_cast<Numbers>(20).value() == Numbers::two);
    REQUIRE(yae::enum_cast<Numbers>(30).value() == Numbers::three);
    REQUIRE_FALSE(yae::enum_cast<Numbers>(0).has_value());

    constexpr auto dr = yae::enum_cast<Directions>(119);
    REQUIRE(yae::enum_cast<Directions>(85).value() == Directions::Up);
    REQUIRE(yae::enum_cast<Directions>(-42).value() == Directions::Down);
    REQUIRE(dr.value() == Directions::Right);
    REQUIRE(yae::enum_cast<Directions>(-119).value() == Directions::Left);
    REQUIRE_FALSE(yae::enum_cast<Directions>(0).has_value());

    constexpr auto nt = yae::enum_cast<number>(30);
    REQUIRE(yae::enum_cast<number>(10).value() == number::one);
    REQUIRE(yae::enum_cast<number>(20).value() == number::two);
    REQUIRE(nt.value() == number::three);
    REQUIRE_FALSE(yae::enum_cast<number>(0).has_value());
  }
}

TEST_CASE("enum_value") {
 constexpr auto cr = yae::enum_value<Color>(0);
  REQUIRE(cr == Color::RED);
  REQUIRE(yae::enum_value<Color>(1) == Color::GREEN);
  REQUIRE(yae::enum_value<Color>(2) == Color::BLUE);

  constexpr auto no = yae::enum_value<Numbers>(0);
  REQUIRE(no == Numbers::one);
  REQUIRE(yae::enum_value<Numbers>(1) == Numbers::two);
  REQUIRE(yae::enum_value<Numbers>(2) == Numbers::three);

  constexpr auto dr = yae::enum_value<Directions>(3);
  REQUIRE(yae::enum_value<Directions>(0) == Directions::Left);
  REQUIRE(yae::enum_value<Directions>(1) == Directions::Down);
  REQUIRE(yae::enum_value<Directions>(2) == Directions::Up);
  REQUIRE(dr == Directions::Right);

  constexpr auto nt = yae::enum_value<number>(2);
  REQUIRE(yae::enum_value<number>(0) == number::one);
  REQUIRE(yae::enum_value<number>(1) == number::two);
  REQUIRE(nt == number::three);
}

TEST_CASE("enum_values") {
  constexpr auto s1 = yae::enum_values<Color>();
  REQUIRE(s1 == std::array<Color, 3>{{Color::RED, Color::GREEN, Color::BLUE}});

  constexpr auto s2 = yae::enum_values<Numbers>();
  REQUIRE(s2 == std::array<Numbers, 3>{{Numbers::one, Numbers::two, Numbers::three}});

  constexpr auto s3 = yae::enum_values<Directions>();
  REQUIRE(s3 == std::array<Directions, 4>{{Directions::Left, Directions::Down, Directions::Up, Directions::Right}});

  constexpr auto s4 = yae::enum_values<number>();
  REQUIRE(s4 == std::array<number, 3>{{number::one, number::two, number::three}});
}

TEST_CASE("enum_count") {
  constexpr auto s1 = yae::enum_count<Color>();
  REQUIRE(s1 == 3);

  constexpr auto s2 = yae::enum_count<Numbers>();
  REQUIRE(s2 == 3);

  constexpr auto s3 = yae::enum_count<Directions>();
  REQUIRE(s3 == 4);

  constexpr auto s4 = yae::enum_count<number>();
  REQUIRE(s4 == 3);
}

TEST_CASE("enum_name") {
  constexpr Color cr = Color::RED;
  constexpr auto cr_name = yae::enum_name(cr);
  Color cm[3] = {Color::RED, Color::GREEN, Color::BLUE};
  REQUIRE(cr_name.value() == "RED");
  REQUIRE(yae::enum_name(Color::BLUE).value() == "BLUE");
  REQUIRE(yae::enum_name(cm[1]).value() == "GREEN");
  REQUIRE_FALSE(yae::enum_name(static_cast<Color>(MAGIC_ENUM_RANGE)).has_value());
  REQUIRE_FALSE(yae::enum_name(static_cast<Color>(-MAGIC_ENUM_RANGE)).has_value());

  constexpr Numbers no = Numbers::one;
  constexpr auto no_name = yae::enum_name(no);
  REQUIRE(no_name.value() == "one");
  REQUIRE(yae::enum_name(Numbers::two).value() == "two");
  REQUIRE(yae::enum_name(Numbers::three).value() == "three");
  REQUIRE_FALSE(yae::enum_name(static_cast<Numbers>(MAGIC_ENUM_RANGE)).has_value());
  REQUIRE_FALSE(yae::enum_name(static_cast<Numbers>(-MAGIC_ENUM_RANGE)).has_value());

  constexpr Directions dr = Directions::Right;
  constexpr auto dr_name = yae::enum_name(dr);
  REQUIRE(yae::enum_name(Directions::Up).value() == "Up");
  REQUIRE(yae::enum_name(Directions::Down).value() == "Down");
  REQUIRE(dr_name.value() == "Right");
  REQUIRE(yae::enum_name(Directions::Left).value() == "Left");
  REQUIRE_FALSE(yae::enum_name(static_cast<Directions>(MAGIC_ENUM_RANGE)).has_value());
  REQUIRE_FALSE(yae::enum_name(static_cast<Directions>(-MAGIC_ENUM_RANGE)).has_value());

  constexpr number nt = number::three;
  constexpr auto nt_name = yae::enum_name(nt);
  REQUIRE(yae::enum_name(number::one).value() == "one");
  REQUIRE(yae::enum_name(number::two).value() == "two");
  REQUIRE(nt_name.value() == "three");
  REQUIRE_FALSE(yae::enum_name(static_cast<number>(MAGIC_ENUM_RANGE)).has_value());
  REQUIRE_FALSE(yae::enum_name(static_cast<number>(-MAGIC_ENUM_RANGE)).has_value());
}

TEST_CASE("enum_names") {
  constexpr auto s1 = yae::enum_names<Color>();
  REQUIRE(s1 == std::array<std::string_view, 3>{{"RED", "GREEN", "BLUE"}});

  constexpr auto s2 = yae::enum_names<Numbers>();
  REQUIRE(s2 == std::array<std::string_view, 3>{{"one", "two", "three"}});

  constexpr auto s3 = yae::enum_names<Directions>();
  REQUIRE(s3 == std::array<std::string_view, 4>{{"Left", "Down", "Up", "Right"}});

  constexpr auto s4 = yae::enum_names<number>();
  REQUIRE(s4 == std::array<std::string_view, 3>{{"one", "two", "three"}});
}

TEST_CASE("operator<<") {
  auto test_ostream = [](auto e, std::string_view name) {
    using namespace yae::ops;
    std::stringstream ss;
    ss << e;
    REQUIRE(ss.str() == name);
  };

  test_ostream(Color::RED, "RED");
  test_ostream(Color::GREEN, "GREEN");
  test_ostream(Color::BLUE, "BLUE");
  test_ostream((Color)0, "");

  test_ostream(Numbers::one, "one");
  test_ostream(Numbers::two, "two");
  test_ostream(Numbers::three, "three");
  test_ostream((Numbers)0, "");

  test_ostream(Directions::Up, "Up");
  test_ostream(Directions::Down, "Down");
  test_ostream(Directions::Right, "Right");
  test_ostream(Directions::Left, "Left");
  test_ostream((Directions)0, "");

  test_ostream(number::one, "one");
  test_ostream(number::two, "two");
  test_ostream(number::three, "three");
  test_ostream((number)0, "");
}
<|endoftext|>


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

  Program: 3D Slicer

  Copyright (c) 2010 Kitware Inc.

  See COPYRIGHT.txt
  or http://www.slicer.org/copyright/copyright.txt for details.

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

  This file was originally developed by Julien Finet, Kitware Inc.
  and was partially funded by NIH grant 3P41RR013218-12S1

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

// Qt includes
#include <QDebug>
#include <QMap>
#include <QSharedPointer>
#include <QStringList>
#include <QVector>

// IGTLIO includes
#include "qIGTLIOConnectorModel.h"
#include "vtkIGTLIOLogic.h"
#include "vtkIGTLIOConnector.h"

//------------------------------------------------------------------------------
qIGTLIOConnectorModel::qIGTLIOConnectorModel(QObject *vparent)
  :QAbstractItemModel(vparent)
{
  HeaderLabels = QStringList() << "Name" << "Type" << "Status" << "Hostname" << "Port";
}

//------------------------------------------------------------------------------
qIGTLIOConnectorModel::~qIGTLIOConnectorModel()
{
}

//-----------------------------------------------------------------------------
int qIGTLIOConnectorModel::columnCount(const QModelIndex& parent) const
{
  return HeaderLabels.size();
}

//-----------------------------------------------------------------------------
int qIGTLIOConnectorModel::rowCount(const QModelIndex& parent) const
{
  if (parent.column() > 0)
    return 0;

  // only topnode has children
  if (!parent.isValid())
  {
    if (!Logic)
    {
        std::cout << "WARNING in: int qIGTLIOConnectorModel::rowCount(const QModelIndex& parent) const: Logic is a NULL object! Returning 0." << std::endl;
        return 0;
    }
    return Logic->GetNumberOfConnectors();
  }
  return 0;
}

//------------------------------------------------------------------------------
QVariant qIGTLIOConnectorModel::data(const QModelIndex &index, int role) const
{
  if (role!=Qt::DisplayRole)
    return QVariant();

  vtkIGTLIOConnector* cnode = this->getNodeFromIndex(index);

  if (!cnode)
    {
    return QVariant();
    }
  switch (index.column())
    {
    case qIGTLIOConnectorModel::NameColumn:
      {
      return QString::fromStdString(cnode->GetName());
      break;
      }
    case qIGTLIOConnectorModel::TypeColumn:
      {
      Q_ASSERT(cnode->GetType() < vtkIGTLIOConnector::NUM_TYPE);
      return QString::fromStdString(vtkIGTLIOConnector::ConnectorTypeStr[cnode->GetType()]);
      break;
      }
    case qIGTLIOConnectorModel::StatusColumn:
      {
      Q_ASSERT(cnode->GetState() < vtkIGTLIOConnector::NUM_STATE);
      return QString::fromStdString(vtkIGTLIOConnector::ConnectorStateStr[cnode->GetState()]);
      break;
      }
    case qIGTLIOConnectorModel::HostnameColumn:
      {
      if (cnode->GetType() == vtkIGTLIOConnector::TYPE_CLIENT)
        {
        return QString::fromStdString(cnode->GetServerHostname());
        }
      else
        {
        return QString("--");
        }
      break;
      }
    case qIGTLIOConnectorModel::PortColumn:
      {
      return QString("%1").arg(cnode->GetServerPort());
      break;
      }
    default:
      break;
    }
  return QVariant();
}

//-----------------------------------------------------------------------------
Qt::ItemFlags qIGTLIOConnectorModel::flags(const QModelIndex &index) const
{
  return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}

//-----------------------------------------------------------------------------
QVariant qIGTLIOConnectorModel::headerData(int section, Qt::Orientation orientation, int role) const
{
  if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
    {
      return HeaderLabels[section];
    }

  return QVariant();
}

//-----------------------------------------------------------------------------
QModelIndex qIGTLIOConnectorModel::index(int row, int column, const QModelIndex &parent) const
{
  if (row < Logic->GetNumberOfConnectors())
    {
      return createIndex(row, column, Logic->GetConnector(row));
    }

  return QModelIndex();
}

//-----------------------------------------------------------------------------
QModelIndex qIGTLIOConnectorModel::parent(const QModelIndex &index) const
{
  return QModelIndex();
}

//-----------------------------------------------------------------------------
void qIGTLIOConnectorModel::resetModel()
{
  this->beginResetModel();
  this->endResetModel();
}

//-----------------------------------------------------------------------------
void qIGTLIOConnectorModel::setLogic(vtkIGTLIOLogicPointer logic)
{
  foreach(int evendId, QList<int>()
          << vtkIGTLIOLogic::ConnectionAddedEvent
          << vtkIGTLIOLogic::ConnectionAboutToBeRemovedEvent)
    {
    qvtkReconnect(this->Logic, logic, evendId,
                  this, SLOT(onConnectionEvent(vtkObject*, unsigned long, void*, void* )));
    }

  this->Logic = logic;
}

//-----------------------------------------------------------------------------
void qIGTLIOConnectorModel::ReconnectConnector(vtkIGTLIOConnector* oldConnector, vtkIGTLIOConnector* newConnector)
{
  foreach(int evendId, QList<int>()
          << vtkIGTLIOConnector::ConnectedEvent
          << vtkIGTLIOConnector::DisconnectedEvent
          << vtkIGTLIOConnector::ActivatedEvent
          << vtkIGTLIOConnector::DeactivatedEvent)
    {
    qvtkReconnect(oldConnector, newConnector, evendId,
                  this, SLOT(onConnectorEvent(vtkObject*, unsigned long, void*, void* )));
    }
}

//-----------------------------------------------------------------------------
void qIGTLIOConnectorModel::onConnectionEvent(vtkObject* caller, unsigned long event, void * , void* connector )
{
  if (event==vtkIGTLIOLogic::ConnectionAddedEvent)
    {
//      std::cout << "on add connected event" << std::endl;
      vtkIGTLIOConnector* c = static_cast<vtkIGTLIOConnector*>(connector);
      this->ReconnectConnector(NULL, c);
      this->resetModel();
    }
  if (event==vtkIGTLIOLogic::ConnectionAboutToBeRemovedEvent)
    {
//      std::cout << "on remove connected event" << std::endl;
      vtkIGTLIOConnector* c = static_cast<vtkIGTLIOConnector*>(connector);
      this->ReconnectConnector(c, NULL);
      this->resetModel();
    }
}

//-----------------------------------------------------------------------------
void qIGTLIOConnectorModel::onConnectorEvent(vtkObject* caller, unsigned long event , void*, void* connector )
{
  emit dataChanged(QModelIndex(), QModelIndex());
}

//-----------------------------------------------------------------------------
vtkIGTLIOConnector* qIGTLIOConnectorModel::getNodeFromIndex(const QModelIndex &index) const
{
  if (!index.isValid())
    return NULL;
  return static_cast<vtkIGTLIOConnector*>(index.internalPointer());
}
<commit_msg>BUG: Fixed crash of qIGTLIOClientWidget constructor<commit_after>/*==============================================================================

  Program: 3D Slicer

  Copyright (c) 2010 Kitware Inc.

  See COPYRIGHT.txt
  or http://www.slicer.org/copyright/copyright.txt for details.

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

  This file was originally developed by Julien Finet, Kitware Inc.
  and was partially funded by NIH grant 3P41RR013218-12S1

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

// Qt includes
#include <QDebug>
#include <QMap>
#include <QSharedPointer>
#include <QStringList>
#include <QVector>

// IGTLIO includes
#include "qIGTLIOConnectorModel.h"
#include "vtkIGTLIOLogic.h"
#include "vtkIGTLIOConnector.h"

//------------------------------------------------------------------------------
qIGTLIOConnectorModel::qIGTLIOConnectorModel(QObject *vparent)
  :QAbstractItemModel(vparent)
{
  HeaderLabels = QStringList() << "Name" << "Type" << "Status" << "Hostname" << "Port";
}

//------------------------------------------------------------------------------
qIGTLIOConnectorModel::~qIGTLIOConnectorModel()
{
}

//-----------------------------------------------------------------------------
int qIGTLIOConnectorModel::columnCount(const QModelIndex& parent) const
{
  return HeaderLabels.size();
}

//-----------------------------------------------------------------------------
int qIGTLIOConnectorModel::rowCount(const QModelIndex& parent) const
{
  if (parent.column() > 0)
    return 0;

  // only topnode has children
  if (!parent.isValid())
  {
    if (!Logic)
    {
        std::cout << "WARNING in: int qIGTLIOConnectorModel::rowCount(const QModelIndex& parent) const: Logic is a NULL object! Returning 0." << std::endl;
        return 0;
    }
    return Logic->GetNumberOfConnectors();
  }
  return 0;
}

//------------------------------------------------------------------------------
QVariant qIGTLIOConnectorModel::data(const QModelIndex &index, int role) const
{
  if (role!=Qt::DisplayRole)
    return QVariant();

  vtkIGTLIOConnector* cnode = this->getNodeFromIndex(index);

  if (!cnode)
    {
    return QVariant();
    }
  switch (index.column())
    {
    case qIGTLIOConnectorModel::NameColumn:
      {
      return QString::fromStdString(cnode->GetName());
      break;
      }
    case qIGTLIOConnectorModel::TypeColumn:
      {
      Q_ASSERT(cnode->GetType() < vtkIGTLIOConnector::NUM_TYPE);
      return QString::fromStdString(vtkIGTLIOConnector::ConnectorTypeStr[cnode->GetType()]);
      break;
      }
    case qIGTLIOConnectorModel::StatusColumn:
      {
      Q_ASSERT(cnode->GetState() < vtkIGTLIOConnector::NUM_STATE);
      return QString::fromStdString(vtkIGTLIOConnector::ConnectorStateStr[cnode->GetState()]);
      break;
      }
    case qIGTLIOConnectorModel::HostnameColumn:
      {
      if (cnode->GetType() == vtkIGTLIOConnector::TYPE_CLIENT)
        {
        return QString::fromStdString(cnode->GetServerHostname());
        }
      else
        {
        return QString("--");
        }
      break;
      }
    case qIGTLIOConnectorModel::PortColumn:
      {
      return QString("%1").arg(cnode->GetServerPort());
      break;
      }
    default:
      break;
    }
  return QVariant();
}

//-----------------------------------------------------------------------------
Qt::ItemFlags qIGTLIOConnectorModel::flags(const QModelIndex &index) const
{
  return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}

//-----------------------------------------------------------------------------
QVariant qIGTLIOConnectorModel::headerData(int section, Qt::Orientation orientation, int role) const
{
  if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
    {
      return HeaderLabels[section];
    }

  return QVariant();
}

//-----------------------------------------------------------------------------
QModelIndex qIGTLIOConnectorModel::index(int row, int column, const QModelIndex &parent) const
{
  if (!Logic)
  {
    return QModelIndex();
  }
  if (row >= Logic->GetNumberOfConnectors())
  {
    return QModelIndex();
  }
  return createIndex(row, column, Logic->GetConnector(row));
}

//-----------------------------------------------------------------------------
QModelIndex qIGTLIOConnectorModel::parent(const QModelIndex &index) const
{
  return QModelIndex();
}

//-----------------------------------------------------------------------------
void qIGTLIOConnectorModel::resetModel()
{
  this->beginResetModel();
  this->endResetModel();
}

//-----------------------------------------------------------------------------
void qIGTLIOConnectorModel::setLogic(vtkIGTLIOLogicPointer logic)
{
  foreach(int evendId, QList<int>()
          << vtkIGTLIOLogic::ConnectionAddedEvent
          << vtkIGTLIOLogic::ConnectionAboutToBeRemovedEvent)
    {
    qvtkReconnect(this->Logic, logic, evendId,
                  this, SLOT(onConnectionEvent(vtkObject*, unsigned long, void*, void* )));
    }

  this->Logic = logic;
}

//-----------------------------------------------------------------------------
void qIGTLIOConnectorModel::ReconnectConnector(vtkIGTLIOConnector* oldConnector, vtkIGTLIOConnector* newConnector)
{
  foreach(int evendId, QList<int>()
          << vtkIGTLIOConnector::ConnectedEvent
          << vtkIGTLIOConnector::DisconnectedEvent
          << vtkIGTLIOConnector::ActivatedEvent
          << vtkIGTLIOConnector::DeactivatedEvent)
    {
    qvtkReconnect(oldConnector, newConnector, evendId,
                  this, SLOT(onConnectorEvent(vtkObject*, unsigned long, void*, void* )));
    }
}

//-----------------------------------------------------------------------------
void qIGTLIOConnectorModel::onConnectionEvent(vtkObject* caller, unsigned long event, void * , void* connector )
{
  if (event==vtkIGTLIOLogic::ConnectionAddedEvent)
    {
//      std::cout << "on add connected event" << std::endl;
      vtkIGTLIOConnector* c = static_cast<vtkIGTLIOConnector*>(connector);
      this->ReconnectConnector(NULL, c);
      this->resetModel();
    }
  if (event==vtkIGTLIOLogic::ConnectionAboutToBeRemovedEvent)
    {
//      std::cout << "on remove connected event" << std::endl;
      vtkIGTLIOConnector* c = static_cast<vtkIGTLIOConnector*>(connector);
      this->ReconnectConnector(c, NULL);
      this->resetModel();
    }
}

//-----------------------------------------------------------------------------
void qIGTLIOConnectorModel::onConnectorEvent(vtkObject* caller, unsigned long event , void*, void* connector )
{
  emit dataChanged(QModelIndex(), QModelIndex());
}

//-----------------------------------------------------------------------------
vtkIGTLIOConnector* qIGTLIOConnectorModel::getNodeFromIndex(const QModelIndex &index) const
{
  if (!index.isValid())
    return NULL;
  return static_cast<vtkIGTLIOConnector*>(index.internalPointer());
}
<|endoftext|>


<commit_before>/*!
@file

@copyright Edouard Alligand and Joel Falcou 2015-2017
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_BRIGAND_FUNCTIONS_COMPARISON_LESS_HPP
#define BOOST_BRIGAND_FUNCTIONS_COMPARISON_LESS_HPP
#include <brigand/types/bool.hpp>

namespace brigand
{
  template <typename A, typename B>
  struct less : bool_ < (A::value < B::value) > {};
}
#endif
<commit_msg>Delete less.hpp<commit_after><|endoftext|>


<commit_before>#pragma once
#include <string>
#include <sstream>
#include <cassert>
#include "detail/parse.hpp"
#include "detail/argumentsCount.hpp"
#include "But/Log/Backend/toString.hpp"
#include "But/Log/Backend/typeString.hpp"

namespace But
{
namespace Format
{

/** @brief represents a parsed format, from a given text with. set of parameters can be applied to get a final message.
 *  @note format of the parameter is defined by its type, via toString() function. it
 *        is not specified for a given type usage. this way formatting for a given parameters
 *        is always constant.
 */
template<unsigned ArgumentsCount, unsigned MaxSegments>
class Parsed final
{
public:
  /** @brief parses input format and constructs the object.
   *  @param format - format is a string with positional arguments, in a form:
   *          $N - expands to N-th argument.
   *          ${N} - the same as $N.
   *          ${N#some text} - the same as $N, but allowing some textual description along (useful for translations!).
   *          ${TN} - prints type of N-th argument, using typeString() function and ADL.
   *          ${TN#some text} - the same as ${TN}, but allowing some textual description along (useful for translations!).
   *          ${VN} - the same as $N.
   *          ${VN#some text} - the same as $N, but allowing some textual description along (useful for translations!).
   *          $$ - liternal '$' character.
   *  @note all numbers are 0-based (i.e. 1st argument has index 0).
   */
  constexpr explicit Parsed(char const* format):
    ps_{ detail::parse<MaxSegments>(format) },
    format_{format}
  { }

  constexpr auto inputFormat() const { return format_; }
  //constexpr auto expectedArguments() const { return detail::argumentsCount(ps_); } // TODO: will not work with static_assert...
  static constexpr auto expectedArguments() { return ArgumentsCount; }
  static constexpr auto maxSegments() { return MaxSegments; }

  template<typename ...Args>
  std::string format(Args const& ...args) const
  {
    static_assert( sizeof...(args) == expectedArguments(), "arity missmatch between provided format and arguments to be formated" );
    assert( expectedArguments() == detail::argumentsCount(ps_) );
    std::ostringstream os;
    for(auto i=0u; i<ps_.count_; ++i)
      formatBlock(os, ps_.segments_[i], args...);
    return os.str();
  }

private:
  template<typename F>
  std::string processArgument(F&& /*f*/, const unsigned /*pos*/) const
  {
    assert(!"this overload is never really called");
    std::terminate();
  }
  template<typename F, typename Head>
  std::string processArgument(F&& f, const unsigned pos, Head const& head) const
  {
    (void)pos;
    assert( pos == 0u && "format is not alligned with arguments" );
    return f(head);
  }
  template<typename F, typename Head, typename ...Tail>
  std::string processArgument(F&& f, const unsigned pos, Head const& head, Tail const& ...tail) const
  {
    if( pos == 0u )
      return f(head);
    return processArgument( std::forward<F>(f), pos-1u, tail... );
  }

  template<typename ...Args>
  std::string getArgumentType(const unsigned pos, Args const& ...args) const
  {
    using Log::Backend::typeString;
    return processArgument( [](auto& e) { return typeString(e); },  pos, args... );
  }
  template<typename ...Args>
  std::string getArgumentValue(const unsigned pos, Args const& ...args) const
  {
    using Log::Backend::toString;
    return processArgument( [](auto& e) { return toString(e); },  pos, args... );
  }

  template<typename ...Args>
  void formatBlock(std::ostringstream& os, detail::State const& state, Args const& ...args) const
  {
    switch(state.type_)
    {
      case detail::State::Type::String:
        os.write( state.begin_, state.end_ - state.begin_ );
        return;
      case detail::State::Type::Value:
        os << getArgumentValue(state.referencedArgument_, args...);
        return;
      case detail::State::Type::TypeName:
        os << getArgumentType(state.referencedArgument_, args...);
        return;
    }
    assert(!"missing type handle");
  }

  const detail::ParserState<MaxSegments> ps_;
  char const* format_;
};

}
}
<commit_msg>comment update - it's not a TODO<commit_after>#pragma once
#include <string>
#include <sstream>
#include <cassert>
#include "detail/parse.hpp"
#include "detail/argumentsCount.hpp"
#include "But/Log/Backend/toString.hpp"
#include "But/Log/Backend/typeString.hpp"

namespace But
{
namespace Format
{

/** @brief represents a parsed format, from a given text with. set of parameters can be applied to get a final message.
 *  @note format of the parameter is defined by its type, via toString() function. it
 *        is not specified for a given type usage. this way formatting for a given parameters
 *        is always constant.
 */
template<unsigned ArgumentsCount, unsigned MaxSegments>
class Parsed final
{
public:
  /** @brief parses input format and constructs the object.
   *  @param format - format is a string with positional arguments, in a form:
   *          $N - expands to N-th argument.
   *          ${N} - the same as $N.
   *          ${N#some text} - the same as $N, but allowing some textual description along (useful for translations!).
   *          ${TN} - prints type of N-th argument, using typeString() function and ADL.
   *          ${TN#some text} - the same as ${TN}, but allowing some textual description along (useful for translations!).
   *          ${VN} - the same as $N.
   *          ${VN#some text} - the same as $N, but allowing some textual description along (useful for translations!).
   *          $$ - liternal '$' character.
   *  @note all numbers are 0-based (i.e. 1st argument has index 0).
   */
  constexpr explicit Parsed(char const* format):
    ps_{ detail::parse<MaxSegments>(format) },
    format_{format}
  { }

  constexpr auto inputFormat() const { return format_; }
  //constexpr auto expectedArguments() const { return detail::argumentsCount(ps_); } // note: would not work with static_assert...
  static constexpr auto expectedArguments() { return ArgumentsCount; }
  static constexpr auto maxSegments() { return MaxSegments; }

  template<typename ...Args>
  std::string format(Args const& ...args) const
  {
    static_assert( sizeof...(args) == expectedArguments(), "arity missmatch between provided format and arguments to be formated" );
    assert( expectedArguments() == detail::argumentsCount(ps_) );
    std::ostringstream os;
    for(auto i=0u; i<ps_.count_; ++i)
      formatBlock(os, ps_.segments_[i], args...);
    return os.str();
  }

private:
  template<typename F>
  std::string processArgument(F&& /*f*/, const unsigned /*pos*/) const
  {
    assert(!"this overload is never really called");
    std::terminate();
  }
  template<typename F, typename Head>
  std::string processArgument(F&& f, const unsigned pos, Head const& head) const
  {
    (void)pos;
    assert( pos == 0u && "format is not alligned with arguments" );
    return f(head);
  }
  template<typename F, typename Head, typename ...Tail>
  std::string processArgument(F&& f, const unsigned pos, Head const& head, Tail const& ...tail) const
  {
    if( pos == 0u )
      return f(head);
    return processArgument( std::forward<F>(f), pos-1u, tail... );
  }

  template<typename ...Args>
  std::string getArgumentType(const unsigned pos, Args const& ...args) const
  {
    using Log::Backend::typeString;
    return processArgument( [](auto& e) { return typeString(e); },  pos, args... );
  }
  template<typename ...Args>
  std::string getArgumentValue(const unsigned pos, Args const& ...args) const
  {
    using Log::Backend::toString;
    return processArgument( [](auto& e) { return toString(e); },  pos, args... );
  }

  template<typename ...Args>
  void formatBlock(std::ostringstream& os, detail::State const& state, Args const& ...args) const
  {
    switch(state.type_)
    {
      case detail::State::Type::String:
        os.write( state.begin_, state.end_ - state.begin_ );
        return;
      case detail::State::Type::Value:
        os << getArgumentValue(state.referencedArgument_, args...);
        return;
      case detail::State::Type::TypeName:
        os << getArgumentType(state.referencedArgument_, args...);
        return;
    }
    assert(!"missing type handle");
  }

  const detail::ParserState<MaxSegments> ps_;
  char const* format_;
};

}
}
<|endoftext|>


<commit_before>//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//
// Copyright (c) 2012, Matthew Renaud
// All rights reserved.
//
// Licensed under the FreeBSD license. See LICENSE file for details.
//
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

#ifndef MRR_UNISTD_HXX_
#define MRR_UNISTD_HXX_

#include <unistd.h>

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

namespace mrr {
namespace posix {

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
ssize_t read(int fildes, void* buf, size_t nbyte)
{
  ssize_t numbytes = 0;

  // Loop while the read function is interupted.  Set errno in the loop
  // to make sure that another system call has not set it.
  do
  {
    errno = 0;
    numbytes = ::read(fildes, buf, nbyte);
  }
  while (numbytes == -1 && errno == EINTR);
  return numbytes;
}

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
ssize_t write(int fildes, void const* buf, size_t nbyte)
{
  // Loop while the write function is interupted.  Set errno in the loop
  // to make sure that another system call has not set it.
  ssize_t numbytes = 0;
  do
  {
    errno = 0;
    numbytes = ::write(fildes, buf, nbyte);
  }
  while (numbytes == -1 && errno == EINTR);
  return numbytes;
}

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
int close(int fd)
{
  int ret_val;
  do
  {
    errno = 0;
    ret_val = ::close(fd);
  } while(ret_val == -1 && errno != EINTR);

  return ret_val;
}

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

} // namespace posix
} // namespace mrr

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

#endif // #ifndef MRR_UNISTD_HXX_
<commit_msg>Fixed errno != EINTR error inside close() for unistd.hxx<commit_after>//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//
// Copyright (c) 2012, Matthew Renaud
// All rights reserved.
//
// Licensed under the FreeBSD license. See LICENSE file for details.
//
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

#ifndef MRR_UNISTD_HXX_
#define MRR_UNISTD_HXX_

#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

namespace mrr {
namespace posix {

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
int myopen(char const* pathname, int flags)
{
  int ret_val;
  do
  {
    errno = 0;
    ret_val = ::open(pathname, flags);
  } while(ret_val == -1 && errno == EINTR);

  return ret_val;
}

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
ssize_t read(int fildes, void* buf, size_t nbyte)
{
  ssize_t numbytes = 0;

  // Loop while the read function is interupted.  Set errno in the loop
  // to make sure that another system call has not set it.
  do
  {
    errno = 0;
    numbytes = ::read(fildes, buf, nbyte);
  }
  while (numbytes == -1 && errno == EINTR);
  return numbytes;
}

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
ssize_t write(int fildes, void const* buf, size_t nbyte)
{
  // Loop while the write function is interupted.  Set errno in the loop
  // to make sure that another system call has not set it.
  ssize_t numbytes = 0;
  do
  {
    errno = 0;
    numbytes = ::write(fildes, buf, nbyte);
  }
  while (numbytes == -1 && errno == EINTR);
  return numbytes;
}

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
int close(int fd)
{
  int ret_val;
  do
  {
    errno = 0;
    ret_val = ::close(fd);
  } while(ret_val == -1 && errno == EINTR);

  return ret_val;
}

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

} // namespace posix
} // namespace mrr

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

#endif // #ifndef MRR_UNISTD_HXX_
<|endoftext|>


<commit_before><commit_msg>Update Prime Factorization.cpp<commit_after><|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <string>
#include "ros/ros.h"
#include "std_msgs/MultiArrayLayout.h"
#include "std_msgs/MultiArrayDimension.h"
#include "std_msgs/Int8MultiArray.h"
#include <fstream>
#include <sstream>
#include <unistd.h>

using std::string;
typedef std::vector < std::vector <int> > Matrix;

#define DEBUG 1
int MATRIX_WIDTH = 200;
int MATRIX_HEIGHT = 200;

Matrix createVector(string f_s)
{
  Matrix m;
  m.resize(MATRIX_HEIGHT, std::vector<int>(MATRIX_WIDTH, 0));
  std::ifstream infile(f_s.c_str());
  if (!infile.good()) {
     throw std::invalid_argument( "File does not exist!" );
  }
  std::string line;
  while (std::getline(infile, line))
  {
    std::istringstream iss(line);
    int a, b;
    float c;
    if (!(iss >> a >> b >> c)) {continue;} // error
    m[a][b] = (int) ((c*100)+100)*1.27;
    if (DEBUG) {
      std::cout << "LINE: " << a << ", "
                << b << ", "
                << c << " -> "
                << m[a][b] << std::endl;
    }

  }

  return m;
}

int main(int argc, char **argv) {

  ros::init(argc, argv, "arrayPublisher");

  ros::NodeHandle n;

  ros::Publisher pub = n.advertise<std_msgs::Int8MultiArray>("/outer_layer", 400);

  char cwd[1024];
  getcwd(cwd, sizeof(cwd));
  string path(cwd);
  while (ros::ok())
  {
    // some vectors of vectors here
    // TODO: ALEX PUT YOUR VECTOR HERE!
    Matrix matrix = createVector(path + "/share/Model-A.txt");

    std_msgs::Int8MultiArray matrix_ma;
    matrix_ma.data.clear();
    // linearise matrix
    std::vector< std::vector<int> >::iterator r;
    std::vector<int>::iterator c;
    for (r = matrix.begin(); r != matrix.end(); r++) {
      for (c = r->begin(); c != r->end(); c++) {
        matrix_ma.data.push_back(*c);
      }
    }

    pub.publish(matrix_ma);
    ROS_INFO("TEST: Outer layer has been published");
    ros::spinOnce();
    sleep(1);
  }
}
<commit_msg>Test publisher: 8Int -> 32Int<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <string>
#include "ros/ros.h"
#include "std_msgs/MultiArrayLayout.h"
#include "std_msgs/MultiArrayDimension.h"
#include "std_msgs/Int32MultiArray.h"
#include <fstream>
#include <sstream>
#include <unistd.h>

using std::string;
typedef std::vector < std::vector <int> > Matrix;

#define DEBUG 1
int MATRIX_WIDTH = 200;
int MATRIX_HEIGHT = 200;

Matrix createVector(string f_s)
{
  Matrix m;
  m.resize(MATRIX_HEIGHT, std::vector<int>(MATRIX_WIDTH, 0));
  std::ifstream infile(f_s.c_str());
  if (!infile.good()) {
     throw std::invalid_argument( "File does not exist!" );
  }
  std::string line;
  while (std::getline(infile, line))
  {
    std::istringstream iss(line);
    int a, b;
    float c;
    if (!(iss >> a >> b >> c)) {continue;} // error
    m[a][b] = (int) ((c*100)+100)*1.27;
    if (DEBUG) {
      std::cout << "LINE: " << a << ", "
                << b << ", "
                << c << " -> "
                << m[a][b] << std::endl;
    }

  }

  return m;
}

int main(int argc, char **argv) {

  ros::init(argc, argv, "arrayPublisher");

  ros::NodeHandle n;

  ros::Publisher pub = n.advertise<std_msgs::Int32MultiArray>("/outer_layer", 400);

  char cwd[1024];
  getcwd(cwd, sizeof(cwd));
  string path(cwd);
  while (ros::ok())
  {
    // some vectors of vectors here
    // TODO: ALEX PUT YOUR VECTOR HERE!
    Matrix matrix = createVector(path + "/share/Model-A.txt");

    std_msgs::Int32MultiArray matrix_ma;
    matrix_ma.data.clear();
    // linearise matrix
    std::vector< std::vector<int> >::iterator r;
    std::vector<int>::iterator c;
    for (r = matrix.begin(); r != matrix.end(); r++) {
      for (c = r->begin(); c != r->end(); c++) {
        matrix_ma.data.push_back(*c);
      }
    }

    pub.publish(matrix_ma);
    ROS_INFO("TEST: Outer layer has been published");
    ros::spinOnce();
    sleep(5);
  }
}
<|endoftext|>


<commit_before>#include "RegisterGlobals.hpp"

void noob::register_globals(asIScriptEngine* script_engine)
{
	noob::globals& g = noob::globals::get_instance();

	int r;
	r = script_engine->RegisterGlobalFunction("shape_handle sphere_shape(float)", asMETHOD(noob::globals, sphere_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("shape_handle box_shape(float, float, float)", asMETHOD(noob::globals, box_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("shape_handle cylinder_shape(float, float)", asMETHOD(noob::globals, cylinder_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("shape_handle cone_shape(float, float)", asMETHOD(noob::globals, cone_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("shape_handle hull_shape(const vector_vec3& in)", asMETHOD(noob::globals, hull_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("shape_handle static_trimesh_shape(const basic_mesh& in)", asMETHOD(noob::globals, static_trimesh_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	// r = script_engine->RegisterGlobalFunction("mesh_handle add_mesh(const basic_mesh& in)", asMETHOD(noob::globals, add_mesh), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	// r = script_engine->RegisterGlobalFunction("model_handle model_by_shape(const shape_handle)", asMETHOD(noob::globals, model_by_shape), asCALL_THISCALL_ASGLOBAL, &g); assert(r >= 0);
	r = script_engine->RegisterGlobalFunction("scaled_model sphere_model(float)", asMETHOD(noob::globals, sphere_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("scaled_model box_model(float, float, float)", asMETHOD(noob::globals, box_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("scaled_model cylinder_model(float, float)", asMETHOD(noob::globals, cylinder_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("scaled_model cone_model(float, float)", asMETHOD(noob::globals, cone_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("scaled_model model_from_mesh(const basic_mesh& in)", asMETHOD(noob::globals, model_from_mesh), asCALL_THISCALL_ASGLOBAL, &g); assert(r >= 0);
	r = script_engine->RegisterGlobalFunction("animated_model_handle animated_model(const string& in)", asMETHOD(noob::globals, animated_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	// r = script_engine->RegisterGlobalFunction("skeleton_handle skeleton(const string& in)", asMETHOD(noob::globals, skeleton), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("light_handle set_light(const light& in, const string& in)", asMETHOD(noob::globals, set_light), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("light_handle get_light(const string& in)", asMETHOD(noob::globals, set_light), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("reflectance_handle set_reflectance(const reflectance& in, const string& in)", asMETHOD(noob::globals, set_reflectance), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("reflectance_handle get_reflectance(const string& in)", asMETHOD(noob::globals, get_reflectance), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("void set_shader(const basic_uniform& in, const string& in)", asMETHODPR(noob::globals, set_shader, (const noob::basic_renderer::uniform&, const std::string&), void), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("void set_shader(const triplanar_gradmap_uniform& in, const string& in)", asMETHODPR(noob::globals, set_shader, (const noob::triplanar_gradient_map_renderer::uniform&, const std::string&), void), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("shader_handle get_shader(const string& in)", asMETHOD(noob::globals, get_shader), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );

	r = script_engine->RegisterGlobalFunction("void set_actor_blueprints(const actor_blueprints& in, const string& in)", asMETHOD(noob::globals, set_actor_blueprints), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("actor_blueprints_handle get_actor_blueprints(const string& in)", asMETHOD(noob::globals, set_actor_blueprints), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );

}
<commit_msg>Tweak<commit_after>#include "RegisterGlobals.hpp"

void noob::register_globals(asIScriptEngine* script_engine)
{
	noob::globals& g = noob::globals::get_instance();

	int r;
	r = script_engine->RegisterGlobalFunction("shape_handle sphere_shape(float)", asMETHOD(noob::globals, sphere_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("shape_handle box_shape(float, float, float)", asMETHOD(noob::globals, box_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("shape_handle cylinder_shape(float, float)", asMETHOD(noob::globals, cylinder_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("shape_handle cone_shape(float, float)", asMETHOD(noob::globals, cone_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("shape_handle hull_shape(const vector_vec3& in)", asMETHOD(noob::globals, hull_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("shape_handle static_trimesh_shape(const basic_mesh& in)", asMETHOD(noob::globals, static_trimesh_shape), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	// r = script_engine->RegisterGlobalFunction("mesh_handle add_mesh(const basic_mesh& in)", asMETHOD(noob::globals, add_mesh), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	// r = script_engine->RegisterGlobalFunction("model_handle model_by_shape(const shape_handle)", asMETHOD(noob::globals, model_by_shape), asCALL_THISCALL_ASGLOBAL, &g); assert(r >= 0);
	r = script_engine->RegisterGlobalFunction("scaled_model sphere_model(float)", asMETHOD(noob::globals, sphere_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("scaled_model box_model(float, float, float)", asMETHOD(noob::globals, box_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("scaled_model cylinder_model(float, float)", asMETHOD(noob::globals, cylinder_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("scaled_model cone_model(float, float)", asMETHOD(noob::globals, cone_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("scaled_model model_from_mesh(const basic_mesh& in)", asMETHOD(noob::globals, model_from_mesh), asCALL_THISCALL_ASGLOBAL, &g); assert(r >= 0);
	r = script_engine->RegisterGlobalFunction("animated_model_handle animated_model(const string& in)", asMETHOD(noob::globals, animated_model), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	// r = script_engine->RegisterGlobalFunction("skeleton_handle skeleton(const string& in)", asMETHOD(noob::globals, skeleton), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("light_handle set_light(const light& in, const string& in)", asMETHOD(noob::globals, set_light), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("light_handle get_light(const string& in)", asMETHOD(noob::globals, set_light), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("reflectance_handle set_reflectance(const reflectance& in, const string& in)", asMETHOD(noob::globals, set_reflectance), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("reflectance_handle get_reflectance(const string& in)", asMETHOD(noob::globals, get_reflectance), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("void set_shader(const basic_uniform& in, const string& in)", asMETHODPR(noob::globals, set_shader, (const noob::basic_renderer::uniform&, const std::string&), void), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("void set_shader(const triplanar_gradmap_uniform& in, const string& in)", asMETHODPR(noob::globals, set_shader, (const noob::triplanar_gradient_map_renderer::uniform&, const std::string&), void), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("shader_handle get_shader(const string& in)", asMETHOD(noob::globals, get_shader), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );

	r = script_engine->RegisterGlobalFunction("void set_actor_blueprints(const actor_blueprints& in, const string& in)", asMETHOD(noob::globals, set_actor_blueprints), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
	r = script_engine->RegisterGlobalFunction("actor_blueprints_handle get_actor_blueprints(const string& in)", asMETHOD(noob::globals, get_actor_blueprints), asCALL_THISCALL_ASGLOBAL, &g); assert( r >= 0 );
}
<|endoftext|>


<commit_before>// Copyright 2015-2020 Elviss Strazdins. All rights reserved.

#include <array>
#include <stdexcept>
#include <android/input.h>
#include "InputSystemAndroid.hpp"
#include "GamepadDeviceAndroid.hpp"
#include "../../core/android/EngineAndroid.hpp"
#include "../../core/Window.hpp"

namespace ouzel::input::android
{
    InputSystem::InputSystem(const std::function<std::future<bool>(const Event&)>& initCallback):
        input::InputSystem(initCallback),
        keyboardDevice(std::make_unique<KeyboardDevice>(*this, getNextDeviceId())),
        mouseDevice(std::make_unique<MouseDevice>(*this, getNextDeviceId())),
        touchpadDevice(std::make_unique<TouchpadDevice>(*this, getNextDeviceId(), true))
    {
        auto engineAndroid = static_cast<ouzel::android::Engine*>(engine);
        javaVm = engineAndroid->getJavaVm();
        void* jniEnvPointer;

        jint result;
        if ((result = javaVm->GetEnv(&jniEnvPointer, JNI_VERSION_1_6)) != JNI_OK)
            throw std::system_error(result, ouzel::android::getErrorCategory(), "Failed to get JNI environment");

        auto jniEnv = static_cast<JNIEnv*>(jniEnvPointer);

        inputDeviceClass = static_cast<jclass>(jniEnv->NewGlobalRef(jniEnv->FindClass("android/view/InputDevice")));
        getDeviceIdsMethod = jniEnv->GetStaticMethodID(inputDeviceClass, "getDeviceIds", "()[I");

        jclass motionEventClass = jniEnv->FindClass("android/view/MotionEvent");
        getActionMethod = jniEnv->GetMethodID(motionEventClass, "getAction", "()I");
        getPointerIdMethod = jniEnv->GetMethodID(motionEventClass, "getPointerId", "(I)I");
        getToolTypeMethod = jniEnv->GetMethodID(motionEventClass, "getToolType", "(I)I");
        getXMethod = jniEnv->GetMethodID(motionEventClass, "getX", "(I)F");
        getYMethod = jniEnv->GetMethodID(motionEventClass, "getY", "(I)F");
        getPressureMethod = jniEnv->GetMethodID(motionEventClass, "getPressure", "(I)F");
        getAxisValueMethod = jniEnv->GetMethodID(motionEventClass, "getAxisValue", "(I)F");
        getButtonStateMethod = jniEnv->GetMethodID(motionEventClass, "getButtonState", "()I");
    }

    InputSystem::~InputSystem()
    {
        void* jniEnvPointer;

        if (javaVm->GetEnv(&jniEnvPointer, JNI_VERSION_1_6) == JNI_OK)
        {
            auto jniEnv = static_cast<JNIEnv*>(jniEnvPointer);
            if (inputDeviceClass) jniEnv->DeleteGlobalRef(inputDeviceClass);
        }
    }

    void InputSystem::executeCommand(const Command& command)
    {
        switch (command.type)
        {
        case Command::Type::startDeviceDiscovery:
            break;
        case Command::Type::stopDeviceDiscovery:
            break;
        case Command::Type::setPlayerIndex:
        {
            break;
        }
        case Command::Type::setVibration:
        {
            break;
        }
        case Command::Type::showVirtualKeyboard:
            break;
        case Command::Type::hideVirtualKeyboard:
            break;
        default:
            break;
        }
    }

    jboolean InputSystem::handleTouchEvent(jobject event)
    {
        void* jniEnvPointer;

        jint result;
        if ((result = javaVm->GetEnv(&jniEnvPointer, JNI_VERSION_1_6)) != JNI_OK)
            throw std::system_error(result, ouzel::android::getErrorCategory(), "Failed to get JNI environment");

        auto jniEnv = static_cast<JNIEnv*>(jniEnvPointer);

        const jint action = jniEnv->CallIntMethod(event, getActionMethod);

        switch (action & AMOTION_EVENT_ACTION_MASK)
        {
            case AMOTION_EVENT_ACTION_DOWN: // first touch
            {
                const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0);
                const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0);
                const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0);

                if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE)
                    return updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y);
                else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_ERASER)
                {
                    const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0);
                    const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, 0);
                    touchpadDevice->handleTouchBegin(static_cast<std::uint64_t>(pointerId),
                                                        engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)),
                                                        pressure);
                    return true;
                }

                break;
            }
            case AMOTION_EVENT_ACTION_POINTER_DOWN: // touches beyond the first
            {
                const jint pointerIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
                const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, pointerIndex);
                const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, pointerIndex);
                const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, pointerIndex);

                if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE)
                    return updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y);
                else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_ERASER)
                {
                    const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, pointerIndex);
                    const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, pointerIndex);
                    touchpadDevice->handleTouchBegin(static_cast<std::uint64_t>(pointerId),
                                                        engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)),
                                                        pressure);
                    return true;
                }

                break;
            }
            case AMOTION_EVENT_ACTION_MOVE:
            {
                const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0);
                const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0);
                const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0);

                if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE)
                {
                    if (!updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y))
                        mouseDevice->handleMove(engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)));
                    return true;
                }
                else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
                    toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
                    toolType == AMOTION_EVENT_TOOL_TYPE_ERASER)
                {
                    const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0);
                    const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, 0);
                    touchpadDevice->handleTouchMove(static_cast<std::uint64_t>(pointerId),
                                                    engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)),
                                                    pressure);
                    return true;
                }

                break;
            }
            case AMOTION_EVENT_ACTION_UP: // first touch
            {
                const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0);
                const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0);
                const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0);

                if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE)
                    return updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y);
                else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_ERASER)
                {
                    const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0);
                    const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, 0);
                    touchpadDevice->handleTouchEnd(static_cast<std::uint64_t>(pointerId),
                                                    engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)),
                                                    pressure);
                    return true;
                }

                break;
            }
            case AMOTION_EVENT_ACTION_POINTER_UP: // touches beyond the first
            {
                const jint pointerIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
                const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, pointerIndex);
                const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, pointerIndex);
                const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, pointerIndex);

                if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE)
                    return updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y);
                else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_ERASER)
                {
                    const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0);
                    const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, pointerIndex);
                    touchpadDevice->handleTouchEnd(static_cast<std::uint64_t>(pointerId),
                                                    engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)),
                                                    pressure);
                    return true;
                }

                break;
            }
            case AMOTION_EVENT_ACTION_CANCEL:
            {
                const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0);
                const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0);
                const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0);

                if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE)
                {
                    if (!updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y))
                        mouseDevice->handleButtonRelease(Mouse::Button::left, engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)));
                    return true;
                }
                else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_ERASER)
                {
                    const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0);
                    const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, 0);
                    touchpadDevice->handleTouchCancel(static_cast<std::uint64_t>(pointerId),
                                                        engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)),
                                                        pressure);
                    return true;
                }

                break;
            }
        }

        return false;
    }

    jboolean InputSystem::handleGenericMotionEvent(jobject event)
    {
        void* jniEnvPointer;

        jint result;
        if ((result = javaVm->GetEnv(&jniEnvPointer, JNI_VERSION_1_6)) != JNI_OK)
            throw std::system_error(result, ouzel::android::getErrorCategory(), "Failed to get JNI environment");

        auto jniEnv = static_cast<JNIEnv*>(jniEnvPointer);

        const jint action = jniEnv->CallIntMethod(event, getActionMethod);
        const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0);
        const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0);
        const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0);

        switch (action & AMOTION_EVENT_ACTION_MASK)
        {
            case AMOTION_EVENT_ACTION_HOVER_MOVE:
            {
                if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE)
                {
                    mouseDevice->handleMove(engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)));
                    return true;
                }
                break;
            }
            case AMOTION_EVENT_ACTION_SCROLL:
            {
                const jfloat scrollX = jniEnv->CallFloatMethod(event, getAxisValueMethod, AMOTION_EVENT_AXIS_HSCROLL);
                const jfloat scrollY = jniEnv->CallFloatMethod(event, getAxisValueMethod, AMOTION_EVENT_AXIS_VSCROLL);

                if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE)
                {
                    mouseDevice->handleScroll(Vector2F(scrollX, scrollY),
                                                engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)));
                    return true;
                }
                break;
            }
        }

        return false;
    }

    bool InputSystem::updateButtonState(jint newButtonState, jint x, jint y)
    {
        bool result = false;

        constexpr std::array<std::pair<jint, Mouse::Button>, 5> buttons = {{
            {AMOTION_EVENT_BUTTON_PRIMARY, Mouse::Button::left},
            {AMOTION_EVENT_BUTTON_SECONDARY, Mouse::Button::right},
            {AMOTION_EVENT_BUTTON_TERTIARY, Mouse::Button::middle},
            {AMOTION_EVENT_BUTTON_BACK, Mouse::Button::x1},
            {AMOTION_EVENT_BUTTON_FORWARD, Mouse::Button::x2}
        }};

        for (const auto& button : buttons)
        {
            if ((newButtonState & button.first) != (buttonState & button.first))
            {
                if (newButtonState & button.first)
                    mouseDevice->handleButtonPress(button.second, engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)));
                else
                    mouseDevice->handleButtonRelease(button.second, engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)));

                result = true;
            }
        }

        buttonState = newButtonState;
        return result;
    }
}
<commit_msg>Fix spacing<commit_after>// Copyright 2015-2020 Elviss Strazdins. All rights reserved.

#include <array>
#include <stdexcept>
#include <android/input.h>
#include "InputSystemAndroid.hpp"
#include "GamepadDeviceAndroid.hpp"
#include "../../core/android/EngineAndroid.hpp"
#include "../../core/Window.hpp"

namespace ouzel::input::android
{
    InputSystem::InputSystem(const std::function<std::future<bool>(const Event&)>& initCallback):
        input::InputSystem(initCallback),
        keyboardDevice(std::make_unique<KeyboardDevice>(*this, getNextDeviceId())),
        mouseDevice(std::make_unique<MouseDevice>(*this, getNextDeviceId())),
        touchpadDevice(std::make_unique<TouchpadDevice>(*this, getNextDeviceId(), true))
    {
        auto engineAndroid = static_cast<ouzel::android::Engine*>(engine);
        javaVm = engineAndroid->getJavaVm();
        void* jniEnvPointer;

        jint result;
        if ((result = javaVm->GetEnv(&jniEnvPointer, JNI_VERSION_1_6)) != JNI_OK)
            throw std::system_error(result, ouzel::android::getErrorCategory(), "Failed to get JNI environment");

        auto jniEnv = static_cast<JNIEnv*>(jniEnvPointer);

        inputDeviceClass = static_cast<jclass>(jniEnv->NewGlobalRef(jniEnv->FindClass("android/view/InputDevice")));
        getDeviceIdsMethod = jniEnv->GetStaticMethodID(inputDeviceClass, "getDeviceIds", "()[I");

        jclass motionEventClass = jniEnv->FindClass("android/view/MotionEvent");
        getActionMethod = jniEnv->GetMethodID(motionEventClass, "getAction", "()I");
        getPointerIdMethod = jniEnv->GetMethodID(motionEventClass, "getPointerId", "(I)I");
        getToolTypeMethod = jniEnv->GetMethodID(motionEventClass, "getToolType", "(I)I");
        getXMethod = jniEnv->GetMethodID(motionEventClass, "getX", "(I)F");
        getYMethod = jniEnv->GetMethodID(motionEventClass, "getY", "(I)F");
        getPressureMethod = jniEnv->GetMethodID(motionEventClass, "getPressure", "(I)F");
        getAxisValueMethod = jniEnv->GetMethodID(motionEventClass, "getAxisValue", "(I)F");
        getButtonStateMethod = jniEnv->GetMethodID(motionEventClass, "getButtonState", "()I");
    }

    InputSystem::~InputSystem()
    {
        void* jniEnvPointer;

        if (javaVm->GetEnv(&jniEnvPointer, JNI_VERSION_1_6) == JNI_OK)
        {
            auto jniEnv = static_cast<JNIEnv*>(jniEnvPointer);
            if (inputDeviceClass) jniEnv->DeleteGlobalRef(inputDeviceClass);
        }
    }

    void InputSystem::executeCommand(const Command& command)
    {
        switch (command.type)
        {
        case Command::Type::startDeviceDiscovery:
            break;
        case Command::Type::stopDeviceDiscovery:
            break;
        case Command::Type::setPlayerIndex:
        {
            break;
        }
        case Command::Type::setVibration:
        {
            break;
        }
        case Command::Type::showVirtualKeyboard:
            break;
        case Command::Type::hideVirtualKeyboard:
            break;
        default:
            break;
        }
    }

    jboolean InputSystem::handleTouchEvent(jobject event)
    {
        void* jniEnvPointer;

        jint result;
        if ((result = javaVm->GetEnv(&jniEnvPointer, JNI_VERSION_1_6)) != JNI_OK)
            throw std::system_error(result, ouzel::android::getErrorCategory(), "Failed to get JNI environment");

        auto jniEnv = static_cast<JNIEnv*>(jniEnvPointer);

        const jint action = jniEnv->CallIntMethod(event, getActionMethod);

        switch (action & AMOTION_EVENT_ACTION_MASK)
        {
            case AMOTION_EVENT_ACTION_DOWN: // first touch
            {
                const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0);
                const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0);
                const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0);

                if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE)
                    return updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y);
                else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_ERASER)
                {
                    const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0);
                    const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, 0);
                    touchpadDevice->handleTouchBegin(static_cast<std::uint64_t>(pointerId),
                                                     engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)),
                                                     pressure);
                    return true;
                }

                break;
            }
            case AMOTION_EVENT_ACTION_POINTER_DOWN: // touches beyond the first
            {
                const jint pointerIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
                const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, pointerIndex);
                const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, pointerIndex);
                const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, pointerIndex);

                if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE)
                    return updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y);
                else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_ERASER)
                {
                    const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, pointerIndex);
                    const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, pointerIndex);
                    touchpadDevice->handleTouchBegin(static_cast<std::uint64_t>(pointerId),
                                                     engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)),
                                                     pressure);
                    return true;
                }

                break;
            }
            case AMOTION_EVENT_ACTION_MOVE:
            {
                const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0);
                const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0);
                const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0);

                if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE)
                {
                    if (!updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y))
                        mouseDevice->handleMove(engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)));
                    return true;
                }
                else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
                    toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
                    toolType == AMOTION_EVENT_TOOL_TYPE_ERASER)
                {
                    const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0);
                    const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, 0);
                    touchpadDevice->handleTouchMove(static_cast<std::uint64_t>(pointerId),
                                                    engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)),
                                                    pressure);
                    return true;
                }

                break;
            }
            case AMOTION_EVENT_ACTION_UP: // first touch
            {
                const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0);
                const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0);
                const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0);

                if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE)
                    return updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y);
                else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_ERASER)
                {
                    const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0);
                    const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, 0);
                    touchpadDevice->handleTouchEnd(static_cast<std::uint64_t>(pointerId),
                                                   engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)),
                                                   pressure);
                    return true;
                }

                break;
            }
            case AMOTION_EVENT_ACTION_POINTER_UP: // touches beyond the first
            {
                const jint pointerIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
                const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, pointerIndex);
                const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, pointerIndex);
                const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, pointerIndex);

                if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE)
                    return updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y);
                else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_ERASER)
                {
                    const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0);
                    const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, pointerIndex);
                    touchpadDevice->handleTouchEnd(static_cast<std::uint64_t>(pointerId),
                                                   engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)),
                                                   pressure);
                    return true;
                }

                break;
            }
            case AMOTION_EVENT_ACTION_CANCEL:
            {
                const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0);
                const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0);
                const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0);

                if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE)
                {
                    if (!updateButtonState(jniEnv->CallIntMethod(event, getButtonStateMethod), x, y))
                        mouseDevice->handleButtonRelease(Mouse::Button::left, engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)));
                    return true;
                }
                else if (toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
                            toolType == AMOTION_EVENT_TOOL_TYPE_ERASER)
                {
                    const jint pointerId = jniEnv->CallIntMethod(event, getPointerIdMethod, 0);
                    const jfloat pressure = jniEnv->CallFloatMethod(event, getPressureMethod, 0);
                    touchpadDevice->handleTouchCancel(static_cast<std::uint64_t>(pointerId),
                                                      engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)),
                                                      pressure);
                    return true;
                }

                break;
            }
        }

        return false;
    }

    jboolean InputSystem::handleGenericMotionEvent(jobject event)
    {
        void* jniEnvPointer;

        jint result;
        if ((result = javaVm->GetEnv(&jniEnvPointer, JNI_VERSION_1_6)) != JNI_OK)
            throw std::system_error(result, ouzel::android::getErrorCategory(), "Failed to get JNI environment");

        auto jniEnv = static_cast<JNIEnv*>(jniEnvPointer);

        const jint action = jniEnv->CallIntMethod(event, getActionMethod);
        const jint toolType = jniEnv->CallIntMethod(event, getToolTypeMethod, 0);
        const jfloat x = jniEnv->CallFloatMethod(event, getXMethod, 0);
        const jfloat y = jniEnv->CallFloatMethod(event, getYMethod, 0);

        switch (action & AMOTION_EVENT_ACTION_MASK)
        {
            case AMOTION_EVENT_ACTION_HOVER_MOVE:
            {
                if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE)
                {
                    mouseDevice->handleMove(engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)));
                    return true;
                }
                break;
            }
            case AMOTION_EVENT_ACTION_SCROLL:
            {
                const jfloat scrollX = jniEnv->CallFloatMethod(event, getAxisValueMethod, AMOTION_EVENT_AXIS_HSCROLL);
                const jfloat scrollY = jniEnv->CallFloatMethod(event, getAxisValueMethod, AMOTION_EVENT_AXIS_VSCROLL);

                if (toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE)
                {
                    mouseDevice->handleScroll(Vector2F(scrollX, scrollY),
                                              engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)));
                    return true;
                }
                break;
            }
        }

        return false;
    }

    bool InputSystem::updateButtonState(jint newButtonState, jint x, jint y)
    {
        bool result = false;

        constexpr std::array<std::pair<jint, Mouse::Button>, 5> buttons = {{
            {AMOTION_EVENT_BUTTON_PRIMARY, Mouse::Button::left},
            {AMOTION_EVENT_BUTTON_SECONDARY, Mouse::Button::right},
            {AMOTION_EVENT_BUTTON_TERTIARY, Mouse::Button::middle},
            {AMOTION_EVENT_BUTTON_BACK, Mouse::Button::x1},
            {AMOTION_EVENT_BUTTON_FORWARD, Mouse::Button::x2}
        }};

        for (const auto& button : buttons)
        {
            if ((newButtonState & button.first) != (buttonState & button.first))
            {
                if (newButtonState & button.first)
                    mouseDevice->handleButtonPress(button.second, engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)));
                else
                    mouseDevice->handleButtonRelease(button.second, engine->getWindow()->convertWindowToNormalizedLocation(Vector2F(x, y)));

                result = true;
            }
        }

        buttonState = newButtonState;
        return result;
    }
}
<|endoftext|>


<commit_before>
#include "E_ConnectivityAccessor.h"

#include "E_TriangleAccessor.h"
#include "../Mesh/E_Mesh.h"

#include <E_Geometry/E_Triangle.h>
#include <E_Geometry/E_Vec3.h>

#include <Rendering/Mesh/VertexAttributeAccessors.h>

#include <EScript/Basics.h>
#include <EScript/StdObjects.h>

namespace E_Rendering{

//! (static)
EScript::Type * E_ConnectivityAccessor::getTypeObject() {
	// E_ConnectivityAccessor ---|> Object
	static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());
	return typeObject.get();
}

//! (static) init members
void E_ConnectivityAccessor::init(EScript::Namespace & lib) {
	EScript::Type * typeObject = E_ConnectivityAccessor::getTypeObject();
	declareConstant(&lib,getClassName(),typeObject);

	using namespace Rendering::MeshUtils;

	//! [ESF] ConnectivityAccessor Rendering.MeshUtils.ConnectivityAccessor.create(Mesh,name)
	ES_FUN(typeObject,"create",1,1,ConnectivityAccessor::create(
					parameter[0].to<Rendering::Mesh*>(rt)))

	//! [ESMF] Geometry::Vec3 ConnectivityAccessor.getVertex(vIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"getVertex",1,1,
				thisObj->getVertex(parameter[0].to<uint32_t>(rt)))

	//! [ESMF] Array ConnectivityAccessor.getTriangle(tIndex)
	ES_MFUNCTION(typeObject,const ConnectivityAccessor,"getTriangle",1,1, {
		auto tri = thisObj->getTriangle(parameter[0].to<uint32_t>(rt));
		auto arr = EScript::Array::create();
		arr->pushBack(EScript::create(std::get<0>(tri)));
		arr->pushBack(EScript::create(std::get<1>(tri)));
		arr->pushBack(EScript::create(std::get<2>(tri)));
		return arr;
	})

	//! [ESMF] Number ConnectivityAccessor.getCorner(vIndex, tIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"getCorner",2,2,
				thisObj->getCorner(parameter[0].to<uint32_t>(rt), parameter[1].to<uint32_t>(rt)))

	//! [ESMF] Number ConnectivityAccessor.getVertexCorner(vIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"getVertexCorner",1,1,
				thisObj->getVertexCorner(parameter[0].to<uint32_t>(rt)))

	//! [ESMF] Number ConnectivityAccessor.getTriangleCorner(tIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"getTriangleCorner",1,1,
				thisObj->getTriangleCorner(parameter[0].to<uint32_t>(rt)))

	//! [ESMF] Number ConnectivityAccessor.getCornerVertex(cIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"getCornerVertex",1,1,
				thisObj->getCornerVertex(parameter[0].to<uint32_t>(rt)))

	//! [ESMF] Number ConnectivityAccessor.getCornerTriangle(cIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"getCornerTriangle",1,1,
				thisObj->getCornerTriangle(parameter[0].to<uint32_t>(rt)))

	//! [ESMF] Number ConnectivityAccessor.getNextVertexCorner(cIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"getNextVertexCorner",1,1,
				thisObj->getNextVertexCorner(parameter[0].to<uint32_t>(rt)))

	//! [ESMF] Number ConnectivityAccessor.getNextTriangleCorner(cIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"getNextTriangleCorner",1,1,
				thisObj->getNextTriangleCorner(parameter[0].to<uint32_t>(rt)))

	//! [ESMF] Array ConnectivityAccessor.getVertexAdjacentTriangles(vIndex)
	ES_MFUNCTION(typeObject,const ConnectivityAccessor,"getVertexAdjacentTriangles",1,1, {
		auto tri = thisObj->getVertexAdjacentTriangles(parameter[0].to<uint32_t>(rt));
		auto arr = EScript::Array::create();
		for(auto t : tri)
			arr->pushBack(EScript::create(t));
		return arr;
	})

	//! [ESMF] Array ConnectivityAccessor.getAdjacentTriangles(tIndex)
	ES_MFUNCTION(typeObject,const ConnectivityAccessor,"getAdjacentTriangles",1,1, {
		auto tri = thisObj->getAdjacentTriangles(parameter[0].to<uint32_t>(rt));
		auto arr = EScript::Array::create();
		for(auto t : tri)
			arr->pushBack(EScript::create(t));
		return arr;
	})

	//! [ESMF] Number ConnectivityAccessor.isBorderEdge(vIndex1, vIndex2)
	ES_MFUN(typeObject,const ConnectivityAccessor,"isBorderEdge",2,2,
				thisObj->isBorderEdge(parameter[0].to<uint32_t>(rt), parameter[1].to<uint32_t>(rt)))

	//! [ESMF] Number ConnectivityAccessor.isBorderTriangle(tIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"isBorderTriangle",2,2,
				thisObj->isBorderTriangle(parameter[0].to<uint32_t>(rt)))
}

}

<commit_msg>added binding for getVertexAdjacentVertices<commit_after>
#include "E_ConnectivityAccessor.h"

#include "E_TriangleAccessor.h"
#include "../Mesh/E_Mesh.h"

#include <E_Geometry/E_Triangle.h>
#include <E_Geometry/E_Vec3.h>

#include <Rendering/Mesh/VertexAttributeAccessors.h>

#include <EScript/Basics.h>
#include <EScript/StdObjects.h>

namespace E_Rendering{

//! (static)
EScript::Type * E_ConnectivityAccessor::getTypeObject() {
	// E_ConnectivityAccessor ---|> Object
	static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());
	return typeObject.get();
}

//! (static) init members
void E_ConnectivityAccessor::init(EScript::Namespace & lib) {
	EScript::Type * typeObject = E_ConnectivityAccessor::getTypeObject();
	declareConstant(&lib,getClassName(),typeObject);

	using namespace Rendering::MeshUtils;

	//! [ESF] ConnectivityAccessor Rendering.MeshUtils.ConnectivityAccessor.create(Mesh,name)
	ES_FUN(typeObject,"create",1,1,ConnectivityAccessor::create(
					parameter[0].to<Rendering::Mesh*>(rt)))

	//! [ESMF] Geometry::Vec3 ConnectivityAccessor.getVertex(vIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"getVertex",1,1,
				thisObj->getVertex(parameter[0].to<uint32_t>(rt)))

	//! [ESMF] Array ConnectivityAccessor.getTriangle(tIndex)
	ES_MFUNCTION(typeObject,const ConnectivityAccessor,"getTriangle",1,1, {
		auto tri = thisObj->getTriangle(parameter[0].to<uint32_t>(rt));
		auto arr = EScript::Array::create();
		arr->pushBack(EScript::create(std::get<0>(tri)));
		arr->pushBack(EScript::create(std::get<1>(tri)));
		arr->pushBack(EScript::create(std::get<2>(tri)));
		return arr;
	})

	//! [ESMF] Number ConnectivityAccessor.getCorner(vIndex, tIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"getCorner",2,2,
				thisObj->getCorner(parameter[0].to<uint32_t>(rt), parameter[1].to<uint32_t>(rt)))

	//! [ESMF] Number ConnectivityAccessor.getVertexCorner(vIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"getVertexCorner",1,1,
				thisObj->getVertexCorner(parameter[0].to<uint32_t>(rt)))

	//! [ESMF] Number ConnectivityAccessor.getTriangleCorner(tIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"getTriangleCorner",1,1,
				thisObj->getTriangleCorner(parameter[0].to<uint32_t>(rt)))

	//! [ESMF] Number ConnectivityAccessor.getCornerVertex(cIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"getCornerVertex",1,1,
				thisObj->getCornerVertex(parameter[0].to<uint32_t>(rt)))

	//! [ESMF] Number ConnectivityAccessor.getCornerTriangle(cIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"getCornerTriangle",1,1,
				thisObj->getCornerTriangle(parameter[0].to<uint32_t>(rt)))

	//! [ESMF] Number ConnectivityAccessor.getNextVertexCorner(cIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"getNextVertexCorner",1,1,
				thisObj->getNextVertexCorner(parameter[0].to<uint32_t>(rt)))

	//! [ESMF] Number ConnectivityAccessor.getNextTriangleCorner(cIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"getNextTriangleCorner",1,1,
				thisObj->getNextTriangleCorner(parameter[0].to<uint32_t>(rt)))

	//! [ESMF] Array ConnectivityAccessor.getVertexAdjacentTriangles(vIndex)
	ES_MFUNCTION(typeObject,const ConnectivityAccessor,"getVertexAdjacentTriangles",1,1, {
		auto tri = thisObj->getVertexAdjacentTriangles(parameter[0].to<uint32_t>(rt));
		auto arr = EScript::Array::create();
		for(auto t : tri)
			arr->pushBack(EScript::create(t));
		return arr;
	})

	//! [ESMF] Array ConnectivityAccessor.getVertexAdjacentVertices(vIndex)
	ES_MFUNCTION(typeObject,const ConnectivityAccessor,"getVertexAdjacentVertices",1,1, {
		auto verts = thisObj->getVertexAdjacentVertices(parameter[0].to<uint32_t>(rt));
		auto arr = EScript::Array::create();
		for(auto v : verts)
			arr->pushBack(EScript::create(v));
		return arr;
	})

	//! [ESMF] Array ConnectivityAccessor.getAdjacentTriangles(tIndex)
	ES_MFUNCTION(typeObject,const ConnectivityAccessor,"getAdjacentTriangles",1,1, {
		auto tri = thisObj->getAdjacentTriangles(parameter[0].to<uint32_t>(rt));
		auto arr = EScript::Array::create();
		for(auto t : tri)
			arr->pushBack(EScript::create(t));
		return arr;
	})

	//! [ESMF] Number ConnectivityAccessor.isBorderEdge(vIndex1, vIndex2)
	ES_MFUN(typeObject,const ConnectivityAccessor,"isBorderEdge",2,2,
				thisObj->isBorderEdge(parameter[0].to<uint32_t>(rt), parameter[1].to<uint32_t>(rt)))

	//! [ESMF] Number ConnectivityAccessor.isBorderTriangle(tIndex)
	ES_MFUN(typeObject,const ConnectivityAccessor,"isBorderTriangle",1,1,
				thisObj->isBorderTriangle(parameter[0].to<uint32_t>(rt)))
}

}

<|endoftext|>