<commit_before>/***************************************************************************
 *   Copyright (c) sliptonic (shopinthewoods@gmail.com) 2020               *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <boost/algorithm/string.hpp>
#endif

#include "Mod/Path/App/Voronoi.h"
#include "Mod/Path/App/VoronoiCell.h"
#include "Mod/Path/App/VoronoiEdge.h"
#include "Mod/Path/App/VoronoiVertex.h"
#include <Base/Exception.h>
#include <Base/GeometryPyCXX.h>
#include <Base/Vector3D.h>
#include <Base/VectorPy.h>

// files generated out of VoronoiPy.xml
#include "VoronoiPy.h"
#include "VoronoiPy.cpp"
#include "VoronoiCellPy.h"
#include "VoronoiEdgePy.h"
#include "VoronoiVertexPy.h"

using namespace Path;

// returns a string which represents the object e.g. when printed in python
std::string VoronoiPy::representation(void) const
{
  std::stringstream ss;
  ss.precision(5);
  ss << "Voronoi("
    << "{" << getVoronoiPtr()->numSegments() << ", " << getVoronoiPtr()->numPoints() << "}"
    << " -> "
    << "{" << getVoronoiPtr()->numCells() << ", " << getVoronoiPtr()->numEdges() << ", " << getVoronoiPtr()->numVertices() << "}"
    << ")";
  return ss.str();
}

PyObject *VoronoiPy::PyMake(struct _typeobject *, PyObject *, PyObject *)  // Python wrapper
{
  // create a new instance of VoronoiPy and its twin object
  return new VoronoiPy(new Voronoi);
}

// constructor
int VoronoiPy::PyInit(PyObject* args, PyObject* /*kwds*/)
{
  Voronoi *vo = getVoronoiPtr();
  double scale = vo->getScale();
  if (!PyArg_ParseTuple(args, "|d", &scale)) {
    PyErr_SetString(PyExc_RuntimeError, "scale argument (double) accepted, default = 1000");
    return -1;
  }
  vo->setScale(scale);
  return 0;
}

Voronoi::point_type getPointFromPy(PyObject *obj) {
  if (obj) {
    if (PyObject_TypeCheck(obj, &Base::VectorPy::Type)) {
      Base::Vector3d *vect = (static_cast<Base::VectorPy*>(obj))->getVectorPtr();
      return Voronoi::point_type(vect->x, vect->y);
    } else if (PyObject_TypeCheck(obj, Base::Vector2dPy::type_object())) {
      Base::Vector2d vect = Py::toVector2d(obj);
      return Voronoi::point_type(vect.x, vect.y);
    }
  }
  throw Py::TypeError("Points must be Base::Vector or Base::Vector2d");
  return Voronoi::point_type();
}

PyObject* VoronoiPy::addPoint(PyObject *args) {
  PyObject *obj = 0;
  if (PyArg_ParseTuple(args, "O", &obj)) {
    getVoronoiPtr()->addPoint(getPointFromPy(obj));
  }
  Py_INCREF(Py_None);
  return Py_None;
}

PyObject* VoronoiPy::addSegment(PyObject *args) {
  PyObject *objBegin = 0;
  PyObject *objEnd   = 0;

  if (PyArg_ParseTuple(args, "OO", &objBegin, &objEnd)) {
    auto p0 = getPointFromPy(objBegin);
    auto p1 = getPointFromPy(objEnd);
    getVoronoiPtr()->addSegment(Voronoi::segment_type(p0, p1));
  }
  Py_INCREF(Py_None);
  return Py_None;
}

PyObject* VoronoiPy::construct(PyObject *args) {
  if (!PyArg_ParseTuple(args, "")) {
    throw  Py::RuntimeError("no arguments accepted");
  }
  getVoronoiPtr()->construct();

  Py_INCREF(Py_None);
  return Py_None;
}

PyObject* VoronoiPy::numCells(PyObject *args)
{
  if (!PyArg_ParseTuple(args, "")) {
    throw  Py::RuntimeError("no arguments accepted");
  }
  return PyLong_FromLong(getVoronoiPtr()->numCells());
}

PyObject* VoronoiPy::numEdges(PyObject *args)
{
  if (!PyArg_ParseTuple(args, "")) {
    throw  Py::RuntimeError("no arguments accepted");
  }
  return PyLong_FromLong(getVoronoiPtr()->numEdges());
}

PyObject* VoronoiPy::numVertices(PyObject *args)
{
  if (!PyArg_ParseTuple(args, "")) {
    throw  Py::RuntimeError("no arguments accepted");
  }
  return PyLong_FromLong(getVoronoiPtr()->numVertices());
}

Py::List VoronoiPy::getVertices(void) const {
  Py::List list;
  for (int i=0; i<getVoronoiPtr()->numVertices(); ++i) {
    list.append(Py::asObject(new VoronoiVertexPy(getVoronoiPtr()->create<VoronoiVertex>(i))));
  }
  return list;
}

Py::List VoronoiPy::getEdges(void) const {
  Py::List list;
  for (int i=0; i<getVoronoiPtr()->numEdges(); ++i) {
    list.append(Py::asObject(new VoronoiEdgePy(getVoronoiPtr()->create<VoronoiEdge>(i))));
  }
  return list;
}

Py::List VoronoiPy::getCells(void) const {
  Py::List list;
  for (int i=0; i<getVoronoiPtr()->numCells(); ++i) {
    list.append(Py::asObject(new VoronoiCellPy(getVoronoiPtr()->create<VoronoiCell>(i))));
  }
  return list;
}

static bool callbackWithVertex(Voronoi::diagram_type *dia, PyObject *callback, const Voronoi::diagram_type::vertex_type *v, bool &isExterior) {
  if (!isExterior && v->color() == 0) {
    PyObject *vx = new VoronoiVertexPy(new VoronoiVertex(dia, v));
    PyObject *arglist = Py_BuildValue("(O)", vx);
    PyObject *result = PyEval_CallObject(callback, arglist);
    Py_DECREF(arglist);
    Py_DECREF(vx);
    if (result == NULL) {
      return false;
    }
    isExterior = result == Py_True;
    Py_DECREF(result);
  }
  return true;
}

PyObject* VoronoiPy::colorExterior(PyObject *args) {
  Voronoi::color_type color = 0;
  PyObject *callback = 0;
  if (!PyArg_ParseTuple(args, "k|O", &color, &callback)) {
    throw  Py::RuntimeError("colorExterior requires an integer (color) argument");
  }
  Voronoi *vo = getVoronoiPtr();
  vo->colorExterior(color);
  if (callback) {
    for (auto e = vo->vd->edges().begin(); e != vo->vd->edges().end(); ++e) {
      if (e->is_finite() && e->color() == 0) {
        const Voronoi::diagram_type::vertex_type *v0 = e->vertex0();
        const Voronoi::diagram_type::vertex_type *v1 = e->vertex1();
        bool is0 = false;
        bool is1 = false;
        if (!callbackWithVertex(vo->vd, callback, v0, is0) || !callbackWithVertex(vo->vd, callback, v1, is1)) {
          return NULL;
        }
        if (is0 && is1) {
          vo->colorExterior(&(*e), color);
        }
      }
    }
  }

  Py_INCREF(Py_None);
  return Py_None;
}

PyObject* VoronoiPy::colorTwins(PyObject *args) {
  Voronoi::color_type color = 0;
  if (!PyArg_ParseTuple(args, "k", &color)) {
    throw  Py::RuntimeError("colorTwins requires an integer (color) argument");
  }
  getVoronoiPtr()->colorTwins(color);

  Py_INCREF(Py_None);
  return Py_None;
}

PyObject* VoronoiPy::colorColinear(PyObject *args) {
  Voronoi::color_type color = 0;
  double degree = 10.;
  if (!PyArg_ParseTuple(args, "k|d", &color, &degree)) {
    throw  Py::RuntimeError("colorColinear requires an integer (color) and optionally a derivation in degrees argument (default 10)");
  }
  getVoronoiPtr()->colorColinear(color, degree);

  Py_INCREF(Py_None);
  return Py_None;
}

PyObject* VoronoiPy::resetColor(PyObject *args) {
  Voronoi::color_type color = 0;
  if (!PyArg_ParseTuple(args, "k", &color)) {
    throw  Py::RuntimeError("clearColor requires an integer (color) argument");
  }

  getVoronoiPtr()->resetColor(color);

  Py_INCREF(Py_None);
  return Py_None;
}

// custom attributes get/set

PyObject *VoronoiPy::getCustomAttributes(const char* /*attr*/) const
{
  return 0;
}

int VoronoiPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
  return 0;
}

<commit_msg>Simplified and further optimised colinear colorisation<commit_after>/***************************************************************************
 *   Copyright (c) sliptonic (shopinthewoods@gmail.com) 2020               *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <boost/algorithm/string.hpp>
#endif

#include "Mod/Path/App/Voronoi.h"
#include "Mod/Path/App/VoronoiCell.h"
#include "Mod/Path/App/VoronoiEdge.h"
#include "Mod/Path/App/VoronoiVertex.h"
#include <Base/Exception.h>
#include <Base/GeometryPyCXX.h>
#include <Base/Vector3D.h>
#include <Base/VectorPy.h>

// files generated out of VoronoiPy.xml
#include "VoronoiPy.h"
#include "VoronoiPy.cpp"
#include "VoronoiCellPy.h"
#include "VoronoiEdgePy.h"
#include "VoronoiVertexPy.h"

using namespace Path;

// returns a string which represents the object e.g. when printed in python
std::string VoronoiPy::representation(void) const
{
  std::stringstream ss;
  ss.precision(5);
  ss << "Voronoi("
    << "{" << getVoronoiPtr()->numSegments() << ", " << getVoronoiPtr()->numPoints() << "}"
    << " -> "
    << "{" << getVoronoiPtr()->numCells() << ", " << getVoronoiPtr()->numEdges() << ", " << getVoronoiPtr()->numVertices() << "}"
    << ")";
  return ss.str();
}

PyObject *VoronoiPy::PyMake(struct _typeobject *, PyObject *, PyObject *)  // Python wrapper
{
  // create a new instance of VoronoiPy and its twin object
  return new VoronoiPy(new Voronoi);
}

// constructor
int VoronoiPy::PyInit(PyObject* args, PyObject* /*kwds*/)
{
  Voronoi *vo = getVoronoiPtr();
  double scale = vo->getScale();
  if (!PyArg_ParseTuple(args, "|d", &scale)) {
    PyErr_SetString(PyExc_RuntimeError, "scale argument (double) accepted, default = 1000");
    return -1;
  }
  vo->setScale(scale);
  return 0;
}

Voronoi::point_type getPointFromPy(PyObject *obj) {
  if (obj) {
    if (PyObject_TypeCheck(obj, &Base::VectorPy::Type)) {
      Base::Vector3d *vect = (static_cast<Base::VectorPy*>(obj))->getVectorPtr();
      return Voronoi::point_type(vect->x, vect->y);
    } else if (PyObject_TypeCheck(obj, Base::Vector2dPy::type_object())) {
      Base::Vector2d vect = Py::toVector2d(obj);
      return Voronoi::point_type(vect.x, vect.y);
    }
  }
  throw Py::TypeError("Points must be Base::Vector or Base::Vector2d");
  return Voronoi::point_type();
}

PyObject* VoronoiPy::addPoint(PyObject *args) {
  PyObject *obj = 0;
  if (PyArg_ParseTuple(args, "O", &obj)) {
    getVoronoiPtr()->addPoint(getPointFromPy(obj));
  }
  Py_INCREF(Py_None);
  return Py_None;
}

PyObject* VoronoiPy::addSegment(PyObject *args) {
  PyObject *objBegin = 0;
  PyObject *objEnd   = 0;

  if (PyArg_ParseTuple(args, "OO", &objBegin, &objEnd)) {
    auto p0 = getPointFromPy(objBegin);
    auto p1 = getPointFromPy(objEnd);
    getVoronoiPtr()->addSegment(Voronoi::segment_type(p0, p1));
  }
  Py_INCREF(Py_None);
  return Py_None;
}

PyObject* VoronoiPy::construct(PyObject *args) {
  if (!PyArg_ParseTuple(args, "")) {
    throw  Py::RuntimeError("no arguments accepted");
  }
  getVoronoiPtr()->construct();

  Py_INCREF(Py_None);
  return Py_None;
}

PyObject* VoronoiPy::numCells(PyObject *args)
{
  if (!PyArg_ParseTuple(args, "")) {
    throw  Py::RuntimeError("no arguments accepted");
  }
  return PyLong_FromLong(getVoronoiPtr()->numCells());
}

PyObject* VoronoiPy::numEdges(PyObject *args)
{
  if (!PyArg_ParseTuple(args, "")) {
    throw  Py::RuntimeError("no arguments accepted");
  }
  return PyLong_FromLong(getVoronoiPtr()->numEdges());
}

PyObject* VoronoiPy::numVertices(PyObject *args)
{
  if (!PyArg_ParseTuple(args, "")) {
    throw  Py::RuntimeError("no arguments accepted");
  }
  return PyLong_FromLong(getVoronoiPtr()->numVertices());
}

Py::List VoronoiPy::getVertices(void) const {
  Py::List list;
  for (int i=0; i<getVoronoiPtr()->numVertices(); ++i) {
    list.append(Py::asObject(new VoronoiVertexPy(getVoronoiPtr()->create<VoronoiVertex>(i))));
  }
  return list;
}

Py::List VoronoiPy::getEdges(void) const {
  Py::List list;
  for (int i=0; i<getVoronoiPtr()->numEdges(); ++i) {
    list.append(Py::asObject(new VoronoiEdgePy(getVoronoiPtr()->create<VoronoiEdge>(i))));
  }
  return list;
}

Py::List VoronoiPy::getCells(void) const {
  Py::List list;
  for (int i=0; i<getVoronoiPtr()->numCells(); ++i) {
    list.append(Py::asObject(new VoronoiCellPy(getVoronoiPtr()->create<VoronoiCell>(i))));
  }
  return list;
}

static bool callbackWithVertex(Voronoi::diagram_type *dia, PyObject *callback, const Voronoi::diagram_type::vertex_type *v, bool &bail) {
  bool rc = false;
  if (!bail && v->color() == 0) {
    PyObject *vx = new VoronoiVertexPy(new VoronoiVertex(dia, v));
    PyObject *arglist = Py_BuildValue("(O)", vx);
    PyObject *result = PyEval_CallObject(callback, arglist);
    Py_DECREF(arglist);
    Py_DECREF(vx);
    if (result == NULL) {
      bail = true;
    } else {
      rc = result == Py_True;
      Py_DECREF(result);
    }
  }
  return rc;
}

PyObject* VoronoiPy::colorExterior(PyObject *args) {
  Voronoi::color_type color = 0;
  PyObject *callback = 0;
  if (!PyArg_ParseTuple(args, "k|O", &color, &callback)) {
    throw  Py::RuntimeError("colorExterior requires an integer (color) argument");
  }
  Voronoi *vo = getVoronoiPtr();
  vo->colorExterior(color);
  if (callback) {
    for (auto e = vo->vd->edges().begin(); e != vo->vd->edges().end(); ++e) {
      if (e->is_finite() && e->color() == 0) {
        const Voronoi::diagram_type::vertex_type *v0 = e->vertex0();
        const Voronoi::diagram_type::vertex_type *v1 = e->vertex1();
        bool bail = false;
        if (callbackWithVertex(vo->vd, callback, v0, bail) && callbackWithVertex(vo->vd, callback, v1, bail)) {
          vo->colorExterior(&(*e), color);
        }
        if (bail) {
          return NULL;
        }
      }
    }
  }

  Py_INCREF(Py_None);
  return Py_None;
}

PyObject* VoronoiPy::colorTwins(PyObject *args) {
  Voronoi::color_type color = 0;
  if (!PyArg_ParseTuple(args, "k", &color)) {
    throw  Py::RuntimeError("colorTwins requires an integer (color) argument");
  }
  getVoronoiPtr()->colorTwins(color);

  Py_INCREF(Py_None);
  return Py_None;
}

PyObject* VoronoiPy::colorColinear(PyObject *args) {
  Voronoi::color_type color = 0;
  double degree = 10.;
  if (!PyArg_ParseTuple(args, "k|d", &color, &degree)) {
    throw  Py::RuntimeError("colorColinear requires an integer (color) and optionally a derivation in degrees argument (default 10)");
  }
  getVoronoiPtr()->colorColinear(color, degree);

  Py_INCREF(Py_None);
  return Py_None;
}

PyObject* VoronoiPy::resetColor(PyObject *args) {
  Voronoi::color_type color = 0;
  if (!PyArg_ParseTuple(args, "k", &color)) {
    throw  Py::RuntimeError("clearColor requires an integer (color) argument");
  }

  getVoronoiPtr()->resetColor(color);

  Py_INCREF(Py_None);
  return Py_None;
}

// custom attributes get/set

PyObject *VoronoiPy::getCustomAttributes(const char* /*attr*/) const
{
  return 0;
}

int VoronoiPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
  return 0;
}

<|endoftext|>


<commit_before>// The MIT License (MIT)

// Copyright (c) 2016, Microsoft

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

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

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

#include "gtest/gtest.h"

#include "Allocator.h"
#include "BitFunnel/Utilities/TextObjectFormatter.h"
#include "CompileNode.h"
#include "PlainTextCodeGenerator.h"
#include "TextObjectParser.h"

namespace BitFunnel
{
    namespace CompileNodeUnitTest
    {
        // TODO: Tests of illegal trees, e.g. and/or/phrases with 0, 1 child

        const char* c_parseFormatCases[] = {

            //
            // AndRowJz
            //

            // AndRowJz does not allow a null child.

            // AndRowJz followed by Report.
            "AndRowJz {\n"
            "  Row: Row(1, 2, 0, false),\n"
            "  Child: Report {\n"
            "    Child: \n"
            "  }\n"
            "}",

            //
            // LoadRowJz
            //

            // LoadRowJz with no child.
            "LoadRowJz {\n"
            "  Row: Row(1, 2, 0, false),\n"
            "  Child: Report {\n"
            "    Child: \n"
            "  }\n"
            "}",

            // LoadRowJz with Report child.
            "LoadRowJz {\n"
            "  Row: Row(1, 2, 0, false),\n"
            "  Child: Report {\n"
            "    Child: \n"
            "  }\n"
            "}",

            //
            // Or
            //

            // Or with 0 children no longer legal.
            // Or with 1 child no longer legal.

            // Or with two children.
            "Or {\n"
            "  Children: [\n"
            "    Report {\n"
            "      Child: \n"
            "    },\n"
            "    Report {\n"
            "      Child: \n"
            "    }\n"
            "  ]\n"
            "}",

            // Or with three children.
            "Or {\n"
            "  Children: [\n"
            "    Report {\n"
            "      Child: \n"
            "    },\n"
            "    Report {\n"
            "      Child: \n"
            "    },\n"
            "    Report {\n"
            "      Child: \n"
            "    }\n"
            "  ]\n"
            "}",

            //
            // RankDown
            //

            // RankDown with Report child.
            "RankDown {\n"
            "  Delta: 3,\n"
            "  Child: Report {\n"
            "    Child: \n"
            "  }\n"
            "}",

            //
            // Report
            //

            // Report with no child.
            "Report {\n"
            "  Child: \n"
            "}",

            // Report with LoadRowJz child.
            "Report {\n"
            "  Child: LoadRowJz {\n"
            "    Row: Row(1, 2, 0, false),\n"
            "    Child: Report {\n"
            "      Child: \n"
            "    }\n"
            "  }\n"
            "}",

            //
            // AndTree
            //
            "AndTree {\n"
            "  Children: [\n"
            "    LoadRow(0, 6, 0, false),\n"
            "    LoadRow(1, 0, 0, false)\n"
            "  ]\n"
            "}",

            "AndTree {\n"
            "  Children: [\n"
            "    LoadRow(0, 6, 0, false),\n"
            "    LoadRow(1, 3, 0, false),\n"
            "    LoadRow(2, 0, 0, false)\n"
            "  ]\n"
            "}",

            //
            // LoadRow
            //
            "LoadRow(0, 6, 0, false)",
            "LoadRow(1, 5, 0, true)",

            //
            // Not
            //
            "Not {\n"
            "  Child: LoadRow(0, 6, 0, false)\n"
            "}",

            //
            // OrTree
            //
            "OrTree {\n"
            "  Children: [\n"
            "    LoadRow(0, 6, 0, false),\n"
            "    LoadRow(1, 0, 0, false)\n"
            "  ]\n"
            "}",

            "OrTree {\n"
            "  Children: [\n"
            "    LoadRow(0, 6, 0, false),\n"
            "    LoadRow(1, 3, 0, false),\n"
            "    LoadRow(2, 0, 0, false)\n"
            "  ]\n"
            "}",
        };

        struct InputOutput
        {
        public:
            char const * m_input;
            char const * m_output;
        };

        const InputOutput c_codeGenerationCases[] =
        {
            // AndRowJz
            {
                "AndRowJz {\n"
                "  Row: Row(1, 2, 0, false),\n"
                "  Child: Report {\n"
                "    Child: \n"
                "  }\n"
                "}",
                "    AndRow(1, false, 0)\n"
                "    Jz(0)\n"
                "    Report()\n"
                "L0:\n"
            },

            // LoadRowJz
            {
                "LoadRowJz {\n"
                "  Row: Row(1, 2, 0, false),\n"
                "  Child: Report {\n"
                "    Child: \n"
                "  }\n"
                "}",
                "    LoadRow(1, false, 0)\n"
                "    Jz(0)\n"
                "    Report()\n"
                "L0:\n"
            },

            // Or
            {
                "Or {\n"
                "  Children: [\n"
                "    LoadRowJz {\n"
                "      Row: Row(0, 6, 0, false),\n"
                "      Child: Report {\n"
                "        Child: \n"
                "      }\n"
                "    },"
                "    LoadRowJz {\n"
                "      Row: Row(1, 6, 0, false),\n"
                "      Child: Report {\n"
                "        Child: \n"
                "      }\n"
                "    }"
                "  ]"
                "}",
                "    Push()\n"
                "    LoadRow(0, false, 0)\n"
                "    Jz(0)\n"
                "    Report()\n"
                "L0:\n"
                "    Pop()\n"
                "    LoadRow(1, false, 0)\n"
                "    Jz(1)\n"
                "    Report()\n"
                "L1:\n"
            },

            // RankDown
            {
                "RankDown {"
                "  Delta: 1,"
                "  Child: LoadRow(1, 2, 0, false)"
                "}",
                "    LeftShiftOffset(1)\n"
                "    Push()\n"
                "    Call(0)\n"
                "    Pop()\n"
                "    IncrementOffset()\n"
                "    Call(0)\n"
                "    Jmp(1)\n"
                "L0:\n"
                "    LoadRow(1, false, 0)\n"
                "    Return()\n"
                "L1:\n"
                "    RightShiftOffset(1)\n"
            },

            // Report with no child.
            // RankDown algorithm does Jz around Report().
            {
                "Report {"
                "  Child:"
                "}",
                "    Report()\n"
            },

            // Report with one child.
            // Includes Jz around Report().
            // TODO: What happens if this is the entire tree? Don't we need to
            // -1 into the accumulator first?
            {
                "Report {"
                "  Child: LoadRow(1, 2, 0, false)\n"
                "}",
                "    Push()\n"
                "    LoadRow(1, false, 0)\n"
                "    AndStack()\n"
                "    Jz(0)\n"
                "    Report()\n"
                "L0:\n"
            },

            {
                "AndTree {\n"
                "  Children: [\n"
                "    LoadRow(0, 6, 0, false),\n"
                "    LoadRow(1, 0, 0, false)\n"
                "  ]\n"
                "}",
                "    LoadRow(0, false, 0)\n"
                "    UpdateFlags()\n"
                "    Jz(0)\n"
                "    Push()\n"
                "    LoadRow(1, false, 0)\n"
                "    AndStack()\n"
                "L0:\n"
            },

            {
                "Not {\n"
                "  Child: LoadRow(0, 6, 0, false)\n"
                "}",
                "    LoadRow(0, false, 0)\n"
                "    Not()\n"
            },

            {
                "OrTree {\n"
                "  Children: [\n"
                "    LoadRow(0, 6, 0, false),\n"
                "    LoadRow(1, 0, 0, false)\n"
                "  ]\n"
                "}",
                "    LoadRow(0, false, 0)\n"
                "    Push()\n"
                "    LoadRow(1, false, 0)\n"
                "    OrStack()\n"
            }
        };

        //*********************************************************************
        //
        // Parse/Format cases.
        //
        //*********************************************************************
        void VerifyRoundtripCase(const char* text)
        {
            std::stringstream input(text);

            Allocator allocator(1024);
            TextObjectParser parser(input, allocator, &CompileNode::GetType);

            CompileNode const & node = CompileNode::Parse(parser);

            std::stringstream output;
            TextObjectFormatter formatter(output);
            node.Format(formatter);

            // std::cout << "\"" << text << "\"" << std::endl;
            // std::cout << "\"" << output.str() << "\"" << std::endl;

            EXPECT_EQ(text, output.str());
        }

        TEST(CompileNode, ParseFormat)
        {
            for (unsigned i = 0; i < sizeof(c_parseFormatCases) / sizeof(const char*); ++i)
            {
                VerifyRoundtripCase(c_parseFormatCases[i]);
            }
        }

        //*********************************************************************
        //
        // Code generation cases.
        //
        //*********************************************************************
        void VerifyCodeGenerationCase(InputOutput const & testCase)
        {
            std::stringstream input(testCase.m_input);

            Allocator allocator(1024);
            TextObjectParser parser(input, allocator, &CompileNode::GetType);

            CompileNode const & node = CompileNode::Parse(parser);

            std::stringstream output;
            PlainTextCodeGenerator code(output);
            node.Compile(code);

            //std::cout << "+++++++++++++++++++" << std::endl;
            //std::cout << "\"" << testCase.m_output << "\"" << std::endl;
            //std::cout << "+++" << std::endl;
            //std::cout << "\"" << output.str() << "\"" << std::endl;

            EXPECT_EQ(testCase.m_output, output.str());
        }

        TEST(CompileNode, CodeGeneration)
        {
            for (unsigned i = 0; i < sizeof(c_codeGenerationCases) / sizeof(InputOutput); ++i)
            {
                VerifyCodeGenerationCase(c_codeGenerationCases[i]);
            }
        }
    }
}
<commit_msg>Shrink allocators in test.<commit_after>// The MIT License (MIT)

// Copyright (c) 2016, Microsoft

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

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

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

#include "gtest/gtest.h"

#include "Allocator.h"
#include "BitFunnel/Utilities/TextObjectFormatter.h"
#include "CompileNode.h"
#include "PlainTextCodeGenerator.h"
#include "TextObjectParser.h"

namespace BitFunnel
{
    namespace CompileNodeUnitTest
    {
        // TODO: Tests of illegal trees, e.g. and/or/phrases with 0, 1 child

        const char* c_parseFormatCases[] = {

            //
            // AndRowJz
            //

            // AndRowJz does not allow a null child.

            // AndRowJz followed by Report.
            "AndRowJz {\n"
            "  Row: Row(1, 2, 0, false),\n"
            "  Child: Report {\n"
            "    Child: \n"
            "  }\n"
            "}",

            //
            // LoadRowJz
            //

            // LoadRowJz with no child.
            "LoadRowJz {\n"
            "  Row: Row(1, 2, 0, false),\n"
            "  Child: Report {\n"
            "    Child: \n"
            "  }\n"
            "}",

            // LoadRowJz with Report child.
            "LoadRowJz {\n"
            "  Row: Row(1, 2, 0, false),\n"
            "  Child: Report {\n"
            "    Child: \n"
            "  }\n"
            "}",

            //
            // Or
            //

            // Or with 0 children no longer legal.
            // Or with 1 child no longer legal.

            // Or with two children.
            "Or {\n"
            "  Children: [\n"
            "    Report {\n"
            "      Child: \n"
            "    },\n"
            "    Report {\n"
            "      Child: \n"
            "    }\n"
            "  ]\n"
            "}",

            // Or with three children.
            "Or {\n"
            "  Children: [\n"
            "    Report {\n"
            "      Child: \n"
            "    },\n"
            "    Report {\n"
            "      Child: \n"
            "    },\n"
            "    Report {\n"
            "      Child: \n"
            "    }\n"
            "  ]\n"
            "}",

            //
            // RankDown
            //

            // RankDown with Report child.
            "RankDown {\n"
            "  Delta: 3,\n"
            "  Child: Report {\n"
            "    Child: \n"
            "  }\n"
            "}",

            //
            // Report
            //

            // Report with no child.
            "Report {\n"
            "  Child: \n"
            "}",

            // Report with LoadRowJz child.
            "Report {\n"
            "  Child: LoadRowJz {\n"
            "    Row: Row(1, 2, 0, false),\n"
            "    Child: Report {\n"
            "      Child: \n"
            "    }\n"
            "  }\n"
            "}",

            //
            // AndTree
            //
            "AndTree {\n"
            "  Children: [\n"
            "    LoadRow(0, 6, 0, false),\n"
            "    LoadRow(1, 0, 0, false)\n"
            "  ]\n"
            "}",

            "AndTree {\n"
            "  Children: [\n"
            "    LoadRow(0, 6, 0, false),\n"
            "    LoadRow(1, 3, 0, false),\n"
            "    LoadRow(2, 0, 0, false)\n"
            "  ]\n"
            "}",

            //
            // LoadRow
            //
            "LoadRow(0, 6, 0, false)",
            "LoadRow(1, 5, 0, true)",

            //
            // Not
            //
            "Not {\n"
            "  Child: LoadRow(0, 6, 0, false)\n"
            "}",

            //
            // OrTree
            //
            "OrTree {\n"
            "  Children: [\n"
            "    LoadRow(0, 6, 0, false),\n"
            "    LoadRow(1, 0, 0, false)\n"
            "  ]\n"
            "}",

            "OrTree {\n"
            "  Children: [\n"
            "    LoadRow(0, 6, 0, false),\n"
            "    LoadRow(1, 3, 0, false),\n"
            "    LoadRow(2, 0, 0, false)\n"
            "  ]\n"
            "}",
        };

        struct InputOutput
        {
        public:
            char const * m_input;
            char const * m_output;
        };

        const InputOutput c_codeGenerationCases[] =
        {
            // AndRowJz
            {
                "AndRowJz {\n"
                "  Row: Row(1, 2, 0, false),\n"
                "  Child: Report {\n"
                "    Child: \n"
                "  }\n"
                "}",
                "    AndRow(1, false, 0)\n"
                "    Jz(0)\n"
                "    Report()\n"
                "L0:\n"
            },

            // LoadRowJz
            {
                "LoadRowJz {\n"
                "  Row: Row(1, 2, 0, false),\n"
                "  Child: Report {\n"
                "    Child: \n"
                "  }\n"
                "}",
                "    LoadRow(1, false, 0)\n"
                "    Jz(0)\n"
                "    Report()\n"
                "L0:\n"
            },

            // Or
            {
                "Or {\n"
                "  Children: [\n"
                "    LoadRowJz {\n"
                "      Row: Row(0, 6, 0, false),\n"
                "      Child: Report {\n"
                "        Child: \n"
                "      }\n"
                "    },"
                "    LoadRowJz {\n"
                "      Row: Row(1, 6, 0, false),\n"
                "      Child: Report {\n"
                "        Child: \n"
                "      }\n"
                "    }"
                "  ]"
                "}",
                "    Push()\n"
                "    LoadRow(0, false, 0)\n"
                "    Jz(0)\n"
                "    Report()\n"
                "L0:\n"
                "    Pop()\n"
                "    LoadRow(1, false, 0)\n"
                "    Jz(1)\n"
                "    Report()\n"
                "L1:\n"
            },

            // RankDown
            {
                "RankDown {"
                "  Delta: 1,"
                "  Child: LoadRow(1, 2, 0, false)"
                "}",
                "    LeftShiftOffset(1)\n"
                "    Push()\n"
                "    Call(0)\n"
                "    Pop()\n"
                "    IncrementOffset()\n"
                "    Call(0)\n"
                "    Jmp(1)\n"
                "L0:\n"
                "    LoadRow(1, false, 0)\n"
                "    Return()\n"
                "L1:\n"
                "    RightShiftOffset(1)\n"
            },

            // Report with no child.
            // RankDown algorithm does Jz around Report().
            {
                "Report {"
                "  Child:"
                "}",
                "    Report()\n"
            },

            // Report with one child.
            // Includes Jz around Report().
            // TODO: What happens if this is the entire tree? Don't we need to
            // -1 into the accumulator first?
            {
                "Report {"
                "  Child: LoadRow(1, 2, 0, false)\n"
                "}",
                "    Push()\n"
                "    LoadRow(1, false, 0)\n"
                "    AndStack()\n"
                "    Jz(0)\n"
                "    Report()\n"
                "L0:\n"
            },

            {
                "AndTree {\n"
                "  Children: [\n"
                "    LoadRow(0, 6, 0, false),\n"
                "    LoadRow(1, 0, 0, false)\n"
                "  ]\n"
                "}",
                "    LoadRow(0, false, 0)\n"
                "    UpdateFlags()\n"
                "    Jz(0)\n"
                "    Push()\n"
                "    LoadRow(1, false, 0)\n"
                "    AndStack()\n"
                "L0:\n"
            },

            {
                "Not {\n"
                "  Child: LoadRow(0, 6, 0, false)\n"
                "}",
                "    LoadRow(0, false, 0)\n"
                "    Not()\n"
            },

            {
                "OrTree {\n"
                "  Children: [\n"
                "    LoadRow(0, 6, 0, false),\n"
                "    LoadRow(1, 0, 0, false)\n"
                "  ]\n"
                "}",
                "    LoadRow(0, false, 0)\n"
                "    Push()\n"
                "    LoadRow(1, false, 0)\n"
                "    OrStack()\n"
            }
        };

        //*********************************************************************
        //
        // Parse/Format cases.
        //
        //*********************************************************************
        void VerifyRoundtripCase(const char* text)
        {
            std::stringstream input(text);

            Allocator allocator(256);
            TextObjectParser parser(input, allocator, &CompileNode::GetType);

            CompileNode const & node = CompileNode::Parse(parser);

            std::stringstream output;
            TextObjectFormatter formatter(output);
            node.Format(formatter);

            // std::cout << "\"" << text << "\"" << std::endl;
            // std::cout << "\"" << output.str() << "\"" << std::endl;

            EXPECT_EQ(text, output.str());
        }

        TEST(CompileNode, ParseFormat)
        {
            for (unsigned i = 0; i < sizeof(c_parseFormatCases) / sizeof(const char*); ++i)
            {
                VerifyRoundtripCase(c_parseFormatCases[i]);
            }
        }

        //*********************************************************************
        //
        // Code generation cases.
        //
        //*********************************************************************
        void VerifyCodeGenerationCase(InputOutput const & testCase)
        {
            std::stringstream input(testCase.m_input);

            Allocator allocator(256);
            TextObjectParser parser(input, allocator, &CompileNode::GetType);

            CompileNode const & node = CompileNode::Parse(parser);

            std::stringstream output;
            PlainTextCodeGenerator code(output);
            node.Compile(code);

            //std::cout << "+++++++++++++++++++" << std::endl;
            //std::cout << "\"" << testCase.m_output << "\"" << std::endl;
            //std::cout << "+++" << std::endl;
            //std::cout << "\"" << output.str() << "\"" << std::endl;

            EXPECT_EQ(testCase.m_output, output.str());
        }

        TEST(CompileNode, CodeGeneration)
        {
            for (unsigned i = 0; i < sizeof(c_codeGenerationCases) / sizeof(InputOutput); ++i)
            {
                VerifyCodeGenerationCase(c_codeGenerationCases[i]);
            }
        }
    }
}
<|endoftext|>


<commit_before>//
// Projectname: amos-ss16-proj5
//
// Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5
//
// This file is part of the AMOS Project 2016 @ FAU
// (Friedrich-Alexander University Erlangen-Nürnberg)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//

//opencv
#include <opencv2/opencv.hpp>

//local
#include "../ObjectDetection/cascade_haar_detector.h"
#include "../ObjectDetection/daimler_people_detector.h"
#include "../ObjectDetection/detection.h"
//#include "../ObjectDetection/hog_people_detector.h"
#include "../StreamDecoder/image_view.h"
#include "../ScenarioAnalysation/scenario.h"
#include "../ScenarioAnalysation/humans_in_front_of_bus_scenario.h"
#include "../ScenarioAnalysation/analyser.h"
#include "controller.h"
#include "../CarCommunication/protoagent.h"

//define keys
const int KEY_ESC = 27;
const int KEY_SPACE = 32;

void Controller::PlayAsVideo(std::string videofile) {
  FrameSelectorFactory frame_selector_factory(videofile);
  FrameSelector* pipeline = frame_selector_factory.GetFrameSelector();
  ImageView image_view;
  int protobuf_counts = pipeline->GetImageCount();
  for (int i=0; i<protobuf_counts; i++) {
      Image * current_image = pipeline->ReadImage(i);
      image_view.ShowImage(current_image);
      delete current_image;
      current_image = NULL;
      if( cvWaitKey(5) == KEY_ESC ) break;
  }
}

void Controller::AnalyseVideo(std::string videofile, uint16_t port, std::string host) {
  ImageView image_view;
  FrameSelectorFactory frame_selector_factory(videofile);
  FrameSelector* pipeline = frame_selector_factory.GetFrameSelector();
  int protobuf_counts = pipeline->GetImageCount();

  DaimlerPeopleDetector people_detector;
  //HOGPeopleDetector people_detector;
  CascadeHaarDetector vehicle_detector("cars3.xml");
  Detection detection(&people_detector, &vehicle_detector);

  // set up all objects needed for analysing
  std::vector<Scenario*> possible_scenarios;
  possible_scenarios.push_back(new HumansInFrontOfBusScenario());
  Analyser analyser(possible_scenarios);

  for (int i=0; i<protobuf_counts; i++) {

    Image * current_image = pipeline->ReadImage(i);
    FrameDetectionData* current_detections = detection.ProcessFrame(current_image);

    if(!current_detections){
        continue;
    }

    Scenario* scenario = analyser.Analyse(*current_detections);

    if(!scenario){

        std::cout << "No scenario in frame " << i << " was detected!" <<std::endl;

    }else{

        if( HumansInFrontOfBusScenario* result = dynamic_cast<HumansInFrontOfBusScenario*>(scenario) ){

            // TODO here for later: inform the communication module that a "Humans in front of bus" scenario was detected
        }
        // for demo: show information about scenario in current frame
        std::cout << "Current detected scenario: " << scenario->GetScenarioInformation() << " in frame: " << i << std::endl;

        #ifdef COMBINE
        //Notifying other car
        if(port!=0)
        {
            std::cout << "Informing other car" << std::endl;
            ProtoAgent::startClient(port,host);
        }
        #endif
    }

    int key = cvWaitKey(10);
    if(key == KEY_ESC)
      break;

    if (key == KEY_SPACE)
      key = cvWaitKey(0);

    delete current_image;
    current_image = NULL;
    delete current_detections;
    current_detections = NULL;
    //delete scenario;
    scenario = NULL;

   }
}

void Controller::SaveAllImagesAsJPEG(std::string videofile) {
    FrameSelectorFactory frame_selector_factory(videofile);
    FrameSelector* pipeline = frame_selector_factory.GetFrameSelector();
    int protobuf_counts = pipeline->GetImageCount();
    std::string filename = videofile.substr(videofile.find_last_of("/\\")+1);
    std::ostringstream os;
    for (int i=0; i<protobuf_counts; i++){
        os << i;
        cv::imwrite(filename+"_"+os.str()+".jpeg", pipeline->ReadImage(i)->GetRGBImage());
    }
}
<commit_msg>the DetectInRoi() function is now used vor the people detection<commit_after>//
// Projectname: amos-ss16-proj5
//
// Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5
//
// This file is part of the AMOS Project 2016 @ FAU
// (Friedrich-Alexander University Erlangen-Nürnberg)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//

//opencv
#include <opencv2/opencv.hpp>

//local
#include "../ObjectDetection/cascade_haar_detector.h"
#include "../ObjectDetection/daimler_people_detector.h"
#include "../ObjectDetection/detection.h"
// #include "../ObjectDetection/hog_people_detector.h"
#include "../StreamDecoder/image_view.h"
#include "../ScenarioAnalysation/scenario.h"
#include "../ScenarioAnalysation/humans_in_front_of_bus_scenario.h"
#include "../ScenarioAnalysation/analyser.h"
#include "controller.h"
#include "../CarCommunication/protoagent.h"

//define keys
const int KEY_ESC = 27;
const int KEY_SPACE = 32;

void Controller::PlayAsVideo(std::string videofile) {
  FrameSelectorFactory frame_selector_factory(videofile);
  FrameSelector* pipeline = frame_selector_factory.GetFrameSelector();
  ImageView image_view;
  int protobuf_counts = pipeline->GetImageCount();
  for (int i=0; i<protobuf_counts; i++) {
      Image * current_image = pipeline->ReadImage(i);
      image_view.ShowImage(current_image);
      delete current_image;
      current_image = NULL;
      if( cvWaitKey(5) == KEY_ESC ) break;
  }
}

void Controller::AnalyseVideo(std::string videofile, uint16_t port, std::string host) {
  ImageView image_view;
  FrameSelectorFactory frame_selector_factory(videofile);
  FrameSelector* pipeline = frame_selector_factory.GetFrameSelector();
  int protobuf_counts = pipeline->GetImageCount();

  DaimlerPeopleDetector people_detector;
  // HOGPeopleDetector people_detector;
  CascadeHaarDetector vehicle_detector("cars3.xml");
  // CascadeHaarDetector people_detector("haarcascade_fullbody.xml", 1.5, 1, cv::Size(14,28), cv::Size(56,112));
  Detection detection(&people_detector, &vehicle_detector);

  // set up all objects needed for analysing
  std::vector<Scenario*> possible_scenarios;
  possible_scenarios.push_back(new HumansInFrontOfBusScenario());
  Analyser analyser(possible_scenarios);

  for (int i=0; i<protobuf_counts; i++) {

    Image * current_image = pipeline->ReadImage(i);
    FrameDetectionData* current_detections = detection.ProcessFrame(current_image);

    if(!current_detections){
        continue;
    }

    Scenario* scenario = analyser.Analyse(*current_detections);

    if(!scenario){

        std::cout << "No scenario in frame " << i << " was detected!" <<std::endl;

    }else{

        if( HumansInFrontOfBusScenario* result = dynamic_cast<HumansInFrontOfBusScenario*>(scenario) ){

            // TODO here for later: inform the communication module that a "Humans in front of bus" scenario was detected
        }
        // for demo: show information about scenario in current frame
        std::cout << "Current detected scenario: " << scenario->GetScenarioInformation() << " in frame: " << i << std::endl;

        #ifdef COMBINE
        //Notifying other car
        if(port!=0)
        {
            std::cout << "Informing other car" << std::endl;
            ProtoAgent::startClient(port,host);
        }
        #endif
    }

    int key = cvWaitKey(10);
    if(key == KEY_ESC)
      break;

    if (key == KEY_SPACE)
      key = cvWaitKey(0);

    delete current_image;
    current_image = NULL;
    delete current_detections;
    current_detections = NULL;
    //delete scenario;
    scenario = NULL;

   }
}

void Controller::SaveAllImagesAsJPEG(std::string videofile) {
    FrameSelectorFactory frame_selector_factory(videofile);
    FrameSelector* pipeline = frame_selector_factory.GetFrameSelector();
    int protobuf_counts = pipeline->GetImageCount();
    std::string filename = videofile.substr(videofile.find_last_of("/\\")+1);
    std::ostringstream os;
    for (int i=0; i<protobuf_counts; i++){
        os << i;
        cv::imwrite(filename+"_"+os.str()+".jpeg", pipeline->ReadImage(i)->GetRGBImage());
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/utf_string_conversions.h"
#include "chrome/browser/automation/automation_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/web_contents.h"
#include "net/base/mock_host_resolver.h"

using content::NavigationController;
using content::WebContents;

namespace {

class ProcessManagementTest : public ExtensionBrowserTest {
 private:
  // This is needed for testing isolated apps, which are still experimental.
  virtual void SetUpCommandLine(CommandLine* command_line) {
    ExtensionBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
  }
};

}  // namespace

// Ensure that an isolated app never shares a process with WebUIs, non-isolated
// extensions, and normal webpages.  None of these should ever comingle
// RenderProcessHosts even if we hit the process limit.
IN_PROC_BROWSER_TEST_F(ProcessManagementTest, ProcessOverflow) {
  // Set max renderers to 1 to force running out of processes.
  content::RenderProcessHost::SetMaxRendererProcessCount(1);

  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("isolated_apps/app1")));
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("isolated_apps/app2")));
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("hosted_app")));
  ASSERT_TRUE(
      LoadExtension(test_data_dir_.AppendASCII("api_test/app_process")));

  // The app under test acts on URLs whose host is "localhost",
  // so the URLs we navigate to must have host "localhost".
  GURL base_url = test_server()->GetURL(
      "files/extensions/");
  GURL::Replacements replace_host;
  std::string host_str("localhost");  // Must stay in scope with replace_host.
  replace_host.SetHostStr(host_str);
  base_url = base_url.ReplaceComponents(replace_host);

  // Load an extension before adding tabs.
  const Extension* extension1 = LoadExtension(
      test_data_dir_.AppendASCII("api_test/browser_action/basics"));
  ASSERT_TRUE(extension1);
  GURL extension1_url = extension1->url();

  // Create multiple tabs for each type of renderer that might exist.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("isolated_apps/app1/main.html"),
      CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), GURL(chrome::kChromeUINewTabURL),
      NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("hosted_app/main.html"),
      NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("test_file.html"),
      NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);

  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("isolated_apps/app2/main.html"),
      NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), GURL(chrome::kChromeUINewTabURL),
      NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("api_test/app_process/path1/empty.html"),
      NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("test_file_with_body.html"),
      NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);

  // Load another copy of isolated app 1.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("isolated_apps/app1/main.html"),
      NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);

  // Load another extension.
  const Extension* extension2 = LoadExtension(
      test_data_dir_.AppendASCII("api_test/browser_action/close_background"));
  ASSERT_TRUE(extension2);
  GURL extension2_url = extension2->url();

  // Get tab processes.
  ASSERT_EQ(9, browser()->tab_count());
  content::RenderProcessHost* isolated1_host =
      browser()->GetWebContentsAt(0)->GetRenderProcessHost();
  content::RenderProcessHost* ntp1_host =
      browser()->GetWebContentsAt(1)->GetRenderProcessHost();
  content::RenderProcessHost* hosted1_host =
      browser()->GetWebContentsAt(2)->GetRenderProcessHost();
  content::RenderProcessHost* web1_host =
      browser()->GetWebContentsAt(3)->GetRenderProcessHost();

  content::RenderProcessHost* isolated2_host =
      browser()->GetWebContentsAt(4)->GetRenderProcessHost();
  content::RenderProcessHost* ntp2_host =
      browser()->GetWebContentsAt(5)->GetRenderProcessHost();
  content::RenderProcessHost* hosted2_host =
      browser()->GetWebContentsAt(6)->GetRenderProcessHost();
  content::RenderProcessHost* web2_host =
      browser()->GetWebContentsAt(7)->GetRenderProcessHost();

  content::RenderProcessHost* second_isolated1_host =
      browser()->GetWebContentsAt(8)->GetRenderProcessHost();

  // Get extension processes.
  ExtensionProcessManager* process_manager =
    browser()->GetProfile()->GetExtensionProcessManager();
  content::RenderProcessHost* extension1_host =
      process_manager->GetSiteInstanceForURL(extension1_url)->GetProcess();
  content::RenderProcessHost* extension2_host =
      process_manager->GetSiteInstanceForURL(extension2_url)->GetProcess();

  // An isolated app only shares with other instances of itself, not other
  // isolated apps or anything else.
  EXPECT_EQ(isolated1_host, second_isolated1_host);
  EXPECT_NE(isolated1_host, isolated2_host);
  EXPECT_NE(isolated1_host, ntp1_host);
  EXPECT_NE(isolated1_host, hosted1_host);
  EXPECT_NE(isolated1_host, web1_host);
  EXPECT_NE(isolated1_host, extension1_host);
  EXPECT_NE(isolated2_host, ntp1_host);
  EXPECT_NE(isolated2_host, hosted1_host);
  EXPECT_NE(isolated2_host, web1_host);
  EXPECT_NE(isolated2_host, extension1_host);

  // Everything else is clannish.  WebUI only shares with other WebUI.
  EXPECT_EQ(ntp1_host, ntp2_host);
  EXPECT_NE(ntp1_host, hosted1_host);
  EXPECT_NE(ntp1_host, web1_host);
  EXPECT_NE(ntp1_host, extension1_host);

  // Hosted apps only share with each other.
  EXPECT_EQ(hosted1_host, hosted2_host);
  EXPECT_NE(hosted1_host, web1_host);
  EXPECT_NE(hosted1_host, extension1_host);

  // Web pages only share with each other.
  EXPECT_EQ(web1_host, web2_host);
  EXPECT_NE(web1_host, extension1_host);

  // Extensions only share with each other.
  EXPECT_EQ(extension1_host, extension2_host);
}

// Test to verify that the policy of maximum share of extension processes is
// properly enforced.
IN_PROC_BROWSER_TEST_F(ProcessManagementTest, ExtensionProcessBalancing) {
  // Set max renderers to 6 so we can expect 2 extension processes to be
  // allocated.
  content::RenderProcessHost::SetMaxRendererProcessCount(6);

  // The app under test acts on URLs whose host is "localhost",
  // so the URLs we navigate to must have host "localhost".
  GURL base_url = test_server()->GetURL(
      "files/extensions/");
  GURL::Replacements replace_host;
  std::string host_str("localhost");  // Must stay in scope with replace_host.
  replace_host.SetHostStr(host_str);
  base_url = base_url.ReplaceComponents(replace_host);

  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("api_test/browser_action/none")));
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("api_test/browser_action/basics")));
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("api_test/browser_action/remove_popup")));
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("api_test/browser_action/add_popup")));
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("api_test/browser_action/no_icon")));
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("isolated_apps/app1")));
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("api_test/management/test")));

  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("isolated_apps/app1/main.html"),
      CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);

  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("api_test/management/test/basics.html"),
      CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);

  std::set<int> process_ids;
  Profile* profile = browser()->GetProfile();
  ExtensionProcessManager* epm = profile->GetExtensionProcessManager();

  for (ExtensionProcessManager::const_iterator iter = epm->begin();
       iter != epm->end();
       ++iter) {
    ExtensionHost* host = *iter;
    if (host->extension()->has_background_page()) {
      process_ids.insert(host->render_process_host()->GetID());
    }
  }

  // We've loaded 5 extensions with background pages, 1 extension without
  // background page, and one isolated app. We expect only 2 unique processes
  // hosting those extensions.
  ASSERT_EQ((size_t) 5, profile->GetExtensionService()->process_map()->size());
  ASSERT_EQ((size_t) 2, process_ids.size());
}
<commit_msg>Making the test more reliable.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/utf_string_conversions.h"
#include "chrome/browser/automation/automation_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/web_contents.h"
#include "net/base/mock_host_resolver.h"

using content::NavigationController;
using content::WebContents;

namespace {

class ProcessManagementTest : public ExtensionBrowserTest {
 private:
  // This is needed for testing isolated apps, which are still experimental.
  virtual void SetUpCommandLine(CommandLine* command_line) {
    ExtensionBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
  }
};

}  // namespace

// Ensure that an isolated app never shares a process with WebUIs, non-isolated
// extensions, and normal webpages.  None of these should ever comingle
// RenderProcessHosts even if we hit the process limit.
IN_PROC_BROWSER_TEST_F(ProcessManagementTest, ProcessOverflow) {
  // Set max renderers to 1 to force running out of processes.
  content::RenderProcessHost::SetMaxRendererProcessCount(1);

  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("isolated_apps/app1")));
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("isolated_apps/app2")));
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("hosted_app")));
  ASSERT_TRUE(
      LoadExtension(test_data_dir_.AppendASCII("api_test/app_process")));

  // The app under test acts on URLs whose host is "localhost",
  // so the URLs we navigate to must have host "localhost".
  GURL base_url = test_server()->GetURL(
      "files/extensions/");
  GURL::Replacements replace_host;
  std::string host_str("localhost");  // Must stay in scope with replace_host.
  replace_host.SetHostStr(host_str);
  base_url = base_url.ReplaceComponents(replace_host);

  // Load an extension before adding tabs.
  const Extension* extension1 = LoadExtension(
      test_data_dir_.AppendASCII("api_test/browser_action/basics"));
  ASSERT_TRUE(extension1);
  GURL extension1_url = extension1->url();

  // Create multiple tabs for each type of renderer that might exist.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("isolated_apps/app1/main.html"),
      CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), GURL(chrome::kChromeUINewTabURL),
      NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("hosted_app/main.html"),
      NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("test_file.html"),
      NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);

  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("isolated_apps/app2/main.html"),
      NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), GURL(chrome::kChromeUINewTabURL),
      NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("api_test/app_process/path1/empty.html"),
      NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("test_file_with_body.html"),
      NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);

  // Load another copy of isolated app 1.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("isolated_apps/app1/main.html"),
      NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);

  // Load another extension.
  const Extension* extension2 = LoadExtension(
      test_data_dir_.AppendASCII("api_test/browser_action/close_background"));
  ASSERT_TRUE(extension2);
  GURL extension2_url = extension2->url();

  // Get tab processes.
  ASSERT_EQ(9, browser()->tab_count());
  content::RenderProcessHost* isolated1_host =
      browser()->GetWebContentsAt(0)->GetRenderProcessHost();
  content::RenderProcessHost* ntp1_host =
      browser()->GetWebContentsAt(1)->GetRenderProcessHost();
  content::RenderProcessHost* hosted1_host =
      browser()->GetWebContentsAt(2)->GetRenderProcessHost();
  content::RenderProcessHost* web1_host =
      browser()->GetWebContentsAt(3)->GetRenderProcessHost();

  content::RenderProcessHost* isolated2_host =
      browser()->GetWebContentsAt(4)->GetRenderProcessHost();
  content::RenderProcessHost* ntp2_host =
      browser()->GetWebContentsAt(5)->GetRenderProcessHost();
  content::RenderProcessHost* hosted2_host =
      browser()->GetWebContentsAt(6)->GetRenderProcessHost();
  content::RenderProcessHost* web2_host =
      browser()->GetWebContentsAt(7)->GetRenderProcessHost();

  content::RenderProcessHost* second_isolated1_host =
      browser()->GetWebContentsAt(8)->GetRenderProcessHost();

  // Get extension processes.
  ExtensionProcessManager* process_manager =
    browser()->GetProfile()->GetExtensionProcessManager();
  content::RenderProcessHost* extension1_host =
      process_manager->GetSiteInstanceForURL(extension1_url)->GetProcess();
  content::RenderProcessHost* extension2_host =
      process_manager->GetSiteInstanceForURL(extension2_url)->GetProcess();

  // An isolated app only shares with other instances of itself, not other
  // isolated apps or anything else.
  EXPECT_EQ(isolated1_host, second_isolated1_host);
  EXPECT_NE(isolated1_host, isolated2_host);
  EXPECT_NE(isolated1_host, ntp1_host);
  EXPECT_NE(isolated1_host, hosted1_host);
  EXPECT_NE(isolated1_host, web1_host);
  EXPECT_NE(isolated1_host, extension1_host);
  EXPECT_NE(isolated2_host, ntp1_host);
  EXPECT_NE(isolated2_host, hosted1_host);
  EXPECT_NE(isolated2_host, web1_host);
  EXPECT_NE(isolated2_host, extension1_host);

  // Everything else is clannish.  WebUI only shares with other WebUI.
  EXPECT_EQ(ntp1_host, ntp2_host);
  EXPECT_NE(ntp1_host, hosted1_host);
  EXPECT_NE(ntp1_host, web1_host);
  EXPECT_NE(ntp1_host, extension1_host);

  // Hosted apps only share with each other.
  EXPECT_EQ(hosted1_host, hosted2_host);
  EXPECT_NE(hosted1_host, web1_host);
  EXPECT_NE(hosted1_host, extension1_host);

  // Web pages only share with each other.
  EXPECT_EQ(web1_host, web2_host);
  EXPECT_NE(web1_host, extension1_host);

  // Extensions only share with each other.
  EXPECT_EQ(extension1_host, extension2_host);
}

// Test to verify that the policy of maximum share of extension processes is
// properly enforced.
IN_PROC_BROWSER_TEST_F(ProcessManagementTest, ExtensionProcessBalancing) {
  // Set max renderers to 6 so we can expect 2 extension processes to be
  // allocated.
  content::RenderProcessHost::SetMaxRendererProcessCount(6);

  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  // The app under test acts on URLs whose host is "localhost",
  // so the URLs we navigate to must have host "localhost".
  GURL base_url = test_server()->GetURL(
      "files/extensions/");
  GURL::Replacements replace_host;
  std::string host_str("localhost");  // Must stay in scope with replace_host.
  replace_host.SetHostStr(host_str);
  base_url = base_url.ReplaceComponents(replace_host);

  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("api_test/browser_action/none")));
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("api_test/browser_action/basics")));
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("api_test/browser_action/remove_popup")));
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("api_test/browser_action/add_popup")));
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("api_test/browser_action/no_icon")));
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("isolated_apps/app1")));
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("api_test/management/test")));

  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("isolated_apps/app1/main.html"),
      CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);

  ui_test_utils::NavigateToURLWithDisposition(
      browser(), base_url.Resolve("api_test/management/test/basics.html"),
      CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);

  std::set<int> process_ids;
  Profile* profile = browser()->GetProfile();
  ExtensionProcessManager* epm = profile->GetExtensionProcessManager();

  for (ExtensionProcessManager::const_iterator iter = epm->begin();
       iter != epm->end();
       ++iter) {
    ExtensionHost* host = *iter;
    if (host->extension()->has_background_page()) {
      process_ids.insert(host->render_process_host()->GetID());
    }
  }

  // We've loaded 5 extensions with background pages, 1 extension without
  // background page, and one isolated app. We expect only 2 unique processes
  // hosting those extensions.
  EXPECT_GE((size_t) 6, profile->GetExtensionService()->process_map()->size());
  EXPECT_EQ((size_t) 2, process_ids.size());
}
<|endoftext|>


<commit_before>// Copyright (c) 2014-2018 Sebastien Rombauts (sebastien.rombauts@gmail.com)
//
// Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
// or copy at http://opensource.org/licenses/MIT)

#include "GitSourceControlPrivatePCH.h"

#include "GitSourceControlMenu.h"

#include "GitSourceControlModule.h"
#include "GitSourceControlProvider.h"
#include "GitSourceControlOperations.h"

#include "ISourceControlOperation.h"
#include "SourceControlOperations.h"

#include "LevelEditor.h"
#include "Widgets/Notifications/SNotificationList.h"
#include "Framework/Notifications/NotificationManager.h"
#include "EditorStyleSet.h"

#include "PackageTools.h"
#include "FileHelpers.h"

#include "Logging/MessageLog.h"

static const FName GitSourceControlMenuTabName("GitSourceControlMenu");

#define LOCTEXT_NAMESPACE "GitSourceControl"

void FGitSourceControlMenu::Register()
{
	// Register the extension with the level editor
	FLevelEditorModule* LevelEditorModule = FModuleManager::GetModulePtr<FLevelEditorModule>("LevelEditor");
	if (LevelEditorModule)
	{
		FLevelEditorModule::FLevelEditorMenuExtender ViewMenuExtender = FLevelEditorModule::FLevelEditorMenuExtender::CreateRaw(this, &FGitSourceControlMenu::OnExtendLevelEditorViewMenu);
		auto& MenuExtenders = LevelEditorModule->GetAllLevelEditorToolbarSourceControlMenuExtenders();
		MenuExtenders.Add(ViewMenuExtender);
		ViewMenuExtenderHandle = MenuExtenders.Last().GetHandle();
	}
}

void FGitSourceControlMenu::Unregister()
{
	// Unregister the level editor extensions
	FLevelEditorModule* LevelEditorModule = FModuleManager::GetModulePtr<FLevelEditorModule>("LevelEditor");
	if (LevelEditorModule)
	{
		LevelEditorModule->GetAllLevelEditorToolbarSourceControlMenuExtenders().RemoveAll([=](const FLevelEditorModule::FLevelEditorMenuExtender& Extender) { return Extender.GetHandle() == ViewMenuExtenderHandle; });
	}
}

bool FGitSourceControlMenu::HaveRemoteUrl() const
{
	FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>("GitSourceControl");
	FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();
	return !Provider.GetRemoteUrl().IsEmpty();
}

void FGitSourceControlMenu::UnlinkSyncAndReloadPackages()
{
	// Prompt to save or discard all packages
	bool bOkToExit = false;
	bool bHadPackagesToSave = false;
	{
		const bool bPromptUserToSave = true;
		const bool bSaveMapPackages = true;
		const bool bSaveContentPackages = true;
		const bool bFastSave = false;
		const bool bNotifyNoPackagesSaved = false;
		const bool bCanBeDeclined = true; // If the user clicks "don't save" this will continue and lose their changes
		bOkToExit = FEditorFileUtils::SaveDirtyPackages(bPromptUserToSave, bSaveMapPackages, bSaveContentPackages, bFastSave, bNotifyNoPackagesSaved, bCanBeDeclined, &bHadPackagesToSave);
	}

	// bOkToExit can be true if the user selects to not save an asset by unchecking it and clicking "save"
	if (bOkToExit)
	{
		TArray<UPackage*> DirtyPackages;
		FEditorFileUtils::GetDirtyWorldPackages(DirtyPackages);
		FEditorFileUtils::GetDirtyContentPackages(DirtyPackages);
		bOkToExit = DirtyPackages.Num() == 0;
	}

	if (bOkToExit)
	{
		FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>("GitSourceControl");
		FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();

		// Unload all packages in Content directory
		TArray<FString> PackageRelativePaths;
		FPackageName::FindPackagesInDirectory(PackageRelativePaths, *FPaths::ConvertRelativePathToFull(FPaths::ProjectContentDir()));

		TArray<FString> PackageNames;
		PackageNames.Reserve(PackageRelativePaths.Num());
		for(const FString& Path : PackageRelativePaths)
		{
			FString PackageName;
			FString FailureReason;
			if (FPackageName::TryConvertFilenameToLongPackageName(Path, PackageName, &FailureReason))
			{
				PackageNames.Add(PackageName);
			}
			else
			{
				FMessageLog("GitSourceControl").Error(FText::FromString(FailureReason));
			}
		}

		// Inspired from ContentBrowserUtils.cpp ContentBrowserUtils::SyncPathsFromSourceControl()
		TArray<UPackage*> LoadedPackages = UnlinkPackages(PackageNames);

		// Execute a Source Control "Sync" synchronously, displaying an ongoing notification during the whole operation
		TSharedRef<FSync, ESPMode::ThreadSafe> SyncOperation = ISourceControlOperation::Create<FSync>();
		DisplayInProgressNotification(SyncOperation->GetInProgressString());
		const ECommandResult::Type Result = Provider.Execute(SyncOperation, TArray<FString>(), EConcurrency::Synchronous);
		OnSourceControlOperationComplete(SyncOperation, Result);

		// Reload all packages
		ReloadPackages(LoadedPackages);
	}
	else
	{
		FMessageLog ErrorMessage("GitSourceControl");
		ErrorMessage.Warning(LOCTEXT("SourceControlMenu_Sync_Unsaved", "Save All Assets before attempting to Sync!"));
		ErrorMessage.Notify();
	}

}

TArray<UPackage*> FGitSourceControlMenu::UnlinkPackages(const TArray<FString>& InPackageNames)
{
	TArray<UPackage*> LoadedPackages;

	if (InPackageNames.Num() > 0)
	{
		// Form a list of loaded packages to reload...
		LoadedPackages.Reserve(InPackageNames.Num());
		for(const FString& PackageName : InPackageNames)
		{
			UPackage* Package = FindPackage(nullptr, *PackageName);
			if (Package)
			{
				LoadedPackages.Emplace(Package);

				// Detach the linkers of any loaded packages so that SCC can overwrite the files...
				if (!Package->IsFullyLoaded())
				{
					FlushAsyncLoading();
					Package->FullyLoad();
				}
				ResetLoaders(Package);
			}
		}
		UE_LOG(LogSourceControl, Log, TEXT("Reseted Loader for %d Packages"), LoadedPackages.Num());
	}

	return LoadedPackages;
}

void FGitSourceControlMenu::ReloadPackages(TArray<UPackage*>& InLoadedPackages)
{
	UE_LOG(LogSourceControl, Log, TEXT("Reloading %d Packages..."), InLoadedPackages.Num());

	// Syncing may have deleted some packages, so we need to unload those rather than re-load them...
	TArray<UPackage*> PackagesToUnload;
	InLoadedPackages.RemoveAll([&](UPackage* InPackage) -> bool
	{
		const FString PackageExtension = InPackage->ContainsMap() ? FPackageName::GetMapPackageExtension() : FPackageName::GetAssetPackageExtension();
		const FString PackageFilename = FPackageName::LongPackageNameToFilename(InPackage->GetName(), PackageExtension);
		if (!FPaths::FileExists(PackageFilename))
		{
			PackagesToUnload.Emplace(InPackage);
			return true; // remove package
		}
		return false; // keep package
	});

	// Hot-reload the new packages...
	PackageTools::ReloadPackages(InLoadedPackages);

	// Unload any deleted packages...
	PackageTools::UnloadPackages(PackagesToUnload);
}

void FGitSourceControlMenu::SyncClicked()
{
	if (!OperationInProgressNotification.IsValid())
	{
		UnlinkSyncAndReloadPackages();
	}
	else
	{
		FMessageLog LogSourceControl("LogSourceControl");
		LogSourceControl.Warning(LOCTEXT("SourceControlMenu_InProgress", "Source control operation already in progress"));
		LogSourceControl.Notify();
	}
}

void FGitSourceControlMenu::PushClicked()
{
	if (!OperationInProgressNotification.IsValid())
	{
		// Launch a "Push" Operation
		FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>("GitSourceControl");
		FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();
		TSharedRef<FGitPush, ESPMode::ThreadSafe> PushOperation = ISourceControlOperation::Create<FGitPush>();
		ECommandResult::Type Result = Provider.Execute(PushOperation, TArray<FString>(), EConcurrency::Asynchronous, FSourceControlOperationComplete::CreateRaw(this, &FGitSourceControlMenu::OnSourceControlOperationComplete));
		if (Result == ECommandResult::Succeeded)
		{
			// Display an ongoing notification during the whole operation
			DisplayInProgressNotification(PushOperation->GetInProgressString());
		}
		else
		{
			// Report failure with a notification
			DisplayFailureNotification(PushOperation->GetName());
		}
	}
	else
	{
		FMessageLog LogSourceControl("LogSourceControl");
		LogSourceControl.Warning(LOCTEXT("SourceControlMenu_InProgress", "Source control operation already in progress"));
		LogSourceControl.Notify();
	}
}

void FGitSourceControlMenu::RefreshClicked()
{
	if (!OperationInProgressNotification.IsValid())
	{
		// Launch an "UpdateStatus" Operation
		FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>("GitSourceControl");
		FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();
		TSharedRef<FUpdateStatus, ESPMode::ThreadSafe> RefreshOperation = ISourceControlOperation::Create<FUpdateStatus>();
		RefreshOperation->SetCheckingAllFiles(true);
		RefreshOperation->SetGetOpenedOnly(true);
		ECommandResult::Type Result = Provider.Execute(RefreshOperation, TArray<FString>(), EConcurrency::Asynchronous, FSourceControlOperationComplete::CreateRaw(this, &FGitSourceControlMenu::OnSourceControlOperationComplete));
		if (Result == ECommandResult::Succeeded)
		{
			// Display an ongoing notification during the whole operation
			DisplayInProgressNotification(RefreshOperation->GetInProgressString());
		}
		else
		{
			// Report failure with a notification
			DisplayFailureNotification(RefreshOperation->GetName());
		}
	}
	else
	{
		FMessageLog LogSourceControl("LogSourceControl");
		LogSourceControl.Warning(LOCTEXT("SourceControlMenu_InProgress", "Source control operation already in progress"));
		LogSourceControl.Notify();
	}
}

// Display an ongoing notification during the whole operation
void FGitSourceControlMenu::DisplayInProgressNotification(const FText& InOperationInProgressString)
{
	if (!OperationInProgressNotification.IsValid())
	{
		FNotificationInfo Info(InOperationInProgressString);
		Info.bFireAndForget = false;
		Info.ExpireDuration = 0.0f;
		Info.FadeOutDuration = 1.0f;
		OperationInProgressNotification = FSlateNotificationManager::Get().AddNotification(Info);
		if (OperationInProgressNotification.IsValid())
		{
			OperationInProgressNotification.Pin()->SetCompletionState(SNotificationItem::CS_Pending);
		}
	}
}

// Remove the ongoing notification at the end of the operation
void FGitSourceControlMenu::RemoveInProgressNotification()
{
	if (OperationInProgressNotification.IsValid())
	{
		OperationInProgressNotification.Pin()->ExpireAndFadeout();
		OperationInProgressNotification.Reset();
	}
}

// Display a temporary success notification at the end of the operation
void FGitSourceControlMenu::DisplaySucessNotification(const FName& InOperationName)
{
	const FText NotificationText = FText::Format(
		LOCTEXT("SourceControlMenu_Success", "{0} operation was successful!"),
		FText::FromName(InOperationName)
	);
	FNotificationInfo Info(NotificationText);
	Info.bUseSuccessFailIcons = true;
	Info.Image = FEditorStyle::GetBrush(TEXT("NotificationList.SuccessImage"));
	FSlateNotificationManager::Get().AddNotification(Info);
	FMessageLog("LogSourceControl").Info(NotificationText);
}

// Display a temporary failure notification at the end of the operation
void FGitSourceControlMenu::DisplayFailureNotification(const FName& InOperationName)
{
	const FText NotificationText = FText::Format(
		LOCTEXT("SourceControlMenu_Failure", "Error: {0} operation failed!"),
		FText::FromName(InOperationName)
	);
	FNotificationInfo Info(NotificationText);
	Info.ExpireDuration = 8.0f;
	FSlateNotificationManager::Get().AddNotification(Info);
	FMessageLog("LogSourceControl").Info(NotificationText);
}

void FGitSourceControlMenu::OnSourceControlOperationComplete(const FSourceControlOperationRef& InOperation, ECommandResult::Type InResult)
{
	RemoveInProgressNotification();

	// Report result with a notification
	if (InResult == ECommandResult::Succeeded)
	{
		DisplaySucessNotification(InOperation->GetName());
	}
	else
	{
		DisplayFailureNotification(InOperation->GetName());
	}
}

void FGitSourceControlMenu::AddMenuExtension(FMenuBuilder& Builder)
{
	Builder.AddMenuEntry(
		LOCTEXT("GitPush",				"Push"),
		LOCTEXT("GitPushTooltip",		"Push all local commits to the remote server."),
		FSlateIcon(FEditorStyle::GetStyleSetName(), "SourceControl.Actions.Submit"),
		FUIAction(
			FExecuteAction::CreateRaw(this, &FGitSourceControlMenu::PushClicked),
			FCanExecuteAction::CreateRaw(this, &FGitSourceControlMenu::HaveRemoteUrl)
		)
	);

	Builder.AddMenuEntry(
		LOCTEXT("GitSync",				"Sync/Pull"),
		LOCTEXT("GitSyncTooltip",		"Update all files in the local repository to the latest version of the remote server."),
		FSlateIcon(FEditorStyle::GetStyleSetName(), "SourceControl.Actions.Sync"),
		FUIAction(
			FExecuteAction::CreateRaw(this, &FGitSourceControlMenu::SyncClicked),
			FCanExecuteAction::CreateRaw(this, &FGitSourceControlMenu::HaveRemoteUrl)
		)
	);

	Builder.AddMenuEntry(
		LOCTEXT("GitRefresh",			"Refresh"),
		LOCTEXT("GitRefreshTooltip",	"Update the source control status of all files in the local repository."),
		FSlateIcon(FEditorStyle::GetStyleSetName(), "SourceControl.Actions.Refresh"),
		FUIAction(
			FExecuteAction::CreateRaw(this, &FGitSourceControlMenu::RefreshClicked),
			FCanExecuteAction()
		)
	);
}

TSharedRef<FExtender> FGitSourceControlMenu::OnExtendLevelEditorViewMenu(const TSharedRef<FUICommandList> CommandList)
{
	TSharedRef<FExtender> Extender(new FExtender());

	Extender->AddMenuExtension(
		"SourceControlActions",
		EExtensionHook::After,
		nullptr,
		FMenuExtensionDelegate::CreateRaw(this, &FGitSourceControlMenu::AddMenuExtension));

	return Extender;
}

#undef LOCTEXT_NAMESPACE
<commit_msg>Fix non-unity build: missing include file for LogSourceControl définition<commit_after>// Copyright (c) 2014-2018 Sebastien Rombauts (sebastien.rombauts@gmail.com)
//
// Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
// or copy at http://opensource.org/licenses/MIT)

#include "GitSourceControlPrivatePCH.h"

#include "GitSourceControlMenu.h"

#include "GitSourceControlModule.h"
#include "GitSourceControlProvider.h"
#include "GitSourceControlOperations.h"

#include "ISourceControlModule.h"
#include "ISourceControlOperation.h"
#include "SourceControlOperations.h"

#include "LevelEditor.h"
#include "Widgets/Notifications/SNotificationList.h"
#include "Framework/Notifications/NotificationManager.h"
#include "EditorStyleSet.h"

#include "PackageTools.h"
#include "FileHelpers.h"

#include "Logging/MessageLog.h"

static const FName GitSourceControlMenuTabName("GitSourceControlMenu");

#define LOCTEXT_NAMESPACE "GitSourceControl"

void FGitSourceControlMenu::Register()
{
	// Register the extension with the level editor
	FLevelEditorModule* LevelEditorModule = FModuleManager::GetModulePtr<FLevelEditorModule>("LevelEditor");
	if (LevelEditorModule)
	{
		FLevelEditorModule::FLevelEditorMenuExtender ViewMenuExtender = FLevelEditorModule::FLevelEditorMenuExtender::CreateRaw(this, &FGitSourceControlMenu::OnExtendLevelEditorViewMenu);
		auto& MenuExtenders = LevelEditorModule->GetAllLevelEditorToolbarSourceControlMenuExtenders();
		MenuExtenders.Add(ViewMenuExtender);
		ViewMenuExtenderHandle = MenuExtenders.Last().GetHandle();
	}
}

void FGitSourceControlMenu::Unregister()
{
	// Unregister the level editor extensions
	FLevelEditorModule* LevelEditorModule = FModuleManager::GetModulePtr<FLevelEditorModule>("LevelEditor");
	if (LevelEditorModule)
	{
		LevelEditorModule->GetAllLevelEditorToolbarSourceControlMenuExtenders().RemoveAll([=](const FLevelEditorModule::FLevelEditorMenuExtender& Extender) { return Extender.GetHandle() == ViewMenuExtenderHandle; });
	}
}

bool FGitSourceControlMenu::HaveRemoteUrl() const
{
	FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>("GitSourceControl");
	FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();
	return !Provider.GetRemoteUrl().IsEmpty();
}

void FGitSourceControlMenu::UnlinkSyncAndReloadPackages()
{
	// Prompt to save or discard all packages
	bool bOkToExit = false;
	bool bHadPackagesToSave = false;
	{
		const bool bPromptUserToSave = true;
		const bool bSaveMapPackages = true;
		const bool bSaveContentPackages = true;
		const bool bFastSave = false;
		const bool bNotifyNoPackagesSaved = false;
		const bool bCanBeDeclined = true; // If the user clicks "don't save" this will continue and lose their changes
		bOkToExit = FEditorFileUtils::SaveDirtyPackages(bPromptUserToSave, bSaveMapPackages, bSaveContentPackages, bFastSave, bNotifyNoPackagesSaved, bCanBeDeclined, &bHadPackagesToSave);
	}

	// bOkToExit can be true if the user selects to not save an asset by unchecking it and clicking "save"
	if (bOkToExit)
	{
		TArray<UPackage*> DirtyPackages;
		FEditorFileUtils::GetDirtyWorldPackages(DirtyPackages);
		FEditorFileUtils::GetDirtyContentPackages(DirtyPackages);
		bOkToExit = DirtyPackages.Num() == 0;
	}

	if (bOkToExit)
	{
		FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>("GitSourceControl");
		FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();

		// Unload all packages in Content directory
		TArray<FString> PackageRelativePaths;
		FPackageName::FindPackagesInDirectory(PackageRelativePaths, *FPaths::ConvertRelativePathToFull(FPaths::ProjectContentDir()));

		TArray<FString> PackageNames;
		PackageNames.Reserve(PackageRelativePaths.Num());
		for(const FString& Path : PackageRelativePaths)
		{
			FString PackageName;
			FString FailureReason;
			if (FPackageName::TryConvertFilenameToLongPackageName(Path, PackageName, &FailureReason))
			{
				PackageNames.Add(PackageName);
			}
			else
			{
				FMessageLog("GitSourceControl").Error(FText::FromString(FailureReason));
			}
		}

		// Inspired from ContentBrowserUtils.cpp ContentBrowserUtils::SyncPathsFromSourceControl()
		TArray<UPackage*> LoadedPackages = UnlinkPackages(PackageNames);

		// Execute a Source Control "Sync" synchronously, displaying an ongoing notification during the whole operation
		TSharedRef<FSync, ESPMode::ThreadSafe> SyncOperation = ISourceControlOperation::Create<FSync>();
		DisplayInProgressNotification(SyncOperation->GetInProgressString());
		const ECommandResult::Type Result = Provider.Execute(SyncOperation, TArray<FString>(), EConcurrency::Synchronous);
		OnSourceControlOperationComplete(SyncOperation, Result);

		// Reload all packages
		ReloadPackages(LoadedPackages);
	}
	else
	{
		FMessageLog ErrorMessage("GitSourceControl");
		ErrorMessage.Warning(LOCTEXT("SourceControlMenu_Sync_Unsaved", "Save All Assets before attempting to Sync!"));
		ErrorMessage.Notify();
	}

}

TArray<UPackage*> FGitSourceControlMenu::UnlinkPackages(const TArray<FString>& InPackageNames)
{
	TArray<UPackage*> LoadedPackages;

	if (InPackageNames.Num() > 0)
	{
		// Form a list of loaded packages to reload...
		LoadedPackages.Reserve(InPackageNames.Num());
		for(const FString& PackageName : InPackageNames)
		{
			UPackage* Package = FindPackage(nullptr, *PackageName);
			if (Package)
			{
				LoadedPackages.Emplace(Package);

				// Detach the linkers of any loaded packages so that SCC can overwrite the files...
				if (!Package->IsFullyLoaded())
				{
					FlushAsyncLoading();
					Package->FullyLoad();
				}
				ResetLoaders(Package);
			}
		}
		UE_LOG(LogSourceControl, Log, TEXT("Reseted Loader for %d Packages"), LoadedPackages.Num());
	}

	return LoadedPackages;
}

void FGitSourceControlMenu::ReloadPackages(TArray<UPackage*>& InLoadedPackages)
{
	UE_LOG(LogSourceControl, Log, TEXT("Reloading %d Packages..."), InLoadedPackages.Num());

	// Syncing may have deleted some packages, so we need to unload those rather than re-load them...
	TArray<UPackage*> PackagesToUnload;
	InLoadedPackages.RemoveAll([&](UPackage* InPackage) -> bool
	{
		const FString PackageExtension = InPackage->ContainsMap() ? FPackageName::GetMapPackageExtension() : FPackageName::GetAssetPackageExtension();
		const FString PackageFilename = FPackageName::LongPackageNameToFilename(InPackage->GetName(), PackageExtension);
		if (!FPaths::FileExists(PackageFilename))
		{
			PackagesToUnload.Emplace(InPackage);
			return true; // remove package
		}
		return false; // keep package
	});

	// Hot-reload the new packages...
	PackageTools::ReloadPackages(InLoadedPackages);

	// Unload any deleted packages...
	PackageTools::UnloadPackages(PackagesToUnload);
}

void FGitSourceControlMenu::SyncClicked()
{
	if (!OperationInProgressNotification.IsValid())
	{
		UnlinkSyncAndReloadPackages();
	}
	else
	{
		FMessageLog LogSourceControl("LogSourceControl");
		LogSourceControl.Warning(LOCTEXT("SourceControlMenu_InProgress", "Source control operation already in progress"));
		LogSourceControl.Notify();
	}
}

void FGitSourceControlMenu::PushClicked()
{
	if (!OperationInProgressNotification.IsValid())
	{
		// Launch a "Push" Operation
		FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>("GitSourceControl");
		FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();
		TSharedRef<FGitPush, ESPMode::ThreadSafe> PushOperation = ISourceControlOperation::Create<FGitPush>();
		ECommandResult::Type Result = Provider.Execute(PushOperation, TArray<FString>(), EConcurrency::Asynchronous, FSourceControlOperationComplete::CreateRaw(this, &FGitSourceControlMenu::OnSourceControlOperationComplete));
		if (Result == ECommandResult::Succeeded)
		{
			// Display an ongoing notification during the whole operation
			DisplayInProgressNotification(PushOperation->GetInProgressString());
		}
		else
		{
			// Report failure with a notification
			DisplayFailureNotification(PushOperation->GetName());
		}
	}
	else
	{
		FMessageLog LogSourceControl("LogSourceControl");
		LogSourceControl.Warning(LOCTEXT("SourceControlMenu_InProgress", "Source control operation already in progress"));
		LogSourceControl.Notify();
	}
}

void FGitSourceControlMenu::RefreshClicked()
{
	if (!OperationInProgressNotification.IsValid())
	{
		// Launch an "UpdateStatus" Operation
		FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>("GitSourceControl");
		FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();
		TSharedRef<FUpdateStatus, ESPMode::ThreadSafe> RefreshOperation = ISourceControlOperation::Create<FUpdateStatus>();
		RefreshOperation->SetCheckingAllFiles(true);
		RefreshOperation->SetGetOpenedOnly(true);
		ECommandResult::Type Result = Provider.Execute(RefreshOperation, TArray<FString>(), EConcurrency::Asynchronous, FSourceControlOperationComplete::CreateRaw(this, &FGitSourceControlMenu::OnSourceControlOperationComplete));
		if (Result == ECommandResult::Succeeded)
		{
			// Display an ongoing notification during the whole operation
			DisplayInProgressNotification(RefreshOperation->GetInProgressString());
		}
		else
		{
			// Report failure with a notification
			DisplayFailureNotification(RefreshOperation->GetName());
		}
	}
	else
	{
		FMessageLog LogSourceControl("LogSourceControl");
		LogSourceControl.Warning(LOCTEXT("SourceControlMenu_InProgress", "Source control operation already in progress"));
		LogSourceControl.Notify();
	}
}

// Display an ongoing notification during the whole operation
void FGitSourceControlMenu::DisplayInProgressNotification(const FText& InOperationInProgressString)
{
	if (!OperationInProgressNotification.IsValid())
	{
		FNotificationInfo Info(InOperationInProgressString);
		Info.bFireAndForget = false;
		Info.ExpireDuration = 0.0f;
		Info.FadeOutDuration = 1.0f;
		OperationInProgressNotification = FSlateNotificationManager::Get().AddNotification(Info);
		if (OperationInProgressNotification.IsValid())
		{
			OperationInProgressNotification.Pin()->SetCompletionState(SNotificationItem::CS_Pending);
		}
	}
}

// Remove the ongoing notification at the end of the operation
void FGitSourceControlMenu::RemoveInProgressNotification()
{
	if (OperationInProgressNotification.IsValid())
	{
		OperationInProgressNotification.Pin()->ExpireAndFadeout();
		OperationInProgressNotification.Reset();
	}
}

// Display a temporary success notification at the end of the operation
void FGitSourceControlMenu::DisplaySucessNotification(const FName& InOperationName)
{
	const FText NotificationText = FText::Format(
		LOCTEXT("SourceControlMenu_Success", "{0} operation was successful!"),
		FText::FromName(InOperationName)
	);
	FNotificationInfo Info(NotificationText);
	Info.bUseSuccessFailIcons = true;
	Info.Image = FEditorStyle::GetBrush(TEXT("NotificationList.SuccessImage"));
	FSlateNotificationManager::Get().AddNotification(Info);
	FMessageLog("LogSourceControl").Info(NotificationText);
}

// Display a temporary failure notification at the end of the operation
void FGitSourceControlMenu::DisplayFailureNotification(const FName& InOperationName)
{
	const FText NotificationText = FText::Format(
		LOCTEXT("SourceControlMenu_Failure", "Error: {0} operation failed!"),
		FText::FromName(InOperationName)
	);
	FNotificationInfo Info(NotificationText);
	Info.ExpireDuration = 8.0f;
	FSlateNotificationManager::Get().AddNotification(Info);
	FMessageLog("LogSourceControl").Info(NotificationText);
}

void FGitSourceControlMenu::OnSourceControlOperationComplete(const FSourceControlOperationRef& InOperation, ECommandResult::Type InResult)
{
	RemoveInProgressNotification();

	// Report result with a notification
	if (InResult == ECommandResult::Succeeded)
	{
		DisplaySucessNotification(InOperation->GetName());
	}
	else
	{
		DisplayFailureNotification(InOperation->GetName());
	}
}

void FGitSourceControlMenu::AddMenuExtension(FMenuBuilder& Builder)
{
	Builder.AddMenuEntry(
		LOCTEXT("GitPush",				"Push"),
		LOCTEXT("GitPushTooltip",		"Push all local commits to the remote server."),
		FSlateIcon(FEditorStyle::GetStyleSetName(), "SourceControl.Actions.Submit"),
		FUIAction(
			FExecuteAction::CreateRaw(this, &FGitSourceControlMenu::PushClicked),
			FCanExecuteAction::CreateRaw(this, &FGitSourceControlMenu::HaveRemoteUrl)
		)
	);

	Builder.AddMenuEntry(
		LOCTEXT("GitSync",				"Sync/Pull"),
		LOCTEXT("GitSyncTooltip",		"Update all files in the local repository to the latest version of the remote server."),
		FSlateIcon(FEditorStyle::GetStyleSetName(), "SourceControl.Actions.Sync"),
		FUIAction(
			FExecuteAction::CreateRaw(this, &FGitSourceControlMenu::SyncClicked),
			FCanExecuteAction::CreateRaw(this, &FGitSourceControlMenu::HaveRemoteUrl)
		)
	);

	Builder.AddMenuEntry(
		LOCTEXT("GitRefresh",			"Refresh"),
		LOCTEXT("GitRefreshTooltip",	"Update the source control status of all files in the local repository."),
		FSlateIcon(FEditorStyle::GetStyleSetName(), "SourceControl.Actions.Refresh"),
		FUIAction(
			FExecuteAction::CreateRaw(this, &FGitSourceControlMenu::RefreshClicked),
			FCanExecuteAction()
		)
	);
}

TSharedRef<FExtender> FGitSourceControlMenu::OnExtendLevelEditorViewMenu(const TSharedRef<FUICommandList> CommandList)
{
	TSharedRef<FExtender> Extender(new FExtender());

	Extender->AddMenuExtension(
		"SourceControlActions",
		EExtensionHook::After,
		nullptr,
		FMenuExtensionDelegate::CreateRaw(this, &FGitSourceControlMenu::AddMenuExtension));

	return Extender;
}

#undef LOCTEXT_NAMESPACE
<|endoftext|>